arvo-event-handler
Version:
Type-safe event handler system with versioning, telemetry, and contract validation for distributed Arvo event-driven architectures, featuring routing and multi-handler support.
260 lines (259 loc) • 12.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleEventBroker = void 0;
var utils_1 = require("./utils");
/**
* A simple event broker for handling local event-driven workflows within function scope.
* Ideal for composing function handlers and coordinating local business logic steps.
*
* @description
* Use SimpleEventBroker when you need:
* - Local event handling within a function's execution scope
* - Decoupling steps in a business process
* - Simple composition of handlers for a workflow
* - In-memory event management for a single operation
*
* Not suitable for:
* - Long-running processes or persistent event storage
* - Cross-process or distributed event handling
* - High-throughput event processing (>1000s events/sec)
* - Mission critical or fault-tolerant systems
* - Complex event routing or filtering
*
* Typical use cases:
* - Coordinating steps in a registration process
* - Managing validation and processing workflows
* - Decoupling business logic steps
* - Local event-driven state management
*
* @example
* ```typescript
* // During a registration flow
* const broker = new SimpleEventBroker({ ... });
*
* broker.subscribe('validation.complete', async (event) => {
* // Handle validation results
* });
*
* broker.subscribe('user.created', async (event) => {
* // Handle user creation side effects
* });
*
* await broker.publish({
* to: 'validation.complete',
* payload: userData
* });
* ```
*/
var SimpleEventBroker = /** @class */ (function () {
function SimpleEventBroker(options) {
this.eventProcessDelay = 1;
this.subscribers = new Map();
this.queue = [];
this.events = [];
this.isProcessing = false;
this.maxQueueSize = options.maxQueueSize;
this.onError = options.errorHandler;
}
Object.defineProperty(SimpleEventBroker.prototype, "topics", {
/**
* All event types that have registered listeners.
*/
get: function () {
return Array.from(this.subscribers.keys());
},
enumerable: false,
configurable: true
});
/**
* Subscribe to a specific event type
* @param topic - Event type to subscribe to
* @param handler - Function to handle the event
* @param assertUnique - Asserts the uniqne-ness of the handler.
* If true, then only one handler per topic
* otherwise, throws error
* @returns Unsubscribe function
*/
SimpleEventBroker.prototype.subscribe = function (topic, handler, assertUnique) {
var _this = this;
var _a, _b;
if (assertUnique === void 0) { assertUnique = false; }
if (!this.subscribers.has(topic)) {
this.subscribers.set(topic, new Set());
}
if (assertUnique && ((_b = (_a = this.subscribers.get(topic)) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0) > 1) {
throw new Error("Only one subscriber allowed per topic: ".concat(topic));
}
// biome-ignore lint/style/noNonNullAssertion: non issue
var handlers = this.subscribers.get(topic);
handlers.add(handler);
return function () {
handlers.delete(handler);
if (handlers.size === 0) {
_this.subscribers.delete(topic);
}
};
};
/**
* Publish an event to subscribers
* @param event - Event to publish
* @throws Error if queue is full or event has no topic
*/
SimpleEventBroker.prototype.publish = function (event) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!event.to) {
throw new Error('Event must have a "to" property');
}
if (this.queue.length >= this.maxQueueSize) {
throw new Error("Event queue is full (max size: ".concat(this.maxQueueSize, ")"));
}
this.queue.push(event);
this.events.push(event);
if (!!this.isProcessing) return [3 /*break*/, 2];
return [4 /*yield*/, this.processQueue()];
case 1:
_a.sent();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
Object.defineProperty(SimpleEventBroker.prototype, "queueLength", {
/**
* Current number of events in queue
*/
get: function () {
return this.queue.length;
},
enumerable: false,
configurable: true
});
/**
* Number of subscribers for a given topic
*/
SimpleEventBroker.prototype.getSubscriberCount = function (topic) {
var _a, _b;
return (_b = (_a = this.subscribers.get(topic)) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0;
};
/**
* Processes queued events asynchronously, ensuring sequential execution.
* Handles error cases and maintains the processing state.
*
* @remarks
* - Only one instance of processQueue runs at a time
* - Events are processed in FIFO order
* - Failed event handlers trigger onError callback
* - All handlers for an event are processed in parallel
*
* @throws Propagates any unhandled errors from event processing
*/
SimpleEventBroker.prototype.processQueue = function () {
return __awaiter(this, void 0, void 0, function () {
var _loop_1, this_1;
var _this = this;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.isProcessing)
return [2 /*return*/];
this.isProcessing = true;
_b.label = 1;
case 1:
_b.trys.push([1, , 5, 6]);
_loop_1 = function () {
var event_1, handlers, handlerPromises;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
event_1 = this_1.queue.pop();
if (!event_1)
return [2 /*return*/, "continue"];
if (!this_1.eventProcessDelay) return [3 /*break*/, 2];
return [4 /*yield*/, (0, utils_1.promiseTimeout)(this_1.eventProcessDelay)];
case 1:
_c.sent();
_c.label = 2;
case 2:
handlers = this_1.subscribers.get((_a = event_1.to) !== null && _a !== void 0 ? _a : '');
if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
this_1.onError(new Error("No handlers registered for event type: ".concat(event_1.to)), event_1);
return [2 /*return*/, "continue"];
}
handlerPromises = Array.from(handlers).map(function (handler) {
return handler(event_1, _this.publish.bind(_this)).catch(function (error) {
if (error instanceof Error) {
_this.onError(error, event_1);
}
else {
_this.onError(new Error(String(error)), event_1);
}
});
});
return [4 /*yield*/, Promise.all(handlerPromises)];
case 3:
_c.sent();
return [2 /*return*/];
}
});
};
this_1 = this;
_b.label = 2;
case 2:
if (!(this.queue.length > 0)) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1()];
case 3:
_b.sent();
return [3 /*break*/, 2];
case 4: return [3 /*break*/, 6];
case 5:
this.isProcessing = false;
return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
});
};
return SimpleEventBroker;
}());
exports.SimpleEventBroker = SimpleEventBroker;