import path from 'path'; import { EventEmitter } from 'events'; import grpc, { ServiceError, status as ServiceErrorStatus } from 'grpc'; import { loadSync as loadProtoSync } from '@grpc/proto-loader'; import { ApplicationConfiguration, getServiceConfiguration } from './configuration'; import { ApplicationDeveloperSubscription, ApplicationDeveloperKey, GetApplicationDeveloperSubscriptionPayload, GetApplicationDeveloperSubscriptionResponse } from './protos/types/application'; const EVENTS = { UPDATE_SUCCESS: Symbol(), UPDATE_ERROR: Symbol() }; export const DEVELOPER_KEY_VALIDATOR_EVENTS = EVENTS; interface ApplicationDeveloperKeyWithSubscription extends ApplicationDeveloperKey { subscription: ApplicationDeveloperSubscription; } class DeveloperSubscriptionReceiver extends EventEmitter { private call: grpc.ServerDuplexStream; private client: grpc.Client; private config: ApplicationConfiguration; get isRunning(): boolean { return !!this.client; } constructor(config: ApplicationConfiguration) { super(); this.config = config; } public start(): this { if (this.isRunning) { // Dont create a duplicate client if one exists return; } const definition = grpc.loadPackageDefinition( loadProtoSync( `${path.join(__dirname, 'protos')}/application.proto`, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } ) ); const { address, credentials } = getServiceConfiguration(); this.client = new (definition.application as any).Application(address, credentials); this.createCall(); return this; } public stop(): this { if (this.isRunning) { this.client.close(); } return this; } private createCall(): void { this.call = (this.client as any).getApplicationDeveloperSubscriptions({ key: this.config.key }); this.call .on('data', data => this.emit('data', data)) // Just proxy .on('error', (err: ServiceError) => { // Connection was interrupted, recreate const retriableErrorStatuses = [ ServiceErrorStatus.INTERNAL, ServiceErrorStatus.UNKNOWN, ServiceErrorStatus.CANCELLED, ServiceErrorStatus.DEADLINE_EXCEEDED, ServiceErrorStatus.ABORTED ]; if (retriableErrorStatuses.includes(err.code)) { this.createCall(); } else { this.emit(EVENTS.UPDATE_ERROR, err); } }); } } export interface DeveloperKeyValidator extends EventEmitter { start(): void; stop(): void; isValidDeveloperKey(key: string): boolean; validateDeveloperKey(key: string): DeveloperSubscriptionValidationError; } export interface DeveloperKeysUpdatedPayload { keys: ApplicationDeveloperKeyWithSubscription[]; subscriptions: ApplicationDeveloperSubscription[]; } export class DeveloperKeyNotSyncedError extends Error {} export class DeveloperKeyNotFoundError extends Error {} export class DeveloperKeyNotActiveError extends Error {} export class DeveloperKeySubscriptionNotActiveError extends Error {} export type DeveloperSubscriptionValidationError = null | DeveloperKeyNotFoundError | DeveloperKeyNotActiveError | DeveloperKeySubscriptionNotActiveError; export class DefaultDeveloperKeyValidator extends DeveloperSubscriptionReceiver implements DeveloperKeyValidator { private developerSubscriptions: Map = new Map(); private developerKeys: Map = new Map(); private developerKeysSynced = false; constructor(config: ApplicationConfiguration) { super(config); } public start(): this { super.start(); super.on('data', this.onSubscriptionsUpdate.bind(this)); return this; } public stop(): this { super.stop(); return this; } public isValidDeveloperKey(key: string): boolean { return this.validateDeveloperKey(key) === null; } public validateDeveloperKey(key: string): DeveloperSubscriptionValidationError { if (!this.developerKeysSynced) { return new DeveloperKeyNotSyncedError('Developer keys not synced'); } if (!this.developerKeys.has(key)) { return new DeveloperKeyNotFoundError('No developer key found'); } const developerKey = this.developerKeys.get(key); if (!developerKey.active) { return new DeveloperKeyNotActiveError('Developer key not active'); } if (!developerKey.subscription.active) { return new DeveloperKeySubscriptionNotActiveError('Developer subscription not active'); } return null; } protected onSubscriptionsUpdate(update: GetApplicationDeveloperSubscriptionResponse): void { const keys = []; const subscriptions = []; for (const updatedSubscription of update.subscriptions) { this.developerSubscriptions.set(updatedSubscription.id, updatedSubscription); for (const updatedKey of updatedSubscription.keys) { const developerKey = updatedKey as ApplicationDeveloperKeyWithSubscription; developerKey.subscription = updatedSubscription; this.developerKeys.set(developerKey.key, developerKey); keys.push(this.developerKeys.get(developerKey.key)); } subscriptions.push(this.developerSubscriptions.get(updatedSubscription.id)); } this.emit(EVENTS.UPDATE_SUCCESS, { keys, subscriptions }); this.developerKeysSynced = true; } }