@streamsy/core 0.0.1 → 0.1.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/dist/index.d.ts +86 -5
- package/dist/index.js +423 -63
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -180,6 +180,15 @@ interface AppendOptions {
|
|
|
180
180
|
seq?: string;
|
|
181
181
|
producer?: ProducerOptions;
|
|
182
182
|
close?: boolean;
|
|
183
|
+
/**
|
|
184
|
+
* Optimistic-concurrency precondition: append only if the stream's tail
|
|
185
|
+
* offset still equals this offset. On mismatch the append fails with a
|
|
186
|
+
* `conflict`/`expected-offset` result carrying the actual tail, and no
|
|
187
|
+
* state (messages, close flag, producer state) is changed. `ZERO_OFFSET`
|
|
188
|
+
* means "append only if the stream is still empty". Streamsy extension to
|
|
189
|
+
* the Durable Streams protocol.
|
|
190
|
+
*/
|
|
191
|
+
expectedOffset?: string;
|
|
183
192
|
}
|
|
184
193
|
interface ReadOptions {
|
|
185
194
|
offset?: string;
|
|
@@ -226,16 +235,29 @@ type CreateResult = {
|
|
|
226
235
|
contentType: string;
|
|
227
236
|
closed?: boolean;
|
|
228
237
|
} | CreateFailureResult;
|
|
229
|
-
type AppendConflictReason = "content-type" | "sequence" | "closed";
|
|
238
|
+
type AppendConflictReason = "content-type" | "sequence" | "closed" | "expected-offset";
|
|
230
239
|
type AppendResult = {
|
|
231
240
|
status: "appended";
|
|
232
|
-
|
|
241
|
+
/**
|
|
242
|
+
* Exact stream offset after this append: the offset of the last message
|
|
243
|
+
* written by it (for a close-only append with no body, the unchanged
|
|
244
|
+
* tail offset). This is the write-acknowledgement token — a reader or
|
|
245
|
+
* mirror that has passed `offset` has observed this write. Because reads
|
|
246
|
+
* are after-exclusive, it is also the read cursor.
|
|
247
|
+
*/
|
|
248
|
+
offset: string;
|
|
233
249
|
producerEpoch?: number;
|
|
234
250
|
producerSeq?: number;
|
|
235
251
|
closed?: boolean;
|
|
236
252
|
} | {
|
|
237
253
|
status: "duplicate";
|
|
238
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Current tail offset at acknowledgement time. The originally appended
|
|
256
|
+
* message sits at or before `offset`, so it remains a valid
|
|
257
|
+
* write-acknowledgement token for sync ("synced once your mirror passes
|
|
258
|
+
* offset X").
|
|
259
|
+
*/
|
|
260
|
+
offset: string;
|
|
239
261
|
producerEpoch: number;
|
|
240
262
|
producerSeq: number;
|
|
241
263
|
closed?: boolean;
|
|
@@ -246,8 +268,17 @@ type AppendResult = {
|
|
|
246
268
|
} | {
|
|
247
269
|
status: "conflict";
|
|
248
270
|
conflictReason: "closed";
|
|
249
|
-
|
|
271
|
+
offset: string;
|
|
250
272
|
closed: true;
|
|
273
|
+
} | {
|
|
274
|
+
status: "conflict";
|
|
275
|
+
conflictReason: "expected-offset";
|
|
276
|
+
/**
|
|
277
|
+
* Actual tail offset at the time the `expectedOffset` precondition
|
|
278
|
+
* failed, so callers can see how far behind they were. Retry loops
|
|
279
|
+
* should re-read state and rebuild the append from the new tail.
|
|
280
|
+
*/
|
|
281
|
+
offset: string;
|
|
251
282
|
} | {
|
|
252
283
|
status: "conflict";
|
|
253
284
|
conflictReason: "content-type" | "sequence";
|
|
@@ -353,6 +384,56 @@ declare class StreamProtocol implements StreamProtocolFactory {
|
|
|
353
384
|
private withStreamMutationLock;
|
|
354
385
|
}
|
|
355
386
|
|
|
387
|
+
//#endregion
|
|
388
|
+
//#region src/storage/memory/stream.d.ts
|
|
389
|
+
declare class MemoryStream implements Stream {
|
|
390
|
+
readonly id: StreamId;
|
|
391
|
+
private readonly deleteFromState;
|
|
392
|
+
private readonly records;
|
|
393
|
+
private readonly messages;
|
|
394
|
+
private readonly producers;
|
|
395
|
+
private readonly lock;
|
|
396
|
+
private readonly notifier;
|
|
397
|
+
private readonly timeout;
|
|
398
|
+
constructor(id: StreamId, deleteFromState: () => void);
|
|
399
|
+
getRecord(): Promise<StreamRecord | null>;
|
|
400
|
+
createRecord(record: StreamRecord): Promise<CreateStreamRecordResult>;
|
|
401
|
+
updateRecord(patch: StreamRecordPatch): Promise<StreamRecord>;
|
|
402
|
+
deleteRecord(): Promise<void>;
|
|
403
|
+
appendMessages(messages: StoredMessage[]): Promise<void>;
|
|
404
|
+
listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
|
|
405
|
+
deleteMessages(): Promise<void>;
|
|
406
|
+
getProducerState(producerId: string): Promise<ProducerState | undefined>;
|
|
407
|
+
setProducerState(producerId: string, state: ProducerState): Promise<void>;
|
|
408
|
+
deleteProducerStates(): Promise<void>;
|
|
409
|
+
incrementChildRefCount(): Promise<number>;
|
|
410
|
+
decrementChildRefCount(): Promise<number>;
|
|
411
|
+
withMutationLock<T>(fn: () => Promise<T>): Promise<T>;
|
|
412
|
+
waitForEvent(options: WaitForEventOptions): Promise<WaitForEventResult>;
|
|
413
|
+
notify(type: StreamEventType): Promise<void> | void;
|
|
414
|
+
scheduleExpiry(at: number, callback?: () => Promise<void>): Promise<void> | void;
|
|
415
|
+
cancelExpiry(): Promise<void> | void;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region src/storage/memory/state.d.ts
|
|
420
|
+
/** Shared in-memory stream registry. */
|
|
421
|
+
declare class MemoryStreamState {
|
|
422
|
+
private readonly streams;
|
|
423
|
+
getStream(id: string): MemoryStream;
|
|
424
|
+
stream(id: string): MemoryStream;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
//#endregion
|
|
428
|
+
//#region src/storage/memory/factory.d.ts
|
|
429
|
+
interface MemoryStreamFactoryOptions {
|
|
430
|
+
/**
|
|
431
|
+
* Share an existing memory state. Omit to get a fresh, isolated state.
|
|
432
|
+
*/
|
|
433
|
+
state?: MemoryStreamState;
|
|
434
|
+
}
|
|
435
|
+
declare function createMemoryStreamFactory(options?: MemoryStreamFactoryOptions): StreamFactory;
|
|
436
|
+
|
|
356
437
|
//#endregion
|
|
357
438
|
//#region src/http/types.d.ts
|
|
358
439
|
interface HttpHandlerOptions {
|
|
@@ -418,4 +499,4 @@ declare function notSupportedResponse(result: NotSupportedResult, responses: Htt
|
|
|
418
499
|
declare function maybeNotSupportedResponse<T>(result: T | NotSupportedResult, responses: HttpResponseFactory): Response | null;
|
|
419
500
|
|
|
420
501
|
//#endregion
|
|
421
|
-
export { AppendConflictReason, AppendOptions, AppendResult, Clock, CreateConflictReason, CreateOptions, CreateResult, CreateStreamRecordResult, DeleteResult, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, ListMessagesOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StoredMessage, Stream, StreamConfig, StreamEventHub, StreamEventType, StreamExpiryScheduler, StreamFactory, StreamId, StreamLifecycleState, StreamMessageStore, StreamMutationCoordinator, StreamProducerStore, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamRecord, StreamRecordPatch, StreamRecordStore, StreamReferenceTracker, WaitForEventOptions, WaitForEventResult, ZERO_OFFSET, createHttpHandler, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
|
|
502
|
+
export { AppendConflictReason, AppendOptions, AppendResult, Clock, CreateConflictReason, CreateOptions, CreateResult, CreateStreamRecordResult, DeleteResult, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, ListMessagesOptions, MemoryStreamFactoryOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StoredMessage, Stream, StreamConfig, StreamEventHub, StreamEventType, StreamExpiryScheduler, StreamFactory, StreamId, StreamLifecycleState, StreamMessageStore, StreamMutationCoordinator, StreamProducerStore, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamRecord, StreamRecordPatch, StreamRecordStore, StreamReferenceTracker, WaitForEventOptions, WaitForEventResult, ZERO_OFFSET, createHttpHandler, createMemoryStreamFactory, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
|
package/dist/index.js
CHANGED
|
@@ -51,7 +51,7 @@ function rejectionToAppendResult(rejection, currentOffset, isClosed) {
|
|
|
51
51
|
switch (rejection.kind) {
|
|
52
52
|
case "duplicate": return {
|
|
53
53
|
status: "duplicate",
|
|
54
|
-
|
|
54
|
+
offset: currentOffset,
|
|
55
55
|
producerEpoch: rejection.epoch,
|
|
56
56
|
producerSeq: rejection.lastSeq,
|
|
57
57
|
closed: isClosed
|
|
@@ -177,20 +177,46 @@ function frameMessages(data, contentType) {
|
|
|
177
177
|
|
|
178
178
|
//#endregion
|
|
179
179
|
//#region src/protocol/append-service.ts
|
|
180
|
-
|
|
180
|
+
/**
|
|
181
|
+
* Mutators return the stream's post-mutation tail offset: the offset of the
|
|
182
|
+
* last message they wrote (or the unchanged tail for a body-less close). That
|
|
183
|
+
* value is both the exact appended offset and, because reads are
|
|
184
|
+
* after-exclusive, the read cursor.
|
|
185
|
+
*/
|
|
186
|
+
function appendedResult(offset, validation, closed) {
|
|
181
187
|
if (validation?.kind === "accepted") return {
|
|
182
188
|
status: "appended",
|
|
183
|
-
|
|
189
|
+
offset,
|
|
184
190
|
producerEpoch: validation.proposedState.epoch,
|
|
185
191
|
producerSeq: validation.proposedState.lastSeq,
|
|
186
192
|
closed
|
|
187
193
|
};
|
|
188
194
|
return {
|
|
189
195
|
status: "appended",
|
|
190
|
-
|
|
196
|
+
offset,
|
|
191
197
|
closed
|
|
192
198
|
};
|
|
193
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Compare-and-swap precondition for optimistic concurrency: when
|
|
202
|
+
* `expectedOffset` is set, the append proceeds only if the stream's tail
|
|
203
|
+
* still equals it. Atomicity with the mutation is guaranteed because the
|
|
204
|
+
* protocol loads the record and runs this service inside the per-stream
|
|
205
|
+
* mutation lock.
|
|
206
|
+
*
|
|
207
|
+
* Pinned precedence: checked after the closed/content-type/sequence conflicts
|
|
208
|
+
* and before any mutation, so a CAS failure never advances producer state.
|
|
209
|
+
* A close-only append on an already-closed stream stays an idempotent
|
|
210
|
+
* success and skips the check (nothing is written, so no update can be lost).
|
|
211
|
+
*/
|
|
212
|
+
function expectedOffsetConflict(record, options) {
|
|
213
|
+
if (options.expectedOffset === void 0 || options.expectedOffset === record.currentOffset) return null;
|
|
214
|
+
return {
|
|
215
|
+
status: "conflict",
|
|
216
|
+
conflictReason: "expected-offset",
|
|
217
|
+
offset: record.currentOffset
|
|
218
|
+
};
|
|
219
|
+
}
|
|
194
220
|
var AppendService = class {
|
|
195
221
|
constructor(deps) {
|
|
196
222
|
this.deps = deps;
|
|
@@ -211,9 +237,11 @@ var AppendService = class {
|
|
|
211
237
|
if (wantClose && !hasBody) {
|
|
212
238
|
if (isClosed) return {
|
|
213
239
|
status: "appended",
|
|
214
|
-
|
|
240
|
+
offset: record.currentOffset,
|
|
215
241
|
closed: true
|
|
216
242
|
};
|
|
243
|
+
const casConflict$1 = expectedOffsetConflict(record, options);
|
|
244
|
+
if (casConflict$1) return casConflict$1;
|
|
217
245
|
const nextOffset$1 = await this.deps.mutators.closeRecord(record, [], options.seq);
|
|
218
246
|
const persisted$1 = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
|
|
219
247
|
if (persisted$1?.status === "not-supported") return persisted$1;
|
|
@@ -223,7 +251,7 @@ var AppendService = class {
|
|
|
223
251
|
status: "conflict",
|
|
224
252
|
conflictReason: "closed",
|
|
225
253
|
closed: true,
|
|
226
|
-
|
|
254
|
+
offset: record.currentOffset
|
|
227
255
|
};
|
|
228
256
|
if (!contentTypeMatches(record.config.contentType, options.contentType)) return {
|
|
229
257
|
status: "conflict",
|
|
@@ -233,6 +261,8 @@ var AppendService = class {
|
|
|
233
261
|
status: "conflict",
|
|
234
262
|
conflictReason: "sequence"
|
|
235
263
|
};
|
|
264
|
+
const casConflict = expectedOffsetConflict(record, options);
|
|
265
|
+
if (casConflict) return casConflict;
|
|
236
266
|
const processed = frameMessages(options.data, record.config.contentType);
|
|
237
267
|
const nextOffset = wantClose ? await this.deps.mutators.closeRecord(record, processed, options.seq) : await this.deps.mutators.appendMessages(record, processed, options.seq);
|
|
238
268
|
const persisted = await this.deps.producerIdempotency.persistIfAccepted(options.producer, producerValidation);
|
|
@@ -916,6 +946,292 @@ var StreamProtocol = class {
|
|
|
916
946
|
}
|
|
917
947
|
};
|
|
918
948
|
|
|
949
|
+
//#endregion
|
|
950
|
+
//#region src/storage/memory/lib/clone.ts
|
|
951
|
+
function clone(value) {
|
|
952
|
+
if (value === null || value === void 0) return value;
|
|
953
|
+
return structuredClone(value);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/storage/memory/stores/message-store.ts
|
|
958
|
+
var MessageStore = class {
|
|
959
|
+
messages = [];
|
|
960
|
+
constructor(records) {
|
|
961
|
+
this.records = records;
|
|
962
|
+
}
|
|
963
|
+
async appendMessages(messages) {
|
|
964
|
+
this.records.requireRecord();
|
|
965
|
+
this.messages.push(...clone(messages));
|
|
966
|
+
}
|
|
967
|
+
async listMessages(options = {}) {
|
|
968
|
+
let out = this.messages;
|
|
969
|
+
if (options.after) out = out.filter((m) => m.offset > options.after);
|
|
970
|
+
if (options.until) out = out.filter((m) => m.offset <= options.until);
|
|
971
|
+
if (options.limit !== void 0) out = out.slice(0, options.limit);
|
|
972
|
+
return clone(out);
|
|
973
|
+
}
|
|
974
|
+
async deleteMessages() {
|
|
975
|
+
this.messages = [];
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
|
|
979
|
+
//#endregion
|
|
980
|
+
//#region src/storage/memory/stores/producer-store.ts
|
|
981
|
+
var ProducerStore = class {
|
|
982
|
+
producers = new Map();
|
|
983
|
+
constructor(records) {
|
|
984
|
+
this.records = records;
|
|
985
|
+
}
|
|
986
|
+
async getProducerState(producerId) {
|
|
987
|
+
return clone(this.producers.get(producerId));
|
|
988
|
+
}
|
|
989
|
+
async setProducerState(producerId, producerState) {
|
|
990
|
+
this.records.requireRecord();
|
|
991
|
+
this.producers.set(producerId, clone(producerState));
|
|
992
|
+
}
|
|
993
|
+
async deleteProducerStates() {
|
|
994
|
+
this.producers.clear();
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
|
|
998
|
+
//#endregion
|
|
999
|
+
//#region src/storage/memory/stores/record-store.ts
|
|
1000
|
+
var RecordStore = class {
|
|
1001
|
+
record;
|
|
1002
|
+
constructor(id) {
|
|
1003
|
+
this.id = id;
|
|
1004
|
+
}
|
|
1005
|
+
async getRecord() {
|
|
1006
|
+
return clone(this.record ?? null);
|
|
1007
|
+
}
|
|
1008
|
+
async createRecord(record) {
|
|
1009
|
+
if (record.id !== this.id) throw new Error(`Record id ${record.id} does not match bound stream ${this.id}`);
|
|
1010
|
+
if (this.record) return {
|
|
1011
|
+
status: "exists",
|
|
1012
|
+
record: clone(this.record)
|
|
1013
|
+
};
|
|
1014
|
+
this.record = clone(record);
|
|
1015
|
+
return { status: "created" };
|
|
1016
|
+
}
|
|
1017
|
+
async updateRecord(patch) {
|
|
1018
|
+
const record = this.requireRecord();
|
|
1019
|
+
this.record = {
|
|
1020
|
+
...record,
|
|
1021
|
+
config: {
|
|
1022
|
+
...record.config,
|
|
1023
|
+
...patch.config
|
|
1024
|
+
},
|
|
1025
|
+
lifecycle: {
|
|
1026
|
+
...record.lifecycle,
|
|
1027
|
+
...patch.lifecycle
|
|
1028
|
+
},
|
|
1029
|
+
currentOffset: patch.currentOffset ?? record.currentOffset,
|
|
1030
|
+
counter: patch.counter ?? record.counter
|
|
1031
|
+
};
|
|
1032
|
+
return clone(this.record);
|
|
1033
|
+
}
|
|
1034
|
+
async deleteRecord() {
|
|
1035
|
+
this.record = void 0;
|
|
1036
|
+
}
|
|
1037
|
+
async incrementChildRefCount() {
|
|
1038
|
+
const updated = this.updateStoredRecord((record) => {
|
|
1039
|
+
const next = record.lifecycle.childRefCount + 1;
|
|
1040
|
+
return {
|
|
1041
|
+
...record,
|
|
1042
|
+
lifecycle: {
|
|
1043
|
+
...record.lifecycle,
|
|
1044
|
+
childRefCount: next
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
});
|
|
1048
|
+
return updated.lifecycle.childRefCount;
|
|
1049
|
+
}
|
|
1050
|
+
async decrementChildRefCount() {
|
|
1051
|
+
const updated = this.updateStoredRecord((record) => {
|
|
1052
|
+
const next = Math.max(0, record.lifecycle.childRefCount - 1);
|
|
1053
|
+
return {
|
|
1054
|
+
...record,
|
|
1055
|
+
lifecycle: {
|
|
1056
|
+
...record.lifecycle,
|
|
1057
|
+
childRefCount: next
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
});
|
|
1061
|
+
return updated.lifecycle.childRefCount;
|
|
1062
|
+
}
|
|
1063
|
+
requireRecord() {
|
|
1064
|
+
if (!this.record) throw new Error(`Stream not found: ${this.id}`);
|
|
1065
|
+
return this.record;
|
|
1066
|
+
}
|
|
1067
|
+
updateStoredRecord(update) {
|
|
1068
|
+
this.record = update(this.requireRecord());
|
|
1069
|
+
return this.record;
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
//#endregion
|
|
1074
|
+
//#region src/storage/memory/utils/lock.ts
|
|
1075
|
+
var MemoryLock = class {
|
|
1076
|
+
lock;
|
|
1077
|
+
async withLock(fn) {
|
|
1078
|
+
while (this.lock) await this.lock;
|
|
1079
|
+
let release;
|
|
1080
|
+
this.lock = new Promise((resolve) => release = resolve);
|
|
1081
|
+
try {
|
|
1082
|
+
return await fn();
|
|
1083
|
+
} finally {
|
|
1084
|
+
this.lock = void 0;
|
|
1085
|
+
release();
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
|
|
1090
|
+
//#endregion
|
|
1091
|
+
//#region src/storage/memory/utils/notifier.ts
|
|
1092
|
+
var MemoryNotifier = class {
|
|
1093
|
+
waiters = new Set();
|
|
1094
|
+
waitForEvent(options) {
|
|
1095
|
+
return new Promise((resolve) => {
|
|
1096
|
+
const timeout = setTimeout(() => finish({ status: "timeout" }), options.timeoutMs);
|
|
1097
|
+
const finish = (result) => {
|
|
1098
|
+
clearTimeout(timeout);
|
|
1099
|
+
this.waiters.delete(finish);
|
|
1100
|
+
resolve(result);
|
|
1101
|
+
};
|
|
1102
|
+
this.waiters.add(finish);
|
|
1103
|
+
options.signal?.addEventListener("abort", () => finish({ status: "aborted" }), { once: true });
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
notify(type) {
|
|
1107
|
+
const waiters = [...this.waiters];
|
|
1108
|
+
this.waiters.clear();
|
|
1109
|
+
for (const waiter of waiters) waiter({
|
|
1110
|
+
status: "notified",
|
|
1111
|
+
type
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
};
|
|
1115
|
+
|
|
1116
|
+
//#endregion
|
|
1117
|
+
//#region src/storage/memory/utils/timeout-scheduler.ts
|
|
1118
|
+
var TimeoutScheduler = class {
|
|
1119
|
+
timer;
|
|
1120
|
+
schedule(at, callback) {
|
|
1121
|
+
this.cancel();
|
|
1122
|
+
if (!callback) return;
|
|
1123
|
+
const delay = Math.max(0, at - Date.now());
|
|
1124
|
+
this.timer = setTimeout(() => void callback(), delay);
|
|
1125
|
+
}
|
|
1126
|
+
cancel() {
|
|
1127
|
+
if (this.timer) clearTimeout(this.timer);
|
|
1128
|
+
this.timer = void 0;
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/storage/memory/stream.ts
|
|
1134
|
+
var MemoryStream = class {
|
|
1135
|
+
records;
|
|
1136
|
+
messages;
|
|
1137
|
+
producers;
|
|
1138
|
+
lock;
|
|
1139
|
+
notifier;
|
|
1140
|
+
timeout;
|
|
1141
|
+
constructor(id, deleteFromState) {
|
|
1142
|
+
this.id = id;
|
|
1143
|
+
this.deleteFromState = deleteFromState;
|
|
1144
|
+
this.records = new RecordStore(id);
|
|
1145
|
+
this.messages = new MessageStore(this.records);
|
|
1146
|
+
this.producers = new ProducerStore(this.records);
|
|
1147
|
+
this.lock = new MemoryLock();
|
|
1148
|
+
this.notifier = new MemoryNotifier();
|
|
1149
|
+
this.timeout = new TimeoutScheduler();
|
|
1150
|
+
}
|
|
1151
|
+
getRecord() {
|
|
1152
|
+
return this.records.getRecord();
|
|
1153
|
+
}
|
|
1154
|
+
createRecord(record) {
|
|
1155
|
+
return this.records.createRecord(record);
|
|
1156
|
+
}
|
|
1157
|
+
updateRecord(patch) {
|
|
1158
|
+
return this.records.updateRecord(patch);
|
|
1159
|
+
}
|
|
1160
|
+
async deleteRecord() {
|
|
1161
|
+
await this.records.deleteRecord();
|
|
1162
|
+
await this.messages.deleteMessages();
|
|
1163
|
+
await this.producers.deleteProducerStates();
|
|
1164
|
+
this.timeout.cancel();
|
|
1165
|
+
this.deleteFromState();
|
|
1166
|
+
}
|
|
1167
|
+
appendMessages(messages) {
|
|
1168
|
+
return this.messages.appendMessages(messages);
|
|
1169
|
+
}
|
|
1170
|
+
listMessages(options) {
|
|
1171
|
+
return this.messages.listMessages(options);
|
|
1172
|
+
}
|
|
1173
|
+
deleteMessages() {
|
|
1174
|
+
return this.messages.deleteMessages();
|
|
1175
|
+
}
|
|
1176
|
+
getProducerState(producerId) {
|
|
1177
|
+
return this.producers.getProducerState(producerId);
|
|
1178
|
+
}
|
|
1179
|
+
setProducerState(producerId, state) {
|
|
1180
|
+
return this.producers.setProducerState(producerId, state);
|
|
1181
|
+
}
|
|
1182
|
+
deleteProducerStates() {
|
|
1183
|
+
return this.producers.deleteProducerStates();
|
|
1184
|
+
}
|
|
1185
|
+
incrementChildRefCount() {
|
|
1186
|
+
return this.records.incrementChildRefCount();
|
|
1187
|
+
}
|
|
1188
|
+
decrementChildRefCount() {
|
|
1189
|
+
return this.records.decrementChildRefCount();
|
|
1190
|
+
}
|
|
1191
|
+
withMutationLock(fn) {
|
|
1192
|
+
return this.lock.withLock(fn);
|
|
1193
|
+
}
|
|
1194
|
+
waitForEvent(options) {
|
|
1195
|
+
return this.notifier.waitForEvent(options);
|
|
1196
|
+
}
|
|
1197
|
+
notify(type) {
|
|
1198
|
+
return this.notifier.notify(type);
|
|
1199
|
+
}
|
|
1200
|
+
scheduleExpiry(at, callback) {
|
|
1201
|
+
return this.timeout.schedule(at, callback);
|
|
1202
|
+
}
|
|
1203
|
+
cancelExpiry() {
|
|
1204
|
+
return this.timeout.cancel();
|
|
1205
|
+
}
|
|
1206
|
+
};
|
|
1207
|
+
|
|
1208
|
+
//#endregion
|
|
1209
|
+
//#region src/storage/memory/state.ts
|
|
1210
|
+
/** Shared in-memory stream registry. */
|
|
1211
|
+
var MemoryStreamState = class {
|
|
1212
|
+
streams = new Map();
|
|
1213
|
+
getStream(id) {
|
|
1214
|
+
let stream = this.streams.get(id);
|
|
1215
|
+
if (!stream) {
|
|
1216
|
+
stream = new MemoryStream(id, () => this.streams.delete(id));
|
|
1217
|
+
this.streams.set(id, stream);
|
|
1218
|
+
}
|
|
1219
|
+
return stream;
|
|
1220
|
+
}
|
|
1221
|
+
stream(id) {
|
|
1222
|
+
return this.getStream(id);
|
|
1223
|
+
}
|
|
1224
|
+
};
|
|
1225
|
+
|
|
1226
|
+
//#endregion
|
|
1227
|
+
//#region src/storage/memory/factory.ts
|
|
1228
|
+
function createMemoryStreamFactory(options = {}) {
|
|
1229
|
+
const state = options.state ?? new MemoryStreamState();
|
|
1230
|
+
return { async getStream(streamId) {
|
|
1231
|
+
return state.getStream(streamId);
|
|
1232
|
+
} };
|
|
1233
|
+
}
|
|
1234
|
+
|
|
919
1235
|
//#endregion
|
|
920
1236
|
//#region src/http/not-supported.ts
|
|
921
1237
|
function notSupportedResponse(result, responses) {
|
|
@@ -1257,7 +1573,8 @@ var AppendHttpService = class {
|
|
|
1257
1573
|
contentType: parsed.contentType ?? "application/octet-stream",
|
|
1258
1574
|
seq: parsed.seq,
|
|
1259
1575
|
producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
|
|
1260
|
-
close: parsed.wantClose
|
|
1576
|
+
close: parsed.wantClose,
|
|
1577
|
+
expectedOffset: parsed.expectedOffset
|
|
1261
1578
|
});
|
|
1262
1579
|
if (result.status === "not-supported") return maybeNotSupportedResponse(result, this.deps.responses);
|
|
1263
1580
|
return this.toResponse(result, parsed.producerHeaders, body.isEmpty);
|
|
@@ -1268,11 +1585,17 @@ var AppendHttpService = class {
|
|
|
1268
1585
|
ok: false,
|
|
1269
1586
|
response: this.deps.responses.badRequest("Invalid producer headers")
|
|
1270
1587
|
};
|
|
1588
|
+
const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
|
|
1589
|
+
if (expectedOffset !== void 0 && !isValidOffset(expectedOffset)) return {
|
|
1590
|
+
ok: false,
|
|
1591
|
+
response: this.deps.responses.badRequest("Invalid expected offset")
|
|
1592
|
+
};
|
|
1271
1593
|
return {
|
|
1272
1594
|
ok: true,
|
|
1273
1595
|
contentType: request.headers.get("content-type"),
|
|
1274
1596
|
seq: request.headers.get("stream-seq") ?? void 0,
|
|
1275
1597
|
wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
1598
|
+
expectedOffset,
|
|
1276
1599
|
producerHeaders
|
|
1277
1600
|
};
|
|
1278
1601
|
}
|
|
@@ -1314,8 +1637,9 @@ var AppendHttpService = class {
|
|
|
1314
1637
|
case "conflict": {
|
|
1315
1638
|
if (result.conflictReason === "closed") return this.deps.responses.empty(409, {
|
|
1316
1639
|
"stream-closed": "true",
|
|
1317
|
-
"stream-next-offset": result.
|
|
1640
|
+
"stream-next-offset": result.offset
|
|
1318
1641
|
});
|
|
1642
|
+
if (result.conflictReason === "expected-offset") return this.deps.responses.conflict("Expected offset mismatch", { "stream-next-offset": result.offset });
|
|
1319
1643
|
return this.deps.responses.conflict(result.conflictReason === "content-type" ? "Content-Type mismatch" : "Sequence conflict");
|
|
1320
1644
|
}
|
|
1321
1645
|
case "stale-epoch": return this.deps.responses.text("Stale producer epoch", 403, { "producer-epoch": String(result.currentEpoch) });
|
|
@@ -1325,14 +1649,14 @@ var AppendHttpService = class {
|
|
|
1325
1649
|
});
|
|
1326
1650
|
case "invalid-epoch-seq": return this.deps.responses.badRequest("New epoch must start at seq=0");
|
|
1327
1651
|
case "duplicate": return this.deps.responses.empty(204, {
|
|
1328
|
-
"stream-next-offset": result.
|
|
1652
|
+
"stream-next-offset": result.offset,
|
|
1329
1653
|
"producer-epoch": String(result.producerEpoch),
|
|
1330
1654
|
"producer-seq": String(result.producerSeq),
|
|
1331
1655
|
...result.closed ? { "stream-closed": "true" } : {}
|
|
1332
1656
|
});
|
|
1333
1657
|
case "appended": {
|
|
1334
1658
|
const headers = {
|
|
1335
|
-
"stream-next-offset": result.
|
|
1659
|
+
"stream-next-offset": result.offset,
|
|
1336
1660
|
...result.closed ? { "stream-closed": "true" } : {}
|
|
1337
1661
|
};
|
|
1338
1662
|
if (result.producerEpoch !== void 0) headers["producer-epoch"] = String(result.producerEpoch);
|
|
@@ -1612,62 +1936,102 @@ var SseHttpService = class {
|
|
|
1612
1936
|
const connectionStartTime = Date.now();
|
|
1613
1937
|
const sseEvents = this.deps.sseEvents;
|
|
1614
1938
|
const clock = this.deps.clock;
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
let
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
}
|
|
1625
|
-
|
|
1626
|
-
|
|
1939
|
+
let cancelActiveRead;
|
|
1940
|
+
return new ReadableStream({
|
|
1941
|
+
start: async (controller) => {
|
|
1942
|
+
const liveReadAbortController = new AbortController();
|
|
1943
|
+
let inactive = false;
|
|
1944
|
+
const shouldStop = () => inactive || liveReadAbortController.signal.aborted;
|
|
1945
|
+
const stop = () => {
|
|
1946
|
+
inactive = true;
|
|
1947
|
+
liveReadAbortController.abort();
|
|
1948
|
+
};
|
|
1949
|
+
cancelActiveRead = stop;
|
|
1950
|
+
const close = () => {
|
|
1951
|
+
if (inactive) return;
|
|
1952
|
+
inactive = true;
|
|
1953
|
+
liveReadAbortController.abort();
|
|
1954
|
+
try {
|
|
1627
1955
|
controller.close();
|
|
1628
|
-
|
|
1956
|
+
} catch {}
|
|
1957
|
+
};
|
|
1958
|
+
const enqueue = (chunk) => {
|
|
1959
|
+
if (shouldStop()) return false;
|
|
1960
|
+
try {
|
|
1961
|
+
controller.enqueue(chunk);
|
|
1962
|
+
return true;
|
|
1963
|
+
} catch {
|
|
1964
|
+
stop();
|
|
1965
|
+
return false;
|
|
1629
1966
|
}
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1967
|
+
};
|
|
1968
|
+
const writeChunks = (chunks, enabled) => {
|
|
1969
|
+
if (!enabled) return true;
|
|
1970
|
+
for (const chunk of chunks) if (!enqueue(chunk)) return false;
|
|
1971
|
+
return true;
|
|
1972
|
+
};
|
|
1973
|
+
try {
|
|
1974
|
+
let initialNextOffset;
|
|
1975
|
+
let initialUpToDate;
|
|
1976
|
+
let initialClosed = false;
|
|
1977
|
+
if (currentOffset === "now") {
|
|
1978
|
+
initialNextOffset = metadataNextOffset;
|
|
1979
|
+
initialUpToDate = true;
|
|
1980
|
+
initialClosed = metadataClosed;
|
|
1981
|
+
} else {
|
|
1982
|
+
const initialResult = await stream.read({ offset: currentOffset === "-1" ? void 0 : currentOffset });
|
|
1983
|
+
if (shouldStop()) return;
|
|
1984
|
+
if (initialResult.status === "not-found" || initialResult.status === "gone") {
|
|
1985
|
+
close();
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
if (!writeChunks(sseEvents.dataEvent(initialResult.messages, encoding), initialResult.messages.length > 0)) return;
|
|
1989
|
+
initialNextOffset = initialResult.nextOffset;
|
|
1990
|
+
initialUpToDate = initialResult.upToDate;
|
|
1991
|
+
initialClosed = initialResult.closed === true;
|
|
1646
1992
|
}
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
});
|
|
1652
|
-
if (result.status === "not-found" || result.status === "not-supported") {
|
|
1653
|
-
controller.close();
|
|
1993
|
+
currentCursor = generateCursor(clock, currentCursor);
|
|
1994
|
+
if (!enqueue(sseEvents.controlEvent(this.buildControlData(initialNextOffset, currentCursor, initialUpToDate, initialClosed)))) return;
|
|
1995
|
+
if (initialClosed) {
|
|
1996
|
+
close();
|
|
1654
1997
|
return;
|
|
1655
1998
|
}
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1999
|
+
currentOffset = initialNextOffset;
|
|
2000
|
+
while (!shouldStop()) {
|
|
2001
|
+
if (Date.now() - connectionStartTime >= CONNECTION_TIMEOUT_MS) {
|
|
2002
|
+
close();
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
const result = await stream.readLive({
|
|
2006
|
+
offset: currentOffset,
|
|
2007
|
+
mode: "sse",
|
|
2008
|
+
cursor: currentCursor,
|
|
2009
|
+
signal: liveReadAbortController.signal
|
|
2010
|
+
});
|
|
2011
|
+
if (shouldStop()) return;
|
|
2012
|
+
if (result.status === "not-found" || result.status === "gone" || result.status === "not-supported") {
|
|
2013
|
+
close();
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
2016
|
+
if (!writeChunks(sseEvents.dataEvent(result.messages, encoding), result.messages.length > 0)) return;
|
|
2017
|
+
if (!enqueue(sseEvents.controlEvent(this.buildControlData(result.nextOffset, result.cursor, result.upToDate, result.closed === true)))) return;
|
|
2018
|
+
currentOffset = result.nextOffset;
|
|
2019
|
+
currentCursor = result.cursor;
|
|
2020
|
+
if (result.closed) {
|
|
2021
|
+
close();
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
if (result.status === "timeout") continue;
|
|
1663
2025
|
}
|
|
1664
|
-
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
if (!shouldStop()) console.error("SSE stream error:", error);
|
|
2028
|
+
close();
|
|
1665
2029
|
}
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
|
-
|
|
2030
|
+
},
|
|
2031
|
+
cancel: () => {
|
|
2032
|
+
cancelActiveRead?.();
|
|
1669
2033
|
}
|
|
1670
|
-
}
|
|
2034
|
+
});
|
|
1671
2035
|
}
|
|
1672
2036
|
buildControlData(nextOffset, cursor, upToDate, closed) {
|
|
1673
2037
|
if (closed) return {
|
|
@@ -1680,10 +2044,6 @@ var SseHttpService = class {
|
|
|
1680
2044
|
...upToDate ? { upToDate: true } : {}
|
|
1681
2045
|
};
|
|
1682
2046
|
}
|
|
1683
|
-
writeChunks(controller, chunks, enabled) {
|
|
1684
|
-
if (!enabled) return;
|
|
1685
|
-
for (const chunk of chunks) controller.enqueue(chunk);
|
|
1686
|
-
}
|
|
1687
2047
|
};
|
|
1688
2048
|
|
|
1689
2049
|
//#endregion
|
|
@@ -1828,4 +2188,4 @@ var ReadOnlyHttpHandler = class {
|
|
|
1828
2188
|
};
|
|
1829
2189
|
|
|
1830
2190
|
//#endregion
|
|
1831
|
-
export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, createHttpHandler, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
|
|
2191
|
+
export { HttpHandler, NotSupportedError, ReadOnlyHttpHandler, StreamProtocol, ZERO_OFFSET, createHttpHandler, createMemoryStreamFactory, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
|