@geekmidas/constructs 4.0.0 → 5.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 +112 -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-CODxw_vc.mjs} +2 -2
- package/dist/{AWSScheduledFunction-D-55GfwL.mjs.map → AWSScheduledFunction-CODxw_vc.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-CdJY2DJS.mjs → Construct-DD8EaWzh.mjs} +4 -2
- package/dist/{Construct-CdJY2DJS.mjs.map → Construct-DD8EaWzh.mjs.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-B14miJ6P.cjs → Construct-vXMZJgRp.cjs} +3 -1
- package/dist/{Construct-B14miJ6P.cjs.map → Construct-vXMZJgRp.cjs.map} +1 -1
- package/dist/{Endpoint-D5SChIsU.d.cts → Endpoint-C3-ZyPSL.d.cts} +5 -5
- package/dist/Endpoint-C3-ZyPSL.d.cts.map +1 -0
- package/dist/{Endpoint-C_qxza6z.d.mts → Endpoint-CLPSIl6S.d.mts} +5 -5
- package/dist/Endpoint-CLPSIl6S.d.mts.map +1 -0
- package/dist/{HonoEndpointAdaptor-CWYBGVFQ.mjs → HonoEndpointAdaptor-BwfNyFCi.mjs} +2 -2
- package/dist/{HonoEndpointAdaptor-CWYBGVFQ.mjs.map → HonoEndpointAdaptor-BwfNyFCi.mjs.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/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 +5 -5
- 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-Bx9Ac0ea.mjs} +2 -2
- package/dist/{functions-C9QhxXoP.mjs.map → functions-Bx9Ac0ea.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-DhOPJsRT.mjs} +3 -3
- package/dist/lazyAccessors-DhOPJsRT.mjs.map +1 -0
- package/dist/{lazyAccessors-DGqzwC-j.cjs → lazyAccessors-DmTG8sQH.cjs} +3 -3
- package/dist/lazyAccessors-DmTG8sQH.cjs.map +1 -0
- 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 +33 -13
- package/src/Construct.ts +2 -0
- package/src/adaptors/aws.ts +1 -0
- package/src/adaptors/testing.ts +1 -0
- package/src/endpoints/Endpoint.ts +16 -10
- 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/Endpoint-C_qxza6z.d.mts.map +0 -1
- package/dist/Endpoint-D5SChIsU.d.cts.map +0 -1
- package/dist/Subscriber-C0v9iOrI.d.mts.map +0 -1
- package/dist/Subscriber-C6YXAmTp.d.cts.map +0 -1
- package/dist/lazyAccessors-Bnq67EHR.mjs.map +0 -1
- package/dist/lazyAccessors-DGqzwC-j.cjs.map +0 -1
|
@@ -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;
|
|
@@ -0,0 +1,103 @@
|
|
|
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 } 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
|
+
/** A topic's event contract — a map of event type → payload schema. */
|
|
18
|
+
export type TopicEvents = Record<string, StandardSchemaV1>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The union of wire messages a topic carries, derived from its event map:
|
|
22
|
+
* `{ type: 'user.created'; payload: … } | { type: 'user.updated'; payload: … }`.
|
|
23
|
+
*/
|
|
24
|
+
export type TopicMessage<TEvents extends TopicEvents> = {
|
|
25
|
+
[K in keyof TEvents & string]: PublishableMessage<
|
|
26
|
+
K,
|
|
27
|
+
InferStandardSchema<TEvents[K]>
|
|
28
|
+
>;
|
|
29
|
+
}[keyof TEvents & string];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A topic — pub/sub fan-out. Unlike a `Queue` (point-to-point, one consumer), a
|
|
33
|
+
* topic is a *resource* owned by no single handler: it declares the event
|
|
34
|
+
* contract, derives a typed producer (`topic.publisher`), and any number of
|
|
35
|
+
* subscribers (`s.topic(topic)`) bind to it. `gkm build` discovers it into the
|
|
36
|
+
* manifest's `topics` field; infra provisions an SNS topic.
|
|
37
|
+
*
|
|
38
|
+
* This replaces hand-writing a publisher `Service`: the publisher is *derived*
|
|
39
|
+
* from the declared event contract, the same way `Queue` derives its publisher.
|
|
40
|
+
*/
|
|
41
|
+
export class Topic<
|
|
42
|
+
TName extends string = string,
|
|
43
|
+
TEvents extends TopicEvents = TopicEvents,
|
|
44
|
+
> extends Construct {
|
|
45
|
+
__IS_TOPIC__ = true;
|
|
46
|
+
|
|
47
|
+
static isTopic(obj: unknown): obj is Topic<string, TopicEvents> {
|
|
48
|
+
return Boolean(
|
|
49
|
+
obj &&
|
|
50
|
+
(obj as { __IS_TOPIC__?: boolean }).__IS_TOPIC__ === true &&
|
|
51
|
+
(obj as Construct).type === ConstructType.Topic,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
public readonly name: TName,
|
|
57
|
+
/**
|
|
58
|
+
* The event contract — a map of event type → payload schema. Named
|
|
59
|
+
* `eventSchemas` (not `events`) to avoid clashing with `Construct.events`,
|
|
60
|
+
* which is the array of `MappedEvent`s a construct *publishes*.
|
|
61
|
+
*/
|
|
62
|
+
public readonly eventSchemas: TEvents,
|
|
63
|
+
logger: Logger = DEFAULT_LOGGER,
|
|
64
|
+
) {
|
|
65
|
+
super(ConstructType.Topic, logger, [], []);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The event type names this topic carries. */
|
|
69
|
+
get eventTypes(): (keyof TEvents & string)[] {
|
|
70
|
+
return Object.keys(this.eventSchemas) as (keyof TEvents & string)[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The producer side — a `Service` exposing an `EventPublisher` typed to the
|
|
75
|
+
* union of this topic's events. Inject via `.publisher(topic.publisher)` (for
|
|
76
|
+
* declarative `.event(...)`) or `.services([topic.publisher])` (to publish
|
|
77
|
+
* imperatively). Reads `<NAME>_PUBLISHER_CONNECTION_STRING` and selects the
|
|
78
|
+
* transport from the URL protocol — `pgboss://` locally, `sns://` deployed.
|
|
79
|
+
*
|
|
80
|
+
* Because it's a `Service`, the connection-string requirement is sniffed into
|
|
81
|
+
* the manifest of whatever construct injects it (least-privilege linking).
|
|
82
|
+
*/
|
|
83
|
+
get publisher(): Service<
|
|
84
|
+
`${TName}Publisher`,
|
|
85
|
+
EventPublisher<TopicMessage<TEvents>>
|
|
86
|
+
> {
|
|
87
|
+
const envVar = `${environmentCase(this.name)}_PUBLISHER_CONNECTION_STRING`;
|
|
88
|
+
return {
|
|
89
|
+
serviceName: `${this.name}Publisher`,
|
|
90
|
+
async register({ envParser }) {
|
|
91
|
+
const { connectionString } = envParser
|
|
92
|
+
.create((get) => ({
|
|
93
|
+
connectionString: get(envVar).string(),
|
|
94
|
+
}))
|
|
95
|
+
.parse();
|
|
96
|
+
|
|
97
|
+
return Publisher.fromConnectionString<TopicMessage<TEvents>>(
|
|
98
|
+
connectionString as EventPublisherConnectionString,
|
|
99
|
+
);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Logger } from '@geekmidas/logger';
|
|
2
|
+
import { DEFAULT_LOGGER } from '@geekmidas/logger/console';
|
|
3
|
+
import { Topic, type TopicEvents } from './Topic';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Builds a {@link Topic} — `t.topic('users').events({ 'user.created': schema, … })`.
|
|
7
|
+
* The event map is the topic's contract: it types the derived `topic.publisher`
|
|
8
|
+
* and the subscribers that bind via `s.topic(topic)`.
|
|
9
|
+
*/
|
|
10
|
+
export class TopicBuilder<
|
|
11
|
+
TName extends string = string,
|
|
12
|
+
TEvents extends TopicEvents = TopicEvents,
|
|
13
|
+
> {
|
|
14
|
+
private _name?: string;
|
|
15
|
+
private _logger: Logger = DEFAULT_LOGGER;
|
|
16
|
+
|
|
17
|
+
/** The topic name — drives the infra topic and its `<NAME>_*` env vars. */
|
|
18
|
+
topic<T extends string>(name: T): TopicBuilder<T, TEvents> {
|
|
19
|
+
this._name = name;
|
|
20
|
+
return this as unknown as TopicBuilder<T, TEvents>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
logger(logger: Logger): this {
|
|
24
|
+
this._logger = logger;
|
|
25
|
+
return this;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The event contract — a map of event type → payload schema. Building the
|
|
30
|
+
* topic requires this; it's what types the publisher and subscribers.
|
|
31
|
+
*/
|
|
32
|
+
events<T extends TopicEvents>(events: T): Topic<TName, T> {
|
|
33
|
+
if (!this._name) {
|
|
34
|
+
throw new Error(
|
|
35
|
+
'Topic requires a name — call .topic(name) before .events().',
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const topic = new Topic<TName, T>(
|
|
40
|
+
this._name as TName,
|
|
41
|
+
events,
|
|
42
|
+
this._logger,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
// Reset builder state to prevent pollution across reuse.
|
|
46
|
+
this._name = undefined;
|
|
47
|
+
this._logger = DEFAULT_LOGGER;
|
|
48
|
+
|
|
49
|
+
return topic;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { s } from '../../subscribers';
|
|
4
|
+
import { Topic } from '../Topic';
|
|
5
|
+
import { TopicBuilder } from '../TopicBuilder';
|
|
6
|
+
|
|
7
|
+
const events = {
|
|
8
|
+
'user.created': z.object({ userId: z.string(), email: z.string() }),
|
|
9
|
+
'user.updated': z.object({
|
|
10
|
+
userId: z.string(),
|
|
11
|
+
changes: z.array(z.string()),
|
|
12
|
+
}),
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
describe('TopicBuilder', () => {
|
|
16
|
+
it('builds a Topic from .topic().events()', () => {
|
|
17
|
+
const topic = new TopicBuilder().topic('users').events(events);
|
|
18
|
+
|
|
19
|
+
expect(Topic.isTopic(topic)).toBe(true);
|
|
20
|
+
expect(topic.name).toBe('users');
|
|
21
|
+
expect(topic.eventSchemas).toBe(events);
|
|
22
|
+
expect(topic.eventTypes.sort()).toEqual(['user.created', 'user.updated']);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('throws when the name is missing', () => {
|
|
26
|
+
expect(() => new TopicBuilder().events(events)).toThrow(/name/);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('resets builder state after events()', () => {
|
|
30
|
+
const builder = new TopicBuilder();
|
|
31
|
+
builder.topic('first').events(events);
|
|
32
|
+
expect(() => builder.events(events)).toThrow(/name/);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe('Topic.publisher', () => {
|
|
37
|
+
it('exposes a `<name>Publisher` producer service', () => {
|
|
38
|
+
const topic = new TopicBuilder().topic('users').events(events);
|
|
39
|
+
expect(topic.publisher.serviceName).toBe('usersPublisher');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('requires the namespaced connection-string env var when injected', async () => {
|
|
43
|
+
const topic = new TopicBuilder().topic('userEvents').events(events);
|
|
44
|
+
|
|
45
|
+
// A construct that injects the publisher (a producer) requires its env var.
|
|
46
|
+
const producer = s
|
|
47
|
+
.services([topic.publisher])
|
|
48
|
+
.subscribe('noop')
|
|
49
|
+
.handle(async () => {});
|
|
50
|
+
|
|
51
|
+
const env = await producer.getEnvironment();
|
|
52
|
+
expect(env).toContain('USER_EVENTS_PUBLISHER_CONNECTION_STRING');
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('subscriber .topic() binding', () => {
|
|
57
|
+
it('binds the topic name and does NOT require the publisher env (least privilege)', async () => {
|
|
58
|
+
const topic = new TopicBuilder().topic('users').events(events);
|
|
59
|
+
|
|
60
|
+
const subscriber = s
|
|
61
|
+
.topic(topic)
|
|
62
|
+
.subscribe(['user.created', 'user.updated'])
|
|
63
|
+
.handle(async ({ events }) => {
|
|
64
|
+
// payloads are typed from the topic contract
|
|
65
|
+
for (const event of events) {
|
|
66
|
+
if (event.type === 'user.created') {
|
|
67
|
+
void event.payload.email;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
expect(subscriber.topicName).toBe('users');
|
|
73
|
+
expect(subscriber.subscribedEvents).toEqual([
|
|
74
|
+
'user.created',
|
|
75
|
+
'user.updated',
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
// A consumer does not publish, so binding a topic requires no publisher env.
|
|
79
|
+
const env = await subscriber.getEnvironment();
|
|
80
|
+
expect(env).not.toContain('USERS_PUBLISHER_CONNECTION_STRING');
|
|
81
|
+
});
|
|
82
|
+
});
|
package/tsdown.config.ts
CHANGED