@stitchwire/client 0.0.0-stage → 0.31.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 +296 -2
- package/dist/chunk-d3248e3w.js +728 -0
- package/dist/chunk-mva06nh4.js +709 -0
- package/dist/contracts.d.ts +1 -0
- package/dist/contracts.js +84 -0
- package/dist/enrollment.d.ts +1 -0
- package/dist/enrollment.js +503 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1680 -0
- package/dist/types/client/src/contracts.d.ts +1 -0
- package/dist/types/client/src/enrollment.d.ts +11 -0
- package/dist/types/client/src/index.d.ts +1 -0
- package/dist/types/contracts/src/door/client-error.d.ts +20 -0
- package/dist/types/contracts/src/door/common.d.ts +3 -0
- package/dist/types/contracts/src/door/event-lifecycle.d.ts +22 -0
- package/dist/types/contracts/src/door/local-contract.d.ts +466 -0
- package/dist/types/contracts/src/door/paths.d.ts +17 -0
- package/dist/types/contracts/src/door/request-bounds.d.ts +4 -0
- package/dist/types/contracts/src/door/requests.d.ts +47 -0
- package/dist/types/contracts/src/door/results.d.ts +319 -0
- package/dist/types/contracts/src/door/status.d.ts +859 -0
- package/dist/types/contracts/src/door/streams.d.ts +226 -0
- package/dist/types/contracts/src/enrollment/fleet-admission.d.ts +413 -0
- package/dist/types/contracts/src/enrollment/outcome.d.ts +29 -0
- package/dist/types/contracts/src/enrollment/request.d.ts +281 -0
- package/dist/types/contracts/src/enrollment/result.d.ts +713 -0
- package/dist/types/contracts/src/fleet/bundle.d.ts +209 -0
- package/dist/types/contracts/src/fleet/identity.d.ts +4 -0
- package/dist/types/contracts/src/fleet/manifest.d.ts +71 -0
- package/dist/types/contracts/src/fleet/status.d.ts +56 -0
- package/dist/types/contracts/src/peer-contract.d.ts +78 -0
- package/dist/types/contracts/src/protocol/bounds.d.ts +37 -0
- package/dist/types/contracts/src/protocol/broker-health.d.ts +384 -0
- package/dist/types/contracts/src/protocol/event.d.ts +222 -0
- package/dist/types/contracts/src/protocol/failure.d.ts +146 -0
- package/dist/types/contracts/src/protocol/identity.d.ts +11 -0
- package/dist/types/contracts/src/protocol/json-bounds.d.ts +6 -0
- package/dist/types/contracts/src/protocol/lane-url.d.ts +16 -0
- package/dist/types/contracts/src/protocol/paths.d.ts +7 -0
- package/dist/types/contracts/src/protocol/payload.d.ts +25 -0
- package/dist/types/contracts/src/protocol/presence.d.ts +66 -0
- package/dist/types/contracts/src/protocol/release.d.ts +61 -0
- package/dist/types/contracts/src/protocol/result.d.ts +41 -0
- package/dist/types/contracts/src/protocol/rpc.d.ts +106 -0
- package/dist/types/contracts/src/protocol/schema-parse.d.ts +23 -0
- package/dist/types/contracts/src/protocol/stream.d.ts +290 -0
- package/dist/types/contracts/src/protocol/topic.d.ts +185 -0
- package/dist/types/contracts/src/service/budgets.d.ts +3 -0
- package/dist/types/contracts/src/service/contract-descriptor.d.ts +9 -0
- package/dist/types/contracts/src/service/contracts.d.ts +430 -0
- package/dist/types/contracts/src/service/declaration.d.ts +122 -0
- package/dist/types/contracts/src/service/diagnostics.d.ts +104 -0
- package/dist/types/contracts/src/service/owner-route-path.d.ts +11 -0
- package/dist/types/contracts/src/service/policy-schema.d.ts +154 -0
- package/dist/types/contracts/src/service/request-bounds.d.ts +5 -0
- package/dist/types/contracts/src/service/service-contract.d.ts +112 -0
- package/dist/types/local-client/src/broker-health.d.ts +18 -0
- package/dist/types/local-client/src/client.d.ts +377 -0
- package/dist/types/local-client/src/contracts.d.ts +112 -0
- package/dist/types/local-client/src/declarations.d.ts +57 -0
- package/dist/types/local-client/src/door-paths.d.ts +18 -0
- package/dist/types/local-client/src/errno.d.ts +6 -0
- package/dist/types/local-client/src/error-chain.d.ts +25 -0
- package/dist/types/local-client/src/errors.d.ts +39 -0
- package/dist/types/local-client/src/event-sequence.d.ts +4 -0
- package/dist/types/local-client/src/feed.d.ts +8 -0
- package/dist/types/local-client/src/http.d.ts +20 -0
- package/dist/types/local-client/src/index.d.ts +13 -0
- package/dist/types/local-client/src/ingress.d.ts +31 -0
- package/dist/types/local-client/src/operation.d.ts +37 -0
- package/dist/types/local-client/src/options.d.ts +18 -0
- package/dist/types/local-client/src/paths.d.ts +52 -0
- package/dist/types/local-client/src/readers.d.ts +143 -0
- package/dist/types/local-client/src/service.d.ts +33 -0
- package/dist/types/local-client/src/status-readers.d.ts +756 -0
- package/dist/types/local-client/src/unary.d.ts +10 -0
- package/package.json +58 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1680 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LOCAL_API_VERSION2,
|
|
3
|
+
NodeIdSchema,
|
|
4
|
+
MAX_ARG_COUNT,
|
|
5
|
+
MAX_ARG_BYTES,
|
|
6
|
+
MAX_STDIN_BYTES,
|
|
7
|
+
MAX_COMMAND_TIMEOUT_MS,
|
|
8
|
+
MAX_STREAM_TIMEOUT_MS,
|
|
9
|
+
MAX_STREAM_TOTAL_BYTES,
|
|
10
|
+
MAX_EVENT_BYTES,
|
|
11
|
+
DOOR_MAX_REQUEST_BYTES,
|
|
12
|
+
DOOR_MAX_RESPONSE_BYTES,
|
|
13
|
+
DOOR_MAX_FRAME_BYTES,
|
|
14
|
+
addInputBoundIssues,
|
|
15
|
+
jsonEnvelopeBytes,
|
|
16
|
+
SERVICE_DEFAULT_REQUEST_BYTES2,
|
|
17
|
+
SERVICE_MAX_REQUEST_BYTES2,
|
|
18
|
+
SERVICE_MAX_REQUEST_ENVELOPE_BYTES,
|
|
19
|
+
SERVICE_TRACE_HEADER,
|
|
20
|
+
ServicePhaseSchema,
|
|
21
|
+
ServiceDiagnosticsSchema,
|
|
22
|
+
TRANSPORT_CAUSES,
|
|
23
|
+
refusalRefinement,
|
|
24
|
+
SERVICE_MAX_RESPONSE_BYTES2,
|
|
25
|
+
SERVICE_MAX_TIMEOUT_MS2,
|
|
26
|
+
SERVICE_MAX_INFLIGHT2,
|
|
27
|
+
SERVICE_MAX_DESCRIPTOR_BYTES2,
|
|
28
|
+
ServiceIdSchema,
|
|
29
|
+
ServiceOperationIdSchema,
|
|
30
|
+
ServiceRevisionSchema,
|
|
31
|
+
ServiceRequestPayloadSchema,
|
|
32
|
+
ServiceCallSchema,
|
|
33
|
+
ServiceIngressSchema,
|
|
34
|
+
ServiceFailureCodeSchema2,
|
|
35
|
+
ServiceOutcomeSchema,
|
|
36
|
+
LocalServiceResultSchema,
|
|
37
|
+
ServiceLimitsSchema2,
|
|
38
|
+
ServiceEffectSchema2,
|
|
39
|
+
ServiceDescriptorSchema2,
|
|
40
|
+
ServiceBindingSchema2,
|
|
41
|
+
TopicNameSchema,
|
|
42
|
+
EventAckSchema,
|
|
43
|
+
TopicRetentionSchema2,
|
|
44
|
+
TopicNamespaceSchema2,
|
|
45
|
+
isTopicInNamespace2,
|
|
46
|
+
isTopicAuthorized2,
|
|
47
|
+
MAX_DECLARED_TOPICS2,
|
|
48
|
+
MAX_TOPIC_DESCRIPTOR_FILES2,
|
|
49
|
+
TOPIC_MAX_DESCRIPTOR_BYTES2,
|
|
50
|
+
TopicProfileSchema2,
|
|
51
|
+
TopicDescriptorSchema2,
|
|
52
|
+
parseTopicDescriptor2,
|
|
53
|
+
ServiceNamespaceSchema2,
|
|
54
|
+
serviceInNamespace2,
|
|
55
|
+
ServiceDeclarationSchema2,
|
|
56
|
+
SERVICE_MAX_DECLARATION_BYTES2,
|
|
57
|
+
parseServiceDeclaration2
|
|
58
|
+
} from "./chunk-mva06nh4.js";
|
|
59
|
+
import {
|
|
60
|
+
ClientErrorCodeSchema2,
|
|
61
|
+
StreamProfileNameSchema,
|
|
62
|
+
LocalEventSubscriptionStateSchema,
|
|
63
|
+
LocalResultSchema,
|
|
64
|
+
LocalStreamChunkSchema,
|
|
65
|
+
LocalStreamEndSchema,
|
|
66
|
+
LocalStreamErrorSchema,
|
|
67
|
+
LocalStreamEventSchema,
|
|
68
|
+
LocalEventFrameSchema,
|
|
69
|
+
LocalEventGapSchema,
|
|
70
|
+
LocalEventErrorSchema,
|
|
71
|
+
LocalEventDeliverySchema,
|
|
72
|
+
PEER_TIMEOUT_MS,
|
|
73
|
+
PeerRequestSchema,
|
|
74
|
+
PeerObservationSchema,
|
|
75
|
+
LocalStatusSchema,
|
|
76
|
+
brokerHealthUrl2,
|
|
77
|
+
AuditStatusSchema2,
|
|
78
|
+
LaneStatusSchema2,
|
|
79
|
+
FleetConfigStateSchema2,
|
|
80
|
+
FleetEditionStatusSchema2,
|
|
81
|
+
FleetNodeStatusSchema2,
|
|
82
|
+
StatusResultSchema2,
|
|
83
|
+
BrokerHealthSchema2,
|
|
84
|
+
CallResultSchema2,
|
|
85
|
+
PublishResultSchema2,
|
|
86
|
+
PeerResultSchema2
|
|
87
|
+
} from "./chunk-d3248e3w.js";
|
|
88
|
+
|
|
89
|
+
// packages/contracts/src/service/contract-descriptor.ts
|
|
90
|
+
import { requireContractOperationEffects } from "stitchkit/contract";
|
|
91
|
+
function serviceDescriptorFromContract(contract, config) {
|
|
92
|
+
const endpointNames = Object.keys(contract.endpoints);
|
|
93
|
+
const effects = requireContractOperationEffects(contract);
|
|
94
|
+
for (const name of Object.keys(config.responseBytes ?? {}))
|
|
95
|
+
if (!Object.hasOwn(contract.endpoints, name))
|
|
96
|
+
throw new TypeError(`Unknown responseBytes endpoint '${name}'`);
|
|
97
|
+
const prefix = contract.meta.prefix.replace(/^\/+|\/+$/g, "");
|
|
98
|
+
return ServiceDescriptorSchema2.parse({
|
|
99
|
+
service: config.service,
|
|
100
|
+
revision: config.revision,
|
|
101
|
+
maxInflight: config.maxInflight,
|
|
102
|
+
operations: endpointNames.map((id) => {
|
|
103
|
+
const endpoint = contract.endpoints[id];
|
|
104
|
+
if (!endpoint)
|
|
105
|
+
throw new TypeError(`Missing Stitchkit endpoint '${id}'`);
|
|
106
|
+
const path = endpoint.path.replace(/^\/+|\/+$/g, "");
|
|
107
|
+
const exposedOnHttp = endpoint.expose === undefined || endpoint.expose.includes("HTTP");
|
|
108
|
+
if (endpoint.method !== "POST" || !exposedOnHttp || endpoint.params !== undefined || endpoint.multipart !== undefined || endpoint.rawResponse === true || endpoint.rawBody === true || endpoint.responseMeta !== undefined || endpoint.path.includes(":") || endpoint.path.includes("*")) {
|
|
109
|
+
throw new TypeError(`Wire service endpoint '${id}' must be an HTTP POST with a static JSON route and response`);
|
|
110
|
+
}
|
|
111
|
+
const stream = "stream" in endpoint ? endpoint.stream : undefined;
|
|
112
|
+
return {
|
|
113
|
+
id,
|
|
114
|
+
path: `/${[prefix, path].filter(Boolean).join("/")}`,
|
|
115
|
+
effect: effects[id],
|
|
116
|
+
limits: {
|
|
117
|
+
requestBytes: endpoint.maxJsonBodyBytes ?? SERVICE_DEFAULT_REQUEST_BYTES2,
|
|
118
|
+
responseBytes: config.responseBytes?.[id] ?? 262144,
|
|
119
|
+
timeoutMs: endpoint.timeout ?? SERVICE_MAX_TIMEOUT_MS2
|
|
120
|
+
},
|
|
121
|
+
response: stream === undefined ? { kind: "unary" } : {
|
|
122
|
+
kind: "stream",
|
|
123
|
+
...stream.lifetimeMs === undefined ? {} : { lifetimeMs: stream.lifetimeMs },
|
|
124
|
+
...stream.idleTimeoutSeconds === undefined ? {} : { idleTimeoutMs: stream.idleTimeoutSeconds * 1000 }
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
})
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
// packages/local-client/src/broker-health.ts
|
|
131
|
+
import { z as z3 } from "zod";
|
|
132
|
+
|
|
133
|
+
// packages/local-client/src/errors.ts
|
|
134
|
+
import { UnixClientTransportError } from "stitchkit/server";
|
|
135
|
+
import { ApiError, StreamTruncatedLineError } from "stitchkit";
|
|
136
|
+
|
|
137
|
+
// packages/local-client/src/errno.ts
|
|
138
|
+
function errnoOf(error) {
|
|
139
|
+
if (typeof error !== "object" || error === null || !("code" in error))
|
|
140
|
+
return;
|
|
141
|
+
return typeof error.code === "string" ? error.code : undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// packages/local-client/src/errors.ts
|
|
145
|
+
class WireClientError extends Error {
|
|
146
|
+
code;
|
|
147
|
+
delivery;
|
|
148
|
+
metadata;
|
|
149
|
+
constructor(code, message, delivery, metadata = {}) {
|
|
150
|
+
super(message, { cause: metadata.cause });
|
|
151
|
+
this.code = code;
|
|
152
|
+
this.delivery = delivery;
|
|
153
|
+
this.metadata = metadata;
|
|
154
|
+
this.name = "WireClientError";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function localError(error, delivery) {
|
|
158
|
+
if (error instanceof WireClientError)
|
|
159
|
+
return error;
|
|
160
|
+
if (error instanceof ApiError) {
|
|
161
|
+
if (error.cause instanceof WireClientError)
|
|
162
|
+
return error.cause;
|
|
163
|
+
const code = error.code === "STREAM_TERMINAL_MISSING" || error.code === "STREAM_TRUNCATED" ? "unexpected-eof" : error.code === "REQUEST_TIMEOUT" ? "timeout" : error.code === "REQUEST_ABORTED" ? "cancelled" : "invalid-response";
|
|
164
|
+
return new WireClientError(code, "Wire stream failed", delivery, { cause: error });
|
|
165
|
+
}
|
|
166
|
+
if (error instanceof RangeError)
|
|
167
|
+
return new WireClientError("limit", "Wire frame exceeds byte limit", delivery, { cause: error });
|
|
168
|
+
if (error instanceof SyntaxError || error instanceof TypeError) {
|
|
169
|
+
const code = error instanceof StreamTruncatedLineError ? "unexpected-eof" : "invalid-response";
|
|
170
|
+
return new WireClientError(code, "Invalid Wire stream frame", delivery, { cause: error });
|
|
171
|
+
}
|
|
172
|
+
if (error instanceof UnixClientTransportError) {
|
|
173
|
+
if (error.code === "UNIX_TARGET_REFUSED")
|
|
174
|
+
return new WireClientError("permission", "Local Wire socket target refused", "not-sent", {
|
|
175
|
+
cause: error
|
|
176
|
+
});
|
|
177
|
+
const code = error.code === "UNIX_CONNECT_FAILED" ? "unavailable" : error.code === "UNIX_CONNECTION_LIMIT" ? "capacity" : error.code === "UNIX_HEADERS_TIMEOUT" ? "timeout" : error.code === "UNIX_RESPONSE_TOO_LARGE" || error.code === "UNIX_REQUEST_TOO_LARGE" ? "limit" : error.code === "UNIX_REDIRECT_REFUSED" ? "http" : error.code === "UNIX_HEADERS_TOO_LARGE" ? "invalid-response" : "transport";
|
|
178
|
+
return new WireClientError(code, "Local Wire transport failed", error.delivery === "not-dispatched" ? "not-sent" : "unknown", { cause: error });
|
|
179
|
+
}
|
|
180
|
+
const code = errnoOf(error);
|
|
181
|
+
if (code === "ENOENT" || code === "ECONNREFUSED" || code === "FailedToOpenSocket") {
|
|
182
|
+
return new WireClientError("unavailable", "Local Wire agent is unavailable", "not-sent", {
|
|
183
|
+
cause: error
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
187
|
+
return new WireClientError("permission", "Local Wire socket access denied", "not-sent", { cause: error });
|
|
188
|
+
}
|
|
189
|
+
return new WireClientError("transport", "Local Wire connection failed", delivery, { cause: error });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// packages/local-client/src/http.ts
|
|
193
|
+
import { readBoundedBody } from "stitchkit/http";
|
|
194
|
+
|
|
195
|
+
// packages/contracts/src/door/paths.ts
|
|
196
|
+
function doorPath(contract, endpoint) {
|
|
197
|
+
const prefix = contract.meta.prefix.replace(/^\/+|\/+$/g, "");
|
|
198
|
+
const definition = contract.endpoints[endpoint];
|
|
199
|
+
if (definition === undefined)
|
|
200
|
+
throw new Error(`unknown door endpoint: ${endpoint}`);
|
|
201
|
+
const path = definition.path;
|
|
202
|
+
return prefix === "" ? path : `/${prefix}${path}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// packages/contracts/src/door/local-contract.ts
|
|
206
|
+
import { defineContract } from "stitchkit";
|
|
207
|
+
|
|
208
|
+
// packages/contracts/src/door/request-bounds.ts
|
|
209
|
+
var LOCAL_CALL_ENVELOPE_BYTES = jsonEnvelopeBytes(MAX_STDIN_BYTES + MAX_ARG_BYTES);
|
|
210
|
+
var LOCAL_STREAM_ENVELOPE_BYTES = Math.max(LOCAL_CALL_ENVELOPE_BYTES, SERVICE_MAX_REQUEST_ENVELOPE_BYTES);
|
|
211
|
+
var LOCAL_PUBLISH_ENVELOPE_BYTES = jsonEnvelopeBytes(MAX_EVENT_BYTES);
|
|
212
|
+
var LOCAL_SUBSCRIBE_ENVELOPE_BYTES = jsonEnvelopeBytes(0);
|
|
213
|
+
|
|
214
|
+
// packages/contracts/src/door/requests.ts
|
|
215
|
+
import { z } from "zod";
|
|
216
|
+
var LocalCallSchema = z.object({
|
|
217
|
+
to: NodeIdSchema,
|
|
218
|
+
argv: z.array(z.string().min(1).max(MAX_ARG_BYTES)).min(1).max(MAX_ARG_COUNT),
|
|
219
|
+
stdin: z.string().max(MAX_STDIN_BYTES).nullable().default(null),
|
|
220
|
+
timeoutMs: z.number().int().min(1000).max(MAX_COMMAND_TIMEOUT_MS).optional()
|
|
221
|
+
}).strict().superRefine((call, ctx) => addInputBoundIssues(ctx, { name: "argv", values: call.argv, stdin: call.stdin }));
|
|
222
|
+
var LocalProfileStreamRequestSchema = z.strictObject({
|
|
223
|
+
to: NodeIdSchema,
|
|
224
|
+
profile: StreamProfileNameSchema,
|
|
225
|
+
args: z.array(z.string().min(1).max(MAX_ARG_BYTES)).max(MAX_ARG_COUNT).default([]),
|
|
226
|
+
stdin: z.string().max(MAX_STDIN_BYTES).nullable().default(null),
|
|
227
|
+
cursor: z.string().min(1).max(512).nullable().default(null),
|
|
228
|
+
timeoutMs: z.number().int().min(1000).max(MAX_STREAM_TIMEOUT_MS).optional()
|
|
229
|
+
}).superRefine((request, ctx) => addInputBoundIssues(ctx, { name: "args", values: request.args, stdin: request.stdin }));
|
|
230
|
+
var LocalServiceStreamRequestSchema = z.strictObject({
|
|
231
|
+
to: NodeIdSchema,
|
|
232
|
+
source: z.strictObject({
|
|
233
|
+
kind: z.literal("service"),
|
|
234
|
+
service: ServiceIdSchema,
|
|
235
|
+
revision: ServiceRevisionSchema,
|
|
236
|
+
operation: ServiceOperationIdSchema,
|
|
237
|
+
payload: ServiceRequestPayloadSchema
|
|
238
|
+
}),
|
|
239
|
+
timeoutMs: z.number().int().min(1).max(MAX_STREAM_TIMEOUT_MS).optional()
|
|
240
|
+
});
|
|
241
|
+
var LocalStreamRequestSchema = z.union([
|
|
242
|
+
LocalProfileStreamRequestSchema,
|
|
243
|
+
LocalServiceStreamRequestSchema
|
|
244
|
+
]);
|
|
245
|
+
var LocalEventPublishSchema = z.object({
|
|
246
|
+
topic: TopicNameSchema,
|
|
247
|
+
bootId: z.uuid(),
|
|
248
|
+
seq: z.number().int().min(0),
|
|
249
|
+
observedAt: z.iso.datetime().nullable().default(null),
|
|
250
|
+
cursor: z.string().min(1).max(512).nullable().default(null),
|
|
251
|
+
data: z.string().min(1).max(MAX_EVENT_BYTES)
|
|
252
|
+
}).strict().superRefine((event, ctx) => {
|
|
253
|
+
if (Buffer.byteLength(event.data) > MAX_EVENT_BYTES) {
|
|
254
|
+
ctx.addIssue({ code: "custom", path: ["data"], message: `event exceeds ${MAX_EVENT_BYTES} bytes` });
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
var LocalEventSubscribeSchema = z.object({
|
|
258
|
+
topic: TopicNameSchema,
|
|
259
|
+
resume: z.object({ bootId: z.uuid(), afterSeq: z.number().int().min(0) }).strict().nullable().default(null),
|
|
260
|
+
lifecycle: z.boolean().optional()
|
|
261
|
+
}).strict();
|
|
262
|
+
|
|
263
|
+
// packages/contracts/src/door/local-contract.ts
|
|
264
|
+
var localContract = defineContract({ prefix: "wire" }, {
|
|
265
|
+
peerObservation: {
|
|
266
|
+
method: "POST",
|
|
267
|
+
path: "/peer-observation",
|
|
268
|
+
desc: "Bounded native caller-to-peer RTT on a declared broker route",
|
|
269
|
+
input: PeerRequestSchema,
|
|
270
|
+
output: PeerObservationSchema
|
|
271
|
+
},
|
|
272
|
+
call: {
|
|
273
|
+
method: "POST",
|
|
274
|
+
path: "/call",
|
|
275
|
+
desc: "Run an allowed command on another node and return its result",
|
|
276
|
+
input: LocalCallSchema,
|
|
277
|
+
maxJsonBodyBytes: LOCAL_CALL_ENVELOPE_BYTES,
|
|
278
|
+
output: LocalResultSchema
|
|
279
|
+
},
|
|
280
|
+
status: {
|
|
281
|
+
method: "GET",
|
|
282
|
+
path: "/status",
|
|
283
|
+
desc: "This agent’s link to the broker and the roster it can see",
|
|
284
|
+
output: LocalStatusSchema
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
// packages/contracts/src/service/service-contract.ts
|
|
289
|
+
import { defineContract as defineContract2 } from "stitchkit";
|
|
290
|
+
var serviceContract = defineContract2({ prefix: "wire" }, {
|
|
291
|
+
invokeService: {
|
|
292
|
+
method: "POST",
|
|
293
|
+
path: "/services/invoke",
|
|
294
|
+
desc: "Invoke an explicitly granted owner operation",
|
|
295
|
+
input: ServiceCallSchema,
|
|
296
|
+
output: LocalServiceResultSchema,
|
|
297
|
+
maxJsonBodyBytes: SERVICE_MAX_REQUEST_ENVELOPE_BYTES
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
// packages/contracts/src/door/streams.ts
|
|
302
|
+
import { defineContract as defineContract3 } from "stitchkit";
|
|
303
|
+
import { z as z2 } from "zod";
|
|
304
|
+
function itemStream(item, terminal, maxFrameBytes = DOOR_MAX_FRAME_BYTES) {
|
|
305
|
+
return {
|
|
306
|
+
item,
|
|
307
|
+
terminal,
|
|
308
|
+
format: "ndjson",
|
|
309
|
+
framing: "item",
|
|
310
|
+
completion: "terminal",
|
|
311
|
+
finalLine: "require-newline",
|
|
312
|
+
maxFrameBytes
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
var streamDoorContract = defineContract3({ prefix: "wire" }, {
|
|
316
|
+
stream: {
|
|
317
|
+
method: "POST",
|
|
318
|
+
path: "/stream",
|
|
319
|
+
desc: "Bounded command stream",
|
|
320
|
+
input: LocalStreamRequestSchema,
|
|
321
|
+
maxJsonBodyBytes: LOCAL_STREAM_ENVELOPE_BYTES,
|
|
322
|
+
stream: itemStream(LocalStreamEventSchema, z2.union([LocalStreamEndSchema, LocalStreamErrorSchema]))
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
var eventDoorContract = defineContract3({ prefix: "wire/events" }, {
|
|
326
|
+
publish: {
|
|
327
|
+
method: "POST",
|
|
328
|
+
path: "/publish",
|
|
329
|
+
desc: "Publish one bounded event on a declared topic",
|
|
330
|
+
input: LocalEventPublishSchema,
|
|
331
|
+
output: EventAckSchema,
|
|
332
|
+
maxJsonBodyBytes: LOCAL_PUBLISH_ENVELOPE_BYTES
|
|
333
|
+
},
|
|
334
|
+
subscribe: {
|
|
335
|
+
method: "POST",
|
|
336
|
+
path: "/subscribe",
|
|
337
|
+
desc: "Quiet live events with explicit gaps",
|
|
338
|
+
input: LocalEventSubscribeSchema,
|
|
339
|
+
maxJsonBodyBytes: LOCAL_SUBSCRIBE_ENVELOPE_BYTES,
|
|
340
|
+
stream: itemStream(LocalEventDeliverySchema, LocalEventErrorSchema)
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// packages/local-client/src/door-paths.ts
|
|
345
|
+
var DOOR = {
|
|
346
|
+
call: doorPath(localContract, "call"),
|
|
347
|
+
status: doorPath(localContract, "status"),
|
|
348
|
+
peerObservation: doorPath(localContract, "peerObservation"),
|
|
349
|
+
stream: doorPath(streamDoorContract, "stream"),
|
|
350
|
+
publish: doorPath(eventDoorContract, "publish"),
|
|
351
|
+
subscribe: doorPath(eventDoorContract, "subscribe"),
|
|
352
|
+
invokeService: doorPath(serviceContract, "invokeService")
|
|
353
|
+
};
|
|
354
|
+
var STREAMING_DOOR_PATHS = [DOOR.stream, DOOR.subscribe];
|
|
355
|
+
|
|
356
|
+
// packages/local-client/src/http.ts
|
|
357
|
+
function declaredLengthExceeds(headers, maxBytes) {
|
|
358
|
+
const declared = headers.get("content-length");
|
|
359
|
+
return declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes;
|
|
360
|
+
}
|
|
361
|
+
function openDoor(session, operation, path, body, signal, traceId) {
|
|
362
|
+
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
363
|
+
if (payload !== undefined && Buffer.byteLength(payload) > DOOR_MAX_REQUEST_BYTES)
|
|
364
|
+
throw new WireClientError("limit", "Encoded Wire request exceeds byte limit", "not-sent");
|
|
365
|
+
if (operation.controller.signal.aborted)
|
|
366
|
+
throw operation.error(undefined);
|
|
367
|
+
operation.sent = true;
|
|
368
|
+
return session.fetch(`http://wire.invalid${path}`, {
|
|
369
|
+
method: body === undefined ? "GET" : "POST",
|
|
370
|
+
body: payload,
|
|
371
|
+
headers: {
|
|
372
|
+
accept: "application/json, application/x-ndjson",
|
|
373
|
+
...traceId === undefined ? {} : { [SERVICE_TRACE_HEADER]: traceId },
|
|
374
|
+
...payload === undefined ? {} : { "content-type": "application/json" }
|
|
375
|
+
},
|
|
376
|
+
redirect: "error",
|
|
377
|
+
signal: signal ?? operation.controller.signal
|
|
378
|
+
}, STREAMING_DOOR_PATHS.includes(path));
|
|
379
|
+
}
|
|
380
|
+
function checkResponse(response, expected) {
|
|
381
|
+
const status = response.status;
|
|
382
|
+
if (status < 200 || status >= 300)
|
|
383
|
+
throw new WireClientError(status === 404 ? "unsupported" : "http", "Local Wire HTTP request failed", "unknown", { status });
|
|
384
|
+
if (response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== (expected === "json" ? "application/json" : "application/x-ndjson"))
|
|
385
|
+
throw new WireClientError("invalid-response", "Unexpected Wire response content type", "unknown");
|
|
386
|
+
}
|
|
387
|
+
var strictUtf8 = new TextDecoder("utf-8", { fatal: true });
|
|
388
|
+
async function readJson(response, limit, options = {}) {
|
|
389
|
+
const label = options.label ?? "Wire response";
|
|
390
|
+
const limitError = () => new WireClientError("limit", `${label} exceeds byte limit`, "unknown");
|
|
391
|
+
if (declaredLengthExceeds(response.headers, limit))
|
|
392
|
+
throw limitError();
|
|
393
|
+
const bytes = await readBoundedBody(response.body, {
|
|
394
|
+
maxBytes: limit,
|
|
395
|
+
signal: options.signal,
|
|
396
|
+
limitError,
|
|
397
|
+
abortError: options.abortError
|
|
398
|
+
});
|
|
399
|
+
try {
|
|
400
|
+
return JSON.parse(strictUtf8.decode(bytes));
|
|
401
|
+
} catch (cause) {
|
|
402
|
+
throw new WireClientError("invalid-response", `${label} is not valid UTF-8 JSON`, "unknown", { cause });
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// packages/local-client/src/broker-health.ts
|
|
407
|
+
var DEFAULT_BROKER_HEALTH_TIMEOUT_MS = 8000;
|
|
408
|
+
var DEFAULT_BROKER_HEALTH_MAX_BYTES = 8 * 1024 * 1024;
|
|
409
|
+
var ReadBrokerHealthOptionsSchema = z3.object({
|
|
410
|
+
timeoutMs: z3.number().int().min(500).max(60000).default(DEFAULT_BROKER_HEALTH_TIMEOUT_MS),
|
|
411
|
+
maxResponseBytes: z3.number().int().min(1).max(DEFAULT_BROKER_HEALTH_MAX_BYTES).default(DEFAULT_BROKER_HEALTH_MAX_BYTES)
|
|
412
|
+
}).strict();
|
|
413
|
+
var UNAVAILABLE_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH"]);
|
|
414
|
+
function isUnavailableNetworkError(error) {
|
|
415
|
+
const seen = new Set;
|
|
416
|
+
const queue = [error];
|
|
417
|
+
while (queue.length > 0 && seen.size < 32) {
|
|
418
|
+
const current = queue.shift();
|
|
419
|
+
if (typeof current !== "object" || current === null || seen.has(current))
|
|
420
|
+
continue;
|
|
421
|
+
seen.add(current);
|
|
422
|
+
try {
|
|
423
|
+
const code = errnoOf(current);
|
|
424
|
+
if (code !== undefined && UNAVAILABLE_CODES.has(code))
|
|
425
|
+
return true;
|
|
426
|
+
const cause = Reflect.get(current, "cause");
|
|
427
|
+
if (cause !== undefined)
|
|
428
|
+
queue.push(cause);
|
|
429
|
+
if (current instanceof AggregateError && Array.isArray(current.errors)) {
|
|
430
|
+
for (const inner of current.errors)
|
|
431
|
+
queue.push(inner);
|
|
432
|
+
}
|
|
433
|
+
} catch {}
|
|
434
|
+
}
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
async function readBrokerHealth(laneUrl, options = {}) {
|
|
438
|
+
const parsedOptions = ReadBrokerHealthOptionsSchema.safeParse({
|
|
439
|
+
...options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },
|
|
440
|
+
...options.maxResponseBytes === undefined ? {} : { maxResponseBytes: options.maxResponseBytes }
|
|
441
|
+
});
|
|
442
|
+
if (!parsedOptions.success) {
|
|
443
|
+
throw new WireClientError("invalid-request", "Invalid readBrokerHealth options", "not-sent", {
|
|
444
|
+
cause: parsedOptions.error
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
let url;
|
|
448
|
+
try {
|
|
449
|
+
url = brokerHealthUrl2(laneUrl);
|
|
450
|
+
} catch (cause) {
|
|
451
|
+
throw new WireClientError("invalid-request", "Invalid broker lane URL", "not-sent", { cause });
|
|
452
|
+
}
|
|
453
|
+
const { timeoutMs, maxResponseBytes } = parsedOptions.data;
|
|
454
|
+
if (options.signal?.aborted) {
|
|
455
|
+
throw new WireClientError("cancelled", "Broker health request cancelled", "not-sent", {
|
|
456
|
+
cause: options.signal.reason
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
460
|
+
const signal = options.signal === undefined ? timeoutSignal : AbortSignal.any([options.signal, timeoutSignal]);
|
|
461
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
462
|
+
let response;
|
|
463
|
+
try {
|
|
464
|
+
response = await fetchFn(url, {
|
|
465
|
+
method: "GET",
|
|
466
|
+
headers: { accept: "application/json" },
|
|
467
|
+
redirect: "error",
|
|
468
|
+
signal
|
|
469
|
+
});
|
|
470
|
+
if (!response.ok) {
|
|
471
|
+
throw new WireClientError("http", `Broker health returned HTTP ${response.status}`, "unknown", {
|
|
472
|
+
status: response.status
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
if (response.body === null) {
|
|
476
|
+
throw new WireClientError("invalid-response", "Broker health response has no body", "unknown");
|
|
477
|
+
}
|
|
478
|
+
const payload = await readJson(response, maxResponseBytes, {
|
|
479
|
+
label: "Broker health response",
|
|
480
|
+
signal,
|
|
481
|
+
abortError: () => options.signal?.aborted ? new WireClientError("cancelled", "Broker health request cancelled", "unknown", {
|
|
482
|
+
cause: options.signal.reason
|
|
483
|
+
}) : new WireClientError("timeout", "Broker health request timed out", "unknown", {
|
|
484
|
+
cause: timeoutSignal.reason
|
|
485
|
+
})
|
|
486
|
+
});
|
|
487
|
+
const validated = BrokerHealthSchema2.safeParse(payload);
|
|
488
|
+
if (!validated.success) {
|
|
489
|
+
throw new WireClientError("invalid-response", "Broker health payload failed schema validation", "unknown", { cause: validated.error });
|
|
490
|
+
}
|
|
491
|
+
return validated.data;
|
|
492
|
+
} catch (error) {
|
|
493
|
+
if (error instanceof WireClientError)
|
|
494
|
+
throw error;
|
|
495
|
+
if (options.signal?.aborted) {
|
|
496
|
+
throw new WireClientError("cancelled", "Broker health request cancelled", "unknown", {
|
|
497
|
+
cause: error
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
if (timeoutSignal.aborted || error instanceof Error && error.name === "TimeoutError") {
|
|
501
|
+
throw new WireClientError("timeout", "Broker health request timed out", "unknown", {
|
|
502
|
+
cause: error
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
if (isUnavailableNetworkError(error)) {
|
|
506
|
+
throw new WireClientError("unavailable", "Broker health endpoint is unavailable", "not-sent", {
|
|
507
|
+
cause: error
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
throw new WireClientError("transport", "Broker health request failed", "unknown", { cause: error });
|
|
511
|
+
} finally {
|
|
512
|
+
if (response?.body && !response.body.locked) {
|
|
513
|
+
await response.body.cancel().catch(() => {
|
|
514
|
+
return;
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
// packages/local-client/src/client.ts
|
|
520
|
+
import { z as z7 } from "zod";
|
|
521
|
+
|
|
522
|
+
// packages/local-client/src/event-sequence.ts
|
|
523
|
+
function eventSequence(topic, resume) {
|
|
524
|
+
let subscriptionId;
|
|
525
|
+
let producer;
|
|
526
|
+
let bootId = resume?.bootId;
|
|
527
|
+
let successor;
|
|
528
|
+
let nextSeq = resume ? resume.afterSeq + 1 : undefined;
|
|
529
|
+
let initial = true;
|
|
530
|
+
const invalid = () => {
|
|
531
|
+
throw new WireClientError("invalid-response", "Inconsistent Wire event sequence or identity", "unknown");
|
|
532
|
+
};
|
|
533
|
+
return (item) => {
|
|
534
|
+
const frame = item.frame;
|
|
535
|
+
if (frame.topic !== topic)
|
|
536
|
+
invalid();
|
|
537
|
+
if (frame.subscriptionId === null) {
|
|
538
|
+
if (!initial)
|
|
539
|
+
invalid();
|
|
540
|
+
} else {
|
|
541
|
+
subscriptionId ??= frame.subscriptionId;
|
|
542
|
+
if (subscriptionId !== frame.subscriptionId)
|
|
543
|
+
invalid();
|
|
544
|
+
}
|
|
545
|
+
if (item.kind === "error")
|
|
546
|
+
return item;
|
|
547
|
+
if (item.kind === "subscription") {
|
|
548
|
+
initial = false;
|
|
549
|
+
return item;
|
|
550
|
+
}
|
|
551
|
+
const value = item.frame;
|
|
552
|
+
producer ??= value.producer;
|
|
553
|
+
if (producer !== value.producer)
|
|
554
|
+
invalid();
|
|
555
|
+
bootId ??= value.bootId;
|
|
556
|
+
if (bootId !== value.bootId) {
|
|
557
|
+
if (value.bootId !== successor)
|
|
558
|
+
invalid();
|
|
559
|
+
bootId = successor;
|
|
560
|
+
successor = undefined;
|
|
561
|
+
nextSeq = undefined;
|
|
562
|
+
}
|
|
563
|
+
if (item.kind === "event") {
|
|
564
|
+
if (nextSeq !== undefined && item.frame.seq !== nextSeq)
|
|
565
|
+
invalid();
|
|
566
|
+
nextSeq = item.frame.seq + 1;
|
|
567
|
+
} else if (item.frame.reason === "boot-change") {
|
|
568
|
+
if (successor !== undefined)
|
|
569
|
+
invalid();
|
|
570
|
+
successor = item.frame.nextBootId;
|
|
571
|
+
} else if (item.frame.reason === "resume" && nextSeq !== undefined && item.frame.toSeq < nextSeq) {} else {
|
|
572
|
+
if (nextSeq !== undefined && item.frame.fromSeq !== nextSeq)
|
|
573
|
+
invalid();
|
|
574
|
+
nextSeq = item.frame.toSeq + 1;
|
|
575
|
+
}
|
|
576
|
+
initial = false;
|
|
577
|
+
return item;
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// packages/local-client/src/feed.ts
|
|
582
|
+
import { createClient, defineContract as defineContract4 } from "stitchkit";
|
|
583
|
+
import { z as z4 } from "zod";
|
|
584
|
+
function createFeed(session, path, body, parse, terminal, signal, durationMs, confirmsOpen) {
|
|
585
|
+
let operation;
|
|
586
|
+
let closed = false;
|
|
587
|
+
let pending = false;
|
|
588
|
+
const close = () => {
|
|
589
|
+
closed = true;
|
|
590
|
+
operation?.abort("cancelled");
|
|
591
|
+
operation?.finish();
|
|
592
|
+
};
|
|
593
|
+
const source = async function* () {
|
|
594
|
+
if (closed)
|
|
595
|
+
return;
|
|
596
|
+
operation = session.begin(signal);
|
|
597
|
+
operation.deadline(session.options.openTimeoutMs);
|
|
598
|
+
const current = operation;
|
|
599
|
+
try {
|
|
600
|
+
const contract = defineContract4({ prefix: path }, {
|
|
601
|
+
read: {
|
|
602
|
+
method: "POST",
|
|
603
|
+
path: "",
|
|
604
|
+
desc: "Wire local feed",
|
|
605
|
+
stream: itemStream(z4.unknown().transform((value) => {
|
|
606
|
+
const item = parse(value);
|
|
607
|
+
if (confirmsOpen?.(item))
|
|
608
|
+
current.clearDeadline();
|
|
609
|
+
return item;
|
|
610
|
+
}), terminal, session.options.maxFrameBytes)
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
const client = createClient(contract, {
|
|
614
|
+
baseUrl: "http://wire.invalid",
|
|
615
|
+
timeout: session.options.openTimeoutMs,
|
|
616
|
+
fetch: async (_url, init) => {
|
|
617
|
+
init?.signal?.addEventListener("abort", () => current.finish(), { once: true });
|
|
618
|
+
const response = await openDoor(session, current, path, body, init?.signal ?? undefined);
|
|
619
|
+
if (confirmsOpen === undefined)
|
|
620
|
+
current.clearDeadline();
|
|
621
|
+
if (durationMs !== undefined)
|
|
622
|
+
current.deadline(durationMs);
|
|
623
|
+
checkResponse(response, "ndjson");
|
|
624
|
+
return response;
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
yield* await client.read.withOptions({ signal: current.controller.signal });
|
|
628
|
+
} catch (error) {
|
|
629
|
+
throw operation.error(error);
|
|
630
|
+
} finally {
|
|
631
|
+
operation.controller.abort();
|
|
632
|
+
operation.finish();
|
|
633
|
+
}
|
|
634
|
+
}();
|
|
635
|
+
const feed = {
|
|
636
|
+
[Symbol.asyncIterator]() {
|
|
637
|
+
return this;
|
|
638
|
+
},
|
|
639
|
+
async next() {
|
|
640
|
+
if (pending)
|
|
641
|
+
throw new WireClientError("capacity", "Concurrent feed reads are not supported", "not-sent");
|
|
642
|
+
if (closed)
|
|
643
|
+
return { done: true, value: undefined };
|
|
644
|
+
pending = true;
|
|
645
|
+
try {
|
|
646
|
+
return await source.next();
|
|
647
|
+
} finally {
|
|
648
|
+
pending = false;
|
|
649
|
+
}
|
|
650
|
+
},
|
|
651
|
+
async return() {
|
|
652
|
+
close();
|
|
653
|
+
return await source.return(undefined);
|
|
654
|
+
},
|
|
655
|
+
close
|
|
656
|
+
};
|
|
657
|
+
return feed;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// packages/local-client/src/operation.ts
|
|
661
|
+
import { createBoundedAdmission } from "stitchkit/application";
|
|
662
|
+
import { createUnixClientTransport } from "stitchkit/server";
|
|
663
|
+
|
|
664
|
+
// packages/local-client/src/options.ts
|
|
665
|
+
import { isAbsolute } from "node:path";
|
|
666
|
+
import { z as z5 } from "zod";
|
|
667
|
+
var COMMAND_RESULT_GRACE_MS = 1e4;
|
|
668
|
+
var STREAM_TERMINAL_GRACE_MS = 1e4;
|
|
669
|
+
var ClientOptionsSchema = z5.object({
|
|
670
|
+
socketPath: z5.string().min(1).refine((p) => isAbsolute(p) && !p.includes("\x00"), "absolute Unix socket path required"),
|
|
671
|
+
timeoutMs: z5.number().int().min(1000).max(MAX_STREAM_TIMEOUT_MS).default(30000),
|
|
672
|
+
openTimeoutMs: z5.number().int().min(1).max(60000).default(1e4),
|
|
673
|
+
maxConcurrentRequests: z5.number().int().min(1).max(256).default(32),
|
|
674
|
+
maxResponseBytes: z5.number().int().min(1).max(DOOR_MAX_RESPONSE_BYTES).default(DOOR_MAX_RESPONSE_BYTES),
|
|
675
|
+
maxFrameBytes: z5.number().int().min(1).max(DOOR_MAX_FRAME_BYTES).default(DOOR_MAX_FRAME_BYTES)
|
|
676
|
+
}).strict();
|
|
677
|
+
function requestInput(schema, input) {
|
|
678
|
+
const result = schema.safeParse(input);
|
|
679
|
+
if (!result.success)
|
|
680
|
+
throw new WireClientError("invalid-request", "Invalid Wire client request", "not-sent", {
|
|
681
|
+
cause: result.error
|
|
682
|
+
});
|
|
683
|
+
return result.data;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// packages/local-client/src/operation.ts
|
|
687
|
+
var UNARY_HEADERS_TIMEOUT_MS = MAX_COMMAND_TIMEOUT_MS + COMMAND_RESULT_GRACE_MS + 5000;
|
|
688
|
+
|
|
689
|
+
class Operation {
|
|
690
|
+
release;
|
|
691
|
+
controller = new AbortController;
|
|
692
|
+
timer;
|
|
693
|
+
external;
|
|
694
|
+
externalAbort = () => this.abort("cancelled");
|
|
695
|
+
finished = false;
|
|
696
|
+
sent = false;
|
|
697
|
+
constructor(release) {
|
|
698
|
+
this.release = release;
|
|
699
|
+
}
|
|
700
|
+
listen(signal) {
|
|
701
|
+
this.external = signal;
|
|
702
|
+
if (signal?.aborted)
|
|
703
|
+
this.abort("cancelled");
|
|
704
|
+
else
|
|
705
|
+
signal?.addEventListener("abort", this.externalAbort, { once: true });
|
|
706
|
+
}
|
|
707
|
+
deadline(ms) {
|
|
708
|
+
this.clearDeadline();
|
|
709
|
+
this.timer = setTimeout(() => this.abort("timeout"), ms);
|
|
710
|
+
this.timer.unref();
|
|
711
|
+
}
|
|
712
|
+
clearDeadline() {
|
|
713
|
+
clearTimeout(this.timer);
|
|
714
|
+
this.timer = undefined;
|
|
715
|
+
}
|
|
716
|
+
abort(code) {
|
|
717
|
+
this.controller.abort(new WireClientError(code, `Wire operation ${code}`, this.sent ? "unknown" : "not-sent", {
|
|
718
|
+
...code === "timeout" ? { cancellationOrigin: "caller-deadline" } : code === "cancelled" ? { cancellationOrigin: "caller-abort" } : {}
|
|
719
|
+
}));
|
|
720
|
+
this.finish();
|
|
721
|
+
}
|
|
722
|
+
error(error) {
|
|
723
|
+
const reason = this.controller.signal.reason;
|
|
724
|
+
return reason instanceof WireClientError ? reason : localError(error, this.sent ? "unknown" : "not-sent");
|
|
725
|
+
}
|
|
726
|
+
finish() {
|
|
727
|
+
if (this.finished)
|
|
728
|
+
return;
|
|
729
|
+
this.finished = true;
|
|
730
|
+
this.clearDeadline();
|
|
731
|
+
this.external?.removeEventListener("abort", this.externalAbort);
|
|
732
|
+
this.external = undefined;
|
|
733
|
+
this.release();
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
class ClientSession {
|
|
738
|
+
options;
|
|
739
|
+
transport;
|
|
740
|
+
streaming;
|
|
741
|
+
admission;
|
|
742
|
+
closed = false;
|
|
743
|
+
active = new Set;
|
|
744
|
+
constructor(options) {
|
|
745
|
+
this.options = options;
|
|
746
|
+
this.admission = createBoundedAdmission({
|
|
747
|
+
policy: { global: { maxConcurrent: options.maxConcurrentRequests } }
|
|
748
|
+
});
|
|
749
|
+
const config = {
|
|
750
|
+
socketPath: options.socketPath,
|
|
751
|
+
maxConnections: options.maxConcurrentRequests,
|
|
752
|
+
maxRequestBytes: DOOR_MAX_REQUEST_BYTES,
|
|
753
|
+
maxHeaderBytes: 65536,
|
|
754
|
+
maxRedirects: 0
|
|
755
|
+
};
|
|
756
|
+
this.transport = createUnixClientTransport({
|
|
757
|
+
...config,
|
|
758
|
+
headersTimeoutMs: UNARY_HEADERS_TIMEOUT_MS,
|
|
759
|
+
maxResponseBytes: options.maxResponseBytes
|
|
760
|
+
});
|
|
761
|
+
this.streaming = createUnixClientTransport({
|
|
762
|
+
...config,
|
|
763
|
+
headersTimeoutMs: options.openTimeoutMs,
|
|
764
|
+
responseBodyMode: "streaming"
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
begin(signal) {
|
|
768
|
+
if (this.closed)
|
|
769
|
+
throw new WireClientError("closed", "Wire client is closed", "not-sent");
|
|
770
|
+
const admitted = this.admission.acquire();
|
|
771
|
+
if (admitted.outcome === "refused")
|
|
772
|
+
throw new WireClientError("capacity", "Wire client concurrency limit reached", "not-sent");
|
|
773
|
+
const operation = new Operation(() => {
|
|
774
|
+
this.active.delete(operation);
|
|
775
|
+
admitted.lease.release();
|
|
776
|
+
});
|
|
777
|
+
this.active.add(operation);
|
|
778
|
+
operation.listen(signal);
|
|
779
|
+
return operation;
|
|
780
|
+
}
|
|
781
|
+
fetch(url, init, streaming) {
|
|
782
|
+
return (streaming ? this.streaming : this.transport).fetch(url, init);
|
|
783
|
+
}
|
|
784
|
+
close() {
|
|
785
|
+
this.closed = true;
|
|
786
|
+
this.admission.stopAdmission();
|
|
787
|
+
for (const operation of this.active) {
|
|
788
|
+
operation.abort("closed");
|
|
789
|
+
operation.finish();
|
|
790
|
+
}
|
|
791
|
+
this.transport.close();
|
|
792
|
+
this.streaming.close();
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// packages/local-client/src/readers.ts
|
|
797
|
+
import { z as z6 } from "zod";
|
|
798
|
+
var diagnosticsReader = ServiceDiagnosticsSchema.extend({
|
|
799
|
+
phases: z6.array(ServicePhaseSchema.strip()).max(16)
|
|
800
|
+
}).strip();
|
|
801
|
+
var ServiceResultReaderSchema = LocalServiceResultSchema.extend({
|
|
802
|
+
outcome: z6.discriminatedUnion("status", [
|
|
803
|
+
ServiceOutcomeSchema.options[0].extend({ diagnostics: diagnosticsReader.optional() }).strip(),
|
|
804
|
+
ServiceOutcomeSchema.options[1].strip().safeExtend({ diagnostics: diagnosticsReader.optional() })
|
|
805
|
+
])
|
|
806
|
+
}).strip();
|
|
807
|
+
var version = z6.object({ v: z6.number().int() });
|
|
808
|
+
function readResponse(schema, value, versioned = true) {
|
|
809
|
+
if (versioned) {
|
|
810
|
+
const result = version.safeParse(value);
|
|
811
|
+
if (result.success && result.data.v !== LOCAL_API_VERSION2) {
|
|
812
|
+
throw new WireClientError("version", "Unsupported local Wire door version", "unknown", {
|
|
813
|
+
actualVersion: result.data.v
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
const parsed = schema.safeParse(value);
|
|
818
|
+
if (!parsed.success)
|
|
819
|
+
throw new WireClientError("invalid-response", "Invalid Wire response envelope", "unknown", {
|
|
820
|
+
cause: parsed.error
|
|
821
|
+
});
|
|
822
|
+
return parsed.data;
|
|
823
|
+
}
|
|
824
|
+
function decodeWireData(frame) {
|
|
825
|
+
const decoded = Buffer.from(frame.data, "base64");
|
|
826
|
+
if (decoded.byteLength !== frame.bytes || decoded.toString("base64") !== frame.data) {
|
|
827
|
+
throw new WireClientError("invalid-response", "Wire payload encoding or byte count is invalid", "unknown");
|
|
828
|
+
}
|
|
829
|
+
return decoded;
|
|
830
|
+
}
|
|
831
|
+
var shape = z6.record(z6.string(), z6.unknown());
|
|
832
|
+
var chunkReader = LocalStreamChunkSchema.strip();
|
|
833
|
+
var endReader = LocalStreamEndSchema.strip();
|
|
834
|
+
var streamErrorReader = LocalStreamErrorSchema.strip().superRefine(refusalRefinement);
|
|
835
|
+
var subscriptionReader = LocalEventSubscriptionStateSchema.strip();
|
|
836
|
+
var eventReader = LocalEventFrameSchema.strip();
|
|
837
|
+
var gapReader = LocalEventGapSchema.strip();
|
|
838
|
+
var eventErrorReader = LocalEventErrorSchema.strip().superRefine(refusalRefinement);
|
|
839
|
+
function readStreamItem(value) {
|
|
840
|
+
const raw = readResponse(shape, value);
|
|
841
|
+
if ("data" in raw) {
|
|
842
|
+
const frame = readResponse(chunkReader, raw);
|
|
843
|
+
return { kind: "chunk", frame, data: decodeWireData(frame) };
|
|
844
|
+
}
|
|
845
|
+
if ("lastSeq" in raw)
|
|
846
|
+
return { kind: "end", frame: readResponse(endReader, raw) };
|
|
847
|
+
return { kind: "error", frame: readResponse(streamErrorReader, raw) };
|
|
848
|
+
}
|
|
849
|
+
function readEventItem(value) {
|
|
850
|
+
const raw = readResponse(shape, value);
|
|
851
|
+
if ("subscriptionState" in raw)
|
|
852
|
+
return { kind: "subscription", frame: readResponse(subscriptionReader, raw) };
|
|
853
|
+
if ("data" in raw) {
|
|
854
|
+
const frame = readResponse(eventReader, raw);
|
|
855
|
+
return { kind: "event", frame, data: decodeWireData(frame) };
|
|
856
|
+
}
|
|
857
|
+
if ("fromSeq" in raw) {
|
|
858
|
+
const frame = readResponse(gapReader, raw);
|
|
859
|
+
if (frame.fromSeq > frame.toSeq || (frame.reason === "boot-change" ? frame.nextBootId === undefined || frame.nextBootId === frame.bootId : frame.nextBootId !== undefined))
|
|
860
|
+
throw new WireClientError("invalid-response", "Invalid Wire gap range", "unknown");
|
|
861
|
+
return { kind: "gap", frame };
|
|
862
|
+
}
|
|
863
|
+
return { kind: "error", frame: readResponse(eventErrorReader, raw) };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// packages/local-client/src/unary.ts
|
|
867
|
+
async function unary(session, path, body, schema, options) {
|
|
868
|
+
const operation = session.begin(options.signal);
|
|
869
|
+
const startedAt = new Date().toISOString();
|
|
870
|
+
const start = performance.now();
|
|
871
|
+
let headersMs = null;
|
|
872
|
+
let phase = "dispatch";
|
|
873
|
+
operation.deadline(options.timeoutMs);
|
|
874
|
+
let response;
|
|
875
|
+
try {
|
|
876
|
+
response = await openDoor(session, operation, path, body, undefined, options.traceId);
|
|
877
|
+
headersMs = performance.now() - start;
|
|
878
|
+
phase = "headers";
|
|
879
|
+
checkResponse(response, "json");
|
|
880
|
+
phase = "body";
|
|
881
|
+
const raw = await readJson(response, Math.min(options.maxBytes ?? session.options.maxResponseBytes, session.options.maxResponseBytes));
|
|
882
|
+
return readResponse(schema, raw, options.versioned);
|
|
883
|
+
} catch (error) {
|
|
884
|
+
const failure = operation.error(error);
|
|
885
|
+
throw new WireClientError(failure.code, failure.message, failure.delivery, {
|
|
886
|
+
...failure.metadata,
|
|
887
|
+
timing: {
|
|
888
|
+
startedAt,
|
|
889
|
+
elapsedMs: performance.now() - start,
|
|
890
|
+
headersMs,
|
|
891
|
+
timeoutMs: options.timeoutMs,
|
|
892
|
+
phase,
|
|
893
|
+
callerAborted: options.signal?.aborted ?? false
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
} finally {
|
|
897
|
+
if (response?.body && !response.body.locked)
|
|
898
|
+
await response.body.cancel().catch(() => {
|
|
899
|
+
return;
|
|
900
|
+
});
|
|
901
|
+
operation.finish();
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// packages/local-client/src/client.ts
|
|
906
|
+
function createWireClient(options) {
|
|
907
|
+
const config = requestInput(ClientOptionsSchema, options);
|
|
908
|
+
const session = new ClientSession(config);
|
|
909
|
+
function subscribe(input, options = {}) {
|
|
910
|
+
const request = requestInput(LocalEventSubscribeSchema, input);
|
|
911
|
+
const sequence = eventSequence(request.topic, request.resume);
|
|
912
|
+
const lifecycle = request.lifecycle === true;
|
|
913
|
+
return createFeed(session, DOOR.subscribe, request, (value) => {
|
|
914
|
+
const item = sequence(readEventItem(value));
|
|
915
|
+
if (!lifecycle && item.kind === "subscription") {
|
|
916
|
+
throw new WireClientError("invalid-response", "Wire sent a subscription lifecycle frame to a feed that did not request one", "unknown");
|
|
917
|
+
}
|
|
918
|
+
return item;
|
|
919
|
+
}, z7.object({ kind: z7.literal("error") }), options.signal, undefined, lifecycle ? (item) => item.kind === "subscription" && item.frame.subscriptionState === "ready" : undefined);
|
|
920
|
+
}
|
|
921
|
+
return {
|
|
922
|
+
async invokeService(input, options = {}) {
|
|
923
|
+
const traceId = input.traceId ?? crypto.randomUUID();
|
|
924
|
+
options.onTrace?.({ traceId, phase: "start" });
|
|
925
|
+
try {
|
|
926
|
+
const parsed = requestInput(ServiceCallSchema, { ...input, traceId });
|
|
927
|
+
const result = await unary(session, DOOR.invokeService, parsed, ServiceResultReaderSchema, {
|
|
928
|
+
traceId,
|
|
929
|
+
timeoutMs: parsed.timeoutMs,
|
|
930
|
+
signal: options.signal,
|
|
931
|
+
versioned: true
|
|
932
|
+
});
|
|
933
|
+
options.onTrace?.({
|
|
934
|
+
traceId,
|
|
935
|
+
phase: "result",
|
|
936
|
+
diagnostics: result.outcome.diagnostics,
|
|
937
|
+
...result.outcome.status === "failure" ? { cancellationOrigin: result.outcome.cancellationOrigin } : {}
|
|
938
|
+
});
|
|
939
|
+
return { ...result, traceId };
|
|
940
|
+
} catch (error) {
|
|
941
|
+
const failure = localError(error, "not-sent");
|
|
942
|
+
const origin = failure.metadata.cancellationOrigin;
|
|
943
|
+
options.onTrace?.({
|
|
944
|
+
traceId,
|
|
945
|
+
phase: "result",
|
|
946
|
+
...origin === undefined ? {} : { cancellationOrigin: origin }
|
|
947
|
+
});
|
|
948
|
+
throw new WireClientError(failure.code, failure.message, failure.delivery, {
|
|
949
|
+
...failure.metadata,
|
|
950
|
+
traceId
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
},
|
|
954
|
+
call(input, options = {}) {
|
|
955
|
+
const parsed = requestInput(LocalCallSchema, input);
|
|
956
|
+
const request = { ...parsed, timeoutMs: parsed.timeoutMs ?? config.timeoutMs };
|
|
957
|
+
return unary(session, DOOR.call, request, CallResultSchema2, {
|
|
958
|
+
timeoutMs: request.timeoutMs + COMMAND_RESULT_GRACE_MS,
|
|
959
|
+
signal: options.signal,
|
|
960
|
+
versioned: true
|
|
961
|
+
});
|
|
962
|
+
},
|
|
963
|
+
status(options = {}) {
|
|
964
|
+
return unary(session, DOOR.status, undefined, StatusResultSchema2, {
|
|
965
|
+
timeoutMs: config.openTimeoutMs,
|
|
966
|
+
signal: options.signal,
|
|
967
|
+
versioned: true
|
|
968
|
+
});
|
|
969
|
+
},
|
|
970
|
+
peerObservation(input, options = {}) {
|
|
971
|
+
return unary(session, DOOR.peerObservation, requestInput(PeerRequestSchema, input), PeerResultSchema2, {
|
|
972
|
+
timeoutMs: PEER_TIMEOUT_MS + config.openTimeoutMs,
|
|
973
|
+
signal: options.signal,
|
|
974
|
+
versioned: true
|
|
975
|
+
});
|
|
976
|
+
},
|
|
977
|
+
publish(input, options = {}) {
|
|
978
|
+
return unary(session, DOOR.publish, requestInput(LocalEventPublishSchema, input), PublishResultSchema2, {
|
|
979
|
+
timeoutMs: config.timeoutMs,
|
|
980
|
+
signal: options.signal,
|
|
981
|
+
versioned: false,
|
|
982
|
+
maxBytes: 16 * 1024
|
|
983
|
+
});
|
|
984
|
+
},
|
|
985
|
+
stream(input, options = {}) {
|
|
986
|
+
const parsed = requestInput(LocalStreamRequestSchema, input);
|
|
987
|
+
const request = { ...parsed, timeoutMs: parsed.timeoutMs ?? config.timeoutMs };
|
|
988
|
+
let streamId;
|
|
989
|
+
let nextSeq = 0;
|
|
990
|
+
let bytes = 0;
|
|
991
|
+
return createFeed(session, DOOR.stream, request, (value) => {
|
|
992
|
+
const item = readStreamItem(value);
|
|
993
|
+
streamId ??= item.frame.streamId;
|
|
994
|
+
if (streamId !== item.frame.streamId)
|
|
995
|
+
throw new WireClientError("invalid-response", "Wire stream identity changed", "unknown");
|
|
996
|
+
if (item.kind === "chunk") {
|
|
997
|
+
if (item.frame.from !== request.to || item.frame.seq !== nextSeq++)
|
|
998
|
+
throw new WireClientError("invalid-response", "Wire stream source or sequence changed", "unknown");
|
|
999
|
+
bytes += item.data.byteLength;
|
|
1000
|
+
if (bytes > MAX_STREAM_TOTAL_BYTES)
|
|
1001
|
+
throw new WireClientError("limit", "Wire stream exceeds total byte limit", "unknown");
|
|
1002
|
+
}
|
|
1003
|
+
if (item.kind === "end" && (item.frame.from !== request.to || item.frame.lastSeq !== nextSeq - 1)) {
|
|
1004
|
+
throw new WireClientError("invalid-response", "Wire stream terminal sequence is inconsistent", "unknown");
|
|
1005
|
+
}
|
|
1006
|
+
return item;
|
|
1007
|
+
}, z7.object({ kind: z7.enum(["end", "error"]) }), options.signal, request.timeoutMs + STREAM_TERMINAL_GRACE_MS);
|
|
1008
|
+
},
|
|
1009
|
+
subscribe,
|
|
1010
|
+
close() {
|
|
1011
|
+
session.close();
|
|
1012
|
+
},
|
|
1013
|
+
[Symbol.dispose]() {
|
|
1014
|
+
session.close();
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
// packages/local-client/src/declarations.ts
|
|
1019
|
+
import { constants } from "node:fs";
|
|
1020
|
+
import { chmod, lstat, mkdir, open, unlink } from "node:fs/promises";
|
|
1021
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
1022
|
+
import { writeFileAtomic } from "stitchkit/files";
|
|
1023
|
+
|
|
1024
|
+
// packages/local-client/src/paths.ts
|
|
1025
|
+
import { homedir } from "node:os";
|
|
1026
|
+
import { basename, dirname, isAbsolute as isAbsolute2, join, resolve } from "node:path";
|
|
1027
|
+
var NODE_CONFIG_FILE = "node.json";
|
|
1028
|
+
function absolutePath(what, path) {
|
|
1029
|
+
if (!isAbsolute2(path))
|
|
1030
|
+
throw new RangeError(`${what} must be an absolute path, not ${JSON.stringify(path.slice(0, 256))}: a relative one resolves against each process's own working directory`);
|
|
1031
|
+
return path;
|
|
1032
|
+
}
|
|
1033
|
+
function envPath(name, env = process.env) {
|
|
1034
|
+
const value = env[name];
|
|
1035
|
+
return value === undefined || value === "" ? undefined : absolutePath(name, value);
|
|
1036
|
+
}
|
|
1037
|
+
function home(options) {
|
|
1038
|
+
return options.homeDir === undefined || options.homeDir === "" ? homedir() : options.homeDir;
|
|
1039
|
+
}
|
|
1040
|
+
function defaultConfigDir(options = {}) {
|
|
1041
|
+
return envPath("STITCHWIRE_CONFIG_DIR", options.env) ?? join(home(options), ".config", "stitchwire");
|
|
1042
|
+
}
|
|
1043
|
+
function defaultStateDir(options = {}) {
|
|
1044
|
+
return envPath("STITCHWIRE_STATE_DIR", options.env) ?? join(home(options), ".local", "state", "stitchwire");
|
|
1045
|
+
}
|
|
1046
|
+
function defaultWireSocketPath(options = {}) {
|
|
1047
|
+
return envPath("STITCHWIRE_AGENT_SOCKET", options.env) ?? join(defaultStateDir(options), "agent.sock");
|
|
1048
|
+
}
|
|
1049
|
+
function defaultNodeConfigPath(options = {}) {
|
|
1050
|
+
return join(defaultConfigDir(options), NODE_CONFIG_FILE);
|
|
1051
|
+
}
|
|
1052
|
+
function dropInDirBeside(configPath, kind) {
|
|
1053
|
+
const absolute = resolve(configPath);
|
|
1054
|
+
return basename(absolute) === NODE_CONFIG_FILE ? join(dirname(absolute), kind) : undefined;
|
|
1055
|
+
}
|
|
1056
|
+
function defaultDropInDir(options, kind) {
|
|
1057
|
+
const configPath = options.configPath === undefined || options.configPath === "" ? defaultNodeConfigPath(options) : absolutePath("configPath", options.configPath);
|
|
1058
|
+
const dir = dropInDirBeside(configPath, kind);
|
|
1059
|
+
if (dir === undefined)
|
|
1060
|
+
throw new RangeError(`${configPath} has no default drop-in directory: only ${NODE_CONFIG_FILE} has one; pass the dropInDir its agent reads`);
|
|
1061
|
+
return dir;
|
|
1062
|
+
}
|
|
1063
|
+
function defaultServiceDropInDir(options = {}) {
|
|
1064
|
+
return defaultDropInDir(options, "services.d");
|
|
1065
|
+
}
|
|
1066
|
+
function defaultEventDropInDir(options = {}) {
|
|
1067
|
+
return defaultDropInDir(options, "events.d");
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// packages/local-client/src/declarations.ts
|
|
1071
|
+
function dropInRefusal(info, kind, uid = process.getuid?.()) {
|
|
1072
|
+
if (kind === "directory" ? !info.isDirectory() : !info.isFile())
|
|
1073
|
+
return {
|
|
1074
|
+
rule: "type",
|
|
1075
|
+
detail: kind === "directory" ? "drop-in path is not a directory (symlinks are refused)" : "drop-in file is not a regular file (symlinks are refused)"
|
|
1076
|
+
};
|
|
1077
|
+
if (uid !== undefined && info.uid !== uid)
|
|
1078
|
+
return { rule: "owner", detail: `drop-in ${kind} is owned by uid ${info.uid}, expected ${uid}` };
|
|
1079
|
+
if ((info.mode & 18) !== 0)
|
|
1080
|
+
return {
|
|
1081
|
+
rule: "mode",
|
|
1082
|
+
detail: `drop-in ${kind} must not be group- or world-writable (mode ${(info.mode & 511).toString(8)})`
|
|
1083
|
+
};
|
|
1084
|
+
return null;
|
|
1085
|
+
}
|
|
1086
|
+
var DROP_IN_STEM_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
1087
|
+
function filesystemFailure(message, cause) {
|
|
1088
|
+
const code = errnoOf(cause);
|
|
1089
|
+
return new WireClientError(code === "EACCES" || code === "EPERM" ? "permission" : "transport", message, "not-sent", {
|
|
1090
|
+
cause
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
function normalizeDropInFilename(name) {
|
|
1094
|
+
const stem = name.endsWith(".json") ? name.slice(0, -".json".length) : name;
|
|
1095
|
+
if (!DROP_IN_STEM_PATTERN.test(stem) || stem.includes("..") || stem.endsWith(".") || stem.endsWith(".json") || name.includes("/") || name.includes("\\") || name.includes("\x00")) {
|
|
1096
|
+
throw new WireClientError("invalid-request", `Invalid drop-in declaration name '${name}': expected lowercase slug [a-z0-9][a-z0-9._-]{0,63} without path separators`, "not-sent");
|
|
1097
|
+
}
|
|
1098
|
+
return `${stem}.json`;
|
|
1099
|
+
}
|
|
1100
|
+
function assertOwnedPrivateDir(path, info) {
|
|
1101
|
+
const refusal = dropInRefusal(info, "directory");
|
|
1102
|
+
if (refusal !== null)
|
|
1103
|
+
throw new WireClientError("permission", `${refusal.detail}: ${path}`, "not-sent");
|
|
1104
|
+
}
|
|
1105
|
+
async function ensureDropInDir(dir) {
|
|
1106
|
+
try {
|
|
1107
|
+
const info = await lstat(dir);
|
|
1108
|
+
assertOwnedPrivateDir(dir, info);
|
|
1109
|
+
return;
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
if (error instanceof WireClientError)
|
|
1112
|
+
throw error;
|
|
1113
|
+
if (errnoOf(error) !== "ENOENT")
|
|
1114
|
+
throw filesystemFailure(`Cannot inspect drop-in directory ${dir}`, error);
|
|
1115
|
+
}
|
|
1116
|
+
const missing = [];
|
|
1117
|
+
let cursor = dir;
|
|
1118
|
+
while (true) {
|
|
1119
|
+
try {
|
|
1120
|
+
await lstat(cursor);
|
|
1121
|
+
break;
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
if (errnoOf(error) !== "ENOENT")
|
|
1124
|
+
throw filesystemFailure(`Cannot inspect ancestor directory ${cursor}`, error);
|
|
1125
|
+
missing.push(cursor);
|
|
1126
|
+
const parent = dirname2(cursor);
|
|
1127
|
+
if (parent === cursor)
|
|
1128
|
+
break;
|
|
1129
|
+
cursor = parent;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
for (const segment of missing.reverse()) {
|
|
1133
|
+
try {
|
|
1134
|
+
await mkdir(segment, { mode: 448 });
|
|
1135
|
+
await chmod(segment, 448);
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
if (errnoOf(error) !== "EEXIST")
|
|
1138
|
+
throw filesystemFailure(`Cannot create drop-in directory ${segment}`, error);
|
|
1139
|
+
const existing = await lstat(segment).catch((cause) => {
|
|
1140
|
+
throw filesystemFailure(`Cannot inspect directory ${segment}`, cause);
|
|
1141
|
+
});
|
|
1142
|
+
if (!existing.isDirectory()) {
|
|
1143
|
+
throw new WireClientError("permission", `Path ${segment} is not a directory`, "not-sent");
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
let finalInfo;
|
|
1148
|
+
try {
|
|
1149
|
+
finalInfo = await lstat(dir);
|
|
1150
|
+
} catch (cause) {
|
|
1151
|
+
throw filesystemFailure(`Cannot inspect drop-in directory ${dir}`, cause);
|
|
1152
|
+
}
|
|
1153
|
+
assertOwnedPrivateDir(dir, finalInfo);
|
|
1154
|
+
}
|
|
1155
|
+
async function matchesExistingPrivateFile(target, expected) {
|
|
1156
|
+
let handle;
|
|
1157
|
+
try {
|
|
1158
|
+
handle = await open(target, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
1159
|
+
const info = await handle.stat();
|
|
1160
|
+
const refusal = dropInRefusal(info, "file");
|
|
1161
|
+
if (refusal !== null && refusal.rule !== "mode")
|
|
1162
|
+
throw new WireClientError("permission", `${refusal.detail}: ${target}`, "not-sent");
|
|
1163
|
+
if ((info.mode & 511) !== 384 || info.size !== expected.byteLength) {
|
|
1164
|
+
return false;
|
|
1165
|
+
}
|
|
1166
|
+
const buf = Buffer.allocUnsafe(expected.byteLength + 1);
|
|
1167
|
+
let filled = 0;
|
|
1168
|
+
while (filled < buf.length) {
|
|
1169
|
+
const { bytesRead } = await handle.read(buf, filled, buf.length - filled, filled);
|
|
1170
|
+
if (bytesRead === 0)
|
|
1171
|
+
break;
|
|
1172
|
+
filled += bytesRead;
|
|
1173
|
+
}
|
|
1174
|
+
return filled === expected.byteLength && buf.subarray(0, filled).equals(expected);
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
if (error instanceof WireClientError)
|
|
1177
|
+
throw error;
|
|
1178
|
+
const code = errnoOf(error);
|
|
1179
|
+
if (code === "ENOENT")
|
|
1180
|
+
return false;
|
|
1181
|
+
if (code === "ELOOP" || code === "EISDIR") {
|
|
1182
|
+
throw new WireClientError("permission", `Drop-in target ${target} is not a regular file`, "not-sent", {
|
|
1183
|
+
cause: error
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
throw filesystemFailure(`Cannot inspect existing drop-in file ${target}`, error);
|
|
1187
|
+
} finally {
|
|
1188
|
+
await handle?.close().catch(() => {
|
|
1189
|
+
return;
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
async function writeValidatedDropIn(dir, name, serialized, maxBytes) {
|
|
1194
|
+
const expected = Buffer.from(serialized, "utf8");
|
|
1195
|
+
if (expected.byteLength > maxBytes) {
|
|
1196
|
+
throw new WireClientError("limit", `Declaration payload is ${expected.byteLength} bytes, above the ${maxBytes}-byte limit`, "not-sent");
|
|
1197
|
+
}
|
|
1198
|
+
const filename = normalizeDropInFilename(name);
|
|
1199
|
+
await ensureDropInDir(dir);
|
|
1200
|
+
const target = join2(dir, filename);
|
|
1201
|
+
if (await matchesExistingPrivateFile(target, expected)) {
|
|
1202
|
+
return { path: target, changed: false };
|
|
1203
|
+
}
|
|
1204
|
+
try {
|
|
1205
|
+
await writeFileAtomic(target, serialized, { mode: 384 });
|
|
1206
|
+
} catch (cause) {
|
|
1207
|
+
throw filesystemFailure(`Cannot write drop-in file ${target}`, cause);
|
|
1208
|
+
}
|
|
1209
|
+
return { path: target, changed: true };
|
|
1210
|
+
}
|
|
1211
|
+
async function removeDropIn(dir, name) {
|
|
1212
|
+
const filename = normalizeDropInFilename(name);
|
|
1213
|
+
const target = join2(dir, filename);
|
|
1214
|
+
try {
|
|
1215
|
+
const dirInfo = await lstat(dir);
|
|
1216
|
+
assertOwnedPrivateDir(dir, dirInfo);
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
if (error instanceof WireClientError)
|
|
1219
|
+
throw error;
|
|
1220
|
+
if (errnoOf(error) === "ENOENT")
|
|
1221
|
+
return { path: target, removed: false };
|
|
1222
|
+
throw filesystemFailure(`Cannot inspect drop-in directory ${dir}`, error);
|
|
1223
|
+
}
|
|
1224
|
+
try {
|
|
1225
|
+
const info = await lstat(target);
|
|
1226
|
+
if (info.isDirectory()) {
|
|
1227
|
+
throw new WireClientError("invalid-request", `Drop-in target ${target} is a directory`, "not-sent");
|
|
1228
|
+
}
|
|
1229
|
+
await unlink(target);
|
|
1230
|
+
return { path: target, removed: true };
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
if (error instanceof WireClientError)
|
|
1233
|
+
throw error;
|
|
1234
|
+
if (errnoOf(error) === "ENOENT")
|
|
1235
|
+
return { path: target, removed: false };
|
|
1236
|
+
throw filesystemFailure(`Cannot remove drop-in file ${target}`, error);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
function targetDir(options, kind) {
|
|
1240
|
+
try {
|
|
1241
|
+
if (options.dropInDir !== undefined)
|
|
1242
|
+
return absolutePath("dropInDir", options.dropInDir);
|
|
1243
|
+
return kind === "services.d" ? defaultServiceDropInDir(options) : defaultEventDropInDir(options);
|
|
1244
|
+
} catch (cause) {
|
|
1245
|
+
if (!(cause instanceof RangeError))
|
|
1246
|
+
throw cause;
|
|
1247
|
+
throw new WireClientError("invalid-request", cause.message, "not-sent", { cause });
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
function serializeDeclaration(value, schema, what) {
|
|
1251
|
+
const checked = schema.safeParse(value);
|
|
1252
|
+
if (!checked.success)
|
|
1253
|
+
throw new WireClientError("invalid-request", `Invalid ${what}`, "not-sent", { cause: checked.error });
|
|
1254
|
+
const serialized = `${JSON.stringify(value, null, 2)}
|
|
1255
|
+
`;
|
|
1256
|
+
const reread = schema.safeParse(JSON.parse(serialized));
|
|
1257
|
+
if (!reread.success)
|
|
1258
|
+
throw new WireClientError("invalid-request", `Invalid ${what}: it does not survive JSON`, "not-sent", {
|
|
1259
|
+
cause: reread.error
|
|
1260
|
+
});
|
|
1261
|
+
return serialized;
|
|
1262
|
+
}
|
|
1263
|
+
async function writeServiceDeclarationFile(name, declaration, options = {}) {
|
|
1264
|
+
const serialized = serializeDeclaration(declaration, ServiceDeclarationSchema2, "service declaration");
|
|
1265
|
+
return writeValidatedDropIn(targetDir(options, "services.d"), name, serialized, SERVICE_MAX_DECLARATION_BYTES2);
|
|
1266
|
+
}
|
|
1267
|
+
async function removeServiceDeclarationFile(name, options = {}) {
|
|
1268
|
+
return removeDropIn(targetDir(options, "services.d"), name);
|
|
1269
|
+
}
|
|
1270
|
+
async function writeTopicDescriptorFile(name, descriptor, options = {}) {
|
|
1271
|
+
const serialized = serializeDeclaration(descriptor, TopicDescriptorSchema2, "topic descriptor");
|
|
1272
|
+
return writeValidatedDropIn(targetDir(options, "events.d"), name, serialized, TOPIC_MAX_DESCRIPTOR_BYTES2);
|
|
1273
|
+
}
|
|
1274
|
+
async function removeTopicDescriptorFile(name, options = {}) {
|
|
1275
|
+
return removeDropIn(targetDir(options, "events.d"), name);
|
|
1276
|
+
}
|
|
1277
|
+
// packages/local-client/src/service.ts
|
|
1278
|
+
import { readBoundedBody as readBoundedBody2 } from "stitchkit/http";
|
|
1279
|
+
import { z as z8 } from "zod";
|
|
1280
|
+
|
|
1281
|
+
// packages/contracts/src/service/budgets.ts
|
|
1282
|
+
function serviceOperationTimeout(operation) {
|
|
1283
|
+
return operation.response.kind === "stream" ? operation.response.lifetimeMs ?? operation.limits.timeoutMs : operation.limits.timeoutMs;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// packages/local-client/src/service.ts
|
|
1287
|
+
class WireServiceError extends Error {
|
|
1288
|
+
outcome;
|
|
1289
|
+
traceId;
|
|
1290
|
+
constructor(outcome, traceId) {
|
|
1291
|
+
super(`Wire service ${outcome.code}`);
|
|
1292
|
+
this.outcome = outcome;
|
|
1293
|
+
this.traceId = traceId;
|
|
1294
|
+
this.name = "WireServiceError";
|
|
1295
|
+
}
|
|
1296
|
+
get delivery() {
|
|
1297
|
+
return this.outcome.delivery;
|
|
1298
|
+
}
|
|
1299
|
+
get transportCause() {
|
|
1300
|
+
return this.outcome.transportCause ?? null;
|
|
1301
|
+
}
|
|
1302
|
+
get refusal() {
|
|
1303
|
+
return this.outcome.refusal;
|
|
1304
|
+
}
|
|
1305
|
+
get detail() {
|
|
1306
|
+
return this.outcome.detail ?? null;
|
|
1307
|
+
}
|
|
1308
|
+
get cancellationOrigin() {
|
|
1309
|
+
return this.outcome.cancellationOrigin;
|
|
1310
|
+
}
|
|
1311
|
+
get diagnostics() {
|
|
1312
|
+
return this.outcome.diagnostics;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
function endedWithoutOutcome(traceId, error) {
|
|
1316
|
+
const diagnostics = error instanceof WireServiceError ? error.diagnostics : undefined;
|
|
1317
|
+
const origin = error instanceof WireServiceError ? error.cancellationOrigin : error instanceof WireClientError ? error.metadata.cancellationOrigin : undefined;
|
|
1318
|
+
return {
|
|
1319
|
+
traceId,
|
|
1320
|
+
phase: "result",
|
|
1321
|
+
...diagnostics === undefined ? {} : { diagnostics },
|
|
1322
|
+
...origin === undefined ? {} : { cancellationOrigin: origin }
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
function invalidRequest(detail) {
|
|
1326
|
+
return new WireServiceError({
|
|
1327
|
+
status: "failure",
|
|
1328
|
+
code: "invalid-request",
|
|
1329
|
+
delivery: "not-dispatched",
|
|
1330
|
+
retryAfterMs: null,
|
|
1331
|
+
transportCause: null,
|
|
1332
|
+
refusal: "request",
|
|
1333
|
+
detail
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
function cancelledRequest() {
|
|
1337
|
+
return new WireServiceError({
|
|
1338
|
+
status: "failure",
|
|
1339
|
+
code: "cancelled",
|
|
1340
|
+
cancellationOrigin: "caller-abort",
|
|
1341
|
+
delivery: "not-dispatched",
|
|
1342
|
+
retryAfterMs: null,
|
|
1343
|
+
transportCause: null,
|
|
1344
|
+
refusal: "none",
|
|
1345
|
+
detail: "service request body consumption was cancelled"
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
async function readRequestText(request, maxBytes) {
|
|
1349
|
+
if (declaredLengthExceeds(request.headers, maxBytes))
|
|
1350
|
+
throw invalidRequest("service request body exceeds its declared byte limit");
|
|
1351
|
+
const bytes = await readBoundedBody2(request.body, {
|
|
1352
|
+
maxBytes,
|
|
1353
|
+
signal: request.signal,
|
|
1354
|
+
limitError: () => invalidRequest("service request body exceeds its declared byte limit"),
|
|
1355
|
+
abortError: cancelledRequest
|
|
1356
|
+
});
|
|
1357
|
+
if (request.body === null)
|
|
1358
|
+
return "{}";
|
|
1359
|
+
try {
|
|
1360
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1361
|
+
} catch {
|
|
1362
|
+
throw invalidRequest("service request body is not UTF-8");
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
function streamFailure(item) {
|
|
1366
|
+
if (item.kind === "end") {
|
|
1367
|
+
const code = item.frame.reason === "cancelled" ? "cancelled" : item.frame.reason === "timeout" ? "timeout" : item.frame.reason === "unsupported" ? "unsupported" : item.frame.reason === "limit" ? "invalid-response" : "unavailable";
|
|
1368
|
+
return {
|
|
1369
|
+
status: "failure",
|
|
1370
|
+
code,
|
|
1371
|
+
delivery: "unknown",
|
|
1372
|
+
retryAfterMs: null,
|
|
1373
|
+
transportCause: null,
|
|
1374
|
+
refusal: "none",
|
|
1375
|
+
detail: `service stream ended with ${item.frame.reason}`
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
const { frame } = item;
|
|
1379
|
+
const code = frame.refusal === "capacity" ? "capacity" : frame.refusal === "request" ? "invalid-request" : frame.failure === "offline" ? "offline" : frame.failure === "denied" ? "denied" : frame.failure === "timeout" ? "timeout" : frame.failure === "cancelled" ? "cancelled" : frame.failure === "rejected" ? "invalid-request" : "unavailable";
|
|
1380
|
+
const notDispatched = frame.refusal !== "none" || frame.failure === "offline" || frame.failure === "denied" || frame.failure === "rejected" || frame.transportCause != null && TRANSPORT_CAUSES[frame.transportCause].delivery === "not-dispatched";
|
|
1381
|
+
return {
|
|
1382
|
+
status: "failure",
|
|
1383
|
+
code,
|
|
1384
|
+
delivery: notDispatched ? "not-dispatched" : "unknown",
|
|
1385
|
+
retryAfterMs: frame.retryAfterMs,
|
|
1386
|
+
transportCause: frame.transportCause ?? null,
|
|
1387
|
+
refusal: frame.refusal,
|
|
1388
|
+
detail: frame.detail
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
var BindingSchema = z8.strictObject({
|
|
1392
|
+
to: NodeIdSchema,
|
|
1393
|
+
baseUrl: z8.url(),
|
|
1394
|
+
descriptor: ServiceDescriptorSchema2
|
|
1395
|
+
});
|
|
1396
|
+
function createServiceFetch(client, binding) {
|
|
1397
|
+
if (typeof client.invokeService !== "function" || typeof client.stream !== "function")
|
|
1398
|
+
throw new TypeError("Wire service adapter requires invokeService and stream capabilities");
|
|
1399
|
+
const { onTrace, ...definition } = binding;
|
|
1400
|
+
const config = BindingSchema.parse(definition);
|
|
1401
|
+
const origin = new URL(config.baseUrl).origin;
|
|
1402
|
+
return async (input, init) => {
|
|
1403
|
+
const request = input instanceof Request ? init === undefined ? input : new Request(input, init) : new Request(String(input), init);
|
|
1404
|
+
const url = new URL(request.url);
|
|
1405
|
+
const operation = config.descriptor.operations.find((entry) => url.pathname === entry.path);
|
|
1406
|
+
if (url.origin !== origin || url.search || url.hash || url.username || url.password || request.method !== "POST" || !operation)
|
|
1407
|
+
throw invalidRequest("request does not match a declared virtual service operation");
|
|
1408
|
+
const traceId = crypto.randomUUID();
|
|
1409
|
+
if (operation.response.kind === "unary")
|
|
1410
|
+
onTrace?.({ traceId, phase: "start" });
|
|
1411
|
+
let body;
|
|
1412
|
+
try {
|
|
1413
|
+
body = await readRequestText(request, operation.limits.requestBytes);
|
|
1414
|
+
if (!ServiceRequestPayloadSchema.safeParse(body).success)
|
|
1415
|
+
throw invalidRequest("service request body is not a JSON document");
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
if (operation.response.kind === "unary") {
|
|
1418
|
+
onTrace?.(endedWithoutOutcome(traceId, error));
|
|
1419
|
+
if (error instanceof WireServiceError)
|
|
1420
|
+
throw new WireServiceError(error.outcome, traceId);
|
|
1421
|
+
}
|
|
1422
|
+
throw error;
|
|
1423
|
+
}
|
|
1424
|
+
if (operation.response.kind === "stream") {
|
|
1425
|
+
const feed = client.stream({
|
|
1426
|
+
to: config.to,
|
|
1427
|
+
source: {
|
|
1428
|
+
kind: "service",
|
|
1429
|
+
service: config.descriptor.service,
|
|
1430
|
+
revision: config.descriptor.revision,
|
|
1431
|
+
operation: operation.id,
|
|
1432
|
+
payload: body
|
|
1433
|
+
},
|
|
1434
|
+
timeoutMs: serviceOperationTimeout(operation)
|
|
1435
|
+
}, { signal: request.signal });
|
|
1436
|
+
return new Response(new ReadableStream({
|
|
1437
|
+
async pull(controller) {
|
|
1438
|
+
try {
|
|
1439
|
+
const next = await feed.next();
|
|
1440
|
+
if (next.done) {
|
|
1441
|
+
controller.close();
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
if (next.value.kind === "chunk") {
|
|
1445
|
+
controller.enqueue(next.value.data);
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
if (next.value.kind === "end" && next.value.frame.reason === "completed") {
|
|
1449
|
+
controller.close();
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
controller.error(new WireServiceError(streamFailure(next.value)));
|
|
1453
|
+
} catch (error) {
|
|
1454
|
+
controller.error(error);
|
|
1455
|
+
}
|
|
1456
|
+
},
|
|
1457
|
+
cancel() {
|
|
1458
|
+
feed.close();
|
|
1459
|
+
}
|
|
1460
|
+
}, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "application/x-ndjson" } });
|
|
1461
|
+
}
|
|
1462
|
+
const { outcome } = await client.invokeService({
|
|
1463
|
+
traceId,
|
|
1464
|
+
to: config.to,
|
|
1465
|
+
service: config.descriptor.service,
|
|
1466
|
+
revision: config.descriptor.revision,
|
|
1467
|
+
operation: operation.id,
|
|
1468
|
+
payload: body,
|
|
1469
|
+
timeoutMs: operation.limits.timeoutMs
|
|
1470
|
+
}, { signal: request.signal }).catch((error) => {
|
|
1471
|
+
onTrace?.(endedWithoutOutcome(traceId, error));
|
|
1472
|
+
throw error;
|
|
1473
|
+
});
|
|
1474
|
+
onTrace?.({
|
|
1475
|
+
traceId,
|
|
1476
|
+
phase: "result",
|
|
1477
|
+
diagnostics: outcome.diagnostics,
|
|
1478
|
+
...outcome.status === "failure" ? { cancellationOrigin: outcome.cancellationOrigin } : {}
|
|
1479
|
+
});
|
|
1480
|
+
if (outcome.status === "failure")
|
|
1481
|
+
throw new WireServiceError(outcome, traceId);
|
|
1482
|
+
return new Response(outcome.payload, {
|
|
1483
|
+
status: outcome.httpStatus,
|
|
1484
|
+
headers: { "content-type": "application/json", [SERVICE_TRACE_HEADER]: traceId }
|
|
1485
|
+
});
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// packages/local-client/src/error-chain.ts
|
|
1490
|
+
var DEFAULT_MAX_DEPTH = 16;
|
|
1491
|
+
function readCause(value) {
|
|
1492
|
+
if (typeof value !== "object" || value === null)
|
|
1493
|
+
return;
|
|
1494
|
+
try {
|
|
1495
|
+
return Reflect.get(value, "cause");
|
|
1496
|
+
} catch {
|
|
1497
|
+
return;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
function matchSafely(match, node) {
|
|
1501
|
+
try {
|
|
1502
|
+
return match(node);
|
|
1503
|
+
} catch {
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
function findInCauseChain(error, match, maxDepth) {
|
|
1508
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1)
|
|
1509
|
+
throw new RangeError(`maxDepth must be a positive integer (got ${maxDepth})`);
|
|
1510
|
+
const seen = new Set;
|
|
1511
|
+
let current = error;
|
|
1512
|
+
for (let depth = 0;depth < maxDepth && current !== undefined && current !== null; depth++) {
|
|
1513
|
+
const matched = matchSafely(match, current);
|
|
1514
|
+
if (matched !== undefined)
|
|
1515
|
+
return matched;
|
|
1516
|
+
if (typeof current !== "object" || seen.has(current))
|
|
1517
|
+
return;
|
|
1518
|
+
seen.add(current);
|
|
1519
|
+
current = readCause(current);
|
|
1520
|
+
}
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
function extractWireServiceError(error, maxDepth = DEFAULT_MAX_DEPTH) {
|
|
1524
|
+
return findInCauseChain(error, (node) => node instanceof WireServiceError ? node : undefined, maxDepth);
|
|
1525
|
+
}
|
|
1526
|
+
function extractWireClientError(error, maxDepth = DEFAULT_MAX_DEPTH) {
|
|
1527
|
+
return findInCauseChain(error, (node) => node instanceof WireClientError ? node : undefined, maxDepth);
|
|
1528
|
+
}
|
|
1529
|
+
function wireErrorCode(error, maxDepth = DEFAULT_MAX_DEPTH) {
|
|
1530
|
+
return findInCauseChain(error, (node) => node instanceof WireServiceError ? { source: "service", code: node.outcome.code } : node instanceof WireClientError ? { source: "client", code: node.code } : undefined, maxDepth);
|
|
1531
|
+
}
|
|
1532
|
+
// packages/local-client/src/ingress.ts
|
|
1533
|
+
import { readBoundedBody as readBoundedBody3 } from "stitchkit/http";
|
|
1534
|
+
import { defineRequestIngress } from "stitchkit/server";
|
|
1535
|
+
import { z as z9 } from "zod";
|
|
1536
|
+
var delivered = defineRequestIngress("stitchwire.service-caller");
|
|
1537
|
+
function serviceCaller(source) {
|
|
1538
|
+
return delivered.from(source);
|
|
1539
|
+
}
|
|
1540
|
+
var TraceIdSchema = z9.uuid();
|
|
1541
|
+
var BodyTimeoutSchema = z9.int().min(1).max(SERVICE_MAX_TIMEOUT_MS2);
|
|
1542
|
+
var envelopeText = new TextDecoder("utf-8", { fatal: true });
|
|
1543
|
+
function refusal(detail) {
|
|
1544
|
+
return Response.json({ error: "invalid-request", detail }, { status: 400 });
|
|
1545
|
+
}
|
|
1546
|
+
function createServiceIngress(options) {
|
|
1547
|
+
const descriptor = ServiceDescriptorSchema2.parse(options.descriptor);
|
|
1548
|
+
const { handler } = options;
|
|
1549
|
+
if (typeof handler !== "function")
|
|
1550
|
+
throw new TypeError("Service ingress requires a handler function");
|
|
1551
|
+
const bodyTimeoutMs = options.bodyTimeoutMs === undefined ? Math.max(...descriptor.operations.map(serviceOperationTimeout)) : BodyTimeoutSchema.parse(options.bodyTimeoutMs);
|
|
1552
|
+
const operations = new Map(descriptor.operations.map((operation) => [operation.id, operation]));
|
|
1553
|
+
const envelopeBytes = jsonEnvelopeBytes(Math.max(...descriptor.operations.map((operation) => operation.limits.requestBytes)));
|
|
1554
|
+
return async (request) => {
|
|
1555
|
+
if (request.method !== "POST")
|
|
1556
|
+
return refusal("service requests are POST envelopes");
|
|
1557
|
+
if (declaredLengthExceeds(request.headers, envelopeBytes))
|
|
1558
|
+
return refusal("service envelope exceeds the descriptor request limit");
|
|
1559
|
+
const expired = new Error("envelope read deadline");
|
|
1560
|
+
const reading = new AbortController;
|
|
1561
|
+
const timer = setTimeout(() => reading.abort(expired), bodyTimeoutMs);
|
|
1562
|
+
const callerGone = () => reading.abort(request.signal.reason);
|
|
1563
|
+
if (request.signal.aborted)
|
|
1564
|
+
callerGone();
|
|
1565
|
+
else
|
|
1566
|
+
request.signal.addEventListener("abort", callerGone, { once: true });
|
|
1567
|
+
let text;
|
|
1568
|
+
try {
|
|
1569
|
+
const bytes = await readBoundedBody3(request.body, {
|
|
1570
|
+
maxBytes: envelopeBytes,
|
|
1571
|
+
signal: reading.signal,
|
|
1572
|
+
limitError: () => new RangeError("envelope limit")
|
|
1573
|
+
});
|
|
1574
|
+
text = envelopeText.decode(bytes);
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
return refusal(error === expired ? "service envelope was not read within its deadline" : error instanceof RangeError ? "service envelope exceeds the descriptor request limit" : "service envelope could not be read");
|
|
1577
|
+
} finally {
|
|
1578
|
+
clearTimeout(timer);
|
|
1579
|
+
request.signal.removeEventListener("abort", callerGone);
|
|
1580
|
+
}
|
|
1581
|
+
let json;
|
|
1582
|
+
try {
|
|
1583
|
+
json = JSON.parse(text);
|
|
1584
|
+
} catch {
|
|
1585
|
+
return refusal("service envelope is not JSON");
|
|
1586
|
+
}
|
|
1587
|
+
const envelope = ServiceIngressSchema.safeParse(json);
|
|
1588
|
+
if (!envelope.success)
|
|
1589
|
+
return refusal("service envelope is not a version 1 ingress");
|
|
1590
|
+
const call = envelope.data;
|
|
1591
|
+
if (call.service !== descriptor.service)
|
|
1592
|
+
return refusal("service is not served here");
|
|
1593
|
+
if (call.revision !== descriptor.revision)
|
|
1594
|
+
return refusal("service revision is not served here");
|
|
1595
|
+
const operation = operations.get(call.operation);
|
|
1596
|
+
if (operation === undefined)
|
|
1597
|
+
return refusal("operation is not declared");
|
|
1598
|
+
if (Buffer.byteLength(call.payload) > operation.limits.requestBytes)
|
|
1599
|
+
return refusal("payload exceeds the operation request limit");
|
|
1600
|
+
const trace = TraceIdSchema.safeParse(request.headers.get(SERVICE_TRACE_HEADER));
|
|
1601
|
+
const forwarded = new Request(`http://owner.invalid${operation.path}`, {
|
|
1602
|
+
method: "POST",
|
|
1603
|
+
headers: { "content-type": "application/json" },
|
|
1604
|
+
body: call.payload,
|
|
1605
|
+
signal: request.signal
|
|
1606
|
+
});
|
|
1607
|
+
delivered.attach(forwarded, {
|
|
1608
|
+
caller: call.caller,
|
|
1609
|
+
operation: call.operation,
|
|
1610
|
+
id: call.id,
|
|
1611
|
+
traceId: trace.success ? trace.data : call.id
|
|
1612
|
+
});
|
|
1613
|
+
return handler(forwarded);
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
export {
|
|
1617
|
+
AuditStatusSchema2 as AuditStatusSchema,
|
|
1618
|
+
BrokerHealthSchema2 as BrokerHealthSchema,
|
|
1619
|
+
CallResultSchema2 as CallResultSchema,
|
|
1620
|
+
ClientErrorCodeSchema2 as ClientErrorCodeSchema,
|
|
1621
|
+
DEFAULT_BROKER_HEALTH_MAX_BYTES,
|
|
1622
|
+
DEFAULT_BROKER_HEALTH_TIMEOUT_MS,
|
|
1623
|
+
FleetConfigStateSchema2 as FleetConfigStateSchema,
|
|
1624
|
+
FleetEditionStatusSchema2 as FleetEditionStatusSchema,
|
|
1625
|
+
FleetNodeStatusSchema2 as FleetNodeStatusSchema,
|
|
1626
|
+
LOCAL_API_VERSION2 as LOCAL_API_VERSION,
|
|
1627
|
+
LaneStatusSchema2 as LaneStatusSchema,
|
|
1628
|
+
MAX_DECLARED_TOPICS2 as MAX_DECLARED_TOPICS,
|
|
1629
|
+
MAX_TOPIC_DESCRIPTOR_FILES2 as MAX_TOPIC_DESCRIPTOR_FILES,
|
|
1630
|
+
PeerResultSchema2 as PeerResultSchema,
|
|
1631
|
+
PublishResultSchema2 as PublishResultSchema,
|
|
1632
|
+
SERVICE_DEFAULT_REQUEST_BYTES2 as SERVICE_DEFAULT_REQUEST_BYTES,
|
|
1633
|
+
SERVICE_MAX_DECLARATION_BYTES2 as SERVICE_MAX_DECLARATION_BYTES,
|
|
1634
|
+
SERVICE_MAX_DESCRIPTOR_BYTES2 as SERVICE_MAX_DESCRIPTOR_BYTES,
|
|
1635
|
+
SERVICE_MAX_INFLIGHT2 as SERVICE_MAX_INFLIGHT,
|
|
1636
|
+
SERVICE_MAX_REQUEST_BYTES2 as SERVICE_MAX_REQUEST_BYTES,
|
|
1637
|
+
SERVICE_MAX_RESPONSE_BYTES2 as SERVICE_MAX_RESPONSE_BYTES,
|
|
1638
|
+
SERVICE_MAX_TIMEOUT_MS2 as SERVICE_MAX_TIMEOUT_MS,
|
|
1639
|
+
ServiceBindingSchema2 as ServiceBindingSchema,
|
|
1640
|
+
ServiceDeclarationSchema2 as ServiceDeclarationSchema,
|
|
1641
|
+
ServiceDescriptorSchema2 as ServiceDescriptorSchema,
|
|
1642
|
+
ServiceEffectSchema2 as ServiceEffectSchema,
|
|
1643
|
+
ServiceFailureCodeSchema2 as ServiceFailureCodeSchema,
|
|
1644
|
+
ServiceLimitsSchema2 as ServiceLimitsSchema,
|
|
1645
|
+
ServiceNamespaceSchema2 as ServiceNamespaceSchema,
|
|
1646
|
+
StatusResultSchema2 as StatusResultSchema,
|
|
1647
|
+
TOPIC_MAX_DESCRIPTOR_BYTES2 as TOPIC_MAX_DESCRIPTOR_BYTES,
|
|
1648
|
+
TopicDescriptorSchema2 as TopicDescriptorSchema,
|
|
1649
|
+
TopicNamespaceSchema2 as TopicNamespaceSchema,
|
|
1650
|
+
TopicProfileSchema2 as TopicProfileSchema,
|
|
1651
|
+
TopicRetentionSchema2 as TopicRetentionSchema,
|
|
1652
|
+
WireClientError,
|
|
1653
|
+
WireServiceError,
|
|
1654
|
+
brokerHealthUrl2 as brokerHealthUrl,
|
|
1655
|
+
createServiceFetch,
|
|
1656
|
+
createServiceIngress,
|
|
1657
|
+
createWireClient,
|
|
1658
|
+
decodeWireData,
|
|
1659
|
+
defaultConfigDir,
|
|
1660
|
+
defaultEventDropInDir,
|
|
1661
|
+
defaultNodeConfigPath,
|
|
1662
|
+
defaultServiceDropInDir,
|
|
1663
|
+
defaultStateDir,
|
|
1664
|
+
defaultWireSocketPath,
|
|
1665
|
+
extractWireClientError,
|
|
1666
|
+
extractWireServiceError,
|
|
1667
|
+
isTopicAuthorized2 as isTopicAuthorized,
|
|
1668
|
+
isTopicInNamespace2 as isTopicInNamespace,
|
|
1669
|
+
parseServiceDeclaration2 as parseServiceDeclaration,
|
|
1670
|
+
parseTopicDescriptor2 as parseTopicDescriptor,
|
|
1671
|
+
readBrokerHealth,
|
|
1672
|
+
removeServiceDeclarationFile,
|
|
1673
|
+
removeTopicDescriptorFile,
|
|
1674
|
+
serviceCaller,
|
|
1675
|
+
serviceDescriptorFromContract,
|
|
1676
|
+
serviceInNamespace2 as serviceInNamespace,
|
|
1677
|
+
wireErrorCode,
|
|
1678
|
+
writeServiceDeclarationFile,
|
|
1679
|
+
writeTopicDescriptorFile
|
|
1680
|
+
};
|