-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathrun.go
More file actions
218 lines (193 loc) · 8.11 KB
/
run.go
File metadata and controls
218 lines (193 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright 2022-2026 Salesforce, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package platform
import (
"context"
"fmt"
"strings"
"github.com/opentracing/opentracing-go"
"github.com/slackapi/slack-cli/cmd/feedback"
"github.com/slackapi/slack-cli/cmd/triggers"
"github.com/slackapi/slack-cli/internal/config"
"github.com/slackapi/slack-cli/internal/pkg/apps"
"github.com/slackapi/slack-cli/internal/shared"
"github.com/slackapi/slack-cli/internal/shared/types"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/slackapi/slack-cli/internal/slacktrace"
"github.com/slackapi/slack-cli/internal/style"
)
// RunArgs are the arguments passed into the Run function
type RunArgs struct {
Activity bool
ActivityLevel string
App types.App
AppPath string
Auth types.SlackAuth
Cleanup bool
ShowTriggers bool
OrgGrantWorkspaceID string
}
// Run locally runs your app.
func Run(ctx context.Context, clients *shared.ClientFactory, runArgs RunArgs) (types.InstallState, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "cmd.create")
defer span.Finish()
// Save token for use later on
ctx = config.SetContextToken(ctx, runArgs.Auth.Token)
// Validate auth session
authSession, err := clients.API().ValidateSession(ctx, runArgs.Auth.Token)
if err != nil {
err = slackerror.Wrap(err, "No auth session found")
return "", slackerror.Wrap(err, slackerror.ErrLocalAppRun)
}
teamName := *authSession.TeamName
if authSession.UserID != nil {
ctx = config.SetContextUserID(ctx, *authSession.UserID)
clients.EventTracker.SetAuthUserID(*authSession.UserID)
}
// Load local dev environment
clients.Config.TeamFlag = *authSession.TeamID
// Load the project's CLI config
var cliConfig = clients.SDKConfig
// A Start script hook must be provided in SDKCLIConfig in order
// For CLI Run command execute successfully
if !clients.SDKConfig.Hooks.Start.IsAvailable() {
var err = slackerror.New(slackerror.ErrSDKHookNotFound).WithMessage("The `start` script was not found")
return "", err
}
// Update local install
installedApp, localInstallResult, installState, err := apps.InstallLocalApp(ctx, clients, runArgs.OrgGrantWorkspaceID, runArgs.Auth, runArgs.App)
if err != nil {
return "", slackerror.Wrap(err, slackerror.ErrLocalAppRun)
}
if installState == types.InstallRequestPending || installState == types.InstallRequestCancelled || installState == types.InstallRequestNotSent {
return types.InstallSuccess, nil
}
if runArgs.ShowTriggers {
// Generate an optional trigger when none exist
_, err = triggers.TriggerGenerate(ctx, clients, installedApp)
if err != nil {
if strings.Contains(err.Error(), "workflow_not_found") {
listErr := triggers.ListWorkflows(ctx, clients, runArgs.App, runArgs.Auth)
if listErr != nil {
return "", slackerror.Wrap(listErr, "Error listing workflows").WithRootCause(err)
}
}
return "", err
}
}
// Gather environment variables from an environment file
variables, err := clients.Config.GetDotEnvFileVariables()
if err != nil {
return "", slackerror.Wrap(err, slackerror.ErrLocalAppRun).
WithMessage("Failed to read the local .env file")
}
// Set SLACK_API_URL to the resolved host value found in the environment
if value, ok := variables["SLACK_API_URL"]; ok {
_ = clients.Os.Setenv("SLACK_API_URL", value)
} else {
variables["SLACK_API_URL"] = fmt.Sprintf("%s/api/", clients.Config.APIHostResolved)
}
var localHostedContext = LocalHostedContext{
BotAccessToken: localInstallResult.APIAccessTokens.Bot,
AppID: installedApp.AppID,
TeamID: *authSession.TeamID,
Variables: variables,
}
var server = LocalServer{
clients: clients,
token: localInstallResult.APIAccessTokens.AppLevel,
localHostedContext: localHostedContext,
cliConfig: cliConfig,
appPath: runArgs.AppPath,
Connection: nil,
}
// Once the "run" command completes, delete the app if the --cleanup flag is
// provided and gracefully shutdown websocket connections.
//
// Signal to CLI that the cleanup in this goroutine needs to complete before
// exiting the process.
clients.CleanupWaitGroup.Add(1)
go func(cleanup bool) {
// Wait until process interrupt via ctx.Done() / canceled context
<-ctx.Done()
clients.IO.PrintDebug(ctx, "Interrupt signal received in Run command, cleaning up and shutting down")
if cleanup {
deleteAppOnTerminate(ctx, clients, runArgs.Auth, installedApp, teamName)
}
feedback.ShowFeedbackMessageOnTerminate(ctx, clients)
// Notify Slack backend we are closing connection; this should trigger an echoing close message from Slack
// in Listen() below (as per WS spec), which we can detect and gracefully return from.
// In turn, should trigger the final cleanup routine below (see deferred function below), which closes the socket connection.
// In case this is an SDK-managed run, the next line is a no-op.
sendWebSocketCloseControlMessage(ctx, clients, server.Connection)
server.stopDelegateProcess(ctx)
clients.IO.PrintTrace(ctx, slacktrace.PlatformRunStop)
clients.CleanupWaitGroup.Done()
}(runArgs.Cleanup)
// Coordinate three goroutines for long running processes and exit on error:
// 1. Watch for changes to the app manifest
// 2. Watch for activity logs from the Slack API
// 3. Listen to events over a managed socket connection or wait for the SDK
// delegated "start" command to exit
//
// An error channel is shared between the goroutines so that the context can
// be canceled, then cleanup performed, with the erroring error returned.
errChan := make(chan error)
clients.IO.PrintTrace(ctx, slacktrace.PlatformRunStart)
// Start watching for Slack Platform log activity
if runArgs.Activity {
go func() {
errChan <- server.WatchActivityLogs(ctx, runArgs.ActivityLevel)
}()
}
// Start watching for manifest changes
// TODO - reinstalled apps via FS watcher do nothing with new tokens returned - may lead to permission issues / missing events?
go func() {
errChan <- server.WatchManifest(ctx, runArgs.Auth, installedApp)
}()
// Check to see whether the SDK managed connection flag is enabled
// If so start app watcher (which handles initial start + restarts), otherwise start connection
if cliConfig.Config.SDKManagedConnection {
clients.IO.PrintDebug(ctx, "Delegating connection to SDK managed script hook")
// Start app watcher which handles initial server start and restarts on file changes
go func() {
errChan <- server.WatchApp(ctx)
}()
} else {
// Listen for messages in a goroutine, and provide an error channel for raising errors
go func() {
errChan <- server.Start(ctx)
}()
}
if err := <-errChan; err != nil {
switch slackerror.ToSlackError(err).Code {
case slackerror.ErrLocalAppRunCleanExit:
return types.InstallSuccess, nil
case slackerror.ErrSDKHookInvocationFailed:
return "", err
}
return "", slackerror.Wrap(err, slackerror.ErrLocalAppRun)
}
return types.InstallSuccess, nil
}
func deleteAppOnTerminate(ctx context.Context, clients *shared.ClientFactory, auth types.SlackAuth, app types.App, teamName string) {
clients.IO.PrintDebug(ctx, "Removing the local version of this app from the workspace")
_, _, err := apps.Delete(ctx, clients, app.TeamDomain, app, auth)
if err != nil {
clients.IO.PrintInfo(ctx, false, "%s", style.Secondary(fmt.Sprintf(`Cleaning up local app install for "%s" failed.`, teamName)))
clients.IO.PrintWarning(ctx, "Local app cleanup failed: %s", err)
} else {
clients.IO.PrintInfo(ctx, false, "%s", style.Secondary(fmt.Sprintf(`Cleaned up local app install for "%s".`, teamName)))
}
}