-
Notifications
You must be signed in to change notification settings - Fork 368
/
integration.service.ts
228 lines (193 loc) · 8.81 KB
/
integration.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
import type { Context } from '@temporalio/activity';
import type { IntegrationServiceInterface, NangoIntegrationData, NangoProps, ServiceResponse } from '@nangohq/shared';
import { integrationFilesAreRemote, isCloud, isProd } from '@nangohq/utils/dist/environment/detection.js';
import { createActivityLogMessage, localFileService, remoteFileService, NangoError, formatScriptError, isOk } from '@nangohq/shared';
import type { Runner } from './runner/runner.js';
import { getOrStartRunner, getRunnerId } from './runner/runner.js';
import tracer from 'dd-trace';
interface ScriptObject {
context: Context | null;
runner: Runner;
activityLogId: number | undefined;
cancelled?: boolean;
}
class IntegrationService implements IntegrationServiceInterface {
public runningScripts: Map<string, ScriptObject>;
constructor() {
this.runningScripts = new Map();
this.sendHeartbeat();
}
async cancelScript(syncId: string, environmentId: number): Promise<void> {
const scriptObject = this.runningScripts.get(syncId);
if (!scriptObject) {
return;
}
const { runner, activityLogId } = scriptObject;
const res = await runner.client.cancel.mutate({
syncId
});
if (isOk(res)) {
this.runningScripts.set(syncId, { ...scriptObject, cancelled: true });
} else {
if (activityLogId && environmentId) {
await createActivityLogMessage({
level: 'error',
environment_id: environmentId,
activity_log_id: activityLogId,
content: `Failed to cancel script`,
timestamp: Date.now()
});
}
}
}
async runScript(
syncName: string,
syncId: string,
activityLogId: number | undefined,
nangoProps: NangoProps,
integrationData: NangoIntegrationData,
environmentId: number,
writeToDb: boolean,
isInvokedImmediately: boolean,
isWebhook: boolean,
optionalLoadLocation?: string,
input?: object,
temporalContext?: Context
): Promise<ServiceResponse<any>> {
const span = tracer
.startSpan('runScript')
.setTag('accountId', nangoProps.accountId)
.setTag('environmentId', nangoProps.environmentId)
.setTag('connectionId', nangoProps.connectionId)
.setTag('providerConfigKey', nangoProps.providerConfigKey)
.setTag('syncId', nangoProps.syncId)
.setTag('syncName', syncName);
try {
const script: string | null =
(isCloud || integrationFilesAreRemote) && !optionalLoadLocation
? await remoteFileService.getFile(integrationData.fileLocation as string, environmentId)
: localFileService.getIntegrationFile(syncName, optionalLoadLocation);
if (!script) {
const content = `Unable to find integration file for ${syncName}`;
if (activityLogId && writeToDb) {
await createActivityLogMessage({
level: 'error',
environment_id: environmentId,
activity_log_id: activityLogId,
content,
timestamp: Date.now()
});
}
}
if (!script && activityLogId && writeToDb) {
await createActivityLogMessage({
level: 'error',
environment_id: environmentId,
activity_log_id: activityLogId,
content: `Unable to find integration file for ${syncName}`,
timestamp: Date.now()
});
const error = new NangoError('Unable to find integration file', 404);
return { success: false, error, response: null };
}
if (nangoProps.accountId == null) {
throw new Error(`No accountId provided (instead ${nangoProps.accountId})`);
}
const accountId = nangoProps.accountId;
// a runner per account in prod only
const runnerId = isProd() ? getRunnerId(`${accountId}`) : getRunnerId('default');
// fallback to default runner if account runner isn't ready yet
const runner = await getOrStartRunner(runnerId).catch(() => getOrStartRunner(getRunnerId('default')));
if (temporalContext) {
this.runningScripts.set(syncId, { context: temporalContext, runner, activityLogId });
} else {
this.runningScripts.set(syncId, { context: null, runner, activityLogId });
}
const runSpan = tracer.startSpan('runner.run', { childOf: span }).setTag('runnerId', runner.id);
try {
// TODO: request sent to the runner for it to run the script is synchronous.
// TODO: Make the request return immediately and have the runner ping the job service when it's done.
// https://github.com/trpc/trpc/blob/66d7db60e59b7c758709175a53765c9db0563dc0/packages/tests/server/abortQuery.test.ts#L26
const res = await runner.client.run.mutate({
nangoProps,
code: script as string,
codeParams: input as object,
isInvokedImmediately,
isWebhook
});
if (res && res.response && res.response.cancelled) {
const error = new NangoError('script_cancelled');
runSpan.setTag('error', error);
return { success: false, error, response: null };
}
// TODO handle errors from the runner more gracefully and this service doesn't have to handle them
if (res && !res.success && res.error) {
const { error } = res;
runSpan.setTag('error', error);
const err = new NangoError(error.type, error.payload, error.status);
return { success: false, error: err, response: null };
}
return { success: true, error: null, response: res };
} catch (err) {
runSpan.setTag('error', err);
const scriptObject = this.runningScripts.get(syncId);
if (scriptObject) {
const { cancelled } = scriptObject;
if (cancelled) {
this.runningScripts.delete(syncId);
return { success: false, error: new NangoError('script_cancelled'), response: null };
}
}
let errorType = 'sync_script_failure';
if (isWebhook) {
errorType = 'webhook_script_failure';
} else if (isInvokedImmediately) {
errorType = 'action_script_failure';
}
const { success, error, response } = formatScriptError(err, errorType, syncName);
if (activityLogId && writeToDb) {
await createActivityLogMessage({
level: 'error',
environment_id: environmentId,
activity_log_id: activityLogId,
content: error.message,
timestamp: Date.now()
});
}
return { success, error, response };
} finally {
runSpan.finish();
}
} catch (err) {
span.setTag('error', err);
const errorMessage = JSON.stringify(err, ['message', 'name', 'stack'], 2);
const content = `There was an error running integration '${syncName}': ${errorMessage}`;
if (activityLogId && writeToDb) {
await createActivityLogMessage({
level: 'error',
environment_id: environmentId,
activity_log_id: activityLogId,
content,
timestamp: Date.now()
});
}
return { success: false, error: new NangoError(content, 500), response: null };
} finally {
this.runningScripts.delete(syncId);
span.finish();
}
}
private sendHeartbeat() {
setInterval(() => {
Object.keys(this.runningScripts).forEach((syncId) => {
const scriptObject = this.runningScripts.get(syncId);
if (!scriptObject) {
return;
}
const { context } = scriptObject;
context?.heartbeat();
});
}, 300000);
}
}
export default new IntegrationService();