@geekmidas/constructs 4.0.1 → 6.0.0
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/CHANGELOG.md +100 -0
- package/dist/{AWSScheduledFunction-COv8bB1v.d.mts → AWSScheduledFunction-1GYwJS7F.d.cts} +4 -4
- package/dist/{AWSScheduledFunction-D9uCAd76.d.cts.map → AWSScheduledFunction-1GYwJS7F.d.cts.map} +1 -1
- package/dist/{AWSScheduledFunction-D-55GfwL.mjs → AWSScheduledFunction-CufMMhGB.mjs} +2 -2
- package/dist/{AWSScheduledFunction-D-55GfwL.mjs.map → AWSScheduledFunction-CufMMhGB.mjs.map} +1 -1
- package/dist/{AWSScheduledFunction-sWwZC9hg.cjs → AWSScheduledFunction-DbkDr8CA.cjs} +3 -3
- package/dist/{AWSScheduledFunction-sWwZC9hg.cjs.map → AWSScheduledFunction-DbkDr8CA.cjs.map} +1 -1
- package/dist/{AWSScheduledFunction-D9uCAd76.d.cts → AWSScheduledFunction-ysaCsdWx.d.mts} +4 -4
- package/dist/{AWSScheduledFunction-COv8bB1v.d.mts.map → AWSScheduledFunction-ysaCsdWx.d.mts.map} +1 -1
- package/dist/{Construct-D0n7QTaI.d.mts → Construct-DCMuYOox.d.mts} +3 -1
- package/dist/{Construct-D0n7QTaI.d.mts.map → Construct-DCMuYOox.d.mts.map} +1 -1
- package/dist/{Construct-cjIs74Gb.d.cts → Construct-_1wX7p_Y.d.cts} +3 -1
- package/dist/{Construct-cjIs74Gb.d.cts.map → Construct-_1wX7p_Y.d.cts.map} +1 -1
- package/dist/{Construct-CdJY2DJS.mjs → Construct-r0U2zBwW.mjs} +3 -1
- package/dist/{Construct-CdJY2DJS.mjs.map → Construct-r0U2zBwW.mjs.map} +1 -1
- package/dist/{Construct-B14miJ6P.cjs → Construct-vXMZJgRp.cjs} +3 -1
- package/dist/{Construct-B14miJ6P.cjs.map → Construct-vXMZJgRp.cjs.map} +1 -1
- package/dist/{Endpoint-CKGT5TgS.d.cts → Endpoint-C3-ZyPSL.d.cts} +2 -2
- package/dist/{Endpoint-CKGT5TgS.d.cts.map → Endpoint-C3-ZyPSL.d.cts.map} +1 -1
- package/dist/{Endpoint-agNpJO38.d.mts → Endpoint-CLPSIl6S.d.mts} +2 -2
- package/dist/{Endpoint-agNpJO38.d.mts.map → Endpoint-CLPSIl6S.d.mts.map} +1 -1
- package/dist/{HonoEndpointAdaptor-C_2jaZ4k.cjs → HonoEndpointAdaptor-CkJENANP.cjs} +4 -4
- package/dist/{HonoEndpointAdaptor-C_2jaZ4k.cjs.map → HonoEndpointAdaptor-CkJENANP.cjs.map} +1 -1
- package/dist/{HonoEndpointAdaptor-CWYBGVFQ.mjs → HonoEndpointAdaptor-DJDT3PMx.mjs} +2 -2
- package/dist/{HonoEndpointAdaptor-CWYBGVFQ.mjs.map → HonoEndpointAdaptor-DJDT3PMx.mjs.map} +1 -1
- package/dist/Queue-DaxjwmOQ.d.cts +66 -0
- package/dist/Queue-DaxjwmOQ.d.cts.map +1 -0
- package/dist/Queue-HBDf0fqz.d.mts +66 -0
- package/dist/Queue-HBDf0fqz.d.mts.map +1 -0
- package/dist/{Subscriber-C6YXAmTp.d.cts → Subscriber-B69ngPwl.d.cts} +17 -3
- package/dist/Subscriber-B69ngPwl.d.cts.map +1 -0
- package/dist/{Subscriber-C0v9iOrI.d.mts → Subscriber-D8Xm-86W.d.mts} +17 -3
- package/dist/Subscriber-D8Xm-86W.d.mts.map +1 -0
- package/dist/Topic-C5ZMfveW.d.cts +60 -0
- package/dist/Topic-C5ZMfveW.d.cts.map +1 -0
- package/dist/Topic-DT10AqHk.d.mts +60 -0
- package/dist/Topic-DT10AqHk.d.mts.map +1 -0
- package/dist/adaptors/aws.cjs +109 -5
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +39 -7
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts +39 -7
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +108 -5
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +5 -5
- package/dist/adaptors/hono.d.cts +5 -5
- package/dist/adaptors/hono.d.cts.map +1 -1
- package/dist/adaptors/hono.d.mts +5 -5
- package/dist/adaptors/hono.mjs +4 -4
- package/dist/adaptors/testing.cjs +42 -5
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +29 -5
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +29 -5
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +41 -5
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/crons/index.cjs +3 -3
- package/dist/crons/index.d.cts +3 -3
- package/dist/crons/index.d.mts +3 -3
- package/dist/crons/index.mjs +3 -3
- package/dist/endpoints/index.cjs +3 -3
- package/dist/endpoints/index.d.cts +3 -3
- package/dist/endpoints/index.d.mts +3 -3
- package/dist/endpoints/index.mjs +3 -3
- package/dist/functions/index.cjs +2 -2
- package/dist/functions/index.d.cts +2 -2
- package/dist/functions/index.d.mts +2 -2
- package/dist/functions/index.mjs +2 -2
- package/dist/{functions-C9QhxXoP.mjs → functions-B-qt91O7.mjs} +2 -2
- package/dist/{functions-C9QhxXoP.mjs.map → functions-B-qt91O7.mjs.map} +1 -1
- package/dist/{functions-cL1XwEHW.cjs → functions-C8i1kCMM.cjs} +2 -2
- package/dist/{functions-cL1XwEHW.cjs.map → functions-C8i1kCMM.cjs.map} +1 -1
- package/dist/{index-Cg0m0uBN.d.cts → index-D-s9UrHd.d.cts} +6 -6
- package/dist/{index-Cg0m0uBN.d.cts.map → index-D-s9UrHd.d.cts.map} +1 -1
- package/dist/{index-C0XoazSK.d.mts → index-DP6fqv0I.d.mts} +2 -2
- package/dist/{index-C0XoazSK.d.mts.map → index-DP6fqv0I.d.mts.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{lazyAccessors-Bnq67EHR.mjs → lazyAccessors-DfqZR6C4.mjs} +3 -3
- package/dist/{lazyAccessors-Bnq67EHR.mjs.map → lazyAccessors-DfqZR6C4.mjs.map} +1 -1
- package/dist/{lazyAccessors-DGqzwC-j.cjs → lazyAccessors-DmTG8sQH.cjs} +3 -3
- package/dist/{lazyAccessors-DGqzwC-j.cjs.map → lazyAccessors-DmTG8sQH.cjs.map} +1 -1
- package/dist/{processAudits-BmjKsnF7.cjs → processAudits-CKjjivyz.cjs} +2 -2
- package/dist/{processAudits-BmjKsnF7.cjs.map → processAudits-CKjjivyz.cjs.map} +1 -1
- package/dist/queue/index.cjs +127 -0
- package/dist/queue/index.cjs.map +1 -0
- package/dist/queue/index.d.cts +45 -0
- package/dist/queue/index.d.cts.map +1 -0
- package/dist/queue/index.d.mts +44 -0
- package/dist/queue/index.d.mts.map +1 -0
- package/dist/queue/index.mjs +125 -0
- package/dist/queue/index.mjs.map +1 -0
- package/dist/subscribers/index.cjs +21 -3
- package/dist/subscribers/index.cjs.map +1 -1
- package/dist/subscribers/index.d.cts +18 -4
- package/dist/subscribers/index.d.cts.map +1 -1
- package/dist/subscribers/index.d.mts +16 -2
- package/dist/subscribers/index.d.mts.map +1 -1
- package/dist/subscribers/index.mjs +21 -3
- package/dist/subscribers/index.mjs.map +1 -1
- package/dist/topic/index.cjs +94 -0
- package/dist/topic/index.cjs.map +1 -0
- package/dist/topic/index.d.cts +32 -0
- package/dist/topic/index.d.cts.map +1 -0
- package/dist/topic/index.d.mts +32 -0
- package/dist/topic/index.d.mts.map +1 -0
- package/dist/topic/index.mjs +92 -0
- package/dist/topic/index.mjs.map +1 -0
- package/package.json +35 -15
- package/src/Construct.ts +2 -0
- package/src/adaptors/aws.ts +1 -0
- package/src/adaptors/testing.ts +1 -0
- package/src/queue/AWSLambdaQueueAdaptor.ts +162 -0
- package/src/queue/Queue.ts +128 -0
- package/src/queue/QueueBuilder.ts +115 -0
- package/src/queue/TestQueueAdaptor.ts +63 -0
- package/src/queue/__tests__/QueueBuilder.spec.ts +137 -0
- package/src/queue/index.ts +12 -0
- package/src/subscribers/Subscriber.ts +7 -0
- package/src/subscribers/SubscriberBuilder.ts +36 -0
- package/src/topic/Topic.ts +103 -0
- package/src/topic/TopicBuilder.ts +51 -0
- package/src/topic/__tests__/TopicBuilder.spec.ts +82 -0
- package/src/topic/index.ts +11 -0
- package/tsdown.config.ts +2 -0
- package/dist/Subscriber-C0v9iOrI.d.mts.map +0 -1
- package/dist/Subscriber-C6YXAmTp.d.cts.map +0 -1
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
2
|
+
import { wrapError } from '@geekmidas/errors';
|
|
3
|
+
import type { Logger } from '@geekmidas/logger';
|
|
4
|
+
import type { InferStandardSchema } from '@geekmidas/schema';
|
|
5
|
+
import type { Service, ServiceRecord } from '@geekmidas/services';
|
|
6
|
+
import { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';
|
|
7
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
8
|
+
import type {
|
|
9
|
+
Context,
|
|
10
|
+
Handler,
|
|
11
|
+
SQSBatchResponse,
|
|
12
|
+
SQSEvent,
|
|
13
|
+
SQSRecord,
|
|
14
|
+
} from 'aws-lambda';
|
|
15
|
+
import type { Queue } from './Queue';
|
|
16
|
+
|
|
17
|
+
export type AWSLambdaHandler<TEvent = any, TResult = any> = Handler<
|
|
18
|
+
TEvent,
|
|
19
|
+
TResult
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Runs a {@link Queue} worker as an AWS Lambda backed by an SQS event-source
|
|
24
|
+
* mapping. Unlike a subscriber, a queue drains *every* record (no type filter):
|
|
25
|
+
* each record body (`{ type, payload }`, as written by the SQS publisher) is
|
|
26
|
+
* unwrapped to its `payload`, validated against the queue's `messageSchema`, and
|
|
27
|
+
* the whole batch is handed to the handler as `messages`.
|
|
28
|
+
*
|
|
29
|
+
* Uses SQS partial-batch responses: a record that fails to parse, validate, or
|
|
30
|
+
* (when the handler throws) process is returned in `batchItemFailures` so SQS
|
|
31
|
+
* retries only those records.
|
|
32
|
+
*/
|
|
33
|
+
export class AWSLambdaQueue<
|
|
34
|
+
TName extends string = string,
|
|
35
|
+
TMessage extends StandardSchemaV1 = StandardSchemaV1,
|
|
36
|
+
TServices extends Service[] = [],
|
|
37
|
+
TLogger extends Logger = Logger,
|
|
38
|
+
> {
|
|
39
|
+
private _services?: ServiceRecord<TServices>;
|
|
40
|
+
|
|
41
|
+
constructor(
|
|
42
|
+
private readonly envParser: EnvironmentParser<{}>,
|
|
43
|
+
readonly queue: Queue<TName, TMessage, TServices, TLogger>,
|
|
44
|
+
) {}
|
|
45
|
+
|
|
46
|
+
get logger(): TLogger {
|
|
47
|
+
return this.queue.logger;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private async getServices(): Promise<ServiceRecord<TServices>> {
|
|
51
|
+
if (this._services) {
|
|
52
|
+
return this._services;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(this.envParser);
|
|
56
|
+
|
|
57
|
+
this._services =
|
|
58
|
+
this.queue.services.length > 0
|
|
59
|
+
? ((await serviceDiscovery.register(
|
|
60
|
+
this.queue.services,
|
|
61
|
+
)) as ServiceRecord<TServices>)
|
|
62
|
+
: ({} as ServiceRecord<TServices>);
|
|
63
|
+
|
|
64
|
+
return this._services;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private safeJsonParse(value: string): unknown {
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(value);
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Unwrap the queue payload from an SQS record. The SQS publisher writes
|
|
77
|
+
* `{ type, payload }`; a payload-only body is also accepted as-is.
|
|
78
|
+
*/
|
|
79
|
+
private extractPayload(record: SQSRecord): unknown {
|
|
80
|
+
const body = this.safeJsonParse(record.body);
|
|
81
|
+
if (body && typeof body === 'object' && 'payload' in body) {
|
|
82
|
+
return (body as { payload: unknown }).payload;
|
|
83
|
+
}
|
|
84
|
+
return body ?? record.body;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private async _handler(
|
|
88
|
+
event: SQSEvent,
|
|
89
|
+
context: Context,
|
|
90
|
+
): Promise<SQSBatchResponse> {
|
|
91
|
+
const logger = this.queue.logger.child({
|
|
92
|
+
queue: {
|
|
93
|
+
name: this.queue.name,
|
|
94
|
+
fn: context.functionName,
|
|
95
|
+
},
|
|
96
|
+
req: { id: context.awsRequestId },
|
|
97
|
+
}) as TLogger;
|
|
98
|
+
|
|
99
|
+
const services = await this.getServices();
|
|
100
|
+
const schema = this.queue.messageSchema;
|
|
101
|
+
|
|
102
|
+
const batchItemFailures: { itemIdentifier: string }[] = [];
|
|
103
|
+
const messages: InferStandardSchema<TMessage>[] = [];
|
|
104
|
+
|
|
105
|
+
for (const record of event.Records) {
|
|
106
|
+
try {
|
|
107
|
+
const payload = this.extractPayload(record);
|
|
108
|
+
const validation = await schema['~standard'].validate(payload);
|
|
109
|
+
if (validation.issues) {
|
|
110
|
+
logger.error(
|
|
111
|
+
{ issues: validation.issues, messageId: record.messageId },
|
|
112
|
+
'Queue message failed validation',
|
|
113
|
+
);
|
|
114
|
+
batchItemFailures.push({ itemIdentifier: record.messageId });
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
messages.push(validation.value as InferStandardSchema<TMessage>);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
logger.error(
|
|
120
|
+
{ error, messageId: record.messageId },
|
|
121
|
+
'Failed to parse SQS record',
|
|
122
|
+
);
|
|
123
|
+
batchItemFailures.push({ itemIdentifier: record.messageId });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (messages.length === 0) {
|
|
128
|
+
return { batchItemFailures };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
await this.queue.handler({ messages, services, logger });
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.error(wrapError(error), 'Queue handler failed; retrying batch');
|
|
135
|
+
// Handler processes the batch atomically — fail the whole batch so SQS
|
|
136
|
+
// retries every (valid) record.
|
|
137
|
+
for (const record of event.Records) {
|
|
138
|
+
if (
|
|
139
|
+
!batchItemFailures.some((f) => f.itemIdentifier === record.messageId)
|
|
140
|
+
) {
|
|
141
|
+
batchItemFailures.push({ itemIdentifier: record.messageId });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return { batchItemFailures };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
get handler(): AWSLambdaHandler<SQSEvent, SQSBatchResponse> {
|
|
150
|
+
const handler = this._handler.bind(this);
|
|
151
|
+
|
|
152
|
+
return (async (event: SQSEvent, context: Context) => {
|
|
153
|
+
const startTime = Date.now();
|
|
154
|
+
const requestId = context.awsRequestId;
|
|
155
|
+
const logger = this.queue.logger.child({ requestId }) as TLogger;
|
|
156
|
+
|
|
157
|
+
return runWithRequestContext({ logger, requestId, startTime }, () =>
|
|
158
|
+
handler(event, context),
|
|
159
|
+
);
|
|
160
|
+
}) as unknown as AWSLambdaHandler<SQSEvent, SQSBatchResponse>;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { environmentCase } from '@geekmidas/envkit';
|
|
2
|
+
import {
|
|
3
|
+
type EventPublisher,
|
|
4
|
+
type EventPublisherConnectionString,
|
|
5
|
+
type PublishableMessage,
|
|
6
|
+
Publisher,
|
|
7
|
+
} from '@geekmidas/events';
|
|
8
|
+
import type { Logger } from '@geekmidas/logger';
|
|
9
|
+
import { ConsoleLogger } from '@geekmidas/logger/console';
|
|
10
|
+
import type { InferStandardSchema } from '@geekmidas/schema';
|
|
11
|
+
import type { Service, ServiceRecord } from '@geekmidas/services';
|
|
12
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
13
|
+
import { Construct, ConstructType } from '../Construct';
|
|
14
|
+
|
|
15
|
+
const DEFAULT_LOGGER = new ConsoleLogger() as unknown as Logger;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The wire message a queue carries: `{ type: <queue name>, payload: <message> }`.
|
|
19
|
+
* The producer publishes this shape and the worker receives the `payload`s as
|
|
20
|
+
* its `messages`. Typing `type` to the queue name keeps the publisher fully
|
|
21
|
+
* typed and lets pg-boss (local) / SQS (deployed) route by name.
|
|
22
|
+
*/
|
|
23
|
+
export type QueueMessage<
|
|
24
|
+
TName extends string,
|
|
25
|
+
TMessage extends StandardSchemaV1,
|
|
26
|
+
> = PublishableMessage<TName, InferStandardSchema<TMessage>>;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A queue worker — a point-to-point SQS-style queue and its single consumer.
|
|
30
|
+
* Unlike a `Subscriber` (topic fan-out, filtered by `subscribedEvents`), a queue
|
|
31
|
+
* drains every message of its one `message` type. Build one with `q` (see
|
|
32
|
+
* `QueueBuilder`); `gkm build` discovers it into the manifest's `queues` field.
|
|
33
|
+
*
|
|
34
|
+
* The producer side is {@link Queue.publisher} — a ready-to-inject `Service`
|
|
35
|
+
* that any endpoint/function drops into `.services([...])` to send messages.
|
|
36
|
+
*/
|
|
37
|
+
export class Queue<
|
|
38
|
+
TName extends string = string,
|
|
39
|
+
TMessage extends StandardSchemaV1 = StandardSchemaV1,
|
|
40
|
+
TServices extends Service[] = [],
|
|
41
|
+
TLogger extends Logger = Logger,
|
|
42
|
+
> extends Construct<TLogger, string, undefined, undefined, TServices> {
|
|
43
|
+
__IS_QUEUE__ = true;
|
|
44
|
+
|
|
45
|
+
static isQueue(
|
|
46
|
+
obj: unknown,
|
|
47
|
+
): obj is Queue<string, StandardSchemaV1, Service[], Logger> {
|
|
48
|
+
return Boolean(
|
|
49
|
+
obj &&
|
|
50
|
+
(obj as { __IS_QUEUE__?: boolean }).__IS_QUEUE__ === true &&
|
|
51
|
+
(obj as Construct).type === ConstructType.Queue,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
public readonly name: TName,
|
|
57
|
+
public readonly handler: QueueHandler<TMessage, TServices, TLogger>,
|
|
58
|
+
public readonly messageSchema: TMessage,
|
|
59
|
+
public override readonly timeout: number = 30000,
|
|
60
|
+
public override readonly services: TServices = [] as unknown as TServices,
|
|
61
|
+
public override readonly logger: TLogger = DEFAULT_LOGGER as TLogger,
|
|
62
|
+
/** SQS event-source batch size (deployed). */
|
|
63
|
+
public readonly batchSize?: number,
|
|
64
|
+
/** Whether the queue is FIFO (deployed). */
|
|
65
|
+
public readonly fifo?: boolean,
|
|
66
|
+
) {
|
|
67
|
+
super(
|
|
68
|
+
ConstructType.Queue,
|
|
69
|
+
logger,
|
|
70
|
+
services,
|
|
71
|
+
[],
|
|
72
|
+
undefined,
|
|
73
|
+
undefined,
|
|
74
|
+
timeout,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The producer side — a `Service` exposing an `EventPublisher` typed to this
|
|
80
|
+
* queue's message. Inject it via `.services([queue.publisher])`; the handler
|
|
81
|
+
* then calls `services.<name>Publisher.publish([{ type, payload }])`.
|
|
82
|
+
*
|
|
83
|
+
* It reads `<NAME>_PUBLISHER_CONNECTION_STRING` and builds the transport from
|
|
84
|
+
* the URL protocol — `pgboss://` locally, `sqs://` deployed — so the same
|
|
85
|
+
* code publishes to Postgres in dev and SQS in prod. Because it's a `Service`,
|
|
86
|
+
* `Construct.getEnvironment()` sniffs it, so the env requirement flows into
|
|
87
|
+
* the manifest and infra links exactly this queue with least privilege.
|
|
88
|
+
*/
|
|
89
|
+
get publisher(): Service<
|
|
90
|
+
`${TName}Publisher`,
|
|
91
|
+
EventPublisher<QueueMessage<TName, TMessage>>
|
|
92
|
+
> {
|
|
93
|
+
const envVar = `${environmentCase(this.name)}_PUBLISHER_CONNECTION_STRING`;
|
|
94
|
+
return {
|
|
95
|
+
serviceName: `${this.name}Publisher`,
|
|
96
|
+
async register({ envParser }) {
|
|
97
|
+
const { connectionString } = envParser
|
|
98
|
+
.create((get) => ({
|
|
99
|
+
connectionString: get(envVar).string(),
|
|
100
|
+
}))
|
|
101
|
+
.parse();
|
|
102
|
+
|
|
103
|
+
return Publisher.fromConnectionString<QueueMessage<TName, TMessage>>(
|
|
104
|
+
connectionString as EventPublisherConnectionString,
|
|
105
|
+
);
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The context a queue handler receives — a batch of typed messages. */
|
|
112
|
+
export type QueueContext<
|
|
113
|
+
TMessage extends StandardSchemaV1,
|
|
114
|
+
TServices extends Service[] = [],
|
|
115
|
+
TLogger extends Logger = Logger,
|
|
116
|
+
> = {
|
|
117
|
+
messages: InferStandardSchema<TMessage>[];
|
|
118
|
+
services: ServiceRecord<TServices>;
|
|
119
|
+
logger: TLogger;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
export type QueueHandler<
|
|
123
|
+
TMessage extends StandardSchemaV1,
|
|
124
|
+
TServices extends Service[] = [],
|
|
125
|
+
TLogger extends Logger = Logger,
|
|
126
|
+
> = (
|
|
127
|
+
ctx: QueueContext<TMessage, TServices, TLogger>,
|
|
128
|
+
) => unknown | Promise<unknown>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { Logger } from '@geekmidas/logger';
|
|
2
|
+
import { DEFAULT_LOGGER } from '@geekmidas/logger/console';
|
|
3
|
+
import type { Service } from '@geekmidas/services';
|
|
4
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
5
|
+
import { Queue, type QueueHandler } from './Queue';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
9
|
+
* Services are an array (sniffed for required env vars); `message` is the typed
|
|
10
|
+
* job payload; `handle` is the single consumer. The queue name is captured as a
|
|
11
|
+
* literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.
|
|
12
|
+
*/
|
|
13
|
+
export class QueueBuilder<
|
|
14
|
+
TName extends string = string,
|
|
15
|
+
TMessage extends StandardSchemaV1 | undefined = undefined,
|
|
16
|
+
TServices extends Service[] = [],
|
|
17
|
+
TLogger extends Logger = Logger,
|
|
18
|
+
> {
|
|
19
|
+
private _name?: string;
|
|
20
|
+
private _messageSchema?: TMessage;
|
|
21
|
+
private _timeout = 30000;
|
|
22
|
+
private _batchSize?: number;
|
|
23
|
+
private _fifo?: boolean;
|
|
24
|
+
private _services: TServices = [] as Service[] as TServices;
|
|
25
|
+
private _logger: TLogger = DEFAULT_LOGGER as TLogger;
|
|
26
|
+
|
|
27
|
+
/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */
|
|
28
|
+
queue<T extends string>(
|
|
29
|
+
name: T,
|
|
30
|
+
): QueueBuilder<T, TMessage, TServices, TLogger> {
|
|
31
|
+
this._name = name;
|
|
32
|
+
return this as unknown as QueueBuilder<T, TMessage, TServices, TLogger>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
timeout(timeout: number): this {
|
|
36
|
+
this._timeout = timeout;
|
|
37
|
+
return this;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** SQS event-source batch size (deployed). */
|
|
41
|
+
batchSize(batchSize: number): this {
|
|
42
|
+
this._batchSize = batchSize;
|
|
43
|
+
return this;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Mark the queue as FIFO (deployed). */
|
|
47
|
+
fifo(fifo = true): this {
|
|
48
|
+
this._fifo = fifo;
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
services<T extends Service[]>(
|
|
53
|
+
services: T,
|
|
54
|
+
): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger> {
|
|
55
|
+
this._services = [...this._services, ...services] as unknown as TServices;
|
|
56
|
+
return this as unknown as QueueBuilder<
|
|
57
|
+
TName,
|
|
58
|
+
TMessage,
|
|
59
|
+
[...TServices, ...T],
|
|
60
|
+
TLogger
|
|
61
|
+
>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
logger<T extends Logger>(
|
|
65
|
+
logger: T,
|
|
66
|
+
): QueueBuilder<TName, TMessage, TServices, T> {
|
|
67
|
+
this._logger = logger as unknown as TLogger;
|
|
68
|
+
return this as unknown as QueueBuilder<TName, TMessage, TServices, T>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The typed message (job) payload the queue carries. */
|
|
72
|
+
message<T extends StandardSchemaV1>(
|
|
73
|
+
schema: T,
|
|
74
|
+
): QueueBuilder<TName, T, TServices, TLogger> {
|
|
75
|
+
this._messageSchema = schema as unknown as TMessage;
|
|
76
|
+
return this as unknown as QueueBuilder<TName, T, TServices, TLogger>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
handle(
|
|
80
|
+
fn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>,
|
|
81
|
+
): Queue<TName, NonNullable<TMessage>, TServices, TLogger> {
|
|
82
|
+
if (!this._name) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
'Queue requires a name — call .queue(name) before .handle().',
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (!this._messageSchema) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
'Queue requires a message schema — call .message(schema) before .handle().',
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const queue = new Queue<TName, NonNullable<TMessage>, TServices, TLogger>(
|
|
94
|
+
this._name as TName,
|
|
95
|
+
fn,
|
|
96
|
+
this._messageSchema as NonNullable<TMessage>,
|
|
97
|
+
this._timeout,
|
|
98
|
+
this._services,
|
|
99
|
+
this._logger,
|
|
100
|
+
this._batchSize,
|
|
101
|
+
this._fifo,
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
// Reset builder state to prevent pollution across reuse.
|
|
105
|
+
this._name = undefined;
|
|
106
|
+
this._messageSchema = undefined;
|
|
107
|
+
this._timeout = 30000;
|
|
108
|
+
this._batchSize = undefined;
|
|
109
|
+
this._fifo = undefined;
|
|
110
|
+
this._services = [] as Service[] as TServices;
|
|
111
|
+
this._logger = DEFAULT_LOGGER as TLogger;
|
|
112
|
+
|
|
113
|
+
return queue;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { EnvironmentParser } from '@geekmidas/envkit';
|
|
2
|
+
import type { Logger } from '@geekmidas/logger';
|
|
3
|
+
import type { InferStandardSchema } from '@geekmidas/schema';
|
|
4
|
+
import type { Service, ServiceRecord } from '@geekmidas/services';
|
|
5
|
+
import { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';
|
|
6
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
7
|
+
import type { Queue } from './Queue';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* In-memory test driver for a {@link Queue} worker. Hand it a batch of messages
|
|
11
|
+
* and it registers the queue's services, runs the handler in a request context,
|
|
12
|
+
* and returns the handler result — no SQS/pg-boss required.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* const adapter = new TestQueueAdaptor(ordersQueue);
|
|
16
|
+
* await adapter.invoke({ messages: [{ orderId: '123' }] });
|
|
17
|
+
*/
|
|
18
|
+
export class TestQueueAdaptor<
|
|
19
|
+
TName extends string = string,
|
|
20
|
+
TMessage extends StandardSchemaV1 = StandardSchemaV1,
|
|
21
|
+
TServices extends Service[] = [],
|
|
22
|
+
TLogger extends Logger = Logger,
|
|
23
|
+
> {
|
|
24
|
+
static getDefaultServiceDiscovery() {
|
|
25
|
+
return ServiceDiscovery.getInstance(new EnvironmentParser({}));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
private readonly queue: Queue<TName, TMessage, TServices, TLogger>,
|
|
30
|
+
private serviceDiscovery: ServiceDiscovery<any> = TestQueueAdaptor.getDefaultServiceDiscovery(),
|
|
31
|
+
) {}
|
|
32
|
+
|
|
33
|
+
async invoke(
|
|
34
|
+
request: TestQueueRequest<TMessage, TServices>,
|
|
35
|
+
): Promise<unknown> {
|
|
36
|
+
const logger = this.queue.logger.child({ test: true }) as TLogger;
|
|
37
|
+
|
|
38
|
+
const services =
|
|
39
|
+
request.services ??
|
|
40
|
+
((await this.serviceDiscovery.register(
|
|
41
|
+
this.queue.services,
|
|
42
|
+
)) as ServiceRecord<TServices>);
|
|
43
|
+
|
|
44
|
+
const requestId = `test-${Date.now()}`;
|
|
45
|
+
const startTime = Date.now();
|
|
46
|
+
|
|
47
|
+
return runWithRequestContext({ logger, requestId, startTime }, () =>
|
|
48
|
+
this.queue.handler({
|
|
49
|
+
messages: request.messages,
|
|
50
|
+
services,
|
|
51
|
+
logger,
|
|
52
|
+
}),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type TestQueueRequest<
|
|
58
|
+
TMessage extends StandardSchemaV1 = StandardSchemaV1,
|
|
59
|
+
TServices extends Service[] = [],
|
|
60
|
+
> = {
|
|
61
|
+
messages: InferStandardSchema<TMessage>[];
|
|
62
|
+
services?: ServiceRecord<TServices>;
|
|
63
|
+
};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { Service } from '@geekmidas/services';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { Queue } from '../Queue';
|
|
5
|
+
import { QueueBuilder } from '../QueueBuilder';
|
|
6
|
+
import { TestQueueAdaptor } from '../TestQueueAdaptor';
|
|
7
|
+
|
|
8
|
+
const schema = z.object({ orderId: z.string() });
|
|
9
|
+
|
|
10
|
+
const svc = (name: string): Service<string, object> => ({
|
|
11
|
+
serviceName: name,
|
|
12
|
+
async register() {
|
|
13
|
+
return {};
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
describe('QueueBuilder', () => {
|
|
18
|
+
it('builds a Queue from .queue().message().handle()', () => {
|
|
19
|
+
const handler = async () => {};
|
|
20
|
+
const queue = new QueueBuilder()
|
|
21
|
+
.queue('orders')
|
|
22
|
+
.message(schema)
|
|
23
|
+
.handle(handler);
|
|
24
|
+
|
|
25
|
+
expect(Queue.isQueue(queue)).toBe(true);
|
|
26
|
+
expect(queue.name).toBe('orders');
|
|
27
|
+
expect(queue.messageSchema).toBe(schema);
|
|
28
|
+
expect(queue.handler).toBe(handler);
|
|
29
|
+
expect(queue.services).toEqual([]);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('collects services as an array', () => {
|
|
33
|
+
const a = svc('a');
|
|
34
|
+
const queue = new QueueBuilder()
|
|
35
|
+
.queue('jobs')
|
|
36
|
+
.services([a])
|
|
37
|
+
.message(schema)
|
|
38
|
+
.handle(async () => {});
|
|
39
|
+
|
|
40
|
+
expect(queue.services).toEqual([a]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('captures batchSize and fifo', () => {
|
|
44
|
+
const queue = new QueueBuilder()
|
|
45
|
+
.queue('orders')
|
|
46
|
+
.batchSize(5)
|
|
47
|
+
.fifo()
|
|
48
|
+
.message(schema)
|
|
49
|
+
.handle(async () => {});
|
|
50
|
+
|
|
51
|
+
expect(queue.batchSize).toBe(5);
|
|
52
|
+
expect(queue.fifo).toBe(true);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('throws when the name is missing', () => {
|
|
56
|
+
expect(() =>
|
|
57
|
+
new QueueBuilder().message(schema).handle(async () => {}),
|
|
58
|
+
).toThrow(/name/);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('throws when the message schema is missing', () => {
|
|
62
|
+
const builder = new QueueBuilder().queue('x');
|
|
63
|
+
expect(() =>
|
|
64
|
+
(builder as QueueBuilder<'x', typeof schema>).handle(async () => {}),
|
|
65
|
+
).toThrow(/message/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('resets builder state after handle', () => {
|
|
69
|
+
const builder = new QueueBuilder();
|
|
70
|
+
builder
|
|
71
|
+
.queue('first')
|
|
72
|
+
.services([svc('x')])
|
|
73
|
+
.message(schema)
|
|
74
|
+
.handle(async () => {});
|
|
75
|
+
// State cleared — a second handle with no name throws.
|
|
76
|
+
expect(() =>
|
|
77
|
+
(builder as QueueBuilder<string, typeof schema>).handle(async () => {}),
|
|
78
|
+
).toThrow(/name/);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('Queue.publisher', () => {
|
|
83
|
+
it('exposes a `<name>Publisher` producer service', () => {
|
|
84
|
+
const queue = new QueueBuilder()
|
|
85
|
+
.queue('orders')
|
|
86
|
+
.message(schema)
|
|
87
|
+
.handle(async () => {});
|
|
88
|
+
|
|
89
|
+
expect(queue.publisher.serviceName).toBe('ordersPublisher');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('requires the namespaced connection-string env var (sniffed into the manifest)', async () => {
|
|
93
|
+
const producer = new QueueBuilder()
|
|
94
|
+
.queue('orderEvents')
|
|
95
|
+
.message(schema)
|
|
96
|
+
.handle(async () => {});
|
|
97
|
+
|
|
98
|
+
// Inject the publisher into a construct's services so getEnvironment sniffs it.
|
|
99
|
+
const consumer = new QueueBuilder()
|
|
100
|
+
.queue('caller')
|
|
101
|
+
.services([producer.publisher])
|
|
102
|
+
.message(schema)
|
|
103
|
+
.handle(async () => {});
|
|
104
|
+
|
|
105
|
+
const env = await consumer.getEnvironment();
|
|
106
|
+
expect(env).toContain('ORDER_EVENTS_PUBLISHER_CONNECTION_STRING');
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe('TestQueueAdaptor', () => {
|
|
111
|
+
it('invokes the handler with the batch of messages and services', async () => {
|
|
112
|
+
const seen: { messages: unknown[]; hadDb: boolean }[] = [];
|
|
113
|
+
const db = svc('db');
|
|
114
|
+
|
|
115
|
+
const queue = new QueueBuilder()
|
|
116
|
+
.queue('orders')
|
|
117
|
+
.services([db])
|
|
118
|
+
.message(schema)
|
|
119
|
+
.handle(async ({ messages, services }) => {
|
|
120
|
+
seen.push({
|
|
121
|
+
messages,
|
|
122
|
+
hadDb: 'db' in (services as Record<string, unknown>),
|
|
123
|
+
});
|
|
124
|
+
return { processed: messages.length };
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
const adapter = new TestQueueAdaptor(queue);
|
|
128
|
+
const result = await adapter.invoke({
|
|
129
|
+
messages: [{ orderId: '1' }, { orderId: '2' }],
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
expect(result).toEqual({ processed: 2 });
|
|
133
|
+
expect(seen).toHaveLength(1);
|
|
134
|
+
expect(seen[0]?.messages).toEqual([{ orderId: '1' }, { orderId: '2' }]);
|
|
135
|
+
expect(seen[0]?.hadDb).toBe(true);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
@@ -63,6 +63,13 @@ export class Subscriber<
|
|
|
63
63
|
TEventPublisherServiceName,
|
|
64
64
|
TEventPublisher
|
|
65
65
|
>,
|
|
66
|
+
/**
|
|
67
|
+
* The name of the {@link Topic} this subscriber binds to (via
|
|
68
|
+
* `s.topic(topic)`), recorded for the manifest so infra wires the SNS
|
|
69
|
+
* subscription. Undefined when the subscriber's events are typed from a
|
|
70
|
+
* (hand-written) publisher instead.
|
|
71
|
+
*/
|
|
72
|
+
public readonly topicName?: string,
|
|
66
73
|
) {
|
|
67
74
|
super(
|
|
68
75
|
ConstructType.Subscriber,
|
|
@@ -6,6 +6,7 @@ import type { Logger } from '@geekmidas/logger';
|
|
|
6
6
|
import { DEFAULT_LOGGER } from '@geekmidas/logger/console';
|
|
7
7
|
import type { Service } from '@geekmidas/services';
|
|
8
8
|
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
9
|
+
import type { Topic, TopicEvents, TopicMessage } from '../topic/Topic';
|
|
9
10
|
import { Subscriber, type SubscriberHandler } from './Subscriber';
|
|
10
11
|
|
|
11
12
|
export class SubscriberBuilder<
|
|
@@ -22,11 +23,44 @@ export class SubscriberBuilder<
|
|
|
22
23
|
private _services: TServices = [] as Service[] as TServices;
|
|
23
24
|
private _logger: TLogger = DEFAULT_LOGGER;
|
|
24
25
|
private _publisher?: Service<TEventPublisherServiceName, TEventPublisher>;
|
|
26
|
+
private _topicName?: string;
|
|
25
27
|
|
|
26
28
|
constructor() {
|
|
27
29
|
this._timeout = 30000; // Default timeout
|
|
28
30
|
}
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Bind this subscriber to a {@link Topic} — the preferred way to type and wire
|
|
34
|
+
* a fan-out consumer. It supplies the subscribable event types (and their
|
|
35
|
+
* payloads) from the topic's contract and records the binding for the manifest,
|
|
36
|
+
* so infra wires the SNS subscription.
|
|
37
|
+
*
|
|
38
|
+
* Prefer this over typing via a hand-written publisher service: a consumer does
|
|
39
|
+
* not publish, so binding a topic does *not* require the topic's publisher
|
|
40
|
+
* connection string (least privilege). Use `.publisher(...)` only when the
|
|
41
|
+
* subscriber actually publishes follow-up events.
|
|
42
|
+
*/
|
|
43
|
+
topic<TName extends string, TEvents extends TopicEvents>(
|
|
44
|
+
topic: Topic<TName, TEvents>,
|
|
45
|
+
): SubscriberBuilder<
|
|
46
|
+
TServices,
|
|
47
|
+
TLogger,
|
|
48
|
+
OutSchema,
|
|
49
|
+
EventPublisher<TopicMessage<TEvents>>,
|
|
50
|
+
TEventPublisherServiceName,
|
|
51
|
+
TSubscribedEvents
|
|
52
|
+
> {
|
|
53
|
+
this._topicName = topic.name;
|
|
54
|
+
return this as unknown as SubscriberBuilder<
|
|
55
|
+
TServices,
|
|
56
|
+
TLogger,
|
|
57
|
+
OutSchema,
|
|
58
|
+
EventPublisher<TopicMessage<TEvents>>,
|
|
59
|
+
TEventPublisherServiceName,
|
|
60
|
+
TSubscribedEvents
|
|
61
|
+
>;
|
|
62
|
+
}
|
|
63
|
+
|
|
30
64
|
timeout(timeout: number): this {
|
|
31
65
|
this._timeout = timeout;
|
|
32
66
|
return this;
|
|
@@ -135,12 +169,14 @@ export class SubscriberBuilder<
|
|
|
135
169
|
this._services,
|
|
136
170
|
this._logger,
|
|
137
171
|
this._publisher,
|
|
172
|
+
this._topicName,
|
|
138
173
|
);
|
|
139
174
|
|
|
140
175
|
// Reset builder state after creating the subscriber to prevent pollution
|
|
141
176
|
this._services = [] as Service[] as TServices;
|
|
142
177
|
this._logger = DEFAULT_LOGGER;
|
|
143
178
|
this._publisher = undefined;
|
|
179
|
+
this._topicName = undefined;
|
|
144
180
|
this._subscribedEvents = [] as any;
|
|
145
181
|
this._timeout = 30000; // Reset to default
|
|
146
182
|
this.outputSchema = undefined;
|