@celerity-sdk/topic 0.3.1 → 0.4.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/README.md +10 -12
- package/dist/index.cjs +456 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +214 -1
- package/dist/index.d.ts +214 -1
- package/dist/index.js +436 -0
- package/dist/index.js.map +1 -1
- package/package.json +20 -4
package/README.md
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# @celerity-sdk/topic
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cloud-agnostic pub/sub topic abstraction for the Celerity Node SDK.
|
|
4
4
|
|
|
5
|
-
Provides a unified `TopicClient` interface for publishing messages to topics across cloud providers
|
|
5
|
+
Provides a unified `TopicClient` interface for publishing messages to topics across cloud providers. The Celerity runtime handles all consumption — this package is **publish-only** (`publish`, `publishBatch`).
|
|
6
6
|
|
|
7
|
-
- **AWS**:Amazon SNS
|
|
8
|
-
- **GCP**:Google Cloud Pub/Sub
|
|
9
|
-
- **Azure**:Azure Service Bus Topics
|
|
7
|
+
- **AWS**: Amazon SNS
|
|
8
|
+
- **GCP**: Google Cloud Pub/Sub *(planned)*
|
|
9
|
+
- **Azure**: Azure Service Bus Topics *(planned)*
|
|
10
|
+
- **Local**: Redis pub/sub channels via Celerity CLI
|
|
10
11
|
|
|
11
12
|
## Installation
|
|
12
13
|
|
|
@@ -20,17 +21,14 @@ Install the cloud SDK for your target platform as a peer dependency:
|
|
|
20
21
|
# AWS
|
|
21
22
|
pnpm add @aws-sdk/client-sns
|
|
22
23
|
|
|
23
|
-
#
|
|
24
|
-
pnpm add
|
|
25
|
-
|
|
26
|
-
# Azure
|
|
27
|
-
pnpm add @azure/service-bus
|
|
24
|
+
# Local development (managed by Celerity CLI, but needed for direct usage)
|
|
25
|
+
pnpm add ioredis
|
|
28
26
|
```
|
|
29
27
|
|
|
30
28
|
## Status
|
|
31
29
|
|
|
32
|
-
This package
|
|
30
|
+
This package implements the `TopicClient` interface with providers for AWS SNS and Redis (local development). Support for Google Cloud Pub/Sub and Azure Service Bus Topics will be added in future releases.
|
|
33
31
|
|
|
34
32
|
## Part of the Celerity Framework
|
|
35
33
|
|
|
36
|
-
See [celerityframework.
|
|
34
|
+
See [celerityframework.io](https://celerityframework.io) for full documentation.
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
6
13
|
var __copyProps = (to, from, except, desc) => {
|
|
7
14
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
15
|
for (let key of __getOwnPropNames(from))
|
|
@@ -11,9 +18,458 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
11
18
|
}
|
|
12
19
|
return to;
|
|
13
20
|
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
14
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
30
|
|
|
16
31
|
// src/index.ts
|
|
17
32
|
var index_exports = {};
|
|
33
|
+
__export(index_exports, {
|
|
34
|
+
DEFAULT_TOPIC_TOKEN: () => DEFAULT_TOPIC_TOKEN,
|
|
35
|
+
RedisTopicClient: () => RedisTopicClient,
|
|
36
|
+
SNSTopicClient: () => SNSTopicClient,
|
|
37
|
+
Topic: () => Topic,
|
|
38
|
+
TopicClient: () => TopicClient,
|
|
39
|
+
TopicError: () => TopicError,
|
|
40
|
+
TopicLayer: () => TopicLayer,
|
|
41
|
+
createTopicClient: () => createTopicClient,
|
|
42
|
+
getTopic: () => getTopic,
|
|
43
|
+
topicToken: () => topicToken
|
|
44
|
+
});
|
|
18
45
|
module.exports = __toCommonJS(index_exports);
|
|
46
|
+
|
|
47
|
+
// src/types.ts
|
|
48
|
+
var TopicClient = /* @__PURE__ */ Symbol.for("TopicClient");
|
|
49
|
+
|
|
50
|
+
// src/providers/sns/sns-topic-client.ts
|
|
51
|
+
var import_client_sns2 = require("@aws-sdk/client-sns");
|
|
52
|
+
|
|
53
|
+
// src/providers/sns/sns-topic.ts
|
|
54
|
+
var import_debug = __toESM(require("debug"), 1);
|
|
55
|
+
var import_client_sns = require("@aws-sdk/client-sns");
|
|
56
|
+
|
|
57
|
+
// src/errors.ts
|
|
58
|
+
var TopicError = class extends Error {
|
|
59
|
+
static {
|
|
60
|
+
__name(this, "TopicError");
|
|
61
|
+
}
|
|
62
|
+
topic;
|
|
63
|
+
constructor(message, topic, options) {
|
|
64
|
+
super(message, options), this.topic = topic;
|
|
65
|
+
this.name = "TopicError";
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// src/providers/sns/sns-topic.ts
|
|
70
|
+
var debug = (0, import_debug.default)("celerity:topic:sns");
|
|
71
|
+
var SNS_MAX_BATCH_SIZE = 10;
|
|
72
|
+
var SNSTopic = class {
|
|
73
|
+
static {
|
|
74
|
+
__name(this, "SNSTopic");
|
|
75
|
+
}
|
|
76
|
+
topicArn;
|
|
77
|
+
client;
|
|
78
|
+
tracer;
|
|
79
|
+
constructor(topicArn, client, tracer) {
|
|
80
|
+
this.topicArn = topicArn;
|
|
81
|
+
this.client = client;
|
|
82
|
+
this.tracer = tracer;
|
|
83
|
+
}
|
|
84
|
+
async publish(body, options) {
|
|
85
|
+
debug("publish %s", this.topicArn);
|
|
86
|
+
return this.traced("celerity.topic.publish", {
|
|
87
|
+
"topic.arn": this.topicArn
|
|
88
|
+
}, async () => {
|
|
89
|
+
try {
|
|
90
|
+
const result = await this.client.send(new import_client_sns.PublishCommand({
|
|
91
|
+
TopicArn: this.topicArn,
|
|
92
|
+
Message: JSON.stringify(body),
|
|
93
|
+
MessageGroupId: options?.groupId,
|
|
94
|
+
MessageDeduplicationId: options?.deduplicationId,
|
|
95
|
+
Subject: options?.subject,
|
|
96
|
+
MessageAttributes: options?.attributes ? toSNSAttributes(options.attributes) : void 0
|
|
97
|
+
}));
|
|
98
|
+
return {
|
|
99
|
+
messageId: result.MessageId
|
|
100
|
+
};
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw new TopicError(`Failed to publish message to topic "${this.topicArn}"`, this.topicArn, {
|
|
103
|
+
cause: error
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
async publishBatch(entries) {
|
|
109
|
+
debug("publishBatch %s (%d entries)", this.topicArn, entries.length);
|
|
110
|
+
return this.traced("celerity.topic.publish_batch", {
|
|
111
|
+
"topic.arn": this.topicArn,
|
|
112
|
+
"topic.message_count": entries.length
|
|
113
|
+
}, async () => {
|
|
114
|
+
const successful = [];
|
|
115
|
+
const failed = [];
|
|
116
|
+
for (let i = 0; i < entries.length; i += SNS_MAX_BATCH_SIZE) {
|
|
117
|
+
const chunk = entries.slice(i, i + SNS_MAX_BATCH_SIZE);
|
|
118
|
+
const snsEntries = chunk.map((entry) => ({
|
|
119
|
+
Id: entry.id,
|
|
120
|
+
Message: JSON.stringify(entry.body),
|
|
121
|
+
MessageGroupId: entry.options?.groupId,
|
|
122
|
+
MessageDeduplicationId: entry.options?.deduplicationId,
|
|
123
|
+
Subject: entry.options?.subject,
|
|
124
|
+
MessageAttributes: entry.options?.attributes ? toSNSAttributes(entry.options.attributes) : void 0
|
|
125
|
+
}));
|
|
126
|
+
try {
|
|
127
|
+
const result = await this.client.send(new import_client_sns.PublishBatchCommand({
|
|
128
|
+
TopicArn: this.topicArn,
|
|
129
|
+
PublishBatchRequestEntries: snsEntries
|
|
130
|
+
}));
|
|
131
|
+
for (const s of result.Successful ?? []) {
|
|
132
|
+
successful.push({
|
|
133
|
+
id: s.Id,
|
|
134
|
+
messageId: s.MessageId
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
for (const f of result.Failed ?? []) {
|
|
138
|
+
failed.push({
|
|
139
|
+
id: f.Id,
|
|
140
|
+
code: f.Code,
|
|
141
|
+
message: f.Message ?? "Unknown error"
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
} catch (error) {
|
|
145
|
+
throw new TopicError(`Failed to publish message batch to topic "${this.topicArn}"`, this.topicArn, {
|
|
146
|
+
cause: error
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
successful,
|
|
152
|
+
failed
|
|
153
|
+
};
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
traced(name, attributes, fn) {
|
|
157
|
+
if (!this.tracer) return fn();
|
|
158
|
+
return this.tracer.withSpan(name, (span) => fn(span), attributes);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
function toSNSAttributes(attrs) {
|
|
162
|
+
const result = {};
|
|
163
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
164
|
+
result[key] = {
|
|
165
|
+
DataType: "String",
|
|
166
|
+
StringValue: value
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
return result;
|
|
170
|
+
}
|
|
171
|
+
__name(toSNSAttributes, "toSNSAttributes");
|
|
172
|
+
|
|
173
|
+
// src/providers/sns/config.ts
|
|
174
|
+
function captureSNSConfig() {
|
|
175
|
+
return {
|
|
176
|
+
region: process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,
|
|
177
|
+
endpoint: process.env.AWS_ENDPOINT_URL,
|
|
178
|
+
credentials: process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY ? {
|
|
179
|
+
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
|
180
|
+
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
|
|
181
|
+
} : void 0
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
__name(captureSNSConfig, "captureSNSConfig");
|
|
185
|
+
|
|
186
|
+
// src/providers/sns/sns-topic-client.ts
|
|
187
|
+
var SNSTopicClient = class {
|
|
188
|
+
static {
|
|
189
|
+
__name(this, "SNSTopicClient");
|
|
190
|
+
}
|
|
191
|
+
tracer;
|
|
192
|
+
client = null;
|
|
193
|
+
config;
|
|
194
|
+
constructor(config, tracer) {
|
|
195
|
+
this.tracer = tracer;
|
|
196
|
+
this.config = config ?? captureSNSConfig();
|
|
197
|
+
}
|
|
198
|
+
topic(name) {
|
|
199
|
+
return new SNSTopic(name, this.getClient(), this.tracer);
|
|
200
|
+
}
|
|
201
|
+
close() {
|
|
202
|
+
this.client?.destroy();
|
|
203
|
+
this.client = null;
|
|
204
|
+
}
|
|
205
|
+
getClient() {
|
|
206
|
+
if (!this.client) {
|
|
207
|
+
this.client = new import_client_sns2.SNSClient({
|
|
208
|
+
region: this.config.region,
|
|
209
|
+
endpoint: this.config.endpoint,
|
|
210
|
+
credentials: this.config.credentials
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return this.client;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// src/providers/redis/redis-topic.ts
|
|
218
|
+
var import_node_crypto = require("crypto");
|
|
219
|
+
var import_debug2 = __toESM(require("debug"), 1);
|
|
220
|
+
var debug2 = (0, import_debug2.default)("celerity:topic:redis");
|
|
221
|
+
var RedisTopic = class {
|
|
222
|
+
static {
|
|
223
|
+
__name(this, "RedisTopic");
|
|
224
|
+
}
|
|
225
|
+
channelName;
|
|
226
|
+
client;
|
|
227
|
+
tracer;
|
|
228
|
+
constructor(channelName, client, tracer) {
|
|
229
|
+
this.channelName = channelName;
|
|
230
|
+
this.client = client;
|
|
231
|
+
this.tracer = tracer;
|
|
232
|
+
}
|
|
233
|
+
async publish(body, options) {
|
|
234
|
+
debug2("publish %s", this.channelName);
|
|
235
|
+
return this.traced("celerity.topic.publish", {
|
|
236
|
+
"topic.channel": this.channelName
|
|
237
|
+
}, async () => {
|
|
238
|
+
try {
|
|
239
|
+
const messageId = (0, import_node_crypto.randomUUID)();
|
|
240
|
+
const payload = buildEnvelope(body, messageId, options);
|
|
241
|
+
await this.client.publish(this.channelName, payload);
|
|
242
|
+
return {
|
|
243
|
+
messageId
|
|
244
|
+
};
|
|
245
|
+
} catch (error) {
|
|
246
|
+
throw new TopicError(`Failed to publish message to channel "${this.channelName}"`, this.channelName, {
|
|
247
|
+
cause: error
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async publishBatch(entries) {
|
|
253
|
+
debug2("publishBatch %s (%d entries)", this.channelName, entries.length);
|
|
254
|
+
return this.traced("celerity.topic.publish_batch", {
|
|
255
|
+
"topic.channel": this.channelName,
|
|
256
|
+
"topic.message_count": entries.length
|
|
257
|
+
}, async () => {
|
|
258
|
+
const successful = [];
|
|
259
|
+
const failed = [];
|
|
260
|
+
const messageIds = [];
|
|
261
|
+
const pipeline = this.client.pipeline();
|
|
262
|
+
for (const entry of entries) {
|
|
263
|
+
const messageId = (0, import_node_crypto.randomUUID)();
|
|
264
|
+
messageIds.push(messageId);
|
|
265
|
+
const payload = buildEnvelope(entry.body, messageId, entry.options);
|
|
266
|
+
pipeline.publish(this.channelName, payload);
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
const results = await pipeline.exec();
|
|
270
|
+
if (!results) {
|
|
271
|
+
throw new Error("Pipeline returned null");
|
|
272
|
+
}
|
|
273
|
+
for (let i = 0; i < entries.length; i++) {
|
|
274
|
+
const [err] = results[i];
|
|
275
|
+
if (err) {
|
|
276
|
+
failed.push({
|
|
277
|
+
id: entries[i].id,
|
|
278
|
+
code: err.name ?? "PipelineError",
|
|
279
|
+
message: err.message
|
|
280
|
+
});
|
|
281
|
+
} else {
|
|
282
|
+
successful.push({
|
|
283
|
+
id: entries[i].id,
|
|
284
|
+
messageId: messageIds[i]
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
} catch (error) {
|
|
289
|
+
throw new TopicError(`Failed to publish message batch to channel "${this.channelName}"`, this.channelName, {
|
|
290
|
+
cause: error
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
successful,
|
|
295
|
+
failed
|
|
296
|
+
};
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
traced(name, attributes, fn) {
|
|
300
|
+
if (!this.tracer) return fn();
|
|
301
|
+
return this.tracer.withSpan(name, (span) => fn(span), attributes);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
function buildEnvelope(body, messageId, options) {
|
|
305
|
+
const envelope = {
|
|
306
|
+
body: JSON.stringify(body),
|
|
307
|
+
messageId
|
|
308
|
+
};
|
|
309
|
+
if (options?.subject) {
|
|
310
|
+
envelope.subject = options.subject;
|
|
311
|
+
}
|
|
312
|
+
if (options?.attributes && Object.keys(options.attributes).length > 0) {
|
|
313
|
+
envelope.attributes = options.attributes;
|
|
314
|
+
}
|
|
315
|
+
return JSON.stringify(envelope);
|
|
316
|
+
}
|
|
317
|
+
__name(buildEnvelope, "buildEnvelope");
|
|
318
|
+
|
|
319
|
+
// src/providers/redis/config.ts
|
|
320
|
+
var DEFAULT_REDIS_URL = "redis://localhost:6379";
|
|
321
|
+
function captureRedisConfig() {
|
|
322
|
+
return {
|
|
323
|
+
url: process.env.CELERITY_LOCAL_REDIS_URL ?? DEFAULT_REDIS_URL
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
__name(captureRedisConfig, "captureRedisConfig");
|
|
327
|
+
|
|
328
|
+
// src/providers/redis/redis-topic-client.ts
|
|
329
|
+
var RedisTopicClient = class {
|
|
330
|
+
static {
|
|
331
|
+
__name(this, "RedisTopicClient");
|
|
332
|
+
}
|
|
333
|
+
tracer;
|
|
334
|
+
client = null;
|
|
335
|
+
config;
|
|
336
|
+
constructor(config, tracer) {
|
|
337
|
+
this.tracer = tracer;
|
|
338
|
+
this.config = config ?? captureRedisConfig();
|
|
339
|
+
}
|
|
340
|
+
topic(name) {
|
|
341
|
+
return new RedisTopic(name, this.getClient(), this.tracer);
|
|
342
|
+
}
|
|
343
|
+
async close() {
|
|
344
|
+
if (this.client) {
|
|
345
|
+
await this.client.quit();
|
|
346
|
+
this.client = null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
getClient() {
|
|
350
|
+
if (!this.client) {
|
|
351
|
+
const Redis = require("ioredis").default ?? require("ioredis");
|
|
352
|
+
this.client = new Redis(this.config.url);
|
|
353
|
+
}
|
|
354
|
+
return this.client;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
// src/factory.ts
|
|
359
|
+
var import_config3 = require("@celerity-sdk/config");
|
|
360
|
+
function createTopicClient(options) {
|
|
361
|
+
const resolved = (0, import_config3.resolveConfig)("topic");
|
|
362
|
+
const provider = options?.provider ?? resolved.provider;
|
|
363
|
+
switch (provider) {
|
|
364
|
+
case "aws":
|
|
365
|
+
return new SNSTopicClient(options?.aws, options?.tracer);
|
|
366
|
+
// Local environments always use Redis pub/sub regardless of deploy target.
|
|
367
|
+
// The Celerity CLI manages the Redis instance and local-events sidecar.
|
|
368
|
+
case "local":
|
|
369
|
+
return new RedisTopicClient(options?.local, options?.tracer);
|
|
370
|
+
// case "gcp":
|
|
371
|
+
// v1: Google Cloud Pub/Sub
|
|
372
|
+
// case "azure":
|
|
373
|
+
// v1: Azure Service Bus Topics
|
|
374
|
+
default:
|
|
375
|
+
throw new Error(`Unsupported topic provider: "${provider}"`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
__name(createTopicClient, "createTopicClient");
|
|
379
|
+
|
|
380
|
+
// src/decorators.ts
|
|
381
|
+
var import_reflect_metadata = require("reflect-metadata");
|
|
382
|
+
var import_common = require("@celerity-sdk/common");
|
|
383
|
+
function topicToken(resourceName) {
|
|
384
|
+
return /* @__PURE__ */ Symbol.for(`celerity:topic:${resourceName}`);
|
|
385
|
+
}
|
|
386
|
+
__name(topicToken, "topicToken");
|
|
387
|
+
var DEFAULT_TOPIC_TOKEN = /* @__PURE__ */ Symbol.for("celerity:topic:default");
|
|
388
|
+
function Topic(resourceName) {
|
|
389
|
+
return (target, _propertyKey, parameterIndex) => {
|
|
390
|
+
const token = resourceName ? topicToken(resourceName) : DEFAULT_TOPIC_TOKEN;
|
|
391
|
+
const existing = Reflect.getOwnMetadata(import_common.INJECT_METADATA, target) ?? /* @__PURE__ */ new Map();
|
|
392
|
+
existing.set(parameterIndex, token);
|
|
393
|
+
Reflect.defineMetadata(import_common.INJECT_METADATA, existing, target);
|
|
394
|
+
if (resourceName) {
|
|
395
|
+
const resources = Reflect.getOwnMetadata(import_common.USE_RESOURCE_METADATA, target) ?? [];
|
|
396
|
+
if (!resources.includes(resourceName)) {
|
|
397
|
+
Reflect.defineMetadata(import_common.USE_RESOURCE_METADATA, [
|
|
398
|
+
...resources,
|
|
399
|
+
resourceName
|
|
400
|
+
], target);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
__name(Topic, "Topic");
|
|
406
|
+
|
|
407
|
+
// src/helpers.ts
|
|
408
|
+
function getTopic(container, resourceName) {
|
|
409
|
+
const token = resourceName ? topicToken(resourceName) : DEFAULT_TOPIC_TOKEN;
|
|
410
|
+
return container.resolve(token);
|
|
411
|
+
}
|
|
412
|
+
__name(getTopic, "getTopic");
|
|
413
|
+
|
|
414
|
+
// src/layer.ts
|
|
415
|
+
var import_debug3 = __toESM(require("debug"), 1);
|
|
416
|
+
var import_common2 = require("@celerity-sdk/common");
|
|
417
|
+
var import_config4 = require("@celerity-sdk/config");
|
|
418
|
+
var debug3 = (0, import_debug3.default)("celerity:topic");
|
|
419
|
+
var TopicLayer = class {
|
|
420
|
+
static {
|
|
421
|
+
__name(this, "TopicLayer");
|
|
422
|
+
}
|
|
423
|
+
initialized = false;
|
|
424
|
+
async handle(context, next) {
|
|
425
|
+
if (!this.initialized) {
|
|
426
|
+
const tracer = context.container.has(import_common2.TRACER_TOKEN) ? await context.container.resolve(import_common2.TRACER_TOKEN) : void 0;
|
|
427
|
+
const client = createTopicClient({
|
|
428
|
+
tracer
|
|
429
|
+
});
|
|
430
|
+
debug3("registering TopicClient");
|
|
431
|
+
context.container.register("TopicClient", {
|
|
432
|
+
useValue: client
|
|
433
|
+
});
|
|
434
|
+
const links = (0, import_config4.captureResourceLinks)();
|
|
435
|
+
const topicLinks = (0, import_config4.getLinksOfType)(links, "topic");
|
|
436
|
+
if (topicLinks.size > 0) {
|
|
437
|
+
const configService = await context.container.resolve(import_common2.CONFIG_SERVICE_TOKEN);
|
|
438
|
+
const resourceConfig = configService.namespace(import_config4.RESOURCE_CONFIG_NAMESPACE);
|
|
439
|
+
for (const [resourceName, configKey] of topicLinks) {
|
|
440
|
+
const actualName = await resourceConfig.getOrThrow(configKey);
|
|
441
|
+
debug3("registered topic resource %s \u2192 %s", resourceName, actualName);
|
|
442
|
+
context.container.register(topicToken(resourceName), {
|
|
443
|
+
useValue: client.topic(actualName)
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
if (topicLinks.size === 1) {
|
|
447
|
+
const [, configKey] = [
|
|
448
|
+
...topicLinks.entries()
|
|
449
|
+
][0];
|
|
450
|
+
const actualName = await resourceConfig.getOrThrow(configKey);
|
|
451
|
+
debug3("registered default topic \u2192 %s", actualName);
|
|
452
|
+
context.container.register(DEFAULT_TOPIC_TOKEN, {
|
|
453
|
+
useValue: client.topic(actualName)
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
this.initialized = true;
|
|
458
|
+
}
|
|
459
|
+
return next();
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
463
|
+
0 && (module.exports = {
|
|
464
|
+
DEFAULT_TOPIC_TOKEN,
|
|
465
|
+
RedisTopicClient,
|
|
466
|
+
SNSTopicClient,
|
|
467
|
+
Topic,
|
|
468
|
+
TopicClient,
|
|
469
|
+
TopicError,
|
|
470
|
+
TopicLayer,
|
|
471
|
+
createTopicClient,
|
|
472
|
+
getTopic,
|
|
473
|
+
topicToken
|
|
474
|
+
});
|
|
19
475
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// TODO: Implement pub/sub topic abstraction.\n// Key modules: interfaces (TopicClient), factory (createTopicClient), providers (sns, google-pubsub, azure-service-bus)\nexport {};\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/providers/sns/sns-topic-client.ts","../src/providers/sns/sns-topic.ts","../src/errors.ts","../src/providers/sns/config.ts","../src/providers/redis/redis-topic.ts","../src/providers/redis/config.ts","../src/providers/redis/redis-topic-client.ts","../src/factory.ts","../src/decorators.ts","../src/helpers.ts","../src/layer.ts"],"sourcesContent":["// Core types\nexport {\n TopicClient,\n type PublishOptions,\n type PublishResult,\n type BatchPublishEntry,\n type BatchPublishResult,\n type BatchPublishSuccess,\n type BatchPublishFailure,\n} from \"./types\";\n\nexport { SNSTopicClient } from \"./providers/sns/sns-topic-client\";\nexport type { SNSTopicConfig } from \"./providers/sns/types\";\nexport { RedisTopicClient } from \"./providers/redis/redis-topic-client\";\nexport type { RedisTopicConfig } from \"./providers/redis/types\";\n\nexport { createTopicClient } from \"./factory\";\nexport type { CreateTopicClientOptions } from \"./factory\";\n\nexport { Topic, topicToken, DEFAULT_TOPIC_TOKEN } from \"./decorators\";\n\nexport { getTopic } from \"./helpers\";\n\nexport { TopicLayer } from \"./layer\";\n\nexport { TopicError } from \"./errors\";\n","import type { Closeable } from \"@celerity-sdk/types\";\n\nexport const TopicClient = Symbol.for(\"TopicClient\");\n\n/**\n * A topic client abstraction for pub/sub topics. Provides access to named\n * topics, each representing a logical destination for published messages.\n */\nexport interface TopicClient extends Closeable {\n /**\n * Retrieves a topic instance by its name. The returned topic is a lightweight\n * handle — no network calls are made until an operation is invoked.\n *\n * @param name The topic identifier (SNS topic ARN, Redis channel name, etc.).\n */\n topic(name: string): Topic;\n}\n\n/**\n * A topic represents a logical pub/sub destination. It provides methods for\n * publishing messages individually or in batches. The Celerity runtime handles\n * all subscription and consumption — this interface is producer-only.\n */\nexport interface Topic {\n /**\n * Publish a single message to the topic. The body is serialized to JSON.\n *\n * @param body The message body (serialized to JSON string for transport).\n * @param options Optional publish parameters such as FIFO ordering or subject.\n * @returns A promise that resolves to the publish result with the provider-assigned message ID.\n */\n publish<T = Record<string, unknown>>(body: T, options?: PublishOptions): Promise<PublishResult>;\n\n /**\n * Publish multiple messages in a single batch. The provider may impose batch\n * size limits (e.g. SNS limits to 10 per request) — the implementation\n * handles chunking transparently.\n *\n * @param entries The batch of messages to publish, each with a caller-assigned ID for correlation.\n * @returns A promise that resolves to the batch result with successful and failed entries.\n */\n publishBatch<T = Record<string, unknown>>(\n entries: BatchPublishEntry<T>[],\n ): Promise<BatchPublishResult>;\n}\n\n/**\n * Options for the publish and publishBatch operations.\n */\nexport type PublishOptions = {\n /** Message group ID for FIFO topics (SNS: MessageGroupId, Pub/Sub: ordering key). */\n groupId?: string;\n /** Deduplication ID for FIFO topics. */\n deduplicationId?: string;\n /** Message subject (SNS: Subject). */\n subject?: string;\n /** String key-value message attributes (metadata sent alongside the body). */\n attributes?: Record<string, string>;\n};\n\n/**\n * The result of a single publish call.\n */\nexport type PublishResult = {\n /** The provider-assigned message identifier. */\n messageId: string;\n};\n\n/**\n * A single entry in a batch publish request.\n */\nexport type BatchPublishEntry<T = Record<string, unknown>> = {\n /** Caller-assigned ID for correlating results within the batch. */\n id: string;\n /** The message body (serialized to JSON). */\n body: T;\n /** Per-message publish options. */\n options?: PublishOptions;\n};\n\n/**\n * The result of a batch publish operation.\n */\nexport type BatchPublishResult = {\n /** Entries that were published successfully. */\n successful: BatchPublishSuccess[];\n /** Entries that failed. */\n failed: BatchPublishFailure[];\n};\n\n/**\n * A successfully published entry from a batch operation.\n */\nexport type BatchPublishSuccess = {\n /** The caller-assigned entry ID. */\n id: string;\n /** The provider-assigned message ID. */\n messageId: string;\n};\n\n/**\n * A failed entry from a batch operation.\n */\nexport type BatchPublishFailure = {\n /** The caller-assigned entry ID. */\n id: string;\n /** Provider error code. */\n code: string;\n /** Human-readable error message. */\n message: string;\n};\n","import { SNSClient } from \"@aws-sdk/client-sns\";\nimport type { CelerityTracer } from \"@celerity-sdk/types\";\nimport type { TopicClient, Topic } from \"../../types\";\nimport { SNSTopic } from \"./sns-topic\";\nimport type { SNSTopicConfig } from \"./types\";\nimport { captureSNSConfig } from \"./config\";\n\nexport class SNSTopicClient implements TopicClient {\n private client: SNSClient | null = null;\n private readonly config: SNSTopicConfig;\n\n constructor(\n config?: SNSTopicConfig,\n private readonly tracer?: CelerityTracer,\n ) {\n this.config = config ?? captureSNSConfig();\n }\n\n topic(name: string): Topic {\n return new SNSTopic(name, this.getClient(), this.tracer);\n }\n\n close(): void {\n this.client?.destroy();\n this.client = null;\n }\n\n private getClient(): SNSClient {\n if (!this.client) {\n this.client = new SNSClient({\n region: this.config.region,\n endpoint: this.config.endpoint,\n credentials: this.config.credentials,\n });\n }\n return this.client;\n }\n}\n","import createDebug from \"debug\";\nimport {\n type SNSClient,\n PublishCommand,\n PublishBatchCommand,\n type MessageAttributeValue,\n type PublishBatchRequestEntry,\n} from \"@aws-sdk/client-sns\";\nimport type { CelerityTracer, CeleritySpan } from \"@celerity-sdk/types\";\nimport type {\n Topic,\n PublishOptions,\n PublishResult,\n BatchPublishEntry,\n BatchPublishResult,\n BatchPublishSuccess,\n BatchPublishFailure,\n} from \"../../types\";\nimport { TopicError } from \"../../errors\";\n\nconst debug = createDebug(\"celerity:topic:sns\");\n\nconst SNS_MAX_BATCH_SIZE = 10;\n\nexport class SNSTopic implements Topic {\n constructor(\n private readonly topicArn: string,\n private readonly client: SNSClient,\n private readonly tracer?: CelerityTracer,\n ) {}\n\n async publish<T = Record<string, unknown>>(\n body: T,\n options?: PublishOptions,\n ): Promise<PublishResult> {\n debug(\"publish %s\", this.topicArn);\n return this.traced(\"celerity.topic.publish\", { \"topic.arn\": this.topicArn }, async () => {\n try {\n const result = await this.client.send(\n new PublishCommand({\n TopicArn: this.topicArn,\n Message: JSON.stringify(body),\n MessageGroupId: options?.groupId,\n MessageDeduplicationId: options?.deduplicationId,\n Subject: options?.subject,\n MessageAttributes: options?.attributes\n ? toSNSAttributes(options.attributes)\n : undefined,\n }),\n );\n return { messageId: result.MessageId! };\n } catch (error) {\n throw new TopicError(\n `Failed to publish message to topic \"${this.topicArn}\"`,\n this.topicArn,\n { cause: error },\n );\n }\n });\n }\n\n async publishBatch<T = Record<string, unknown>>(\n entries: BatchPublishEntry<T>[],\n ): Promise<BatchPublishResult> {\n debug(\"publishBatch %s (%d entries)\", this.topicArn, entries.length);\n return this.traced(\n \"celerity.topic.publish_batch\",\n { \"topic.arn\": this.topicArn, \"topic.message_count\": entries.length },\n async () => {\n const successful: BatchPublishSuccess[] = [];\n const failed: BatchPublishFailure[] = [];\n\n // Auto-chunk into groups of 10 (SNS limit)\n for (let i = 0; i < entries.length; i += SNS_MAX_BATCH_SIZE) {\n const chunk = entries.slice(i, i + SNS_MAX_BATCH_SIZE);\n const snsEntries: PublishBatchRequestEntry[] = chunk.map((entry) => ({\n Id: entry.id,\n Message: JSON.stringify(entry.body),\n MessageGroupId: entry.options?.groupId,\n MessageDeduplicationId: entry.options?.deduplicationId,\n Subject: entry.options?.subject,\n MessageAttributes: entry.options?.attributes\n ? toSNSAttributes(entry.options.attributes)\n : undefined,\n }));\n\n try {\n const result = await this.client.send(\n new PublishBatchCommand({\n TopicArn: this.topicArn,\n PublishBatchRequestEntries: snsEntries,\n }),\n );\n\n for (const s of result.Successful ?? []) {\n successful.push({ id: s.Id!, messageId: s.MessageId! });\n }\n for (const f of result.Failed ?? []) {\n failed.push({ id: f.Id!, code: f.Code!, message: f.Message ?? \"Unknown error\" });\n }\n } catch (error) {\n throw new TopicError(\n `Failed to publish message batch to topic \"${this.topicArn}\"`,\n this.topicArn,\n { cause: error },\n );\n }\n }\n\n return { successful, failed };\n },\n );\n }\n\n private traced<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: (span?: CeleritySpan) => Promise<T>,\n ): Promise<T> {\n if (!this.tracer) return fn();\n return this.tracer.withSpan(name, (span) => fn(span), attributes);\n }\n}\n\nfunction toSNSAttributes(attrs: Record<string, string>): Record<string, MessageAttributeValue> {\n const result: Record<string, MessageAttributeValue> = {};\n for (const [key, value] of Object.entries(attrs)) {\n result[key] = { DataType: \"String\", StringValue: value };\n }\n return result;\n}\n","/**\n * Base error for topic operations. Wraps provider SDK errors and includes\n * the topic identifier for context.\n */\nexport class TopicError extends Error {\n constructor(\n message: string,\n public readonly topic: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"TopicError\";\n }\n}\n","import type { SNSTopicConfig } from \"./types\";\n\n/**\n * Captures SNS configuration from environment variables.\n * This is the only place that reads `process.env` for SNS config.\n */\nexport function captureSNSConfig(): SNSTopicConfig {\n return {\n region: process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,\n endpoint: process.env.AWS_ENDPOINT_URL,\n credentials:\n process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY\n ? {\n accessKeyId: process.env.AWS_ACCESS_KEY_ID,\n secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,\n }\n : undefined,\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport createDebug from \"debug\";\nimport type Redis from \"ioredis\";\nimport type { CelerityTracer, CeleritySpan } from \"@celerity-sdk/types\";\nimport type {\n Topic,\n PublishOptions,\n PublishResult,\n BatchPublishEntry,\n BatchPublishResult,\n BatchPublishSuccess,\n BatchPublishFailure,\n} from \"../../types\";\nimport { TopicError } from \"../../errors\";\n\nconst debug = createDebug(\"celerity:topic:redis\");\n\nexport class RedisTopic implements Topic {\n constructor(\n private readonly channelName: string,\n private readonly client: Redis,\n private readonly tracer?: CelerityTracer,\n ) {}\n\n async publish<T = Record<string, unknown>>(\n body: T,\n options?: PublishOptions,\n ): Promise<PublishResult> {\n debug(\"publish %s\", this.channelName);\n return this.traced(\n \"celerity.topic.publish\",\n { \"topic.channel\": this.channelName },\n async () => {\n try {\n const messageId = randomUUID();\n const payload = buildEnvelope(body, messageId, options);\n await this.client.publish(this.channelName, payload);\n return { messageId };\n } catch (error) {\n throw new TopicError(\n `Failed to publish message to channel \"${this.channelName}\"`,\n this.channelName,\n { cause: error },\n );\n }\n },\n );\n }\n\n async publishBatch<T = Record<string, unknown>>(\n entries: BatchPublishEntry<T>[],\n ): Promise<BatchPublishResult> {\n debug(\"publishBatch %s (%d entries)\", this.channelName, entries.length);\n return this.traced(\n \"celerity.topic.publish_batch\",\n { \"topic.channel\": this.channelName, \"topic.message_count\": entries.length },\n async () => {\n const successful: BatchPublishSuccess[] = [];\n const failed: BatchPublishFailure[] = [];\n\n const messageIds: string[] = [];\n const pipeline = this.client.pipeline();\n for (const entry of entries) {\n const messageId = randomUUID();\n messageIds.push(messageId);\n const payload = buildEnvelope(entry.body, messageId, entry.options);\n pipeline.publish(this.channelName, payload);\n }\n\n try {\n const results = await pipeline.exec();\n if (!results) {\n throw new Error(\"Pipeline returned null\");\n }\n\n for (let i = 0; i < entries.length; i++) {\n const [err] = results[i];\n if (err) {\n failed.push({\n id: entries[i].id,\n code: err.name ?? \"PipelineError\",\n message: err.message,\n });\n } else {\n successful.push({\n id: entries[i].id,\n messageId: messageIds[i],\n });\n }\n }\n } catch (error) {\n throw new TopicError(\n `Failed to publish message batch to channel \"${this.channelName}\"`,\n this.channelName,\n { cause: error },\n );\n }\n\n return { successful, failed };\n },\n );\n }\n\n private traced<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: (span?: CeleritySpan) => Promise<T>,\n ): Promise<T> {\n if (!this.tracer) return fn();\n return this.tracer.withSpan(name, (span) => fn(span), attributes);\n }\n}\n\n/**\n * Builds the JSON envelope published to the pub/sub channel.\n * The local-events bridge parses this envelope and extracts individual\n * fields when writing to target consumer streams.\n *\n * `messageId`, `subject`, and `attributes` are included in the envelope.\n * `groupId` and `deduplicationId` are silently ignored — ordering is\n * inherent in the single-instance bridge architecture.\n */\nfunction buildEnvelope<T>(body: T, messageId: string, options?: PublishOptions): string {\n const envelope: Record<string, unknown> = {\n body: JSON.stringify(body),\n messageId,\n };\n\n if (options?.subject) {\n envelope.subject = options.subject;\n }\n if (options?.attributes && Object.keys(options.attributes).length > 0) {\n envelope.attributes = options.attributes;\n }\n\n return JSON.stringify(envelope);\n}\n","import type { RedisTopicConfig } from \"./types\";\n\nconst DEFAULT_REDIS_URL = \"redis://localhost:6379\";\n\n/**\n * Captures Redis configuration from environment variables.\n * This is the only place that reads `process.env` for Redis config.\n */\nexport function captureRedisConfig(): RedisTopicConfig {\n return {\n url: process.env.CELERITY_LOCAL_REDIS_URL ?? DEFAULT_REDIS_URL,\n };\n}\n","import type { CelerityTracer } from \"@celerity-sdk/types\";\nimport type { TopicClient, Topic } from \"../../types\";\nimport { RedisTopic } from \"./redis-topic\";\nimport type { RedisTopicConfig } from \"./types\";\nimport { captureRedisConfig } from \"./config\";\n\nexport class RedisTopicClient implements TopicClient {\n private client: import(\"ioredis\").default | null = null;\n private readonly config: RedisTopicConfig;\n\n constructor(\n config?: RedisTopicConfig,\n private readonly tracer?: CelerityTracer,\n ) {\n this.config = config ?? captureRedisConfig();\n }\n\n topic(name: string): Topic {\n return new RedisTopic(name, this.getClient(), this.tracer);\n }\n\n async close(): Promise<void> {\n if (this.client) {\n await this.client.quit();\n this.client = null;\n }\n }\n\n private getClient(): import(\"ioredis\").default {\n if (!this.client) {\n // Dynamic require to avoid bundling ioredis when not used.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const Redis = require(\"ioredis\").default ?? require(\"ioredis\");\n this.client = new Redis(this.config.url);\n }\n return this.client!;\n }\n}\n","import { resolveConfig } from \"@celerity-sdk/config\";\nimport type { CelerityTracer } from \"@celerity-sdk/types\";\nimport type { TopicClient } from \"./types\";\nimport type { SNSTopicConfig } from \"./providers/sns/types\";\nimport type { RedisTopicConfig } from \"./providers/redis/types\";\nimport { SNSTopicClient } from \"./providers/sns/sns-topic-client\";\nimport { RedisTopicClient } from \"./providers/redis/redis-topic-client\";\n\nexport type CreateTopicClientOptions = {\n /** Override provider selection. If omitted, derived from platform config. */\n provider?: \"aws\" | \"local\" | \"gcp\" | \"azure\";\n /** SNS-specific configuration overrides. */\n aws?: SNSTopicConfig;\n /** Redis-specific configuration overrides (local environment). */\n local?: RedisTopicConfig;\n /** Optional tracer for Celerity-level span instrumentation. */\n tracer?: CelerityTracer;\n};\n\nexport function createTopicClient(options?: CreateTopicClientOptions): TopicClient {\n const resolved = resolveConfig(\"topic\");\n const provider = options?.provider ?? resolved.provider;\n\n switch (provider) {\n case \"aws\":\n return new SNSTopicClient(options?.aws, options?.tracer);\n // Local environments always use Redis pub/sub regardless of deploy target.\n // The Celerity CLI manages the Redis instance and local-events sidecar.\n case \"local\":\n return new RedisTopicClient(options?.local, options?.tracer);\n // case \"gcp\":\n // v1: Google Cloud Pub/Sub\n // case \"azure\":\n // v1: Azure Service Bus Topics\n default:\n throw new Error(`Unsupported topic provider: \"${provider}\"`);\n }\n}\n","import \"reflect-metadata\";\nimport { INJECT_METADATA, USE_RESOURCE_METADATA } from \"@celerity-sdk/common\";\nimport type { Topic as TopicType } from \"./types\";\n\n// Re-declare as interface so the type merges with the decorator function below.\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface Topic extends TopicType {}\n\nexport function topicToken(resourceName: string): symbol {\n return Symbol.for(`celerity:topic:${resourceName}`);\n}\n\nexport const DEFAULT_TOPIC_TOKEN = Symbol.for(\"celerity:topic:default\");\n\n/**\n * Parameter decorator that injects a {@link Topic} instance for the given\n * blueprint resource. Writes both DI injection metadata and CLI resource-ref\n * metadata using well-known `Symbol.for()` keys (no dependency on core).\n *\n * When `resourceName` is omitted, the default topic token is used — this\n * auto-resolves when exactly one topic resource exists.\n *\n * @example\n * ```ts\n * @Controller(\"/orders\")\n * class OrderController {\n * constructor(@Topic(\"orderEvents\") private events: Topic) {}\n * }\n * ```\n */\nexport function Topic(resourceName?: string): ParameterDecorator {\n return (target, _propertyKey, parameterIndex) => {\n const token = resourceName ? topicToken(resourceName) : DEFAULT_TOPIC_TOKEN;\n const existing: Map<number, unknown> =\n Reflect.getOwnMetadata(INJECT_METADATA, target) ?? new Map();\n existing.set(parameterIndex, token);\n Reflect.defineMetadata(INJECT_METADATA, existing, target);\n\n if (resourceName) {\n const resources: string[] = Reflect.getOwnMetadata(USE_RESOURCE_METADATA, target) ?? [];\n if (!resources.includes(resourceName)) {\n Reflect.defineMetadata(USE_RESOURCE_METADATA, [...resources, resourceName], target);\n }\n }\n };\n}\n","import type { ServiceContainer } from \"@celerity-sdk/types\";\nimport type { Topic } from \"./types\";\nimport { topicToken, DEFAULT_TOPIC_TOKEN } from \"./decorators\";\n\n/**\n * Resolves a {@link Topic} instance from the DI container.\n * For function-based handlers where parameter decorators aren't available.\n *\n * @param container - The service container (typically `context.container`).\n * @param resourceName - The blueprint resource name. Omit when exactly one\n * topic resource exists to use the default.\n *\n * @example\n * ```ts\n * const handler = createHttpHandler(async (req, ctx) => {\n * const events = await getTopic(ctx.container, \"orderEvents\");\n * await events.publish({ orderId: \"123\", action: \"created\" });\n * });\n * ```\n */\nexport function getTopic(container: ServiceContainer, resourceName?: string): Promise<Topic> {\n const token = resourceName ? topicToken(resourceName) : DEFAULT_TOPIC_TOKEN;\n return container.resolve<Topic>(token);\n}\n","import createDebug from \"debug\";\nimport type { CelerityLayer, BaseHandlerContext, CelerityTracer } from \"@celerity-sdk/types\";\nimport { TRACER_TOKEN, CONFIG_SERVICE_TOKEN } from \"@celerity-sdk/common\";\nimport {\n type ConfigService,\n captureResourceLinks,\n getLinksOfType,\n RESOURCE_CONFIG_NAMESPACE,\n} from \"@celerity-sdk/config\";\nimport { createTopicClient } from \"./factory\";\nimport { topicToken, DEFAULT_TOPIC_TOKEN } from \"./decorators\";\n\nconst debug = createDebug(\"celerity:topic\");\n\n/**\n * System layer that auto-registers {@link TopicClient} and per-resource\n * {@link Topic} handles in the DI container.\n *\n * Reads resource link topology from `CELERITY_RESOURCE_LINKS` and resolves\n * actual topic ARNs / channel names from the ConfigService \"resources\" namespace.\n * Must run after ConfigLayer in the layer pipeline.\n */\nexport class TopicLayer implements CelerityLayer<BaseHandlerContext> {\n private initialized = false;\n\n async handle(context: BaseHandlerContext, next: () => Promise<unknown>): Promise<unknown> {\n if (!this.initialized) {\n const tracer = context.container.has(TRACER_TOKEN)\n ? await context.container.resolve<CelerityTracer>(TRACER_TOKEN)\n : undefined;\n\n const client = createTopicClient({ tracer });\n debug(\"registering TopicClient\");\n context.container.register(\"TopicClient\", { useValue: client });\n\n const links = captureResourceLinks();\n const topicLinks = getLinksOfType(links, \"topic\");\n\n if (topicLinks.size > 0) {\n const configService = await context.container.resolve<ConfigService>(CONFIG_SERVICE_TOKEN);\n const resourceConfig = configService.namespace(RESOURCE_CONFIG_NAMESPACE);\n\n for (const [resourceName, configKey] of topicLinks) {\n const actualName = await resourceConfig.getOrThrow(configKey);\n debug(\"registered topic resource %s → %s\", resourceName, actualName);\n context.container.register(topicToken(resourceName), {\n useValue: client.topic(actualName),\n });\n }\n\n if (topicLinks.size === 1) {\n const [, configKey] = [...topicLinks.entries()][0];\n const actualName = await resourceConfig.getOrThrow(configKey);\n debug(\"registered default topic → %s\", actualName);\n context.container.register(DEFAULT_TOPIC_TOKEN, {\n useValue: client.topic(actualName),\n });\n }\n }\n\n this.initialized = true;\n }\n\n return next();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;ACEO,IAAMA,cAAcC,uBAAOC,IAAI,aAAA;;;ACFtC,IAAAC,qBAA0B;;;ACA1B,mBAAwB;AACxB,wBAMO;;;ACHA,IAAMC,aAAN,cAAyBC,MAAAA;EAJhC,OAIgCA;;;;EAC9B,YACEC,SACgBC,OAChBC,SACA;AACA,UAAMF,SAASE,OAAAA,GAAAA,KAHCD,QAAAA;AAIhB,SAAKE,OAAO;EACd;AACF;;;ADOA,IAAMC,YAAQC,aAAAA,SAAY,oBAAA;AAE1B,IAAMC,qBAAqB;AAEpB,IAAMC,WAAN,MAAMA;EAxBb,OAwBaA;;;;;;EACX,YACmBC,UACAC,QACAC,QACjB;SAHiBF,WAAAA;SACAC,SAAAA;SACAC,SAAAA;EAChB;EAEH,MAAMC,QACJC,MACAC,SACwB;AACxBT,UAAM,cAAc,KAAKI,QAAQ;AACjC,WAAO,KAAKM,OAAO,0BAA0B;MAAE,aAAa,KAAKN;IAAS,GAAG,YAAA;AAC3E,UAAI;AACF,cAAMO,SAAS,MAAM,KAAKN,OAAOO,KAC/B,IAAIC,iCAAe;UACjBC,UAAU,KAAKV;UACfW,SAASC,KAAKC,UAAUT,IAAAA;UACxBU,gBAAgBT,SAASU;UACzBC,wBAAwBX,SAASY;UACjCC,SAASb,SAASc;UAClBC,mBAAmBf,SAASgB,aACxBC,gBAAgBjB,QAAQg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E,WAAWE,OAAO,GAAG;AACvB,cAAMC,gBAAgB,MAAMjB,QAAQG,UAAUG,QAAuBY,mCAAAA;AACrE,cAAMC,iBAAiBF,cAAcG,UAAUC,wCAAAA;AAE/C,mBAAW,CAACC,cAAcC,SAAAA,KAAcT,YAAY;AAClD,gBAAMU,aAAa,MAAML,eAAeM,WAAWF,SAAAA;AACnD5B,UAAAA,OAAM,0CAAqC2B,cAAcE,UAAAA;AACzDxB,kBAAQG,UAAUO,SAASgB,WAAWJ,YAAAA,GAAe;YACnDX,UAAUH,OAAOmB,MAAMH,UAAAA;UACzB,CAAA;QACF;AAEA,YAAIV,WAAWE,SAAS,GAAG;AACzB,gBAAM,CAAA,EAAGO,SAAAA,IAAa;eAAIT,WAAWc,QAAO;YAAI,CAAA;AAChD,gBAAMJ,aAAa,MAAML,eAAeM,WAAWF,SAAAA;AACnD5B,UAAAA,OAAM,sCAAiC6B,UAAAA;AACvCxB,kBAAQG,UAAUO,SAASmB,qBAAqB;YAC9ClB,UAAUH,OAAOmB,MAAMH,UAAAA;UACzB,CAAA;QACF;MACF;AAEA,WAAK1B,cAAc;IACrB;AAEA,WAAOG,KAAAA;EACT;AACF;","names":["TopicClient","Symbol","for","import_client_sns","TopicError","Error","message","topic","options","name","debug","createDebug","SNS_MAX_BATCH_SIZE","SNSTopic","topicArn","client","tracer","publish","body","options","traced","result","send","PublishCommand","TopicArn","Message","JSON","stringify","MessageGroupId","groupId","MessageDeduplicationId","deduplicationId","Subject","subject","MessageAttributes","attributes","toSNSAttributes","undefined","messageId","MessageId","error","TopicError","cause","publishBatch","entries","length","successful","failed","i","chunk","slice","snsEntries","map","entry","Id","id","PublishBatchCommand","PublishBatchRequestEntries","s","Successful","push","f","Failed","code","Code","message","name","fn","withSpan","span","attrs","key","value","Object","DataType","StringValue","captureSNSConfig","region","process","env","AWS_REGION","AWS_DEFAULT_REGION","endpoint","AWS_ENDPOINT_URL","credentials","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","accessKeyId","secretAccessKey","undefined","SNSTopicClient","client","config","tracer","captureSNSConfig","topic","name","SNSTopic","getClient","close","destroy","SNSClient","region","endpoint","credentials","import_debug","debug","createDebug","RedisTopic","channelName","client","tracer","publish","body","options","traced","messageId","randomUUID","payload","buildEnvelope","error","TopicError","cause","publishBatch","entries","length","successful","failed","messageIds","pipeline","entry","push","results","exec","Error","i","err","id","code","name","message","attributes","fn","withSpan","span","envelope","JSON","stringify","subject","Object","keys","DEFAULT_REDIS_URL","captureRedisConfig","url","process","env","CELERITY_LOCAL_REDIS_URL","RedisTopicClient","client","config","tracer","captureRedisConfig","topic","name","RedisTopic","getClient","close","quit","Redis","require","default","url","import_config","createTopicClient","options","resolved","resolveConfig","provider","SNSTopicClient","aws","tracer","RedisTopicClient","local","Error","topicToken","resourceName","Symbol","for","DEFAULT_TOPIC_TOKEN","Topic","target","_propertyKey","parameterIndex","token","existing","Reflect","getOwnMetadata","INJECT_METADATA","Map","set","defineMetadata","resources","USE_RESOURCE_METADATA","includes","getTopic","container","resourceName","token","topicToken","DEFAULT_TOPIC_TOKEN","resolve","import_debug","import_common","import_config","debug","createDebug","TopicLayer","initialized","handle","context","next","tracer","container","has","TRACER_TOKEN","resolve","undefined","client","createTopicClient","register","useValue","links","captureResourceLinks","topicLinks","getLinksOfType","size","configService","CONFIG_SERVICE_TOKEN","resourceConfig","namespace","RESOURCE_CONFIG_NAMESPACE","resourceName","configKey","actualName","getOrThrow","topicToken","topic","entries","DEFAULT_TOPIC_TOKEN"]}
|