@streamsy/core 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/cursor-generator-CGz1TO_N.js +13 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +3 -0
- package/dist/http-EnNOUsIK.js +69 -0
- package/dist/index-CFv8vZvy.d.ts +513 -0
- package/dist/index.d.ts +3 -1054
- package/dist/index.js +107 -3865
- package/dist/internal/index.d.ts +22 -0
- package/dist/internal/index.js +3 -0
- package/dist/layer-D8ybaCL2.js +340 -0
- package/dist/layer-KvknRFUT.js +656 -0
- package/dist/owner-BQzMpfC1.js +36 -0
- package/dist/owner-records-CX6yU28i.js +5 -0
- package/dist/owner-records-QDlssl__.d.ts +2963 -0
- package/dist/program-DJ8NpHIf.js +814 -0
- package/dist/protocol/index.d.ts +8 -0
- package/dist/protocol/index.js +16 -0
- package/dist/remote/index.d.ts +23 -0
- package/dist/remote/index.js +428 -0
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/streamsy-OjRubIPC.js +829 -0
- package/dist/testing/index.d.ts +44 -0
- package/dist/testing/index.js +757 -0
- package/package.json +50 -13
|
@@ -0,0 +1,814 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
+
import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-OjRubIPC.js";
|
|
3
|
+
import { t as generateCursor } from "./cursor-generator-CGz1TO_N.js";
|
|
4
|
+
import { Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Ref, Schedule, Stream } from "effect";
|
|
5
|
+
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
6
|
+
//#region src/http/responses.ts
|
|
7
|
+
var responses_exports = /* @__PURE__ */ __exportAll({
|
|
8
|
+
badRequest: () => badRequest$1,
|
|
9
|
+
cacheControlForVisibility: () => cacheControlForVisibility,
|
|
10
|
+
conflict: () => conflict$1,
|
|
11
|
+
empty: () => empty,
|
|
12
|
+
fromWeb: () => fromWeb,
|
|
13
|
+
gone: () => gone,
|
|
14
|
+
internalError: () => internalError,
|
|
15
|
+
invalidJson: () => invalidJson,
|
|
16
|
+
methodNotAllowed: () => methodNotAllowed,
|
|
17
|
+
noStore: () => noStore,
|
|
18
|
+
notFound: () => notFound,
|
|
19
|
+
payloadTooLarge: () => payloadTooLarge,
|
|
20
|
+
text: () => text
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Response factory for the HTTP layer.
|
|
24
|
+
*
|
|
25
|
+
* Centralizes security headers and the small set of plain text/empty
|
|
26
|
+
* responses that recur across handlers (400/404/410/413/etc.). Method-
|
|
27
|
+
* specific result mapping (append producer-state shaping, create conflict
|
|
28
|
+
* mapping, catch-up ETag responses) stays in the owning service.
|
|
29
|
+
*/
|
|
30
|
+
const CACHE_CONTROL_NO_STORE = "no-store";
|
|
31
|
+
const CACHE_CONTROL_PUBLIC = "public, max-age=60, stale-while-revalidate=300";
|
|
32
|
+
const CACHE_CONTROL_PRIVATE = "private, max-age=60, stale-while-revalidate=300";
|
|
33
|
+
function cacheControlForVisibility(visibility) {
|
|
34
|
+
return visibility === "public" ? CACHE_CONTROL_PUBLIC : CACHE_CONTROL_PRIVATE;
|
|
35
|
+
}
|
|
36
|
+
function noStore(response) {
|
|
37
|
+
const headers = new Headers(response.headers);
|
|
38
|
+
headers.set("cache-control", CACHE_CONTROL_NO_STORE);
|
|
39
|
+
return new Response(response.body, {
|
|
40
|
+
status: response.status,
|
|
41
|
+
statusText: response.statusText,
|
|
42
|
+
headers
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function text(message, status, headers) {
|
|
46
|
+
return new Response(message, {
|
|
47
|
+
status,
|
|
48
|
+
headers
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function empty(status, headers) {
|
|
52
|
+
return new Response(null, {
|
|
53
|
+
status,
|
|
54
|
+
headers
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function badRequest$1(message) {
|
|
58
|
+
return new Response(message, { status: 400 });
|
|
59
|
+
}
|
|
60
|
+
function notFound(message = "Stream not found") {
|
|
61
|
+
return new Response(message, { status: 404 });
|
|
62
|
+
}
|
|
63
|
+
function gone(message = "Stream is soft-deleted") {
|
|
64
|
+
return new Response(message, { status: 410 });
|
|
65
|
+
}
|
|
66
|
+
function conflict$1(message, headers) {
|
|
67
|
+
return new Response(message, {
|
|
68
|
+
status: 409,
|
|
69
|
+
headers
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function payloadTooLarge() {
|
|
73
|
+
return new Response("Payload too large", { status: 413 });
|
|
74
|
+
}
|
|
75
|
+
function invalidJson() {
|
|
76
|
+
return new Response("Invalid JSON", { status: 400 });
|
|
77
|
+
}
|
|
78
|
+
function methodNotAllowed() {
|
|
79
|
+
return new Response("Method not allowed", { status: 405 });
|
|
80
|
+
}
|
|
81
|
+
function internalError() {
|
|
82
|
+
return new Response("Internal server error", { status: 500 });
|
|
83
|
+
}
|
|
84
|
+
/** Preserve the protocol's frozen byte and content-type conventions at one boundary. */
|
|
85
|
+
function fromWeb(response) {
|
|
86
|
+
return HttpServerResponse.raw(response, {
|
|
87
|
+
status: response.status,
|
|
88
|
+
statusText: response.statusText,
|
|
89
|
+
headers: Object.fromEntries(response.headers)
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/http/security-headers.ts
|
|
94
|
+
/** Shared protocol and host security headers. */
|
|
95
|
+
const securityHeaders = Object.freeze({
|
|
96
|
+
"x-content-type-options": "nosniff",
|
|
97
|
+
"cross-origin-resource-policy": "cross-origin"
|
|
98
|
+
});
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/http/stream-path-service.ts
|
|
101
|
+
/** Prefix helpers shared by protocol and host routers. */
|
|
102
|
+
const streamPath = (pathPrefix = "/") => {
|
|
103
|
+
const prefix = pathPrefix.endsWith("/") ? pathPrefix : `${pathPrefix}/`;
|
|
104
|
+
const regex = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
|
|
105
|
+
const strip = (pathname) => pathname.replace(regex, "");
|
|
106
|
+
return {
|
|
107
|
+
requiredPathPattern: () => `${prefix}{path}`,
|
|
108
|
+
strip,
|
|
109
|
+
canonicalizeForkSource: (source) => regex.test(source) ? strip(source) : source.replace(/^\//, "")
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/http/request-body-reader.ts
|
|
114
|
+
const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody")(function* (request) {
|
|
115
|
+
return yield* request.arrayBuffer.pipe(Effect.map((data) => data.byteLength > maxMessageSize ? {
|
|
116
|
+
ok: false,
|
|
117
|
+
response: payloadTooLarge()
|
|
118
|
+
} : {
|
|
119
|
+
ok: true,
|
|
120
|
+
data: new Uint8Array(data),
|
|
121
|
+
byteLength: data.byteLength
|
|
122
|
+
}), Effect.orElseSucceed(() => ({
|
|
123
|
+
ok: false,
|
|
124
|
+
response: payloadTooLarge()
|
|
125
|
+
})));
|
|
126
|
+
}) });
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/http/request-body-discard.ts
|
|
129
|
+
/**
|
|
130
|
+
* Consumes an unread request body before an early rejection.
|
|
131
|
+
*
|
|
132
|
+
* An HTTP/1.1 host can only reuse a connection when the request body was read
|
|
133
|
+
* to its end. A body that is dropped or cancelled counts as unread, so the host
|
|
134
|
+
* closes the connection after the response, and a client that reuses the pooled
|
|
135
|
+
* connection at that moment sees a socket close. Under workerd this showed up
|
|
136
|
+
* as the conformance case that sends four rejected appends back to back.
|
|
137
|
+
*
|
|
138
|
+
* The body is read through the Effect stream and discarded chunk by chunk, so
|
|
139
|
+
* nothing is buffered. An absent body fails the stream and a locked body
|
|
140
|
+
* defects on `getReader`; both are ignored because the rejection response is
|
|
141
|
+
* the outcome that matters.
|
|
142
|
+
*/
|
|
143
|
+
const discardRequestBody = (request) => Stream.runDrain(request.stream).pipe(Effect.ignoreCause);
|
|
144
|
+
//#endregion
|
|
145
|
+
//#region src/http/create.ts
|
|
146
|
+
const responses$4 = responses_exports;
|
|
147
|
+
function parseHeaders$1(request, path) {
|
|
148
|
+
const rawContentType = request.headers.get("content-type");
|
|
149
|
+
const ttlHeader = request.headers.get("stream-ttl");
|
|
150
|
+
const expiresAtHeader = request.headers.get("stream-expires-at");
|
|
151
|
+
const forkedFromHeader = request.headers.get("stream-forked-from");
|
|
152
|
+
const forkOffsetHeader = request.headers.get("stream-fork-offset");
|
|
153
|
+
const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
|
|
154
|
+
if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
|
|
155
|
+
ok: false,
|
|
156
|
+
response: responses$4.badRequest("Invalid Stream-TTL format")
|
|
157
|
+
};
|
|
158
|
+
if (ttlHeader && expiresAtHeader) return {
|
|
159
|
+
ok: false,
|
|
160
|
+
response: responses$4.badRequest("Cannot specify both Stream-TTL and Stream-Expires-At")
|
|
161
|
+
};
|
|
162
|
+
if (expiresAtHeader && Option.isNone(DateTime.make(expiresAtHeader))) return {
|
|
163
|
+
ok: false,
|
|
164
|
+
response: responses$4.badRequest("Invalid Stream-Expires-At format")
|
|
165
|
+
};
|
|
166
|
+
if (forkOffsetHeader && !forkedFromHeader) return {
|
|
167
|
+
ok: false,
|
|
168
|
+
response: responses$4.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
|
|
169
|
+
};
|
|
170
|
+
if (forkSubOffsetHeader !== null) {
|
|
171
|
+
if (!forkedFromHeader) return {
|
|
172
|
+
ok: false,
|
|
173
|
+
response: responses$4.badRequest("Stream-Fork-Sub-Offset requires Stream-Forked-From")
|
|
174
|
+
};
|
|
175
|
+
if (!/^(0|[1-9]\d*)$/.test(forkSubOffsetHeader)) return {
|
|
176
|
+
ok: false,
|
|
177
|
+
response: responses$4.badRequest("Invalid Stream-Fork-Sub-Offset format")
|
|
178
|
+
};
|
|
179
|
+
if (parseInt(forkSubOffsetHeader, 10) > 0 && !forkOffsetHeader) return {
|
|
180
|
+
ok: false,
|
|
181
|
+
response: responses$4.badRequest("Stream-Fork-Sub-Offset greater than zero requires Stream-Fork-Offset")
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
ok: true,
|
|
186
|
+
contentType: rawContentType ?? (!!forkedFromHeader ? void 0 : "application/octet-stream"),
|
|
187
|
+
ttlSeconds: ttlHeader ? parseInt(ttlHeader, 10) : void 0,
|
|
188
|
+
expiresAt: expiresAtHeader ?? void 0,
|
|
189
|
+
wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
190
|
+
forkedFromStreamId: forkedFromHeader ? path.canonicalizeForkSource(forkedFromHeader) : void 0,
|
|
191
|
+
forkOffset: forkOffsetHeader ?? void 0,
|
|
192
|
+
forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
function normalizeInitialData(data, contentType) {
|
|
196
|
+
let effectiveInitialData = data.byteLength > 0 ? data : void 0;
|
|
197
|
+
if (effectiveInitialData && contentType?.toLowerCase().startsWith("application/json")) try {
|
|
198
|
+
const parsed = JSON.parse(new TextDecoder().decode(effectiveInitialData));
|
|
199
|
+
if (Array.isArray(parsed) && parsed.length === 0) effectiveInitialData = void 0;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error instanceof SyntaxError) return {
|
|
202
|
+
ok: false,
|
|
203
|
+
response: responses$4.invalidJson()
|
|
204
|
+
};
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
ok: true,
|
|
209
|
+
initialData: effectiveInitialData
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function toResponse$1(result, location) {
|
|
213
|
+
const created = CreateResult.$is("Created")(result);
|
|
214
|
+
const headers = new Headers({
|
|
215
|
+
"content-type": result.contentType,
|
|
216
|
+
"stream-next-offset": result.nextOffset
|
|
217
|
+
});
|
|
218
|
+
if (created) headers.set("location", location);
|
|
219
|
+
if (result.closed) headers.set("stream-closed", "true");
|
|
220
|
+
return responses$4.empty(created ? 201 : 200, headers);
|
|
221
|
+
}
|
|
222
|
+
//#endregion
|
|
223
|
+
//#region src/http/producer-header-parser.ts
|
|
224
|
+
var producer_header_parser_exports = /* @__PURE__ */ __exportAll({ parse: () => parse });
|
|
225
|
+
const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
|
|
226
|
+
const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
|
|
227
|
+
function parse(request) {
|
|
228
|
+
const id = request.headers.get("producer-id");
|
|
229
|
+
const epoch = request.headers.get("producer-epoch");
|
|
230
|
+
const seq = request.headers.get("producer-seq");
|
|
231
|
+
const present = [
|
|
232
|
+
id,
|
|
233
|
+
epoch,
|
|
234
|
+
seq
|
|
235
|
+
].filter((v) => v !== null).length;
|
|
236
|
+
if (present === 0) return { kind: "absent" };
|
|
237
|
+
if (present !== 3 || id === null || epoch === null || seq === null) return { kind: "invalid" };
|
|
238
|
+
if (id.length === 0) return { kind: "invalid" };
|
|
239
|
+
const parsedEpoch = parseInt$1(epoch);
|
|
240
|
+
const parsedSeq = parseInt$1(seq);
|
|
241
|
+
if (parsedEpoch === null || parsedSeq === null) return { kind: "invalid" };
|
|
242
|
+
return {
|
|
243
|
+
kind: "ok",
|
|
244
|
+
producer: {
|
|
245
|
+
producerId: id,
|
|
246
|
+
producerEpoch: parsedEpoch,
|
|
247
|
+
producerSeq: parsedSeq
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function parseInt$1(raw) {
|
|
252
|
+
if (!NON_NEGATIVE_INT_RE.test(raw)) return null;
|
|
253
|
+
const n = Number(raw);
|
|
254
|
+
if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
|
|
255
|
+
return n;
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/http/append.ts
|
|
259
|
+
const producerParser = producer_header_parser_exports;
|
|
260
|
+
const responses$3 = responses_exports;
|
|
261
|
+
function parseHeaders(request) {
|
|
262
|
+
const producerHeaders = producerParser.parse(request);
|
|
263
|
+
if (producerHeaders.kind === "invalid") return {
|
|
264
|
+
ok: false,
|
|
265
|
+
response: responses$3.badRequest("Invalid producer headers")
|
|
266
|
+
};
|
|
267
|
+
const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
|
|
268
|
+
if (expectedOffset !== void 0 && !isValid(expectedOffset)) return {
|
|
269
|
+
ok: false,
|
|
270
|
+
response: responses$3.badRequest("Invalid expected offset")
|
|
271
|
+
};
|
|
272
|
+
return {
|
|
273
|
+
ok: true,
|
|
274
|
+
contentType: request.headers.get("content-type"),
|
|
275
|
+
seq: request.headers.get("stream-seq") ?? void 0,
|
|
276
|
+
wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
|
|
277
|
+
expectedOffset,
|
|
278
|
+
producerHeaders
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
function toResponse(result, producerHeaders, isEmpty) {
|
|
282
|
+
return AppendResult.$match(result, {
|
|
283
|
+
Duplicate: (duplicate) => {
|
|
284
|
+
const headers = new Headers({
|
|
285
|
+
"stream-next-offset": duplicate.offset,
|
|
286
|
+
"producer-epoch": String(duplicate.producerEpoch),
|
|
287
|
+
"producer-seq": String(duplicate.producerSeq)
|
|
288
|
+
});
|
|
289
|
+
if (duplicate.closed) headers.set("stream-closed", "true");
|
|
290
|
+
return responses$3.empty(204, headers);
|
|
291
|
+
},
|
|
292
|
+
Appended: (appended) => {
|
|
293
|
+
const headers = new Headers({ "stream-next-offset": appended.offset });
|
|
294
|
+
if (appended.closed) headers.set("stream-closed", "true");
|
|
295
|
+
if (appended.producerEpoch !== void 0) headers.set("producer-epoch", String(appended.producerEpoch));
|
|
296
|
+
if (appended.producerSeq !== void 0) headers.set("producer-seq", String(appended.producerSeq));
|
|
297
|
+
return responses$3.empty(producerHeaders.kind === "ok" && !isEmpty ? 200 : 204, headers);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
//#endregion
|
|
302
|
+
//#region src/http/etag-builder.ts
|
|
303
|
+
var etag_builder_exports = /* @__PURE__ */ __exportAll({ forCatchUp: () => forCatchUp });
|
|
304
|
+
function forCatchUp(pathname, startOffset, nextOffset, closed) {
|
|
305
|
+
const closedSuffix = closed ? ":c" : "";
|
|
306
|
+
return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
|
|
307
|
+
}
|
|
308
|
+
//#endregion
|
|
309
|
+
//#region src/http/bytes.ts
|
|
310
|
+
/**
|
|
311
|
+
* Cross-runtime byte normalization for HTTP bodies.
|
|
312
|
+
*
|
|
313
|
+
* `Uint8Array.prototype.buffer` is typed `ArrayBufferLike`, which also admits a
|
|
314
|
+
* `SharedArrayBuffer`. `BodyInit` accepts only a real `ArrayBuffer`, and a view
|
|
315
|
+
* may cover just part of its backing buffer, so neither the buffer identity nor
|
|
316
|
+
* its element type can be assumed. These helpers establish both with runtime
|
|
317
|
+
* checks instead of an assertion.
|
|
318
|
+
*/
|
|
319
|
+
/**
|
|
320
|
+
* Returns an `ArrayBuffer` holding exactly the bytes of `view`.
|
|
321
|
+
*
|
|
322
|
+
* When the view already owns its whole backing `ArrayBuffer` the buffer is
|
|
323
|
+
* returned as-is (no copy), which is the common case for freshly concatenated
|
|
324
|
+
* bodies. Otherwise — a partial view, or a `SharedArrayBuffer` backing — the
|
|
325
|
+
* bytes are copied into a fresh, exactly sized `ArrayBuffer`.
|
|
326
|
+
*/
|
|
327
|
+
function toArrayBuffer(view) {
|
|
328
|
+
const { buffer, byteOffset, byteLength } = view;
|
|
329
|
+
if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) return buffer;
|
|
330
|
+
const copy = new ArrayBuffer(byteLength);
|
|
331
|
+
new Uint8Array(copy).set(view);
|
|
332
|
+
return copy;
|
|
333
|
+
}
|
|
334
|
+
function isReferenceValue(candidate) {
|
|
335
|
+
return candidate !== null && Object(candidate) === candidate;
|
|
336
|
+
}
|
|
337
|
+
function isCallable(candidate) {
|
|
338
|
+
if (!isReferenceValue(candidate)) return false;
|
|
339
|
+
try {
|
|
340
|
+
Function.prototype.toString.call(candidate);
|
|
341
|
+
return true;
|
|
342
|
+
} catch {
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function isNodeBufferGlobal(candidate) {
|
|
347
|
+
return isReferenceValue(candidate) && isCallable(candidate) && "from" in candidate && isCallable(candidate.from);
|
|
348
|
+
}
|
|
349
|
+
function parseBase64Encoder(result) {
|
|
350
|
+
const { value } = result;
|
|
351
|
+
if (!isReferenceValue(value)) return void 0;
|
|
352
|
+
let owner = value;
|
|
353
|
+
while (owner !== null) {
|
|
354
|
+
const descriptor = Object.getOwnPropertyDescriptor(owner, "toString");
|
|
355
|
+
if (descriptor !== void 0) {
|
|
356
|
+
const method = "value" in descriptor ? descriptor.value : descriptor.get?.call(value);
|
|
357
|
+
return isCallable(method) ? (encoding) => method.call(value, encoding) : void 0;
|
|
358
|
+
}
|
|
359
|
+
owner = Object.getPrototypeOf(owner);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function nodeBufferBase64(bytes) {
|
|
363
|
+
if (!("Buffer" in globalThis)) return void 0;
|
|
364
|
+
const bufferGlobal = globalThis.Buffer;
|
|
365
|
+
if (!isReferenceValue(bufferGlobal) || !isNodeBufferGlobal(bufferGlobal)) return void 0;
|
|
366
|
+
const encode = parseBase64Encoder({ value: bufferGlobal.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) });
|
|
367
|
+
if (encode === void 0) return void 0;
|
|
368
|
+
const encoded = encode("base64");
|
|
369
|
+
if (encoded === null || encoded === void 0 || isReferenceValue(encoded) || Object.getPrototypeOf(Object(encoded)) !== String.prototype) return;
|
|
370
|
+
return String.prototype.valueOf.call(encoded);
|
|
371
|
+
}
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region src/http/message-body-codec.ts
|
|
374
|
+
var message_body_codec_exports = /* @__PURE__ */ __exportAll({
|
|
375
|
+
bytesToBase64: () => bytesToBase64,
|
|
376
|
+
concatBytes: () => concatBytes,
|
|
377
|
+
emptyBodyForContentType: () => emptyBodyForContentType,
|
|
378
|
+
encodeHttpBody: () => encodeHttpBody
|
|
379
|
+
});
|
|
380
|
+
const decoder$1 = new TextDecoder();
|
|
381
|
+
function encodeHttpBody(messages, contentType) {
|
|
382
|
+
const lower = contentType.toLowerCase();
|
|
383
|
+
if (lower.startsWith("application/json")) return `[${messages.map((msg) => decoder$1.decode(msg.data)).join(",")}]`;
|
|
384
|
+
if (lower.startsWith("text/")) return messages.map((msg) => decoder$1.decode(msg.data)).join("");
|
|
385
|
+
return toArrayBuffer(concatBytes(messages));
|
|
386
|
+
}
|
|
387
|
+
function emptyBodyForContentType(contentType) {
|
|
388
|
+
return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
|
|
389
|
+
}
|
|
390
|
+
function concatBytes(messages) {
|
|
391
|
+
const totalLength = messages.reduce((acc, msg) => acc + msg.data.length, 0);
|
|
392
|
+
const combined = new Uint8Array(totalLength);
|
|
393
|
+
let pos = 0;
|
|
394
|
+
for (const msg of messages) {
|
|
395
|
+
combined.set(msg.data, pos);
|
|
396
|
+
pos += msg.data.length;
|
|
397
|
+
}
|
|
398
|
+
return combined;
|
|
399
|
+
}
|
|
400
|
+
function bytesToBase64(bytes) {
|
|
401
|
+
const viaBuffer = nodeBufferBase64(bytes);
|
|
402
|
+
if (viaBuffer !== void 0) return viaBuffer;
|
|
403
|
+
let binary = "";
|
|
404
|
+
const chunk = 32768;
|
|
405
|
+
for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
406
|
+
return btoa(binary);
|
|
407
|
+
}
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region src/http/read-query-parser.ts
|
|
410
|
+
const readQueryParser = (isValidOffset) => ({ parse(url) {
|
|
411
|
+
const offset = url.searchParams.get("offset") ?? void 0;
|
|
412
|
+
const liveParam = url.searchParams.get("live");
|
|
413
|
+
const cursor = url.searchParams.get("cursor") ?? void 0;
|
|
414
|
+
const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
|
|
415
|
+
if (offset !== void 0 && offset !== "-1" && offset !== "now" && !isValidOffset(offset)) return {
|
|
416
|
+
ok: false,
|
|
417
|
+
response: new Response("Invalid offset format", { status: 400 })
|
|
418
|
+
};
|
|
419
|
+
if (cursor !== void 0 && (!/^(0|[1-9]\d*)$/.test(cursor) || !Number.isSafeInteger(Number(cursor)) || Number(cursor) > Number.MAX_SAFE_INTEGER - 180)) return {
|
|
420
|
+
ok: false,
|
|
421
|
+
response: new Response("Invalid cursor", { status: 400 })
|
|
422
|
+
};
|
|
423
|
+
return {
|
|
424
|
+
ok: true,
|
|
425
|
+
offset,
|
|
426
|
+
live,
|
|
427
|
+
cursor
|
|
428
|
+
};
|
|
429
|
+
} });
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/http/sse-event-encoder.ts
|
|
432
|
+
var sse_event_encoder_exports = /* @__PURE__ */ __exportAll({
|
|
433
|
+
controlEvent: () => controlEvent,
|
|
434
|
+
dataEvent: () => dataEvent
|
|
435
|
+
});
|
|
436
|
+
const encoder = new TextEncoder();
|
|
437
|
+
const decoder = new TextDecoder();
|
|
438
|
+
function dataEvent(messages, options) {
|
|
439
|
+
const chunks = [encode("event: data\n")];
|
|
440
|
+
if (options.useBase64) {
|
|
441
|
+
const combined = concatBytes(messages);
|
|
442
|
+
chunks.push(encode(`data:${bytesToBase64(combined)}\n`));
|
|
443
|
+
} else if (options.isJson) {
|
|
444
|
+
const items = messages.map((msg) => decoder.decode(msg.data));
|
|
445
|
+
chunks.push(encode("data:[\n"));
|
|
446
|
+
for (let i = 0; i < items.length; i++) {
|
|
447
|
+
const suffix = i < items.length - 1 ? "," : "";
|
|
448
|
+
chunks.push(encode(`data:${items[i]}${suffix}\n`));
|
|
449
|
+
}
|
|
450
|
+
chunks.push(encode("data:]\n"));
|
|
451
|
+
} else {
|
|
452
|
+
const text = messages.map((msg) => decoder.decode(msg.data)).join("");
|
|
453
|
+
for (const line of text.split(/\r\n|\r|\n/)) chunks.push(encode(`data:${line}\n`));
|
|
454
|
+
}
|
|
455
|
+
chunks.push(encode("\n"));
|
|
456
|
+
return chunks;
|
|
457
|
+
}
|
|
458
|
+
function controlEvent(data) {
|
|
459
|
+
return encode(`event: control\ndata:${JSON.stringify(data)}\n\n`);
|
|
460
|
+
}
|
|
461
|
+
function encode(value) {
|
|
462
|
+
return encoder.encode(value);
|
|
463
|
+
}
|
|
464
|
+
//#endregion
|
|
465
|
+
//#region src/http/sse.ts
|
|
466
|
+
const events = sse_event_encoder_exports;
|
|
467
|
+
/** Each connection's deadline is `deadlineMs` scaled by a factor from 0.9 to 1.1. */
|
|
468
|
+
const DEADLINE_JITTER = .1;
|
|
469
|
+
/**
|
|
470
|
+
* Spread `deadlineMs` by up to `DEADLINE_JITTER` either way, from one draw `r`
|
|
471
|
+
* in [0, 1). Connections opened together then do not all close together.
|
|
472
|
+
*/
|
|
473
|
+
function jitterDeadline(deadlineMs, r) {
|
|
474
|
+
return Math.round(deadlineMs * (.9 + 2 * DEADLINE_JITTER * r));
|
|
475
|
+
}
|
|
476
|
+
/** Pull-based batches are unbounded in message count, like readNext and toolkit follow. */
|
|
477
|
+
function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal) {
|
|
478
|
+
const encoding = {
|
|
479
|
+
isJson: contentType.toLowerCase().startsWith("application/json"),
|
|
480
|
+
isText: contentType.toLowerCase().startsWith("text/"),
|
|
481
|
+
useBase64: false
|
|
482
|
+
};
|
|
483
|
+
encoding.useBase64 = !encoding.isJson && !encoding.isText;
|
|
484
|
+
const frames = Stream.suspend(() => {
|
|
485
|
+
let initial = true;
|
|
486
|
+
let currentOffset = offset;
|
|
487
|
+
let currentCursor = cursor;
|
|
488
|
+
return Stream.fromEffectRepeat(Effect.gen(function* () {
|
|
489
|
+
const result = initial ? yield* reader.read(id, { offset: currentOffset }).pipe(Effect.map((batch) => ({
|
|
490
|
+
...batch,
|
|
491
|
+
cursor: void 0
|
|
492
|
+
}))) : yield* reader.readNext(id, {
|
|
493
|
+
offset: currentOffset,
|
|
494
|
+
cursor: currentCursor
|
|
495
|
+
});
|
|
496
|
+
if (initial) {
|
|
497
|
+
const now = yield* Clock.currentTimeMillis;
|
|
498
|
+
const random = yield* Random.next;
|
|
499
|
+
currentCursor = generateCursor({ now: () => now }, currentCursor, () => random);
|
|
500
|
+
} else if (result.cursor !== void 0) currentCursor = result.cursor;
|
|
501
|
+
initial = false;
|
|
502
|
+
currentOffset = result.nextOffset;
|
|
503
|
+
const chunks = result.messages.length ? events.dataEvent(result.messages, encoding) : [];
|
|
504
|
+
const control = result.closed ? {
|
|
505
|
+
streamNextOffset: currentOffset,
|
|
506
|
+
streamClosed: true
|
|
507
|
+
} : {
|
|
508
|
+
streamNextOffset: currentOffset,
|
|
509
|
+
streamCursor: currentCursor
|
|
510
|
+
};
|
|
511
|
+
if (!result.closed && result.upToDate) control.upToDate = true;
|
|
512
|
+
chunks.push(events.controlEvent(control));
|
|
513
|
+
return {
|
|
514
|
+
frames: [concatBytes(chunks.map((data) => ({ data })))],
|
|
515
|
+
done: result.closed
|
|
516
|
+
};
|
|
517
|
+
}).pipe(Effect.catchTags({
|
|
518
|
+
StreamNotFound: () => Effect.succeed({
|
|
519
|
+
frames: [],
|
|
520
|
+
done: true
|
|
521
|
+
}),
|
|
522
|
+
StreamGone: () => Effect.succeed({
|
|
523
|
+
frames: [],
|
|
524
|
+
done: true
|
|
525
|
+
}),
|
|
526
|
+
NotSupported: () => Effect.succeed({
|
|
527
|
+
frames: [],
|
|
528
|
+
done: true
|
|
529
|
+
})
|
|
530
|
+
}))).pipe(Stream.takeUntil((batch) => batch.done), Stream.flatMap((batch) => Stream.fromIterable(batch.frames)), Stream.merge(Stream.fromEffect(Random.next.pipe(Effect.flatMap((r) => Effect.sleep(jitterDeadline(deadlineMs, r))))).pipe(Stream.drain), { haltStrategy: "either" }), Stream.merge(Stream.fromEffect(signal?.draining ?? Effect.never).pipe(Stream.drain), { haltStrategy: "either" }));
|
|
531
|
+
});
|
|
532
|
+
const headers = new Headers({
|
|
533
|
+
"content-type": "text/event-stream",
|
|
534
|
+
"cache-control": "no-cache",
|
|
535
|
+
connection: "keep-alive"
|
|
536
|
+
});
|
|
537
|
+
if (encoding.useBase64) headers.set("stream-sse-data-encoding", "base64");
|
|
538
|
+
const body = signal === void 0 ? frames : signal.trackStream(frames);
|
|
539
|
+
return HttpServerResponse.stream(body, { headers: Object.fromEntries(headers) });
|
|
540
|
+
}
|
|
541
|
+
//#endregion
|
|
542
|
+
//#region src/http/shutdown-signal.ts
|
|
543
|
+
var ShutdownSignal = class extends Context.Service()("@streamsy/core/ShutdownSignal") {};
|
|
544
|
+
/** How often `drain` checks the live-read count. */
|
|
545
|
+
const POLL = Schedule.spaced("5 millis");
|
|
546
|
+
const makeShutdownSignal = Effect.gen(function* () {
|
|
547
|
+
const started = yield* Deferred.make();
|
|
548
|
+
const count = yield* Ref.make(0);
|
|
549
|
+
const enter = Ref.update(count, (n) => n + 1);
|
|
550
|
+
const leave = Ref.update(count, (n) => n - 1);
|
|
551
|
+
return ShutdownSignal.of({
|
|
552
|
+
draining: Deferred.await(started),
|
|
553
|
+
track: (effect) => Effect.acquireUseRelease(enter, () => effect, () => leave),
|
|
554
|
+
trackStream: (stream) => Stream.unwrap(Effect.acquireRelease(enter, () => leave).pipe(Effect.as(stream))),
|
|
555
|
+
drain: (timeout) => Deferred.succeed(started, void 0).pipe(Effect.andThen(Ref.get(count).pipe(Effect.repeat({
|
|
556
|
+
until: (n) => n === 0,
|
|
557
|
+
schedule: POLL
|
|
558
|
+
}))), Effect.timeoutOption(timeout), Effect.asVoid),
|
|
559
|
+
active: Ref.get(count)
|
|
560
|
+
});
|
|
561
|
+
});
|
|
562
|
+
/** A fresh signal. Provide it to the routes and call `drain` before they close. */
|
|
563
|
+
const layerShutdownSignal = Layer.effect(ShutdownSignal, makeShutdownSignal);
|
|
564
|
+
//#endregion
|
|
565
|
+
//#region src/http/read.ts
|
|
566
|
+
const responses$2 = responses_exports;
|
|
567
|
+
const bodyCodec = message_body_codec_exports;
|
|
568
|
+
const etags = etag_builder_exports;
|
|
569
|
+
const queryParser = readQueryParser(isValid);
|
|
570
|
+
/**
|
|
571
|
+
* The reply a parked long poll gives when the host drains: no messages, the
|
|
572
|
+
* requested offset, and a fresh cursor. The HTTP layer turns it into the same
|
|
573
|
+
* `204` as a long-poll timeout, so a client reconnects as it always does. The
|
|
574
|
+
* next read, on this host or the next one, returns anything that arrived.
|
|
575
|
+
*/
|
|
576
|
+
const drainReply = Effect.fn("Http.drainReply")(function* (reader, id, offset, cursor) {
|
|
577
|
+
const head = yield* reader.head(id);
|
|
578
|
+
const now = yield* Clock.currentTimeMillis;
|
|
579
|
+
const random = yield* Random.next;
|
|
580
|
+
return {
|
|
581
|
+
contentType: head.contentType,
|
|
582
|
+
messages: [],
|
|
583
|
+
nextOffset: offset === "now" ? head.nextOffset : offset,
|
|
584
|
+
upToDate: true,
|
|
585
|
+
closed: false,
|
|
586
|
+
timedOut: true,
|
|
587
|
+
cursor: generateCursor({ now: () => now }, cursor, () => random)
|
|
588
|
+
};
|
|
589
|
+
});
|
|
590
|
+
/** Park on `readNext` until data, timeout, or the host's drain signal. */
|
|
591
|
+
const longPoll = (reader, id, offset, cursor, signal) => {
|
|
592
|
+
const wait = reader.readNext(id, {
|
|
593
|
+
offset,
|
|
594
|
+
cursor
|
|
595
|
+
});
|
|
596
|
+
if (Option.isNone(signal)) return wait;
|
|
597
|
+
const drained = signal.value.draining.pipe(Effect.andThen(drainReply(reader, id, offset, cursor)));
|
|
598
|
+
return signal.value.track(Effect.raceFirst(wait, drained));
|
|
599
|
+
};
|
|
600
|
+
const read$1 = Effect.fn("Http.read")(function* (reader, id, url, requestHeaders, cacheControl, sseDeadlineMs) {
|
|
601
|
+
const query = queryParser.parse(url);
|
|
602
|
+
if (!query.ok) return query.response;
|
|
603
|
+
const offset = query.offset;
|
|
604
|
+
if (offset === "now" && !query.live) {
|
|
605
|
+
const result = yield* reader.read(id, { offset: "now" });
|
|
606
|
+
const headers = new Headers({
|
|
607
|
+
"content-type": result.contentType,
|
|
608
|
+
"stream-next-offset": result.nextOffset,
|
|
609
|
+
"stream-up-to-date": "true",
|
|
610
|
+
"cache-control": "no-store"
|
|
611
|
+
});
|
|
612
|
+
if (result.closed) headers.set("stream-closed", "true");
|
|
613
|
+
return new Response(bodyCodec.emptyBodyForContentType(result.contentType), { headers });
|
|
614
|
+
}
|
|
615
|
+
if (query.live && !offset) return responses$2.badRequest("offset required for live modes");
|
|
616
|
+
const signal = yield* Effect.serviceOption(ShutdownSignal);
|
|
617
|
+
if (query.live === "sse" && offset) {
|
|
618
|
+
const meta = yield* reader.head(id);
|
|
619
|
+
return sse(reader, id, meta.contentType, offset === "now" ? meta.nextOffset : offset, query.cursor, sseDeadlineMs, Option.getOrUndefined(signal));
|
|
620
|
+
}
|
|
621
|
+
const live = query.live === "long-poll" && offset !== void 0;
|
|
622
|
+
const result = live && offset !== void 0 ? yield* longPoll(reader, id, offset, query.cursor, signal) : yield* reader.read(id, { offset }).pipe(Effect.map((batch) => ({
|
|
623
|
+
...batch,
|
|
624
|
+
cursor: void 0
|
|
625
|
+
})));
|
|
626
|
+
const headers = new Headers({ "stream-next-offset": result.nextOffset });
|
|
627
|
+
if (result.closed) headers.set("stream-closed", "true");
|
|
628
|
+
if (live || result.upToDate) headers.set("stream-up-to-date", "true");
|
|
629
|
+
if (live && !result.closed && result.cursor !== void 0) headers.set("stream-cursor", result.cursor);
|
|
630
|
+
if (live && result.messages.length === 0) {
|
|
631
|
+
headers.set("cache-control", "no-store");
|
|
632
|
+
return responses$2.empty(204, headers);
|
|
633
|
+
}
|
|
634
|
+
const etag = etags.forCatchUp(url.pathname, offset ?? "-1", result.nextOffset, result.closed);
|
|
635
|
+
const literalNow = live && query.offset === "now";
|
|
636
|
+
headers.set("cache-control", literalNow ? "no-store" : cacheControl);
|
|
637
|
+
if (!literalNow) {
|
|
638
|
+
if (requestHeaders.get("if-none-match") === etag) return responses$2.empty(304, {
|
|
639
|
+
etag,
|
|
640
|
+
"cache-control": cacheControl
|
|
641
|
+
});
|
|
642
|
+
headers.set("etag", etag);
|
|
643
|
+
}
|
|
644
|
+
headers.set("content-type", result.contentType);
|
|
645
|
+
return new Response(bodyCodec.encodeHttpBody(result.messages, result.contentType), { headers });
|
|
646
|
+
});
|
|
647
|
+
//#endregion
|
|
648
|
+
//#region src/http/route.ts
|
|
649
|
+
/** Preserve the Web request origin; Effect 4.0.1 toURL otherwise reconstructs it from Host. */
|
|
650
|
+
function requestUrl(request) {
|
|
651
|
+
return URL.parse(request.originalUrl) ?? Option.getOrUndefined(HttpServerRequest.toURL(request));
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region src/http/read-program.ts
|
|
655
|
+
/** @internal Shared construction-time validation for HTTP read routes. */
|
|
656
|
+
function checkReadOptions(options) {
|
|
657
|
+
if (options.sseDeadlineMs !== void 0 && (!Number.isFinite(options.sseDeadlineMs) || options.sseDeadlineMs <= 0)) throw new RangeError("sseDeadlineMs must be positive");
|
|
658
|
+
}
|
|
659
|
+
/** Read an already resolved id using the protocol's HTTP framing and live modes. */
|
|
660
|
+
function read(id, options = {}) {
|
|
661
|
+
checkReadOptions(options);
|
|
662
|
+
return Effect.gen(function* () {
|
|
663
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
664
|
+
const reader = yield* StreamsReader;
|
|
665
|
+
const url = requestUrl(request);
|
|
666
|
+
if (!url) return HttpServerResponse.text("Invalid request URL", { status: 400 });
|
|
667
|
+
if (request.method === "HEAD") {
|
|
668
|
+
const meta = yield* reader.head(id);
|
|
669
|
+
const headers = new Headers({
|
|
670
|
+
"content-type": meta.contentType,
|
|
671
|
+
"stream-next-offset": meta.nextOffset,
|
|
672
|
+
"cache-control": "no-store"
|
|
673
|
+
});
|
|
674
|
+
if (meta.closed) headers.set("stream-closed", "true");
|
|
675
|
+
if (meta.ttlSeconds) headers.set("stream-ttl", String(meta.ttlSeconds));
|
|
676
|
+
if (meta.expiresAt) headers.set("stream-expires-at", meta.expiresAt);
|
|
677
|
+
return HttpServerResponse.empty({
|
|
678
|
+
status: 200,
|
|
679
|
+
headers: Object.fromEntries(headers)
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
const response = yield* read$1(reader, id, url, new Headers(request.headers), cacheControlForVisibility(options.cacheVisibility ?? "private"), options.sseDeadlineMs);
|
|
683
|
+
return response instanceof Response ? fromWeb(response) : response;
|
|
684
|
+
}).pipe(Effect.map(HttpServerResponse.setHeaders(securityHeaders)));
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/http/protocol-error-response.ts
|
|
688
|
+
const responses$1 = responses_exports;
|
|
689
|
+
const conflict = ({ message }) => responses$1.conflict(message);
|
|
690
|
+
const badRequest = ({ message }) => responses$1.badRequest(message);
|
|
691
|
+
/** The sole protocol rejection mapping at the HTTP edge. */
|
|
692
|
+
function protocolErrorResponse(error, context) {
|
|
693
|
+
return Match.valueTags(error, {
|
|
694
|
+
StreamNotFound: () => context.method === "HEAD" ? responses$1.noStore(responses$1.notFound()) : responses$1.notFound(),
|
|
695
|
+
StreamGone: () => context.method === "HEAD" ? responses$1.noStore(responses$1.gone()) : responses$1.gone(),
|
|
696
|
+
ForkSourceNotFound: ({ source }) => responses$1.notFound(`Source stream not found: ${source}`),
|
|
697
|
+
CreateConflict: conflict,
|
|
698
|
+
AppendConflict: conflict,
|
|
699
|
+
InvalidReadRequest: badRequest,
|
|
700
|
+
InvalidForkRequest: badRequest,
|
|
701
|
+
InvalidAppendRequest: badRequest,
|
|
702
|
+
StreamClosed: ({ offset }) => responses$1.empty(409, {
|
|
703
|
+
"stream-closed": "true",
|
|
704
|
+
"stream-next-offset": offset
|
|
705
|
+
}),
|
|
706
|
+
OffsetMismatch: ({ actual }) => responses$1.conflict("Expected offset mismatch", { "stream-next-offset": actual }),
|
|
707
|
+
StreamBusy: () => responses$1.text("Stream busy, retry later", 503),
|
|
708
|
+
StaleEpoch: ({ currentEpoch }) => responses$1.text("Stale producer epoch", 403, { "producer-epoch": String(currentEpoch) }),
|
|
709
|
+
ProducerGap: ({ expectedSeq, receivedSeq }) => responses$1.conflict("Producer sequence gap", {
|
|
710
|
+
"producer-expected-seq": String(expectedSeq),
|
|
711
|
+
"producer-received-seq": String(receivedSeq)
|
|
712
|
+
}),
|
|
713
|
+
InvalidEpochSeq: () => responses$1.badRequest("New epoch must start at seq=0"),
|
|
714
|
+
NotSupported: ({ feature }) => new Response(`Feature not supported: ${feature}`, {
|
|
715
|
+
status: 400,
|
|
716
|
+
headers: { "stream-not-supported": feature }
|
|
717
|
+
})
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
//#endregion
|
|
721
|
+
//#region src/http/program.ts
|
|
722
|
+
const responses = responses_exports;
|
|
723
|
+
const failure = (error) => Effect.map(HttpServerRequest.HttpServerRequest, (request) => protocolErrorResponse(error, { method: request.method }));
|
|
724
|
+
/**
|
|
725
|
+
* The public HTTP program. It is the whole application an Effect host serves.
|
|
726
|
+
*
|
|
727
|
+
* Its success type is `HttpServerResponse` alone, its error channel is closed,
|
|
728
|
+
* and it requires exactly `HttpServerRequest | StreamsReader | StreamsWriter`.
|
|
729
|
+
* Those three facts are what let a host type it as an Alchemy `HttpEffect` and
|
|
730
|
+
* what let one composition serve several backends.
|
|
731
|
+
*/
|
|
732
|
+
function app(options = {}) {
|
|
733
|
+
checkReadOptions(options);
|
|
734
|
+
const path = streamPath(options.pathPrefix ?? "/");
|
|
735
|
+
const bodyReader = requestBodyReader(options.maxMessageSize ?? 1048576);
|
|
736
|
+
return Effect.gen(function* () {
|
|
737
|
+
const request = yield* HttpServerRequest.HttpServerRequest;
|
|
738
|
+
const writer = yield* StreamsWriter;
|
|
739
|
+
const url = requestUrl(request);
|
|
740
|
+
if (!url) return responses.badRequest("Invalid request URL");
|
|
741
|
+
const stripped = path.strip(url.pathname);
|
|
742
|
+
if (!stripped || stripped === url.pathname) return responses.badRequest(`Stream path required: ${path.requiredPathPattern()}`);
|
|
743
|
+
const id = StreamId.make(stripped);
|
|
744
|
+
const headers = new Headers(request.headers);
|
|
745
|
+
if (request.method === "PUT") {
|
|
746
|
+
const parsed = parseHeaders$1({ headers }, path);
|
|
747
|
+
if (!parsed.ok) return parsed.response;
|
|
748
|
+
const body = yield* bodyReader.read(request);
|
|
749
|
+
if (!body.ok) return body.response;
|
|
750
|
+
const normalized = normalizeInitialData(body.data, parsed.contentType);
|
|
751
|
+
if (!normalized.ok) return normalized.response;
|
|
752
|
+
return toResponse$1(yield* writer.create(id, {
|
|
753
|
+
contentType: parsed.contentType,
|
|
754
|
+
ttlSeconds: parsed.ttlSeconds,
|
|
755
|
+
expiresAt: parsed.expiresAt,
|
|
756
|
+
initialData: normalized.initialData,
|
|
757
|
+
closed: parsed.wantClosed,
|
|
758
|
+
forkedFrom: parsed.forkedFromStreamId,
|
|
759
|
+
forkOffset: parsed.forkOffset,
|
|
760
|
+
forkSubOffset: parsed.forkSubOffset
|
|
761
|
+
}), url.href);
|
|
762
|
+
}
|
|
763
|
+
if (request.method === "OPTIONS") return responses.empty(204, {
|
|
764
|
+
"access-control-allow-origin": "*",
|
|
765
|
+
"access-control-allow-methods": "GET, HEAD, PUT, POST, DELETE, OPTIONS",
|
|
766
|
+
"access-control-allow-headers": "Authorization, Content-Type, If-None-Match, Producer-Id, Producer-Epoch, Producer-Seq, Stream-Closed, Stream-Expected-Offset, Stream-Seq, Stream-TTL, Stream-Expires-At",
|
|
767
|
+
"access-control-max-age": "86400"
|
|
768
|
+
});
|
|
769
|
+
if (![
|
|
770
|
+
"POST",
|
|
771
|
+
"GET",
|
|
772
|
+
"HEAD",
|
|
773
|
+
"DELETE"
|
|
774
|
+
].includes(request.method)) return responses.methodNotAllowed();
|
|
775
|
+
switch (request.method) {
|
|
776
|
+
case "POST": {
|
|
777
|
+
const parsed = parseHeaders({ headers });
|
|
778
|
+
if (!parsed.ok) {
|
|
779
|
+
yield* discardRequestBody(request);
|
|
780
|
+
return parsed.response;
|
|
781
|
+
}
|
|
782
|
+
const body = yield* bodyReader.read(request);
|
|
783
|
+
if (!body.ok) return body.response;
|
|
784
|
+
const isEmpty = body.byteLength === 0;
|
|
785
|
+
if (isEmpty && !parsed.wantClose) return responses.badRequest("Empty body not allowed");
|
|
786
|
+
if (!parsed.contentType && !isEmpty) return responses.badRequest("Content-Type required");
|
|
787
|
+
const normalized = normalizeInitialData(body.data, parsed.contentType ?? void 0);
|
|
788
|
+
if (!normalized.ok) return normalized.response;
|
|
789
|
+
return toResponse(yield* writer.append(id, {
|
|
790
|
+
data: body.data,
|
|
791
|
+
contentType: parsed.contentType ?? "application/octet-stream",
|
|
792
|
+
seq: parsed.seq,
|
|
793
|
+
producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
|
|
794
|
+
close: parsed.wantClose,
|
|
795
|
+
expectedOffset: parsed.expectedOffset
|
|
796
|
+
}), parsed.producerHeaders, isEmpty);
|
|
797
|
+
}
|
|
798
|
+
case "GET":
|
|
799
|
+
case "HEAD": return yield* read(id, options);
|
|
800
|
+
case "DELETE":
|
|
801
|
+
yield* writer.remove(id);
|
|
802
|
+
return responses.empty(204);
|
|
803
|
+
default: return responses.methodNotAllowed();
|
|
804
|
+
}
|
|
805
|
+
}).pipe(Effect.catchIf(isProtocolError, failure), Effect.catchTags({
|
|
806
|
+
StorageFault: () => Effect.succeed(responses.internalError()),
|
|
807
|
+
TransportFault: () => Effect.succeed(responses.internalError())
|
|
808
|
+
}), Effect.map((response) => {
|
|
809
|
+
const result = response instanceof Response ? responses.fromWeb(response) : response;
|
|
810
|
+
return HttpServerResponse.setHeaders(result, securityHeaders);
|
|
811
|
+
}));
|
|
812
|
+
}
|
|
813
|
+
//#endregion
|
|
814
|
+
export { ShutdownSignal as a, streamPath as c, requestUrl as i, securityHeaders as l, checkReadOptions as n, layerShutdownSignal as o, read as r, discardRequestBody as s, app as t };
|