@dawntech/dispatcher 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.prettierignore +4 -0
- package/.prettierrc +7 -0
- package/README.md +3 -0
- package/dist/chunk-64334IMD.mjs +2 -0
- package/dist/chunk-64334IMD.mjs.map +1 -0
- package/dist/chunk-6IAFH374.mjs +2 -0
- package/dist/chunk-6IAFH374.mjs.map +1 -0
- package/dist/chunk-HYW2O7ZX.mjs +2 -0
- package/dist/chunk-HYW2O7ZX.mjs.map +1 -0
- package/dist/chunk-OR34YAY3.mjs +2 -0
- package/dist/chunk-OR34YAY3.mjs.map +1 -0
- package/dist/chunk-OXXLVJVC.mjs +2 -0
- package/dist/chunk-OXXLVJVC.mjs.map +1 -0
- package/dist/chunk-QA6PFVGP.mjs +2 -0
- package/dist/chunk-QA6PFVGP.mjs.map +1 -0
- package/dist/chunk-SLZLYBPB.mjs +2 -0
- package/dist/chunk-SLZLYBPB.mjs.map +1 -0
- package/dist/chunk-UFUGEIFL.mjs +2 -0
- package/dist/chunk-UFUGEIFL.mjs.map +1 -0
- package/dist/chunk-XLRB2LAD.mjs +2 -0
- package/dist/chunk-XLRB2LAD.mjs.map +1 -0
- package/dist/chunk-YDWZJWCU.mjs +2 -0
- package/dist/chunk-YDWZJWCU.mjs.map +1 -0
- package/dist/core/Blip.d.mts +84 -0
- package/dist/core/Blip.js +2 -0
- package/dist/core/Blip.js.map +1 -0
- package/dist/core/Blip.mjs +2 -0
- package/dist/core/Blip.mjs.map +1 -0
- package/dist/core/Dispatcher.d.mts +52 -0
- package/dist/core/Dispatcher.js +2 -0
- package/dist/core/Dispatcher.js.map +1 -0
- package/dist/core/Dispatcher.mjs +2 -0
- package/dist/core/Dispatcher.mjs.map +1 -0
- package/dist/core/DispatcherDescriptor.d.mts +23 -0
- package/dist/core/DispatcherDescriptor.js +2 -0
- package/dist/core/DispatcherDescriptor.js.map +1 -0
- package/dist/core/DispatcherDescriptor.mjs +2 -0
- package/dist/core/DispatcherDescriptor.mjs.map +1 -0
- package/dist/core/DispatcherMonitor.d.mts +52 -0
- package/dist/core/DispatcherMonitor.js +2 -0
- package/dist/core/DispatcherMonitor.js.map +1 -0
- package/dist/core/DispatcherMonitor.mjs +2 -0
- package/dist/core/DispatcherMonitor.mjs.map +1 -0
- package/dist/core/DispatcherQuery.d.mts +14 -0
- package/dist/core/DispatcherQuery.js +2 -0
- package/dist/core/DispatcherQuery.js.map +1 -0
- package/dist/core/DispatcherQuery.mjs +2 -0
- package/dist/core/DispatcherQuery.mjs.map +1 -0
- package/dist/core/DispatcherRepository.d.mts +47 -0
- package/dist/core/DispatcherRepository.js +2 -0
- package/dist/core/DispatcherRepository.js.map +1 -0
- package/dist/core/DispatcherRepository.mjs +2 -0
- package/dist/core/DispatcherRepository.mjs.map +1 -0
- package/dist/core/DispatcherStateMachine.d.mts +20 -0
- package/dist/core/DispatcherStateMachine.js +2 -0
- package/dist/core/DispatcherStateMachine.js.map +1 -0
- package/dist/core/DispatcherStateMachine.mjs +2 -0
- package/dist/core/DispatcherStateMachine.mjs.map +1 -0
- package/dist/errors/index.d.mts +54 -0
- package/dist/errors/index.js +2 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/errors/index.mjs +2 -0
- package/dist/errors/index.mjs.map +1 -0
- package/dist/index.d.mts +11 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/server.d.mts +2 -0
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/server.mjs +2 -0
- package/dist/server.mjs.map +1 -0
- package/dist/types/blip.d.mts +127 -0
- package/dist/types/blip.js +2 -0
- package/dist/types/blip.js.map +1 -0
- package/dist/types/blip.mjs +2 -0
- package/dist/types/blip.mjs.map +1 -0
- package/dist/types/index.d.mts +155 -0
- package/dist/types/index.js +2 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +2 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/utils/logger.d.mts +73 -0
- package/dist/utils/logger.js +2 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/logger.mjs +2 -0
- package/dist/utils/logger.mjs.map +1 -0
- package/jest.config.js +48 -0
- package/package.json +81 -0
- package/tsconfig.json +22 -0
- package/tsconfig.test.json +10 -0
- package/tsup.config.js +10 -0
- package/types/core/Blip.d.ts.map +1 -0
- package/types/core/Dispatcher.d.ts.map +1 -0
- package/types/core/DispatcherDescriptor.d.ts.map +1 -0
- package/types/core/DispatcherMonitor.d.ts.map +1 -0
- package/types/core/DispatcherQuery.d.ts.map +1 -0
- package/types/core/DispatcherRepository.d.ts.map +1 -0
- package/types/core/DispatcherStateMachine.d.ts.map +1 -0
- package/types/errors/index.d.ts.map +1 -0
- package/types/index.d.ts.map +1 -0
- package/types/server.d.ts.map +1 -0
- package/types/types/blip.d.ts.map +1 -0
- package/types/types/index.d.ts.map +1 -0
- package/types/utils/logger.d.ts.map +1 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var A=Object.create;var p=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var v=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var s in t)p(e,s,{get:t[s],enumerable:!0})},b=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of x(t))!R.call(e,r)&&r!==s&&p(e,r,{get:()=>t[r],enumerable:!(i=L(t,r))||i.enumerable});return e};var N=(e,t,s)=>(s=e!=null?A(v(e)):{},b(t||!e||!e.__esModule?p(s,"default",{value:e,enumerable:!0}):s,e)),S=e=>b(p({},"__esModule",{value:!0}),e);var O={};C(O,{DispatcherQuery:()=>D});module.exports=S(O);var l=(o=>(o.INIT="INIT",o.PENDING="PENDING",o.SENDING="SENDING",o.DELIVERED="DELIVERED",o.READ="READ",o.REPLIED="REPLIED",o.FAILED="FAILED",o.CANCELED="CANCELED",o))(l||{});var u=N(require("debug")),d={debug:"debug",info:"info",warn:"warn",error:"error"},I=new Map;function F(e){if(e==null)return e;if(typeof e=="object")try{return JSON.stringify(e,null,2)}catch{return e}return e}function y(e){return(...t)=>{let s=t.map(F);e(...s)}}function h(e){if(!I.has(e)){let t=(0,u.default)(`${e}:${d.debug}`),s=(0,u.default)(`${e}:${d.info}`),i=(0,u.default)(`${e}:${d.warn}`),r=(0,u.default)(`${e}:${d.error}`);r.log=console.error.bind(console);let a={debug:y(t),info:y(s),warn:y(i),error:y(r)};I.set(e,a)}return I.get(e)}var M=h("DispatcherQuery"),D=class{constructor(t){this.repository=t}get client(){return this.repository.redis}async query(t){let s=[],i=this.repository.keyPrefix;if(t.contactId&&s.push(this.repository.getContactKey(t.contactId)),t.descriptorId&&s.push(this.repository.getDescriptorKey(t.descriptorId)),t.status){let n=Array.isArray(t.status)?t.status:[t.status];n.length===1?s.push(this.repository.getStatusKey(n[0])):n.length>1&&s.push(this.repository.getStatusKey(n[0]))}if(t.state){let n=Array.isArray(t.state)?t.state:[t.state];n.length===1&&s.push(this.repository.getStateKey(n[0]))}let r=[];if(s.length>0)r=await this.client.sinter(s);else{let n=Object.values(l).map(c=>this.repository.getStatusKey(c));r=await this.client.sunion(n)}let a=t.skip??0,g=t.size??50,E=r.slice(a,a+g),o=[],m=[];for(let n of E){let c=await this.repository.getMessage(n);if(c){if(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(c.status)||t.state&&!(Array.isArray(t.state)?t.state:[t.state]).includes(c.state))continue;o.push(c)}else m.push(n)}return m.length>0&&this.cleanupIndices(m,t),o}async cleanupIndices(t,s){let i=this.client.pipeline(),r=this.repository.keyPrefix;s.contactId&&i.srem(this.repository.getContactKey(s.contactId),t),s.descriptorId&&i.srem(this.repository.getDescriptorKey(s.descriptorId),t),s.status&&(Array.isArray(s.status)?s.status:[s.status]).forEach(g=>{i.srem(this.repository.getStatusKey(g),t)}),s.state&&(Array.isArray(s.state)?s.state:[s.state]).forEach(g=>{i.srem(this.repository.getStateKey(g),t)}),await i.exec(),M.debug("[cleanupIndices] Removed expired IDs from checked indices",{count:t.length})}};0&&(module.exports={DispatcherQuery});
|
|
2
|
+
//# sourceMappingURL=DispatcherQuery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/DispatcherQuery.ts","../../src/types/index.ts","../../src/utils/logger.ts"],"sourcesContent":["import { DispatcherRepository } from './DispatcherRepository.js';\nimport { Message, MessageState, MessageStatus, QueryFilter } from '../types/index.js';\nimport { getLogger } from '../utils/logger.js';\nimport IORedis from 'ioredis';\n\nconst logger = getLogger('DispatcherQuery');\n\nexport class DispatcherQuery {\n private repository: DispatcherRepository;\n\n constructor(repository: DispatcherRepository) {\n this.repository = repository;\n }\n\n private get client(): IORedis {\n return this.repository.redis;\n }\n\n public async query(filter: QueryFilter): Promise<Message[]> {\n const keysToIntersect: string[] = [];\n const prefix = this.repository['keyPrefix'];\n\n // 1. Build Intersection Sets using new INDEX keys\n if (filter.contactId) {\n keysToIntersect.push(this.repository.getContactKey(filter.contactId));\n }\n\n if (filter.descriptorId) {\n keysToIntersect.push(this.repository.getDescriptorKey(filter.descriptorId));\n }\n\n if (filter.status) {\n const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];\n if (statuses.length === 1) {\n keysToIntersect.push(this.repository.getStatusKey(statuses[0]));\n } else if (statuses.length > 1) {\n // For MVP, if multiple statuses, we intersect the FIRST one and filter the rest in memory.\n keysToIntersect.push(this.repository.getStatusKey(statuses[0]));\n }\n }\n\n // Now safe to use state index for ALL states (even SCHEDULED/QUEUED) because we index them as Sets too.\n if (filter.state) {\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n if (states.length === 1) {\n keysToIntersect.push(this.repository.getStateKey(states[0]));\n }\n }\n\n let messageIds: string[] = [];\n\n if (keysToIntersect.length > 0) {\n // Execute Intersection\n messageIds = await this.client.sinter(keysToIntersect);\n } else {\n // Fallback: No filters provided (e.g. \"All\" selected without other filters)\n // We want to return ALL messages. We can do this by Unioning all Status sets.\n // This allows us to see Delivered/Failed messages even if not filtering by them.\n const allStatusKeys = Object.values(MessageStatus).map((status) =>\n this.repository.getStatusKey(status)\n );\n messageIds = await this.client.sunion(allStatusKeys);\n }\n\n // 2. Handle OR logic for multiple statuses/states if needed\n // (Omitted for MVP, assuming single values or handling in memory for small intersections)\n\n // 3. Paging\n const skip = filter.skip ?? 0;\n const size = filter.size ?? 50;\n const pagedIds = messageIds.slice(skip, skip + size);\n\n // 4. Fetch Messages & Lazy Cleanup\n const messages: Message[] = [];\n const idsToRemove: string[] = [];\n\n for (const id of pagedIds) {\n const message = await this.repository.getMessage(id);\n if (message) {\n // Validate in-memory filters (e.g. multiple statuses, or if SINTER wasn't perfect)\n if (filter.status) {\n const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];\n if (!statuses.includes(message.status)) continue;\n }\n if (filter.state) {\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n if (!states.includes(message.state)) continue;\n }\n\n messages.push(message);\n } else {\n // Message ID exists in index but not in storage -> Expired\n idsToRemove.push(id);\n }\n }\n\n // Lazy Cleanup\n if (idsToRemove.length > 0) {\n this.cleanupIndices(idsToRemove, filter);\n }\n\n return messages;\n }\n\n private async cleanupIndices(ids: string[], context: QueryFilter): Promise<void> {\n const pipeline = this.client.pipeline();\n const prefix = this.repository['keyPrefix'];\n\n // Basic cleanup: Remove from the keys we just queried.\n if (context.contactId) {\n pipeline.srem(this.repository.getContactKey(context.contactId), ids);\n }\n if (context.descriptorId) {\n pipeline.srem(this.repository.getDescriptorKey(context.descriptorId), ids);\n }\n\n if (context.status) {\n const statuses = Array.isArray(context.status) ? context.status : [context.status];\n statuses.forEach((s) => {\n pipeline.srem(this.repository.getStatusKey(s), ids);\n });\n }\n if (context.state) {\n const states = Array.isArray(context.state) ? context.state : [context.state];\n states.forEach((s) => {\n pipeline.srem(this.repository.getStateKey(s), ids);\n });\n }\n\n await pipeline.exec();\n logger.debug('[cleanupIndices] Removed expired IDs from checked indices', {\n count: ids.length,\n });\n }\n}\n","import { Vnd } from './blip';\n\nexport type Contact = Omit<Vnd.Iris.Contact, 'identity'>;\n\nexport type MessageData = {\n type: string;\n content: Record<string, any> | string;\n};\n\nexport type MessagePayload = Record<string, any> | Array<any> | string;\n\nexport enum MessageState {\n INIT = 'INIT',\n DISPATCHED = 'DISPATCHED',\n SCHEDULED = 'SCHEDULED',\n QUEUED = 'QUEUED',\n FINAL = 'FINAL',\n}\n\nexport enum MessageStatus {\n INIT = 'INIT',\n PENDING = 'PENDING',\n SENDING = 'SENDING',\n DELIVERED = 'DELIVERED',\n READ = 'READ',\n REPLIED = 'REPLIED',\n FAILED = 'FAILED',\n CANCELED = 'CANCELED',\n}\n\nexport enum DispatchState {\n ACCEPTED = 'accepted',\n DISPATCHED = 'dispatched',\n RECEIVED = 'received',\n CONSUMED = 'consumed',\n FAILED = 'failed',\n}\n\nexport interface Message {\n messageId: string;\n contactId: string;\n descriptorId: string;\n\n payload: MessageData;\n status: MessageStatus;\n state: MessageState;\n\n attempts?: number;\n retries?: number;\n\n options?: MessageOptions; // Persisted options for scheduled/retried messages\n\n expiresAt?: string; // ISO 8601 datetime\n\n scheduledTo?: string; // ISO 8601 datetime\n sentAt?: string; // ISO 8601 datetime\n acceptedAt?: string; // ISO 8601 datetime - When message was accepted by gateway (SENDING status)\n lastDispatchAttemptAt?: string; // ISO 8601 datetime - When last dispatch attempt started\n createdAt: string; // ISO 8601 datetime\n deliveredAt?: string; // ISO 8601 datetime\n readAt?: string; // ISO 8601 datetime\n repliedAt?: string; // ISO 8601 datetime\n failedAt?: string; // ISO 8601 datetime\n\n error?: string;\n}\n\nexport interface Shift {\n days: number; // Bitmask: use Weekdays enum (e.g., Weekdays.MONDAY | Weekdays.FRIDAY) or manual (31=Mon-Fri)\n start: string; // HH:mm format (e.g., \"09:00\")\n end: string; // HH:mm format (e.g., \"18:00\")\n gmt?: string; // Timezone offset (default: \"-3\" for BRT)\n}\n\nexport enum Weekdays {\n MONDAY = 1,\n TUESDAY = 2,\n WEDNESDAY = 4,\n THURSDAY = 8,\n FRIDAY = 16,\n SATURDAY = 32,\n SUNDAY = 64,\n}\n\nexport interface Intent {\n intent: string;\n dueDate?: string;\n event?: string;\n payload?: any | null;\n expired?: {\n event?: string;\n intent?: string;\n };\n}\n\nexport type CallbackEvent =\n | 'dispatch' // Before message send process begins\n | 'sending' // MessageStatus.SENDING - message accepted by gateway\n | 'delivered' // MessageStatus.DELIVERED - message successfully delivered\n | 'failed' // MessageStatus.FAILED - message failed permanently\n | 'read' // MessageStatus.READ - message read by recipient\n | 'replied' // MessageStatus.REPLIED - recipient replied\n | 'scheduled' // MessageState.SCHEDULED - message scheduled\n | 'retry' // Retry attempt scheduled\n | 'evicted' // Message evicted from state machine due to TTL\n | 'canceled'; // Message canceled before send\n\nexport type ConnectionConfig = {\n contract: string; // Contract ID (without https:// prefix)\n key: string; // Bot authorization key\n};\n\nexport interface MessageOptions {\n shifts?: Array<Shift>; // Business hours constraints\n contact?: Contact;\n state?: {\n // Bot state to set after send\n stateId: string;\n botId: string;\n botIds?: Array<string>; // Bot IDs to reset before setting state\n };\n intent?: string | Intent; // Intent to trigger after send\n finalStatus?: 'DELIVERED' | 'READ' | 'REPLIED'; // Default: 'DELIVERED'\n}\n\nexport interface DispatchMessageOptions extends MessageOptions {\n schedule?: string; // ISO 8601 datetime to schedule send\n}\n\nexport interface DispatcherOptions {\n maxRetries?: number; // Default: 0\n retryIntervals?: number[]; // Default: [1000, 5000, 15000] (exponential backoff in ms)\n\n // Storage Duration (Redis TTL)\n retention?: number; // Default: 3600000 ms (1 hour) - Time to keep message in storage after creation/dispatch\n\n // State Constraints (Force transition to FAILED)\n timeouts?: {\n pending?: number; // Default: 10000 ms (10 seconds)\n sending?: number; // Default: 60000 ms (60 seconds)\n };\n\n batchSize?: number; // Default: 100 messages per polling cycle\n pollingIntervals?: {\n scheduled?: number; // Default: 5000 ms\n pending?: number; // Default: 5000 ms\n sending?: number; // Default: 10000 ms\n delivered?: number; // Default: 1800000 ms (30 minutes)\n read?: number; // Default: 3600000 ms (60 minutes)\n queue?: number; // Default: 100 ms\n };\n maxQueueSize?: number; // Maximum number of pending/scheduled messages. Oldest evicted if exceeded.\n rateLimits?: {\n global?: { points: number; duration: number }; // Global rate limit (requests per duration)\n message?: { points: number; duration: number }; // Message sending rate limit (requests per duration)\n };\n}\n\nexport interface QueryFilter {\n contactId?: string;\n descriptorId?: string;\n status?: MessageStatus | MessageStatus[];\n state?: MessageState | MessageState[];\n size?: number;\n skip?: number;\n}\n\nexport interface DispatcherMetrics {\n total: number;\n byState: {\n [key in MessageState]?: number;\n };\n byStatus: {\n [key in MessageStatus]?: number;\n };\n cumulative: {\n dispatched: number;\n delivered: number;\n failed: number;\n };\n}\n\n/**\n * @deprecated Use DispatcherOptions instead\n */\nexport type MessageDispatcherOptions = DispatcherOptions;\n","/**\n * Logger utility using the 'debug' package.\n *\n * This module provides a configurable logger based on the 'debug' package.\n * By default, all logging is disabled. To enable logging, set the DEBUG\n * environment variable.\n *\n * The DEBUG variable can be a single namespace or a comma-separated list of\n * namespaces. Wildcards are supported.\n *\n * For example:\n * - `DEBUG=blip-api` enables all logs for the 'blip-api' scope.\n * - `DEBUG=blip-api:*` enables all sub-scopes under 'blip-api'.\n * - `DEBUG=*` enables all logs.\n *\n * The logger exposes different levels (debug, info, warn, error), which are\n * different namespaces.\n *\n * Example usage:\n * ```\n * import { getLogger } from './logger';\n *\n * const logger = getLogger('my-feature');\n *\n * logger.info('This is an info message');\n * logger.error('This is an error');\n * ```\n *\n * To see the output, run your application with:\n * `DEBUG=my-feature:* node your-app.js`\n */\n\nimport debug from 'debug';\n\n// Define the available log levels\nexport const LogLevels = {\n debug: 'debug',\n info: 'info',\n warn: 'warn',\n error: 'error',\n};\n\nexport type LogLevel = keyof typeof LogLevels;\n\ntype LogFunction = (...args: any[]) => void;\n\nexport interface Logger {\n debug: LogFunction;\n info: LogFunction;\n warn: LogFunction;\n error: LogFunction;\n}\n\nconst loggers = new Map<string, Logger>();\n\nfunction serializeArg(arg: any): any {\n if (arg === null || arg === undefined) return arg;\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg, null, 2);\n } catch (e) {\n return arg;\n }\n }\n return arg;\n}\n\nfunction createLogFunction(debugInstance: debug.Debugger): LogFunction {\n return (...args: any[]) => {\n const serialized = args.map(serializeArg);\n (debugInstance as any)(...serialized);\n };\n}\n\n/**\n * Creates a logger with a specific scope.\n *\n * @param scope - The scope for the logger (e.g., 'blip-api', 'dispatcher').\n * @returns A logger object with methods for each log level.\n */\nexport function getLogger(scope: string): Logger {\n if (!loggers.has(scope)) {\n const debugInstance = debug(`${scope}:${LogLevels.debug}`);\n const infoInstance = debug(`${scope}:${LogLevels.info}`);\n const warnInstance = debug(`${scope}:${LogLevels.warn}`);\n const errorInstance = debug(`${scope}:${LogLevels.error}`);\n\n errorInstance.log = console.error.bind(console);\n\n const logger: Logger = {\n debug: createLogFunction(debugInstance),\n info: createLogFunction(infoInstance),\n warn: createLogFunction(warnInstance),\n error: createLogFunction(errorInstance),\n };\n\n loggers.set(scope, logger);\n }\n return loggers.get(scope)!;\n}\n\n/**\n * Enables logging for a specific scope and level.\n * This is a convenience function to programmatically enable logging,\n * equivalent to setting the DEBUG environment variable.\n *\n * @param scope - The scope to enable (e.g., 'blip-api').\n * @param level - The minimum log level to enable (e.g., 'info').\n */\nexport function enableLogger(namespaces: string): void {\n const currentDebug = debug.disable();\n debug.enable(`${currentDebug},${namespaces}`);\n}\n\n/**\n * Disables all logging.\n */\nexport function disableLogger(): void {\n debug.disable();\n}\n\n/**\n * Get all registered logger scopes.\n *\n * @returns An array of all registered scopes.\n */\nexport function getAllScopes(): string[] {\n return Array.from(loggers.keys());\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GCmBO,IAAKI,OACVA,EAAA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KAAMH,EAAU,CACzB,IAAMI,EAAU,MAAM,KAAK,WAAW,WAAWD,CAAE,EACnD,GAAIC,EAAS,CAMX,GAJIf,EAAO,QAEL,EADa,MAAM,QAAQA,EAAO,MAAM,EAAIA,EAAO,OAAS,CAACA,EAAO,MAAM,GAChE,SAASe,EAAQ,MAAM,GAEnCf,EAAO,OAEL,EADW,MAAM,QAAQA,EAAO,KAAK,EAAIA,EAAO,MAAQ,CAACA,EAAO,KAAK,GAC7D,SAASe,EAAQ,KAAK,EAAG,SAGvCH,EAAS,KAAKG,CAAO,CACvB,MAEEF,EAAY,KAAKC,CAAE,CAEvB,CAGA,OAAID,EAAY,OAAS,GACvB,KAAK,eAAeA,EAAab,CAAM,EAGlCY,CACT,CAEA,MAAc,eAAeI,EAAeC,EAAqC,CAC/E,IAAMC,EAAW,KAAK,OAAO,SAAS,EAChChB,EAAS,KAAK,WAAW,UAG3Be,EAAQ,WACVC,EAAS,KAAK,KAAK,WAAW,cAAcD,EAAQ,SAAS,EAAGD,CAAG,EAEjEC,EAAQ,cACVC,EAAS,KAAK,KAAK,WAAW,iBAAiBD,EAAQ,YAAY,EAAGD,CAAG,EAGvEC,EAAQ,SACO,MAAM,QAAQA,EAAQ,MAAM,EAAIA,EAAQ,OAAS,CAACA,EAAQ,MAAM,GACxE,QAASE,GAAM,CACtBD,EAAS,KAAK,KAAK,WAAW,aAAaC,CAAC,EAAGH,CAAG,CACpD,CAAC,EAECC,EAAQ,QACK,MAAM,QAAQA,EAAQ,KAAK,EAAIA,EAAQ,MAAQ,CAACA,EAAQ,KAAK,GACrE,QAASE,GAAM,CACpBD,EAAS,KAAK,KAAK,WAAW,YAAYC,CAAC,EAAGH,CAAG,CACnD,CAAC,EAGH,MAAME,EAAS,KAAK,EACpBtB,EAAO,MAAM,4DAA6D,CACxE,MAAOoB,EAAI,MACb,CAAC,CACH,CACF","names":["DispatcherQuery_exports","__export","DispatcherQuery","__toCommonJS","MessageStatus","import_debug","LogLevels","loggers","serializeArg","arg","createLogFunction","debugInstance","args","serialized","getLogger","scope","debug","infoInstance","warnInstance","errorInstance","logger","logger","getLogger","DispatcherQuery","repository","filter","keysToIntersect","prefix","statuses","states","messageIds","allStatusKeys","MessageStatus","status","skip","size","pagedIds","messages","idsToRemove","id","message","ids","context","pipeline","s"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { MessageState, MessageStatus, Message } from '../types/index.mjs';
|
|
2
|
+
import IORedis from 'ioredis';
|
|
3
|
+
import '../types/blip.mjs';
|
|
4
|
+
|
|
5
|
+
declare class DispatcherRepository {
|
|
6
|
+
private static readonly INDEXED_STATUSES;
|
|
7
|
+
private static readonly INDEXED_STATES;
|
|
8
|
+
private client;
|
|
9
|
+
private keyPrefix;
|
|
10
|
+
constructor(dispatcherId: string, redisUrl: string);
|
|
11
|
+
setup(): Promise<void>;
|
|
12
|
+
teardown(): Promise<void>;
|
|
13
|
+
get redis(): IORedis;
|
|
14
|
+
getKey(messageId: string): string;
|
|
15
|
+
getStateKey(state: MessageState): string;
|
|
16
|
+
getStatusKey(status: MessageStatus): string;
|
|
17
|
+
getContactKey(contactId: string): string;
|
|
18
|
+
getDescriptorKey(descriptorId: string): string;
|
|
19
|
+
getQueueKey(name: 'scheduled' | 'queued' | 'dispatched' | 'expiration' | 'retention'): string;
|
|
20
|
+
upsertMessage(message: Message, ttl?: number): Promise<void>;
|
|
21
|
+
getMessage(messageId: string): Promise<Message | null>;
|
|
22
|
+
getMessages(filter: {
|
|
23
|
+
status?: MessageStatus;
|
|
24
|
+
state?: MessageState;
|
|
25
|
+
size?: number;
|
|
26
|
+
skip?: number;
|
|
27
|
+
}): Promise<Message[]>;
|
|
28
|
+
getQueueSize(): Promise<number>;
|
|
29
|
+
evictOldest(count: number): Promise<number>;
|
|
30
|
+
getExpiredMessages(count?: number): Promise<string[]>;
|
|
31
|
+
getRetentionMessages(count?: number): Promise<string[]>;
|
|
32
|
+
incrementMetric(key: string, value?: number): Promise<number>;
|
|
33
|
+
getMetric(key: string): Promise<number>;
|
|
34
|
+
deleteMessage(messageId: string): Promise<void>;
|
|
35
|
+
private deleteMessageData;
|
|
36
|
+
countMessages(filter: {
|
|
37
|
+
status?: MessageStatus;
|
|
38
|
+
state?: MessageState;
|
|
39
|
+
}): Promise<number>;
|
|
40
|
+
getMetrics(descriptorId?: string): Promise<any>;
|
|
41
|
+
getDescriptors(): Promise<{
|
|
42
|
+
id: string;
|
|
43
|
+
count: number;
|
|
44
|
+
}[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { DispatcherRepository };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var f=Object.create;var p=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var L=(r,e)=>{for(var t in e)p(r,t,{get:e[t],enumerable:!0})},E=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of w(e))!A.call(r,n)&&n!==t&&p(r,n,{get:()=>e[n],enumerable:!(s=S(e,n))||s.enumerable});return r};var m=(r,e,t)=>(t=r!=null?f(K(r)):{},E(e||!r||!r.__esModule?p(t,"default",{value:r,enumerable:!0}):t,r)),x=r=>E(p({},"__esModule",{value:!0}),r);var M={};L(M,{DispatcherRepository:()=>D});module.exports=x(M);var g=m(require("debug")),h={debug:"debug",info:"info",warn:"warn",error:"error"},y=new Map;function T(r){if(r==null)return r;if(typeof r=="object")try{return JSON.stringify(r,null,2)}catch{return r}return r}function l(r){return(...e)=>{let t=e.map(T);r(...t)}}function I(r){if(!y.has(r)){let e=(0,g.default)(`${r}:${h.debug}`),t=(0,g.default)(`${r}:${h.info}`),s=(0,g.default)(`${r}:${h.warn}`),n=(0,g.default)(`${r}:${h.error}`);n.log=console.error.bind(console);let i={debug:l(e),info:l(t),warn:l(s),error:l(n)};y.set(r,i)}return y.get(r)}var b=m(require("ioredis")),c=I("Repository"),u=class u{constructor(e,t){this.client=new b.default(t,{maxRetriesPerRequest:null}),this.keyPrefix=`dwn:dispatcher:${e}`,this.client.on("error",s=>{c.error("[client] Redis error",s)})}async setup(){if(this.client.status==="ready"){c.debug("[setup] Redis already connected, skipping");return}this.client.status==="wait"&&await this.client.connect(),c.info("[setup] Repository connected",{status:this.client.status})}async teardown(){this.client.status!=="end"&&(await this.client.quit(),c.info("[teardown] Repository disconnected"))}get redis(){return this.client}getKey(e){return`${this.keyPrefix}:message:${e}`}getStateKey(e){return`${this.keyPrefix}:index:state:${e.toLowerCase()}`}getStatusKey(e){return`${this.keyPrefix}:index:status:${e.toLowerCase()}`}getContactKey(e){return`${this.keyPrefix}:index:contact:${e}`}getDescriptorKey(e){return`${this.keyPrefix}:index:descriptor:${e}`}getQueueKey(e){return`${this.keyPrefix}:queue:${e.toLowerCase()}`}async upsertMessage(e,t){let s=this.getKey(e.messageId),n=JSON.stringify(e),i=this.client.pipeline();i.set(s,n),e.contactId&&i.sadd(this.getContactKey(e.contactId),e.messageId),e.descriptorId&&i.sadd(this.getDescriptorKey(e.descriptorId),e.messageId);for(let o of u.INDEXED_STATUSES){let d=this.getStatusKey(o);e.status===o?i.sadd(d,e.messageId):i.srem(d,e.messageId)}for(let o of u.INDEXED_STATES){let d=this.getStateKey(o);e.state===o?i.sadd(d,e.messageId):i.srem(d,e.messageId)}let a=Date.now()+(t||36e5*24*2);if(e.state==="SCHEDULED"&&e.scheduledTo&&(a=new Date(e.scheduledTo).getTime()+(t||0)),i.zadd(this.getQueueKey("retention"),a,e.messageId),e.state==="SCHEDULED"&&e.scheduledTo){let o=new Date(e.scheduledTo).getTime();i.zadd(this.getQueueKey("scheduled"),o,e.messageId)}else i.zrem(this.getQueueKey("scheduled"),e.messageId);if(e.state==="QUEUED"){let o=new Date(e.createdAt||Date.now()).getTime();i.zadd(this.getQueueKey("queued"),o,e.messageId)}else i.zrem(this.getQueueKey("queued"),e.messageId);if(e.state==="DISPATCHED"){let o=new Date(e.createdAt||Date.now()).getTime();i.zadd(this.getQueueKey("dispatched"),o,e.messageId)}else i.zrem(this.getQueueKey("dispatched"),e.messageId);await i.exec(),c.debug("[upsertMessage]",{messageId:e.messageId,status:e.status,state:e.state})}async getMessage(e){let t=this.getKey(e),s=await this.client.get(t);return s?JSON.parse(s):null}async getMessages(e){let t=[];if(e.state==="SCHEDULED"){let n=Date.now(),i=e.skip??0,a=e.size??0;a>0?t=await this.client.zrangebyscore(this.getQueueKey("scheduled"),0,n,"LIMIT",i,a):t=await this.client.zrangebyscore(this.getQueueKey("scheduled"),0,n)}else if(e.state==="QUEUED")t=await this.client.zrange(this.getQueueKey("queued"),e.skip??0,(e.skip??0)+(e.size?e.size-1:-1));else if(e.state==="DISPATCHED")t=await this.client.zrange(this.getQueueKey("dispatched"),e.skip??0,(e.skip??0)+(e.size?e.size-1:-1));else if(e.status){let n=await this.client.smembers(this.getStatusKey(e.status)),i=e.skip??0,a=e.size;t=a?n.slice(i,i+a):n.slice(i)}else if(e.state)try{let n=await this.client.smembers(this.getStateKey(e.state)),i=e.skip??0,a=e.size;t=a?n.slice(i,i+a):n.slice(i)}catch{return[]}else return c.warn("[getMessages] no filter provided"),[];let s=[];for(let n of t){let i=await this.getMessage(n);if(i){if(e.status&&i.status!==e.status||e.state&&i.state!==e.state)continue;s.push(i)}}return c.debug("[getMessages]",{count:s.length,filter:e}),s}async getQueueSize(){return await this.client.zcard(this.getQueueKey("dispatched"))}async evictOldest(e){if(e<=0)return 0;let t=await this.client.zpopmin(this.getQueueKey("dispatched"),e),s=0;for(let n=0;n<t.length;n+=2){let i=t[n];await this.deleteMessage(i),s++}return s}async getExpiredMessages(e=50){let t=Date.now();return await this.client.zrangebyscore(this.getQueueKey("expiration"),0,t,"LIMIT",0,e)}async getRetentionMessages(e=50){let t=Date.now();return await this.client.zrangebyscore(this.getQueueKey("retention"),0,t,"LIMIT",0,e)}async incrementMetric(e,t=1){let s=`${this.keyPrefix}:metrics:${e}`;return await this.client.incrby(s,t)}async getMetric(e){let t=`${this.keyPrefix}:metrics:${e}`,s=await this.client.get(t);return s?parseInt(s,10):0}async deleteMessage(e){let t=await this.getMessage(e);t&&await this.deleteMessageData(e,t)}async deleteMessageData(e,t){let s=this.client.pipeline();s.del(this.getKey(e)),s.zrem(this.getQueueKey("scheduled"),e),s.zrem(this.getQueueKey("queued"),e),s.zrem(this.getQueueKey("dispatched"),e),s.zrem(this.getQueueKey("expiration"),e),s.zrem(this.getQueueKey("retention"),e);for(let n of u.INDEXED_STATUSES)s.srem(this.getStatusKey(n),e);for(let n of u.INDEXED_STATES)s.srem(this.getStateKey(n),e);t.contactId&&s.srem(this.getContactKey(t.contactId),e),t.descriptorId&&s.srem(this.getDescriptorKey(t.descriptorId),e),await s.exec()}async countMessages(e){if(e.state==="SCHEDULED")return await this.client.zcard(this.getQueueKey("scheduled"));if(e.state==="QUEUED")return await this.client.zcard(this.getQueueKey("queued"));if(e.state==="DISPATCHED")return await this.client.zcard(this.getQueueKey("dispatched"));if(e.status)return await this.client.scard(this.getStatusKey(e.status));if(e.state)try{return await this.client.scard(this.getStateKey(e.state))}catch{return 0}return 0}async getMetrics(e){let t={cumulative:{dispatched:0,delivered:0,failed:0},queues:{queued:0,scheduled:0,dispatched:0},status:{}},s=async a=>{if(e){let o=this.getDescriptorKey(e);return(await this.client.sinter(a,o)).length}return await this.client.scard(a)};for(let a of u.INDEXED_STATUSES){let o=await s(this.getStatusKey(a));t.status[a]=o,a==="DELIVERED"&&(t.cumulative.delivered=o),a==="FAILED"&&(t.cumulative.failed=o)}let n=this.getStateKey("DISPATCHED"),i=await s(n);return t.cumulative.dispatched=i+t.cumulative.delivered+t.cumulative.failed,e?(t.queues.queued=await s(this.getStateKey("QUEUED")),t.queues.scheduled=await s(this.getStateKey("SCHEDULED")),t.queues.dispatched=i):(t.queues.queued=await this.client.zcard(this.getQueueKey("queued")),t.queues.scheduled=await this.client.zcard(this.getQueueKey("scheduled")),t.queues.dispatched=await this.client.zcard(this.getQueueKey("dispatched"))),t}async getDescriptors(){let e=this.getDescriptorKey("*"),t=await this.client.keys(e),s=[];for(let n of t){let i=n.split(":").pop();if(i){let a=await this.client.scard(n);s.push({id:i,count:a})}}return s.sort((n,i)=>i.count-n.count),s}};u.INDEXED_STATUSES=["INIT","PENDING","SENDING","DELIVERED","READ","REPLIED","FAILED","CANCELED"],u.INDEXED_STATES=["INIT","DISPATCHED","SCHEDULED","QUEUED","FINAL"];var D=u;0&&(module.exports={DispatcherRepository});
|
|
2
|
+
//# sourceMappingURL=DispatcherRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/DispatcherRepository.ts","../../src/utils/logger.ts"],"sourcesContent":["import { Message, MessageState, MessageStatus } from '../types/index.js';\nimport { getLogger } from '../utils/logger.js';\nimport IORedis from 'ioredis';\n\nconst logger = getLogger('Repository');\n\nexport class DispatcherRepository {\n private static readonly INDEXED_STATUSES = [\n MessageStatus.INIT,\n MessageStatus.PENDING,\n MessageStatus.SENDING,\n MessageStatus.DELIVERED,\n MessageStatus.READ,\n MessageStatus.REPLIED,\n MessageStatus.FAILED,\n MessageStatus.CANCELED,\n ];\n\n private static readonly INDEXED_STATES = [\n MessageState.INIT,\n MessageState.DISPATCHED,\n MessageState.SCHEDULED,\n MessageState.QUEUED,\n MessageState.FINAL,\n ];\n\n private client: IORedis;\n private keyPrefix: string;\n\n constructor(dispatcherId: string, redisUrl: string) {\n this.client = new IORedis(redisUrl, { maxRetriesPerRequest: null });\n this.keyPrefix = `dwn:dispatcher:${dispatcherId}`;\n\n this.client.on('error', (err) => {\n logger.error('[client] Redis error', err);\n });\n }\n\n async setup(): Promise<void> {\n if (this.client.status === 'ready') {\n logger.debug('[setup] Redis already connected, skipping');\n return;\n }\n // IORedis connects automatically, but we can wait for ready\n if (this.client.status === 'wait') {\n await this.client.connect();\n }\n logger.info('[setup] Repository connected', { status: this.client.status });\n }\n\n async teardown(): Promise<void> {\n if (this.client.status === 'end') {\n return;\n }\n await this.client.quit();\n logger.info('[teardown] Repository disconnected');\n }\n\n public get redis(): IORedis {\n return this.client;\n }\n\n public getKey(messageId: string): string {\n return `${this.keyPrefix}:message:${messageId}`;\n }\n\n public getStateKey(state: MessageState): string {\n return `${this.keyPrefix}:index:state:${state.toLowerCase()}`;\n }\n\n public getStatusKey(status: MessageStatus): string {\n return `${this.keyPrefix}:index:status:${status.toLowerCase()}`;\n }\n\n public getContactKey(contactId: string): string {\n return `${this.keyPrefix}:index:contact:${contactId}`;\n }\n\n public getDescriptorKey(descriptorId: string): string {\n return `${this.keyPrefix}:index:descriptor:${descriptorId}`;\n }\n\n public getQueueKey(\n name: 'scheduled' | 'queued' | 'dispatched' | 'expiration' | 'retention'\n ): string {\n return `${this.keyPrefix}:queue:${name.toLowerCase()}`;\n }\n\n async upsertMessage(message: Message, ttl?: number): Promise<void> {\n const key = this.getKey(message.messageId);\n const data = JSON.stringify(message);\n\n const pipeline = this.client.pipeline();\n\n pipeline.set(key, data);\n\n // --- INDICES (Sets for Querying) ---\n // Prefix: index:contact, index:descriptor, index:status, index:state\n\n // 1. Contact Index\n if (message.contactId) {\n pipeline.sadd(this.getContactKey(message.contactId), message.messageId);\n }\n // 2. Descriptor Index\n if (message.descriptorId) {\n pipeline.sadd(this.getDescriptorKey(message.descriptorId), message.messageId);\n }\n\n // 3. Status Index (ALL statuses are indexed)\n for (const status of DispatcherRepository.INDEXED_STATUSES) {\n const indexKey = this.getStatusKey(status);\n if (message.status === status) {\n pipeline.sadd(indexKey, message.messageId);\n } else {\n pipeline.srem(indexKey, message.messageId);\n }\n }\n\n // 4. State Index (ALL states are indexed)\n for (const state of DispatcherRepository.INDEXED_STATES) {\n const indexKey = this.getStateKey(state);\n if (message.state === state) {\n pipeline.sadd(indexKey, message.messageId);\n } else {\n pipeline.srem(indexKey, message.messageId);\n }\n }\n\n // --- QUEUES (ZSets for Processing) ---\n // Prefix: queue:scheduled, queue:queued, queue:dispatched, queue:retention, queue:expiration\n\n // 0. Retention Queue (Data Cleanup)\n // We ALWAYS enforce retention.\n let retentionTime = Date.now() + (ttl || 3600000 * 24 * 2); // Default to provided TTL or fallbacks (should be provided by Dispatcher)\n\n if (message.state === MessageState.SCHEDULED && message.scheduledTo) {\n // Retention starts after scheduled time\n retentionTime = new Date(message.scheduledTo).getTime() + (ttl || 0);\n }\n pipeline.zadd(this.getQueueKey('retention'), retentionTime, message.messageId);\n\n // 0.5 Expiration Queue (State Timeouts - PENDING/SENDING)\n // If message is in transient state, we might want to track it in queue:expiration for TimeoutMonitor\n // The Dispatcher currently handles TimeoutMonitor by scanning INDEXED PENDING/SENDING.\n // We can keep that logic or move to ZSET.\n // For now, let's strictly follow the plan: queue:retention for cleanup.\n // \"queue:expiration is reserved for state timeouts\" - Implementation of that would be in Dispatcher/StateMachine logic\n // explicitly adding to it, OR we can infer here.\n // Let's stick to existing TimeoutMonitor scanning Indices for now as it works,\n // unless we want to optimize. The user just wanted to separate concerns.\n // I will NOT add implicit queue:expiration logic here to avoid conflict with existing Monitor.\n // But I MUST remove usage of queue:expiration for *retention* purposes if it was there.\n // The previous code used queue:expiration for cleanup. I will rename that to queue:expiration -> queue:retention in effect.\n\n // 1. Scheduled Queue\n if (message.state === MessageState.SCHEDULED && message.scheduledTo) {\n const scheduledTime = new Date(message.scheduledTo).getTime();\n pipeline.zadd(this.getQueueKey('scheduled'), scheduledTime, message.messageId);\n } else {\n pipeline.zrem(this.getQueueKey('scheduled'), message.messageId);\n }\n\n // 2. Queued Queue (FIFO)\n if (message.state === MessageState.QUEUED) {\n const score = new Date(message.createdAt || Date.now()).getTime();\n pipeline.zadd(this.getQueueKey('queued'), score, message.messageId);\n } else {\n pipeline.zrem(this.getQueueKey('queued'), message.messageId);\n }\n\n // 3. Dispatched Queue (LRU/Tracking)\n if (message.state === MessageState.DISPATCHED) {\n const score = new Date(message.createdAt || Date.now()).getTime();\n pipeline.zadd(this.getQueueKey('dispatched'), score, message.messageId);\n } else {\n pipeline.zrem(this.getQueueKey('dispatched'), message.messageId);\n }\n\n await pipeline.exec();\n\n logger.debug('[upsertMessage]', {\n messageId: message.messageId,\n status: message.status,\n state: message.state,\n });\n }\n\n async getMessage(messageId: string): Promise<Message | null> {\n const key = this.getKey(messageId);\n const data = await this.client.get(key);\n\n if (!data) {\n return null;\n }\n\n return JSON.parse(data) as Message;\n }\n\n async getMessages(filter: {\n status?: MessageStatus;\n state?: MessageState;\n size?: number;\n skip?: number;\n }): Promise<Message[]> {\n let messageIds: string[] = [];\n\n // Note: DispatcherQuery is now the preferred way to query with complex filters.\n // This method is kept for backward compatibility and simple state/queue polling.\n\n if (filter.state === MessageState.SCHEDULED) {\n const now = Date.now();\n const skip = filter.skip ?? 0;\n const size = filter.size ?? 0;\n\n // Use the QUEUE key for scheduled checking\n // IORedis: zrangebyscore(key, min, max, 'LIMIT', offset, count)\n if (size > 0) {\n messageIds = await this.client.zrangebyscore(\n this.getQueueKey('scheduled'),\n 0,\n now,\n 'LIMIT',\n skip,\n size\n );\n } else {\n messageIds = await this.client.zrangebyscore(this.getQueueKey('scheduled'), 0, now);\n }\n } else if (filter.state === MessageState.QUEUED) {\n // Use the QUEUE key for FIFO processing\n messageIds = await this.client.zrange(\n this.getQueueKey('queued'),\n filter.skip ?? 0,\n (filter.skip ?? 0) + (filter.size ? filter.size - 1 : -1)\n );\n } else if (filter.state === MessageState.DISPATCHED) {\n // Use the QUEUE key for Tracking\n messageIds = await this.client.zrange(\n this.getQueueKey('dispatched'),\n filter.skip ?? 0,\n (filter.skip ?? 0) + (filter.size ? filter.size - 1 : -1)\n );\n } else if (filter.status) {\n // Use the INDEX key for status\n const allIds = await this.client.smembers(this.getStatusKey(filter.status));\n const skip = filter.skip ?? 0;\n const size = filter.size;\n messageIds = size ? allIds.slice(skip, skip + size) : allIds.slice(skip);\n } else if (filter.state) {\n // Use the INDEX key for generic state querying\n try {\n const allIds = await this.client.smembers(this.getStateKey(filter.state));\n const skip = filter.skip ?? 0;\n const size = filter.size;\n messageIds = size ? allIds.slice(skip, skip + size) : allIds.slice(skip);\n } catch (error) {\n return [];\n }\n } else {\n logger.warn('[getMessages] no filter provided');\n return [];\n }\n\n const messages: Message[] = [];\n for (const messageId of messageIds) {\n const message = await this.getMessage(messageId);\n if (message) {\n if (filter.status && message.status !== filter.status) {\n continue;\n }\n if (filter.state && message.state !== filter.state) {\n continue;\n }\n messages.push(message);\n }\n }\n\n logger.debug('[getMessages]', { count: messages.length, filter });\n return messages;\n }\n\n async getQueueSize(): Promise<number> {\n return await this.client.zcard(this.getQueueKey('dispatched'));\n }\n\n async evictOldest(count: number): Promise<number> {\n if (count <= 0) return 0;\n\n // Evict from DISPATCHED ZSet (Oldest first -> min score)\n // IORedis: zpopmin(key, count)\n const popped = await this.client.zpopmin(this.getQueueKey('dispatched'), count);\n // popped is [value1, score1, value2, score2, ...]\n\n let evicted = 0;\n for (let i = 0; i < popped.length; i += 2) {\n const messageId = popped[i];\n await this.deleteMessage(messageId);\n evicted++;\n }\n\n return evicted;\n }\n\n async getExpiredMessages(count: number = 50): Promise<string[]> {\n const now = Date.now();\n return await this.client.zrangebyscore(\n this.getQueueKey('expiration'),\n 0,\n now,\n 'LIMIT',\n 0,\n count\n );\n }\n\n async getRetentionMessages(count: number = 50): Promise<string[]> {\n const now = Date.now();\n return await this.client.zrangebyscore(\n this.getQueueKey('retention'),\n 0,\n now,\n 'LIMIT',\n 0,\n count\n );\n }\n\n async incrementMetric(key: string, value: number = 1): Promise<number> {\n const metricKey = `${this.keyPrefix}:metrics:${key}`;\n return await this.client.incrby(metricKey, value);\n }\n\n async getMetric(key: string): Promise<number> {\n const metricKey = `${this.keyPrefix}:metrics:${key}`;\n const value = await this.client.get(metricKey);\n return value ? parseInt(value, 10) : 0;\n }\n\n async deleteMessage(messageId: string): Promise<void> {\n const msg = await this.getMessage(messageId);\n if (!msg) return;\n await this.deleteMessageData(messageId, msg);\n }\n\n private async deleteMessageData(messageId: string, message: Message): Promise<void> {\n const pipeline = this.client.pipeline();\n pipeline.del(this.getKey(messageId));\n\n // Remove from Queues\n pipeline.zrem(this.getQueueKey('scheduled'), messageId);\n pipeline.zrem(this.getQueueKey('queued'), messageId);\n pipeline.zrem(this.getQueueKey('dispatched'), messageId);\n pipeline.zrem(this.getQueueKey('expiration'), messageId);\n pipeline.zrem(this.getQueueKey('retention'), messageId);\n\n // Remove from Indices\n for (const status of DispatcherRepository.INDEXED_STATUSES) {\n pipeline.srem(this.getStatusKey(status), messageId);\n }\n\n for (const state of DispatcherRepository.INDEXED_STATES) {\n pipeline.srem(this.getStateKey(state), messageId);\n }\n\n if (message.contactId) {\n pipeline.srem(this.getContactKey(message.contactId), messageId);\n }\n\n if (message.descriptorId) {\n pipeline.srem(this.getDescriptorKey(message.descriptorId), messageId);\n }\n\n await pipeline.exec();\n }\n\n async countMessages(filter: { status?: MessageStatus; state?: MessageState }): Promise<number> {\n if (filter.state === MessageState.SCHEDULED) {\n return await this.client.zcard(this.getQueueKey('scheduled'));\n }\n\n if (filter.state === MessageState.QUEUED) {\n return await this.client.zcard(this.getQueueKey('queued'));\n }\n\n if (filter.state === MessageState.DISPATCHED) {\n return await this.client.zcard(this.getQueueKey('dispatched'));\n }\n\n if (filter.status) {\n return await this.client.scard(this.getStatusKey(filter.status));\n }\n\n if (filter.state) {\n try {\n return await this.client.scard(this.getStateKey(filter.state));\n } catch (error) {\n return 0;\n }\n }\n\n return 0;\n }\n\n async getMetrics(descriptorId?: string): Promise<any> {\n const metrics: any = {\n cumulative: { dispatched: 0, delivered: 0, failed: 0 },\n queues: { queued: 0, scheduled: 0, dispatched: 0 },\n status: {},\n };\n\n // Helper to get count\n const getCount = async (setKey: string) => {\n if (descriptorId) {\n const descriptorKey = this.getDescriptorKey(descriptorId);\n const intersection = await this.client.sinter(setKey, descriptorKey);\n return intersection.length;\n }\n return await this.client.scard(setKey);\n };\n\n // Status Counts\n for (const status of DispatcherRepository.INDEXED_STATUSES) {\n const count = await getCount(this.getStatusKey(status));\n metrics.status[status] = count;\n\n if (status === MessageStatus.DELIVERED) metrics.cumulative.delivered = count;\n if (status === MessageStatus.FAILED) metrics.cumulative.failed = count;\n }\n\n // Dispatched Total (approximate)\n const dispatchedKey = this.getStateKey(MessageState.DISPATCHED);\n const dispatchedCount = await getCount(dispatchedKey);\n metrics.cumulative.dispatched =\n dispatchedCount + metrics.cumulative.delivered + metrics.cumulative.failed;\n\n // Queues\n if (descriptorId) {\n // Filtered queues via indices (approximate intersection using state sets)\n metrics.queues.queued = await getCount(this.getStateKey(MessageState.QUEUED));\n metrics.queues.scheduled = await getCount(this.getStateKey(MessageState.SCHEDULED));\n metrics.queues.dispatched = dispatchedCount;\n } else {\n // Direct queue counts\n metrics.queues.queued = await this.client.zcard(this.getQueueKey('queued'));\n metrics.queues.scheduled = await this.client.zcard(this.getQueueKey('scheduled'));\n metrics.queues.dispatched = await this.client.zcard(this.getQueueKey('dispatched'));\n }\n\n return metrics;\n }\n\n async getDescriptors(): Promise<{ id: string; count: number }[]> {\n const pattern = this.getDescriptorKey('*');\n const keys = await this.client.keys(pattern);\n\n const descriptors = [];\n for (const key of keys) {\n const id = key.split(':').pop();\n if (id) {\n const count = await this.client.scard(key);\n descriptors.push({ id, count });\n }\n }\n\n descriptors.sort((a, b) => b.count - a.count);\n return descriptors;\n }\n}\n","/**\n * Logger utility using the 'debug' package.\n *\n * This module provides a configurable logger based on the 'debug' package.\n * By default, all logging is disabled. To enable logging, set the DEBUG\n * environment variable.\n *\n * The DEBUG variable can be a single namespace or a comma-separated list of\n * namespaces. Wildcards are supported.\n *\n * For example:\n * - `DEBUG=blip-api` enables all logs for the 'blip-api' scope.\n * - `DEBUG=blip-api:*` enables all sub-scopes under 'blip-api'.\n * - `DEBUG=*` enables all logs.\n *\n * The logger exposes different levels (debug, info, warn, error), which are\n * different namespaces.\n *\n * Example usage:\n * ```\n * import { getLogger } from './logger';\n *\n * const logger = getLogger('my-feature');\n *\n * logger.info('This is an info message');\n * logger.error('This is an error');\n * ```\n *\n * To see the output, run your application with:\n * `DEBUG=my-feature:* node your-app.js`\n */\n\nimport debug from 'debug';\n\n// Define the available log levels\nexport const LogLevels = {\n debug: 'debug',\n info: 'info',\n warn: 'warn',\n error: 'error',\n};\n\nexport type LogLevel = keyof typeof LogLevels;\n\ntype LogFunction = (...args: any[]) => void;\n\nexport interface Logger {\n debug: LogFunction;\n info: LogFunction;\n warn: LogFunction;\n error: LogFunction;\n}\n\nconst loggers = new Map<string, Logger>();\n\nfunction serializeArg(arg: any): any {\n if (arg === null || arg === undefined) return arg;\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg, null, 2);\n } catch (e) {\n return arg;\n }\n }\n return arg;\n}\n\nfunction createLogFunction(debugInstance: debug.Debugger): LogFunction {\n return (...args: any[]) => {\n const serialized = args.map(serializeArg);\n (debugInstance as any)(...serialized);\n };\n}\n\n/**\n * Creates a logger with a specific scope.\n *\n * @param scope - The scope for the logger (e.g., 'blip-api', 'dispatcher').\n * @returns A logger object with methods for each log level.\n */\nexport function getLogger(scope: string): Logger {\n if (!loggers.has(scope)) {\n const debugInstance = debug(`${scope}:${LogLevels.debug}`);\n const infoInstance = debug(`${scope}:${LogLevels.info}`);\n const warnInstance = debug(`${scope}:${LogLevels.warn}`);\n const errorInstance = debug(`${scope}:${LogLevels.error}`);\n\n errorInstance.log = console.error.bind(console);\n\n const logger: Logger = {\n debug: createLogFunction(debugInstance),\n info: createLogFunction(infoInstance),\n warn: createLogFunction(warnInstance),\n error: createLogFunction(errorInstance),\n };\n\n loggers.set(scope, logger);\n }\n return loggers.get(scope)!;\n}\n\n/**\n * Enables logging for a specific scope and level.\n * This is a convenience function to programmatically enable logging,\n * equivalent to setting the DEBUG environment variable.\n *\n * @param scope - The scope to enable (e.g., 'blip-api').\n * @param level - The minimum log level to enable (e.g., 'info').\n */\nexport function enableLogger(namespaces: string): void {\n const currentDebug = debug.disable();\n debug.enable(`${currentDebug},${namespaces}`);\n}\n\n/**\n * Disables all logging.\n */\nexport function disableLogger(): void {\n debug.disable();\n}\n\n/**\n * Get all registered logger scopes.\n *\n * @returns An array of all registered scopes.\n */\nexport function getAllScopes(): string[] {\n return Array.from(loggers.keys());\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,IAAA,eAAAC,EAAAH,GCgCA,IAAAI,EAAkB,oBAGLC,EAAY,CACvB,MAAO,QACP,KAAM,OACN,KAAM,OACN,MAAO,OACT,EAaMC,EAAU,IAAI,IAEpB,SAASC,EAAaC,EAAe,CACnC,GAAIA,GAAQ,KAA2B,OAAOA,EAC9C,GAAI,OAAOA,GAAQ,SACjB,GAAI,CACF,OAAO,KAAK,UAAUA,EAAK,KAAM,CAAC,CACpC,MAAY,CACV,OAAOA,CACT,CAEF,OAAOA,CACT,CAEA,SAASC,EAAkBC,EAA4C,CACrE,MAAO,IAAIC,IAAgB,CACzB,IAAMC,EAAaD,EAAK,IAAIJ,CAAY,EACvCG,EAAsB,GAAGE,CAAU,CACtC,CACF,CAQO,SAASC,EAAUC,EAAuB,CAC/C,GAAI,CAACR,EAAQ,IAAIQ,CAAK,EAAG,CACvB,IAAMJ,KAAgB,EAAAK,SAAM,GAAGD,CAAK,IAAIT,EAAU,KAAK,EAAE,EACnDW,KAAe,EAAAD,SAAM,GAAGD,CAAK,IAAIT,EAAU,IAAI,EAAE,EACjDY,KAAe,EAAAF,SAAM,GAAGD,CAAK,IAAIT,EAAU,IAAI,EAAE,EACjDa,KAAgB,EAAAH,SAAM,GAAGD,CAAK,IAAIT,EAAU,KAAK,EAAE,EAEzDa,EAAc,IAAM,QAAQ,MAAM,KAAK,OAAO,EAE9C,IAAMC,EAAiB,CACrB,MAAOV,EAAkBC,CAAa,EACtC,KAAMD,EAAkBO,CAAY,EACpC,KAAMP,EAAkBQ,CAAY,EACpC,MAAOR,EAAkBS,CAAa,CACxC,EAEAZ,EAAQ,IAAIQ,EAA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d,CAAG,EACzC6B,EAAY,KAAK,CAAE,GAAAC,EAAI,MAAAhB,CAAM,CAAC,CAChC,CACF,CAEA,OAAAe,EAAY,KAAK,CAACE,EAAGC,IAAMA,EAAE,MAAQD,EAAE,KAAK,EACrCF,CACT,CACF,EA7ca1C,EACa,iBAAmB,4EAS3C,EAVWA,EAYa,eAAiB,iDAMzC,EAlBK,IAAM8C,EAAN9C","names":["DispatcherRepository_exports","__export","DispatcherRepository","__toCommonJS","import_debug","LogLevels","loggers","serializeArg","arg","createLogFunction","debugInstance","args","serialized","getLogger","scope","debug","infoInstance","warnInstance","errorInstance","logger","import_ioredis","logger","getLogger","_DispatcherRepository","dispatcherId","redisUrl","IORedis","err","messageId","state","status","contactId","descriptorId","name","message","ttl","key","data","pipeline","indexKey","retentionTime","scheduledTime","score","filter","messageIds","now","skip","size","allIds","messages","count","popped","evicted","i","value","metricKey","msg","metrics","getCount","setKey","descriptorKey","dispatchedKey","dispatchedCount","pattern","keys","descriptors","id","a","b","DispatcherRepository"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CallbackEvent, Message, MessageState, MessageStatus } from '../types/index.mjs';
|
|
2
|
+
import { DispatcherRepository } from './DispatcherRepository.mjs';
|
|
3
|
+
import '../types/blip.mjs';
|
|
4
|
+
import 'ioredis';
|
|
5
|
+
|
|
6
|
+
type StateTransitionCallback = (event: CallbackEvent, message: Message) => void;
|
|
7
|
+
declare class DispatcherStateMachine {
|
|
8
|
+
private id;
|
|
9
|
+
private repository;
|
|
10
|
+
private emit;
|
|
11
|
+
constructor(id: string, repository: DispatcherRepository, emit: StateTransitionCallback);
|
|
12
|
+
/**
|
|
13
|
+
* Transition message to a new state/status.
|
|
14
|
+
* Validates transition, updates timestamps, persists to Redis, and emits events.
|
|
15
|
+
*/
|
|
16
|
+
transition(message: Message, targetState: MessageState, targetStatus: MessageStatus, data?: Partial<Message>): Promise<Message>;
|
|
17
|
+
private emitStatusEvent;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { DispatcherStateMachine, type StateTransitionCallback };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var I=Object.create;var d=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty;var y=(t,e)=>{for(var n in e)d(t,n,{get:e[n],enumerable:!0})},l=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of A(e))!m.call(t,i)&&i!==n&&d(t,i,{get:()=>e[i],enumerable:!(r=f(e,i))||r.enumerable});return t};var N=(t,e,n)=>(n=t!=null?I(L(t)):{},l(e||!t||!t.__esModule?d(n,"default",{value:t,enumerable:!0}):n,t)),v=t=>l(d({},"__esModule",{value:!0}),t);var C={};y(C,{DispatcherStateMachine:()=>g});module.exports=v(C);var c=N(require("debug")),p={debug:"debug",info:"info",warn:"warn",error:"error"},E=new Map;function x(t){if(t==null)return t;if(typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return t}return t}function u(t){return(...e)=>{let n=e.map(x);t(...n)}}function D(t){if(!E.has(t)){let e=(0,c.default)(`${t}:${p.debug}`),n=(0,c.default)(`${t}:${p.info}`),r=(0,c.default)(`${t}:${p.warn}`),i=(0,c.default)(`${t}:${p.error}`);i.log=console.error.bind(console);let s={debug:u(e),info:u(n),warn:u(r),error:u(i)};E.set(t,s)}return E.get(t)}var b=D("StateMachine"),g=class{constructor(e,n,r){this.id=e;this.repository=n;this.emit=r}async transition(e,n,r,i){let s=e.state,a=e.status;s==="FINAL"&&n!=="FINAL"&&b.warn(`[transition] Attempting to move from FINAL back to ${n}`,{messageId:e.messageId}),e.state=n,e.status=r,i&&Object.assign(e,i);let o=new Date().toISOString();return r==="SENDING"&&!e.acceptedAt&&a!=="SENDING"&&(e.acceptedAt=o),r==="DELIVERED"&&!e.deliveredAt&&(e.deliveredAt=o),r==="READ"&&!e.readAt&&(e.readAt=o),r==="REPLIED"&&!e.repliedAt&&(e.repliedAt=o,e.readAt||(e.readAt=o)),r==="FAILED"&&!e.failedAt&&(e.failedAt=o),n==="DISPATCHED"&&!e.sentAt&&"PENDING",await this.repository.upsertMessage(e),a!==r&&(r==="REPLIED"&&a!=="READ"&&this.emit("read",e),this.emitStatusEvent(e,r)),n==="SCHEDULED"&&s!=="SCHEDULED"&&this.emit("scheduled",e),b.debug(`[transition] ${e.messageId} : ${s}/${a} -> ${n}/${r}`),e}emitStatusEvent(e,n){switch(n){case"SENDING":this.emit("sending",e);break;case"DELIVERED":this.emit("delivered",e);break;case"READ":this.emit("read",e);break;case"REPLIED":this.emit("replied",e);break;case"FAILED":this.emit("failed",e);break;case"CANCELED":this.emit("canceled",e);break}}};0&&(module.exports={DispatcherStateMachine});
|
|
2
|
+
//# sourceMappingURL=DispatcherStateMachine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/DispatcherStateMachine.ts","../../src/utils/logger.ts"],"sourcesContent":["import { Message, MessageState, MessageStatus, CallbackEvent } from '../types/index.js';\nimport { DispatcherRepository } from './DispatcherRepository.js';\nimport { getLogger } from '../utils/logger.js';\n\nconst logger = getLogger('StateMachine');\n\nexport type StateTransitionCallback = (event: CallbackEvent, message: Message) => void;\n\nexport class DispatcherStateMachine {\n constructor(\n private id: string,\n private repository: DispatcherRepository,\n private emit: StateTransitionCallback\n ) {}\n\n /**\n * Transition message to a new state/status.\n * Validates transition, updates timestamps, persists to Redis, and emits events.\n */\n async transition(\n message: Message,\n targetState: MessageState,\n targetStatus: MessageStatus,\n data?: Partial<Message> // Additional data to merge (e.g. error, timestamps)\n ): Promise<Message> {\n const fromState = message.state;\n const fromStatus = message.status;\n\n // 1. Validation (Optional: Strict Transition Rules)\n // For now, we allow most transitions but can add guards here.\n if (fromState === MessageState.FINAL && targetState !== MessageState.FINAL) {\n logger.warn(`[transition] Attempting to move from FINAL back to ${targetState}`, {\n messageId: message.messageId,\n });\n // We could throw or ignore. For safety, let's log and proceed for now, or block.\n // Usually FINAL is terminal.\n }\n\n // 2. Update Message Object\n message.state = targetState;\n message.status = targetStatus;\n\n if (data) {\n Object.assign(message, data);\n }\n\n // 3. Update Timestamps based on Status/State\n const now = new Date().toISOString();\n\n // Status-based timestamps\n if (\n targetStatus === MessageStatus.SENDING &&\n !message.acceptedAt &&\n fromStatus !== MessageStatus.SENDING\n ) {\n message.acceptedAt = now;\n }\n if (targetStatus === MessageStatus.DELIVERED && !message.deliveredAt) {\n message.deliveredAt = now;\n }\n if (targetStatus === MessageStatus.READ && !message.readAt) {\n message.readAt = now;\n }\n if (targetStatus === MessageStatus.REPLIED && !message.repliedAt) {\n message.repliedAt = now;\n // Implicit Read for Reply\n if (!message.readAt) message.readAt = now;\n }\n if (targetStatus === MessageStatus.FAILED && !message.failedAt) {\n message.failedAt = now;\n }\n\n // State-based timestamps\n if (\n targetState === MessageState.DISPATCHED &&\n !message.sentAt &&\n targetStatus === MessageStatus.PENDING\n ) {\n // Dispatcher sets dispatched state before sending to API (PENDING)\n // Dispatcher sets sentAt AFTER successful API call.\n // This logic might need to be flexible or handled by caller providing 'sentAt' in `data`.\n }\n\n // 4. Persistence\n // We rely on Repository to handle queues based on state/status\n await this.repository.upsertMessage(message);\n\n // 5. Emit Events based on Transition\n // Detect Status Changes\n if (fromStatus !== targetStatus) {\n // Implicit Read on Reply\n if (targetStatus === MessageStatus.REPLIED && fromStatus !== MessageStatus.READ) {\n this.emit('read', message);\n }\n this.emitStatusEvent(message, targetStatus);\n }\n\n // Detect State Changes (specific ones)\n if (targetState === MessageState.SCHEDULED && fromState !== MessageState.SCHEDULED) {\n this.emit('scheduled', message);\n }\n // Retry is usually a specific flow/event, handled by caller or explicit call?\n // Dispatcher calls transition -> SCHEDULED (retry).\n\n logger.debug(\n `[transition] ${message.messageId} : ${fromState}/${fromStatus} -> ${targetState}/${targetStatus}`\n );\n\n return message;\n }\n\n private emitStatusEvent(message: Message, status: MessageStatus) {\n switch (status) {\n case MessageStatus.SENDING:\n this.emit('sending', message);\n break;\n case MessageStatus.DELIVERED:\n this.emit('delivered', message);\n break;\n case MessageStatus.READ:\n this.emit('read', message);\n break;\n case MessageStatus.REPLIED:\n this.emit('replied', message);\n break;\n case MessageStatus.FAILED:\n this.emit('failed', message);\n break;\n case MessageStatus.CANCELED:\n this.emit('canceled', message);\n break;\n }\n }\n}\n","/**\n * Logger utility using the 'debug' package.\n *\n * This module provides a configurable logger based on the 'debug' package.\n * By default, all logging is disabled. To enable logging, set the DEBUG\n * environment variable.\n *\n * The DEBUG variable can be a single namespace or a comma-separated list of\n * namespaces. Wildcards are supported.\n *\n * For example:\n * - `DEBUG=blip-api` enables all logs for the 'blip-api' scope.\n * - `DEBUG=blip-api:*` enables all sub-scopes under 'blip-api'.\n * - `DEBUG=*` enables all logs.\n *\n * The logger exposes different levels (debug, info, warn, error), which are\n * different namespaces.\n *\n * Example usage:\n * ```\n * import { getLogger } from './logger';\n *\n * const logger = getLogger('my-feature');\n *\n * logger.info('This is an info message');\n * logger.error('This is an error');\n * ```\n *\n * To see the output, run your application with:\n * `DEBUG=my-feature:* node your-app.js`\n */\n\nimport debug from 'debug';\n\n// Define the available log levels\nexport const LogLevels = {\n debug: 'debug',\n info: 'info',\n warn: 'warn',\n error: 'error',\n};\n\nexport type LogLevel = keyof typeof LogLevels;\n\ntype LogFunction = (...args: any[]) => void;\n\nexport interface Logger {\n debug: LogFunction;\n info: LogFunction;\n warn: LogFunction;\n error: LogFunction;\n}\n\nconst loggers = new Map<string, Logger>();\n\nfunction serializeArg(arg: any): any {\n if (arg === null || arg === undefined) return arg;\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg, null, 2);\n } catch (e) {\n return arg;\n }\n }\n return arg;\n}\n\nfunction createLogFunction(debugInstance: debug.Debugger): LogFunction {\n return (...args: any[]) => {\n const serialized = args.map(serializeArg);\n (debugInstance as any)(...serialized);\n };\n}\n\n/**\n * Creates a logger with a specific scope.\n *\n * @param scope - The scope for the logger (e.g., 'blip-api', 'dispatcher').\n * @returns A logger object with methods for each log level.\n */\nexport function getLogger(scope: string): Logger {\n if (!loggers.has(scope)) {\n const debugInstance = debug(`${scope}:${LogLevels.debug}`);\n const infoInstance = debug(`${scope}:${LogLevels.info}`);\n const warnInstance = debug(`${scope}:${LogLevels.warn}`);\n const errorInstance = debug(`${scope}:${LogLevels.error}`);\n\n errorInstance.log = console.error.bind(console);\n\n const logger: Logger = {\n debug: createLogFunction(debugInstance),\n info: createLogFunction(infoInstance),\n warn: createLogFunction(warnInstance),\n error: createLogFunction(errorInstance),\n };\n\n loggers.set(scope, logger);\n }\n return loggers.get(scope)!;\n}\n\n/**\n * Enables logging for a specific scope and level.\n * This is a convenience function to programmatically enable logging,\n * equivalent to setting the DEBUG environment variable.\n *\n * @param scope - The scope to enable (e.g., 'blip-api').\n * @param level - The minimum log level to enable (e.g., 'info').\n */\nexport function enableLogger(namespaces: string): void {\n const currentDebug = debug.disable();\n debug.enable(`${currentDebug},${namespaces}`);\n}\n\n/**\n * Disables all logging.\n */\nexport function disableLogger(): void {\n debug.disable();\n}\n\n/**\n * Get all registered logger scopes.\n *\n * @returns An array of all registered scopes.\n */\nexport function getAllScopes(): string[] {\n return Array.from(loggers.keys());\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,4BAAAE,IAAA,eAAAC,EAAAH,GCgCA,IAAAI,EAAkB,oBAGLC,EAAY,CACvB,MAAO,QACP,KAAM,OACN,KAAM,OACN,MAAO,OACT,EAaMC,EAAU,IAAI,IAEpB,SAASC,EAAaC,EAAe,CACnC,GAAIA,GAAQ,KAA2B,OAAOA,EAC9C,GAAI,OAAOA,GAAQ,SACjB,GAAI,CACF,OAAO,KAAK,UAAUA,EAAK,KAAM,CAAC,CACpC,MAAY,CACV,OAAOA,CACT,CAEF,OAAOA,CACT,CAEA,SAASC,EA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e,YAEfL,EAAQ,WAAaM,GAEnBJ,IAAiB,aAA2B,CAACF,EAAQ,cACvDA,EAAQ,YAAcM,GAEpBJ,IAAiB,QAAsB,CAACF,EAAQ,SAClDA,EAAQ,OAASM,GAEfJ,IAAiB,WAAyB,CAACF,EAAQ,YACrDA,EAAQ,UAAYM,EAEfN,EAAQ,SAAQA,EAAQ,OAASM,IAEpCJ,IAAiB,UAAwB,CAACF,EAAQ,WACpDA,EAAQ,SAAWM,GAKnBL,IAAgB,cAChB,CAACD,EAAQ,QACQ,UASnB,MAAM,KAAK,WAAW,cAAcA,CAAO,EAIvCK,IAAeH,IAEbA,IAAiB,WAAyBG,IAAe,QAC3D,KAAK,KAAK,OAAQL,CAAO,EAE3B,KAAK,gBAAgBA,EAASE,CAAY,GAIxCD,IAAgB,aAA0BG,IAAc,aAC1D,KAAK,KAAK,YAAaJ,CAAO,EAKhCN,EAAO,MACL,gBAAgBM,EAAQ,SAAS,MAAMI,CAAS,IAAIC,CAAU,OAAOJ,CAAW,IAAIC,CAAY,EAClG,EAEOF,CACT,CAEQ,gBAAgBA,EAAkBO,EAAuB,CAC/D,OAAQA,EAAQ,CACd,cACE,KAAK,KAAK,UAAWP,CAAO,EAC5B,MACF,gBACE,KAAK,KAAK,YAAaA,CAAO,EAC9B,MACF,WACE,KAAK,KAAK,OAAQA,CAAO,EACzB,MACF,cACE,KAAK,KAAK,UAAWA,CAAO,EAC5B,MACF,aACE,KAAK,KAAK,SAAUA,CAAO,EAC3B,MACF,eACE,KAAK,KAAK,WAAYA,CAAO,EAC7B,KACJ,CACF,CACF","names":["DispatcherStateMachine_exports","__export","DispatcherStateMachine","__toCommonJS","import_debug","LogLevels","loggers","serializeArg","arg","createLogFunction","debugInstance","args","serialized","getLogger","scope","debug","infoInstance","warnInstance","errorInstance","logger","logger","getLogger","DispatcherStateMachine","id","repository","emit","message","targetState","targetStatus","data","fromState","fromStatus","now","status"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error classes for the dispatcher system
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Base error class for all dispatcher errors
|
|
6
|
+
*/
|
|
7
|
+
declare class DispatcherError extends Error {
|
|
8
|
+
details?: any | undefined;
|
|
9
|
+
constructor(message: string, details?: any | undefined);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Permanent errors - do not retry
|
|
13
|
+
*/
|
|
14
|
+
declare class PermanentError extends DispatcherError {
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Error when a message is already in progress for a contact + template
|
|
18
|
+
*/
|
|
19
|
+
declare class MessageInProgressError extends PermanentError {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Error for invalid configuration
|
|
23
|
+
*/
|
|
24
|
+
declare class InvalidConfigurationError extends PermanentError {
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Error when no valid shift is found
|
|
28
|
+
*/
|
|
29
|
+
declare class NoValidShiftError extends PermanentError {
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Retryable errors - trigger retry logic
|
|
33
|
+
*/
|
|
34
|
+
declare class RetryableError extends DispatcherError {
|
|
35
|
+
cause?: Error | undefined;
|
|
36
|
+
retryOptions?: {
|
|
37
|
+
backoffMultiplier?: number;
|
|
38
|
+
} | undefined;
|
|
39
|
+
constructor(message: string, cause?: Error | undefined, retryOptions?: {
|
|
40
|
+
backoffMultiplier?: number;
|
|
41
|
+
} | undefined);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Service errors - circuit breaker eligible
|
|
45
|
+
*/
|
|
46
|
+
declare class ServiceUnavailableError extends DispatcherError {
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Error for configuration issues
|
|
50
|
+
*/
|
|
51
|
+
declare class ConfigurationError extends PermanentError {
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export { ConfigurationError, DispatcherError, InvalidConfigurationError, MessageInProgressError, NoValidShiftError, PermanentError, RetryableError, ServiceUnavailableError };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var l=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var r=(s,t)=>{for(var e in t)l(s,e,{get:t[e],enumerable:!0})},T=(s,t,e,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of k(t))!m.call(s,c)&&c!==e&&l(s,c,{get:()=>t[c],enumerable:!(u=i(t,c))||u.enumerable});return s};var j=s=>T(l({},"__esModule",{value:!0}),s);var q={};r(q,{ConfigurationError:()=>h,DispatcherError:()=>p,InvalidConfigurationError:()=>d,MessageInProgressError:()=>n,NoValidShiftError:()=>o,PermanentError:()=>x,RetryableError:()=>a,ServiceUnavailableError:()=>b});module.exports=j(q);var p=class extends Error{constructor(e,u){super(e);this.details=u;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},x=class extends p{},n=class extends x{},d=class extends x{},o=class extends x{},a=class extends p{constructor(e,u,c){super(e,{cause:u,retryOptions:c});this.cause=u;this.retryOptions=c}},b=class extends p{},h=class extends x{};0&&(module.exports={ConfigurationError,DispatcherError,InvalidConfigurationError,MessageInProgressError,NoValidShiftError,PermanentError,RetryableError,ServiceUnavailableError});
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/index.ts"],"sourcesContent":["/**\n * Error classes for the dispatcher system\n */\n\n/**\n * Base error class for all dispatcher errors\n */\nexport class DispatcherError extends Error {\n constructor(\n message: string,\n public details?: any\n ) {\n super(message);\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Permanent errors - do not retry\n */\nexport class PermanentError extends DispatcherError {}\n\n/**\n * Error when a message is already in progress for a contact + template\n */\nexport class MessageInProgressError extends PermanentError {}\n\n/**\n * Error for invalid configuration\n */\nexport class InvalidConfigurationError extends PermanentError {}\n\n/**\n * Error when no valid shift is found\n */\nexport class NoValidShiftError extends PermanentError {}\n\n/**\n * Retryable errors - trigger retry logic\n */\nexport class RetryableError extends DispatcherError {\n constructor(\n message: string,\n public cause?: Error,\n public retryOptions?: { backoffMultiplier?: number }\n ) {\n super(message, { cause, retryOptions });\n }\n}\n\n/**\n * Service errors - circuit breaker eligible\n */\nexport class ServiceUnavailableError extends DispatcherError {}\n\n/**\n * Error for configuration issues\n */\nexport class ConfigurationError extends PermanentError {}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,oBAAAC,EAAA,8BAAAC,EAAA,2BAAAC,EAAA,sBAAAC,EAAA,mBAAAC,EAAA,mBAAAC,EAAA,4BAAAC,IAAA,eAAAC,EAAAV,GAOO,IAAMG,EAAN,cAA8B,KAAM,CACzC,YACEQ,EACOC,EACP,CACA,MAAMD,CAAO,EAFN,aAAAC,EAGP,KAAK,KAAO,KAAK,YAAY,KAC7B,MAAM,kBAAkB,KAAM,KAAK,WAAW,CAChD,CACF,EAKaL,EAAN,cAA6BJ,CAAgB,CAAC,EAKxCE,EAAN,cAAqCE,CAAe,CAAC,EAK/CH,EAAN,cAAwCG,CAAe,CAAC,EAKlDD,EAAN,cAAgCC,CAAe,CAAC,EAK1CC,EAAN,cAA6BL,CAAgB,CAClD,YACEQ,EACOE,EACAC,EACP,CACA,MAAMH,EAAS,CAAE,MAAAE,EAAO,aAAAC,CAAa,CAAC,EAH/B,WAAAD,EACA,kBAAAC,CAGT,CACF,EAKaL,EAAN,cAAsCN,CAAgB,CAAC,EAKjDD,EAAN,cAAiCK,CAAe,CAAC","names":["errors_exports","__export","ConfigurationError","DispatcherError","InvalidConfigurationError","MessageInProgressError","NoValidShiftError","PermanentError","RetryableError","ServiceUnavailableError","__toCommonJS","message","details","cause","retryOptions"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class extends Error{constructor(c,x){super(c);this.details=x;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},t=class extends e{},p=class extends t{},u=class extends t{},l=class extends t{},n=class extends e{constructor(c,x,b){super(c,{cause:x,retryOptions:b});this.cause=x;this.retryOptions=b}},d=class extends e{},o=class extends t{};export{o as ConfigurationError,e as DispatcherError,u as InvalidConfigurationError,p as MessageInProgressError,l as NoValidShiftError,t as PermanentError,n as RetryableError,d as ServiceUnavailableError};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/index.ts"],"sourcesContent":["/**\n * Error classes for the dispatcher system\n */\n\n/**\n * Base error class for all dispatcher errors\n */\nexport class DispatcherError extends Error {\n constructor(\n message: string,\n public details?: any\n ) {\n super(message);\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Permanent errors - do not retry\n */\nexport class PermanentError extends DispatcherError {}\n\n/**\n * Error when a message is already in progress for a contact + template\n */\nexport class MessageInProgressError extends PermanentError {}\n\n/**\n * Error for invalid configuration\n */\nexport class InvalidConfigurationError extends PermanentError {}\n\n/**\n * Error when no valid shift is found\n */\nexport class NoValidShiftError extends PermanentError {}\n\n/**\n * Retryable errors - trigger retry logic\n */\nexport class RetryableError extends DispatcherError {\n constructor(\n message: string,\n public cause?: Error,\n public retryOptions?: { backoffMultiplier?: number }\n ) {\n super(message, { cause, retryOptions });\n }\n}\n\n/**\n * Service errors - circuit breaker eligible\n */\nexport class ServiceUnavailableError extends DispatcherError {}\n\n/**\n * Error for configuration issues\n */\nexport class ConfigurationError extends PermanentError {}\n"],"mappings":"AAOO,IAAMA,EAAN,cAA8B,KAAM,CACzC,YACEC,EACOC,EACP,CACA,MAAMD,CAAO,EAFN,aAAAC,EAGP,KAAK,KAAO,KAAK,YAAY,KAC7B,MAAM,kBAAkB,KAAM,KAAK,WAAW,CAChD,CACF,EAKaC,EAAN,cAA6BH,CAAgB,CAAC,EAKxCI,EAAN,cAAqCD,CAAe,CAAC,EAK/CE,EAAN,cAAwCF,CAAe,CAAC,EAKlDG,EAAN,cAAgCH,CAAe,CAAC,EAK1CI,EAAN,cAA6BP,CAAgB,CAClD,YACEC,EACOO,EACAC,EACP,CACA,MAAMR,EAAS,CAAE,MAAAO,EAAO,aAAAC,CAAa,CAAC,EAH/B,WAAAD,EACA,kBAAAC,CAGT,CACF,EAKaC,EAAN,cAAsCV,CAAgB,CAAC,EAKjDW,EAAN,cAAiCR,CAAe,CAAC","names":["DispatcherError","message","details","PermanentError","MessageInProgressError","InvalidConfigurationError","NoValidShiftError","RetryableError","cause","retryOptions","ServiceUnavailableError","ConfigurationError"]}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { CallbackMap, DispatcherDescriptor, DispatcherDescriptorOptions } from './core/DispatcherDescriptor.mjs';
|
|
2
|
+
export { Dispatcher } from './core/Dispatcher.mjs';
|
|
3
|
+
export { Blip, BlipError } from './core/Blip.mjs';
|
|
4
|
+
export { DispatcherMonitor, MonitorAlert, MonitorOptions, MonitorRule } from './core/DispatcherMonitor.mjs';
|
|
5
|
+
export { DispatcherRepository } from './core/DispatcherRepository.mjs';
|
|
6
|
+
export { enableLogger, getLogger } from './utils/logger.mjs';
|
|
7
|
+
export { CallbackEvent, ConnectionConfig, Contact, DispatchMessageOptions, DispatchState, DispatcherMetrics, DispatcherOptions, Intent, Message, MessageData, MessageDispatcherOptions, MessageOptions, MessagePayload, MessageState, MessageStatus, QueryFilter, Shift, Weekdays } from './types/index.mjs';
|
|
8
|
+
export { BlipConfig, DateInterval, PartiallyOptional, PartiallyRequiredStrict, Vnd } from './types/blip.mjs';
|
|
9
|
+
import './core/DispatcherQuery.mjs';
|
|
10
|
+
import 'events';
|
|
11
|
+
import 'ioredis';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var W=Object.create;var x=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var it=(c,t)=>{for(var e in t)x(c,e,{get:t[e],enumerable:!0})},V=(c,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tt(t))!st.call(c,i)&&i!==e&&x(c,i,{get:()=>t[i],enumerable:!(s=Z(t,i))||s.enumerable});return c};var Q=(c,t,e)=>(e=c!=null?W(et(c)):{},V(t||!c||!c.__esModule?x(e,"default",{value:c,enumerable:!0}):e,c)),rt=c=>V(x({},"__esModule",{value:!0}),c);var ot={};it(ot,{Blip:()=>T,BlipError:()=>E,DispatchState:()=>R,Dispatcher:()=>K,DispatcherDescriptor:()=>C,DispatcherMonitor:()=>$,DispatcherRepository:()=>z,MessageState:()=>v,MessageStatus:()=>w,Vnd:()=>f,Weekdays:()=>G,enableLogger:()=>J,getLogger:()=>g});module.exports=rt(ot);var C=class{constructor(t,e,s){this.callbacks={};this.id=t,this.transformFn=e,this.contactIdTransform=s?.toContactId||(i=>i),this.options=s}transform(t){return this.transformFn(t)}toContactId(t){return this.contactIdTransform(t)}get messageOptions(){return this.options}on(t,e){let s=this.options?.finalStatus||"DELIVERED";if(t==="read"&&s!=="READ"&&s!=="REPLIED")throw new Error(`Cannot listen to 'read' event when finalStatus is '${s}'. Set finalStatus to 'READ' or 'REPLIED'.`);if(t==="replied"&&s!=="REPLIED")throw new Error(`Cannot listen to 'replied' event when finalStatus is '${s}'. Set finalStatus to 'REPLIED'.`);return this.callbacks[t]=e,this}emit(t,e,s,i){this.callbacks[t]?.(e,s,i)}};var X=require("uuid"),q=require("bullmq");var v=(r=>(r.INIT="INIT",r.DISPATCHED="DISPATCHED",r.SCHEDULED="SCHEDULED",r.QUEUED="QUEUED",r.FINAL="FINAL",r))(v||{}),w=(o=>(o.INIT="INIT",o.PENDING="PENDING",o.SENDING="SENDING",o.DELIVERED="DELIVERED",o.READ="READ",o.REPLIED="REPLIED",o.FAILED="FAILED",o.CANCELED="CANCELED",o))(w||{}),R=(r=>(r.ACCEPTED="accepted",r.DISPATCHED="dispatched",r.RECEIVED="received",r.CONSUMED="consumed",r.FAILED="failed",r))(R||{}),G=(n=>(n[n.MONDAY=1]="MONDAY",n[n.TUESDAY=2]="TUESDAY",n[n.WEDNESDAY=4]="WEDNESDAY",n[n.THURSDAY=8]="THURSDAY",n[n.FRIDAY=16]="FRIDAY",n[n.SATURDAY=32]="SATURDAY",n[n.SUNDAY=64]="SUNDAY",n))(G||{});var S=Q(require("debug")),P={debug:"debug",info:"info",warn:"warn",error:"error"},H=new Map;function nt(c){if(c==null)return c;if(typeof c=="object")try{return JSON.stringify(c,null,2)}catch{return c}return c}function L(c){return(...t)=>{let e=t.map(nt);c(...e)}}function g(c){if(!H.has(c)){let t=(0,S.default)(`${c}:${P.debug}`),e=(0,S.default)(`${c}:${P.info}`),s=(0,S.default)(`${c}:${P.warn}`),i=(0,S.default)(`${c}:${P.error}`);i.log=console.error.bind(console);let r={debug:L(t),info:L(e),warn:L(s),error:L(i)};H.set(c,r)}return H.get(c)}function J(c){let t=S.default.disable();S.default.enable(`${t},${c}`)}var j=g("StateMachine"),k=class{constructor(t,e,s){this.id=t;this.repository=e;this.emit=s}async transition(t,e,s,i){let r=t.state,a=t.status;r==="FINAL"&&e!=="FINAL"&&j.warn(`[transition] Attempting to move from FINAL back to ${e}`,{messageId:t.messageId}),t.state=e,t.status=s,i&&Object.assign(t,i);let n=new Date().toISOString();return s==="SENDING"&&!t.acceptedAt&&a!=="SENDING"&&(t.acceptedAt=n),s==="DELIVERED"&&!t.deliveredAt&&(t.deliveredAt=n),s==="READ"&&!t.readAt&&(t.readAt=n),s==="REPLIED"&&!t.repliedAt&&(t.repliedAt=n,t.readAt||(t.readAt=n)),s==="FAILED"&&!t.failedAt&&(t.failedAt=n),e==="DISPATCHED"&&!t.sentAt&&"PENDING",await this.repository.upsertMessage(t),a!==s&&(s==="REPLIED"&&a!=="READ"&&this.emit("read",t),this.emitStatusEvent(t,s)),e==="SCHEDULED"&&r!=="SCHEDULED"&&this.emit("scheduled",t),j.debug(`[transition] ${t.messageId} : ${r}/${a} -> ${e}/${s}`),t}emitStatusEvent(t,e){switch(e){case"SENDING":this.emit("sending",t);break;case"DELIVERED":this.emit("delivered",t);break;case"READ":this.emit("read",t);break;case"REPLIED":this.emit("replied",t);break;case"FAILED":this.emit("failed",t);break;case"CANCELED":this.emit("canceled",t);break}}};var B=Q(require("axios")),N=require("uuid");var f;(t=>{let c;(i=>{let e;(u=>(u.GET="get",u.SET="set",u.DELETE="delete",u.OBSERVE="observe",u.SUBSCRIBE="subscribe",u.MERGE="merge"))(e=i.Method||(i.Method={}));let s;(n=>(n.SUCCESS="success",n.FAILURE="failure"))(s=i.Status||(i.Status={}))})(c=t.Lime||(t.Lime={}))})(f||(f={}));var l=g("Blip"),T=class{constructor(t,e,s=3e4){let i=`https://${t}.http.msging.net`;this.client=B.default.create({baseURL:i,timeout:s,headers:{"Content-Type":"application/json",Authorization:e}}),this.client.interceptors.response.use(r=>r,r=>{if(r.response){let a=r.response.data?.reason||{code:r.response.status,description:r.response.statusText||"Unknown error"};throw new E(a.description,a.code)}else throw r.request?new E("No response from server",0):new E(r.message,0)})}async postCommand(t){let e={...t,id:t.id||(0,N.v4)()};l.debug("[postCommand] payload",e);let i=(await this.client.post("/commands",e)).data;if(i.status!==f.Lime.Status.SUCCESS)throw l.error("[postCommand] failed",{method:e.method,uri:e.uri,status:i.status,reason:i.reason}),new E(i.reason?.description||"Command failed",i.reason?.code||0);return l.debug("[postCommand] succeeded",e.uri),i}async postMessage(t){let e={...t,id:t.id||(0,N.v4)()};return l.info("[postMessage] payload",e),(await this.client.post("/messages",e)).data}async mergeContact(t,e){l.info("[mergeContact] called with",{contactId:t,data:e});let s={...e,identity:t},i={method:f.Lime.Method.MERGE,uri:"/contacts",type:"application/vnd.lime.contact+json",resource:s};await this.postCommand(i)}async sendMessage(t,e,s){l.info("[sendMessage] called with",{contactId:t,message:e,id:s});let i=s||(0,N.v4)(),r={id:i,to:t,type:e.type,content:e.content};return await this.postMessage(r),l.info("[sendMessage] sent",{contactId:t,messageId:i}),i}async getDispatchState(t,e){l.info("[getDispatchState] called with",{messageId:t,contactId:e});let s={method:f.Lime.Method.GET,uri:`/notifications?id=${t}`,to:"postmaster@msging.net"};try{let i=await this.postCommand(s);if(!i.resource||!i.resource.items||i.resource.items.length===0)return l.debug("[getDispatchState] no notifications found",{messageId:t,contactId:e}),null;let r={failed:4,consumed:3,received:2,accepted:1,dispatched:0},a=null,n=-1;for(let o of i.resource.items){let p=o.event,d=r[p]??-1;d>n&&(n=d,a=p)}return l.info("[getDispatchState] state retrieved",{messageId:t,contactId:e,state:a,notificationsCount:i.resource.items.length}),a}catch(i){if(i instanceof E&&i.code===67)return l.debug("[getDispatchState] resource not found",{messageId:t,contactId:e}),null;throw l.error("[getDispatchState] failed",{messageId:t,contactId:e,error:i}),i}}async getMessageAfter(t,e){l.info("[getMessageAfter] called with",{contactId:t,messageId:e});let s=e,i=0,r=10;for(;i<r;){let a={method:f.Lime.Method.GET,uri:`/threads/${t}?$skip=0&$take=1&$order=asc&messageId=${s}`,to:"postmaster@msging.net"};try{let n=await this.postCommand(a);if(!n.resource||!n.resource.items||n.resource.items.length===0)return l.debug("[getMessageAfter] no message found after",{contactId:t,messageId:s}),null;let o=n.resource.items[0];if(o.direction==="received")return l.info("[getMessageAfter] found received message",{contactId:t,messageId:s,nextMessageId:o.id}),o;l.debug("[getMessageAfter] skipping sent message",{contactId:t,messageId:o.id}),s=o.id,i++}catch(n){if(n instanceof E&&n.code===67)return l.debug("[getMessageAfter] resource not found",{contactId:t,messageId:s}),null;throw l.error("[getMessageAfter] failed",{contactId:t,messageId:s,error:n}),n}}return l.warn("[getMessageAfter] max traversal attempts reached",{contactId:t,startMessageId:e}),null}async sendEvent(t,e,s,i){l.info("[sendEvent] called with",{contactId:t,category:e,action:s,extras:i});let r={to:"postmaster@analytics.msging.net",method:f.Lime.Method.SET,type:"application/vnd.iris.eventTrack+json",uri:"/event-track",resource:{category:e,action:s,contact:{identity:t},extras:i}};await this.postCommand(r)}async setState(t,e,s="onboarding"){l.info("[setState] called with",{contactId:t,botId:e,stateId:s});let i={uri:`/flow-id?shortName=${e}`,to:"postmaster@builder.msging.net",method:f.Lime.Method.GET},r=await this.postCommand(i);if(!r.resource)throw l.error("[setState] flow ID not found",{botId:e}),new E(`Flow ID not found for bot: ${e}`,404);let a=r.resource,n={method:f.Lime.Method.SET,uri:`/contexts/${t}/stateid@${a}`,resource:s,type:"text/plain"};await this.postCommand(n);let o={method:f.Lime.Method.SET,uri:`/contexts/${t}/master-state`,resource:`${e}@msging.net`,type:"text/plain"};await this.postCommand(o)}},E=class c extends Error{constructor(t,e){super(t),this.name="BlipError",this.code=e,Object.setPrototypeOf(this,c.prototype)}};var at=g("DispatcherQuery"),O=class{constructor(t){this.repository=t}get client(){return this.repository.redis}async query(t){let e=[],s=this.repository.keyPrefix;if(t.contactId&&e.push(this.repository.getContactKey(t.contactId)),t.descriptorId&&e.push(this.repository.getDescriptorKey(t.descriptorId)),t.status){let d=Array.isArray(t.status)?t.status:[t.status];d.length===1?e.push(this.repository.getStatusKey(d[0])):d.length>1&&e.push(this.repository.getStatusKey(d[0]))}if(t.state){let d=Array.isArray(t.state)?t.state:[t.state];d.length===1&&e.push(this.repository.getStateKey(d[0]))}let i=[];if(e.length>0)i=await this.client.sinter(e);else{let d=Object.values(w).map(u=>this.repository.getStatusKey(u));i=await this.client.sunion(d)}let r=t.skip??0,a=t.size??50,n=i.slice(r,r+a),o=[],p=[];for(let d of n){let u=await this.repository.getMessage(d);if(u){if(t.status&&!(Array.isArray(t.status)?t.status:[t.status]).includes(u.status)||t.state&&!(Array.isArray(t.state)?t.state:[t.state]).includes(u.state))continue;o.push(u)}else p.push(d)}return p.length>0&&this.cleanupIndices(p,t),o}async cleanupIndices(t,e){let s=this.client.pipeline(),i=this.repository.keyPrefix;e.contactId&&s.srem(this.repository.getContactKey(e.contactId),t),e.descriptorId&&s.srem(this.repository.getDescriptorKey(e.descriptorId),t),e.status&&(Array.isArray(e.status)?e.status:[e.status]).forEach(a=>{s.srem(this.repository.getStatusKey(a),t)}),e.state&&(Array.isArray(e.state)?e.state:[e.state]).forEach(a=>{s.srem(this.repository.getStateKey(a),t)}),await s.exec(),at.debug("[cleanupIndices] Removed expired IDs from checked indices",{count:t.length})}};var h=g("Dispatcher"),K=class{constructor(t,e,s,i){this.callbacks={};this.descriptors=new Map;this.isRunning=!1;this.setupCompleted=!1;this.id=t,this.repository=e,this.redis=this.repository.redis,this.stateMachine=new k(this.id,this.repository,(r,a)=>{this.emit(r,a),this.descriptors.get(a.descriptorId)?.emit(r,a,this.api,this.id)}),this.api=new T(s.contract,s.key),this.queueName=`dispatcher-${this.id}`,this.maxRetries=i?.maxRetries??0,this.retryIntervals=i?.retryIntervals??[1*1e3,5*1e3,15*1e3],this.timeouts={pending:i?.timeouts?.pending??120*1e3,sending:i?.timeouts?.sending??120*1e3},this.retention=i?.retention??2880*60*1e3,this.pollingIntervals={scheduled:i?.pollingIntervals?.scheduled??30*1e3,pending:i?.pollingIntervals?.pending??10*1e3,sending:i?.pollingIntervals?.sending??10*1e3,delivered:i?.pollingIntervals?.delivered??1800*1e3,read:i?.pollingIntervals?.read??1800*1e3,queue:i?.pollingIntervals?.queue??1*1e3},this.timeoutTimer=null,this.query=new O(this.repository),this.queue=new q.Queue(this.queueName,{connection:this.redis,defaultJobOptions:{removeOnComplete:!0,removeOnFail:!0}}),this.worker=new q.Worker(this.queueName,async r=>{try{await this.processJob(r)}catch(a){throw h.error(`[Worker] Job ${r.name} failed`,a),a}},{connection:this.redis,concurrency:i?.batchSize||50,limiter:i?.rateLimits?.global?{max:i.rateLimits.global.points,duration:i.rateLimits.global.duration*1e3}:void 0}),this.worker.on("error",r=>h.error("[Worker] Error",r)),this.worker.on("failed",(r,a)=>h.error(`[Worker] Job ${r?.id} failed`,a))}async setup(){this.setupCompleted||(await this.repository.setup(),await this.queue.waitUntilReady(),this.isRunning=!0,this.setupCompleted=!0,this.startTimeoutMonitor(),h.info("[setup] Dispatcher started (BullMQ)",{queue:this.queueName}))}async teardown(){this.isRunning=!1,this.timeoutTimer&&(clearInterval(this.timeoutTimer),this.timeoutTimer=null),await this.queue.close(),await this.worker.close(),await this.repository.teardown(),h.info("[teardown] Dispatcher stopped")}on(t,e){return this.callbacks[t]=e,this}async getMetrics(){let t={total:0,byState:{},byStatus:{},cumulative:{dispatched:await this.repository.getMetric("dispatched"),delivered:await this.repository.getMetric("delivered"),failed:await this.repository.getMetric("failed")}},e=Object.values(v);for(let i of e)t.byState[i]=await this.repository.countMessages({state:i});let s=Object.values(w);for(let i of s)t.byStatus[i]=await this.repository.countMessages({status:i});return t.total=Object.values(t.byState).reduce((i,r)=>i+(r||0),0),t}emit(t,e){this.callbacks[t]?.(e,this.api,this.id)}async send(t,e,s,i){this.descriptors.set(t.id,t);let r=t.toContactId(e),a=t.transform(s),n=new Date().toISOString(),o={messageId:(0,X.v4)(),contactId:r,descriptorId:t.id,payload:a,status:"INIT",state:"INIT",createdAt:n,attempts:0,retries:this.maxRetries},d={...t.messageOptions,...i},{schedule:u,...D}=d;o.options=D,this.emit("dispatch",o),t.emit("dispatch",o,this.api,this.id);let m=this.calculateScheduledTime(u,d.shifts),y=0;if(m){o.scheduledTo=m,o.state="SCHEDULED";let I=new Date(m).getTime();y=Math.max(0,I-Date.now()),this.emit("scheduled",o),t.emit("scheduled",o,this.api,this.id),h.info("[send] message scheduled",{messageId:o.messageId,scheduledTo:m,delay:y})}else o.state="QUEUED",o.status="INIT",h.info("[send] message queued",{messageId:o.messageId});return o.expiresAt=new Date(Date.now()+(o.state==="SCHEDULED"?y+this.retention:this.retention)).toISOString(),await this.stateMachine.transition(o,o.state,o.status),await this.queue.add("send",{messageId:o.messageId},{jobId:o.messageId,delay:y,priority:1}),o}async cancel(t){let e=await this.repository.getMessage(t);if(!e)return h.warn("[cancel] message not found",{messageId:t}),!1;if(e.state==="FINAL")return h.warn("[cancel] message already final",{messageId:t,status:e.status}),!1;let s=await this.queue.getJob(t);return s&&(await s.remove(),h.info("[cancel] removed job from queue",{messageId:t})),await this.stateMachine.transition(e,"FINAL","CANCELED"),h.info("[cancel] message canceled",{messageId:t}),!0}async processJob(t){let{messageId:e}=t.data,s=await this.repository.getMessage(e);if(!s){h.warn(`[processJob] Message not found: ${e}`);return}let i=this.descriptors.get(s.descriptorId)||null;switch(t.name){case"send":await this.handleSendJob(s,i);break;case"check":await this.handleCheckJob(s,i);break;default:h.warn(`[processJob] Unknown job name: ${t.name}`)}}async handleSendJob(t,e){t.lastDispatchAttemptAt=new Date().toISOString(),await this.stateMachine.transition(t,"DISPATCHED","PENDING");try{await this.api.sendMessage(t.contactId,t.payload,t.messageId),await this.handlePostSendOperations(t,t.options),t.sentAt=new Date().toISOString(),await this.stateMachine.transition(t,"DISPATCHED","PENDING"),h.info("[handleSendJob] Message sent to API",{messageId:t.messageId}),await this.repository.incrementMetric("dispatched"),await this.queue.add("check",{messageId:t.messageId},{delay:this.pollingIntervals.pending,priority:5})}catch(s){let i=s instanceof Error?s:new Error(String(s));await this.handleDispatchFailure(t,e,i)}}async handlePostSendOperations(t,e={}){let s={...e.contact||{}};if(e.intent)if(typeof e.intent=="string")s.intent=e.intent;else{s.intent=e.intent.intent;let{intent:i,...r}=e.intent;Object.entries(r).forEach(([a,n])=>{n!=null&&(s[a]=typeof n=="object"?JSON.stringify(n):String(n))})}Object.keys(s).length>0&&await this.api.mergeContact(t.contactId,s),e.state&&await this.api.setState(t.contactId,e.state.botId,e.state.stateId)}async handleCheckJob(t,e){if(t.state!=="FINAL"){if(this.checkAndHandleTimeout(t)){await this.handleTimeout(t,e);return}try{let s=await this.api.getDispatchState(t.messageId,t.contactId);if(!s){await this.rescheduleCheck(t,this.pollingIntervals.pending);return}let i=this.pollingIntervals.pending,r=!1;switch(s){case"accepted":t.status!=="SENDING"&&(await this.stateMachine.transition(t,t.state,"SENDING"),r=!0),i=this.pollingIntervals.sending;break;case"received":case"consumed":if(await this.api.getMessageAfter(t.contactId,t.messageId)){let p="REPLIED";t.status!==p&&t.status!=="READ"&&(await this.repository.incrementMetric("delivered"),await this.stateMachine.transition(t,"FINAL","REPLIED"),r=!0);break}let n=s==="consumed"?"READ":"DELIVERED";t.status!==n&&(await this.repository.incrementMetric("delivered"),await this.stateMachine.transition(t,t.state,n),r=!0);let o=t.options?.finalStatus||"DELIVERED";this.getStatusRank(t.status)>=this.getStatusRank(o)?(await this.stateMachine.transition(t,"FINAL",t.status),r=!0):i=this.pollingIntervals.delivered;break;case"failed":await this.handleDispatchFailure(t,e,new Error("Dispatch failed from Gateway"));return}t.state!=="FINAL"&&await this.rescheduleCheck(t,i)}catch(s){h.error("[handleCheckJob] Error",s),await this.rescheduleCheck(t,this.pollingIntervals.pending)}}}checkAndHandleTimeout(t){let e=new Date;if(t.status==="PENDING"){let s=t.lastDispatchAttemptAt||t.sentAt||t.createdAt;if(e.getTime()-new Date(s).getTime()>this.timeouts.pending)return!0}return!!(t.status==="SENDING"&&t.acceptedAt&&e.getTime()-new Date(t.acceptedAt).getTime()>this.timeouts.sending)}async handleTimeout(t,e){await this.stateMachine.transition(t,"FINAL","FAILED",{error:"Timeout Exceeded"}),h.info("[handleTimeout] Message timed out",{messageId:t.messageId})}startTimeoutMonitor(){this.timeoutTimer||(this.timeoutTimer=setInterval(async()=>{try{let t=await this.repository.getMessages({status:"PENDING"}),e=await this.repository.getMessages({status:"SENDING"}),s=[...t,...e];for(let r of s)if(this.checkAndHandleTimeout(r)){let a=this.descriptors.get(r.descriptorId)||null;await this.handleTimeout(r,a)}let i=await this.repository.getRetentionMessages(100);if(i.length>0){h.debug("[CleanupMonitor] Cleaning up expired messages",{count:i.length});for(let r of i)await this.repository.deleteMessage(r)}}catch(t){h.error("[TimeoutMonitor] Error during scan",t)}},10*1e3))}async rescheduleCheck(t,e){await this.queue.add("check",{messageId:t.messageId},{delay:e,priority:5})}async handleDispatchFailure(t,e,s){if(t.attempts=(t.attempts??0)+1,t.error=s.message,h.error("[handleDispatchFailure]",{messageId:t.messageId,attempts:t.attempts,maxRetries:this.maxRetries,error:s.message}),t.attempts<=this.maxRetries){t.retries=this.maxRetries-t.attempts;let i=this.retryIntervals[t.attempts-1]||this.retryIntervals[this.retryIntervals.length-1];await this.stateMachine.transition(t,"SCHEDULED",t.status),this.emit("retry",t),e?.emit("retry",t,this.api,this.id),await this.queue.add("send",{messageId:t.messageId},{delay:i,priority:1}),h.info("[handleDispatchFailure] Rescheduled retry",{messageId:t.messageId,retryDelay:i})}else t.retries=0,await this.stateMachine.transition(t,"FINAL","FAILED"),await this.repository.incrementMetric("failed")}calculateScheduledTime(t,e){if(t)return t;if(!e||e.length===0)return;let s=new Date;return this.isWithinShifts(s,e)?void 0:this.findNextShiftTime(s,e)?.toISOString()}isWithinShifts(t,e){let s=t.getDay(),i=s===0?64:Math.pow(2,s-1);for(let r of e){if((r.days&i)===0)continue;let a=r.gmt||"-3",n=parseInt(a,10),o=new Date(t.getTime()-n*60*60*1e3),p=o.getHours()*60+o.getMinutes(),[d,u]=r.start.split(":").map(Number),[D,m]=r.end.split(":").map(Number),y=d*60+u,I=D*60+m;if(p>=y&&p<I)return!0}return!1}findNextShiftTime(t,e){for(let i=0;i<=7;i++){let r=new Date(t);r.setDate(r.getDate()+i);let a=r.getDay(),n=a===0?64:Math.pow(2,a-1),o=e.filter(p=>(p.days&n)!==0);if(o.length!==0){o.sort((p,d)=>{let[u,D]=p.start.split(":").map(Number),[m,y]=d.start.split(":").map(Number);return u*60+D-(m*60+y)});for(let p of o){let d=p.gmt||"-3",u=parseInt(d,10),[D,m]=p.start.split(":").map(Number),y=new Date(r);y.setHours(D,m,0,0);let I=new Date(y.getTime()+u*60*60*1e3);if(i===0){if(I>t)return I}else return I}}}}getStatusRank(t){return{INIT:0,PENDING:1,SENDING:2,DELIVERED:3,READ:4,REPLIED:5,FAILED:6,CANCELED:6}[t]||0}};var Y=require("events"),F=require("bullmq");var M=g("DispatcherMonitor"),$=class extends Y.EventEmitter{constructor(e,s,i){super();this.history=[];this.lastAlerts={};this.activeAlerts=new Set;this.isRunning=!1;this.id=e,this.repository=s,this.options={interval:6e4,historySize:1e3,...i},this.queueName=`monitor-${this.id}`,this.queue=new F.Queue(this.queueName,{connection:s.redis,defaultJobOptions:{removeOnComplete:!0,removeOnFail:!0}}),this.worker=new F.Worker(this.queueName,async r=>{r.name==="check"&&await this.check()},{connection:s.redis}),this.worker.on("error",r=>M.error("[MonitorWorker] Error",r)),this.worker.on("failed",(r,a)=>M.error(`[MonitorWorker] Job ${r?.id} failed`,a))}async start(){this.isRunning||(M.info("[Monitor] Started"),await this.queue.obliterate({force:!0}),await this.queue.add("check",{},{repeat:{every:this.options.interval,immediately:!0}}),this.isRunning=!0)}async stop(){this.isRunning=!1,await this.queue.close(),await this.worker.close(),M.info("[Monitor] Stopped")}async collectMetrics(){let e=this.repository,s={total:0,byState:{},byStatus:{},cumulative:{dispatched:0,delivered:0,failed:0}},r=Object.values(v).map(async d=>{s.byState[d]=await e.countMessages({state:d})}),n=Object.values(w).map(async d=>{s.byStatus[d]=await e.countMessages({status:d})}),p=["dispatched","delivered","failed"].map(async d=>{s.cumulative[d]=await e.getMetric(d)});return await Promise.all([...r,...n,...p]),s.total=Object.values(s.byState).reduce((d,u)=>d+(u||0),0),s}async check(){try{let e=await this.collectMetrics(),s=Date.now();this.history.push({timestamp:s,metrics:e}),this.cleanHistory();for(let i of this.options.rules)await this.evaluateRule(i,e,s)}catch(e){M.error("[Monitor] Error during check",e)}}cleanHistory(){let e=this.options.historySize;this.history.length>e&&(this.history=this.history.slice(this.history.length-e));let s=Math.max(...this.options.rules.map(r=>r.window||0)),i=Date.now()-s-6e4;if(this.history.length>0&&this.history[0].timestamp<i){let r=this.history.findIndex(a=>a.timestamp>=i);r>0&&(this.history=this.history.slice(r))}}async evaluateRule(e,s,i){let r=`${e.type}`,a=!1,n=0,o={};switch(e.type){case"queue_size":let p=s.byState.FINAL||0;n=s.total-p,a=n>e.threshold,o={current:n,threshold:e.threshold};break;case"failure_rate":if(!e.window){M.warn("[Monitor] failure_rate rule missing window");return}let d=this.findSnapshotAt(i-e.window);if(!d)return;let u=s.cumulative.failed,D=d.metrics.cumulative.failed,m=u-D,y=s.cumulative.dispatched,I=d.metrics.cumulative.dispatched,U=y-I;U===0?n=0:n=m/U,a=n>e.threshold,o={rate:(n*100).toFixed(2)+"%",threshold:(e.threshold*100).toFixed(2)+"%",failed:m,dispatched:U,window:e.window};break}a?this.activeAlerts.has(r)?e.debounce&&!this.isDebounced(r,e.debounce)&&this.emitAlert(r,e,n,o):(this.emitAlert(r,e,n,o),this.activeAlerts.add(r)):this.activeAlerts.has(r)&&(this.resolveAlert(r,e),this.activeAlerts.delete(r))}isDebounced(e,s){if(!s)return!1;let i=this.lastAlerts[e];return i?Date.now()-i<s:!1}emitAlert(e,s,i,r){M.warn(`[Monitor] Alert triggered: ${s.type}`,r),this.lastAlerts[e]=Date.now();let a={type:s.type,message:`${s.type} exceeded threshold`,level:"warning",details:r,timestamp:new Date().toISOString()};this.emit("alert",a)}resolveAlert(e,s){M.info(`[Monitor] Alert resolved: ${s.type}`);let i={type:s.type,message:`${s.type} resolved`,level:"warning",details:{},timestamp:new Date().toISOString()};this.emit("resolved",i)}findSnapshotAt(e){if(this.history.length===0)return null;for(let s of this.history)if(s.timestamp>=e)return s;return this.history[0]}};var _=Q(require("ioredis")),A=g("Repository"),b=class b{constructor(t,e){this.client=new _.default(e,{maxRetriesPerRequest:null}),this.keyPrefix=`dwn:dispatcher:${t}`,this.client.on("error",s=>{A.error("[client] Redis error",s)})}async setup(){if(this.client.status==="ready"){A.debug("[setup] Redis already connected, skipping");return}this.client.status==="wait"&&await this.client.connect(),A.info("[setup] Repository connected",{status:this.client.status})}async teardown(){this.client.status!=="end"&&(await this.client.quit(),A.info("[teardown] Repository disconnected"))}get redis(){return this.client}getKey(t){return`${this.keyPrefix}:message:${t}`}getStateKey(t){return`${this.keyPrefix}:index:state:${t.toLowerCase()}`}getStatusKey(t){return`${this.keyPrefix}:index:status:${t.toLowerCase()}`}getContactKey(t){return`${this.keyPrefix}:index:contact:${t}`}getDescriptorKey(t){return`${this.keyPrefix}:index:descriptor:${t}`}getQueueKey(t){return`${this.keyPrefix}:queue:${t.toLowerCase()}`}async upsertMessage(t,e){let s=this.getKey(t.messageId),i=JSON.stringify(t),r=this.client.pipeline();r.set(s,i),t.contactId&&r.sadd(this.getContactKey(t.contactId),t.messageId),t.descriptorId&&r.sadd(this.getDescriptorKey(t.descriptorId),t.messageId);for(let n of b.INDEXED_STATUSES){let o=this.getStatusKey(n);t.status===n?r.sadd(o,t.messageId):r.srem(o,t.messageId)}for(let n of b.INDEXED_STATES){let o=this.getStateKey(n);t.state===n?r.sadd(o,t.messageId):r.srem(o,t.messageId)}let a=Date.now()+(e||36e5*24*2);if(t.state==="SCHEDULED"&&t.scheduledTo&&(a=new Date(t.scheduledTo).getTime()+(e||0)),r.zadd(this.getQueueKey("retention"),a,t.messageId),t.state==="SCHEDULED"&&t.scheduledTo){let n=new Date(t.scheduledTo).getTime();r.zadd(this.getQueueKey("scheduled"),n,t.messageId)}else r.zrem(this.getQueueKey("scheduled"),t.messageId);if(t.state==="QUEUED"){let n=new Date(t.createdAt||Date.now()).getTime();r.zadd(this.getQueueKey("queued"),n,t.messageId)}else r.zrem(this.getQueueKey("queued"),t.messageId);if(t.state==="DISPATCHED"){let n=new Date(t.createdAt||Date.now()).getTime();r.zadd(this.getQueueKey("dispatched"),n,t.messageId)}else r.zrem(this.getQueueKey("dispatched"),t.messageId);await r.exec(),A.debug("[upsertMessage]",{messageId:t.messageId,status:t.status,state:t.state})}async getMessage(t){let e=this.getKey(t),s=await this.client.get(e);return s?JSON.parse(s):null}async getMessages(t){let e=[];if(t.state==="SCHEDULED"){let i=Date.now(),r=t.skip??0,a=t.size??0;a>0?e=await this.client.zrangebyscore(this.getQueueKey("scheduled"),0,i,"LIMIT",r,a):e=await this.client.zrangebyscore(this.getQueueKey("scheduled"),0,i)}else if(t.state==="QUEUED")e=await this.client.zrange(this.getQueueKey("queued"),t.skip??0,(t.skip??0)+(t.size?t.size-1:-1));else if(t.state==="DISPATCHED")e=await this.client.zrange(this.getQueueKey("dispatched"),t.skip??0,(t.skip??0)+(t.size?t.size-1:-1));else if(t.status){let i=await this.client.smembers(this.getStatusKey(t.status)),r=t.skip??0,a=t.size;e=a?i.slice(r,r+a):i.slice(r)}else if(t.state)try{let i=await this.client.smembers(this.getStateKey(t.state)),r=t.skip??0,a=t.size;e=a?i.slice(r,r+a):i.slice(r)}catch{return[]}else return A.warn("[getMessages] no filter provided"),[];let s=[];for(let i of e){let r=await this.getMessage(i);if(r){if(t.status&&r.status!==t.status||t.state&&r.state!==t.state)continue;s.push(r)}}return A.debug("[getMessages]",{count:s.length,filter:t}),s}async getQueueSize(){return await this.client.zcard(this.getQueueKey("dispatched"))}async evictOldest(t){if(t<=0)return 0;let e=await this.client.zpopmin(this.getQueueKey("dispatched"),t),s=0;for(let i=0;i<e.length;i+=2){let r=e[i];await this.deleteMessage(r),s++}return s}async getExpiredMessages(t=50){let e=Date.now();return await this.client.zrangebyscore(this.getQueueKey("expiration"),0,e,"LIMIT",0,t)}async getRetentionMessages(t=50){let e=Date.now();return await this.client.zrangebyscore(this.getQueueKey("retention"),0,e,"LIMIT",0,t)}async incrementMetric(t,e=1){let s=`${this.keyPrefix}:metrics:${t}`;return await this.client.incrby(s,e)}async getMetric(t){let e=`${this.keyPrefix}:metrics:${t}`,s=await this.client.get(e);return s?parseInt(s,10):0}async deleteMessage(t){let e=await this.getMessage(t);e&&await this.deleteMessageData(t,e)}async deleteMessageData(t,e){let s=this.client.pipeline();s.del(this.getKey(t)),s.zrem(this.getQueueKey("scheduled"),t),s.zrem(this.getQueueKey("queued"),t),s.zrem(this.getQueueKey("dispatched"),t),s.zrem(this.getQueueKey("expiration"),t),s.zrem(this.getQueueKey("retention"),t);for(let i of b.INDEXED_STATUSES)s.srem(this.getStatusKey(i),t);for(let i of b.INDEXED_STATES)s.srem(this.getStateKey(i),t);e.contactId&&s.srem(this.getContactKey(e.contactId),t),e.descriptorId&&s.srem(this.getDescriptorKey(e.descriptorId),t),await s.exec()}async countMessages(t){if(t.state==="SCHEDULED")return await this.client.zcard(this.getQueueKey("scheduled"));if(t.state==="QUEUED")return await this.client.zcard(this.getQueueKey("queued"));if(t.state==="DISPATCHED")return await this.client.zcard(this.getQueueKey("dispatched"));if(t.status)return await this.client.scard(this.getStatusKey(t.status));if(t.state)try{return await this.client.scard(this.getStateKey(t.state))}catch{return 0}return 0}async getMetrics(t){let e={cumulative:{dispatched:0,delivered:0,failed:0},queues:{queued:0,scheduled:0,dispatched:0},status:{}},s=async a=>{if(t){let n=this.getDescriptorKey(t);return(await this.client.sinter(a,n)).length}return await this.client.scard(a)};for(let a of b.INDEXED_STATUSES){let n=await s(this.getStatusKey(a));e.status[a]=n,a==="DELIVERED"&&(e.cumulative.delivered=n),a==="FAILED"&&(e.cumulative.failed=n)}let i=this.getStateKey("DISPATCHED"),r=await s(i);return e.cumulative.dispatched=r+e.cumulative.delivered+e.cumulative.failed,t?(e.queues.queued=await s(this.getStateKey("QUEUED")),e.queues.scheduled=await s(this.getStateKey("SCHEDULED")),e.queues.dispatched=r):(e.queues.queued=await this.client.zcard(this.getQueueKey("queued")),e.queues.scheduled=await this.client.zcard(this.getQueueKey("scheduled")),e.queues.dispatched=await this.client.zcard(this.getQueueKey("dispatched"))),e}async getDescriptors(){let t=this.getDescriptorKey("*"),e=await this.client.keys(t),s=[];for(let i of e){let r=i.split(":").pop();if(r){let a=await this.client.scard(i);s.push({id:r,count:a})}}return s.sort((i,r)=>r.count-i.count),s}};b.INDEXED_STATUSES=["INIT","PENDING","SENDING","DELIVERED","READ","REPLIED","FAILED","CANCELED"],b.INDEXED_STATES=["INIT","DISPATCHED","SCHEDULED","QUEUED","FINAL"];var z=b;0&&(module.exports={Blip,BlipError,DispatchState,Dispatcher,DispatcherDescriptor,DispatcherMonitor,DispatcherRepository,MessageState,MessageStatus,Vnd,Weekdays,enableLogger,getLogger});
|
|
2
|
+
//# sourceMappingURL=index.js.map
|