@party-stack/ontology-server 0.0.0-stage → 0.11.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 +493 -2
- package/lib/attachmentHttp.d.ts +15 -0
- package/lib/attachmentHttp.d.ts.map +1 -0
- package/lib/attachmentHttp.js +235 -0
- package/lib/attachmentHttp.js.map +1 -0
- package/lib/attachmentTransfers.d.ts +115 -0
- package/lib/attachmentTransfers.d.ts.map +1 -0
- package/lib/attachmentTransfers.js +208 -0
- package/lib/attachmentTransfers.js.map +1 -0
- package/lib/authorization.d.ts +21 -0
- package/lib/authorization.d.ts.map +1 -0
- package/lib/authorization.js +385 -0
- package/lib/authorization.js.map +1 -0
- package/lib/bindingFence.d.ts +27 -0
- package/lib/bindingFence.d.ts.map +1 -0
- package/lib/bindingFence.js +39 -0
- package/lib/bindingFence.js.map +1 -0
- package/lib/composition.d.ts +467 -0
- package/lib/composition.d.ts.map +1 -0
- package/lib/composition.js +102 -0
- package/lib/composition.js.map +1 -0
- package/lib/definitionProjection.d.ts +21 -0
- package/lib/definitionProjection.d.ts.map +1 -0
- package/lib/definitionProjection.js +441 -0
- package/lib/definitionProjection.js.map +1 -0
- package/lib/errorProjection.d.ts +22 -0
- package/lib/errorProjection.d.ts.map +1 -0
- package/lib/errorProjection.js +72 -0
- package/lib/errorProjection.js.map +1 -0
- package/lib/http.d.ts +23 -0
- package/lib/http.d.ts.map +1 -0
- package/lib/http.js +17 -0
- package/lib/http.js.map +1 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +3 -0
- package/lib/internalAccess.d.ts +10 -0
- package/lib/internalAccess.d.ts.map +1 -0
- package/lib/internalAccess.js +18 -0
- package/lib/internalAccess.js.map +1 -0
- package/lib/operations.d.ts +1265 -0
- package/lib/operations.d.ts.map +1 -0
- package/lib/operations.js +621 -0
- package/lib/operations.js.map +1 -0
- package/lib/policyDefinition.d.ts +19 -0
- package/lib/policyDefinition.d.ts.map +1 -0
- package/lib/policyDefinition.js +226 -0
- package/lib/policyDefinition.js.map +1 -0
- package/lib/policyWatches.d.ts +17 -0
- package/lib/policyWatches.d.ts.map +1 -0
- package/lib/policyWatches.js +49 -0
- package/lib/policyWatches.js.map +1 -0
- package/lib/receiptPolicy.d.ts +12 -0
- package/lib/receiptPolicy.d.ts.map +1 -0
- package/lib/receiptPolicy.js +63 -0
- package/lib/receiptPolicy.js.map +1 -0
- package/lib/replicaBootstrap.d.ts +56 -0
- package/lib/replicaBootstrap.d.ts.map +1 -0
- package/lib/replicaBootstrap.js +60 -0
- package/lib/replicaBootstrap.js.map +1 -0
- package/lib/routing.d.ts +87 -0
- package/lib/routing.d.ts.map +1 -0
- package/lib/routing.js +344 -0
- package/lib/routing.js.map +1 -0
- package/lib/rpc.d.ts +4799 -0
- package/lib/rpc.d.ts.map +1 -0
- package/lib/rpc.js +575 -0
- package/lib/rpc.js.map +1 -0
- package/lib/rpcActivity.d.ts +6 -0
- package/lib/rpcActivity.d.ts.map +1 -0
- package/lib/rpcActivity.js +8 -0
- package/lib/rpcActivity.js.map +1 -0
- package/lib/rpcBackend.d.ts +8 -0
- package/lib/rpcBackend.d.ts.map +1 -0
- package/lib/rpcBackend.js +76 -0
- package/lib/rpcBackend.js.map +1 -0
- package/lib/rpcHttp.d.ts +24 -0
- package/lib/rpcHttp.d.ts.map +1 -0
- package/lib/rpcHttp.js +118 -0
- package/lib/rpcHttp.js.map +1 -0
- package/lib/rpcLocal.d.ts +13 -0
- package/lib/rpcLocal.d.ts.map +1 -0
- package/lib/rpcLocal.js +26 -0
- package/lib/rpcLocal.js.map +1 -0
- package/lib/rpcWatch.d.ts +9 -0
- package/lib/rpcWatch.d.ts.map +1 -0
- package/lib/rpcWatch.js +29 -0
- package/lib/rpcWatch.js.map +1 -0
- package/lib/rpcWorker.d.ts +38 -0
- package/lib/rpcWorker.d.ts.map +1 -0
- package/lib/rpcWorker.js +192 -0
- package/lib/rpcWorker.js.map +1 -0
- package/package.json +53 -3
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { Attachment, AttachmentUploadSchema } from "./attachmentTransfers.js";
|
|
2
|
+
import { withExpectedBinding } from "./bindingFence.js";
|
|
3
|
+
import { errorContext } from "./errorProjection.js";
|
|
4
|
+
import { ontologyAttachmentHandlers } from "./operations.js";
|
|
5
|
+
import { ActionReceiptSchema, BackendError, backendErrorStatus, classifyBackendFailure, projectBackendError } from "@party-stack/ontology-backend";
|
|
6
|
+
import { ActionRequestSchema, protocolValueCodec } from "@party-stack/ontology-backend/protocol";
|
|
7
|
+
import { attachmentByteSource, byteChunks, byteSource, collectActionAttachments, readableByteSource } from "@party-stack/ontology-storage/blobs";
|
|
8
|
+
import { Cause, Context, Deferred, Effect, Fiber, Queue, Schema, Stream } from "effect";
|
|
9
|
+
import { Headers, HttpClient, HttpClientRequest, Multipart } from "effect/http";
|
|
10
|
+
//#region src/attachmentHttp.ts
|
|
11
|
+
const uploadParameter = "attachment-upload";
|
|
12
|
+
const actionParameter = "action-upload";
|
|
13
|
+
const maxMetadataBytes = 262144;
|
|
14
|
+
const maxFiles = 32;
|
|
15
|
+
const Payload = Schema.Struct({
|
|
16
|
+
request: protocolValueCodec(ActionRequestSchema),
|
|
17
|
+
files: Schema.Array(Schema.Struct({
|
|
18
|
+
attachment: Attachment,
|
|
19
|
+
size: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
|
20
|
+
type: Schema.String,
|
|
21
|
+
name: Schema.optional(Schema.String)
|
|
22
|
+
})).check(Schema.isMinLength(1), Schema.isMaxLength(maxFiles))
|
|
23
|
+
});
|
|
24
|
+
const invalid = (message) => new BackendError({
|
|
25
|
+
operation: "attachment.http",
|
|
26
|
+
kind: "InvalidRequest",
|
|
27
|
+
message,
|
|
28
|
+
retryable: false,
|
|
29
|
+
actionOutcome: "not-committed"
|
|
30
|
+
});
|
|
31
|
+
const failure = (cause) => cause instanceof BackendError ? cause : classifyBackendFailure("attachment.http", cause);
|
|
32
|
+
const status = (kind) => backendErrorStatus({ kind });
|
|
33
|
+
const isAttachmentHttpRequest = (request) => {
|
|
34
|
+
const url = new URL(request.url);
|
|
35
|
+
return url.searchParams.has(uploadParameter) || url.searchParams.has(actionParameter);
|
|
36
|
+
};
|
|
37
|
+
/** Byte bodies stay on one HTTP request. No upload registry or cross-request affinity is required. */
|
|
38
|
+
const makeAttachmentHttpHandler = Effect.fnUntraced(function* (options) {
|
|
39
|
+
const authorize = withExpectedBinding(options);
|
|
40
|
+
const captured = yield* Effect.context();
|
|
41
|
+
const scope = yield* Effect.scope;
|
|
42
|
+
const handlers = ontologyAttachmentHandlers(options, authorize);
|
|
43
|
+
const maxBytes = options.attachmentTransfers?.limits?.maxBytes ?? 1073741824;
|
|
44
|
+
const maxTotal = options.attachmentTransfers?.limits?.maxReservedBytes ?? 4294967296;
|
|
45
|
+
const idle = options.attachmentTransfers?.limits?.idleTimeoutMs ?? 6e4;
|
|
46
|
+
const duration = options.attachmentTransfers?.limits?.maxDurationMs ?? 18e5;
|
|
47
|
+
const authorizeUpload = (metadata, headers) => authorize({
|
|
48
|
+
operation: "CreateAttachment",
|
|
49
|
+
...metadata
|
|
50
|
+
}, headers);
|
|
51
|
+
const checked = (input, complete) => {
|
|
52
|
+
const source = byteSource(input);
|
|
53
|
+
let size = 0;
|
|
54
|
+
return {
|
|
55
|
+
...source,
|
|
56
|
+
stream: Stream.concat(byteChunks(source).pipe(Stream.timeout(idle), Stream.mapEffect((chunk) => Effect.gen(function* () {
|
|
57
|
+
size += chunk.length;
|
|
58
|
+
if (size > maxBytes || source.size !== void 0 && size > source.size) return yield* invalid("Attachment exceeds its size limit.");
|
|
59
|
+
return chunk;
|
|
60
|
+
}))), Stream.fromEffect(Effect.gen(function* () {
|
|
61
|
+
if (source.size !== void 0 && size !== source.size) return yield* invalid("Incomplete attachment upload.");
|
|
62
|
+
yield* complete;
|
|
63
|
+
})).pipe(Stream.drain)).pipe(Stream.provideContext(captured))
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
const raw = Effect.fnUntraced(function* (request, action) {
|
|
67
|
+
if (request.method !== "POST") return yield* invalid("Uploads require POST.");
|
|
68
|
+
const headers = Headers.fromInput(request.headers);
|
|
69
|
+
const url = new URL(request.url);
|
|
70
|
+
if (url.searchParams.has(uploadParameter)) {
|
|
71
|
+
const metadataText = url.searchParams.get(uploadParameter);
|
|
72
|
+
if (metadataText.length > 16384) return yield* invalid("Upload metadata is too large.");
|
|
73
|
+
const metadata = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(AttachmentUploadSchema))(metadataText).pipe(Effect.mapError(() => invalid("Invalid upload metadata.")));
|
|
74
|
+
if (metadata.size !== void 0 && metadata.size > maxBytes) return yield* invalid("Attachment exceeds its size limit.");
|
|
75
|
+
yield* authorizeUpload(metadata, headers);
|
|
76
|
+
const source = checked(readableByteSource(request.body ?? new Blob([]).stream(), metadata), authorizeUpload(metadata, headers));
|
|
77
|
+
const attachment = yield* handlers.create(metadata, source);
|
|
78
|
+
return Response.json(Schema.encodeSync(Attachment)(attachment));
|
|
79
|
+
}
|
|
80
|
+
const backend = options.backend;
|
|
81
|
+
const ir = options.ir ?? options.replica?.ir;
|
|
82
|
+
if (!backend || !ir) return yield* new BackendError({
|
|
83
|
+
operation: "applyAction",
|
|
84
|
+
kind: "NotImplemented",
|
|
85
|
+
message: "Multipart actions require a native backend and its ontology definition.",
|
|
86
|
+
retryable: false
|
|
87
|
+
});
|
|
88
|
+
const requestContext = yield* Effect.context();
|
|
89
|
+
const result = yield* Deferred.make();
|
|
90
|
+
let payload;
|
|
91
|
+
let queues = [];
|
|
92
|
+
let nextFile = 0;
|
|
93
|
+
let total = 0;
|
|
94
|
+
const parse = Stream.fromReadableStream({
|
|
95
|
+
evaluate: () => request.body ?? new Blob([]).stream(),
|
|
96
|
+
onError: failure
|
|
97
|
+
}).pipe(Stream.pipeThroughChannel(Multipart.makeChannel(headers)), Stream.mapError((cause) => cause instanceof BackendError ? cause : invalid("Invalid multipart action body.")));
|
|
98
|
+
const producer = Effect.gen(function* () {
|
|
99
|
+
yield* Stream.runForEach(parse, (part) => Effect.gen(function* () {
|
|
100
|
+
if (part._tag === "Field") {
|
|
101
|
+
if (payload || part.key !== "payload") return yield* invalid("Expected one action payload before files.");
|
|
102
|
+
payload = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Payload))(part.value).pipe(Effect.mapError(() => invalid("Invalid multipart action payload.")));
|
|
103
|
+
action.name = payload.request.name;
|
|
104
|
+
const ids = payload.files.map((file) => file.attachment.id);
|
|
105
|
+
if (new Set(ids).size !== ids.length) return yield* invalid("Duplicate action attachment ID.");
|
|
106
|
+
const actionPayload = payload;
|
|
107
|
+
const references = yield* Effect.try({
|
|
108
|
+
try: () => new Map(collectActionAttachments(ir, actionPayload.request.name, actionPayload.request.parameters).map((reference) => [reference.attachment.id, reference])),
|
|
109
|
+
catch: () => invalid("Invalid action attachment references.")
|
|
110
|
+
});
|
|
111
|
+
if (ids.some((id) => !references.has(id))) return yield* invalid("An upload is not referenced by the action parameters.");
|
|
112
|
+
yield* authorize({
|
|
113
|
+
operation: "ApplyAction",
|
|
114
|
+
invocation: payload.request
|
|
115
|
+
}, headers);
|
|
116
|
+
queues = yield* Effect.forEach(payload.files, () => Queue.bounded(1));
|
|
117
|
+
yield* Effect.addFinalizer(() => Effect.forEach(queues, Queue.shutdown, { discard: true }));
|
|
118
|
+
const invocation = {
|
|
119
|
+
...payload.request,
|
|
120
|
+
attachmentUploads: payload.files.map((file, index) => ({
|
|
121
|
+
...references.get(file.attachment.id),
|
|
122
|
+
blob: checked({
|
|
123
|
+
size: file.size,
|
|
124
|
+
type: file.type,
|
|
125
|
+
name: file.name,
|
|
126
|
+
stream: Stream.fromQueue(queues[index])
|
|
127
|
+
}, Effect.void)
|
|
128
|
+
}))
|
|
129
|
+
};
|
|
130
|
+
yield* Effect.forkScoped(backend.applyAction(invocation).pipe(Effect.exit, Effect.flatMap((exit) => Deferred.done(result, exit))));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (!payload || nextFile >= queues.length || part.key !== `file-${nextFile}`) return yield* invalid("Unexpected multipart attachment part.");
|
|
134
|
+
const index = nextFile++;
|
|
135
|
+
yield* Stream.runForEach(byteChunks({
|
|
136
|
+
type: part.contentType,
|
|
137
|
+
stream: part.content
|
|
138
|
+
}), (bytes) => Effect.gen(function* () {
|
|
139
|
+
total += bytes.length;
|
|
140
|
+
if (total > maxTotal) return yield* invalid("Action attachments exceed the total byte limit.");
|
|
141
|
+
if (!(yield* Queue.offer(queues[index], bytes))) return yield* invalid("The action upload has ended.");
|
|
142
|
+
}));
|
|
143
|
+
if (index < queues.length - 1) yield* Queue.end(queues[index]);
|
|
144
|
+
}));
|
|
145
|
+
if (!payload || nextFile !== queues.length) return yield* invalid("Incomplete action attachment list.");
|
|
146
|
+
yield* authorize({
|
|
147
|
+
operation: "ApplyAction",
|
|
148
|
+
invocation: payload.request
|
|
149
|
+
}, headers);
|
|
150
|
+
yield* Queue.end(queues.at(-1));
|
|
151
|
+
}).pipe(Effect.provideContext(Context.merge(requestContext, Multipart.limitsServices({
|
|
152
|
+
maxParts: 33,
|
|
153
|
+
maxFieldSize: maxMetadataBytes,
|
|
154
|
+
maxFileSize: maxBytes,
|
|
155
|
+
maxTotalSize: maxTotal + maxMetadataBytes + maxFiles * 1024
|
|
156
|
+
}))), Effect.onError((cause) => Deferred.failCause(result, Cause.map(cause, failure))));
|
|
157
|
+
const pump = yield* Effect.forkScoped(producer);
|
|
158
|
+
const receipt = yield* Deferred.await(result);
|
|
159
|
+
yield* Fiber.join(pump);
|
|
160
|
+
return Response.json(Schema.encodeSync(ActionReceiptSchema)(receipt));
|
|
161
|
+
});
|
|
162
|
+
return (request) => {
|
|
163
|
+
const action = {};
|
|
164
|
+
return Effect.runPromiseWith(captured)(Effect.acquireUseRelease(Effect.forkIn(Effect.scoped(raw(request, action)).pipe(Effect.timeout(duration), Effect.mapError(failure), Effect.catchDefect(() => Effect.fail(new BackendError({
|
|
165
|
+
operation: "attachment.http",
|
|
166
|
+
kind: "Internal",
|
|
167
|
+
message: "Upload could not be completed.",
|
|
168
|
+
retryable: false,
|
|
169
|
+
actionOutcome: "unknown"
|
|
170
|
+
})))), scope), Fiber.join, Fiber.interrupt).pipe(Effect.catch((error) => Effect.sync(() => {
|
|
171
|
+
const projected = projectBackendError(error, options.errors, errorContext(options, action.name));
|
|
172
|
+
return Response.json(Schema.encodeSync(BackendError)(projected), { status: status(projected.kind) });
|
|
173
|
+
}).pipe(Effect.catchDefect(() => Effect.succeed(Response.json(Schema.encodeSync(BackendError)(new BackendError({
|
|
174
|
+
operation: "attachment.http",
|
|
175
|
+
kind: "Internal",
|
|
176
|
+
message: "The operation could not be completed.",
|
|
177
|
+
retryable: false,
|
|
178
|
+
actionOutcome: "unknown"
|
|
179
|
+
})), { status: 500 })))))), { signal: request.signal });
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
/** The HTTP transport shares its configured Effect HttpClient (credentials, tracing, cancellation). */
|
|
183
|
+
const makeHttpAttachmentClient = Effect.fnUntraced(function* (url) {
|
|
184
|
+
const http = yield* HttpClient.HttpClient;
|
|
185
|
+
const execute = Effect.fnUntraced(function* (request, schema) {
|
|
186
|
+
const response = yield* http.execute(request).pipe(Effect.mapError(failure));
|
|
187
|
+
const data = yield* response.json.pipe(Effect.mapError(failure));
|
|
188
|
+
if (response.status < 200 || response.status >= 300) return yield* yield* Schema.decodeUnknownEffect(BackendError)(data).pipe(Effect.mapError(failure));
|
|
189
|
+
return yield* Schema.decodeUnknownEffect(schema)(data).pipe(Effect.mapError(failure));
|
|
190
|
+
});
|
|
191
|
+
const create = (input, options) => Effect.gen(function* () {
|
|
192
|
+
const source = attachmentByteSource(input);
|
|
193
|
+
const request = HttpClientRequest.post(url).pipe(HttpClientRequest.setUrlParam(uploadParameter, JSON.stringify({
|
|
194
|
+
size: source.size,
|
|
195
|
+
type: source.type,
|
|
196
|
+
name: source.name,
|
|
197
|
+
...options
|
|
198
|
+
})), HttpClientRequest.bodyStream(byteChunks(source), {
|
|
199
|
+
contentType: "application/octet-stream",
|
|
200
|
+
contentLength: source.size
|
|
201
|
+
}));
|
|
202
|
+
return { attachment: yield* execute(request, Attachment) };
|
|
203
|
+
});
|
|
204
|
+
return {
|
|
205
|
+
create,
|
|
206
|
+
applyAction: Effect.fnUntraced(function* (invocation) {
|
|
207
|
+
const uploads = invocation.attachmentUploads ?? [];
|
|
208
|
+
const files = uploads.map((upload) => ({
|
|
209
|
+
attachment: upload.attachment,
|
|
210
|
+
size: byteSource(upload.blob).size,
|
|
211
|
+
type: byteSource(upload.blob).type,
|
|
212
|
+
name: byteSource(upload.blob).name
|
|
213
|
+
}));
|
|
214
|
+
const payload = yield* Effect.try({
|
|
215
|
+
try: () => JSON.stringify(Schema.encodeSync(Payload)({
|
|
216
|
+
request: invocation,
|
|
217
|
+
files
|
|
218
|
+
})),
|
|
219
|
+
catch: () => invalid("Invalid action upload metadata.")
|
|
220
|
+
});
|
|
221
|
+
if (new TextEncoder().encode(payload).length > maxMetadataBytes) return yield* invalid("Action upload metadata is too large.");
|
|
222
|
+
const boundary = `party-${crypto.randomUUID()}`;
|
|
223
|
+
const encode = (text) => new TextEncoder().encode(text);
|
|
224
|
+
const content = Stream.concat(Stream.succeed(encode(`--${boundary}\r\nContent-Disposition: form-data; name="payload"\r\nContent-Type: application/json\r\n\r\n${payload}\r\n`)), Stream.concat(Stream.fromIterable(uploads.map((upload, index) => ({
|
|
225
|
+
upload,
|
|
226
|
+
index
|
|
227
|
+
})), { chunkSize: 1 }).pipe(Stream.flatMap(({ upload, index }) => Stream.concat(Stream.succeed(encode(`--${boundary}\r\nContent-Disposition: form-data; name="file-${index}"; filename="attachment.bin"\r\nContent-Type: application/octet-stream\r\n\r\n`)), Stream.concat(byteChunks(upload.blob), Stream.succeed(encode("\r\n")))))), Stream.succeed(encode(`--${boundary}--\r\n`))));
|
|
228
|
+
return yield* execute(HttpClientRequest.post(url).pipe(HttpClientRequest.setUrlParam(actionParameter, "1"), HttpClientRequest.bodyStream(content, { contentType: `multipart/form-data; boundary=${boundary}` })), ActionReceiptSchema);
|
|
229
|
+
})
|
|
230
|
+
};
|
|
231
|
+
});
|
|
232
|
+
//#endregion
|
|
233
|
+
export { isAttachmentHttpRequest, makeAttachmentHttpHandler, makeHttpAttachmentClient };
|
|
234
|
+
|
|
235
|
+
//# sourceMappingURL=attachmentHttp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachmentHttp.js","names":[],"sources":["../src/attachmentHttp.ts"],"sourcesContent":["import {\n ActionReceiptSchema,\n BackendError,\n backendErrorStatus,\n classifyBackendFailure,\n projectBackendError,\n type ActionRequest,\n} from \"@party-stack/ontology-backend\";\nimport { ActionRequestSchema, protocolValueCodec } from \"@party-stack/ontology-backend/protocol\";\nimport {\n attachmentByteSource,\n byteChunks,\n byteSource,\n collectActionAttachments,\n readableByteSource,\n type ByteInput,\n type ByteSource,\n} from \"@party-stack/ontology-storage/blobs\";\nimport { Cause, Context, Deferred, Effect, Fiber, Queue, Schema, Stream } from \"effect\";\nimport { Headers, HttpClient, HttpClientRequest, Multipart } from \"effect/http\";\nimport { Attachment, AttachmentUploadSchema } from \"./attachmentTransfers.js\";\nimport { withExpectedBinding } from \"./bindingFence.js\";\nimport { errorContext } from \"./errorProjection.js\";\nimport { ontologyAttachmentHandlers, type OntologyOperationOptions } from \"./operations.js\";\nimport type { ProtocolAttachments } from \"./operations.js\";\nimport type { Scope } from \"effect\";\n\nconst uploadParameter = \"attachment-upload\";\nconst actionParameter = \"action-upload\";\nconst maxMetadataBytes = 256 * 1024;\nconst maxFiles = 32;\nconst Payload = Schema.Struct({\n request: protocolValueCodec(ActionRequestSchema),\n files: Schema.Array(\n Schema.Struct({\n attachment: Attachment,\n size: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n type: Schema.String,\n name: Schema.optional(Schema.String),\n })\n ).check(Schema.isMinLength(1), Schema.isMaxLength(maxFiles)),\n});\nconst invalid = (message: string) =>\n new BackendError({\n operation: \"attachment.http\",\n kind: \"InvalidRequest\",\n message,\n retryable: false,\n actionOutcome: \"not-committed\",\n });\nconst failure = (cause: unknown) =>\n cause instanceof BackendError ? cause : classifyBackendFailure(\"attachment.http\", cause);\nconst status = (kind: BackendError[\"kind\"]) => backendErrorStatus({ kind });\nexport const isAttachmentHttpRequest = (request: Request) => {\n const url = new URL(request.url);\n return url.searchParams.has(uploadParameter) || url.searchParams.has(actionParameter);\n};\n\n/** Byte bodies stay on one HTTP request. No upload registry or cross-request affinity is required. */\nexport const makeAttachmentHttpHandler = Effect.fnUntraced(function* <R>(\n options: OntologyOperationOptions<R>\n) {\n const authorize = withExpectedBinding(options);\n const captured = yield* Effect.context<R>();\n const scope = yield* Effect.scope;\n const handlers = ontologyAttachmentHandlers(options, authorize);\n const maxBytes = options.attachmentTransfers?.limits?.maxBytes ?? 1024 * 1024 * 1024;\n const maxTotal = options.attachmentTransfers?.limits?.maxReservedBytes ?? 4 * 1024 * 1024 * 1024;\n const idle = options.attachmentTransfers?.limits?.idleTimeoutMs ?? 60_000;\n const duration = options.attachmentTransfers?.limits?.maxDurationMs ?? 30 * 60_000;\n const authorizeUpload = (metadata: typeof AttachmentUploadSchema.Type, headers: Headers.Headers) =>\n authorize({ operation: \"CreateAttachment\", ...metadata }, headers);\n const checked = (input: ByteInput, complete: Effect.Effect<void, BackendError, R>): ByteSource => {\n const source = byteSource(input);\n let size = 0;\n return {\n ...source,\n stream: Stream.concat(\n byteChunks(source).pipe(\n Stream.timeout(idle),\n Stream.mapEffect((chunk) =>\n Effect.gen(function* () {\n size += chunk.length;\n if (size > maxBytes || (source.size !== undefined && size > source.size))\n return yield* invalid(\"Attachment exceeds its size limit.\");\n return chunk;\n })\n )\n ),\n Stream.fromEffect(\n Effect.gen(function* () {\n if (source.size !== undefined && size !== source.size)\n return yield* invalid(\"Incomplete attachment upload.\");\n yield* complete;\n })\n ).pipe(Stream.drain)\n ).pipe(Stream.provideContext(captured)),\n };\n };\n const raw = Effect.fnUntraced(function* (request: Request, action: { name?: string }) {\n if (request.method !== \"POST\") return yield* invalid(\"Uploads require POST.\");\n const headers = Headers.fromInput(request.headers);\n const url = new URL(request.url);\n if (url.searchParams.has(uploadParameter)) {\n const metadataText = url.searchParams.get(uploadParameter)!;\n if (metadataText.length > 16_384) return yield* invalid(\"Upload metadata is too large.\");\n const metadata = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(AttachmentUploadSchema))(\n metadataText\n ).pipe(Effect.mapError(() => invalid(\"Invalid upload metadata.\")));\n if (metadata.size !== undefined && metadata.size > maxBytes)\n return yield* invalid(\"Attachment exceeds its size limit.\");\n yield* authorizeUpload(metadata, headers);\n const source = checked(\n readableByteSource(request.body ?? new Blob([]).stream(), metadata),\n authorizeUpload(metadata, headers)\n );\n const attachment = yield* handlers.create(metadata, source);\n return Response.json(Schema.encodeSync(Attachment)(attachment));\n }\n const backend = options.backend;\n const ir = options.ir ?? options.replica?.ir;\n if (!backend || !ir)\n return yield* new BackendError({\n operation: \"applyAction\",\n kind: \"NotImplemented\",\n message: \"Multipart actions require a native backend and its ontology definition.\",\n retryable: false,\n });\n const requestContext = yield* Effect.context<R | Scope.Scope>();\n const result = yield* Deferred.make<\n import(\"@party-stack/ontology-backend\").ActionReceipt,\n BackendError\n >();\n let payload: typeof Payload.Type | undefined;\n let queues: Queue.Queue<Uint8Array, BackendError | Cause.Done>[] = [];\n let nextFile = 0;\n let total = 0;\n const parse = Stream.fromReadableStream({\n evaluate: () => request.body ?? new Blob([]).stream(),\n onError: failure,\n }).pipe(\n Stream.pipeThroughChannel(Multipart.makeChannel(headers)),\n Stream.mapError((cause) =>\n cause instanceof BackendError ? cause : invalid(\"Invalid multipart action body.\")\n )\n );\n const producer = Effect.gen(function* () {\n yield* Stream.runForEach(parse, (part) =>\n Effect.gen(function* () {\n if (part._tag === \"Field\") {\n if (payload || part.key !== \"payload\")\n return yield* invalid(\"Expected one action payload before files.\");\n payload = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Payload))(\n part.value\n ).pipe(Effect.mapError(() => invalid(\"Invalid multipart action payload.\")));\n action.name = payload.request.name;\n const ids = payload.files.map((file) => file.attachment.id);\n if (new Set(ids).size !== ids.length)\n return yield* invalid(\"Duplicate action attachment ID.\");\n const actionPayload = payload;\n const references = yield* Effect.try({\n try: () =>\n new Map(\n collectActionAttachments(\n ir,\n actionPayload.request.name,\n actionPayload.request.parameters\n ).map((reference) => [reference.attachment.id, reference])\n ),\n catch: () => invalid(\"Invalid action attachment references.\"),\n });\n if (ids.some((id) => !references.has(id)))\n return yield* invalid(\"An upload is not referenced by the action parameters.\");\n yield* authorize({ operation: \"ApplyAction\", invocation: payload.request }, headers);\n queues = yield* Effect.forEach(payload.files, () =>\n Queue.bounded<Uint8Array, BackendError | Cause.Done>(1)\n );\n yield* Effect.addFinalizer(() =>\n Effect.forEach(queues, Queue.shutdown, { discard: true })\n );\n const invocation = {\n ...payload.request,\n attachmentUploads: payload.files.map((file, index) => ({\n ...references.get(file.attachment.id)!,\n blob: checked(\n {\n size: file.size,\n type: file.type,\n name: file.name,\n stream: Stream.fromQueue(queues[index]!),\n },\n Effect.void\n ),\n })),\n };\n yield* Effect.forkScoped(\n backend.applyAction(invocation).pipe(\n Effect.exit,\n Effect.flatMap((exit) => Deferred.done(result, exit))\n )\n );\n return;\n }\n if (!payload || nextFile >= queues.length || part.key !== `file-${nextFile}`)\n return yield* invalid(\"Unexpected multipart attachment part.\");\n const index = nextFile++;\n yield* Stream.runForEach(\n byteChunks({ type: part.contentType, stream: part.content }),\n (bytes) =>\n Effect.gen(function* () {\n total += bytes.length;\n if (total > maxTotal)\n return yield* invalid(\"Action attachments exceed the total byte limit.\");\n if (!(yield* Queue.offer(queues[index]!, bytes)))\n return yield* invalid(\"The action upload has ended.\");\n })\n );\n // Withhold the final EOF until the entire multipart body and final authorization pass.\n // Providers cannot dispatch the action while an extra/malformed trailing part remains.\n if (index < queues.length - 1) yield* Queue.end(queues[index]!);\n })\n );\n if (!payload || nextFile !== queues.length)\n return yield* invalid(\"Incomplete action attachment list.\");\n yield* authorize({ operation: \"ApplyAction\", invocation: payload.request }, headers);\n yield* Queue.end(queues.at(-1)!);\n }).pipe(\n Effect.provideContext(\n Context.merge(\n requestContext,\n Multipart.limitsServices({\n maxParts: maxFiles + 1,\n maxFieldSize: maxMetadataBytes,\n maxFileSize: maxBytes,\n maxTotalSize: maxTotal + maxMetadataBytes + maxFiles * 1024,\n })\n )\n ),\n // A parser/authorization defect must wake the request too, rather than\n // leaving it waiting on a result that only the failed producer can supply.\n Effect.onError((cause) => Deferred.failCause(result, Cause.map(cause, failure)))\n );\n const pump = yield* Effect.forkScoped(producer);\n const receipt = yield* Deferred.await(result);\n yield* Fiber.join(pump);\n return Response.json(Schema.encodeSync(ActionReceiptSchema)(receipt));\n });\n return (request: Request) => {\n const action: { name?: string } = {};\n return Effect.runPromiseWith(captured)(\n Effect.acquireUseRelease(\n Effect.forkIn(\n Effect.scoped(raw(request, action)).pipe(\n Effect.timeout(duration),\n Effect.mapError(failure),\n Effect.catchDefect(() =>\n Effect.fail(\n new BackendError({\n operation: \"attachment.http\",\n kind: \"Internal\",\n message: \"Upload could not be completed.\",\n retryable: false,\n actionOutcome: \"unknown\",\n })\n )\n )\n ),\n scope\n ),\n Fiber.join,\n Fiber.interrupt\n ).pipe(\n Effect.catch((error) =>\n Effect.sync(() => {\n const projected = projectBackendError(\n error,\n options.errors,\n errorContext(options, action.name)\n );\n return Response.json(Schema.encodeSync(BackendError)(projected), {\n status: status(projected.kind),\n });\n }).pipe(\n Effect.catchDefect(() =>\n Effect.succeed(\n Response.json(\n Schema.encodeSync(BackendError)(\n new BackendError({\n operation: \"attachment.http\",\n kind: \"Internal\",\n message: \"The operation could not be completed.\",\n retryable: false,\n actionOutcome: \"unknown\",\n })\n ),\n { status: 500 }\n )\n )\n )\n )\n )\n ),\n { signal: request.signal }\n );\n };\n});\n\n/** The HTTP transport shares its configured Effect HttpClient (credentials, tracing, cancellation). */\nexport const makeHttpAttachmentClient = Effect.fnUntraced(function* (url: string): Effect.fn.Return<\n {\n readonly create: ProtocolAttachments[\"create\"];\n readonly applyAction: (\n request: ActionRequest\n ) => Effect.Effect<import(\"@party-stack/ontology-backend\").ActionReceipt, BackendError>;\n },\n never,\n HttpClient.HttpClient | Scope.Scope\n> {\n const http = yield* HttpClient.HttpClient;\n const execute = Effect.fnUntraced(function* <A, I>(\n request: HttpClientRequest.HttpClientRequest,\n schema: Schema.Codec<A, I>\n ) {\n const response = yield* http.execute(request).pipe(Effect.mapError(failure));\n const data = yield* response.json.pipe(Effect.mapError(failure));\n if (response.status < 200 || response.status >= 300) {\n const error = yield* Schema.decodeUnknownEffect(BackendError)(data).pipe(\n Effect.mapError(failure)\n );\n return yield* error;\n }\n return yield* Schema.decodeUnknownEffect(schema)(data).pipe(Effect.mapError(failure));\n });\n const create: ProtocolAttachments[\"create\"] = (input, options) =>\n Effect.gen(function* () {\n const source = attachmentByteSource(input);\n const request = HttpClientRequest.post(url).pipe(\n HttpClientRequest.setUrlParam(\n uploadParameter,\n JSON.stringify({ size: source.size, type: source.type, name: source.name, ...options })\n ),\n HttpClientRequest.bodyStream(byteChunks(source), {\n contentType: \"application/octet-stream\",\n contentLength: source.size,\n })\n );\n return { attachment: yield* execute(request, Attachment) };\n });\n const applyAction = Effect.fnUntraced(function* (invocation: ActionRequest) {\n const uploads = invocation.attachmentUploads ?? [];\n const files = uploads.map((upload) => ({\n attachment: upload.attachment,\n size: byteSource(upload.blob).size,\n type: byteSource(upload.blob).type,\n name: byteSource(upload.blob).name,\n }));\n const payload = yield* Effect.try({\n try: () => JSON.stringify(Schema.encodeSync(Payload)({ request: invocation, files })),\n catch: () => invalid(\"Invalid action upload metadata.\"),\n });\n if (new TextEncoder().encode(payload).length > maxMetadataBytes)\n return yield* invalid(\"Action upload metadata is too large.\");\n const boundary = `party-${crypto.randomUUID()}`;\n const encode = (text: string) => new TextEncoder().encode(text);\n const content = Stream.concat(\n Stream.succeed(\n encode(\n `--${boundary}\\r\\nContent-Disposition: form-data; name=\"payload\"\\r\\nContent-Type: application/json\\r\\n\\r\\n${payload}\\r\\n`\n )\n ),\n Stream.concat(\n Stream.fromIterable(\n uploads.map((upload, index) => ({ upload, index })),\n { chunkSize: 1 }\n ).pipe(\n Stream.flatMap(({ upload, index }) =>\n Stream.concat(\n Stream.succeed(\n encode(\n `--${boundary}\\r\\nContent-Disposition: form-data; name=\"file-${index}\"; filename=\"attachment.bin\"\\r\\nContent-Type: application/octet-stream\\r\\n\\r\\n`\n )\n ),\n Stream.concat(byteChunks(upload.blob), Stream.succeed(encode(\"\\r\\n\")))\n )\n )\n ),\n Stream.succeed(encode(`--${boundary}--\\r\\n`))\n )\n );\n return yield* execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setUrlParam(actionParameter, \"1\"),\n HttpClientRequest.bodyStream(content, {\n contentType: `multipart/form-data; boundary=${boundary}`,\n })\n ),\n ActionReceiptSchema\n );\n });\n return { create, applyAction };\n});\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,WAAW;AACjB,MAAM,UAAU,OAAO,OAAO;CAC1B,SAAS,mBAAmB,mBAAmB;CAC/C,OAAO,OAAO,MACV,OAAO,OAAO;EACV,YAAY;EACZ,MAAM,OAAO,SAAS,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,CAAC;EACxE,MAAM,OAAO;EACb,MAAM,OAAO,SAAS,OAAO,MAAM;CACvC,CAAC,CACL,CAAC,CAAC,MAAM,OAAO,YAAY,CAAC,GAAG,OAAO,YAAY,QAAQ,CAAC;AAC/D,CAAC;AACD,MAAM,WAAW,YACb,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN;CACA,WAAW;CACX,eAAe;AACnB,CAAC;AACL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/blobs";
|
|
3
|
+
import { Effect, Schema, Scope } from "effect";
|
|
4
|
+
import { Rpc, RpcGroup } from "effect/rpc";
|
|
5
|
+
import { Headers } from "effect/http/Headers";
|
|
6
|
+
//#region src/attachmentTransfers.d.ts
|
|
7
|
+
export declare const attachmentChunkSize: number;
|
|
8
|
+
export declare const Attachment: Schema.Struct<{
|
|
9
|
+
readonly id: Schema.NonEmptyString;
|
|
10
|
+
readonly type: Schema.optional<Schema.String>;
|
|
11
|
+
readonly source: Schema.optional<Schema.Struct<{
|
|
12
|
+
readonly objectType: Schema.String;
|
|
13
|
+
readonly primaryKey: Schema.Union<readonly [Schema.String, Schema.Number]>;
|
|
14
|
+
readonly property: Schema.String;
|
|
15
|
+
}>>;
|
|
16
|
+
}>;
|
|
17
|
+
export declare const Target: Schema.Union<readonly [Schema.Struct<{
|
|
18
|
+
readonly kind: Schema.Literal<"objectProperty">;
|
|
19
|
+
readonly objectType: Schema.String;
|
|
20
|
+
readonly property: Schema.String;
|
|
21
|
+
}>, Schema.Struct<{
|
|
22
|
+
readonly kind: Schema.Literal<"actionParameter">;
|
|
23
|
+
readonly actionType: Schema.String;
|
|
24
|
+
readonly parameter: Schema.String;
|
|
25
|
+
}>]>;
|
|
26
|
+
export declare const AttachmentUploadSchema: Schema.Struct<{
|
|
27
|
+
readonly size: Schema.optional<Schema.Int>;
|
|
28
|
+
readonly type: Schema.String;
|
|
29
|
+
readonly name: Schema.optional<Schema.String>;
|
|
30
|
+
readonly id: Schema.optional<Schema.NonEmptyString>;
|
|
31
|
+
readonly target: Schema.optional<Schema.Union<readonly [Schema.Struct<{
|
|
32
|
+
readonly kind: Schema.Literal<"objectProperty">;
|
|
33
|
+
readonly objectType: Schema.String;
|
|
34
|
+
readonly property: Schema.String;
|
|
35
|
+
}>, Schema.Struct<{
|
|
36
|
+
readonly kind: Schema.Literal<"actionParameter">;
|
|
37
|
+
readonly actionType: Schema.String;
|
|
38
|
+
readonly parameter: Schema.String;
|
|
39
|
+
}>]>>;
|
|
40
|
+
readonly eager: Schema.optional<Schema.Boolean>;
|
|
41
|
+
}>;
|
|
42
|
+
/** RPC streams responses. Upload chunks use acknowledged calls beneath a scoped response stream. */
|
|
43
|
+
export declare const AttachmentTransferRpcs: RpcGroup.RpcGroup<Rpc.Rpc<"CreateAttachment", Schema.Struct<{
|
|
44
|
+
readonly size: Schema.optional<Schema.Int>;
|
|
45
|
+
readonly type: Schema.String;
|
|
46
|
+
readonly name: Schema.optional<Schema.String>;
|
|
47
|
+
readonly id: Schema.optional<Schema.NonEmptyString>;
|
|
48
|
+
readonly target: Schema.optional<Schema.Union<readonly [Schema.Struct<{
|
|
49
|
+
readonly kind: Schema.Literal<"objectProperty">;
|
|
50
|
+
readonly objectType: Schema.String;
|
|
51
|
+
readonly property: Schema.String;
|
|
52
|
+
}>, Schema.Struct<{
|
|
53
|
+
readonly kind: Schema.Literal<"actionParameter">;
|
|
54
|
+
readonly actionType: Schema.String;
|
|
55
|
+
readonly parameter: Schema.String;
|
|
56
|
+
}>]>>;
|
|
57
|
+
readonly eager: Schema.optional<Schema.Boolean>;
|
|
58
|
+
}>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [Schema.Struct<{
|
|
59
|
+
readonly kind: Schema.Literal<"ready">;
|
|
60
|
+
readonly uploadId: Schema.NonEmptyString;
|
|
61
|
+
}>, Schema.Struct<{
|
|
62
|
+
readonly kind: Schema.Literal<"complete">;
|
|
63
|
+
readonly attachment: Schema.Struct<{
|
|
64
|
+
readonly id: Schema.NonEmptyString;
|
|
65
|
+
readonly type: Schema.optional<Schema.String>;
|
|
66
|
+
readonly source: Schema.optional<Schema.Struct<{
|
|
67
|
+
readonly objectType: Schema.String;
|
|
68
|
+
readonly primaryKey: Schema.Union<readonly [Schema.String, Schema.Number]>;
|
|
69
|
+
readonly property: Schema.String;
|
|
70
|
+
}>>;
|
|
71
|
+
}>;
|
|
72
|
+
}>]>, typeof BackendError>, Schema.Never, never, never> | Rpc.Rpc<"ReadAttachment", Schema.Struct<{
|
|
73
|
+
readonly id: Schema.NonEmptyString;
|
|
74
|
+
readonly type: Schema.optional<Schema.String>;
|
|
75
|
+
readonly source: Schema.optional<Schema.Struct<{
|
|
76
|
+
readonly objectType: Schema.String;
|
|
77
|
+
readonly primaryKey: Schema.Union<readonly [Schema.String, Schema.Number]>;
|
|
78
|
+
readonly property: Schema.String;
|
|
79
|
+
}>>;
|
|
80
|
+
}>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [Schema.Struct<{
|
|
81
|
+
readonly kind: Schema.Literal<"metadata">;
|
|
82
|
+
readonly type: Schema.String;
|
|
83
|
+
readonly size: Schema.optional<Schema.Int>;
|
|
84
|
+
readonly name: Schema.optional<Schema.String>;
|
|
85
|
+
}>, Schema.Struct<{
|
|
86
|
+
readonly kind: Schema.Literal<"bytes">;
|
|
87
|
+
readonly bytes: Schema.Uint8ArrayFromBase64;
|
|
88
|
+
}>]>, typeof BackendError>, Schema.Never, never, never> | Rpc.Rpc<"WriteAttachmentChunk", Schema.Struct<{
|
|
89
|
+
readonly uploadId: Schema.NonEmptyString;
|
|
90
|
+
readonly sequence: Schema.Int;
|
|
91
|
+
readonly bytes: Schema.Uint8ArrayFromBase64;
|
|
92
|
+
readonly end: Schema.Boolean;
|
|
93
|
+
}>, Schema.Void, typeof BackendError, never, never>>;
|
|
94
|
+
export type AttachmentUpload = Schema.Schema.Type<typeof AttachmentUploadSchema>;
|
|
95
|
+
export type AttachmentValue = Schema.Schema.Type<typeof Attachment>;
|
|
96
|
+
export interface AttachmentTransferPolicy<R = never> {
|
|
97
|
+
/** For custom authentication, return the stable authenticated principal + form/revision scope. */
|
|
98
|
+
uploadOwner?: (headers: Headers) => Effect.Effect<string, BackendError, R>;
|
|
99
|
+
limits?: {
|
|
100
|
+
maxBytes?: number;
|
|
101
|
+
maxConcurrent?: number;
|
|
102
|
+
maxPerOwner?: number;
|
|
103
|
+
maxReservedBytes?: number;
|
|
104
|
+
idleTimeoutMs?: number;
|
|
105
|
+
maxDurationMs?: number;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export declare const attachmentTransferHandlers: <R>(options: AttachmentTransferPolicy<R> & {
|
|
109
|
+
authorizeUpload(request: AttachmentUpload, headers: Headers): Effect.Effect<void, BackendError, R>;
|
|
110
|
+
create(request: AttachmentUpload, blob: ByteInput): Effect.Effect<AttachmentValue, BackendError, R>;
|
|
111
|
+
read(attachment: AttachmentValue, headers: Headers): Effect.Effect<ByteInput, BackendError, R | Scope.Scope>;
|
|
112
|
+
}) => import("effect/Layer").Layer<Rpc.Handler<"CreateAttachment"> | Rpc.Handler<"ReadAttachment"> | Rpc.Handler<"WriteAttachmentChunk">, never, Exclude<Exclude<R, never>, Scope.Scope> | Exclude<Exclude<R, never>, Scope.Scope> | Exclude<Exclude<Exclude<R, Scope.Scope>, never>, Scope.Scope> | Exclude<Exclude<Exclude<R, Scope.Scope>, never>, Scope.Scope>>;
|
|
113
|
+
export declare function splitAttachmentChunk(bytes: Uint8Array): Generator<Uint8Array<ArrayBufferLike>, void, unknown>;
|
|
114
|
+
//#endregion
|
|
115
|
+
//# sourceMappingURL=attachmentTransfers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachmentTransfers.d.ts","names":[],"sources":["../src/attachmentTransfers.ts"],"mappings":";;;;;;qBAQa;qBAEA,YAAU,OAAA;;;;;;;;;qBAWV,QAAM,OAAA,gBAAA,OAAA;;;;;;;;;qBAYN,wBAAsB,OAAA;;;;;;;;;;;;;;;;;qBA6BtB,wBAAsB,SAAA,SAAA,IAAA,wBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAclC,OAAA,aAAA;YACW,mBAAmB,OAAO,OAAO,YAAY;YAC7C,kBAAkB,OAAO,OAAO,YAAY;iBAUvC,yBAAyB;;EAEtC,eAAe,SAAS,YAAY,OAAO,eAAe,cAAc;EACxE;IACI;IACA;IACA;IACA;IACA;IACA;;;qBAIK,6BAA8B,GAAC,SAC/B,yBAAyB;EAC9B,gBAAgB,SAAS,kBAAkB,SAAS,UAAU,OAAO,aAAa,cAAc;EAChG,OAAO,SAAS,kBAAkB,MAAM,YAAY,OAAO,OAAO,iBAAiB,cAAc;EACjG,KACI,YAAY,iBACZ,SAAS,UACV,OAAO,OAAO,WAAW,cAAc,IAAI,MAAM;6BACvD,MAAA,IAAA,8BAAA,IAAA,4BAAA,IAAA,wCAAA,QAAA,QAAA,WAAA,MAAA,SAAA,QAAA,QAAA,WAAA,MAAA,SAAA,QAAA,QAAA,QAAA,GAAA,MAAA,gBAAA,MAAA,SAAA,QAAA,QAAA,QAAA,GAAA,MAAA,gBAAA,MAAA;wBAiNY,qBAAqB,OAAO,aAAU,UAAA,WAAA"}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { RpcActivity } from "./rpcActivity.js";
|
|
2
|
+
import { BackendError } from "@party-stack/ontology-backend";
|
|
3
|
+
import { byteChunks, byteSource } from "@party-stack/ontology-storage/blobs";
|
|
4
|
+
import { Effect, Queue, Schema, Semaphore, Stream } from "effect";
|
|
5
|
+
import { Rpc, RpcGroup } from "effect/rpc";
|
|
6
|
+
//#region src/attachmentTransfers.ts
|
|
7
|
+
const attachmentChunkSize = 65536;
|
|
8
|
+
const Counter = Schema.Int.check(Schema.isBetween({
|
|
9
|
+
minimum: 0,
|
|
10
|
+
maximum: Number.MAX_SAFE_INTEGER
|
|
11
|
+
}));
|
|
12
|
+
const Attachment = Schema.Struct({
|
|
13
|
+
id: Schema.NonEmptyString,
|
|
14
|
+
type: Schema.optional(Schema.String),
|
|
15
|
+
source: Schema.optional(Schema.Struct({
|
|
16
|
+
objectType: Schema.String,
|
|
17
|
+
primaryKey: Schema.Union([Schema.String, Schema.Number]),
|
|
18
|
+
property: Schema.String
|
|
19
|
+
}))
|
|
20
|
+
});
|
|
21
|
+
const Target = Schema.Union([Schema.Struct({
|
|
22
|
+
kind: Schema.Literal("objectProperty"),
|
|
23
|
+
objectType: Schema.String,
|
|
24
|
+
property: Schema.String
|
|
25
|
+
}), Schema.Struct({
|
|
26
|
+
kind: Schema.Literal("actionParameter"),
|
|
27
|
+
actionType: Schema.String,
|
|
28
|
+
parameter: Schema.String
|
|
29
|
+
})]);
|
|
30
|
+
const AttachmentUploadSchema = Schema.Struct({
|
|
31
|
+
size: Schema.optional(Counter),
|
|
32
|
+
type: Schema.String,
|
|
33
|
+
name: Schema.optional(Schema.String),
|
|
34
|
+
id: Schema.optional(Schema.NonEmptyString),
|
|
35
|
+
target: Schema.optional(Target),
|
|
36
|
+
eager: Schema.optional(Schema.Boolean)
|
|
37
|
+
});
|
|
38
|
+
const Chunk = Schema.Struct({
|
|
39
|
+
uploadId: Schema.NonEmptyString,
|
|
40
|
+
sequence: Counter,
|
|
41
|
+
bytes: Schema.Uint8ArrayFromBase64.check(Schema.isMaxLength(attachmentChunkSize)),
|
|
42
|
+
end: Schema.Boolean
|
|
43
|
+
});
|
|
44
|
+
const UploadEvent = Schema.Union([Schema.Struct({
|
|
45
|
+
kind: Schema.Literal("ready"),
|
|
46
|
+
uploadId: Schema.NonEmptyString
|
|
47
|
+
}), Schema.Struct({
|
|
48
|
+
kind: Schema.Literal("complete"),
|
|
49
|
+
attachment: Attachment
|
|
50
|
+
})]);
|
|
51
|
+
const DownloadEvent = Schema.Union([Schema.Struct({
|
|
52
|
+
kind: Schema.Literal("metadata"),
|
|
53
|
+
type: Schema.String,
|
|
54
|
+
size: Schema.optional(Counter),
|
|
55
|
+
name: Schema.optional(Schema.String)
|
|
56
|
+
}), Schema.Struct({
|
|
57
|
+
kind: Schema.Literal("bytes"),
|
|
58
|
+
bytes: Schema.Uint8ArrayFromBase64
|
|
59
|
+
})]);
|
|
60
|
+
/** RPC streams responses. Upload chunks use acknowledged calls beneath a scoped response stream. */
|
|
61
|
+
const AttachmentTransferRpcs = RpcGroup.make(Rpc.make("CreateAttachment", {
|
|
62
|
+
payload: AttachmentUploadSchema,
|
|
63
|
+
success: UploadEvent,
|
|
64
|
+
error: BackendError,
|
|
65
|
+
stream: true
|
|
66
|
+
}).annotate(RpcActivity, "transfer"), Rpc.make("WriteAttachmentChunk", {
|
|
67
|
+
payload: Chunk,
|
|
68
|
+
error: BackendError
|
|
69
|
+
}), Rpc.make("ReadAttachment", {
|
|
70
|
+
payload: Attachment,
|
|
71
|
+
success: DownloadEvent,
|
|
72
|
+
error: BackendError,
|
|
73
|
+
stream: true
|
|
74
|
+
}).annotate(RpcActivity, "transfer"));
|
|
75
|
+
const rejected = (message) => new BackendError({
|
|
76
|
+
operation: "attachment.transfer",
|
|
77
|
+
kind: "InvalidRequest",
|
|
78
|
+
message,
|
|
79
|
+
retryable: false
|
|
80
|
+
});
|
|
81
|
+
const attachmentTransferHandlers = (options) => {
|
|
82
|
+
const uploads = /* @__PURE__ */ new Map();
|
|
83
|
+
const limits = {
|
|
84
|
+
maxBytes: 1073741824,
|
|
85
|
+
maxConcurrent: 8,
|
|
86
|
+
maxPerOwner: 2,
|
|
87
|
+
maxReservedBytes: 4294967296,
|
|
88
|
+
idleTimeoutMs: 6e4,
|
|
89
|
+
maxDurationMs: 18e5,
|
|
90
|
+
...options.limits
|
|
91
|
+
};
|
|
92
|
+
for (const value of Object.values(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError("Invalid attachment transfer limits.");
|
|
93
|
+
const owner = options.uploadOwner ?? ((headers) => Effect.tryPromise(async () => {
|
|
94
|
+
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([headers.authorization ?? "", headers.cookie ?? ""])));
|
|
95
|
+
return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
96
|
+
}).pipe(Effect.mapError(() => rejected("Cannot identify attachment transfer owner."))));
|
|
97
|
+
const limited = () => new BackendError({
|
|
98
|
+
operation: "attachment.transfer",
|
|
99
|
+
kind: "RateLimited",
|
|
100
|
+
message: "Attachment transfer capacity is in use.",
|
|
101
|
+
retryable: true
|
|
102
|
+
});
|
|
103
|
+
return AttachmentTransferRpcs.toLayer({
|
|
104
|
+
CreateAttachment: (request, context) => Stream.unwrap(Effect.gen(function* () {
|
|
105
|
+
yield* Effect.annotateCurrentSpan("activity", "transfer");
|
|
106
|
+
yield* options.authorizeUpload(request, context.headers);
|
|
107
|
+
if (request.size !== void 0 && request.size > limits.maxBytes) return yield* rejected("Attachment exceeds the configured upload limit.");
|
|
108
|
+
const principal = yield* owner(context.headers);
|
|
109
|
+
const id = crypto.randomUUID();
|
|
110
|
+
const queue = yield* Queue.bounded(1);
|
|
111
|
+
const transfer = {
|
|
112
|
+
request,
|
|
113
|
+
owner: principal,
|
|
114
|
+
clientId: context.client.id,
|
|
115
|
+
reserved: request.size ?? limits.maxBytes,
|
|
116
|
+
queue,
|
|
117
|
+
gate: yield* Semaphore.make(1),
|
|
118
|
+
sequence: 0,
|
|
119
|
+
size: 0,
|
|
120
|
+
ended: false
|
|
121
|
+
};
|
|
122
|
+
yield* Effect.acquireRelease(Effect.gen(function* () {
|
|
123
|
+
const active = [...uploads.values()];
|
|
124
|
+
if (active.length >= limits.maxConcurrent || active.filter((item) => item.owner === principal).length >= limits.maxPerOwner || active.reduce((total, item) => total + item.reserved, transfer.reserved) > limits.maxReservedBytes) return yield* limited();
|
|
125
|
+
uploads.set(id, transfer);
|
|
126
|
+
}), () => Effect.sync(() => {
|
|
127
|
+
uploads.delete(id);
|
|
128
|
+
Queue.shutdownUnsafe(queue);
|
|
129
|
+
}));
|
|
130
|
+
const consume = Effect.gen(function* () {
|
|
131
|
+
const stream = Stream.fromQueue(queue).pipe(Stream.timeout(limits.idleTimeoutMs), Stream.mapError((cause) => cause instanceof BackendError ? cause : rejected("Attachment transfer timed out.")), Stream.takeUntil((frame) => frame.end), Stream.map((frame) => frame.bytes));
|
|
132
|
+
const attachment = yield* options.create(request, {
|
|
133
|
+
stream,
|
|
134
|
+
size: request.size,
|
|
135
|
+
type: request.type,
|
|
136
|
+
name: request.name
|
|
137
|
+
});
|
|
138
|
+
if (!transfer.ended) return yield* rejected("Attachment writer returned before the upload finished.");
|
|
139
|
+
return {
|
|
140
|
+
kind: "complete",
|
|
141
|
+
attachment
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
return Stream.concat(Stream.succeed({
|
|
145
|
+
kind: "ready",
|
|
146
|
+
uploadId: id
|
|
147
|
+
}), Stream.fromEffect(consume.pipe(Effect.timeout(limits.maxDurationMs), Effect.catchTag("TimeoutError", () => Effect.fail(new BackendError({
|
|
148
|
+
operation: "attachment.transfer",
|
|
149
|
+
kind: "Unavailable",
|
|
150
|
+
message: "Attachment transfer deadline expired.",
|
|
151
|
+
retryable: true
|
|
152
|
+
}))))));
|
|
153
|
+
})),
|
|
154
|
+
WriteAttachmentChunk: (request, context) => Effect.gen(function* () {
|
|
155
|
+
const transfer = uploads.get(request.uploadId);
|
|
156
|
+
if (!transfer) return yield* rejected("The attachment transfer has ended.");
|
|
157
|
+
if (transfer.clientId !== context.client.id || transfer.owner !== (yield* owner(context.headers))) return yield* new BackendError({
|
|
158
|
+
operation: "attachment.transfer",
|
|
159
|
+
kind: "Forbidden",
|
|
160
|
+
message: "Attachment transfer is unavailable.",
|
|
161
|
+
retryable: false
|
|
162
|
+
});
|
|
163
|
+
yield* transfer.gate.withPermits(1)(Effect.gen(function* () {
|
|
164
|
+
if (transfer.ended || request.sequence !== transfer.sequence || transfer.size + request.bytes.length > limits.maxBytes || transfer.request.size !== void 0 && transfer.size + request.bytes.length > transfer.request.size || request.end && transfer.request.size !== void 0 && transfer.size + request.bytes.length !== transfer.request.size) {
|
|
165
|
+
const error = rejected("Invalid attachment chunk sequence or size.");
|
|
166
|
+
yield* Queue.fail(transfer.queue, error);
|
|
167
|
+
return yield* error;
|
|
168
|
+
}
|
|
169
|
+
if (request.end) yield* options.authorizeUpload(transfer.request, context.headers).pipe(Effect.tapError((error) => Queue.fail(transfer.queue, error)));
|
|
170
|
+
transfer.sequence++;
|
|
171
|
+
transfer.size += request.bytes.length;
|
|
172
|
+
transfer.ended = request.end;
|
|
173
|
+
if (!(yield* Queue.offer(transfer.queue, {
|
|
174
|
+
bytes: request.bytes,
|
|
175
|
+
end: request.end
|
|
176
|
+
}))) return yield* rejected("The attachment transfer has ended.");
|
|
177
|
+
}));
|
|
178
|
+
}),
|
|
179
|
+
ReadAttachment: (attachment, context) => Stream.unwrap(Effect.gen(function* () {
|
|
180
|
+
yield* Effect.annotateCurrentSpan("activity", "transfer");
|
|
181
|
+
const blob = byteSource(yield* options.read(attachment, context.headers));
|
|
182
|
+
const metadata = {
|
|
183
|
+
kind: "metadata",
|
|
184
|
+
type: blob.type,
|
|
185
|
+
size: blob.size,
|
|
186
|
+
name: blob.name
|
|
187
|
+
};
|
|
188
|
+
const bytes = byteChunks(blob).pipe(Stream.mapError((cause) => cause instanceof BackendError ? cause : new BackendError({
|
|
189
|
+
operation: "attachment.read",
|
|
190
|
+
kind: "Unavailable",
|
|
191
|
+
message: "Attachment stream failed.",
|
|
192
|
+
retryable: true,
|
|
193
|
+
cause
|
|
194
|
+
})), Stream.map((bytes) => ({
|
|
195
|
+
kind: "bytes",
|
|
196
|
+
bytes
|
|
197
|
+
})));
|
|
198
|
+
return Stream.concat(Stream.succeed(metadata), bytes);
|
|
199
|
+
}))
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
function* splitAttachmentChunk(bytes) {
|
|
203
|
+
for (let offset = 0; offset < bytes.length; offset += attachmentChunkSize) yield bytes.subarray(offset, offset + attachmentChunkSize);
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
export { Attachment, AttachmentTransferRpcs, AttachmentUploadSchema, Target, attachmentChunkSize, attachmentTransferHandlers, splitAttachmentChunk };
|
|
207
|
+
|
|
208
|
+
//# sourceMappingURL=attachmentTransfers.js.map
|