-
Notifications
You must be signed in to change notification settings - Fork 367
/
deploy.service.ts
307 lines (255 loc) · 12.6 KB
/
deploy.service.ts
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import chalk from 'chalk';
import promptly from 'promptly';
import axios, { AxiosError, AxiosResponse } from 'axios';
import type { SyncType, SyncDeploymentResult, StandardNangoConfig, IncomingFlowConfig, NangoConfigMetadata } from '@nangohq/shared';
import { SyncConfigType, localFileService, getInterval, stagingHost, cloudHost } from '@nangohq/shared';
import configService from './config.service.js';
import compileService from './compile.service.js';
import verificationService from './verification.service.js';
import { printDebug, parseSecretKey, port, enrichHeaders, httpsAgent } from '../utils.js';
import type { DeployOptions } from '../types.js';
class DeployService {
public async admin(environmentName: string, debug = false): Promise<void> {
await verificationService.necessaryFilesExist(false);
await parseSecretKey(environmentName, debug);
if (!process.env['NANGO_HOSTPORT']) {
switch (environmentName) {
case 'local':
process.env['NANGO_HOSTPORT'] = `http://localhost:${port}`;
break;
case 'staging':
process.env['NANGO_HOSTPORT'] = stagingHost;
break;
default:
process.env['NANGO_HOSTPORT'] = cloudHost;
break;
}
}
if (debug) {
printDebug(`NANGO_HOSTPORT is set to ${process.env['NANGO_HOSTPORT']}.`);
printDebug(`Environment is set to ${environmentName}`);
}
await compileService.run(debug);
const { success, error, response: config } = await configService.load('', debug);
if (!success || !config) {
console.log(chalk.red(error?.message));
return;
}
const flowData = this.package(config, debug);
if (!flowData) {
return;
}
const targetAccountUUID = await promptly.prompt('Input the account uuid to deploy to: ');
if (!targetAccountUUID) {
console.log(chalk.red('Account uuid is required. Exiting'));
return;
}
const url = process.env['NANGO_HOSTPORT'] + `/admin/flow/deploy/pre-built`;
const nangoYamlBody = localFileService.getNangoYamlFileContents('./');
try {
await axios
.post(
url,
{ targetAccountUUID, targetEnvironment: environmentName, config: flowData, nangoYamlBody },
{ headers: enrichHeaders(), httpsAgent: httpsAgent() }
)
.then(() => {
console.log(chalk.green(`Successfully deployed the syncs/actions to the users account.`));
})
.catch((err: any) => {
const errorMessage = JSON.stringify(err.response.data, null, 2);
console.log(chalk.red(`Error deploying the syncs/actions with the following error: ${errorMessage}`));
process.exit(1);
});
} catch (e) {
console.log(e);
}
}
public async prep(options: DeployOptions, environment: string, debug = false) {
const { env, version, sync: optionalSyncName, action: optionalActionName, autoConfirm } = options;
await verificationService.necessaryFilesExist(autoConfirm);
await parseSecretKey(environment, debug);
if (!process.env['NANGO_HOSTPORT']) {
switch (env) {
case 'local':
process.env['NANGO_HOSTPORT'] = `http://localhost:${port}`;
break;
case 'staging':
process.env['NANGO_HOSTPORT'] = stagingHost;
break;
default:
process.env['NANGO_HOSTPORT'] = cloudHost;
break;
}
}
if (debug) {
printDebug(`NANGO_HOSTPORT is set to ${process.env['NANGO_HOSTPORT']}.`);
printDebug(`Environment is set to ${environment}`);
}
const singleDeployMode = Boolean(optionalSyncName || optionalActionName);
await compileService.run(debug);
const { success, error, response: config } = await configService.load('', debug);
if (!success || !config) {
console.log(chalk.red(error?.message));
return;
}
const postData: IncomingFlowConfig[] | null = this.package(config, debug, version, optionalSyncName, optionalActionName);
if (!postData) {
return;
}
const url = process.env['NANGO_HOSTPORT'] + `/sync/deploy`;
const nangoYamlBody = localFileService.getNangoYamlFileContents('./');
if (process.env['NANGO_DEPLOY_AUTO_CONFIRM'] !== 'true' && !autoConfirm) {
const confirmationUrl = process.env['NANGO_HOSTPORT'] + `/sync/deploy/confirmation`;
try {
const response = await axios.post(
confirmationUrl,
{ syncs: postData, reconcile: false, debug, singleDeployMode },
{ headers: enrichHeaders(), httpsAgent: httpsAgent() }
);
console.log(JSON.stringify(response.data, null, 2));
const { newSyncs, deletedSyncs } = response.data;
for (const sync of newSyncs) {
const actionMessage =
sync.connections === 0 || sync.auto_start === false
? 'The sync will be added to your Nango instance if you deploy.'
: `Nango will start syncing the corresponding data for ${sync.connections} existing connections.`;
console.log(chalk.yellow(`Sync "${sync.name}" is new. ${actionMessage}`));
}
for (const sync of deletedSyncs) {
console.log(
chalk.red(
`Sync "${sync.name}" has been removed. It will stop running and the corresponding data will be deleted for ${sync.connections} existing connections.`
)
);
}
const confirmation = await promptly.confirm('Do you want to continue y/n?');
if (confirmation) {
await this.run(url, { syncs: postData, nangoYamlBody, reconcile: true, debug, singleDeployMode });
} else {
console.log(chalk.red('Syncs/Actions were not deployed. Exiting'));
process.exit(0);
}
} catch (err) {
let errorMessage;
if (err instanceof AxiosError) {
const errorObject = { message: err.message, stack: err.stack, code: err.code, status: err.status, url, method: err.config?.method };
errorMessage = JSON.stringify(errorObject, null, 2);
} else {
errorMessage = JSON.stringify(err, null, 2);
}
console.log(chalk.red(`Error deploying the syncs/actions with the following error: ${errorMessage}`));
process.exit(1);
}
} else {
if (debug) {
printDebug(`Auto confirm is set so deploy will start without confirmation`);
}
await this.run(url, { syncs: postData, nangoYamlBody, reconcile: true, debug, singleDeployMode });
}
}
public async run(
url: string,
body: { syncs: IncomingFlowConfig[]; nangoYamlBody: string | null; reconcile: boolean; debug: boolean; singleDeployMode?: boolean }
) {
await axios
.post(url, body, { headers: enrichHeaders(), httpsAgent: httpsAgent() })
.then((response: AxiosResponse<SyncDeploymentResult[]>) => {
const results = response.data;
if (results.length === 0) {
console.log(chalk.green(`Successfully removed the syncs/actions.`));
} else {
const nameAndVersions = results.map((result) => `${result.sync_name || result.name}@v${result.version}`);
console.log(chalk.green(`Successfully deployed the syncs/actions: ${nameAndVersions.join(', ')}!`));
}
})
.catch((err) => {
const errorMessage = JSON.stringify(err instanceof AxiosError ? err.response?.data : err, null, 2);
console.log(chalk.red(`Error deploying the syncs/actions with the following error: ${errorMessage}`));
process.exit(1);
});
}
public package(config: StandardNangoConfig[], debug: boolean, version = '', optionalSyncName = '', optionalActionName = ''): IncomingFlowConfig[] | null {
const postData: IncomingFlowConfig[] = [];
for (const integration of config) {
const { providerConfigKey } = integration;
let { syncs, actions } = integration;
let flows = [...syncs, ...actions];
if (optionalSyncName) {
syncs = syncs.filter((sync) => sync.name === optionalSyncName);
flows = syncs;
}
if (optionalActionName) {
actions = actions.filter((action) => action.name === optionalActionName);
flows = actions;
}
if (optionalSyncName && optionalActionName) {
flows = [...syncs, ...actions];
}
for (const flow of flows) {
const { name: syncName, runs = '', returns: models, models: model_schema, type = SyncConfigType.SYNC } = flow;
const { path: integrationFilePath, result: integrationFileResult } = localFileService.checkForIntegrationDistFile(syncName, './');
const metadata = {} as NangoConfigMetadata;
if (flow.description) {
metadata['description'] = flow.description;
}
if (flow.scopes) {
metadata['scopes'] = flow.scopes;
}
if (!integrationFileResult) {
console.log(chalk.red(`No integration file found for ${syncName} at ${integrationFilePath}. Skipping...`));
continue;
}
if (type !== SyncConfigType.SYNC && type !== SyncConfigType.ACTION) {
console.log(
chalk.red(
`The sync ${syncName} has an invalid type "${type}". The type must be either ${SyncConfigType.SYNC} or${SyncConfigType.ACTION}. Skipping...`
)
);
}
if (type === SyncConfigType.SYNC && !runs) {
console.log(chalk.red(`The sync ${syncName} is missing the "runs" property. Skipping...`));
continue;
}
if (runs && type === SyncConfigType.SYNC) {
const { success, error } = getInterval(runs, new Date());
if (!success) {
console.log(chalk.red(`The sync ${syncName} has an issue with the sync interval "${runs}": ${error?.message}`));
return null;
}
}
if (debug) {
printDebug(`Integration file found for ${syncName} at ${integrationFilePath}`);
}
if (flow?.input?.fields) {
model_schema.push(flow.input);
}
const body = {
syncName,
providerConfigKey,
models: Array.isArray(models) ? models : [models],
version: version,
runs,
track_deletes: flow.track_deletes || false,
auto_start: flow.auto_start === false ? false : true,
attributes: flow.attributes || {},
metadata: metadata || {},
input: flow?.input?.name || '',
sync_type: flow.sync_type as SyncType,
type,
fileBody: {
js: localFileService.getIntegrationFile(syncName, './') as string,
ts: localFileService.getIntegrationTsFile(syncName, './') as string
},
model_schema: JSON.stringify(model_schema),
endpoints: flow.endpoints,
webhookSubscriptions: flow.webhookSubscriptions || []
};
postData.push(body);
}
}
return postData;
}
}
const deployService = new DeployService();
export default deployService;