|
| 1 | +import { AlertableInteractionTypes, IClientOptions, RequestApiOptions, StreamingClientExtension } from './types/interfaces'; |
| 2 | +import { Client } from './client'; |
| 3 | +import { NamedAgent } from './types/named-agent'; |
| 4 | +import { retryPromise } from './utils'; |
| 5 | + |
| 6 | +export class AlertingLeaderExtension implements StreamingClientExtension { |
| 7 | + private connectionId?: string; |
| 8 | + private alertableInteractionTypes: AlertableInteractionTypes[]; |
| 9 | + |
| 10 | + constructor (private client: Client, options: IClientOptions) { |
| 11 | + this.alertableInteractionTypes = options.alertableInteractionTypes ?? []; |
| 12 | + } |
| 13 | + |
| 14 | + handleStanzaInstanceChange (stanzaInstance: NamedAgent) { |
| 15 | + this.connectionId = stanzaInstance.transport?.stream?.id; |
| 16 | + |
| 17 | + if (this.alertableInteractionTypes.length !== 0) { |
| 18 | + this.markAsAlertable(); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + private async markAsAlertable (): Promise<any> { |
| 23 | + const userId = this.client.config.userId; |
| 24 | + const connectionsRequestOptions: RequestApiOptions = { |
| 25 | + method: 'patch', |
| 26 | + host: this.client.config.apiHost, |
| 27 | + authToken: this.client.config.authToken, |
| 28 | + logger: this.client.logger, |
| 29 | + data: { |
| 30 | + alertable: true |
| 31 | + } |
| 32 | + }; |
| 33 | + |
| 34 | + // STREAM-1204 |
| 35 | + // There's a race condition between the backend service knowing about the connection |
| 36 | + // and us marking the connection as alertable. For now, we'll just retry with some delay. |
| 37 | + const maxRetries = 16; |
| 38 | + let retryCount = 0; |
| 39 | + const retry = retryPromise( |
| 40 | + () => this.client.http.requestApi(`apps/users/${userId}/connections/${this.connectionId}`, connectionsRequestOptions), |
| 41 | + () => { |
| 42 | + retryCount++; |
| 43 | + if (retryCount >= maxRetries) { |
| 44 | + this.client.logger.info('Max retries reached for marking connection as alertable'); |
| 45 | + return false; |
| 46 | + } |
| 47 | + return true; |
| 48 | + }, |
| 49 | + 500, |
| 50 | + this.client.logger |
| 51 | + ); |
| 52 | + |
| 53 | + return retry.promise |
| 54 | + .catch(() => { |
| 55 | + this.client.logger.warn('Could not mark this connection as alertable; this client may not alert for incoming interactions'); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + get expose (): AlertingLeaderApi { |
| 60 | + return { |
| 61 | + }; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export interface AlertingLeaderApi { |
| 66 | +} |
0 commit comments