All files ServiceBusPubSub.ts

89.47% Statements 51/57
66.66% Branches 26/39
76.47% Functions 13/17
89.09% Lines 49/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1851x   1x                       1x 1x   1x                                       1x       2x     2x 2x                     2x 2x 2x 2x 2x       2x 2x 2x       2x 2x 2x                               6x 6x             6x       6x                                   9x 9x   9x 2x     9x           3x       2x 2x     2x 2x     9x               4x 4x   3x 3x 3x     3x 3x             6x   6x 6x   6x 6x       6x       6x      
import { PubSubEngine } from "graphql-subscriptions";
 
import {
  ServiceBusClient,
  ServiceBusMessage,
  ServiceBusReceivedMessage,
  ServiceBusSender,
  ServiceBusReceiver,
  delay,
  isServiceBusError,
  ProcessErrorArgs,
  ServiceBusError,
} from "@azure/service-bus";
 
import { Subject, Subscription, filter, tap, map } from "rxjs";
import debug from "debug";
import { IEvent, IEventResult } from "./Event";
import { IMessageProcessor, MessageProcessor } from "./MessageProcessor";
 
export interface ILogger extends Console {}
 
/**
 * Represents configuration needed to wire up PubSub engine with the ServiceBus topic
 * @property {string} connectionString - The ServiceBus connection string. This would be the Shared Access Policy connection string.
 * @property {string} topicName - This would be the topic where all the events will be published.
 * @property {string} subscriptionName - This would be the ServiceBus topic subscription name.
 */
export interface IServiceBusOptions {
  connectionString: string;
  topicName: string;
  subscriptionName: string;
}
 
/**
 * An override for the in-memory PubSubEngine which connects to the Azure ServiceBus.
 */
 
export class ServiceBusPubSub extends PubSubEngine {
  private client: ServiceBusClient;
  private sender: ServiceBusSender;
  private reciever: ServiceBusReceiver;
  private subscriptions = new Map<number, Subscription>();
  private options: IServiceBusOptions;
  private subject: Subject<IEventResult>;
  private debugger = debug("graphql:servicebus");
  private eventNameKey: string = "sub.eventName";
  private subscription: { close(): Promise<void> } | undefined;
  private logger: ILogger;
  private messageProcessor: IMessageProcessor;
 
  constructor(
    options: IServiceBusOptions,
    logger: ILogger,
    messageProcessor?: IMessageProcessor,
    client?: ServiceBusClient
  ) {
    super();
    this.options = options;
    this.client = client || new ServiceBusClient(this.options.connectionString);
    this.sender = this.client.createSender(this.options.topicName);
    this.reciever = this.client.createReceiver(
      this.options.topicName,
      this.options.subscriptionName
    );
    this.logger = logger;
    this.messageProcessor = messageProcessor || new MessageProcessor(logger);
    this.subject = new Subject<IEventResult>();
  }
 
  createSubscription(): { close(): Promise<void> } {
    return this.reciever.subscribe({
      processMessage: async (message: ServiceBusReceivedMessage) => {
        await this.messageProcessor.process(this.subject, message);
      },
      processError: async (args: ProcessErrorArgs) => {
        await this.messageProcessor.onError(
          args,
          async (error: ServiceBusError): Promise<void> => {
            if (error.code === "UnauthorizedAccess") {
              await this.subscription?.close();
            }
          }
        );
      },
    });
  }
 
  async publish(eventName: string, payload: any): Promise<void> {
    try {
      let event: IEvent = {
        body: {
          name: eventName,
          payload: payload,
        },
      };
 
      event = this.enrichMessage(
        new Map<string, any>([[this.eventNameKey, eventName]]),
        event
      );
      return this.sender.sendMessages(event);
    } catch (error) {
      this.logger.error(error);
    }
  }
 
  /**
   * Subscribe to a specific event updates. The subscribe method would create a ServiceBusReceiver to listen to all the published events.
   * The method internally would filter out all the received events that are not meant for this subscriber.
   * @property {eventName | string} - published event name
   * @property {onMessage | Function} - client handler for processing received events.
   * @returns {Promise<number>} - returns the created identifier for the created subscription. It would be used to dispose/close any resources while unsubscribing.
   */
  async subscribe(
    eventName: string,
    onMessage: Function,
    options: Object = {}
  ): Promise<number> {
    const id = Date.now() * Math.random();
    this.debugger("sub metadata: ", eventName, onMessage, options);
 
    if (this.subscriptions.size <= 0) {
      this.subscription = this.createSubscription();
    }
 
    this.subscriptions.set(
      id,
      this.subject
        .pipe(
          filter(
            (e) =>
              (eventName && e.body.name === eventName) ||
              !eventName ||
              eventName === "*"
          ),
          map((e) => e.body.payload),
          tap((e) => e)
        )
        .subscribe((event) => {
          this.debugger("returned event: ", event);
          onMessage(event);
        })
    );
    return id;
  }
 
  /**
   * Unsubscribe method would close open connection with the ServiceBus for a specific event handler.
   * @property {subId} - It's a unique identifier for each subscribed client.
   */
  async unsubscribe(subId: number): Promise<boolean> {
    const subscription = this.subscriptions.get(subId) || undefined;
    if (!subscription) return false;
 
    Eif (!subscription.closed) {
      subscription.unsubscribe();
      this.subscriptions.delete(subId);
    }
 
    if (this.subscriptions.size <= 0) await this.subscription?.close();
    return true;
  }
 
  private enrichMessage(
    attributes: Map<string, any>,
    message: ServiceBusMessage
  ): ServiceBusMessage {
    const enrichedMessage = Object.assign({}, message);
 
    Eif (enrichedMessage.applicationProperties == undefined)
      enrichedMessage.applicationProperties = {};
 
    attributes.forEach((value, key) => {
      Eif (
        enrichedMessage.applicationProperties !== undefined &&
        enrichedMessage.applicationProperties?.[key] === undefined
      ) {
        enrichedMessage.applicationProperties[key] = value;
      }
    });
 
    return enrichedMessage;
  }
}