-
Notifications
You must be signed in to change notification settings - Fork 484
/
Copy pathslack.service.ts
807 lines (721 loc) · 27.6 KB
/
slack.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
import db, { dbNamespace, schema } from '@nangohq/database';
import { Err, Ok, basePublicUrl, getLogger, stringToHash, truncateJson } from '@nangohq/utils';
import configService from '../config.service.js';
import connectionService from '../connection.service.js';
import { refreshOrTestCredentials } from '../connections/credentials/refresh.js';
import environmentService from '../environment.service.js';
import { ProxyRequest } from '../proxy/request.js';
import { getProxyConfiguration } from '../proxy/utils.js';
import type { ServiceResponse } from '../../models/Generic.js';
import type { Config } from '../../models/Provider.js';
import type { NangoError } from '../../utils/error.js';
import type { FeatureFlags } from '@nangohq/kvstore';
import type { LogContextGetter } from '@nangohq/logs';
import type { ConnectionJobs, DBConnection, DBConnectionDecrypted, DBEnvironment, DBSlackNotification, DBTeam } from '@nangohq/types';
import type { Result } from '@nangohq/utils';
const logger = getLogger('SlackService');
const TABLE = dbNamespace + 'slack_notifications';
interface NotificationResponse {
id: number;
isOpen: boolean;
connectionCount: number;
slack_timestamp?: string;
admin_slack_timestamp?: string;
}
interface NotificationPayload {
content: string;
meta?: {
accountName: string;
accountUuid: string;
};
providerConfigKey: string;
provider: string;
status: string;
ts?: string;
}
interface PostSlackMessageResponse {
ok: boolean;
channel: string;
ts: string;
message: {
bot_id: string;
type: string;
text: string;
user: string;
ts: string;
app_id: string;
team: string;
bot_profile: {
id: string;
app_id: string;
name: string;
icons: any;
deleted: boolean;
updated: number;
team_id: string;
};
attachments: any[];
};
warning?: string;
response_metadata: {
warnings: string[];
};
}
export const generateSlackConnectionId = (accountUUID: string, environmentName: string) => `account-${accountUUID}-${environmentName}`;
/**
* _nango_slack_notifications
* @desc persistence layer for slack notifications and the connection list
* to be able to trigger or resolve notifications
*
* index:
* - open
* - environment_id
* - name
*/
export class SlackService {
private logContextGetter: LogContextGetter;
private featureFlags: FeatureFlags;
private integrationKey = process.env['NANGO_SLACK_INTEGRATION_KEY'] || 'slack';
private nangoAdminUUID = process.env['NANGO_ADMIN_UUID'];
private env = process.env['NANGO_ADMIN_PROD_ENV'] || 'prod';
constructor({ logContextGetter, featureFlags }: { logContextGetter: LogContextGetter; featureFlags: FeatureFlags }) {
this.logContextGetter = logContextGetter;
this.featureFlags = featureFlags;
}
private async isDisabled() {
return this.featureFlags.isSet('disable-slack-notifications');
}
/**
* Update Notification with Timestamp
* @desc used to keep the slack_timestamp up to date to be able to
* send updates to the original notification
*/
private async updateNotificationWithTimestamp(id: number, ts: string) {
await schema()
.from<DBSlackNotification>(TABLE)
.update({
slack_timestamp: ts
})
.where('id', id);
}
/**
* Report Failure
* @desc
* 1) if slack notifications are enabled and the name is not itself (to avoid an infinite loop)
* add the connection to the notification list, grab the connection information
* of the admin slack notification action and send the notification to the slack channel
* by triggering the action.
* 2) Update the notification record with the slack timestamp
* so future notifications can be sent as updates to the original.
* 3) Add an activity log entry for the notification to the admin account
*/
async reportFailure({
account,
environment,
provider,
name,
connection,
type,
originalActivityLogId
}: {
account: DBTeam;
environment: DBEnvironment;
connection: ConnectionJobs;
name: string;
type: string;
originalActivityLogId: string;
provider: string;
}) {
if (await this.isDisabled()) {
return;
}
if (!environment.slack_notifications) {
return;
}
const { success, error, response: slackNotificationStatus } = await this.addFailingConnection(connection, name, type);
// this must mean we don't want to trigger the slack notification
// b/c it is auth and we don't increment the connection count
if (success && !slackNotificationStatus) {
return;
}
const count = slackNotificationStatus?.connectionCount || 0;
const connectionWord = count === 1 ? 'connection' : 'connections';
const flowType = type;
const date = new Date();
const payload: NotificationPayload = {
content: this.getMessage({
type,
count,
connectionWord,
flowType,
name,
providerConfigKey: connection.provider_config_key,
envName: environment.name,
originalActivityLogId,
date,
resolved: false
}),
status: 'open',
providerConfigKey: connection.provider_config_key,
provider,
...(slackNotificationStatus?.slack_timestamp ? { ts: slackNotificationStatus.slack_timestamp } : {})
};
const res = await this.sendSlackNotification({ account, environment, type, name, connection, payload, lookupError: error });
if (res.isOk() && slackNotificationStatus) {
await this.updateNotificationWithTimestamp(slackNotificationStatus.id, res.value.ts);
}
}
/**
* Report Resolution
* @desc
* 1) if there are no more connections that are failing then send
* a resolution notification to the slack channel, otherwise update the message
* with the decremented connection count.
* 2) Add an activity log entry for the notification to the admin account
*
*/
private async reportResolution(
connection: ConnectionJobs,
name: string,
type: string,
originalActivityLogId: string | null,
provider: string,
slack_timestamp: string,
connectionCount: number
) {
if (await this.isDisabled()) {
return;
}
const accountEnv = await environmentService.getAccountAndEnvironment({ environmentId: connection.environment_id });
if (!accountEnv) {
throw new Error('failed_to_get_account');
}
const { account, environment } = accountEnv;
let payloadContent = '';
if (connectionCount === 0) {
payloadContent = this.getMessage({
type,
count: connectionCount,
connectionWord: 'connections',
flowType: type,
name,
providerConfigKey: connection.provider_config_key,
envName: environment.name,
originalActivityLogId,
date: new Date(),
resolved: true
});
} else {
const count = connectionCount;
const connectionWord = count === 1 ? 'connection' : 'connections';
payloadContent = this.getMessage({
type,
count,
connectionWord,
flowType: type,
name,
providerConfigKey: connection.provider_config_key,
envName: environment.name,
originalActivityLogId,
date: new Date(),
resolved: false
});
}
const payload: NotificationPayload = {
content: payloadContent,
status: connectionCount === 0 ? 'closed' : 'open',
providerConfigKey: connection.provider_config_key,
provider,
ts: slack_timestamp
};
await this.sendSlackNotification({ account, environment, type, name, connection, payload });
}
/**
* Has Open Notification
* @desc Check if there is an open notification for the given name
* and environment id and if so return the necessary information to be able
* to update the notification.
*/
private async hasOpenNotification(
nangoConnection: Pick<DBConnection, 'environment_id'>,
name: string,
type: string,
trx = db.knex
): Promise<DBSlackNotification | null> {
const hasOpenNotification = await trx
.select<DBSlackNotification>('*')
.from<DBSlackNotification>(TABLE)
.forUpdate()
.where({
open: true,
environment_id: nangoConnection.environment_id,
name,
type
})
.first();
return hasOpenNotification || null;
}
/**
* Create Notification
* @desc create a new notification for the given name and environment id
* and return the id of the created notification.
*/
private async createNotification(
nangoConnection: Pick<DBConnection, 'id' | 'environment_id'>,
name: string,
type: string,
trx = db.knex
): Promise<Pick<DBSlackNotification, 'id'> | null> {
const result = await trx
.from<DBSlackNotification>(TABLE)
.insert({
open: true,
environment_id: nangoConnection.environment_id,
name,
type,
connection_list: [nangoConnection.id]
})
.returning('id');
if (result && result.length > 0 && result[0]) {
return result[0];
}
return null;
}
/**
* Add Failing Connection
* @desc check if there is an open notification for the given name and environment id
* and if so add the connection id to the connection list.
*/
private async addFailingConnection(nangoConnection: ConnectionJobs, name: string, type: string): Promise<ServiceResponse<NotificationResponse>> {
return await db.knex.transaction(async (trx) => {
const lockKey = stringToHash(`${nangoConnection.environment_id}-${name}-${type}-add`);
const { rows } = await trx.raw<{ rows: { lock_slack_add_connection: boolean }[] }>(
`SELECT pg_try_advisory_xact_lock(?) as lock_slack_add_connection`,
[lockKey]
);
if (!rows?.[0]?.lock_slack_add_connection) {
logger.info(`addFailingConnection operation: ${lockKey} could not acquire lock, skipping`);
return { success: true, error: null, response: null };
}
const isOpen = await this.hasOpenNotification(nangoConnection, name, type, trx);
if (isOpen && type === 'auth') {
return {
success: true,
error: null,
response: null
};
}
logger.info(`Notifying connection:${nangoConnection.id} type:${type} name:${name}`);
if (!isOpen) {
const created = await this.createNotification(nangoConnection, name, type, trx);
return {
success: true,
error: null,
response: {
id: created?.id as number,
isOpen: false,
connectionCount: 1
}
};
}
const { id, connection_list } = isOpen;
if (connection_list.includes(nangoConnection.id)) {
return {
success: true,
error: null,
response: {
id,
isOpen: true,
slack_timestamp: isOpen.slack_timestamp as string,
admin_slack_timestamp: isOpen.admin_slack_timestamp as string,
connectionCount: connection_list.length
}
};
}
connection_list.push(nangoConnection.id);
await trx.from<DBSlackNotification>(TABLE).where({ id }).update({
connection_list,
updated_at: new Date()
});
return {
success: true,
error: null,
response: {
id,
isOpen: true,
slack_timestamp: isOpen.slack_timestamp as string,
admin_slack_timestamp: isOpen.admin_slack_timestamp as string,
connectionCount: connection_list.length
}
};
});
}
/**
* Remove Failing Connection
* @desc check if there is an open notification for the given name and environment id
* and if so remove the connection id from the connection list and report
* resolution to the slack channel.
*/
async removeFailingConnection({
connection: nangoConnection,
name,
type,
originalActivityLogId,
provider
}: {
connection: ConnectionJobs;
name: string;
type: string;
originalActivityLogId: string | null;
provider: string;
}): Promise<void> {
const update = await db.knex.transaction(async (trx) => {
const slackNotificationsEnabled = await environmentService.getSlackNotificationsEnabled(nangoConnection.environment_id, trx);
if (!slackNotificationsEnabled) {
return;
}
const lockKey = stringToHash(`${nangoConnection.environment_id}-${name}-${type}-remove`);
const { rows } = await trx.raw<{ rows: { lock_slack_remove_connection: boolean }[] }>(
`SELECT pg_try_advisory_xact_lock(?) as lock_slack_remove_connection`,
[lockKey]
);
if (!rows?.[0]?.lock_slack_remove_connection) {
logger.info(`removeFailingConnection operation: ${lockKey} could not acquire lock, skipping`);
return;
}
const isOpen = await this.hasOpenNotification(nangoConnection, name, type, trx);
if (!isOpen) {
return;
}
const { id, connection_list, slack_timestamp, admin_slack_timestamp } = isOpen;
const index = connection_list.indexOf(nangoConnection.id);
if (index === -1) {
return;
}
logger.info(`Resolving ${nangoConnection.id} type:${type} name:${name}`);
connection_list.splice(index, 1);
await trx
.from<DBSlackNotification>(TABLE)
.where({ id })
.update({
open: connection_list.length > 0,
connection_list,
updated_at: new Date()
});
return {
id,
slackTimestamp: slack_timestamp,
adminSlackTimestamp: admin_slack_timestamp,
connectionCount: connection_list.length
};
});
if (update) {
// we report resolution to the slack channel which could be either
// 1) The slack notification is resolved, connection_list === 0
// 2) The list of failing connections has been decremented
await this.reportResolution(nangoConnection, name, type, originalActivityLogId, provider, update.slackTimestamp as string, update.connectionCount);
}
}
async closeAllOpenNotificationsForEnv(environment_id: number): Promise<void> {
await db.knex
.from<DBSlackNotification>(TABLE)
.where({
environment_id,
open: true
})
.update({
open: false,
updated_at: new Date()
});
}
private getLogUrl({
envName,
originalActivityLogId,
name,
date,
type
}: {
envName: string;
originalActivityLogId: string | null;
name: string;
date: Date;
type: string;
}) {
const usp = new URLSearchParams();
if (originalActivityLogId) {
usp.set('operationId', String(originalActivityLogId));
}
const from = new Date(date);
from.setHours(0, 0);
const to = new Date(date);
to.setHours(23, 59);
usp.set('from', from.toISOString());
usp.set('to', to.toISOString());
if (type === 'auth') {
usp.set('connections', name);
} else if (type === 'integration') {
usp.set('integrations', name);
} else {
usp.set('syncs', name);
}
return `${basePublicUrl}/${envName}/logs?${usp.toString()}`;
}
private getPageUrl({ envName, providerConfigKey, name, type }: { envName: string; providerConfigKey: string; name: string; type: string }) {
return `${basePublicUrl}/${envName}/${type}/${providerConfigKey}/${name}`;
}
private getMessage({
type,
count,
connectionWord,
flowType,
name,
providerConfigKey,
envName,
originalActivityLogId,
date,
resolved
}: {
type: string;
count: number;
connectionWord: string;
flowType: string;
name: string;
providerConfigKey: string;
envName: string;
originalActivityLogId: string | null;
date: Date;
resolved: boolean;
}): string {
switch (type) {
case 'sync':
case 'action': {
if (resolved) {
return `[Resolved] \`${name}\` ${flowType.toLowerCase()} (integration: \`${providerConfigKey}\`) in *${envName}* failed. Read <${this.getLogUrl({ envName, originalActivityLogId, name, date, type })}|logs>.`;
} else {
return `\`${name}\` ${flowType.toLowerCase()} (integration: \`${providerConfigKey}\`) is failing for ${count} ${connectionWord} in *${envName}*. Read <${this.getLogUrl({ envName, originalActivityLogId, name, date, type })}|logs>.`;
}
}
case 'auth': {
if (resolved) {
return `[Resolved] connection <${this.getPageUrl({ envName, name, providerConfigKey, type: 'connections' })}|*${name}*> (integration: \`${providerConfigKey}\`) in *${envName}* refresh failed.`;
} else {
return `Could not refresh token of connection <${this.getPageUrl({ envName, name, providerConfigKey, type: 'connections' })}|*${name}*> in *${envName}* (integration: \`${providerConfigKey}\`). Read <${this.getLogUrl({ envName, originalActivityLogId, name, date, type })}|logs>.`;
}
}
}
return '';
}
private async sendSlackNotification({
account,
environment,
type,
name,
connection,
payload,
lookupError = null
}: {
account: DBTeam;
environment: DBEnvironment;
type: string;
name: string;
connection: ConnectionJobs;
payload: NotificationPayload;
lookupError?: NangoError | null;
}): Promise<Result<PostSlackMessageResponse>> {
const admin = await environmentService.getAccountAndEnvironment({ accountUuid: this.nangoAdminUUID!, envName: this.env });
if (!admin) {
return Err('failed_to_get_admin_env');
}
const integration = await configService.getProviderConfig(this.integrationKey, admin.environment.id);
if (!integration) {
return Err('failed_to_get_integration');
}
const slackConnectionId = generateSlackConnectionId(account.uuid, environment.name);
// we get the connection on the nango admin account to be able to send the notification
const {
success: connectionSuccess,
error: slackConnectionError,
response: slackConnection
} = await connectionService.getConnection(slackConnectionId, this.integrationKey, admin.environment.id);
if (!connectionSuccess || !slackConnection) {
logger.error(slackConnectionError);
return Err('failed_to_get_slack_connection');
}
const logCtx = await this.logContextGetter.create(
{ operation: { type: 'proxy', action: 'call' } },
{
account: admin.account,
environment: admin.environment,
integration: { id: slackConnection.config_id, name: slackConnection.provider_config_key, provider: 'slack' },
connection: { id: slackConnection.id, name: slackConnection.connection_id },
meta: {
accountId: account.id,
accountName: account.name,
environment: environment.id,
environmentName: environment.name,
connectionId: connection.id,
connection: connection.connection_id,
type,
name,
input: truncateJson(payload)
}
}
);
if (lookupError) {
void logCtx.error('Failed looking up slack notification', { error: lookupError });
await logCtx.failed();
return Err(lookupError);
}
const refreshedConnection = await refreshOrTestCredentials({
connection: slackConnection,
account: admin.account,
environment: admin.environment,
integration,
instantRefresh: false,
onRefreshSuccess: async () => {},
onRefreshFailed: async () => {},
logContextGetter: this.logContextGetter
});
if (refreshedConnection.isErr()) {
void logCtx.error('Failed to refresh slack connection', { error: refreshedConnection.error });
await logCtx.failed();
return Err(refreshedConnection.error);
}
const res = await this.proxySlackMessage({ slackConnection: refreshedConnection.value, payload, integration });
if (res.isErr()) {
void logCtx.error(`Failed to send Slack notification`, { error: res.error });
await logCtx.failed();
return Err(res.error);
}
void logCtx.info(`Posted to https://slack.com/archives/${res.value.channel}/p${res.value.ts.replace('.', '')}`);
await logCtx.success();
return Ok(res.value);
}
private async proxySlackMessage({
slackConnection,
payload,
integration
}: {
slackConnection: DBConnectionDecrypted;
payload: NotificationPayload;
integration: Config;
}): Promise<Result<PostSlackMessageResponse>> {
const color = payload.status === 'open' ? '#e01e5a' : '#36a64f';
const channel = slackConnection.connection_config['incoming_webhook.channel_id'];
if (!channel) {
return Err('slack_hook_channel_id_not_configured');
}
// Join the Slack channel
let proxyConfig = getProxyConfiguration({
externalConfig: {
method: 'POST' as const,
endpoint: 'conversations.join',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
data: { channel },
decompress: false,
providerConfigKey: integration.unique_key
},
internalConfig: {
providerName: integration.provider
}
});
if (proxyConfig.isErr()) {
return Err('failed_to_get_proxy_config');
}
let proxy = new ProxyRequest({
logger: () => {},
proxyConfig: proxyConfig.value,
getConnection: () => slackConnection
});
const join = await proxy.request();
if (join.isErr()) {
return Err('slack_join_channel_failed');
}
if (!join.value.data.ok) {
return Err(join.value.data.error);
}
// Send/update chat message
const data = {
channel,
ts: payload.ts || '',
attachments: [
{
color: color,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: payload.content
}
},
...(payload.meta
? [
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `${payload.meta.accountName} (uuid: ${payload.meta.accountUuid})`
}
]
}
]
: [])
]
}
]
};
proxyConfig = getProxyConfiguration({
externalConfig: {
method: 'POST' as const,
endpoint: data.ts ? 'chat.update' : 'chat.postMessage',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
data,
decompress: false,
providerConfigKey: integration.unique_key,
retries: 10
},
internalConfig: {
providerName: integration.provider
}
});
if (proxyConfig.isErr()) {
return Err('failed_to_get_proxy_config');
}
proxy = new ProxyRequest({
logger: () => {},
proxyConfig: proxyConfig.value,
getConnection: () => slackConnection
});
const slackMessage = await proxy.request();
if (slackMessage.isErr()) {
return Err('slack_post_failed');
}
return Ok(slackMessage.value.data as PostSlackMessageResponse);
}
public async closeOpenNotificationForConnection({ connectionId, environmentId }: { connectionId: number; environmentId: number }) {
await db.knex.transaction(async (trx) => {
const rows = await trx
.select('*')
.from<DBSlackNotification>(TABLE)
.forUpdate()
.where({
open: true,
environment_id: environmentId
})
.whereRaw(`connection_list && '{${connectionId}}'`);
for (const row of rows) {
const connectionIds = row.connection_list.filter((id) => id !== connectionId);
await trx
.from<DBSlackNotification>(TABLE)
.where({ id: row.id })
.update({
open: connectionIds.length > 0,
connection_list: connectionIds,
updated_at: new Date()
});
}
});
}
}