@spraxium/rpc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1177 @@
1
+ import { Code, Code as Code$1, ConnectError } from "@connectrpc/connect";
2
+ import { ConfigStore, ParentHookRegistry, definePlugin, isShardChild } from "@spraxium/core";
3
+ import "reflect-metadata";
4
+ import { Global, Inject, Injectable, Module } from "@spraxium/common";
5
+ import { DEFAULT_MAX_PAYLOAD_BYTES, RpcGateway, decodeJson, encodeJson } from "@spraxium/rpc-protocol";
6
+ import process from "node:process";
7
+ import { logger } from "@spraxium/logger";
8
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
9
+ import { once } from "node:events";
10
+ import { createSecureServer, createServer } from "node:http2";
11
+ import { connectNodeAdapter } from "@connectrpc/connect-node";
12
+ import { ShardClientUtil } from "discord.js";
13
+ //#region src/configuration/rpc.config.ts
14
+ const defineRpc = definePlugin("rpc");
15
+ //#endregion
16
+ //#region src/execution/rpc.error.ts
17
+ var RpcError = class extends Error {
18
+ constructor(message, code = Code$1.Internal) {
19
+ super(message);
20
+ this.code = code;
21
+ this.name = "RpcError";
22
+ }
23
+ };
24
+ //#endregion
25
+ //#region src/handlers/rpc-handler-metadata.constant.ts
26
+ const RPC_HANDLER_METADATA = Symbol.for("spraxium:rpc:handler");
27
+ //#endregion
28
+ //#region src/handlers/rpc-handler-options.validator.ts
29
+ var RpcHandlerOptionsValidator = class RpcHandlerOptionsValidator {
30
+ static validate(name, options) {
31
+ if (!/^[a-zA-Z][a-zA-Z0-9._-]{0,127}$/.test(name)) throw new Error("Invalid RPC handler name.");
32
+ if (!options || !["guild", "singleton"].includes(options.routing)) throw new Error(`RPC ${name} requires routing.`);
33
+ if (options.permissions !== void 0 && !RpcHandlerOptionsValidator.validPermissions(options.permissions)) throw new Error(`RPC ${name} has invalid permissions.`);
34
+ if (!options.permissions?.length && options.allowAuthenticated !== true) throw new Error(`RPC ${name} requires permissions or explicit allowAuthenticated: true.`);
35
+ if (options.schema && typeof options.schema.parse !== "function") throw new Error(`RPC ${name} has an invalid schema.`);
36
+ if (options.responseSchema && typeof options.responseSchema.parse !== "function") throw new Error(`RPC ${name} has an invalid responseSchema.`);
37
+ }
38
+ static validPermissions(value) {
39
+ if (!Array.isArray(value)) return false;
40
+ for (const permission of value) if (typeof permission !== "string" || !permission.trim()) return false;
41
+ return true;
42
+ }
43
+ };
44
+ //#endregion
45
+ //#region src/handlers/rpc-handler-metadata.store.ts
46
+ var RpcHandlerMetadataStore = class {
47
+ static register(name, options, target, key, descriptor) {
48
+ if (typeof target === "function" || typeof descriptor.value !== "function") throw new Error(`RPC ${name} must decorate an instance method.`);
49
+ if (Reflect.hasOwnMetadata(RPC_HANDLER_METADATA, target, key)) throw new Error(`RPC method ${String(key)} is already decorated.`);
50
+ Reflect.defineMetadata(RPC_HANDLER_METADATA, {
51
+ name,
52
+ ...options,
53
+ permissions: [...options.permissions ?? []]
54
+ }, target, key);
55
+ }
56
+ static read(target, key) {
57
+ const metadata = Reflect.getOwnMetadata(RPC_HANDLER_METADATA, target, key);
58
+ if (metadata) RpcHandlerOptionsValidator.validate(metadata.name, metadata);
59
+ return metadata;
60
+ }
61
+ };
62
+ //#endregion
63
+ //#region src/handlers/rpc-handler.decorator.ts
64
+ function RpcHandler(name, options) {
65
+ RpcHandlerOptionsValidator.validate(name, options);
66
+ return (target, key, descriptor) => RpcHandlerMetadataStore.register(name, options, target, key, descriptor);
67
+ }
68
+ //#endregion
69
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/decorate.js
70
+ function __decorate(decorators, target, key, desc) {
71
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
72
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
74
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
75
+ }
76
+ //#endregion
77
+ //#region src/configuration/rpc-config.resolver.ts
78
+ let RpcConfigResolver = class RpcConfigResolver {
79
+ resolve(config) {
80
+ const resolved = {
81
+ host: "127.0.0.1",
82
+ port: 4300,
83
+ maxPayloadBytes: DEFAULT_MAX_PAYLOAD_BYTES,
84
+ timeoutMs: 1e4,
85
+ maxConcurrentCalls: 100,
86
+ shutdownGraceMs: 5e3,
87
+ singletonShard: 0,
88
+ tlsTerminationProxy: false,
89
+ rateLimit: {
90
+ maxRequests: 120,
91
+ windowMs: 6e4
92
+ },
93
+ ...config,
94
+ enabled: config.enabled ?? true,
95
+ auth: this.resolveAuthentication(config)
96
+ };
97
+ this.validateLimits(resolved);
98
+ this.validateCredentials(resolved);
99
+ this.validateTransport(resolved);
100
+ return resolved;
101
+ }
102
+ validateLimits(resolved) {
103
+ if (typeof resolved.enabled !== "boolean" || typeof resolved.tlsTerminationProxy !== "boolean") throw new Error("RPC enabled and tlsTerminationProxy must be booleans.");
104
+ for (const [key, value] of Object.entries({
105
+ maxPayloadBytes: resolved.maxPayloadBytes,
106
+ timeoutMs: resolved.timeoutMs,
107
+ maxConcurrentCalls: resolved.maxConcurrentCalls,
108
+ shutdownGraceMs: resolved.shutdownGraceMs,
109
+ maxRequests: resolved.rateLimit.maxRequests,
110
+ windowMs: resolved.rateLimit.windowMs
111
+ })) if (!Number.isSafeInteger(value) || value <= 0 || value > 2147483647) throw new Error(`RPC ${key} must be a positive integer no greater than 2147483647.`);
112
+ if (!Number.isInteger(resolved.port) || resolved.port < 0 || resolved.port > 65535) throw new Error("RPC port must be between 0 and 65535.");
113
+ if (!Number.isSafeInteger(resolved.singletonShard) || resolved.singletonShard < 0) throw new Error("RPC singletonShard must be a nonnegative integer.");
114
+ if (typeof resolved.host !== "string" || !resolved.host.trim()) throw new Error("RPC host is required.");
115
+ }
116
+ resolveAuthentication(config) {
117
+ if (config.auth) {
118
+ if (config.token !== void 0 || config.permissions !== void 0) throw new Error("RPC accepts token/permissions or auth.tokens, not both.");
119
+ return config.auth;
120
+ }
121
+ if (config.token === void 0) throw new Error("RPC requires at least one access token.");
122
+ return { tokens: [{
123
+ id: "default",
124
+ value: config.token,
125
+ permissions: config.permissions ?? []
126
+ }] };
127
+ }
128
+ validateCredentials(config) {
129
+ const ids = /* @__PURE__ */ new Set();
130
+ const values = /* @__PURE__ */ new Set();
131
+ if (!config.auth?.tokens?.length) throw new Error("RPC requires at least one access token.");
132
+ for (const token of config.auth.tokens) {
133
+ if (!token.id || ids.has(token.id) || !/^[A-Za-z0-9._-]{1,64}$/.test(token.id)) throw new Error("RPC credential IDs must be unique identifiers (1-64 characters).");
134
+ if (typeof token.value !== "string" || token.value.length < 32 || token.value.length > 4096 || !/^[\x21-\x7E]+$/.test(token.value) || values.has(token.value)) throw new Error("RPC tokens must be unique and contain 32-4096 printable ASCII characters without whitespace.");
135
+ if (!this.validPermissions(token.permissions)) throw new Error("RPC credential permissions must be an array of nonempty strings.");
136
+ ids.add(token.id);
137
+ values.add(token.value);
138
+ }
139
+ }
140
+ validateTransport(resolved) {
141
+ if (resolved.tls && (!resolved.tls.cert || !resolved.tls.key)) throw new Error("RPC TLS requires key and cert.");
142
+ if (![
143
+ "127.0.0.1",
144
+ "::1",
145
+ "localhost"
146
+ ].includes(resolved.host) && !resolved.tls && !resolved.tlsTerminationProxy) throw new Error("Remote RPC listeners require TLS or an explicit tlsTerminationProxy configuration.");
147
+ }
148
+ validPermissions(value) {
149
+ if (!Array.isArray(value)) return false;
150
+ for (const permission of value) if (typeof permission !== "string" || !permission.trim()) return false;
151
+ return true;
152
+ }
153
+ };
154
+ RpcConfigResolver = __decorate([Injectable()], RpcConfigResolver);
155
+ //#endregion
156
+ //#region src/handlers/rpc-bound.handler.ts
157
+ var RpcBoundHandler = class {
158
+ constructor(metadata, instance, method) {
159
+ this.instance = instance;
160
+ this.method = method;
161
+ if (typeof method !== "function") throw new Error(`RPC ${metadata.name} is not a method.`);
162
+ this.name = metadata.name;
163
+ this.routing = metadata.routing;
164
+ this.permissions = [...metadata.permissions ?? []];
165
+ this.allowAuthenticated = metadata.allowAuthenticated === true;
166
+ this.schema = metadata.schema;
167
+ this.responseSchema = metadata.responseSchema;
168
+ }
169
+ execute(input, context) {
170
+ if (typeof this.method !== "function") throw new Error(`RPC ${this.name} is not a method.`);
171
+ return this.method.call(this.instance, input, context);
172
+ }
173
+ };
174
+ //#endregion
175
+ //#region src/handlers/rpc-handler.registry.ts
176
+ let RpcRegistry = class RpcRegistry {
177
+ constructor() {
178
+ this.handlers = /* @__PURE__ */ new Map();
179
+ this.scanned = /* @__PURE__ */ new WeakSet();
180
+ }
181
+ scan(instance) {
182
+ if (!instance || typeof instance !== "object" || this.scanned.has(instance)) return;
183
+ this.scanned.add(instance);
184
+ const visited = /* @__PURE__ */ new Set();
185
+ let prototype = Object.getPrototypeOf(instance);
186
+ while (prototype && prototype !== Object.prototype) {
187
+ for (const key of Reflect.ownKeys(prototype)) {
188
+ if (visited.has(key)) continue;
189
+ visited.add(key);
190
+ const metadata = RpcHandlerMetadataStore.read(prototype, key);
191
+ if (!metadata) continue;
192
+ if (this.handlers.has(metadata.name)) throw new Error(`Duplicate RPC handler: ${metadata.name}.`);
193
+ const method = Object.getOwnPropertyDescriptor(prototype, key)?.value;
194
+ this.handlers.set(metadata.name, new RpcBoundHandler(metadata, instance, method));
195
+ }
196
+ prototype = Object.getPrototypeOf(prototype);
197
+ }
198
+ }
199
+ get(name) {
200
+ const handler = this.handlers.get(name);
201
+ if (!handler) throw new ConnectError("RPC handler not found.", Code$1.NotFound);
202
+ return handler;
203
+ }
204
+ descriptions() {
205
+ const descriptions = [];
206
+ for (const { name, routing, permissions, allowAuthenticated } of this.handlers.values()) descriptions.push({
207
+ name,
208
+ routing,
209
+ permissions,
210
+ allowAuthenticated
211
+ });
212
+ return descriptions;
213
+ }
214
+ };
215
+ RpcRegistry = __decorate([Injectable()], RpcRegistry);
216
+ //#endregion
217
+ //#region src/handlers/rpc-guild-id.validator.ts
218
+ var RpcGuildIdValidator = class {
219
+ static read(input) {
220
+ const guildId = input && typeof input === "object" && "guildId" in input ? input.guildId : void 0;
221
+ if (typeof guildId !== "string" || !/^[1-9][0-9]{0,19}$/.test(guildId) || BigInt(guildId) > 18446744073709551615n) throw new ConnectError("A valid guildId string is required.", Code$1.InvalidArgument);
222
+ return guildId;
223
+ }
224
+ };
225
+ //#endregion
226
+ //#region src/security/rpc-access.policy.ts
227
+ var RpcAccessPolicy = class {
228
+ static authorize(handler, identity) {
229
+ if (!handler.allowAuthenticated && !handler.permissions.length) throw new ConnectError("Permission denied.", Code$1.PermissionDenied);
230
+ for (const permission of handler.permissions) if (!identity.permissions.includes(permission)) throw new ConnectError("Permission denied.", Code$1.PermissionDenied);
231
+ }
232
+ };
233
+ //#endregion
234
+ //#region src/execution/rpc-failure.mapper.ts
235
+ var RpcFailureMapper = class {
236
+ static fromPayload(error) {
237
+ return new ConnectError(error instanceof RangeError ? "RPC payload limit exceeded." : "Invalid JSON payload.", error instanceof RangeError ? Code$1.ResourceExhausted : Code$1.InvalidArgument);
238
+ }
239
+ static fromCancellation(signal) {
240
+ return signal.reason instanceof ConnectError ? signal.reason : new ConnectError("RPC call canceled.", Code$1.Canceled);
241
+ }
242
+ static ipcUnavailable() {
243
+ return new ConnectError("RPC shard IPC unavailable.", Code$1.Unavailable);
244
+ }
245
+ };
246
+ //#endregion
247
+ //#region src/execution/rpc-cancellation.service.ts
248
+ var RpcCancellation = class {
249
+ static async waitForSettled(work, timeoutMs) {
250
+ if (timeoutMs <= 0) return;
251
+ let timer;
252
+ try {
253
+ await Promise.race([Promise.allSettled(work), new Promise((resolve) => {
254
+ timer = setTimeout(resolve, timeoutMs);
255
+ })]);
256
+ } finally {
257
+ clearTimeout(timer);
258
+ }
259
+ }
260
+ static wait(work, signal) {
261
+ return new Promise((resolve, reject) => {
262
+ const cancel = () => reject(RpcFailureMapper.fromCancellation(signal));
263
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", cancel));
264
+ if (signal.aborted) cancel();
265
+ else signal.addEventListener("abort", cancel, { once: true });
266
+ });
267
+ }
268
+ };
269
+ //#endregion
270
+ //#region src/execution/rpc-schema.validator.ts
271
+ var RpcSchemaValidator = class {
272
+ static parse(schema, value, response) {
273
+ let parsed;
274
+ try {
275
+ parsed = schema.parse(value);
276
+ } catch {
277
+ throw new ConnectError(response ? "Invalid RPC result." : "Invalid RPC arguments.", response ? Code$1.Internal : Code$1.InvalidArgument);
278
+ }
279
+ if (parsed !== null && (typeof parsed === "object" || typeof parsed === "function") && "then" in parsed && typeof parsed.then === "function") {
280
+ Promise.resolve(parsed).catch(() => void 0);
281
+ throw new ConnectError("RPC schemas must be synchronous.", Code$1.Internal);
282
+ }
283
+ return parsed;
284
+ }
285
+ };
286
+ //#endregion
287
+ //#region src/execution/rpc.invocation.ts
288
+ var RpcInvocation = class {
289
+ constructor(handler, input, context, config, guildId) {
290
+ this.handler = handler;
291
+ this.input = input;
292
+ this.context = context;
293
+ this.config = config;
294
+ this.guildId = guildId;
295
+ this.controller = new AbortController();
296
+ this.cancel = this.forwardCancellation.bind(this);
297
+ this.cleanup = this.dispose.bind(this);
298
+ if (context.signal.aborted) throw RpcFailureMapper.fromCancellation(context.signal);
299
+ const remaining = Math.min(context.deadline.getTime() - Date.now(), config.timeoutMs);
300
+ if (remaining <= 0) throw new ConnectError("RPC deadline exceeded.", Code$1.DeadlineExceeded);
301
+ context.signal.addEventListener("abort", this.cancel, { once: true });
302
+ this.timer = setTimeout(this.expire.bind(this), remaining);
303
+ this.controller.signal.addEventListener("abort", this.cleanup, { once: true });
304
+ }
305
+ run() {
306
+ return Promise.resolve().then(this.execute.bind(this));
307
+ }
308
+ dispose() {
309
+ clearTimeout(this.timer);
310
+ this.context.signal.removeEventListener("abort", this.cancel);
311
+ this.controller.signal.removeEventListener("abort", this.cleanup);
312
+ }
313
+ forwardCancellation() {
314
+ this.controller.abort(RpcFailureMapper.fromCancellation(this.context.signal));
315
+ }
316
+ expire() {
317
+ this.controller.abort(new ConnectError("RPC deadline exceeded.", Code$1.DeadlineExceeded));
318
+ }
319
+ async execute() {
320
+ if (this.controller.signal.aborted) throw RpcFailureMapper.fromCancellation(this.controller.signal);
321
+ this.validateArguments();
322
+ const result = await this.executeHandler();
323
+ if (this.controller.signal.aborted) throw RpcFailureMapper.fromCancellation(this.controller.signal);
324
+ const output = this.handler.responseSchema ? RpcSchemaValidator.parse(this.handler.responseSchema, result, true) : result;
325
+ try {
326
+ return encodeJson(output, this.config.maxPayloadBytes);
327
+ } catch (error) {
328
+ throw new ConnectError(error instanceof RangeError ? "RPC result exceeds the payload limit." : "RPC result is not JSON serializable.", error instanceof RangeError ? Code$1.ResourceExhausted : Code$1.Internal);
329
+ }
330
+ }
331
+ validateArguments() {
332
+ if (!this.handler.schema) return;
333
+ this.input = RpcSchemaValidator.parse(this.handler.schema, this.input, false);
334
+ if (this.handler.routing === "guild" && RpcGuildIdValidator.read(this.input) !== this.guildId) throw new ConnectError("RPC schema changed guildId.", Code$1.InvalidArgument);
335
+ }
336
+ async executeHandler() {
337
+ try {
338
+ return await this.handler.execute(this.input, {
339
+ ...this.context,
340
+ signal: this.controller.signal
341
+ });
342
+ } catch (error) {
343
+ if (this.controller.signal.aborted) throw RpcFailureMapper.fromCancellation(this.controller.signal);
344
+ if (error instanceof RpcError) throw new ConnectError(error.message, error.code);
345
+ throw new ConnectError("RPC handler failed.", Code$1.Internal);
346
+ }
347
+ }
348
+ };
349
+ //#endregion
350
+ //#region src/execution/rpc.executor.ts
351
+ var RpcExecutor = class {
352
+ constructor(registry, config) {
353
+ this.registry = registry;
354
+ this.config = config;
355
+ this.stopping = false;
356
+ this.active = /* @__PURE__ */ new Map();
357
+ }
358
+ descriptions() {
359
+ return this.registry.descriptions();
360
+ }
361
+ async invoke(method, payload, context) {
362
+ if (this.stopping) throw new ConnectError("RPC is shutting down.", Code$1.Unavailable);
363
+ if (this.active.size >= this.config.maxConcurrentCalls) throw new ConnectError("RPC concurrency limit exceeded.", Code$1.ResourceExhausted);
364
+ const handler = this.registry.get(method);
365
+ RpcAccessPolicy.authorize(handler, context.identity);
366
+ const input = this.decodeInput(payload);
367
+ const guildId = handler.routing === "guild" ? RpcGuildIdValidator.read(input) : void 0;
368
+ const invocation = new RpcInvocation(handler, input, context, this.config, guildId);
369
+ const execution = invocation.run();
370
+ this.active.set(execution, invocation);
371
+ execution.finally(() => this.release(execution, invocation)).catch(() => void 0);
372
+ return RpcCancellation.wait(execution, invocation.controller.signal);
373
+ }
374
+ async close(graceMs) {
375
+ this.stopping = true;
376
+ await RpcCancellation.waitForSettled(this.active.keys(), graceMs);
377
+ for (const invocation of this.active.values()) invocation.controller.abort(new ConnectError("RPC is shutting down.", Code$1.Unavailable));
378
+ this.active.clear();
379
+ }
380
+ decodeInput(payload) {
381
+ try {
382
+ return decodeJson(payload, this.config.maxPayloadBytes);
383
+ } catch (error) {
384
+ throw RpcFailureMapper.fromPayload(error);
385
+ }
386
+ }
387
+ release(execution, invocation) {
388
+ this.active.delete(execution);
389
+ invocation.dispose();
390
+ }
391
+ };
392
+ //#endregion
393
+ //#region src/sharding/process-ipc.peer.ts
394
+ var ProcessIpcPeer = class {
395
+ on(event, listener) {
396
+ return process.on(event, listener);
397
+ }
398
+ off(event, listener) {
399
+ return process.off(event, listener);
400
+ }
401
+ send(message) {
402
+ return new Promise((resolve, reject) => {
403
+ if (!process.send || !process.connected) {
404
+ reject(RpcFailureMapper.ipcUnavailable());
405
+ return;
406
+ }
407
+ process.send(message, (error) => {
408
+ if (error) reject(RpcFailureMapper.ipcUnavailable());
409
+ else resolve();
410
+ });
411
+ });
412
+ }
413
+ };
414
+ //#endregion
415
+ //#region src/sharding/rpc-ipc.constant.ts
416
+ const RPC_IPC = "spraxium:rpc:v1";
417
+ //#endregion
418
+ //#region src/sharding/rpc-ipc.validator.ts
419
+ var RpcIpcValidator = class RpcIpcValidator {
420
+ static isMessage(value) {
421
+ if (!value || typeof value !== "object" || !("rpc" in value) || value.rpc !== "spraxium:rpc:v1" || !("kind" in value) || !("id" in value) || typeof value.id !== "string" || value.id.length > 128) return false;
422
+ switch (value.kind) {
423
+ case "describe":
424
+ case "cancel": return true;
425
+ case "invoke": return "method" in value && typeof value.method === "string" && value.method.length <= 128 && "payload" in value && typeof value.payload === "string" && "deadline" in value && typeof value.deadline === "number" && Number.isFinite(value.deadline) && "identity" in value && !!value.identity && typeof value.identity === "object" && "id" in value.identity && typeof value.identity.id === "string" && "permissions" in value.identity && RpcIpcValidator.isStringArray(value.identity.permissions);
426
+ case "result": return "payload" in value && typeof value.payload === "string";
427
+ case "error": return "message" in value && typeof value.message === "string" && "code" in value && typeof value.code === "number" && Number.isInteger(value.code) && value.code >= 1 && value.code <= 16;
428
+ case "manifest": return "handlers" in value && RpcIpcValidator.isDescriptionArray(value.handlers);
429
+ default: return false;
430
+ }
431
+ }
432
+ static isDescription(value) {
433
+ return !!value && typeof value === "object" && "name" in value && typeof value.name === "string" && "routing" in value && (value.routing === "guild" || value.routing === "singleton") && "permissions" in value && RpcIpcValidator.isStringArray(value.permissions) && "allowAuthenticated" in value && typeof value.allowAuthenticated === "boolean";
434
+ }
435
+ static isStringArray(value) {
436
+ if (!Array.isArray(value)) return false;
437
+ for (const item of value) if (typeof item !== "string") return false;
438
+ return true;
439
+ }
440
+ static isDescriptionArray(value) {
441
+ if (!Array.isArray(value)) return false;
442
+ for (const item of value) if (!RpcIpcValidator.isDescription(item)) return false;
443
+ return true;
444
+ }
445
+ };
446
+ //#endregion
447
+ //#region src/sharding/rpc-request.history.ts
448
+ var RpcRequestHistory = class {
449
+ constructor() {
450
+ this.ids = /* @__PURE__ */ new Set();
451
+ this.expirations = [];
452
+ }
453
+ get size() {
454
+ return this.ids.size;
455
+ }
456
+ has(id) {
457
+ return this.ids.has(id);
458
+ }
459
+ add(id, deadline) {
460
+ if (this.ids.has(id)) return;
461
+ this.ids.add(id);
462
+ const entry = {
463
+ id,
464
+ deadline
465
+ };
466
+ let index = this.expirations.length;
467
+ this.expirations.push(entry);
468
+ while (index > 0) {
469
+ const parent = Math.floor((index - 1) / 2);
470
+ if (this.expirations[parent].deadline <= deadline) break;
471
+ this.expirations[index] = this.expirations[parent];
472
+ index = parent;
473
+ }
474
+ this.expirations[index] = entry;
475
+ }
476
+ expire(now) {
477
+ while (this.expirations.length && this.expirations[0].deadline <= now) {
478
+ this.ids.delete(this.expirations[0].id);
479
+ this.removeEarliest();
480
+ }
481
+ }
482
+ clear() {
483
+ this.ids.clear();
484
+ this.expirations.length = 0;
485
+ }
486
+ removeEarliest() {
487
+ const last = this.expirations.pop();
488
+ if (!last || this.expirations.length === 0) return;
489
+ let index = 0;
490
+ let child = 1;
491
+ while (child < this.expirations.length) {
492
+ const right = child + 1;
493
+ if (right < this.expirations.length && this.expirations[right].deadline < this.expirations[child].deadline) child = right;
494
+ if (last.deadline <= this.expirations[child].deadline) break;
495
+ this.expirations[index] = this.expirations[child];
496
+ index = child;
497
+ child = index * 2 + 1;
498
+ }
499
+ this.expirations[index] = last;
500
+ }
501
+ };
502
+ //#endregion
503
+ //#region src/sharding/rpc-shard-worker.service.ts
504
+ var RpcShardWorker = class RpcShardWorker {
505
+ static {
506
+ this.historyLimit = 1e4;
507
+ }
508
+ constructor(peer, executor, maxPayloadBytes) {
509
+ this.peer = peer;
510
+ this.executor = executor;
511
+ this.maxPayloadBytes = maxPayloadBytes;
512
+ this.active = /* @__PURE__ */ new Map();
513
+ this.history = new RpcRequestHistory();
514
+ this.stopping = false;
515
+ this.ready = false;
516
+ this.describeRequests = /* @__PURE__ */ new Set();
517
+ this.listener = this.handleMessage.bind(this);
518
+ peer.on("message", this.listener);
519
+ }
520
+ async markReady() {
521
+ this.ready = true;
522
+ for (const id of this.describeRequests) await this.sendManifest(id);
523
+ this.describeRequests.clear();
524
+ }
525
+ async close(graceMs) {
526
+ this.stopping = true;
527
+ try {
528
+ await this.executor.close(graceMs);
529
+ } finally {
530
+ for (const controller of this.active.values()) controller.abort(new ConnectError("RPC shard is shutting down.", Code$1.Unavailable));
531
+ this.active.clear();
532
+ this.history.clear();
533
+ this.describeRequests.clear();
534
+ this.peer.off("message", this.listener);
535
+ }
536
+ }
537
+ handleMessage(message) {
538
+ this.receive(message).catch(() => void 0);
539
+ }
540
+ async receive(value) {
541
+ if (!RpcIpcValidator.isMessage(value)) return;
542
+ if (value.kind === "cancel") {
543
+ this.active.get(value.id)?.abort(new ConnectError("RPC call canceled.", Code$1.Canceled));
544
+ this.describeRequests.delete(value.id);
545
+ return;
546
+ }
547
+ if (value.kind !== "describe" && value.kind !== "invoke") return;
548
+ if (this.stopping || value.kind === "invoke" && !this.ready) {
549
+ await this.sendFailure(value.id, Code$1.Unavailable, "RPC shard is not ready.");
550
+ return;
551
+ }
552
+ if (value.kind === "describe") {
553
+ if (!this.ready) {
554
+ this.describeRequests.add(value.id);
555
+ return;
556
+ }
557
+ await this.sendManifest(value.id);
558
+ return;
559
+ }
560
+ await this.invoke(value);
561
+ }
562
+ async invoke(value) {
563
+ const now = Date.now();
564
+ this.history.expire(now);
565
+ if (this.active.has(value.id) || this.history.has(value.id)) return;
566
+ if (value.deadline <= now) {
567
+ await this.sendFailure(value.id, Code$1.DeadlineExceeded, "RPC deadline exceeded.");
568
+ return;
569
+ }
570
+ if (this.history.size >= RpcShardWorker.historyLimit) {
571
+ await this.sendFailure(value.id, Code$1.ResourceExhausted, "RPC shard request limit exceeded.");
572
+ return;
573
+ }
574
+ this.history.add(value.id, value.deadline);
575
+ const controller = new AbortController();
576
+ this.active.set(value.id, controller);
577
+ try {
578
+ if (Buffer.byteLength(value.payload) > this.maxPayloadBytes) throw new ConnectError("RPC payload limit exceeded.", Code$1.ResourceExhausted);
579
+ const payload = await this.executor.invoke(value.method, Buffer.from(value.payload, "utf8"), {
580
+ requestId: value.id,
581
+ identity: Object.freeze({
582
+ id: value.identity.id,
583
+ permissions: Object.freeze([...value.identity.permissions])
584
+ }),
585
+ deadline: new Date(value.deadline),
586
+ signal: controller.signal
587
+ });
588
+ await this.peer.send({
589
+ rpc: RPC_IPC,
590
+ kind: "result",
591
+ id: value.id,
592
+ payload: Buffer.from(payload).toString("utf8")
593
+ });
594
+ } catch (error) {
595
+ const safe = error instanceof ConnectError ? error : new ConnectError("RPC shard failed.", Code$1.Internal);
596
+ await this.sendFailure(value.id, safe.code, safe.rawMessage);
597
+ } finally {
598
+ this.active.delete(value.id);
599
+ }
600
+ }
601
+ async sendManifest(id) {
602
+ await this.peer.send({
603
+ rpc: RPC_IPC,
604
+ kind: "manifest",
605
+ id,
606
+ handlers: this.executor.descriptions()
607
+ });
608
+ }
609
+ async sendFailure(id, code, message) {
610
+ await this.peer.send({
611
+ rpc: RPC_IPC,
612
+ kind: "error",
613
+ id,
614
+ code,
615
+ message
616
+ });
617
+ }
618
+ };
619
+ //#endregion
620
+ //#region src/security/rpc-credential-rate.limiter.ts
621
+ var RpcCredentialRateLimiter = class {
622
+ constructor(config) {
623
+ this.config = config;
624
+ this.windows = /* @__PURE__ */ new Map();
625
+ }
626
+ check(identity) {
627
+ const now = Date.now();
628
+ let window = this.windows.get(identity.id);
629
+ if (!window || now - window.start >= this.config.rateLimit.windowMs) {
630
+ window = {
631
+ start: now,
632
+ count: 0
633
+ };
634
+ this.windows.set(identity.id, window);
635
+ }
636
+ if (window.count >= this.config.rateLimit.maxRequests) throw new ConnectError("RPC rate limit exceeded.", Code$1.ResourceExhausted);
637
+ window.count++;
638
+ }
639
+ };
640
+ //#endregion
641
+ //#region src/security/rpc-token.authenticator.ts
642
+ var RpcTokenAuthenticator = class {
643
+ constructor(config) {
644
+ this.credentials = [];
645
+ for (const token of config.auth.tokens) this.credentials.push({
646
+ digest: createHash("sha256").update(token.value).digest(),
647
+ identity: Object.freeze({
648
+ id: token.id,
649
+ permissions: Object.freeze([...token.permissions])
650
+ })
651
+ });
652
+ }
653
+ authenticate(header) {
654
+ if (!header || !header.startsWith("Bearer ") || header.length > 8192) throw new ConnectError("Authentication required.", Code$1.Unauthenticated);
655
+ const digest = createHash("sha256").update(header.slice(7)).digest();
656
+ let identity;
657
+ for (const credential of this.credentials) if (timingSafeEqual(digest, credential.digest)) identity = credential.identity;
658
+ if (!identity) throw new ConnectError("Authentication required.", Code$1.Unauthenticated);
659
+ return identity;
660
+ }
661
+ };
662
+ //#endregion
663
+ //#region src/transport/rpc.server.ts
664
+ var RpcServer = class {
665
+ constructor(config, dispatcher, authenticator, rateLimiter, log) {
666
+ this.config = config;
667
+ this.dispatcher = dispatcher;
668
+ this.authenticator = authenticator;
669
+ this.rateLimiter = rateLimiter;
670
+ this.log = log;
671
+ this.sessions = /* @__PURE__ */ new Set();
672
+ this.sockets = /* @__PURE__ */ new Set();
673
+ this.active = /* @__PURE__ */ new Map();
674
+ this.stopping = false;
675
+ this.registeredMethods = /* @__PURE__ */ new Set();
676
+ for (const handler of dispatcher.descriptions()) this.registeredMethods.add(handler.name);
677
+ }
678
+ get address() {
679
+ const address = this.server?.address();
680
+ if (!address || typeof address === "string") return void 0;
681
+ return `${this.config.tls ? "https" : "http"}://${address.family === "IPv6" ? `[${address.address}]` : address.address}:${address.port}`;
682
+ }
683
+ async start() {
684
+ if (!this.config.enabled) return;
685
+ if (this.server || this.stopping) throw new Error("RPC server has already been started or closed.");
686
+ const adapter = connectNodeAdapter({
687
+ routes: this.registerRoutes.bind(this),
688
+ readMaxBytes: this.config.maxPayloadBytes * 2 + 4096,
689
+ writeMaxBytes: this.config.maxPayloadBytes * 2 + 4096,
690
+ maxTimeoutMs: 2147483647
691
+ });
692
+ const server = this.config.tls ? createSecureServer({
693
+ ...this.config.tls,
694
+ allowHTTP1: true,
695
+ maxHeaderListPairs: 64
696
+ }, adapter) : createServer({ maxHeaderListPairs: 64 }, adapter);
697
+ this.server = server;
698
+ server.on("session", this.trackSession.bind(this));
699
+ server.on("connection", this.trackSocket.bind(this));
700
+ server.on("error", this.listenerFailed.bind(this));
701
+ const listening = once(server, "listening");
702
+ server.listen(this.config.port, this.config.host);
703
+ await listening;
704
+ this.log.info(`Registered ${this.dispatcher.descriptions().length} RPC handlers; listening on ${this.address}`);
705
+ }
706
+ close() {
707
+ this.closing ??= this.shutdown();
708
+ return this.closing;
709
+ }
710
+ registerRoutes(router) {
711
+ router.service(RpcGateway, { invoke: this.invoke.bind(this) });
712
+ }
713
+ trackSession(session) {
714
+ this.sessions.add(session);
715
+ session.once("close", this.releaseSession.bind(this, session));
716
+ }
717
+ releaseSession(session) {
718
+ this.sessions.delete(session);
719
+ }
720
+ trackSocket(socket) {
721
+ this.sockets.add(socket);
722
+ socket.once("close", this.releaseSocket.bind(this, socket));
723
+ }
724
+ releaseSocket(socket) {
725
+ this.sockets.delete(socket);
726
+ }
727
+ listenerFailed() {
728
+ this.log.error("RPC listener error.");
729
+ }
730
+ validateRequest(request) {
731
+ if (this.active.size >= this.config.maxConcurrentCalls) throw new ConnectError("RPC concurrency limit exceeded.", Code$1.ResourceExhausted);
732
+ if (!/^[a-zA-Z][a-zA-Z0-9._-]{0,127}$/.test(request.method)) throw new ConnectError("Invalid RPC method name.", Code$1.InvalidArgument);
733
+ if (request.payloadJson.byteLength > this.config.maxPayloadBytes) throw new ConnectError("RPC payload limit exceeded.", Code$1.ResourceExhausted);
734
+ }
735
+ async invoke(request, context) {
736
+ const startedAt = Date.now();
737
+ const requestId = randomUUID();
738
+ context.responseHeader.set("x-request-id", requestId);
739
+ let code;
740
+ let timer;
741
+ let controller;
742
+ const cancel = () => controller?.abort(RpcFailureMapper.fromCancellation(context.signal));
743
+ try {
744
+ if (this.stopping) throw new ConnectError("RPC is shutting down.", Code$1.Unavailable);
745
+ const identity = this.authenticator.authenticate(context.requestHeader.get("authorization"));
746
+ this.rateLimiter.check(identity);
747
+ this.validateRequest(request);
748
+ controller = new AbortController();
749
+ context.signal.addEventListener("abort", cancel, { once: true });
750
+ if (context.signal.aborted) cancel();
751
+ const timeout = Math.min(this.config.timeoutMs, context.timeoutMs() ?? this.config.timeoutMs);
752
+ timer = setTimeout(() => controller?.abort(new ConnectError("RPC deadline exceeded.", Code$1.DeadlineExceeded)), timeout);
753
+ this.active.set(requestId, controller);
754
+ return { payloadJson: await RpcCancellation.wait(this.dispatcher.invoke(request.method, request.payloadJson, {
755
+ identity,
756
+ requestId,
757
+ deadline: new Date(Date.now() + timeout),
758
+ signal: controller.signal
759
+ }), controller.signal) };
760
+ } catch (error) {
761
+ const safe = error instanceof ConnectError ? error : new ConnectError("RPC request failed.", Code$1.Internal);
762
+ code = safe.code;
763
+ throw safe;
764
+ } finally {
765
+ clearTimeout(timer);
766
+ context.signal.removeEventListener("abort", cancel);
767
+ this.active.delete(requestId);
768
+ const method = this.registeredMethods.has(request.method) ? request.method : "<unregistered>";
769
+ this.log.info(`method=${method} requestId=${requestId} durationMs=${Date.now() - startedAt} code=${code ?? "OK"}`);
770
+ }
771
+ }
772
+ async shutdown() {
773
+ this.stopping = true;
774
+ const closed = new Promise((resolve) => {
775
+ if (!this.server?.listening) resolve();
776
+ else this.server.close(() => resolve());
777
+ });
778
+ try {
779
+ await this.dispatcher.close(this.config.shutdownGraceMs);
780
+ } finally {
781
+ await this.closeConnections(closed);
782
+ }
783
+ }
784
+ async closeConnections(closed) {
785
+ for (const controller of this.active.values()) controller.abort(new ConnectError("RPC is shutting down.", Code$1.Unavailable));
786
+ await new Promise((resolve) => setImmediate(resolve));
787
+ for (const session of this.sessions) session.close();
788
+ await RpcCancellation.waitForSettled([closed], 100);
789
+ for (const session of this.sessions) session.destroy();
790
+ for (const socket of this.sockets) socket.destroy();
791
+ await closed;
792
+ }
793
+ };
794
+ //#endregion
795
+ //#region src/integration/rpc-runtime.composition.ts
796
+ var RpcRuntimeComposition = class {
797
+ static createServer(config, dispatcher) {
798
+ return new RpcServer(config, dispatcher, new RpcTokenAuthenticator(config), new RpcCredentialRateLimiter(config), logger.child("RpcServer"));
799
+ }
800
+ };
801
+ //#endregion
802
+ //#region src/integration/spraxium-rpc.host.ts
803
+ let SpraxiumRpcHost = class SpraxiumRpcHost {
804
+ configuration() {
805
+ return ConfigStore.getPluginConfig(defineRpc);
806
+ }
807
+ isShardChild() {
808
+ return isShardChild();
809
+ }
810
+ assertCompatible() {
811
+ this.shutdownRegistrar();
812
+ }
813
+ registerParent(hook) {
814
+ ParentHookRegistry.register(hook);
815
+ }
816
+ onShutdown(hook) {
817
+ this.shutdownRegistrar()(hook);
818
+ }
819
+ shutdownRegistrar() {
820
+ if (!("onShutdown" in ParentHookRegistry) || typeof ParentHookRegistry.onShutdown !== "function") throw new Error("Spraxium RPC requires a framework release with module integrations, onApplicationReady and parent shutdown hooks. See docs/framework-compatibility.md in the RPC repository.");
821
+ return ParentHookRegistry.onShutdown.bind(ParentHookRegistry);
822
+ }
823
+ };
824
+ SpraxiumRpcHost = __decorate([Injectable()], SpraxiumRpcHost);
825
+ //#endregion
826
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/decorateMetadata.js
827
+ function __decorateMetadata(k, v) {
828
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
829
+ }
830
+ //#endregion
831
+ //#region \0@oxc-project+runtime@0.154.0/helpers/esm/decorateParam.js
832
+ function __decorateParam(paramIndex, decorator) {
833
+ return function(target, key) {
834
+ decorator(target, key, paramIndex);
835
+ };
836
+ }
837
+ //#endregion
838
+ //#region src/integration/rpc.lifecycle.ts
839
+ let RpcLifecycle = class RpcLifecycle {
840
+ constructor(host, registry, resolver) {
841
+ this.host = host;
842
+ this.registry = registry;
843
+ this.resolver = resolver;
844
+ this.shutdownGraceMs = 5e3;
845
+ }
846
+ onBoot() {
847
+ this.host.assertCompatible();
848
+ const raw = this.host.configuration();
849
+ if (!raw || raw.enabled === false) return;
850
+ const config = this.resolver.resolve(raw);
851
+ this.shutdownGraceMs = config.shutdownGraceMs;
852
+ this.executor = new RpcExecutor(this.registry, config);
853
+ if (this.host.isShardChild()) this.worker = new RpcShardWorker(new ProcessIpcPeer(), this.executor, config.maxPayloadBytes);
854
+ else this.server = RpcRuntimeComposition.createServer(config, this.executor);
855
+ }
856
+ async onApplicationReady() {
857
+ if (this.shutdownPromise) return;
858
+ await this.worker?.markReady();
859
+ await this.server?.start();
860
+ }
861
+ onShutdown() {
862
+ this.shutdownPromise ??= this.shutdown();
863
+ return this.shutdownPromise;
864
+ }
865
+ async shutdown() {
866
+ if (this.server) await this.server.close();
867
+ else if (this.worker) await this.worker.close(this.shutdownGraceMs);
868
+ else await this.executor?.close(this.shutdownGraceMs);
869
+ }
870
+ };
871
+ RpcLifecycle = __decorate([
872
+ Injectable(),
873
+ __decorateParam(0, Inject(SpraxiumRpcHost)),
874
+ __decorateParam(1, Inject(RpcRegistry)),
875
+ __decorateParam(2, Inject(RpcConfigResolver)),
876
+ __decorateMetadata("design:paramtypes", [
877
+ Object,
878
+ typeof RpcRegistry === "undefined" ? Object : RpcRegistry,
879
+ typeof RpcConfigResolver === "undefined" ? Object : RpcConfigResolver
880
+ ])
881
+ ], RpcLifecycle);
882
+ //#endregion
883
+ //#region src/integration/rpc-module.lifecycle.ts
884
+ var RpcModuleLifecycle = class {
885
+ constructor(container) {
886
+ this.container = container;
887
+ this.pendingInstances = [];
888
+ }
889
+ onInstance(instance) {
890
+ if (this.registry) this.registry.scan(instance);
891
+ else this.pendingInstances.push(instance);
892
+ }
893
+ onBoot() {
894
+ this.registry = this.container.get(RpcRegistry);
895
+ if (!this.registry) throw new Error("RpcModule must provide RpcRegistry.");
896
+ for (const instance of this.pendingInstances) this.registry.scan(instance);
897
+ this.pendingInstances.length = 0;
898
+ }
899
+ async onApplicationReady() {
900
+ await this.lifecycle().onApplicationReady();
901
+ }
902
+ async onShutdown() {
903
+ this.pendingInstances.length = 0;
904
+ await this.lifecycle().onShutdown();
905
+ }
906
+ lifecycle() {
907
+ const lifecycle = this.container.get(RpcLifecycle);
908
+ if (!lifecycle) throw new Error("RpcModule must provide RpcLifecycle.");
909
+ return lifecycle;
910
+ }
911
+ };
912
+ //#endregion
913
+ //#region src/sharding/rpc-pending.request.ts
914
+ var RpcPendingRequest = class {
915
+ constructor(shard, message, timeoutMs, signal, onFinish) {
916
+ this.shard = shard;
917
+ this.message = message;
918
+ this.timeoutMs = timeoutMs;
919
+ this.signal = signal;
920
+ this.onFinish = onFinish;
921
+ this.settled = false;
922
+ this.started = false;
923
+ this.abort = this.cancel.bind(this);
924
+ this.shardId = shard.id;
925
+ this.completion = new Promise((resolve, reject) => {
926
+ this.resolve = resolve;
927
+ this.reject = reject;
928
+ });
929
+ }
930
+ start() {
931
+ if (this.started || this.settled) return this.completion;
932
+ if (this.signal?.aborted) {
933
+ this.finish(void 0, RpcFailureMapper.fromCancellation(this.signal));
934
+ return this.completion;
935
+ }
936
+ this.started = true;
937
+ this.timer = setTimeout(this.abort, this.timeoutMs);
938
+ this.signal?.addEventListener("abort", this.abort, { once: true });
939
+ try {
940
+ this.shard.send(this.message).catch(this.sendFailed.bind(this));
941
+ } catch {
942
+ this.sendFailed();
943
+ }
944
+ return this.completion;
945
+ }
946
+ finish(response, error) {
947
+ if (this.settled) return;
948
+ this.settled = true;
949
+ clearTimeout(this.timer);
950
+ this.signal?.removeEventListener("abort", this.abort);
951
+ this.onFinish(this.message.id);
952
+ if (error) this.reject?.(error);
953
+ else if (response?.kind === "error") this.reject?.(new ConnectError(response.message, response.code));
954
+ else if (response) this.resolve?.(response);
955
+ else this.reject?.(RpcFailureMapper.ipcUnavailable());
956
+ }
957
+ cancel(error) {
958
+ if (this.settled) return;
959
+ const reason = error instanceof ConnectError ? error : this.signal?.aborted ? RpcFailureMapper.fromCancellation(this.signal) : new ConnectError("RPC deadline exceeded.", Code$1.DeadlineExceeded);
960
+ this.finish(void 0, reason);
961
+ this.sendCancellation().catch(() => void 0);
962
+ }
963
+ async sendCancellation() {
964
+ await this.shard.send({
965
+ rpc: RPC_IPC,
966
+ kind: "cancel",
967
+ id: this.message.id
968
+ });
969
+ }
970
+ sendFailed() {
971
+ this.finish(void 0, RpcFailureMapper.ipcUnavailable());
972
+ }
973
+ };
974
+ //#endregion
975
+ //#region src/sharding/rpc-shard-dispatcher.service.ts
976
+ var RpcShardDispatcher = class {
977
+ constructor(shards, totalShards, config) {
978
+ this.shards = shards;
979
+ this.totalShards = totalShards;
980
+ this.config = config;
981
+ this.handlers = /* @__PURE__ */ new Map();
982
+ this.available = /* @__PURE__ */ new Set();
983
+ this.pending = /* @__PURE__ */ new Map();
984
+ this.subscriptions = [];
985
+ this.stopping = false;
986
+ if (!Number.isSafeInteger(totalShards) || totalShards < 1) throw new Error("RPC requires the resolved Discord shard count.");
987
+ for (const shard of shards.values()) {
988
+ const listeners = {
989
+ shard,
990
+ message: this.receive.bind(this, shard),
991
+ unavailable: this.markUnavailable.bind(this, shard),
992
+ ready: this.refresh.bind(this, shard)
993
+ };
994
+ shard.on("message", listeners.message);
995
+ shard.on("death", listeners.unavailable);
996
+ shard.on("disconnect", listeners.unavailable);
997
+ shard.on("ready", listeners.ready);
998
+ this.subscriptions.push(listeners);
999
+ }
1000
+ }
1001
+ async start() {
1002
+ if (!this.shards.size) throw new Error("RPC requires at least one local shard.");
1003
+ try {
1004
+ const descriptions = [];
1005
+ for (const shard of this.shards.values()) descriptions.push(this.describe(shard));
1006
+ await Promise.all(descriptions);
1007
+ } catch (error) {
1008
+ await this.close(0);
1009
+ throw error;
1010
+ }
1011
+ }
1012
+ async describe(shard) {
1013
+ this.available.delete(shard.id);
1014
+ const message = await this.request(shard, {
1015
+ rpc: RPC_IPC,
1016
+ kind: "describe",
1017
+ id: randomUUID()
1018
+ }, this.config.timeoutMs);
1019
+ if (this.stopping) throw RpcFailureMapper.ipcUnavailable();
1020
+ if (message.kind !== "manifest") throw RpcFailureMapper.ipcUnavailable();
1021
+ const descriptions = /* @__PURE__ */ new Map();
1022
+ for (const handler of message.handlers) {
1023
+ RpcHandlerOptionsValidator.validate(handler.name, handler);
1024
+ if (descriptions.has(handler.name)) throw new Error(`Duplicate RPC handler: ${handler.name}.`);
1025
+ descriptions.set(handler.name, handler);
1026
+ }
1027
+ const signature = this.canonical([...descriptions.values()]);
1028
+ if (this.manifestSignature !== void 0 && signature !== this.manifestSignature) throw new Error(`RPC handler manifest differs on shard ${shard.id}.`);
1029
+ if (this.manifestSignature === void 0) {
1030
+ for (const [name, handler] of descriptions) this.handlers.set(name, handler);
1031
+ this.manifestSignature = signature;
1032
+ }
1033
+ this.available.add(shard.id);
1034
+ }
1035
+ descriptions() {
1036
+ return [...this.handlers.values()];
1037
+ }
1038
+ get pendingCount() {
1039
+ return this.pending.size;
1040
+ }
1041
+ async invoke(method, payload, context) {
1042
+ if (this.stopping) throw RpcFailureMapper.ipcUnavailable();
1043
+ const handler = this.handlers.get(method);
1044
+ if (!handler) throw new ConnectError("RPC handler not found.", Code$1.NotFound);
1045
+ RpcAccessPolicy.authorize(handler, context.identity);
1046
+ let input;
1047
+ try {
1048
+ input = decodeJson(payload, this.config.maxPayloadBytes);
1049
+ } catch (error) {
1050
+ throw RpcFailureMapper.fromPayload(error);
1051
+ }
1052
+ const shardId = handler.routing === "guild" ? ShardClientUtil.shardIdForGuildId(RpcGuildIdValidator.read(input), this.totalShards) : this.config.singletonShard;
1053
+ const shard = this.shards.get(shardId);
1054
+ if (!shard?.ready || !this.available.has(shardId)) throw new ConnectError("RPC target shard unavailable.", Code$1.Unavailable);
1055
+ const remaining = Math.min(this.config.timeoutMs, context.deadline.getTime() - Date.now());
1056
+ const response = await this.request(shard, {
1057
+ rpc: RPC_IPC,
1058
+ kind: "invoke",
1059
+ id: context.requestId,
1060
+ method,
1061
+ payload: Buffer.from(payload).toString("utf8"),
1062
+ identity: context.identity,
1063
+ deadline: context.deadline.getTime()
1064
+ }, remaining, context.signal);
1065
+ if (response.kind !== "result") throw RpcFailureMapper.ipcUnavailable();
1066
+ const bytes = Buffer.from(response.payload, "utf8");
1067
+ try {
1068
+ decodeJson(bytes, this.config.maxPayloadBytes);
1069
+ } catch {
1070
+ throw new ConnectError("Invalid RPC shard result.", Code$1.Internal);
1071
+ }
1072
+ return bytes;
1073
+ }
1074
+ request(shard, message, timeoutMs, signal) {
1075
+ if (this.stopping) return Promise.reject(RpcFailureMapper.ipcUnavailable());
1076
+ if (signal?.aborted) return Promise.reject(RpcFailureMapper.fromCancellation(signal));
1077
+ if (timeoutMs <= 0) return Promise.reject(new ConnectError("RPC deadline exceeded.", Code$1.DeadlineExceeded));
1078
+ if (this.pending.has(message.id)) return Promise.reject(new ConnectError("Duplicate RPC request ID.", Code$1.AlreadyExists));
1079
+ const request = new RpcPendingRequest(shard, message, timeoutMs, signal, this.release.bind(this));
1080
+ this.pending.set(message.id, request);
1081
+ return request.start();
1082
+ }
1083
+ async close(graceMs) {
1084
+ this.stopping = true;
1085
+ const completions = [];
1086
+ for (const call of this.pending.values()) completions.push(call.completion);
1087
+ await RpcCancellation.waitForSettled(completions, graceMs);
1088
+ for (const call of [...this.pending.values()]) call.cancel(new ConnectError("RPC is shutting down.", Code$1.Unavailable));
1089
+ for (const listeners of this.subscriptions.splice(0)) {
1090
+ const shard = listeners.shard;
1091
+ shard.off("message", listeners.message);
1092
+ shard.off("death", listeners.unavailable);
1093
+ shard.off("disconnect", listeners.unavailable);
1094
+ shard.off("ready", listeners.ready);
1095
+ }
1096
+ this.available.clear();
1097
+ }
1098
+ receive(shard, value) {
1099
+ if (!RpcIpcValidator.isMessage(value)) return;
1100
+ const pending = this.pending.get(value.id);
1101
+ if (pending?.shardId === shard.id) pending.finish(value);
1102
+ }
1103
+ markUnavailable(shard) {
1104
+ this.available.delete(shard.id);
1105
+ for (const call of [...this.pending.values()]) if (call.shardId === shard.id) call.finish(void 0, RpcFailureMapper.ipcUnavailable());
1106
+ }
1107
+ refresh(shard) {
1108
+ this.describe(shard).catch(() => this.available.delete(shard.id));
1109
+ }
1110
+ release(id) {
1111
+ this.pending.delete(id);
1112
+ }
1113
+ canonical(entries) {
1114
+ const normalized = [];
1115
+ entries.sort(this.compareHandlers);
1116
+ for (const entry of entries) normalized.push({
1117
+ name: entry.name,
1118
+ routing: entry.routing,
1119
+ permissions: [...entry.permissions].sort(),
1120
+ allowAuthenticated: entry.allowAuthenticated
1121
+ });
1122
+ return JSON.stringify(normalized);
1123
+ }
1124
+ compareHandlers(left, right) {
1125
+ return left.name.localeCompare(right.name);
1126
+ }
1127
+ };
1128
+ //#endregion
1129
+ //#region src/integration/rpc-parent.gateway.ts
1130
+ var RpcParentGateway = class {
1131
+ constructor(host, resolver) {
1132
+ this.host = host;
1133
+ this.resolver = resolver;
1134
+ }
1135
+ async start(manager) {
1136
+ const raw = this.host.configuration();
1137
+ if (!raw || raw.enabled === false) return;
1138
+ this.host.assertCompatible();
1139
+ const config = this.resolver.resolve(raw);
1140
+ if (typeof manager.totalShards !== "number") throw new Error("Discord shard count was not resolved.");
1141
+ const dispatcher = new RpcShardDispatcher(manager.shards, manager.totalShards, config);
1142
+ await dispatcher.start();
1143
+ const server = RpcRuntimeComposition.createServer(config, dispatcher);
1144
+ try {
1145
+ await server.start();
1146
+ } catch (error) {
1147
+ await server.close();
1148
+ throw error;
1149
+ }
1150
+ this.host.onShutdown(server.close.bind(server));
1151
+ }
1152
+ };
1153
+ //#endregion
1154
+ //#region src/integration/rpc.integration.ts
1155
+ const host = new SpraxiumRpcHost();
1156
+ const parent = new RpcParentGateway(host, new RpcConfigResolver());
1157
+ host.registerParent(parent.start.bind(parent));
1158
+ //#endregion
1159
+ //#region src/rpc.module.ts
1160
+ const metadata = {
1161
+ providers: [
1162
+ RpcRegistry,
1163
+ RpcConfigResolver,
1164
+ SpraxiumRpcHost,
1165
+ RpcLifecycle
1166
+ ],
1167
+ integrations: [{
1168
+ name: "rpc",
1169
+ setup: (context) => new RpcModuleLifecycle(context.container)
1170
+ }]
1171
+ };
1172
+ let RpcModule = class RpcModule {};
1173
+ RpcModule = __decorate([Global(), Module(metadata)], RpcModule);
1174
+ //#endregion
1175
+ export { Code, RpcError, RpcHandler, RpcModule, defineRpc };
1176
+
1177
+ //# sourceMappingURL=index.js.map