@streamsy/core 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +421 -0
- package/dist/index.js +1831 -0
- package/package.json +41 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1831 @@
|
|
|
1
|
+
//#region src/protocol/helpers/clock.ts
|
|
2
|
+
const systemClock = {
|
|
3
|
+
now: () => Date.now(),
|
|
4
|
+
date: (value) => new Date(value ?? Date.now())
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/protocol/helpers/producer-idempotency-service.ts
|
|
9
|
+
function validateProducer(state, epoch, seq) {
|
|
10
|
+
if (!state) return seq === 0 ? {
|
|
11
|
+
kind: "accepted",
|
|
12
|
+
proposedState: {
|
|
13
|
+
epoch,
|
|
14
|
+
lastSeq: 0
|
|
15
|
+
}
|
|
16
|
+
} : {
|
|
17
|
+
kind: "gap",
|
|
18
|
+
expectedSeq: 0,
|
|
19
|
+
receivedSeq: seq
|
|
20
|
+
};
|
|
21
|
+
if (epoch < state.epoch) return {
|
|
22
|
+
kind: "stale-epoch",
|
|
23
|
+
currentEpoch: state.epoch
|
|
24
|
+
};
|
|
25
|
+
if (epoch > state.epoch) return seq === 0 ? {
|
|
26
|
+
kind: "accepted",
|
|
27
|
+
proposedState: {
|
|
28
|
+
epoch,
|
|
29
|
+
lastSeq: 0
|
|
30
|
+
}
|
|
31
|
+
} : { kind: "invalid-epoch-seq" };
|
|
32
|
+
if (seq <= state.lastSeq) return {
|
|
33
|
+
kind: "duplicate",
|
|
34
|
+
lastSeq: state.lastSeq,
|
|
35
|
+
epoch: state.epoch
|
|
36
|
+
};
|
|
37
|
+
if (seq === state.lastSeq + 1) return {
|
|
38
|
+
kind: "accepted",
|
|
39
|
+
proposedState: {
|
|
40
|
+
epoch,
|
|
41
|
+
lastSeq: seq
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
kind: "gap",
|
|
46
|
+
expectedSeq: state.lastSeq + 1,
|
|
47
|
+
receivedSeq: seq
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function rejectionToAppendResult(rejection, currentOffset, isClosed) {
|
|
51
|
+
switch (rejection.kind) {
|
|
52
|
+
case "duplicate": return {
|
|
53
|
+
status: "duplicate",
|
|
54
|
+
nextOffset: currentOffset,
|
|
55
|
+
producerEpoch: rejection.epoch,
|
|
56
|
+
producerSeq: rejection.lastSeq,
|
|
57
|
+
closed: isClosed
|
|
58
|
+
};
|
|
59
|
+
case "stale-epoch": return {
|
|
60
|
+
status: "stale-epoch",
|
|
61
|
+
currentEpoch: rejection.currentEpoch
|
|
62
|
+
};
|
|
63
|
+
case "gap": return {
|
|
64
|
+
status: "producer-gap",
|
|
65
|
+
expectedSeq: rejection.expectedSeq,
|
|
66
|
+
receivedSeq: rejection.receivedSeq
|
|
67
|
+
};
|
|
68
|
+
case "invalid-epoch-seq": return { status: "invalid-epoch-seq" };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
var ProducerIdempotencyService = class {
|
|
72
|
+
constructor(deps) {
|
|
73
|
+
this.deps = deps;
|
|
74
|
+
}
|
|
75
|
+
load(producerId) {
|
|
76
|
+
return this.deps.store.getProducerState(producerId);
|
|
77
|
+
}
|
|
78
|
+
validate(state, epoch, seq) {
|
|
79
|
+
return validateProducer(state, epoch, seq);
|
|
80
|
+
}
|
|
81
|
+
async persistIfAccepted(producer, validation) {
|
|
82
|
+
if (!producer || validation?.kind !== "accepted") return void 0;
|
|
83
|
+
await this.deps.store.setProducerState(producer.producerId, validation.proposedState);
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/types/factory.ts
|
|
90
|
+
/** Internal/storage-level unsupported-feature error. */
|
|
91
|
+
var NotSupportedError = class extends Error {
|
|
92
|
+
constructor(feature, message) {
|
|
93
|
+
super(message ?? `Feature not supported: ${feature}`);
|
|
94
|
+
this.feature = feature;
|
|
95
|
+
this.name = "NotSupportedError";
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
/** Convenience constructor for a {@link NotSupportedResult}. */
|
|
99
|
+
function notSupported(feature, message) {
|
|
100
|
+
return message === void 0 ? {
|
|
101
|
+
status: "not-supported",
|
|
102
|
+
feature
|
|
103
|
+
} : {
|
|
104
|
+
status: "not-supported",
|
|
105
|
+
feature,
|
|
106
|
+
message
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** Convenience constructor for a storage-level unsupported-feature error. */
|
|
110
|
+
function unsupported(feature, message) {
|
|
111
|
+
return new NotSupportedError(feature, message);
|
|
112
|
+
}
|
|
113
|
+
/** Type guard for storage-level unsupported-feature errors. */
|
|
114
|
+
function isNotSupportedError(value) {
|
|
115
|
+
return value instanceof NotSupportedError;
|
|
116
|
+
}
|
|
117
|
+
/** Convert storage-level unsupported-feature errors to public protocol results. */
|
|
118
|
+
function notSupportedFromError(error) {
|
|
119
|
+
return notSupported(error.feature, error.message);
|
|
120
|
+
}
|
|
121
|
+
/** Type guard for protocol results that may be a {@link NotSupportedResult}. */
|
|
122
|
+
function isNotSupported(value) {
|
|
123
|
+
if (typeof value !== "object" || value === null) return false;
|
|
124
|
+
const status = value.status;
|
|
125
|
+
return status === "not-supported";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/protocol/helpers/content-type-matcher.ts
|
|
130
|
+
/**
|
|
131
|
+
* Content type normalization and matching for the durable streams protocol.
|
|
132
|
+
*
|
|
133
|
+
* Responsibilities:
|
|
134
|
+
*
|
|
135
|
+
* - `normalizeContentType` lowercases, strips RFC 7231 parameters (everything
|
|
136
|
+
* after the first `;`), and trims surrounding whitespace.
|
|
137
|
+
* - `contentTypeMatches` compares two content types by equality of their
|
|
138
|
+
* normalized forms.
|
|
139
|
+
*
|
|
140
|
+
* Used by `AppendService` for append content-type conflicts, by
|
|
141
|
+
* `CreateStreamService` via `configMatches` for idempotent create checks, and
|
|
142
|
+
* by `ForkService` for fork content-type compatibility.
|
|
143
|
+
*/
|
|
144
|
+
function normalizeContentType(ct) {
|
|
145
|
+
return ct.toLowerCase().split(";")[0].trim();
|
|
146
|
+
}
|
|
147
|
+
function contentTypeMatches(expected, actual) {
|
|
148
|
+
return normalizeContentType(expected) === normalizeContentType(actual);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
//#endregion
|
|
152
|
+
//#region src/protocol/helpers/message-framer.ts
|
|
153
|
+
/**
|
|
154
|
+
* Body framing for the durable streams protocol.
|
|
155
|
+
*
|
|
156
|
+
* Responsibilities:
|
|
157
|
+
*
|
|
158
|
+
* - Non-JSON content types pass the original bytes through as a single
|
|
159
|
+
* message.
|
|
160
|
+
* - JSON content types are decoded and re-encoded:
|
|
161
|
+
* - JSON object input becomes one canonical `JSON.stringify(parsed)` message.
|
|
162
|
+
* - JSON array input produces one message per item.
|
|
163
|
+
* - Empty JSON array produces zero messages.
|
|
164
|
+
* - The JSON branch is selected by `contentType.toLowerCase().startsWith("application/json")`,
|
|
165
|
+
* without parameter stripping.
|
|
166
|
+
* - Invalid JSON propagates the underlying `JSON.parse` error.
|
|
167
|
+
*
|
|
168
|
+
* Used by `AppendService`, `CreateStreamService`, and `ForkService` before
|
|
169
|
+
* incoming request bodies are persisted as stored messages.
|
|
170
|
+
*/
|
|
171
|
+
function frameMessages(data, contentType) {
|
|
172
|
+
if (!contentType.toLowerCase().startsWith("application/json")) return [data];
|
|
173
|
+
const parsed = JSON.parse(new TextDecoder().decode(data));
|
|
174
|
+
if (Array.isArray(parsed)) return parsed.length === 0 ? [] : parsed.map((item) => new TextEncoder().encode(JSON.stringify(item)));
|
|
175
|
+
return [new TextEncoder().encode(JSON.stringify(parsed))];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/protocol/append-service.ts
|
|
180
|
+
function appendedResult(nextOffset, validation, closed) {
|
|
181
|
+
if (validation?.kind === "accepted") return {
|
|
182
|
+
status: "appended",
|
|
183
|
+
nextOffset,
|
|
184
|
+
producerEpoch: validation.proposedState.epoch,
|
|
185
|
+
producerSeq: validation.proposedState.lastSeq,
|
|
186
|
+
closed
|
|
187
|
+
};
|
|
188
|
+
return {
|
|
189
|
+
status: "appended",
|
|
190
|
+
nextOffset,
|
|
191
|
+
closed
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
var AppendService = class {
|
|
195
|
+
constructor(deps) {
|
|
196
|
+
this.deps = deps;
|
|
197
|
+
}
|
|
198
|
+
async execute(record, options) {
|
|
199
|
+
if (!record) return { status: "not-found" };
|
|
200
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
201
|
+
const isClosed = record.lifecycle.closed === true;
|
|
202
|
+
const wantClose = options.close === true;
|
|
203
|
+
const hasBody = options.data.byteLength > 0;
|
|
204
|
+
let producerValidation;
|
|
205
|
+
if (options.producer) {
|
|
206
|
+
const state = await this.deps.producerIdempotency.load(options.producer.producerId);
|
|
207
|
+
if (isNotSupported(state)) return state;
|
|
208
|
+
producerValidation = this.deps.producerIdempotency.validate(state, options.producer.producerEpoch, options.producer.producerSeq);
|
|
209
|
+
if (producerValidation.kind !== "accepted") return rejectionToAppendResult(producerValidation, record.currentOffset, isClosed);
|
|
210
|
+
}
|
|
211
|
+
if (wantClose && !hasBody) {
|
|
212
|
+
if (isClosed) return {
|
|
213
|
+
status: "appended",
|
|
214
|
+
nextOffset: record.currentOffset,
|
|
215
|
+
closed: true
|
|
216
|
+
};
|
|
217
|
+
const nextOffset$1 = await this.deps.mutators.closeRecord(record, [], options.seq);
|
|
218
|
+
const persisted$1 = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
|
|
219
|
+
if (persisted$1?.status === "not-supported") return persisted$1;
|
|
220
|
+
return appendedResult(nextOffset$1, producerValidation, true);
|
|
221
|
+
}
|
|
222
|
+
if (isClosed) return {
|
|
223
|
+
status: "conflict",
|
|
224
|
+
conflictReason: "closed",
|
|
225
|
+
closed: true,
|
|
226
|
+
nextOffset: record.currentOffset
|
|
227
|
+
};
|
|
228
|
+
if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
|
|
229
|
+
status: "conflict",
|
|
230
|
+
conflictReason: "content-type"
|
|
231
|
+
};
|
|
232
|
+
if (options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return {
|
|
233
|
+
status: "conflict",
|
|
234
|
+
conflictReason: "sequence"
|
|
235
|
+
};
|
|
236
|
+
const processed = frameMessages(options.data, record.config.contentType);
|
|
237
|
+
const nextOffset = wantClose ? await this.deps.mutators.closeRecord(record, processed, options.seq) : await this.deps.mutators.appendMessages(record, processed, options.seq);
|
|
238
|
+
const persisted = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
|
|
239
|
+
if (persisted?.status === "not-supported") return persisted;
|
|
240
|
+
return appendedResult(nextOffset, producerValidation, wantClose);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
//#endregion
|
|
245
|
+
//#region src/protocol/helpers/offset-generator.ts
|
|
246
|
+
const ZERO_OFFSET = `${"0".repeat(16)}_${"0".repeat(16)}`;
|
|
247
|
+
const OFFSET_REGEX = /^\d{1,16}_\d{1,16}$/;
|
|
248
|
+
function isValidOffset(offset) {
|
|
249
|
+
return OFFSET_REGEX.test(offset);
|
|
250
|
+
}
|
|
251
|
+
function compareOffsets(a, b) {
|
|
252
|
+
return a === b ? 0 : a < b ? -1 : 1;
|
|
253
|
+
}
|
|
254
|
+
function formatCounter(counter) {
|
|
255
|
+
return `${String(counter).padStart(16, "0")}_${"0".repeat(16)}`;
|
|
256
|
+
}
|
|
257
|
+
function parseCounter(offset) {
|
|
258
|
+
return parseInt(offset.split("_")[0] ?? "0", 10);
|
|
259
|
+
}
|
|
260
|
+
function allocate(counter, count) {
|
|
261
|
+
const offsets = [];
|
|
262
|
+
for (let i = 1; i <= count; i++) offsets.push(formatCounter(counter + i));
|
|
263
|
+
const endCounter = counter + count;
|
|
264
|
+
return {
|
|
265
|
+
endCounter,
|
|
266
|
+
offsets,
|
|
267
|
+
nextOffset: count > 0 ? formatCounter(endCounter) : formatCounter(counter)
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
//#endregion
|
|
272
|
+
//#region src/protocol/read-service.ts
|
|
273
|
+
function normalizeReadOffset(offset) {
|
|
274
|
+
return !offset || offset === "-1" ? void 0 : offset;
|
|
275
|
+
}
|
|
276
|
+
var ReadService = class {
|
|
277
|
+
constructor(deps) {
|
|
278
|
+
this.deps = deps;
|
|
279
|
+
}
|
|
280
|
+
async execute(record, options) {
|
|
281
|
+
if (!record) return { status: "not-found" };
|
|
282
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
283
|
+
const messages = await this.deps.readChain(record, normalizeReadOffset(options.offset));
|
|
284
|
+
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
285
|
+
const nextOffset = compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset;
|
|
286
|
+
const upToDate = nextOffset === record.currentOffset;
|
|
287
|
+
return {
|
|
288
|
+
status: "ok",
|
|
289
|
+
messages,
|
|
290
|
+
nextOffset,
|
|
291
|
+
upToDate,
|
|
292
|
+
closed: record.lifecycle.closed === true && upToDate
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/protocol/helpers/cursor-generator.ts
|
|
299
|
+
const CURSOR_EPOCH_MS = new Date("2024-10-09T00:00:00.000Z").getTime();
|
|
300
|
+
const CURSOR_INTERVAL_MS = 2e4;
|
|
301
|
+
function generateCursor(clock, previous, random = Math.random) {
|
|
302
|
+
const currentInterval = Math.floor((clock.now() - CURSOR_EPOCH_MS) / CURSOR_INTERVAL_MS);
|
|
303
|
+
if (!previous) return String(currentInterval);
|
|
304
|
+
const previousInterval = parseInt(previous, 10);
|
|
305
|
+
if (previousInterval < currentInterval) return String(currentInterval);
|
|
306
|
+
return String(previousInterval + Math.max(1, Math.floor(random() * 180)));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region src/protocol/live-read-service.ts
|
|
311
|
+
var LiveReadService = class {
|
|
312
|
+
constructor(deps) {
|
|
313
|
+
this.deps = deps;
|
|
314
|
+
}
|
|
315
|
+
async execute(record, options) {
|
|
316
|
+
if (!record) return {
|
|
317
|
+
status: "not-found",
|
|
318
|
+
messages: [],
|
|
319
|
+
nextOffset: "",
|
|
320
|
+
upToDate: false,
|
|
321
|
+
cursor: ""
|
|
322
|
+
};
|
|
323
|
+
if (record.lifecycle.softDeleted) return {
|
|
324
|
+
status: "gone",
|
|
325
|
+
messages: [],
|
|
326
|
+
nextOffset: "",
|
|
327
|
+
upToDate: false,
|
|
328
|
+
cursor: ""
|
|
329
|
+
};
|
|
330
|
+
if (record.lifecycle.closed) {
|
|
331
|
+
const messages = await this.deps.readChain(record, options.offset);
|
|
332
|
+
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
333
|
+
const nextOffset = compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset;
|
|
334
|
+
return {
|
|
335
|
+
status: messages.length > 0 ? "ok" : "timeout",
|
|
336
|
+
messages,
|
|
337
|
+
nextOffset,
|
|
338
|
+
upToDate: true,
|
|
339
|
+
cursor: generateCursor(this.deps.clock, options.cursor),
|
|
340
|
+
closed: nextOffset === record.currentOffset
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
if (record.lifecycle.forkedFrom && record.lifecycle.forkOffset && compareOffsets(options.offset, record.lifecycle.forkOffset) < 0) {
|
|
344
|
+
const messages = await this.deps.readChain(record, options.offset);
|
|
345
|
+
const lastOffset = messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset;
|
|
346
|
+
return {
|
|
347
|
+
status: "ok",
|
|
348
|
+
messages,
|
|
349
|
+
nextOffset: compareOffsets(lastOffset, record.currentOffset) > 0 ? lastOffset : record.currentOffset,
|
|
350
|
+
upToDate: true,
|
|
351
|
+
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
await this.deps.touch(record);
|
|
355
|
+
const immediate = await this.deps.readOwn(options.offset);
|
|
356
|
+
if (immediate.messages.length > 0) return {
|
|
357
|
+
status: "ok",
|
|
358
|
+
...immediate,
|
|
359
|
+
upToDate: true,
|
|
360
|
+
cursor: generateCursor(this.deps.clock, options.cursor)
|
|
361
|
+
};
|
|
362
|
+
const wait = await this.deps.store.waitForEvent({
|
|
363
|
+
timeoutMs: this.deps.longPollTimeoutMs,
|
|
364
|
+
signal: options.signal
|
|
365
|
+
});
|
|
366
|
+
const latest = await this.deps.store.getRecord();
|
|
367
|
+
if (!latest) return {
|
|
368
|
+
status: "not-found",
|
|
369
|
+
messages: [],
|
|
370
|
+
nextOffset: "",
|
|
371
|
+
upToDate: false,
|
|
372
|
+
cursor: ""
|
|
373
|
+
};
|
|
374
|
+
if (latest.lifecycle.softDeleted) return {
|
|
375
|
+
status: "gone",
|
|
376
|
+
messages: [],
|
|
377
|
+
nextOffset: "",
|
|
378
|
+
upToDate: false,
|
|
379
|
+
cursor: ""
|
|
380
|
+
};
|
|
381
|
+
const r = await this.deps.readOwn(options.offset);
|
|
382
|
+
const reachedTail = r.nextOffset === latest.currentOffset;
|
|
383
|
+
const hasMessages = r.messages.length > 0;
|
|
384
|
+
return {
|
|
385
|
+
status: hasMessages ? "ok" : wait.status === "timeout" || wait.status === "aborted" ? "timeout" : "ok",
|
|
386
|
+
messages: r.messages,
|
|
387
|
+
nextOffset: r.nextOffset,
|
|
388
|
+
upToDate: true,
|
|
389
|
+
cursor: generateCursor(this.deps.clock, options.cursor),
|
|
390
|
+
closed: latest.lifecycle.closed === true && reachedTail
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
//#endregion
|
|
396
|
+
//#region src/protocol/helpers/expiry-policy.ts
|
|
397
|
+
var ExpiryPolicy = class {
|
|
398
|
+
constructor(deps) {
|
|
399
|
+
this.deps = deps;
|
|
400
|
+
}
|
|
401
|
+
computeExpiresAtMs(config) {
|
|
402
|
+
if (config.ttlSeconds !== void 0) return this.deps.clock.now() + config.ttlSeconds * 1e3;
|
|
403
|
+
if (config.expiresAt) return this.deps.clock.date(config.expiresAt).getTime();
|
|
404
|
+
return void 0;
|
|
405
|
+
}
|
|
406
|
+
async touch(stream, record, reason) {
|
|
407
|
+
if (record.config.ttlSeconds === void 0) return;
|
|
408
|
+
if (reason === "live-read") return;
|
|
409
|
+
const expiresAtMs = this.deps.clock.now() + record.config.ttlSeconds * 1e3;
|
|
410
|
+
await stream.updateRecord({ lifecycle: { expiresAtMs } });
|
|
411
|
+
await stream.scheduleExpiry(expiresAtMs, () => this.deps.onScheduledExpiry(stream.id));
|
|
412
|
+
}
|
|
413
|
+
async scheduleExpiry(record) {
|
|
414
|
+
const at = record.lifecycle.expiresAtMs;
|
|
415
|
+
if (at !== void 0) {
|
|
416
|
+
const stream = await this.deps.resolve(record.id);
|
|
417
|
+
await stream.scheduleExpiry(at, () => this.deps.onScheduledExpiry(record.id));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Lazily expire the stream if its deadline has passed, returning the current
|
|
422
|
+
* record. The storage stream is already bound to an id, so callers should pass
|
|
423
|
+
* that stream instead of threading a duplicate stream id alongside it. When
|
|
424
|
+
* the stream expires the record is re-read so the returned value reflects the
|
|
425
|
+
* post-expiry state.
|
|
426
|
+
*/
|
|
427
|
+
async expireIfNeeded(stream) {
|
|
428
|
+
const record = await stream.getRecord();
|
|
429
|
+
if (record && this.isExpired(record)) {
|
|
430
|
+
await this.deps.onScheduledExpiry(stream.id);
|
|
431
|
+
return stream.getRecord();
|
|
432
|
+
}
|
|
433
|
+
return record;
|
|
434
|
+
}
|
|
435
|
+
isExpired(record) {
|
|
436
|
+
const at = record.lifecycle.expiresAtMs;
|
|
437
|
+
return at !== void 0 && at <= this.deps.clock.now();
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
//#endregion
|
|
442
|
+
//#region src/protocol/helpers/create-config-matcher.ts
|
|
443
|
+
function configMatches(existing, options) {
|
|
444
|
+
const contentType = options.contentType ?? existing.config.contentType ?? "application/octet-stream";
|
|
445
|
+
if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
|
|
446
|
+
if ((options.forkedFrom ?? void 0) !== existing.lifecycle.forkedFrom) return false;
|
|
447
|
+
if (options.forkOffset !== void 0 && options.forkOffset !== existing.lifecycle.forkOffset) return false;
|
|
448
|
+
const inheritedForkExpiry = options.forkedFrom && options.ttlSeconds === void 0 && options.expiresAt === void 0;
|
|
449
|
+
if (existing.config.ttlSeconds !== options.ttlSeconds && !inheritedForkExpiry) return false;
|
|
450
|
+
if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
|
|
451
|
+
return existing.lifecycle.closed === true === (options.closed === true);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
//#endregion
|
|
455
|
+
//#region src/protocol/create-stream-service.ts
|
|
456
|
+
var CreateStreamService = class {
|
|
457
|
+
constructor(deps) {
|
|
458
|
+
this.deps = deps;
|
|
459
|
+
}
|
|
460
|
+
async execute(record, options) {
|
|
461
|
+
if (record) return this.resultForExisting(record, options);
|
|
462
|
+
if (options.forkedFrom) return this.deps.mutators.createFork(options);
|
|
463
|
+
const contentType = options.contentType ?? "application/octet-stream";
|
|
464
|
+
const initialMessages = options.initialData ? frameMessages(options.initialData, contentType) : [];
|
|
465
|
+
const wantClosed = options.closed === true;
|
|
466
|
+
const newRecord = this.deps.mutators.newRecord(contentType, options);
|
|
467
|
+
const createResult = await this.deps.store.createRecord(newRecord);
|
|
468
|
+
if (createResult.status === "exists") return this.resultForExisting(createResult.record, options);
|
|
469
|
+
await this.deps.mutators.scheduleExpiry(newRecord);
|
|
470
|
+
let final = newRecord.currentOffset;
|
|
471
|
+
if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(newRecord, initialMessages);
|
|
472
|
+
if (wantClosed) {
|
|
473
|
+
const latest = await this.deps.store.getRecord() ?? newRecord;
|
|
474
|
+
final = await this.deps.mutators.closeRecord(latest, []);
|
|
475
|
+
}
|
|
476
|
+
return {
|
|
477
|
+
status: "created",
|
|
478
|
+
nextOffset: final,
|
|
479
|
+
contentType,
|
|
480
|
+
closed: wantClosed
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
resultForExisting(existing, options) {
|
|
484
|
+
if (existing.lifecycle.softDeleted) return {
|
|
485
|
+
status: "conflict",
|
|
486
|
+
nextOffset: "",
|
|
487
|
+
contentType: "",
|
|
488
|
+
conflictReason: "soft-deleted"
|
|
489
|
+
};
|
|
490
|
+
if (!configMatches(existing, options)) return {
|
|
491
|
+
status: "conflict",
|
|
492
|
+
nextOffset: "",
|
|
493
|
+
contentType: "",
|
|
494
|
+
conflictReason: "config-mismatch"
|
|
495
|
+
};
|
|
496
|
+
return {
|
|
497
|
+
status: "exists",
|
|
498
|
+
nextOffset: existing.currentOffset,
|
|
499
|
+
contentType: existing.config.contentType,
|
|
500
|
+
closed: existing.lifecycle.closed === true
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
//#endregion
|
|
506
|
+
//#region src/protocol/helpers/fork-service.ts
|
|
507
|
+
function resolveForkExpiry(opts, source) {
|
|
508
|
+
if (opts.ttlSeconds !== void 0) return { ttlSeconds: opts.ttlSeconds };
|
|
509
|
+
if (opts.expiresAt) return { expiresAt: opts.expiresAt };
|
|
510
|
+
if (source.config.ttlSeconds !== void 0) return { ttlSeconds: source.config.ttlSeconds };
|
|
511
|
+
if (source.config.expiresAt) return { expiresAt: source.config.expiresAt };
|
|
512
|
+
return {};
|
|
513
|
+
}
|
|
514
|
+
var ForkService = class {
|
|
515
|
+
constructor(deps) {
|
|
516
|
+
this.deps = deps;
|
|
517
|
+
}
|
|
518
|
+
async execute(targetStream, options) {
|
|
519
|
+
const sourcePath = options.forkedFrom;
|
|
520
|
+
const sourceStream = await this.deps.resolve(sourcePath);
|
|
521
|
+
await this.deps.mutators.expireIfNeeded(sourceStream);
|
|
522
|
+
const source = await sourceStream.getRecord();
|
|
523
|
+
if (!source) return {
|
|
524
|
+
status: "not-found",
|
|
525
|
+
nextOffset: "",
|
|
526
|
+
contentType: "",
|
|
527
|
+
errorMessage: `Source stream not found: ${sourcePath}`
|
|
528
|
+
};
|
|
529
|
+
if (source.lifecycle.softDeleted) return {
|
|
530
|
+
status: "conflict",
|
|
531
|
+
nextOffset: "",
|
|
532
|
+
contentType: "",
|
|
533
|
+
conflictReason: "fork-source-soft-deleted",
|
|
534
|
+
errorMessage: `Source stream is soft-deleted: ${sourcePath}`
|
|
535
|
+
};
|
|
536
|
+
const forkOffset = options.forkOffset ?? source.currentOffset;
|
|
537
|
+
if (!isValidOffset(forkOffset)) return {
|
|
538
|
+
status: "bad-request",
|
|
539
|
+
nextOffset: "",
|
|
540
|
+
contentType: "",
|
|
541
|
+
errorMessage: "Invalid Stream-Fork-Offset format"
|
|
542
|
+
};
|
|
543
|
+
if (compareOffsets(forkOffset, ZERO_OFFSET) < 0 || compareOffsets(forkOffset, source.currentOffset) > 0) return {
|
|
544
|
+
status: "bad-request",
|
|
545
|
+
nextOffset: "",
|
|
546
|
+
contentType: "",
|
|
547
|
+
errorMessage: "Stream-Fork-Offset exceeds source tail"
|
|
548
|
+
};
|
|
549
|
+
let contentType = options.contentType;
|
|
550
|
+
if (!contentType || contentType.trim() === "") contentType = source.config.contentType;
|
|
551
|
+
else if (!contentTypeMatches(contentType, source.config.contentType)) return {
|
|
552
|
+
status: "conflict",
|
|
553
|
+
nextOffset: "",
|
|
554
|
+
contentType: "",
|
|
555
|
+
conflictReason: "fork-content-type",
|
|
556
|
+
errorMessage: "Fork Content-Type does not match source"
|
|
557
|
+
};
|
|
558
|
+
const expiry = resolveForkExpiry(options, source);
|
|
559
|
+
const record = this.deps.mutators.newRecord(targetStream, contentType, {
|
|
560
|
+
...options,
|
|
561
|
+
...expiry
|
|
562
|
+
}, {
|
|
563
|
+
forkedFrom: sourcePath,
|
|
564
|
+
forkOffset
|
|
565
|
+
});
|
|
566
|
+
const initialMessages = options.initialData ? frameMessages(options.initialData, contentType) : [];
|
|
567
|
+
const createResult = await targetStream.createRecord(record);
|
|
568
|
+
if (createResult.status === "created") await sourceStream.incrementChildRefCount();
|
|
569
|
+
if (createResult.status === "exists") return {
|
|
570
|
+
status: "conflict",
|
|
571
|
+
nextOffset: "",
|
|
572
|
+
contentType: "",
|
|
573
|
+
conflictReason: "config-mismatch",
|
|
574
|
+
errorMessage: `Stream already exists: ${targetStream.id}`
|
|
575
|
+
};
|
|
576
|
+
await this.deps.mutators.scheduleExpiry(record);
|
|
577
|
+
let final = record.currentOffset;
|
|
578
|
+
if (initialMessages.length > 0) final = await this.deps.mutators.appendMessages(record, initialMessages);
|
|
579
|
+
return {
|
|
580
|
+
status: "created",
|
|
581
|
+
nextOffset: final,
|
|
582
|
+
contentType
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
//#endregion
|
|
588
|
+
//#region src/protocol/helpers/stream-gc-service.ts
|
|
589
|
+
var StreamGcService = class {
|
|
590
|
+
constructor(deps) {
|
|
591
|
+
this.deps = deps;
|
|
592
|
+
}
|
|
593
|
+
async deleteStream(stream) {
|
|
594
|
+
const record = await stream.getRecord();
|
|
595
|
+
if (!record) return { status: "not-found" };
|
|
596
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
597
|
+
if (record.lifecycle.childRefCount > 0) {
|
|
598
|
+
await stream.updateRecord({ lifecycle: { softDeleted: true } });
|
|
599
|
+
await stream.notify("soft-deleted");
|
|
600
|
+
return { status: "ok" };
|
|
601
|
+
}
|
|
602
|
+
await this.purgeWithCascade(stream, record);
|
|
603
|
+
return { status: "ok" };
|
|
604
|
+
}
|
|
605
|
+
async handleScheduledExpiry(streamId) {
|
|
606
|
+
const stream = await this.deps.resolve(streamId);
|
|
607
|
+
const record = await stream.getRecord();
|
|
608
|
+
if (!record) return;
|
|
609
|
+
if (!this.deps.mutators.isExpired(record)) return;
|
|
610
|
+
if (record.lifecycle.childRefCount > 0) {
|
|
611
|
+
await stream.updateRecord({ lifecycle: { softDeleted: true } });
|
|
612
|
+
await stream.notify("soft-deleted");
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
await this.purgeWithCascade(stream, record);
|
|
616
|
+
}
|
|
617
|
+
async purgeWithCascade(stream, record) {
|
|
618
|
+
await stream.cancelExpiry();
|
|
619
|
+
await stream.deleteMessages();
|
|
620
|
+
await stream.deleteProducerStates();
|
|
621
|
+
await stream.deleteRecord();
|
|
622
|
+
await stream.notify("deleted");
|
|
623
|
+
const parentId = record.lifecycle.forkedFrom;
|
|
624
|
+
if (!parentId) return;
|
|
625
|
+
const parentStream = await this.deps.resolve(parentId);
|
|
626
|
+
const newRefCount = await parentStream.decrementChildRefCount();
|
|
627
|
+
const parent = await parentStream.getRecord();
|
|
628
|
+
if (parent && newRefCount === 0 && parent.lifecycle.softDeleted) await this.purgeWithCascade(parentStream, parent);
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
//#endregion
|
|
633
|
+
//#region src/protocol/storage/stream-message-reader.ts
|
|
634
|
+
var StreamMessageReader = class {
|
|
635
|
+
constructor(deps) {
|
|
636
|
+
this.deps = deps;
|
|
637
|
+
}
|
|
638
|
+
async readChain(record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
639
|
+
return this.readChainFor(this.deps.stream, record, afterOffset, capOffset, touchOwnTtl);
|
|
640
|
+
}
|
|
641
|
+
async readChainFor(stream, record, afterOffset, capOffset, touchOwnTtl = true) {
|
|
642
|
+
const out = [];
|
|
643
|
+
if (record.lifecycle.forkedFrom && record.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, record.lifecycle.forkOffset) < 0)) {
|
|
644
|
+
const sourceStream = await this.deps.resolve(record.lifecycle.forkedFrom);
|
|
645
|
+
const source = await sourceStream.getRecord();
|
|
646
|
+
if (source) {
|
|
647
|
+
const upstreamCap = capOffset && compareOffsets(capOffset, record.lifecycle.forkOffset) < 0 ? capOffset : record.lifecycle.forkOffset;
|
|
648
|
+
out.push(...await this.readChainFor(sourceStream, source, afterOffset, upstreamCap, false));
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (touchOwnTtl) await this.deps.expiryPolicy.touch(stream, record, "read");
|
|
652
|
+
const ownStart = record.lifecycle.forkOffset && (afterOffset === void 0 || compareOffsets(afterOffset, record.lifecycle.forkOffset) < 0) ? record.lifecycle.forkOffset : afterOffset;
|
|
653
|
+
const own = await stream.listMessages({
|
|
654
|
+
after: ownStart,
|
|
655
|
+
until: capOffset
|
|
656
|
+
});
|
|
657
|
+
out.push(...own);
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
async readOwn(after) {
|
|
661
|
+
const stream = this.deps.stream;
|
|
662
|
+
const record = await stream.getRecord();
|
|
663
|
+
if (!record) return {
|
|
664
|
+
messages: [],
|
|
665
|
+
nextOffset: ""
|
|
666
|
+
};
|
|
667
|
+
const messages = await stream.listMessages({ after });
|
|
668
|
+
return {
|
|
669
|
+
messages,
|
|
670
|
+
nextOffset: messages.length > 0 ? messages[messages.length - 1].offset : record.currentOffset
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
//#endregion
|
|
676
|
+
//#region src/protocol/storage/stream-message-writer.ts
|
|
677
|
+
var StreamMessageWriter = class {
|
|
678
|
+
constructor(deps) {
|
|
679
|
+
this.deps = deps;
|
|
680
|
+
}
|
|
681
|
+
async appendMessages(record, data, seq) {
|
|
682
|
+
await this.deps.expiryPolicy.touch(this.deps.stream, record, "append");
|
|
683
|
+
const allocation = allocate(record.counter, data.length);
|
|
684
|
+
const now = this.deps.clock.now();
|
|
685
|
+
const messages = data.map((bytes, i) => ({
|
|
686
|
+
data: bytes,
|
|
687
|
+
offset: allocation.offsets[i],
|
|
688
|
+
timestamp: now
|
|
689
|
+
}));
|
|
690
|
+
if (messages.length > 0) await this.deps.stream.appendMessages(messages);
|
|
691
|
+
await this.deps.stream.updateRecord({
|
|
692
|
+
currentOffset: allocation.nextOffset,
|
|
693
|
+
counter: allocation.endCounter,
|
|
694
|
+
lifecycle: seq ? { lastSeq: seq } : void 0
|
|
695
|
+
});
|
|
696
|
+
await this.deps.stream.notify("message");
|
|
697
|
+
return allocation.nextOffset;
|
|
698
|
+
}
|
|
699
|
+
async closeRecord(record, data, seq) {
|
|
700
|
+
let latest = record;
|
|
701
|
+
let nextOffset = record.currentOffset;
|
|
702
|
+
if (data.length > 0) {
|
|
703
|
+
nextOffset = await this.appendMessages(record, data, seq);
|
|
704
|
+
latest = await this.deps.stream.getRecord() ?? record;
|
|
705
|
+
} else await this.deps.expiryPolicy.touch(this.deps.stream, record, "close");
|
|
706
|
+
await this.deps.stream.updateRecord({
|
|
707
|
+
lifecycle: {
|
|
708
|
+
closed: true,
|
|
709
|
+
closedAt: this.deps.clock.now(),
|
|
710
|
+
...seq ? { lastSeq: seq } : {}
|
|
711
|
+
},
|
|
712
|
+
currentOffset: nextOffset,
|
|
713
|
+
counter: latest.counter
|
|
714
|
+
});
|
|
715
|
+
await this.deps.stream.notify("closed");
|
|
716
|
+
return nextOffset;
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
//#endregion
|
|
721
|
+
//#region src/protocol/storage/stream-record-factory.ts
|
|
722
|
+
var StreamRecordFactory = class {
|
|
723
|
+
constructor(deps) {
|
|
724
|
+
this.deps = deps;
|
|
725
|
+
}
|
|
726
|
+
newRecord(streamId, contentType, options, fork) {
|
|
727
|
+
const forkOffset = fork?.forkOffset;
|
|
728
|
+
const config = {
|
|
729
|
+
contentType,
|
|
730
|
+
ttlSeconds: options.ttlSeconds,
|
|
731
|
+
expiresAt: options.expiresAt,
|
|
732
|
+
createdAt: this.deps.clock.now()
|
|
733
|
+
};
|
|
734
|
+
return {
|
|
735
|
+
id: streamId,
|
|
736
|
+
config,
|
|
737
|
+
lifecycle: {
|
|
738
|
+
childRefCount: 0,
|
|
739
|
+
forkedFrom: fork?.forkedFrom,
|
|
740
|
+
forkOffset,
|
|
741
|
+
expiresAtMs: this.deps.expiryPolicy.computeExpiresAtMs(config)
|
|
742
|
+
},
|
|
743
|
+
currentOffset: forkOffset ?? ZERO_OFFSET,
|
|
744
|
+
counter: forkOffset ? parseCounter(forkOffset) : 0
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
|
|
749
|
+
//#endregion
|
|
750
|
+
//#region src/protocol.ts
|
|
751
|
+
const LONG_POLL_TIMEOUT_MS = 1500;
|
|
752
|
+
function createStreamProtocol(deps) {
|
|
753
|
+
return new StreamProtocol(deps);
|
|
754
|
+
}
|
|
755
|
+
var ProtocolStream = class {
|
|
756
|
+
id;
|
|
757
|
+
appendService;
|
|
758
|
+
readService;
|
|
759
|
+
liveReadService;
|
|
760
|
+
createService;
|
|
761
|
+
constructor(deps) {
|
|
762
|
+
this.deps = deps;
|
|
763
|
+
this.id = deps.storage.id;
|
|
764
|
+
const producerIdempotency = new ProducerIdempotencyService({ store: deps.storage });
|
|
765
|
+
const messageWriter = new StreamMessageWriter({
|
|
766
|
+
stream: deps.storage,
|
|
767
|
+
clock: deps.clock,
|
|
768
|
+
expiryPolicy: deps.expiryPolicy
|
|
769
|
+
});
|
|
770
|
+
const messageReader = new StreamMessageReader({
|
|
771
|
+
stream: deps.storage,
|
|
772
|
+
resolve: deps.resolveStorageStream,
|
|
773
|
+
expiryPolicy: deps.expiryPolicy
|
|
774
|
+
});
|
|
775
|
+
this.appendService = new AppendService({
|
|
776
|
+
producerIdempotency,
|
|
777
|
+
mutators: {
|
|
778
|
+
appendMessages: (record, data, seq) => messageWriter.appendMessages(record, data, seq),
|
|
779
|
+
closeRecord: (record, data, seq) => messageWriter.closeRecord(record, data, seq)
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
this.readService = new ReadService({ readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset) });
|
|
783
|
+
this.liveReadService = new LiveReadService({
|
|
784
|
+
store: deps.storage,
|
|
785
|
+
clock: deps.clock,
|
|
786
|
+
longPollTimeoutMs: deps.longPollTimeoutMs,
|
|
787
|
+
readChain: (record, afterOffset) => messageReader.readChain(record, afterOffset),
|
|
788
|
+
readOwn: (after) => messageReader.readOwn(after),
|
|
789
|
+
touch: (record) => deps.expiryPolicy.touch(deps.storage, record, "live-read")
|
|
790
|
+
});
|
|
791
|
+
const forkService = new ForkService({
|
|
792
|
+
resolve: deps.resolveStorageStream,
|
|
793
|
+
mutators: {
|
|
794
|
+
expireIfNeeded: async (stream) => {
|
|
795
|
+
await deps.expiryPolicy.expireIfNeeded(stream);
|
|
796
|
+
},
|
|
797
|
+
newRecord: (stream, contentType, opts, fork) => deps.recordFactory.newRecord(stream.id, contentType, opts, fork),
|
|
798
|
+
scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
|
|
799
|
+
appendMessages: (record, data) => messageWriter.appendMessages(record, data)
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
this.createService = new CreateStreamService({
|
|
803
|
+
store: deps.storage,
|
|
804
|
+
mutators: {
|
|
805
|
+
newRecord: (contentType, opts) => deps.recordFactory.newRecord(deps.storage.id, contentType, opts, void 0),
|
|
806
|
+
scheduleExpiry: (record) => deps.expiryPolicy.scheduleExpiry(record),
|
|
807
|
+
appendMessages: (record, data) => messageWriter.appendMessages(record, data),
|
|
808
|
+
closeRecord: (record, data) => messageWriter.closeRecord(record, data),
|
|
809
|
+
createFork: (opts) => forkService.execute(deps.storage, opts)
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
async create(options) {
|
|
814
|
+
return this.deps.withStreamMutationLock(this.deps.storage, async () => {
|
|
815
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
816
|
+
return this.createService.execute(record, options);
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
async append(options) {
|
|
820
|
+
return this.deps.withStreamMutationLock(this.deps.storage, async () => {
|
|
821
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
822
|
+
return this.appendService.execute(record, options);
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
async read(options) {
|
|
826
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
827
|
+
return this.readService.execute(record, options);
|
|
828
|
+
}
|
|
829
|
+
async readLive(options) {
|
|
830
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
831
|
+
return this.liveReadService.execute(record, options);
|
|
832
|
+
}
|
|
833
|
+
async metadata() {
|
|
834
|
+
const record = await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
835
|
+
if (!record) return { status: "not-found" };
|
|
836
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
837
|
+
return {
|
|
838
|
+
status: "ok",
|
|
839
|
+
contentType: record.config.contentType,
|
|
840
|
+
nextOffset: record.currentOffset,
|
|
841
|
+
ttlSeconds: record.config.ttlSeconds,
|
|
842
|
+
expiresAt: record.config.expiresAt,
|
|
843
|
+
closed: record.lifecycle.closed === true
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
async delete() {
|
|
847
|
+
await this.deps.expiryPolicy.expireIfNeeded(this.deps.storage);
|
|
848
|
+
return this.deps.gcService.deleteStream(this.deps.storage);
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
var StreamProtocol = class {
|
|
852
|
+
clock;
|
|
853
|
+
longPollTimeoutMs;
|
|
854
|
+
expiryPolicy;
|
|
855
|
+
gcService;
|
|
856
|
+
recordFactory;
|
|
857
|
+
constructor(deps) {
|
|
858
|
+
this.deps = deps;
|
|
859
|
+
this.clock = deps.clock ?? systemClock;
|
|
860
|
+
this.longPollTimeoutMs = deps.longPollTimeoutMs ?? LONG_POLL_TIMEOUT_MS;
|
|
861
|
+
this.expiryPolicy = new ExpiryPolicy({
|
|
862
|
+
resolve: (id) => this.storageStream(id),
|
|
863
|
+
clock: this.clock,
|
|
864
|
+
onScheduledExpiry: (id) => this.handleScheduledExpiry(id)
|
|
865
|
+
});
|
|
866
|
+
this.gcService = new StreamGcService({
|
|
867
|
+
resolve: (id) => this.storageStream(id),
|
|
868
|
+
mutators: { isExpired: (record) => this.expiryPolicy.isExpired(record) }
|
|
869
|
+
});
|
|
870
|
+
this.recordFactory = new StreamRecordFactory({
|
|
871
|
+
clock: this.clock,
|
|
872
|
+
expiryPolicy: this.expiryPolicy
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
async create(streamId, options) {
|
|
876
|
+
const storage = await this.storageStream(streamId);
|
|
877
|
+
const stream = this.boundProtocolStream(storage);
|
|
878
|
+
const result = await stream.create(options);
|
|
879
|
+
if (result.status === "created" || result.status === "exists") return {
|
|
880
|
+
...result,
|
|
881
|
+
stream
|
|
882
|
+
};
|
|
883
|
+
return result;
|
|
884
|
+
}
|
|
885
|
+
async get(streamId) {
|
|
886
|
+
const storage = await this.storageStream(streamId);
|
|
887
|
+
const record = await this.expiryPolicy.expireIfNeeded(storage);
|
|
888
|
+
if (!record) return { status: "not-found" };
|
|
889
|
+
if (record.lifecycle.softDeleted) return { status: "gone" };
|
|
890
|
+
return {
|
|
891
|
+
status: "ok",
|
|
892
|
+
stream: this.boundProtocolStream(storage)
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
/** Called by adapter schedulers/alarms; core decides soft-delete vs purge. */
|
|
896
|
+
async handleScheduledExpiry(streamId) {
|
|
897
|
+
return this.gcService.handleScheduledExpiry(streamId);
|
|
898
|
+
}
|
|
899
|
+
boundProtocolStream(storage) {
|
|
900
|
+
return new ProtocolStream({
|
|
901
|
+
storage,
|
|
902
|
+
clock: this.clock,
|
|
903
|
+
longPollTimeoutMs: this.longPollTimeoutMs,
|
|
904
|
+
expiryPolicy: this.expiryPolicy,
|
|
905
|
+
gcService: this.gcService,
|
|
906
|
+
recordFactory: this.recordFactory,
|
|
907
|
+
resolveStorageStream: (id) => this.storageStream(id),
|
|
908
|
+
withStreamMutationLock: (stream, fn) => this.withStreamMutationLock(stream, fn)
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
async storageStream(streamId) {
|
|
912
|
+
return this.deps.storage.factory.getStream(streamId);
|
|
913
|
+
}
|
|
914
|
+
async withStreamMutationLock(storage, fn) {
|
|
915
|
+
return storage.withMutationLock(fn);
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
//#endregion
|
|
920
|
+
//#region src/http/not-supported.ts
|
|
921
|
+
function notSupportedResponse(result, responses) {
|
|
922
|
+
const detail = result.message ?? `Feature not supported: ${result.feature}`;
|
|
923
|
+
return responses.text(detail, 400, { "stream-not-supported": result.feature });
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Convenience for use in `case`-style handlers that may want to short
|
|
927
|
+
* circuit on a `not-supported` result before pattern-matching the rest of a
|
|
928
|
+
* union.
|
|
929
|
+
*/
|
|
930
|
+
function maybeNotSupportedResponse(result, responses) {
|
|
931
|
+
return isNotSupported(result) ? notSupportedResponse(result, responses) : null;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
//#endregion
|
|
935
|
+
//#region src/http/dispatch-service.ts
|
|
936
|
+
var HttpDispatchService = class {
|
|
937
|
+
constructor(deps) {
|
|
938
|
+
this.deps = deps;
|
|
939
|
+
}
|
|
940
|
+
async fetch(request) {
|
|
941
|
+
return this.deps.responses.secure(await this.execute(request));
|
|
942
|
+
}
|
|
943
|
+
async execute(request) {
|
|
944
|
+
const url = new URL(request.url);
|
|
945
|
+
const streamId = this.deps.path.strip(url.pathname);
|
|
946
|
+
if (!streamId || streamId === url.pathname) return this.deps.responses.badRequest(`Stream path required: ${this.deps.path.requiredPathPattern()}`);
|
|
947
|
+
const ctx = {
|
|
948
|
+
request,
|
|
949
|
+
url,
|
|
950
|
+
streamId
|
|
951
|
+
};
|
|
952
|
+
try {
|
|
953
|
+
switch (request.method) {
|
|
954
|
+
case "PUT": return await this.deps.create.execute(ctx);
|
|
955
|
+
case "POST": return await this.withBoundStream(ctx, (bound) => this.deps.append.execute(bound));
|
|
956
|
+
case "GET": return await this.withBoundStream(ctx, (bound) => this.deps.read.execute(bound));
|
|
957
|
+
case "HEAD": return await this.withBoundStream(ctx, (bound) => this.deps.metadata.execute(bound));
|
|
958
|
+
case "DELETE": return await this.withBoundStream(ctx, (bound) => this.deps.delete.execute(bound));
|
|
959
|
+
default: return this.deps.responses.methodNotAllowed();
|
|
960
|
+
}
|
|
961
|
+
} catch (error) {
|
|
962
|
+
console.error("Error handling request:", error);
|
|
963
|
+
return this.deps.responses.internalError();
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
async withBoundStream(ctx, fn) {
|
|
967
|
+
const lookup = await this.deps.protocol.get(ctx.streamId);
|
|
968
|
+
if (lookup.status === "not-found") return this.deps.responses.notFound();
|
|
969
|
+
if (lookup.status === "gone") return this.deps.responses.gone();
|
|
970
|
+
if (isNotSupported(lookup)) return notSupportedResponse(lookup, this.deps.responses);
|
|
971
|
+
return fn({
|
|
972
|
+
...ctx,
|
|
973
|
+
stream: lookup.stream
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
//#endregion
|
|
979
|
+
//#region src/http/etag-builder.ts
|
|
980
|
+
var EtagBuilder = class {
|
|
981
|
+
forCatchUp(pathname, startOffset, nextOffset, closed) {
|
|
982
|
+
const closedSuffix = closed ? ":c" : "";
|
|
983
|
+
return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
|
|
984
|
+
}
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
//#endregion
|
|
988
|
+
//#region src/http/message-body-codec.ts
|
|
989
|
+
var MessageBodyCodec = class {
|
|
990
|
+
decoder = new TextDecoder();
|
|
991
|
+
encodeHttpBody(messages, contentType) {
|
|
992
|
+
const lower = contentType.toLowerCase();
|
|
993
|
+
if (lower.startsWith("application/json")) {
|
|
994
|
+
const items = messages.map((msg) => this.decoder.decode(msg.data));
|
|
995
|
+
return `[${items.join(",")}]`;
|
|
996
|
+
}
|
|
997
|
+
if (lower.startsWith("text/")) return messages.map((msg) => this.decoder.decode(msg.data)).join("");
|
|
998
|
+
return this.concatBytes(messages).buffer;
|
|
999
|
+
}
|
|
1000
|
+
emptyBodyForContentType(contentType) {
|
|
1001
|
+
return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
|
|
1002
|
+
}
|
|
1003
|
+
concatBytes(messages) {
|
|
1004
|
+
const totalLength = messages.reduce((acc, msg) => acc + msg.data.length, 0);
|
|
1005
|
+
const combined = new Uint8Array(totalLength);
|
|
1006
|
+
let pos = 0;
|
|
1007
|
+
for (const msg of messages) {
|
|
1008
|
+
combined.set(msg.data, pos);
|
|
1009
|
+
pos += msg.data.length;
|
|
1010
|
+
}
|
|
1011
|
+
return combined;
|
|
1012
|
+
}
|
|
1013
|
+
bytesToBase64(bytes) {
|
|
1014
|
+
const BufferRef = globalThis.Buffer;
|
|
1015
|
+
if (BufferRef) return BufferRef.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
1016
|
+
let binary = "";
|
|
1017
|
+
const chunk = 32768;
|
|
1018
|
+
for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
1019
|
+
return btoa(binary);
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
|
|
1023
|
+
//#endregion
|
|
1024
|
+
//#region src/http/producer-header-parser.ts
|
|
1025
|
+
const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
|
|
1026
|
+
const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
|
|
1027
|
+
var ProducerHeaderParser = class {
|
|
1028
|
+
parse(request) {
|
|
1029
|
+
const id = request.headers.get("producer-id");
|
|
1030
|
+
const epoch = request.headers.get("producer-epoch");
|
|
1031
|
+
const seq = request.headers.get("producer-seq");
|
|
1032
|
+
const present = [
|
|
1033
|
+
id,
|
|
1034
|
+
epoch,
|
|
1035
|
+
seq
|
|
1036
|
+
].filter((v) => v !== null).length;
|
|
1037
|
+
if (present === 0) return { kind: "absent" };
|
|
1038
|
+
if (present !== 3) return { kind: "invalid" };
|
|
1039
|
+
if (id.length === 0) return { kind: "invalid" };
|
|
1040
|
+
const parsedEpoch = this.parseInt(epoch);
|
|
1041
|
+
const parsedSeq = this.parseInt(seq);
|
|
1042
|
+
if (parsedEpoch === null || parsedSeq === null) return { kind: "invalid" };
|
|
1043
|
+
return {
|
|
1044
|
+
kind: "ok",
|
|
1045
|
+
producer: {
|
|
1046
|
+
producerId: id,
|
|
1047
|
+
producerEpoch: parsedEpoch,
|
|
1048
|
+
producerSeq: parsedSeq
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
parseInt(raw) {
|
|
1053
|
+
if (!NON_NEGATIVE_INT_RE.test(raw)) return null;
|
|
1054
|
+
const n = Number(raw);
|
|
1055
|
+
if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
|
|
1056
|
+
return n;
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
//#endregion
|
|
1061
|
+
//#region src/http/read-query-parser.ts
|
|
1062
|
+
var ReadQueryParser = class {
|
|
1063
|
+
parse(url) {
|
|
1064
|
+
const offset = url.searchParams.get("offset") ?? void 0;
|
|
1065
|
+
const liveParam = url.searchParams.get("live");
|
|
1066
|
+
const cursor = url.searchParams.get("cursor") ?? void 0;
|
|
1067
|
+
const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
|
|
1068
|
+
if (offset !== void 0 && offset !== "-1" && offset !== "now" && !/^\d+_\d+$/.test(offset)) return {
|
|
1069
|
+
ok: false,
|
|
1070
|
+
response: new Response("Invalid offset format", { status: 400 })
|
|
1071
|
+
};
|
|
1072
|
+
return {
|
|
1073
|
+
ok: true,
|
|
1074
|
+
offset,
|
|
1075
|
+
live,
|
|
1076
|
+
cursor
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
|
|
1081
|
+
//#endregion
|
|
1082
|
+
//#region src/http/request-body-reader.ts
|
|
1083
|
+
var RequestBodyReader = class {
|
|
1084
|
+
constructor(maxMessageSize, responses) {
|
|
1085
|
+
this.maxMessageSize = maxMessageSize;
|
|
1086
|
+
this.responses = responses;
|
|
1087
|
+
}
|
|
1088
|
+
async read(request) {
|
|
1089
|
+
let data;
|
|
1090
|
+
try {
|
|
1091
|
+
data = await request.arrayBuffer();
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
console.error("Error reading request body:", error);
|
|
1094
|
+
return {
|
|
1095
|
+
ok: false,
|
|
1096
|
+
response: this.responses.payloadTooLarge()
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
if (data.byteLength > this.maxMessageSize) return {
|
|
1100
|
+
ok: false,
|
|
1101
|
+
response: this.responses.payloadTooLarge()
|
|
1102
|
+
};
|
|
1103
|
+
return {
|
|
1104
|
+
ok: true,
|
|
1105
|
+
data: new Uint8Array(data),
|
|
1106
|
+
byteLength: data.byteLength
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
};
|
|
1110
|
+
|
|
1111
|
+
//#endregion
|
|
1112
|
+
//#region src/http/responses.ts
|
|
1113
|
+
/**
|
|
1114
|
+
* Response factory for the HTTP layer.
|
|
1115
|
+
*
|
|
1116
|
+
* Centralizes security headers and the small set of plain text/empty
|
|
1117
|
+
* responses that recur across handlers (400/404/410/413/etc.). Method-
|
|
1118
|
+
* specific result mapping (append producer-state shaping, create conflict
|
|
1119
|
+
* mapping, catch-up ETag responses) stays in the owning service.
|
|
1120
|
+
*/
|
|
1121
|
+
const CACHE_CONTROL_NO_STORE = "no-store";
|
|
1122
|
+
const CACHE_CONTROL_PUBLIC = "public, max-age=60, stale-while-revalidate=300";
|
|
1123
|
+
const CACHE_NO_STORE = CACHE_CONTROL_NO_STORE;
|
|
1124
|
+
const CACHE_REVALIDATE = CACHE_CONTROL_PUBLIC;
|
|
1125
|
+
var HttpResponseFactory = class {
|
|
1126
|
+
secure(response) {
|
|
1127
|
+
return this.withSecurityHeaders(response);
|
|
1128
|
+
}
|
|
1129
|
+
text(message, status, headers) {
|
|
1130
|
+
return new Response(message, {
|
|
1131
|
+
status,
|
|
1132
|
+
headers
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
empty(status, headers) {
|
|
1136
|
+
return new Response(null, {
|
|
1137
|
+
status,
|
|
1138
|
+
headers
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
badRequest(message) {
|
|
1142
|
+
return new Response(message, { status: 400 });
|
|
1143
|
+
}
|
|
1144
|
+
notFound(message = "Stream not found") {
|
|
1145
|
+
return new Response(message, { status: 404 });
|
|
1146
|
+
}
|
|
1147
|
+
gone(message = "Stream is soft-deleted") {
|
|
1148
|
+
return new Response(message, { status: 410 });
|
|
1149
|
+
}
|
|
1150
|
+
conflict(message, headers) {
|
|
1151
|
+
return new Response(message, {
|
|
1152
|
+
status: 409,
|
|
1153
|
+
headers
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
payloadTooLarge() {
|
|
1157
|
+
return new Response("Payload too large", { status: 413 });
|
|
1158
|
+
}
|
|
1159
|
+
invalidJson() {
|
|
1160
|
+
return new Response("Invalid JSON", { status: 400 });
|
|
1161
|
+
}
|
|
1162
|
+
methodNotAllowed() {
|
|
1163
|
+
return new Response("Method not allowed", { status: 405 });
|
|
1164
|
+
}
|
|
1165
|
+
internalError() {
|
|
1166
|
+
return new Response("Internal server error", { status: 500 });
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Wrap a response with the standard security headers used across every
|
|
1170
|
+
* route. Existing values for the same header names are preserved.
|
|
1171
|
+
*/
|
|
1172
|
+
withSecurityHeaders(response) {
|
|
1173
|
+
const headers = new Headers(response.headers);
|
|
1174
|
+
if (!headers.has("x-content-type-options")) headers.set("x-content-type-options", "nosniff");
|
|
1175
|
+
if (!headers.has("cross-origin-resource-policy")) headers.set("cross-origin-resource-policy", "cross-origin");
|
|
1176
|
+
return new Response(response.body, {
|
|
1177
|
+
status: response.status,
|
|
1178
|
+
statusText: response.statusText,
|
|
1179
|
+
headers
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
//#endregion
|
|
1185
|
+
//#region src/http/sse-event-encoder.ts
|
|
1186
|
+
var SseEventEncoder = class {
|
|
1187
|
+
encoder = new TextEncoder();
|
|
1188
|
+
decoder = new TextDecoder();
|
|
1189
|
+
constructor(bodyCodec) {
|
|
1190
|
+
this.bodyCodec = bodyCodec;
|
|
1191
|
+
}
|
|
1192
|
+
dataEvent(messages, options) {
|
|
1193
|
+
const chunks = [this.encode("event: data\n")];
|
|
1194
|
+
if (options.useBase64) {
|
|
1195
|
+
const combined = this.bodyCodec.concatBytes(messages);
|
|
1196
|
+
chunks.push(this.encode(`data:${this.bodyCodec.bytesToBase64(combined)}\n`));
|
|
1197
|
+
} else if (options.isJson) {
|
|
1198
|
+
const items = messages.map((msg) => this.decoder.decode(msg.data));
|
|
1199
|
+
chunks.push(this.encode("data:[\n"));
|
|
1200
|
+
for (let i = 0; i < items.length; i++) {
|
|
1201
|
+
const suffix = i < items.length - 1 ? "," : "";
|
|
1202
|
+
chunks.push(this.encode(`data:${items[i]}${suffix}\n`));
|
|
1203
|
+
}
|
|
1204
|
+
chunks.push(this.encode("data:]\n"));
|
|
1205
|
+
} else {
|
|
1206
|
+
const text = messages.map((msg) => this.decoder.decode(msg.data)).join("");
|
|
1207
|
+
for (const line of text.split(/\r\n|\r|\n/)) chunks.push(this.encode(`data:${line}\n`));
|
|
1208
|
+
}
|
|
1209
|
+
chunks.push(this.encode("\n"));
|
|
1210
|
+
return chunks;
|
|
1211
|
+
}
|
|
1212
|
+
controlEvent(data) {
|
|
1213
|
+
return this.encode(`event: control\ndata:${JSON.stringify(data)}\n\n`);
|
|
1214
|
+
}
|
|
1215
|
+
encode(value) {
|
|
1216
|
+
return this.encoder.encode(value);
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
|
|
1220
|
+
//#endregion
|
|
1221
|
+
//#region src/http/stream-path-service.ts
|
|
1222
|
+
var StreamPathService = class {
|
|
1223
|
+
constructor(pathPrefix) {
|
|
1224
|
+
this.pathPrefix = pathPrefix;
|
|
1225
|
+
}
|
|
1226
|
+
requiredPathPattern() {
|
|
1227
|
+
return `${this.prefixWithSlash()}{path}`;
|
|
1228
|
+
}
|
|
1229
|
+
strip(pathname) {
|
|
1230
|
+
const regex = new RegExp(`^${this.escapeRegex(this.prefixWithSlash())}`);
|
|
1231
|
+
return pathname.replace(regex, "");
|
|
1232
|
+
}
|
|
1233
|
+
canonicalizeForkSource(header) {
|
|
1234
|
+
return this.strip(header);
|
|
1235
|
+
}
|
|
1236
|
+
prefixWithSlash() {
|
|
1237
|
+
return this.pathPrefix.endsWith("/") ? this.pathPrefix : `${this.pathPrefix}/`;
|
|
1238
|
+
}
|
|
1239
|
+
escapeRegex(value) {
|
|
1240
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
|
|
1244
|
+
//#endregion
|
|
1245
|
+
//#region src/http/services/append-http-service.ts
|
|
1246
|
+
var AppendHttpService = class {
|
|
1247
|
+
constructor(deps) {
|
|
1248
|
+
this.deps = deps;
|
|
1249
|
+
}
|
|
1250
|
+
async execute(ctx) {
|
|
1251
|
+
const parsed = this.parseHeaders(ctx.request);
|
|
1252
|
+
if (!parsed.ok) return parsed.response;
|
|
1253
|
+
const body = await this.readAndValidateBody(ctx.request, parsed.contentType, parsed.wantClose);
|
|
1254
|
+
if (!body.ok) return body.response;
|
|
1255
|
+
const result = await ctx.stream.append({
|
|
1256
|
+
data: body.data,
|
|
1257
|
+
contentType: parsed.contentType ?? "application/octet-stream",
|
|
1258
|
+
seq: parsed.seq,
|
|
1259
|
+
producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
|
|
1260
|
+
close: parsed.wantClose
|
|
1261
|
+
});
|
|
1262
|
+
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1263
|
+
return this.toResponse(result, parsed.producerHeaders, body.isEmpty);
|
|
1264
|
+
}
|
|
1265
|
+
parseHeaders(request) {
|
|
1266
|
+
const producerHeaders = this.deps.producerHeaders.parse(request);
|
|
1267
|
+
if (producerHeaders.kind === "invalid") return {
|
|
1268
|
+
ok: false,
|
|
1269
|
+
response: this.deps.responses.badRequest("Invalid producer headers")
|
|
1270
|
+
};
|
|
1271
|
+
return {
|
|
1272
|
+
ok: true,
|
|
1273
|
+
contentType: request.headers.get("content-type"),
|
|
1274
|
+
seq: request.headers.get("stream-seq") ?? void 0,
|
|
1275
|
+
wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
1276
|
+
producerHeaders
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
async readAndValidateBody(request, contentType, wantClose) {
|
|
1280
|
+
const body = await this.deps.bodyReader.read(request);
|
|
1281
|
+
if (!body.ok) return body;
|
|
1282
|
+
const isEmpty = body.byteLength === 0;
|
|
1283
|
+
if (isEmpty && !wantClose) return {
|
|
1284
|
+
ok: false,
|
|
1285
|
+
response: this.deps.responses.badRequest("Empty body not allowed")
|
|
1286
|
+
};
|
|
1287
|
+
if (!contentType && !isEmpty) return {
|
|
1288
|
+
ok: false,
|
|
1289
|
+
response: this.deps.responses.badRequest("Content-Type required")
|
|
1290
|
+
};
|
|
1291
|
+
if (!isEmpty && contentType?.toLowerCase().startsWith("application/json")) try {
|
|
1292
|
+
const parsed = JSON.parse(new TextDecoder().decode(body.data));
|
|
1293
|
+
if (Array.isArray(parsed) && parsed.length === 0) return {
|
|
1294
|
+
ok: false,
|
|
1295
|
+
response: this.deps.responses.badRequest("Empty arrays not allowed")
|
|
1296
|
+
};
|
|
1297
|
+
} catch (error) {
|
|
1298
|
+
if (error instanceof SyntaxError) return {
|
|
1299
|
+
ok: false,
|
|
1300
|
+
response: this.deps.responses.invalidJson()
|
|
1301
|
+
};
|
|
1302
|
+
throw error;
|
|
1303
|
+
}
|
|
1304
|
+
return {
|
|
1305
|
+
ok: true,
|
|
1306
|
+
data: body.data,
|
|
1307
|
+
isEmpty
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
toResponse(result, producerHeaders, isEmpty) {
|
|
1311
|
+
switch (result.status) {
|
|
1312
|
+
case "not-found": return this.deps.responses.notFound();
|
|
1313
|
+
case "gone": return this.deps.responses.gone();
|
|
1314
|
+
case "conflict": {
|
|
1315
|
+
if (result.conflictReason === "closed") return this.deps.responses.empty(409, {
|
|
1316
|
+
"stream-closed": "true",
|
|
1317
|
+
"stream-next-offset": result.nextOffset
|
|
1318
|
+
});
|
|
1319
|
+
return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
|
|
1320
|
+
}
|
|
1321
|
+
case "stale-epoch": return this.deps.responses.text("Stale producer epoch", 403, { "producer-epoch": String(result.currentEpoch) });
|
|
1322
|
+
case "producer-gap": return this.deps.responses.conflict("Producer sequence gap", {
|
|
1323
|
+
"producer-expected-seq": String(result.expectedSeq),
|
|
1324
|
+
"producer-received-seq": String(result.receivedSeq)
|
|
1325
|
+
});
|
|
1326
|
+
case "invalid-epoch-seq": return this.deps.responses.badRequest("New epoch must start at seq=0");
|
|
1327
|
+
case "duplicate": return this.deps.responses.empty(204, {
|
|
1328
|
+
"stream-next-offset": result.nextOffset,
|
|
1329
|
+
"producer-epoch": String(result.producerEpoch),
|
|
1330
|
+
"producer-seq": String(result.producerSeq),
|
|
1331
|
+
...result.closed ? { "stream-closed": "true" } : {}
|
|
1332
|
+
});
|
|
1333
|
+
case "appended": {
|
|
1334
|
+
const headers = {
|
|
1335
|
+
"stream-next-offset": result.nextOffset,
|
|
1336
|
+
...result.closed ? { "stream-closed": "true" } : {}
|
|
1337
|
+
};
|
|
1338
|
+
if (result.producerEpoch !== void 0) headers["producer-epoch"] = String(result.producerEpoch);
|
|
1339
|
+
if (result.producerSeq !== void 0) headers["producer-seq"] = String(result.producerSeq);
|
|
1340
|
+
return this.deps.responses.empty(producerHeaders.kind === "ok" && !isEmpty ? 200 : 204, headers);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
|
|
1346
|
+
//#endregion
|
|
1347
|
+
//#region src/http/services/create-http-service.ts
|
|
1348
|
+
var CreateHttpService = class {
|
|
1349
|
+
constructor(deps) {
|
|
1350
|
+
this.deps = deps;
|
|
1351
|
+
}
|
|
1352
|
+
async execute(ctx) {
|
|
1353
|
+
const parsed = this.parseHeaders(ctx.request);
|
|
1354
|
+
if (!parsed.ok) return parsed.response;
|
|
1355
|
+
const body = await this.deps.bodyReader.read(ctx.request);
|
|
1356
|
+
if (!body.ok) return body.response;
|
|
1357
|
+
const normalized = this.normalizeInitialData(body.data, parsed.contentType);
|
|
1358
|
+
if (!normalized.ok) return normalized.response;
|
|
1359
|
+
const result = await this.deps.protocol.create(ctx.streamId, {
|
|
1360
|
+
contentType: parsed.contentType,
|
|
1361
|
+
ttlSeconds: parsed.ttlSeconds,
|
|
1362
|
+
expiresAt: parsed.expiresAt,
|
|
1363
|
+
initialData: normalized.initialData,
|
|
1364
|
+
closed: parsed.wantClosed,
|
|
1365
|
+
forkedFrom: parsed.forkedFromStreamId,
|
|
1366
|
+
forkOffset: parsed.forkOffset
|
|
1367
|
+
});
|
|
1368
|
+
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1369
|
+
return this.toResponse(result, ctx.request.url);
|
|
1370
|
+
}
|
|
1371
|
+
parseHeaders(request) {
|
|
1372
|
+
const rawContentType = request.headers.get("content-type");
|
|
1373
|
+
const ttlHeader = request.headers.get("stream-ttl");
|
|
1374
|
+
const expiresAtHeader = request.headers.get("stream-expires-at");
|
|
1375
|
+
const forkedFromHeader = request.headers.get("stream-forked-from");
|
|
1376
|
+
const forkOffsetHeader = request.headers.get("stream-fork-offset");
|
|
1377
|
+
if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
|
|
1378
|
+
ok: false,
|
|
1379
|
+
response: this.deps.responses.badRequest("Invalid Stream-TTL format")
|
|
1380
|
+
};
|
|
1381
|
+
if (ttlHeader && expiresAtHeader) return {
|
|
1382
|
+
ok: false,
|
|
1383
|
+
response: this.deps.responses.badRequest("Cannot specify both Stream-TTL and Stream-Expires-At")
|
|
1384
|
+
};
|
|
1385
|
+
if (expiresAtHeader && isNaN(new Date(expiresAtHeader).getTime())) return {
|
|
1386
|
+
ok: false,
|
|
1387
|
+
response: this.deps.responses.badRequest("Invalid Stream-Expires-At format")
|
|
1388
|
+
};
|
|
1389
|
+
if (forkOffsetHeader && !forkedFromHeader) return {
|
|
1390
|
+
ok: false,
|
|
1391
|
+
response: this.deps.responses.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
|
|
1392
|
+
};
|
|
1393
|
+
const isFork = !!forkedFromHeader;
|
|
1394
|
+
return {
|
|
1395
|
+
ok: true,
|
|
1396
|
+
contentType: rawContentType ?? (isFork ? void 0 : "application/octet-stream"),
|
|
1397
|
+
ttlSeconds: ttlHeader ? parseInt(ttlHeader, 10) : void 0,
|
|
1398
|
+
expiresAt: expiresAtHeader ?? void 0,
|
|
1399
|
+
wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
1400
|
+
forkedFromStreamId: forkedFromHeader ? this.deps.path.canonicalizeForkSource(forkedFromHeader) : void 0,
|
|
1401
|
+
forkOffset: forkOffsetHeader ?? void 0
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
normalizeInitialData(data, contentType) {
|
|
1405
|
+
let effectiveInitialData = data.byteLength > 0 ? data : void 0;
|
|
1406
|
+
if (effectiveInitialData && contentType?.toLowerCase().startsWith("application/json")) try {
|
|
1407
|
+
const parsed = JSON.parse(new TextDecoder().decode(effectiveInitialData));
|
|
1408
|
+
if (Array.isArray(parsed) && parsed.length === 0) effectiveInitialData = void 0;
|
|
1409
|
+
} catch (error) {
|
|
1410
|
+
if (error instanceof SyntaxError) return {
|
|
1411
|
+
ok: false,
|
|
1412
|
+
response: this.deps.responses.invalidJson()
|
|
1413
|
+
};
|
|
1414
|
+
throw error;
|
|
1415
|
+
}
|
|
1416
|
+
return {
|
|
1417
|
+
ok: true,
|
|
1418
|
+
initialData: effectiveInitialData
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
toResponse(result, location) {
|
|
1422
|
+
if (result.status === "not-found") return this.deps.responses.notFound(result.errorMessage ?? "Source stream not found");
|
|
1423
|
+
if (result.status === "bad-request") return this.deps.responses.badRequest(result.errorMessage ?? "Invalid fork parameters");
|
|
1424
|
+
if (result.status === "conflict") return this.deps.responses.conflict(result.errorMessage ?? "Stream exists with different configuration");
|
|
1425
|
+
const success = result;
|
|
1426
|
+
const status = success.status === "created" ? 201 : 200;
|
|
1427
|
+
return this.deps.responses.empty(status, {
|
|
1428
|
+
"content-type": success.contentType,
|
|
1429
|
+
"stream-next-offset": success.nextOffset,
|
|
1430
|
+
...status === 201 ? { location } : {},
|
|
1431
|
+
...success.closed ? { "stream-closed": "true" } : {}
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
|
|
1436
|
+
//#endregion
|
|
1437
|
+
//#region src/http/services/delete-http-service.ts
|
|
1438
|
+
var DeleteHttpService = class {
|
|
1439
|
+
constructor(deps) {
|
|
1440
|
+
this.deps = deps;
|
|
1441
|
+
}
|
|
1442
|
+
async execute(ctx) {
|
|
1443
|
+
const result = await ctx.stream.delete();
|
|
1444
|
+
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
1445
|
+
if (result.status === "gone") return this.deps.responses.gone();
|
|
1446
|
+
return this.deps.responses.empty(204);
|
|
1447
|
+
}
|
|
1448
|
+
};
|
|
1449
|
+
|
|
1450
|
+
//#endregion
|
|
1451
|
+
//#region src/http/services/long-poll-http-service.ts
|
|
1452
|
+
var LongPollHttpService = class {
|
|
1453
|
+
constructor(deps) {
|
|
1454
|
+
this.deps = deps;
|
|
1455
|
+
}
|
|
1456
|
+
async execute(stream, offset, cursor) {
|
|
1457
|
+
const result = await stream.readLive({
|
|
1458
|
+
offset,
|
|
1459
|
+
mode: "long-poll",
|
|
1460
|
+
cursor
|
|
1461
|
+
});
|
|
1462
|
+
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1463
|
+
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
1464
|
+
if (result.status === "gone") return this.deps.responses.gone();
|
|
1465
|
+
if (result.messages.length === 0) return this.toNoContentResponse(result);
|
|
1466
|
+
const metadata = await stream.metadata();
|
|
1467
|
+
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
1468
|
+
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
1469
|
+
return new Response(this.deps.bodyCodec.encodeHttpBody(result.messages, metadata.contentType), { headers: {
|
|
1470
|
+
"content-type": metadata.contentType,
|
|
1471
|
+
"stream-next-offset": result.nextOffset,
|
|
1472
|
+
"stream-up-to-date": "true",
|
|
1473
|
+
...result.closed ? {} : { "stream-cursor": result.cursor },
|
|
1474
|
+
...result.closed ? { "stream-closed": "true" } : {}
|
|
1475
|
+
} });
|
|
1476
|
+
}
|
|
1477
|
+
toNoContentResponse(result) {
|
|
1478
|
+
return this.deps.responses.empty(204, {
|
|
1479
|
+
"stream-next-offset": result.nextOffset,
|
|
1480
|
+
"stream-up-to-date": "true",
|
|
1481
|
+
...result.closed ? {} : { "stream-cursor": result.cursor },
|
|
1482
|
+
...result.closed ? { "stream-closed": "true" } : {}
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
|
|
1487
|
+
//#endregion
|
|
1488
|
+
//#region src/http/services/metadata-http-service.ts
|
|
1489
|
+
var MetadataHttpService = class {
|
|
1490
|
+
constructor(deps) {
|
|
1491
|
+
this.deps = deps;
|
|
1492
|
+
}
|
|
1493
|
+
async execute(ctx) {
|
|
1494
|
+
const result = await ctx.stream.metadata();
|
|
1495
|
+
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
1496
|
+
if (result.status === "gone") return this.deps.responses.gone();
|
|
1497
|
+
return this.deps.responses.empty(200, {
|
|
1498
|
+
"content-type": result.contentType,
|
|
1499
|
+
"stream-next-offset": result.nextOffset,
|
|
1500
|
+
...result.ttlSeconds ? { "stream-ttl": String(result.ttlSeconds) } : {},
|
|
1501
|
+
...result.expiresAt ? { "stream-expires-at": result.expiresAt } : {},
|
|
1502
|
+
...result.closed ? { "stream-closed": "true" } : {},
|
|
1503
|
+
"cache-control": CACHE_NO_STORE
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
|
|
1508
|
+
//#endregion
|
|
1509
|
+
//#region src/http/services/read-http-service.ts
|
|
1510
|
+
var ReadHttpService = class {
|
|
1511
|
+
constructor(deps) {
|
|
1512
|
+
this.deps = deps;
|
|
1513
|
+
}
|
|
1514
|
+
async execute(ctx) {
|
|
1515
|
+
const query = this.deps.readQuery.parse(ctx.url);
|
|
1516
|
+
if (!query.ok) return query.response;
|
|
1517
|
+
let effectiveOffset = query.offset;
|
|
1518
|
+
if (query.offset === "now") {
|
|
1519
|
+
const now = await this.resolveNowOffset(ctx, query.live);
|
|
1520
|
+
if (!now.ok) return now.response;
|
|
1521
|
+
effectiveOffset = now.offset;
|
|
1522
|
+
if (now.response) return now.response;
|
|
1523
|
+
}
|
|
1524
|
+
if (query.live) {
|
|
1525
|
+
if (!effectiveOffset) return this.deps.responses.badRequest("offset required for live modes");
|
|
1526
|
+
return query.live === "sse" ? this.deps.sse.execute(ctx.stream, effectiveOffset, query.cursor) : this.deps.longPoll.execute(ctx.stream, effectiveOffset, query.cursor);
|
|
1527
|
+
}
|
|
1528
|
+
return this.handleCatchUp(ctx, effectiveOffset, query.offset ?? "-1");
|
|
1529
|
+
}
|
|
1530
|
+
async resolveNowOffset(ctx, live) {
|
|
1531
|
+
const meta = await ctx.stream.metadata();
|
|
1532
|
+
if (meta.status === "not-found") return {
|
|
1533
|
+
ok: false,
|
|
1534
|
+
response: this.deps.responses.notFound()
|
|
1535
|
+
};
|
|
1536
|
+
if (meta.status === "gone") return {
|
|
1537
|
+
ok: false,
|
|
1538
|
+
response: this.deps.responses.gone()
|
|
1539
|
+
};
|
|
1540
|
+
const offset = meta.nextOffset;
|
|
1541
|
+
if (!live) {
|
|
1542
|
+
const contentType = meta.contentType;
|
|
1543
|
+
return {
|
|
1544
|
+
ok: true,
|
|
1545
|
+
offset,
|
|
1546
|
+
response: new Response(this.deps.bodyCodec.emptyBodyForContentType(contentType), { headers: {
|
|
1547
|
+
"content-type": contentType,
|
|
1548
|
+
"stream-next-offset": offset,
|
|
1549
|
+
"stream-up-to-date": "true",
|
|
1550
|
+
...meta.closed ? { "stream-closed": "true" } : {},
|
|
1551
|
+
"cache-control": CACHE_NO_STORE
|
|
1552
|
+
} })
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
return {
|
|
1556
|
+
ok: true,
|
|
1557
|
+
offset
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
async handleCatchUp(ctx, offset, startOffset) {
|
|
1561
|
+
const result = await ctx.stream.read({ offset });
|
|
1562
|
+
if (result.status === "not-found") return this.deps.responses.notFound();
|
|
1563
|
+
if (result.status === "gone") return this.deps.responses.gone();
|
|
1564
|
+
const etag = this.deps.etags.forCatchUp(ctx.url.pathname, startOffset, result.nextOffset, result.closed === true);
|
|
1565
|
+
if (ctx.request.headers.get("if-none-match") === etag) return this.deps.responses.empty(304, {
|
|
1566
|
+
etag,
|
|
1567
|
+
"cache-control": CACHE_REVALIDATE
|
|
1568
|
+
});
|
|
1569
|
+
const metadata = await ctx.stream.metadata();
|
|
1570
|
+
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
1571
|
+
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
1572
|
+
return new Response(this.deps.bodyCodec.encodeHttpBody(result.messages, metadata.contentType), { headers: {
|
|
1573
|
+
"content-type": metadata.contentType,
|
|
1574
|
+
"stream-next-offset": result.nextOffset,
|
|
1575
|
+
...result.upToDate ? { "stream-up-to-date": "true" } : {},
|
|
1576
|
+
...result.closed ? { "stream-closed": "true" } : {},
|
|
1577
|
+
etag,
|
|
1578
|
+
"cache-control": CACHE_REVALIDATE
|
|
1579
|
+
} });
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
|
|
1583
|
+
//#endregion
|
|
1584
|
+
//#region src/http/services/sse-http-service.ts
|
|
1585
|
+
const CONNECTION_TIMEOUT_MS = 6e4;
|
|
1586
|
+
var SseHttpService = class {
|
|
1587
|
+
constructor(deps) {
|
|
1588
|
+
this.deps = deps;
|
|
1589
|
+
}
|
|
1590
|
+
async execute(stream, offset, cursor) {
|
|
1591
|
+
const metadata = await stream.metadata();
|
|
1592
|
+
if (metadata.status === "not-found") return this.deps.responses.notFound();
|
|
1593
|
+
if (metadata.status === "gone") return this.deps.responses.gone();
|
|
1594
|
+
const contentTypeLower = metadata.contentType.toLowerCase();
|
|
1595
|
+
const encoding = {
|
|
1596
|
+
isText: contentTypeLower.startsWith("text/"),
|
|
1597
|
+
isJson: contentTypeLower.startsWith("application/json"),
|
|
1598
|
+
useBase64: false
|
|
1599
|
+
};
|
|
1600
|
+
encoding.useBase64 = !encoding.isText && !encoding.isJson;
|
|
1601
|
+
const body = this.createStream(stream, offset, cursor, metadata.nextOffset, metadata.closed === true, encoding);
|
|
1602
|
+
return new Response(body, { headers: {
|
|
1603
|
+
"content-type": "text/event-stream",
|
|
1604
|
+
"cache-control": "no-cache",
|
|
1605
|
+
connection: "keep-alive",
|
|
1606
|
+
...encoding.useBase64 ? { "stream-sse-data-encoding": "base64" } : {}
|
|
1607
|
+
} });
|
|
1608
|
+
}
|
|
1609
|
+
createStream(stream, offset, cursor, metadataNextOffset, metadataClosed, encoding) {
|
|
1610
|
+
let currentOffset = offset;
|
|
1611
|
+
let currentCursor = cursor;
|
|
1612
|
+
const connectionStartTime = Date.now();
|
|
1613
|
+
const sseEvents = this.deps.sseEvents;
|
|
1614
|
+
const clock = this.deps.clock;
|
|
1615
|
+
return new ReadableStream({ start: async (controller) => {
|
|
1616
|
+
try {
|
|
1617
|
+
let initialNextOffset;
|
|
1618
|
+
let initialUpToDate;
|
|
1619
|
+
let initialClosed = false;
|
|
1620
|
+
if (currentOffset === "now") {
|
|
1621
|
+
initialNextOffset = metadataNextOffset;
|
|
1622
|
+
initialUpToDate = true;
|
|
1623
|
+
initialClosed = metadataClosed;
|
|
1624
|
+
} else {
|
|
1625
|
+
const initialResult = await stream.read({ offset: currentOffset === "-1" ? void 0 : currentOffset });
|
|
1626
|
+
if (initialResult.status === "not-found" || initialResult.status === "gone") {
|
|
1627
|
+
controller.close();
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
this.writeChunks(controller, sseEvents.dataEvent(initialResult.messages, encoding), initialResult.messages.length > 0);
|
|
1631
|
+
initialNextOffset = initialResult.nextOffset;
|
|
1632
|
+
initialUpToDate = initialResult.upToDate;
|
|
1633
|
+
initialClosed = initialResult.closed === true;
|
|
1634
|
+
}
|
|
1635
|
+
currentCursor = generateCursor(clock, currentCursor);
|
|
1636
|
+
controller.enqueue(sseEvents.controlEvent(this.buildControlData(initialNextOffset, currentCursor, initialUpToDate, initialClosed)));
|
|
1637
|
+
if (initialClosed) {
|
|
1638
|
+
controller.close();
|
|
1639
|
+
return;
|
|
1640
|
+
}
|
|
1641
|
+
currentOffset = initialNextOffset;
|
|
1642
|
+
while (true) {
|
|
1643
|
+
if (Date.now() - connectionStartTime >= CONNECTION_TIMEOUT_MS) {
|
|
1644
|
+
controller.close();
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
const result = await stream.readLive({
|
|
1648
|
+
offset: currentOffset,
|
|
1649
|
+
mode: "sse",
|
|
1650
|
+
cursor: currentCursor
|
|
1651
|
+
});
|
|
1652
|
+
if (result.status === "not-found" || result.status === "not-supported") {
|
|
1653
|
+
controller.close();
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
this.writeChunks(controller, sseEvents.dataEvent(result.messages, encoding), result.messages.length > 0);
|
|
1657
|
+
controller.enqueue(sseEvents.controlEvent(this.buildControlData(result.nextOffset, result.cursor, result.upToDate, result.closed === true)));
|
|
1658
|
+
currentOffset = result.nextOffset;
|
|
1659
|
+
currentCursor = result.cursor;
|
|
1660
|
+
if (result.closed) {
|
|
1661
|
+
controller.close();
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
if (result.status === "timeout") continue;
|
|
1665
|
+
}
|
|
1666
|
+
} catch (error) {
|
|
1667
|
+
console.error("SSE stream error:", error);
|
|
1668
|
+
controller.close();
|
|
1669
|
+
}
|
|
1670
|
+
} });
|
|
1671
|
+
}
|
|
1672
|
+
buildControlData(nextOffset, cursor, upToDate, closed) {
|
|
1673
|
+
if (closed) return {
|
|
1674
|
+
streamNextOffset: nextOffset,
|
|
1675
|
+
streamClosed: true
|
|
1676
|
+
};
|
|
1677
|
+
return {
|
|
1678
|
+
streamNextOffset: nextOffset,
|
|
1679
|
+
streamCursor: cursor,
|
|
1680
|
+
...upToDate ? { upToDate: true } : {}
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
writeChunks(controller, chunks, enabled) {
|
|
1684
|
+
if (!enabled) return;
|
|
1685
|
+
for (const chunk of chunks) controller.enqueue(chunk);
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
|
|
1689
|
+
//#endregion
|
|
1690
|
+
//#region src/http.ts
|
|
1691
|
+
function createHttpHandler(options) {
|
|
1692
|
+
return new HttpHandler(options);
|
|
1693
|
+
}
|
|
1694
|
+
var HttpHandler = class {
|
|
1695
|
+
dispatch;
|
|
1696
|
+
constructor(options) {
|
|
1697
|
+
const path = new StreamPathService(options.pathPrefix ?? "/");
|
|
1698
|
+
const responses = new HttpResponseFactory();
|
|
1699
|
+
const bodyReader = new RequestBodyReader(options.maxMessageSize ?? 1024 * 1024, responses);
|
|
1700
|
+
const bodyCodec = new MessageBodyCodec();
|
|
1701
|
+
const producerHeaders = new ProducerHeaderParser();
|
|
1702
|
+
const readQuery = new ReadQueryParser();
|
|
1703
|
+
const etags = new EtagBuilder();
|
|
1704
|
+
const sseEvents = new SseEventEncoder(bodyCodec);
|
|
1705
|
+
const longPoll = new LongPollHttpService({
|
|
1706
|
+
responses,
|
|
1707
|
+
bodyCodec
|
|
1708
|
+
});
|
|
1709
|
+
const sse = new SseHttpService({
|
|
1710
|
+
responses,
|
|
1711
|
+
sseEvents,
|
|
1712
|
+
clock: systemClock
|
|
1713
|
+
});
|
|
1714
|
+
this.dispatch = new HttpDispatchService({
|
|
1715
|
+
protocol: options.protocol,
|
|
1716
|
+
path,
|
|
1717
|
+
responses,
|
|
1718
|
+
create: new CreateHttpService({
|
|
1719
|
+
protocol: options.protocol,
|
|
1720
|
+
path,
|
|
1721
|
+
responses,
|
|
1722
|
+
bodyReader
|
|
1723
|
+
}),
|
|
1724
|
+
append: new AppendHttpService({
|
|
1725
|
+
responses,
|
|
1726
|
+
bodyReader,
|
|
1727
|
+
producerHeaders
|
|
1728
|
+
}),
|
|
1729
|
+
read: new ReadHttpService({
|
|
1730
|
+
responses,
|
|
1731
|
+
bodyCodec,
|
|
1732
|
+
readQuery,
|
|
1733
|
+
etags,
|
|
1734
|
+
longPoll,
|
|
1735
|
+
sse
|
|
1736
|
+
}),
|
|
1737
|
+
metadata: new MetadataHttpService({ responses }),
|
|
1738
|
+
delete: new DeleteHttpService({ responses })
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
async fetch(request) {
|
|
1742
|
+
return this.dispatch.fetch(request);
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
|
|
1746
|
+
//#endregion
|
|
1747
|
+
//#region src/http/read-only-dispatch-service.ts
|
|
1748
|
+
var ReadOnlyHttpDispatchService = class {
|
|
1749
|
+
constructor(deps) {
|
|
1750
|
+
this.deps = deps;
|
|
1751
|
+
}
|
|
1752
|
+
async fetch(request) {
|
|
1753
|
+
return this.deps.responses.secure(await this.execute(request));
|
|
1754
|
+
}
|
|
1755
|
+
async execute(request) {
|
|
1756
|
+
const url = new URL(request.url);
|
|
1757
|
+
const streamId = this.deps.path.strip(url.pathname);
|
|
1758
|
+
if (!streamId || streamId === url.pathname) return this.deps.responses.badRequest(`Stream path required: ${this.deps.path.requiredPathPattern()}`);
|
|
1759
|
+
const ctx = {
|
|
1760
|
+
request,
|
|
1761
|
+
url,
|
|
1762
|
+
streamId
|
|
1763
|
+
};
|
|
1764
|
+
try {
|
|
1765
|
+
switch (request.method) {
|
|
1766
|
+
case "GET": return await this.withBoundStream(ctx, (bound) => this.deps.read.execute(bound));
|
|
1767
|
+
case "HEAD": return await this.withBoundStream(ctx, (bound) => this.deps.metadata.execute(bound));
|
|
1768
|
+
default: return this.deps.responses.methodNotAllowed();
|
|
1769
|
+
}
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
console.error("Error handling request:", error);
|
|
1772
|
+
return this.deps.responses.internalError();
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async withBoundStream(ctx, fn) {
|
|
1776
|
+
const lookup = await this.deps.protocol.get(ctx.streamId);
|
|
1777
|
+
if (lookup.status === "not-found") return this.deps.responses.notFound();
|
|
1778
|
+
if (lookup.status === "gone") return this.deps.responses.gone();
|
|
1779
|
+
if (isNotSupported(lookup)) return notSupportedResponse(lookup, this.deps.responses);
|
|
1780
|
+
return fn({
|
|
1781
|
+
...ctx,
|
|
1782
|
+
stream: lookup.stream
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
};
|
|
1786
|
+
|
|
1787
|
+
//#endregion
|
|
1788
|
+
//#region src/read-only-http.ts
|
|
1789
|
+
function createReadOnlyHttpHandler(options) {
|
|
1790
|
+
return new ReadOnlyHttpHandler(options);
|
|
1791
|
+
}
|
|
1792
|
+
var ReadOnlyHttpHandler = class {
|
|
1793
|
+
dispatch;
|
|
1794
|
+
constructor(options) {
|
|
1795
|
+
const path = new StreamPathService(options.pathPrefix ?? "/");
|
|
1796
|
+
const responses = new HttpResponseFactory();
|
|
1797
|
+
const bodyCodec = new MessageBodyCodec();
|
|
1798
|
+
const readQuery = new ReadQueryParser();
|
|
1799
|
+
const etags = new EtagBuilder();
|
|
1800
|
+
const sseEvents = new SseEventEncoder(bodyCodec);
|
|
1801
|
+
const longPoll = new LongPollHttpService({
|
|
1802
|
+
responses,
|
|
1803
|
+
bodyCodec
|
|
1804
|
+
});
|
|
1805
|
+
const sse = new SseHttpService({
|
|
1806
|
+
responses,
|
|
1807
|
+
sseEvents,
|
|
1808
|
+
clock: systemClock
|
|
1809
|
+
});
|
|
1810
|
+
this.dispatch = new ReadOnlyHttpDispatchService({
|
|
1811
|
+
protocol: options.protocol,
|
|
1812
|
+
path,
|
|
1813
|
+
responses,
|
|
1814
|
+
read: new ReadHttpService({
|
|
1815
|
+
responses,
|
|
1816
|
+
bodyCodec,
|
|
1817
|
+
readQuery,
|
|
1818
|
+
etags,
|
|
1819
|
+
longPoll,
|
|
1820
|
+
sse
|
|
1821
|
+
}),
|
|
1822
|
+
metadata: new MetadataHttpService({ responses })
|
|
1823
|
+
});
|
|
1824
|
+
}
|
|
1825
|
+
async fetch(request) {
|
|
1826
|
+
return this.dispatch.fetch(request);
|
|
1827
|
+
}
|
|
1828
|
+
};
|
|
1829
|
+
|
|
1830
|
+
//#endregion
|
|
1831
|
+
export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, createHttpHandler, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
|