@flowscripter/io-gateway-http 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/src/HttpGateway.d.ts +39 -0
- package/dist/src/HttpGateway.d.ts.map +1 -0
- package/dist/src/HttpGateway.js +106 -0
- package/dist/src/http/parseRange.d.ts +18 -0
- package/dist/src/http/parseRange.d.ts.map +1 -0
- package/dist/src/http/parseRange.js +41 -0
- package/dist/src/http/resolveTokenPath.d.ts +16 -0
- package/dist/src/http/resolveTokenPath.d.ts.map +1 -0
- package/dist/src/http/resolveTokenPath.js +30 -0
- package/dist/src/http/statusForError.d.ts +7 -0
- package/dist/src/http/statusForError.d.ts.map +1 -0
- package/dist/src/http/statusForError.js +15 -0
- package/dist/src/stream/createResumingReadStream.d.ts +19 -0
- package/dist/src/stream/createResumingReadStream.d.ts.map +1 -0
- package/dist/src/stream/createResumingReadStream.js +46 -0
- package/dist/src/token/GatewayGrant.d.ts +36 -0
- package/dist/src/token/GatewayGrant.d.ts.map +1 -0
- package/dist/src/token/GatewayGrant.js +234 -0
- package/dist/src/token/WriteTracker.d.ts +19 -0
- package/dist/src/token/WriteTracker.d.ts.map +1 -0
- package/dist/src/token/WriteTracker.js +40 -0
- package/dist/src/token/keys.d.ts +6 -0
- package/dist/src/token/keys.d.ts.map +1 -0
- package/dist/src/token/keys.js +16 -0
- package/index.ts +3 -0
- package/package.json +64 -4
- package/src/HttpGateway.ts +142 -0
- package/src/http/parseRange.ts +47 -0
- package/src/http/resolveTokenPath.ts +34 -0
- package/src/http/statusForError.ts +16 -0
- package/src/stream/createResumingReadStream.ts +61 -0
- package/src/token/GatewayGrant.ts +294 -0
- package/src/token/WriteTracker.ts +47 -0
- package/src/token/keys.ts +17 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Item,
|
|
3
|
+
PayloadKind,
|
|
4
|
+
toWebReadableStream,
|
|
5
|
+
TransientIOError,
|
|
6
|
+
} from "@flowscripter/pluggable-io-framework-api";
|
|
7
|
+
import { backoff, type RetryOptions } from "@flowscripter/pluggable-io-framework";
|
|
8
|
+
|
|
9
|
+
export interface ResumingReadOptions {
|
|
10
|
+
readonly initial: ReadableStream<Item<PayloadKind.Js>>;
|
|
11
|
+
/** Byte offset in the entry at which `initial` starts. */
|
|
12
|
+
readonly startOffset: number;
|
|
13
|
+
/** Opens a stream from the given byte offset, or omit to disable resuming. */
|
|
14
|
+
readonly reopen?: (offset: number) => Promise<ReadableStream<Item<PayloadKind.Js>>>;
|
|
15
|
+
readonly retry: RetryOptions;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A pull-based byte stream over a provider read. When the provider fails
|
|
20
|
+
* transiently part way through, the read is reopened at the first byte not
|
|
21
|
+
* yet delivered, so the HTTP client never sees the failure. Consecutive
|
|
22
|
+
* failures are counted against `retry.maxRetries` and reset once data arrives.
|
|
23
|
+
* Cancelling the returned stream cancels the provider stream.
|
|
24
|
+
*/
|
|
25
|
+
export function createResumingReadStream(options: ResumingReadOptions): ReadableStream<Uint8Array> {
|
|
26
|
+
const { reopen, retry } = options;
|
|
27
|
+
let offset = options.startOffset;
|
|
28
|
+
let failures = 0;
|
|
29
|
+
let reader = toWebReadableStream(options.initial).getReader();
|
|
30
|
+
|
|
31
|
+
return new ReadableStream<Uint8Array>({
|
|
32
|
+
async pull(controller) {
|
|
33
|
+
for (;;) {
|
|
34
|
+
try {
|
|
35
|
+
const { done, value } = await reader.read();
|
|
36
|
+
if (done) {
|
|
37
|
+
controller.close();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
failures = 0;
|
|
41
|
+
offset += value.byteLength;
|
|
42
|
+
controller.enqueue(value);
|
|
43
|
+
return;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (reopen === undefined || !(error instanceof TransientIOError)) {
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
failures += 1;
|
|
49
|
+
if (failures > retry.maxRetries) {
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
await backoff(retry, failures);
|
|
53
|
+
reader = toWebReadableStream(await reopen(offset)).getReader();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
cancel(reason) {
|
|
58
|
+
return reader.cancel(reason);
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type IOProvider,
|
|
3
|
+
isRangeReadable,
|
|
4
|
+
type Item,
|
|
5
|
+
type LocationTarget,
|
|
6
|
+
PayloadKind,
|
|
7
|
+
type RangeReadable,
|
|
8
|
+
type StreamHandle,
|
|
9
|
+
fromWebReadableStream,
|
|
10
|
+
} from "@flowscripter/pluggable-io-framework-api";
|
|
11
|
+
import { type RetryOptions, withRetry } from "@flowscripter/pluggable-io-framework";
|
|
12
|
+
import { parseRange } from "../http/parseRange.ts";
|
|
13
|
+
import { statusForError } from "../http/statusForError.ts";
|
|
14
|
+
import { createResumingReadStream } from "../stream/createResumingReadStream.ts";
|
|
15
|
+
import { baseName, joinKey } from "./keys.ts";
|
|
16
|
+
import { WriteTracker, type WriteResult } from "./WriteTracker.ts";
|
|
17
|
+
|
|
18
|
+
export type GrantScope = "read" | "read-write";
|
|
19
|
+
|
|
20
|
+
export interface GrantInit {
|
|
21
|
+
readonly provider: IOProvider<PayloadKind.Js>;
|
|
22
|
+
readonly target: Extract<LocationTarget, { kind: "entry" | "container" }>;
|
|
23
|
+
readonly scope: GrantScope;
|
|
24
|
+
readonly retry: RetryOptions;
|
|
25
|
+
readonly origin: string;
|
|
26
|
+
readonly token: string;
|
|
27
|
+
/** Whether revoking the grant disposes the provider. */
|
|
28
|
+
readonly ownsProvider: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type JsHandle = StreamHandle<PayloadKind.Js>;
|
|
32
|
+
type RangeHandle = JsHandle & RangeReadable<PayloadKind.Js>;
|
|
33
|
+
type JsStream = ReadableStream<Item<PayloadKind.Js>>;
|
|
34
|
+
|
|
35
|
+
function text(status: number, message: string, headers?: HeadersInit): Response {
|
|
36
|
+
return new Response(message, { status, headers });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Serves one root location (a container or a single entry) over HTTP,
|
|
41
|
+
* restricted to a scope. Created by `HttpGateway`; revoking it makes
|
|
42
|
+
* every later request a 404.
|
|
43
|
+
*/
|
|
44
|
+
export class GatewayGrant {
|
|
45
|
+
readonly #init: GrantInit;
|
|
46
|
+
readonly #tracker = new WriteTracker();
|
|
47
|
+
readonly #rangeHandles = new Map<string, RangeHandle>();
|
|
48
|
+
#revoked = false;
|
|
49
|
+
|
|
50
|
+
constructor(init: GrantInit) {
|
|
51
|
+
this.#init = init;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The URL of the root: the container with a trailing slash, or the single entry. */
|
|
55
|
+
get url(): string {
|
|
56
|
+
const { origin, token, target } = this.#init;
|
|
57
|
+
const base = `${origin}/${token}/`;
|
|
58
|
+
return target.kind === "entry" ? `${base}${encodeURIComponent(baseName(target.key))}` : base;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The URL of a path below a container root. */
|
|
62
|
+
urlFor(path: string): string {
|
|
63
|
+
if (this.#init.target.kind === "entry") {
|
|
64
|
+
throw new TypeError("urlFor is only available for a container root");
|
|
65
|
+
}
|
|
66
|
+
const encoded = path
|
|
67
|
+
.split("/")
|
|
68
|
+
.filter((segment) => segment !== "")
|
|
69
|
+
.map(encodeURIComponent)
|
|
70
|
+
.join("/");
|
|
71
|
+
return `${this.#init.origin}/${this.#init.token}/${encoded}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
get revoked(): boolean {
|
|
75
|
+
return this.#revoked;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Resolves with every write and delete result once none is in flight. */
|
|
79
|
+
settled(): Promise<readonly WriteResult[]> {
|
|
80
|
+
return this.#tracker.settled();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Stops serving requests. Writes already in flight still run to completion. */
|
|
84
|
+
async revoke(): Promise<void> {
|
|
85
|
+
if (this.#revoked) {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
this.#revoked = true;
|
|
89
|
+
this.#rangeHandles.clear();
|
|
90
|
+
if (this.#init.ownsProvider) {
|
|
91
|
+
await this.#tracker.settled();
|
|
92
|
+
await this.#init.provider[Symbol.asyncDispose]();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async handle(request: Request, segments: readonly string[]): Promise<Response> {
|
|
97
|
+
const key = this.#resolveKey(segments);
|
|
98
|
+
if (key === undefined) {
|
|
99
|
+
return text(404, "Not Found");
|
|
100
|
+
}
|
|
101
|
+
const path = segments.join("/");
|
|
102
|
+
switch (request.method) {
|
|
103
|
+
case "GET":
|
|
104
|
+
case "HEAD":
|
|
105
|
+
return this.#read(request, key);
|
|
106
|
+
case "PUT":
|
|
107
|
+
case "POST":
|
|
108
|
+
return this.#write(request, key, path);
|
|
109
|
+
case "DELETE":
|
|
110
|
+
return this.#delete(key, path);
|
|
111
|
+
default:
|
|
112
|
+
return text(405, "Method Not Allowed", { Allow: "GET, HEAD, PUT, POST, DELETE" });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#resolveKey(segments: readonly string[]): string | undefined {
|
|
117
|
+
const { target, provider } = this.#init;
|
|
118
|
+
if (target.kind === "entry") {
|
|
119
|
+
return segments.length === 1 && segments[0] === baseName(target.key) ? target.key : undefined;
|
|
120
|
+
}
|
|
121
|
+
if (segments.length === 0) {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
return segments.reduce((key, segment) => joinKey(provider, key, segment), target.key);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async #open(key: string): Promise<JsHandle> {
|
|
128
|
+
return withRetry(() => this.#init.provider.getReadableStream(key), this.#init.retry);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Opens a handle for its range capability only, caching it when it has one. */
|
|
132
|
+
async #rangeHandle(key: string): Promise<JsHandle> {
|
|
133
|
+
const cached = this.#rangeHandles.get(key);
|
|
134
|
+
if (cached !== undefined) {
|
|
135
|
+
return cached;
|
|
136
|
+
}
|
|
137
|
+
const handle = await this.#open(key);
|
|
138
|
+
await (handle.stream as JsStream).cancel();
|
|
139
|
+
if (isRangeReadable(handle)) {
|
|
140
|
+
this.#rangeHandles.set(key, handle);
|
|
141
|
+
}
|
|
142
|
+
return handle;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async #read(request: Request, key: string): Promise<Response> {
|
|
146
|
+
const { provider, retry } = this.#init;
|
|
147
|
+
const head = request.method === "HEAD";
|
|
148
|
+
const rangeHeader = request.headers.get("range");
|
|
149
|
+
try {
|
|
150
|
+
const properties = await withRetry(() => provider.getProperties(key), retry);
|
|
151
|
+
if (properties.isContainer) {
|
|
152
|
+
return text(404, "Not Found");
|
|
153
|
+
}
|
|
154
|
+
const size = properties.size;
|
|
155
|
+
const headers = new Headers({
|
|
156
|
+
"Content-Type": properties.contentType ?? "application/octet-stream",
|
|
157
|
+
});
|
|
158
|
+
if (properties.lastModified !== undefined) {
|
|
159
|
+
headers.set("Last-Modified", properties.lastModified.toUTCString());
|
|
160
|
+
}
|
|
161
|
+
const etag = properties.properties.etag;
|
|
162
|
+
if (typeof etag === "string") {
|
|
163
|
+
headers.set("ETag", etag);
|
|
164
|
+
}
|
|
165
|
+
if (/\bclose\b/i.test(request.headers.get("connection") ?? "")) {
|
|
166
|
+
headers.set("Connection", "close");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (head || rangeHeader !== null) {
|
|
170
|
+
const parked = await this.#rangeHandle(key);
|
|
171
|
+
const rangeable = size !== undefined && parked.bounded !== false && isRangeReadable(parked);
|
|
172
|
+
headers.set("Accept-Ranges", rangeable ? "bytes" : "none");
|
|
173
|
+
if (head) {
|
|
174
|
+
if (size !== undefined && parked.bounded !== false) {
|
|
175
|
+
headers.set("Content-Length", String(size));
|
|
176
|
+
}
|
|
177
|
+
return new Response(null, { status: 200, headers });
|
|
178
|
+
}
|
|
179
|
+
if (rangeable) {
|
|
180
|
+
const range = parseRange(rangeHeader, size);
|
|
181
|
+
if (range.kind === "unsatisfiable") {
|
|
182
|
+
headers.set("Content-Range", `bytes */${size}`);
|
|
183
|
+
headers.set("Content-Length", "0");
|
|
184
|
+
return new Response(null, { status: 416, headers });
|
|
185
|
+
}
|
|
186
|
+
if (range.kind === "range") {
|
|
187
|
+
return await this.#rangeResponse(
|
|
188
|
+
parked as RangeHandle,
|
|
189
|
+
range.start,
|
|
190
|
+
range.end,
|
|
191
|
+
size,
|
|
192
|
+
headers,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return await this.#fullResponse(key, size, headers);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return text(statusForError(error, "read"), "Upstream read failed");
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async #rangeResponse(
|
|
205
|
+
handle: RangeHandle,
|
|
206
|
+
start: number,
|
|
207
|
+
end: number,
|
|
208
|
+
size: number,
|
|
209
|
+
headers: Headers,
|
|
210
|
+
): Promise<Response> {
|
|
211
|
+
const { retry } = this.#init;
|
|
212
|
+
const open = (offset: number) => handle.readRange(offset, end);
|
|
213
|
+
const initial = await withRetry(() => open(start), retry);
|
|
214
|
+
headers.set("Content-Range", `bytes ${start}-${end - 1}/${size}`);
|
|
215
|
+
headers.set("Content-Length", String(end - start));
|
|
216
|
+
return new Response(
|
|
217
|
+
createResumingReadStream({
|
|
218
|
+
initial,
|
|
219
|
+
startOffset: start,
|
|
220
|
+
reopen: (offset) => withRetry(() => open(offset), retry),
|
|
221
|
+
retry,
|
|
222
|
+
}),
|
|
223
|
+
{ status: 206, headers },
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async #fullResponse(key: string, size: number | undefined, headers: Headers): Promise<Response> {
|
|
228
|
+
const { retry } = this.#init;
|
|
229
|
+
const handle = await this.#open(key);
|
|
230
|
+
const bounded = size !== undefined && handle.bounded !== false;
|
|
231
|
+
const rangeable = bounded && isRangeReadable(handle);
|
|
232
|
+
headers.set("Accept-Ranges", rangeable ? "bytes" : "none");
|
|
233
|
+
if (bounded) {
|
|
234
|
+
headers.set("Content-Length", String(size));
|
|
235
|
+
}
|
|
236
|
+
if (rangeable) {
|
|
237
|
+
this.#rangeHandles.set(key, handle);
|
|
238
|
+
}
|
|
239
|
+
return new Response(
|
|
240
|
+
createResumingReadStream({
|
|
241
|
+
initial: handle.stream as JsStream,
|
|
242
|
+
startOffset: 0,
|
|
243
|
+
reopen: rangeable
|
|
244
|
+
? (offset) => withRetry(() => handle.readRange(offset, size), retry)
|
|
245
|
+
: undefined,
|
|
246
|
+
retry,
|
|
247
|
+
}),
|
|
248
|
+
{ status: 200, headers },
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async #write(request: Request, key: string, path: string): Promise<Response> {
|
|
253
|
+
if (this.#init.scope !== "read-write") {
|
|
254
|
+
return text(403, "Forbidden");
|
|
255
|
+
}
|
|
256
|
+
const { provider } = this.#init;
|
|
257
|
+
this.#rangeHandles.delete(key);
|
|
258
|
+
try {
|
|
259
|
+
await this.#tracker.track("write", path, async () => {
|
|
260
|
+
const handle = await provider.getWritableStream(key);
|
|
261
|
+
const sink = handle.stream as WritableStream<Item<PayloadKind.Js>>;
|
|
262
|
+
if (request.body === null) {
|
|
263
|
+
await sink.close();
|
|
264
|
+
} else {
|
|
265
|
+
await fromWebReadableStream(request.body).pipeTo(sink);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
return new Response(null, { status: 201 });
|
|
269
|
+
} catch (error) {
|
|
270
|
+
return text(statusForError(error, "write"), "Upstream write failed");
|
|
271
|
+
} finally {
|
|
272
|
+
this.#rangeHandles.delete(key);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async #delete(key: string, path: string): Promise<Response> {
|
|
277
|
+
const { provider, scope } = this.#init;
|
|
278
|
+
if (scope !== "read-write") {
|
|
279
|
+
return text(403, "Forbidden");
|
|
280
|
+
}
|
|
281
|
+
if (provider.delete === undefined) {
|
|
282
|
+
return text(405, "Method Not Allowed", { Allow: "GET, HEAD, PUT, POST" });
|
|
283
|
+
}
|
|
284
|
+
this.#rangeHandles.delete(key);
|
|
285
|
+
try {
|
|
286
|
+
await this.#tracker.track("delete", path, () =>
|
|
287
|
+
withRetry(() => provider.delete!(key), this.#init.retry),
|
|
288
|
+
);
|
|
289
|
+
return new Response(null, { status: 204 });
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return text(statusForError(error, "read"), "Upstream delete failed");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface WriteResult {
|
|
2
|
+
readonly operation: "write" | "delete";
|
|
3
|
+
readonly path: string;
|
|
4
|
+
readonly error?: unknown;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Records every write and delete served for a token. A tool's exit code says
|
|
9
|
+
* nothing about whether its uploads committed, so callers wait on
|
|
10
|
+
* `settled` and take success or failure from the results.
|
|
11
|
+
*/
|
|
12
|
+
export class WriteTracker {
|
|
13
|
+
readonly #results: WriteResult[] = [];
|
|
14
|
+
readonly #waiters: Array<() => void> = [];
|
|
15
|
+
#inFlight = 0;
|
|
16
|
+
|
|
17
|
+
/** Runs `operation`, recording it as a result and as in flight until it settles. */
|
|
18
|
+
async track(operation: WriteResult["operation"], path: string, run: () => Promise<void>) {
|
|
19
|
+
this.#inFlight += 1;
|
|
20
|
+
try {
|
|
21
|
+
await run();
|
|
22
|
+
this.#results.push({ operation, path });
|
|
23
|
+
} catch (error) {
|
|
24
|
+
this.#results.push({ operation, path, error });
|
|
25
|
+
throw error;
|
|
26
|
+
} finally {
|
|
27
|
+
this.#inFlight -= 1;
|
|
28
|
+
if (this.#inFlight === 0) {
|
|
29
|
+
for (const resolve of this.#waiters.splice(0)) {
|
|
30
|
+
resolve();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get inFlight(): number {
|
|
37
|
+
return this.#inFlight;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Resolves with every result so far once no write or delete is in flight. */
|
|
41
|
+
async settled(): Promise<readonly WriteResult[]> {
|
|
42
|
+
if (this.#inFlight > 0) {
|
|
43
|
+
await new Promise<void>((resolve) => this.#waiters.push(resolve));
|
|
44
|
+
}
|
|
45
|
+
return [...this.#results];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IOProvider } from "@flowscripter/pluggable-io-framework-api";
|
|
2
|
+
|
|
3
|
+
/** Joins a child name onto a container key using the provider's own rule, else with `/`. */
|
|
4
|
+
export function joinKey(provider: IOProvider, containerKey: string, name: string): string {
|
|
5
|
+
if (provider.joinKey) {
|
|
6
|
+
return provider.joinKey(containerKey, name);
|
|
7
|
+
}
|
|
8
|
+
if (name === "") return containerKey;
|
|
9
|
+
if (containerKey === "") return name;
|
|
10
|
+
return `${containerKey.replace(/\/+$/, "")}/${name}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The last segment of a key, treating both `/` and `\` as separators. */
|
|
14
|
+
export function baseName(key: string): string {
|
|
15
|
+
const segments = key.split(/[\\/]+/).filter((segment) => segment !== "");
|
|
16
|
+
return segments.at(-1) ?? key;
|
|
17
|
+
}
|