monoripper 0.1.0-prototype → 0.2.0-prototype

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0-prototype
4
+
5
+ Removes every runtime dependency of the published package. All APIs remain provisional.
6
+
7
+ - The package has no runtime dependencies. The gRPC control API runs on Bun's `node:http2` with a built-in proto3 codec instead of
8
+ `@grpc/grpc-js` and `@grpc/proto-loader` (which pulled in protobufjs, its install script and eval-based codegen, yargs and 20+ transitive packages).
9
+ The wire protocol and `control.proto` are unchanged; grpc-js remains a development dependency to test interoperability.
10
+ - `typescript` is an optional peer dependency, needed only by `check` and `pack`. Without it they fail with `MISSING_DEPENDENCY`.
11
+
3
12
  ## 0.1.0-prototype
4
13
 
5
14
  First prototype of the full release plan (e01–e03). All APIs are provisional. Automated checks pass; user acceptance is pending.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Run selected application contexts — plain `Bun.serve()` handlers or Elysia apps — in separate Bun processes through one HTTP gateway.
4
4
 
5
- **Status: prototype `0.1.0-prototype`, not production-ready. Install with `bun add monoripper@prototype`.**
5
+ **Status: prototype `0.2.0-prototype`, not production-ready. Install with `bun add monoripper@prototype`.**
6
6
  Selected contexts, background contexts, replicas, resource lifecycles, linting, local config, gRPC scale/status, worker recovery,
7
7
  persistent desired state, health/readiness, Prometheus metrics, trusted-proxy client addresses, JSON logs, and relayed WebSockets are implemented,
8
8
  as are immutable releases with a private registry, deploy/rollback of selected contexts, node agents on other machines,
@@ -12,7 +12,9 @@ request context with explicit cross-context calls, and bounded autoscaling. See
12
12
 
13
13
  Verified environment: Linux, Bun **1.3.13**, optionally Elysia **1.4.30**.
14
14
  With Nix, `nix develop` provides the pinned Bun, bun2nix, and Python. The flake pins nixpkgs `nixos-26.05` and fails evaluation if its Bun differs from `.bun-version`.
15
- `elysia` is an optional exact peer dependency: install it only for Elysia contexts, so the application and the runtime share one Elysia copy.
15
+ The package has no runtime dependencies. Both peers are optional:
16
+ `elysia` is an exact peer dependency: install it only for Elysia contexts, so the application and the runtime share one Elysia copy.
17
+ `typescript` (tested with 5.9.3) is needed only by `check` and `pack`; add it as a devDependency where you build releases.
16
18
  Without Elysia, keep `skipLibCheck: true` (the `bun init` default); the SDK declarations reference Elysia's types.
17
19
  Install project dependencies with Bun, not npm.
18
20
 
@@ -130,6 +132,7 @@ The CLI prints requestId and expectedRevision to stderr before the request. For
130
132
  Repeating the same ID/payload returns the same operation. Changed payloads with the same ID are rejected.
131
133
  `operation --id <id> --wait` resumes waiting. Client timeouts do not cancel accepted operations.
132
134
  Failed operations produce a nonzero CLI exit. GetStatus/GetOperation and SetContext are defined in `src/control.proto`, also delivered in dist.
135
+ The control API is standard unary gRPC (protobuf over HTTP/2) on Bun's `node:http2`, so any gRPC client can use that file. Messages are limited to 1 MiB; compression is not supported.
133
136
 
134
137
  SDK: `await connectControl({address, token, project, environment})`, then getStatus/setContext/getOperation/waitOperation, and always close.
135
138
  Programmatic Runtime exposes the same methods without network transport. `status()` still returns workers.
@@ -0,0 +1,77 @@
1
+ // @bun
2
+ import {
3
+ GrpcError,
4
+ controlService,
5
+ listenGrpc,
6
+ status
7
+ } from "./chunk-xa5bwvyr.js";
8
+ import {
9
+ MonoripperError
10
+ } from "./chunk-4030qem7.js";
11
+
12
+ // src/grpc-server.ts
13
+ import { timingSafeEqual } from "crypto";
14
+ import { readFileSync } from "fs";
15
+ var codes = {
16
+ INVALID_ARGUMENT: status.INVALID_ARGUMENT,
17
+ INVALID_CONFIG: status.INVALID_ARGUMENT,
18
+ PERMISSION_DENIED: status.PERMISSION_DENIED,
19
+ CONFLICT: status.ABORTED,
20
+ BUSY: status.FAILED_PRECONDITION,
21
+ ALREADY_EXISTS: status.ALREADY_EXISTS,
22
+ NOT_FOUND: status.NOT_FOUND,
23
+ CAPACITY_EXCEEDED: status.RESOURCE_EXHAUSTED,
24
+ SHUTTING_DOWN: status.UNAVAILABLE,
25
+ STATE_UNAVAILABLE: status.UNAVAILABLE,
26
+ STATE_WRITE_FAILED: status.UNAVAILABLE,
27
+ UNIMPLEMENTED: status.UNIMPLEMENTED,
28
+ RELEASES_DISABLED: status.FAILED_PRECONDITION,
29
+ AUTOSCALE_ACTIVE: status.FAILED_PRECONDITION
30
+ };
31
+ async function startControlServer(controller, config, token) {
32
+ const expected = Buffer.from(`Bearer ${token}`);
33
+ function handler(run) {
34
+ return async (request, headers) => {
35
+ const supplied = headers.authorization;
36
+ const received = Buffer.from(typeof supplied === "string" ? supplied : "");
37
+ if (received.length !== expected.length || !timingSafeEqual(received, expected))
38
+ throw new GrpcError(status.UNAUTHENTICATED, "Invalid control credential");
39
+ const input = request;
40
+ const scope = controller.status();
41
+ if (input.project !== scope.project || input.environment !== scope.environment)
42
+ throw new GrpcError(status.PERMISSION_DENIED, "Wrong project or environment");
43
+ try {
44
+ return await run(input);
45
+ } catch (error) {
46
+ throw error instanceof MonoripperError ? new GrpcError(codes[error.code] ?? status.INTERNAL, error.message) : new GrpcError(status.INTERNAL, "Control request failed");
47
+ }
48
+ };
49
+ }
50
+ const host = config.host ?? "127.0.0.1";
51
+ if (!config.tls && !["127.0.0.1", "::1"].includes(host))
52
+ throw new MonoripperError("INVALID_CONFIG", "Control without TLS permits loopback only");
53
+ const bracketed = host.includes(":") ? `[${host}]` : host;
54
+ const server = await listenGrpc({
55
+ host,
56
+ port: config.port ?? 50051,
57
+ ...config.tls ? { tls: { cert: readFileSync(config.tls.certFile), key: readFileSync(config.tls.keyFile) } } : {},
58
+ methods: [
59
+ [controlService.SetContext, handler((input) => controller.set({
60
+ project: input.project,
61
+ environment: input.environment,
62
+ requestId: input.requestId,
63
+ context: input.context,
64
+ expectedRevision: input.expectedRevision,
65
+ ...input.replicas !== undefined && input.replicas !== null ? { replicas: input.replicas } : {},
66
+ ...input.release ? { release: input.release } : {}
67
+ }))],
68
+ [controlService.GetStatus, handler(() => controller.status())],
69
+ [controlService.GetOperation, handler((input) => controller.operation(input.id))],
70
+ [controlService.SetAutoscale, handler((input) => controller.setAutoscale({ project: input.project, environment: input.environment, context: input.context, ...input.policy ? { policy: input.policy } : {} }))]
71
+ ]
72
+ });
73
+ return { address: `${bracketed}:${server.port}`, close: () => server.close() };
74
+ }
75
+ export {
76
+ startControlServer
77
+ };
@@ -4,8 +4,8 @@ import {
4
4
  publishRelease,
5
5
  registryBase,
6
6
  validToken
7
- } from "./chunk-yhbhg39y.js";
8
- import"./chunk-msm046bp.js";
7
+ } from "./chunk-h65ebvhk.js";
8
+ import"./chunk-nf80yg42.js";
9
9
  import"./chunk-hagr56n9.js";
10
10
  import"./chunk-4030qem7.js";
11
11
  export {
@@ -10,7 +10,7 @@ import {
10
10
  runtimeCompatibility,
11
11
  runtimeVersion,
12
12
  validateReleaseManifest
13
- } from "./chunk-msm046bp.js";
13
+ } from "./chunk-nf80yg42.js";
14
14
  import"./chunk-hagr56n9.js";
15
15
  import"./chunk-4030qem7.js";
16
16
  export {
@@ -4,7 +4,7 @@ import {
4
4
  connectWebSocket,
5
5
  startWorker,
6
6
  websocketLimits
7
- } from "./chunk-9eapbcfj.js";
7
+ } from "./chunk-tqfpxr6n.js";
8
8
  import {
9
9
  forwardingHeaders,
10
10
  leasedBody,
@@ -13,11 +13,11 @@ import {
13
13
  import {
14
14
  registryBase,
15
15
  validToken
16
- } from "./chunk-yhbhg39y.js";
16
+ } from "./chunk-h65ebvhk.js";
17
17
  import {
18
18
  inspectRelease,
19
19
  validDigest
20
- } from "./chunk-msm046bp.js";
20
+ } from "./chunk-nf80yg42.js";
21
21
  import {
22
22
  assertKeys,
23
23
  trustedProxyList,
@@ -1813,7 +1813,7 @@ async function serve(input) {
1813
1813
  }
1814
1814
  });
1815
1815
  if (options.control) {
1816
- const { startControlServer } = await import("./chunk-aqjnq95d.js");
1816
+ const { startControlServer } = await import("./chunk-44eb0x9t.js");
1817
1817
  control = await startControlServer(controller, options.control, token);
1818
1818
  }
1819
1819
  if (options.admin) {
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  checkApp
4
- } from "./chunk-7zgbtyr5.js";
4
+ } from "./chunk-rc52x59s.js";
5
5
  import"./chunk-hagr56n9.js";
6
6
  import"./chunk-4030qem7.js";
7
7
  export {
@@ -4,12 +4,12 @@ import {
4
4
  } from "./chunk-j6t4p7dt.js";
5
5
  import {
6
6
  validToken
7
- } from "./chunk-yhbhg39y.js";
7
+ } from "./chunk-h65ebvhk.js";
8
8
  import {
9
9
  defaultArchiveLimits,
10
10
  inspectRelease,
11
11
  validDigest
12
- } from "./chunk-msm046bp.js";
12
+ } from "./chunk-nf80yg42.js";
13
13
  import {
14
14
  assertKeys
15
15
  } from "./chunk-f3hsabcs.js";
@@ -3,7 +3,7 @@ import {
3
3
  inspectRelease,
4
4
  sha256Digest,
5
5
  validDigest
6
- } from "./chunk-msm046bp.js";
6
+ } from "./chunk-nf80yg42.js";
7
7
  import {
8
8
  MonoripperError
9
9
  } from "./chunk-4030qem7.js";
@@ -272,7 +272,7 @@ async function listFiles(directory, base = directory) {
272
272
  }
273
273
  async function pack(options) {
274
274
  const { loadApp } = await import("./chunk-qd2etnc4.js");
275
- const { checkApp } = await import("./chunk-kzks5b92.js");
275
+ const { checkApp } = await import("./chunk-dzsvdvrw.js");
276
276
  const { app, root } = await loadApp(options.app);
277
277
  if (options.label !== undefined && !/^[\x21-\x7e]{1,128}$/.test(options.label))
278
278
  fail("INVALID_ARGUMENT", "Invalid release label");
@@ -20,8 +20,16 @@ var canonical = (file) => {
20
20
  };
21
21
  var within = (file, root) => file === root || !relative(root, file).startsWith(".." + sep) && !relative(root, file).startsWith(sep) && relative(root, file) !== "..";
22
22
  var loadPackage = createRequire(import.meta.url);
23
+ function loadTypeScript() {
24
+ try {
25
+ loadPackage.resolve("typescript");
26
+ } catch {
27
+ throw new MonoripperError("MISSING_DEPENDENCY", "checkApp needs the typescript package; add it to your dependencies (tested with 5.9.3)");
28
+ }
29
+ return loadPackage("typescript");
30
+ }
23
31
  function checkApp(app, settings = {}) {
24
- const ts = loadPackage("typescript");
32
+ const ts = loadTypeScript();
25
33
  validateApp(app);
26
34
  const root = resolve(settings.root ?? process.cwd());
27
35
  const diagnostics = [];
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-j6t4p7dt.js";
5
5
  import {
6
6
  downloadRelease
7
- } from "./chunk-yhbhg39y.js";
7
+ } from "./chunk-h65ebvhk.js";
8
8
  import {
9
9
  assertCompatible,
10
10
  defaultArchiveLimits,
@@ -14,7 +14,7 @@ import {
14
14
  sha256Digest,
15
15
  validDigest,
16
16
  validateReleaseManifest
17
- } from "./chunk-msm046bp.js";
17
+ } from "./chunk-nf80yg42.js";
18
18
  import {
19
19
  MonoripperError
20
20
  } from "./chunk-4030qem7.js";
@@ -0,0 +1,463 @@
1
+ // @bun
2
+ // src/protobuf.ts
3
+ var message = (fields) => ({ fields });
4
+
5
+ class ProtobufError extends Error {
6
+ }
7
+ var utf8 = new TextEncoder;
8
+ var text = new TextDecoder;
9
+
10
+ class Writer {
11
+ parts = [];
12
+ varint(value) {
13
+ while (value > 0x7fn) {
14
+ this.parts.push(Number(value & 0x7fn) | 128);
15
+ value >>= 7n;
16
+ }
17
+ this.parts.push(Number(value));
18
+ }
19
+ bytes(value) {
20
+ this.varint(BigInt(value.length));
21
+ for (const byte of value)
22
+ this.parts.push(byte);
23
+ }
24
+ finish() {
25
+ return Uint8Array.from(this.parts);
26
+ }
27
+ }
28
+ function writeField(writer, no, type, value) {
29
+ if (typeof type === "object") {
30
+ writer.varint(BigInt(no << 3 | 2));
31
+ writer.bytes(encode(type, value));
32
+ return;
33
+ }
34
+ if (type === "string") {
35
+ writer.varint(BigInt(no << 3 | 2));
36
+ writer.bytes(utf8.encode(String(value)));
37
+ return;
38
+ }
39
+ writer.varint(BigInt(no << 3));
40
+ if (type === "bool")
41
+ writer.varint(value ? 1n : 0n);
42
+ else if (type === "uint32")
43
+ writer.varint(BigInt(Number(value) >>> 0));
44
+ else {
45
+ const number = Math.trunc(Number(value));
46
+ writer.varint(BigInt.asUintN(64, BigInt(Number.isFinite(number) ? number : 0)));
47
+ }
48
+ }
49
+ function encode(type, value) {
50
+ const writer = new Writer;
51
+ for (const [no, field] of Object.entries(type.fields)) {
52
+ const item = value[field.name];
53
+ if (item === undefined || item === null)
54
+ continue;
55
+ if (field.repeated) {
56
+ for (const entry of item)
57
+ writeField(writer, Number(no), field.type, entry);
58
+ } else
59
+ writeField(writer, Number(no), field.type, item);
60
+ }
61
+ return writer.finish();
62
+ }
63
+
64
+ class Reader {
65
+ buffer;
66
+ end;
67
+ offset = 0;
68
+ constructor(buffer, end = buffer.length) {
69
+ this.buffer = buffer;
70
+ this.end = end;
71
+ }
72
+ get done() {
73
+ return this.offset >= this.end;
74
+ }
75
+ varint() {
76
+ let result = 0n;
77
+ for (let shift = 0n;shift < 70n; shift += 7n) {
78
+ if (this.offset >= this.end)
79
+ throw new ProtobufError("Truncated varint");
80
+ const byte = this.buffer[this.offset++];
81
+ result |= BigInt(byte & 127) << shift;
82
+ if (byte < 128)
83
+ return BigInt.asUintN(64, result);
84
+ }
85
+ throw new ProtobufError("Varint is too long");
86
+ }
87
+ take(length) {
88
+ if (length > this.end - this.offset)
89
+ throw new ProtobufError("Truncated field");
90
+ const start = this.offset;
91
+ this.offset += length;
92
+ return this.buffer.subarray(start, this.offset);
93
+ }
94
+ skip(wire) {
95
+ if (wire === 0)
96
+ this.varint();
97
+ else if (wire === 1)
98
+ this.take(8);
99
+ else if (wire === 2)
100
+ this.take(Number(this.varint()));
101
+ else if (wire === 5)
102
+ this.take(4);
103
+ else
104
+ throw new ProtobufError(`Unsupported wire type ${wire}`);
105
+ }
106
+ }
107
+ var defaultOf = (field) => field.repeated ? [] : typeof field.type === "object" ? null : field.type === "string" ? "" : field.type === "bool" ? false : 0;
108
+ function read(reader, type, wire) {
109
+ if (typeof type === "object") {
110
+ if (wire !== 2)
111
+ throw new ProtobufError("Invalid wire type for message");
112
+ return decode(type, reader.take(Number(reader.varint())));
113
+ }
114
+ if (type === "string") {
115
+ if (wire !== 2)
116
+ throw new ProtobufError("Invalid wire type for string");
117
+ return text.decode(reader.take(Number(reader.varint())));
118
+ }
119
+ if (wire !== 0)
120
+ throw new ProtobufError(`Invalid wire type for ${type}`);
121
+ const value = reader.varint();
122
+ return type === "bool" ? value !== 0n : type === "uint32" ? Number(value & 0xffffffffn) : Number(value);
123
+ }
124
+ function decode(type, buffer) {
125
+ const reader = new Reader(buffer);
126
+ const out = {};
127
+ while (!reader.done) {
128
+ const key = reader.varint();
129
+ const no = Number(key >> 3n), wire = Number(key & 7n);
130
+ const field = no > 0 ? type.fields[no] : undefined;
131
+ if (!field) {
132
+ reader.skip(wire);
133
+ continue;
134
+ }
135
+ const value = read(reader, field.type, wire);
136
+ if (field.repeated)
137
+ (out[field.name] ??= []).push(value);
138
+ else
139
+ out[field.name] = value;
140
+ }
141
+ for (const field of Object.values(type.fields))
142
+ if (!(field.name in out) && !field.optional)
143
+ out[field.name] = defaultOf(field);
144
+ return out;
145
+ }
146
+
147
+ // src/control-protocol.ts
148
+ var Scope = message({ 1: { name: "project", type: "string" }, 2: { name: "environment", type: "string" } });
149
+ var SetContextRequest = message({
150
+ 1: { name: "project", type: "string" },
151
+ 2: { name: "environment", type: "string" },
152
+ 3: { name: "requestId", type: "string" },
153
+ 4: { name: "expectedRevision", type: "uint32", optional: true },
154
+ 5: { name: "context", type: "string" },
155
+ 6: { name: "replicas", type: "uint32", optional: true },
156
+ 7: { name: "release", type: "string", optional: true }
157
+ });
158
+ var OperationRequest = message({ 1: { name: "project", type: "string" }, 2: { name: "environment", type: "string" }, 3: { name: "id", type: "string" } });
159
+ var Failure = message({ 1: { name: "code", type: "string" }, 2: { name: "message", type: "string" } });
160
+ var Operation = message({
161
+ 1: { name: "id", type: "string" },
162
+ 2: { name: "requestId", type: "string" },
163
+ 3: { name: "context", type: "string" },
164
+ 4: { name: "replicas", type: "uint32" },
165
+ 5: { name: "revision", type: "uint32" },
166
+ 6: { name: "phase", type: "string" },
167
+ 7: { name: "createdAt", type: "uint64" },
168
+ 8: { name: "updatedAt", type: "uint64" },
169
+ 9: { name: "error", type: Failure },
170
+ 10: { name: "release", type: "string" },
171
+ 11: { name: "step", type: "string" },
172
+ 12: { name: "warning", type: Failure },
173
+ 13: { name: "origin", type: "string" }
174
+ });
175
+ var Worker = message({
176
+ 1: { name: "context", type: "string" },
177
+ 2: { name: "pid", type: "uint32" },
178
+ 3: { name: "ready", type: "bool" },
179
+ 4: { name: "draining", type: "bool" },
180
+ 5: { name: "release", type: "string" },
181
+ 6: { name: "node", type: "string" }
182
+ });
183
+ var Policy = message({ 1: { name: "min", type: "uint32" }, 2: { name: "max", type: "uint32" }, 3: { name: "targetInFlight", type: "uint32" } });
184
+ var Context = message({
185
+ 1: { name: "name", type: "string" },
186
+ 2: { name: "desiredReplicas", type: "uint32" },
187
+ 3: { name: "readyReplicas", type: "uint32" },
188
+ 4: { name: "restarts", type: "uint32" },
189
+ 5: { name: "error", type: Failure },
190
+ 6: { name: "release", type: "string" },
191
+ 7: { name: "servingRelease", type: "string" },
192
+ 8: { name: "lastGoodRelease", type: "string" },
193
+ 9: { name: "autoscale", type: Policy }
194
+ });
195
+ var Node = message({
196
+ 1: { name: "id", type: "string" },
197
+ 2: { name: "healthy", type: "bool" },
198
+ 3: { name: "maxReplicas", type: "uint32" },
199
+ 4: { name: "replicas", type: "uint32" },
200
+ 5: { name: "lastSeenMs", type: "uint64" }
201
+ });
202
+ var Status = message({
203
+ 1: { name: "project", type: "string" },
204
+ 2: { name: "environment", type: "string" },
205
+ 3: { name: "revision", type: "uint32" },
206
+ 4: { name: "persistent", type: "bool" },
207
+ 5: { name: "healthy", type: "bool" },
208
+ 6: { name: "contexts", type: Context, repeated: true },
209
+ 7: { name: "workers", type: Worker, repeated: true },
210
+ 8: { name: "nodes", type: Node, repeated: true }
211
+ });
212
+ var SetAutoscaleRequest = message({
213
+ 1: { name: "project", type: "string" },
214
+ 2: { name: "environment", type: "string" },
215
+ 3: { name: "context", type: "string" },
216
+ 4: { name: "policy", type: Policy }
217
+ });
218
+ var AutoscaleResult = message({ 1: { name: "context", type: "string" }, 2: { name: "policy", type: Policy }, 3: { name: "revision", type: "uint32" } });
219
+ var method = (name, request, response) => ({ path: `/monoripper.v1.Control/${name}`, request, response });
220
+ var controlService = {
221
+ SetContext: method("SetContext", SetContextRequest, Operation),
222
+ GetStatus: method("GetStatus", Scope, Status),
223
+ GetOperation: method("GetOperation", OperationRequest, Operation),
224
+ SetAutoscale: method("SetAutoscale", SetAutoscaleRequest, AutoscaleResult)
225
+ };
226
+
227
+ // src/grpc.ts
228
+ import http2 from "http2";
229
+ var status = {
230
+ OK: 0,
231
+ CANCELLED: 1,
232
+ UNKNOWN: 2,
233
+ INVALID_ARGUMENT: 3,
234
+ DEADLINE_EXCEEDED: 4,
235
+ NOT_FOUND: 5,
236
+ ALREADY_EXISTS: 6,
237
+ PERMISSION_DENIED: 7,
238
+ RESOURCE_EXHAUSTED: 8,
239
+ FAILED_PRECONDITION: 9,
240
+ ABORTED: 10,
241
+ OUT_OF_RANGE: 11,
242
+ UNIMPLEMENTED: 12,
243
+ INTERNAL: 13,
244
+ UNAVAILABLE: 14,
245
+ DATA_LOSS: 15,
246
+ UNAUTHENTICATED: 16
247
+ };
248
+ var statusNames = Object.fromEntries(Object.entries(status).map(([name, code]) => [code, name]));
249
+ var maxMessageBytes = 1024 * 1024;
250
+
251
+ class GrpcError extends Error {
252
+ code;
253
+ details;
254
+ constructor(code, details) {
255
+ super(`${code} ${statusNames[code] ?? "UNKNOWN"}: ${details}`);
256
+ this.code = code;
257
+ this.details = details;
258
+ }
259
+ }
260
+ function frame(payload) {
261
+ const out = Buffer.alloc(5 + payload.length);
262
+ out.writeUInt32BE(payload.length, 1);
263
+ out.set(payload, 5);
264
+ return out;
265
+ }
266
+ function unframe(body) {
267
+ if (body.length < 5)
268
+ throw new GrpcError(status.INTERNAL, "Missing gRPC message");
269
+ if (body[0] !== 0)
270
+ throw new GrpcError(status.UNIMPLEMENTED, "Compressed gRPC messages are not supported");
271
+ if (body.readUInt32BE(1) !== body.length - 5)
272
+ throw new GrpcError(status.INTERNAL, "Expected exactly one gRPC message");
273
+ return body.subarray(5);
274
+ }
275
+ var encodeText = (text2) => [...Buffer.from(text2)].map((byte) => byte >= 32 && byte <= 126 && byte !== 37 ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
276
+ var decodeText = (text2) => {
277
+ try {
278
+ return decodeURIComponent(text2);
279
+ } catch {
280
+ return text2;
281
+ }
282
+ };
283
+ var units = { H: 3600000, M: 60000, S: 1000, m: 1, u: 0.001, n: 0.000001 };
284
+ function collect(stream, overflow) {
285
+ const chunks = [];
286
+ let size = 0;
287
+ stream.on("data", (chunk) => {
288
+ size += chunk.length;
289
+ if (size > maxMessageBytes + 5)
290
+ overflow();
291
+ else
292
+ chunks.push(chunk);
293
+ });
294
+ return () => Buffer.concat(chunks);
295
+ }
296
+ async function listenGrpc(options) {
297
+ const routes = new Map(options.methods.map(([method2, handle]) => [method2.path, { method: method2, handle }]));
298
+ const sessions = new Set;
299
+ const server = options.tls ? http2.createSecureServer({ cert: options.tls.cert, key: options.tls.key }) : http2.createServer();
300
+ server.on("session", (session) => {
301
+ sessions.add(session);
302
+ session.on("close", () => sessions.delete(session));
303
+ session.on("error", () => {});
304
+ });
305
+ server.on("stream", (stream, headers) => {
306
+ stream.on("error", () => {});
307
+ let finished = false;
308
+ const finish = (code, details, payload) => {
309
+ if (finished || stream.destroyed)
310
+ return;
311
+ finished = true;
312
+ clearTimeout(timer);
313
+ stream.respond({ ":status": 200, "content-type": "application/grpc+proto" }, { waitForTrailers: true });
314
+ stream.once("wantTrailers", () => stream.sendTrailers(code === status.OK ? { "grpc-status": "0" } : { "grpc-status": String(code), "grpc-message": encodeText(details) }));
315
+ stream.end(payload && frame(payload));
316
+ };
317
+ stream.on("close", () => {
318
+ finished = true;
319
+ clearTimeout(timer);
320
+ });
321
+ const timeout = String(headers["grpc-timeout"] ?? "").match(/^([0-9]{1,8})([HMSmun])$/);
322
+ const timer = timeout ? setTimeout(() => finish(status.DEADLINE_EXCEEDED, "Deadline exceeded"), Math.min(Number(timeout[1]) * units[timeout[2]], 2147483647)) : undefined;
323
+ if (!String(headers["content-type"] ?? "").startsWith("application/grpc")) {
324
+ finished = true;
325
+ clearTimeout(timer);
326
+ stream.respond({ ":status": 415 }, { endStream: true });
327
+ return;
328
+ }
329
+ const route = headers[":method"] === "POST" ? routes.get(String(headers[":path"])) : undefined;
330
+ if (!route) {
331
+ finish(status.UNIMPLEMENTED, `Method not found: ${headers[":path"]}`);
332
+ return;
333
+ }
334
+ const body = collect(stream, () => finish(status.RESOURCE_EXHAUSTED, "Request message is larger than 1 MiB"));
335
+ stream.on("end", () => {
336
+ if (finished)
337
+ return;
338
+ Promise.resolve().then(() => {
339
+ let request;
340
+ try {
341
+ request = decode(route.method.request, unframe(body()));
342
+ } catch (error) {
343
+ throw error instanceof GrpcError ? error : new GrpcError(status.INTERNAL, "Error deserializing request");
344
+ }
345
+ return route.handle(request, headers);
346
+ }).then((value) => finish(status.OK, "", encode(route.method.response, value)), (error) => finish(error instanceof GrpcError ? error.code : status.INTERNAL, error instanceof GrpcError ? error.details : "Internal error"));
347
+ });
348
+ });
349
+ try {
350
+ await new Promise((resolve, reject) => {
351
+ server.once("error", reject);
352
+ server.listen(options.port, options.host, () => {
353
+ server.off("error", reject);
354
+ resolve();
355
+ });
356
+ });
357
+ } catch (error) {
358
+ server.close();
359
+ throw error;
360
+ }
361
+ return {
362
+ port: server.address().port,
363
+ close() {
364
+ for (const session of sessions)
365
+ session.destroy();
366
+ server.close();
367
+ }
368
+ };
369
+ }
370
+ var httpStatusCode = (code) => code === 400 ? status.INTERNAL : code === 401 ? status.UNAUTHENTICATED : code === 403 ? status.PERMISSION_DENIED : code === 404 ? status.UNIMPLEMENTED : [429, 502, 503, 504].includes(code) ? status.UNAVAILABLE : status.UNKNOWN;
371
+ function connectGrpc(options) {
372
+ const url = `${options.tls ? "https" : "http"}://${options.host}:${options.port}`;
373
+ const authority = options.tls?.serverName ?? `${options.host}:${options.port}`;
374
+ let session;
375
+ let closed = false;
376
+ function connect() {
377
+ if (session && !session.closed && !session.destroyed)
378
+ return session;
379
+ const created = http2.connect(url, options.tls ? { ...options.tls.ca ? { ca: options.tls.ca } : {}, ...options.tls.serverName ? { servername: options.tls.serverName } : {} } : {});
380
+ created.on("error", () => {});
381
+ created.on("close", () => {
382
+ if (session === created)
383
+ session = undefined;
384
+ });
385
+ return session = created;
386
+ }
387
+ return {
388
+ call(method2, request, headers, timeoutMs) {
389
+ if (closed)
390
+ return Promise.reject(new GrpcError(status.UNAVAILABLE, "Control client is closed"));
391
+ return new Promise((resolve, reject) => {
392
+ let stream;
393
+ try {
394
+ stream = connect().request({
395
+ ":method": "POST",
396
+ ":path": method2.path,
397
+ ":authority": authority,
398
+ "content-type": "application/grpc+proto",
399
+ te: "trailers",
400
+ "grpc-timeout": timeoutMs <= 99999999 ? `${timeoutMs}m` : `${Math.ceil(timeoutMs / 1000)}S`,
401
+ ...headers
402
+ });
403
+ } catch (error) {
404
+ reject(new GrpcError(status.UNAVAILABLE, error instanceof Error ? error.message : "Cannot start the call"));
405
+ return;
406
+ }
407
+ let settled = false;
408
+ const fail = (code, details) => {
409
+ if (settled)
410
+ return;
411
+ settled = true;
412
+ clearTimeout(timer);
413
+ stream.close(http2.constants.NGHTTP2_CANCEL);
414
+ reject(new GrpcError(code, details));
415
+ };
416
+ const timer = setTimeout(() => fail(status.DEADLINE_EXCEEDED, "Deadline exceeded"), timeoutMs);
417
+ let httpStatus, grpcStatus, grpcMessage = "";
418
+ const take = (received) => {
419
+ if (received["grpc-status"] === undefined)
420
+ return;
421
+ const code = Number(received["grpc-status"]);
422
+ grpcStatus = Number.isInteger(code) && code >= 0 && code <= 16 ? code : status.UNKNOWN;
423
+ grpcMessage = decodeText(String(received["grpc-message"] ?? ""));
424
+ };
425
+ stream.on("response", (received) => {
426
+ httpStatus = Number(received[":status"]);
427
+ take(received);
428
+ });
429
+ stream.on("trailers", take);
430
+ const body = collect(stream, () => fail(status.RESOURCE_EXHAUSTED, "Response message is larger than 1 MiB"));
431
+ stream.on("error", (error) => fail(status.UNAVAILABLE, error.message));
432
+ stream.on("close", () => {
433
+ if (settled)
434
+ return;
435
+ if (httpStatus === undefined)
436
+ return fail(status.UNAVAILABLE, "Connection to the control server failed");
437
+ if (httpStatus !== 200)
438
+ return fail(httpStatusCode(httpStatus), `Received HTTP status code ${httpStatus}`);
439
+ if (grpcStatus === undefined)
440
+ return fail(status.INTERNAL, "Server ended the call without a status");
441
+ if (grpcStatus !== status.OK)
442
+ return fail(grpcStatus, grpcMessage);
443
+ let value;
444
+ try {
445
+ value = decode(method2.response, unframe(body()));
446
+ } catch {
447
+ return fail(status.INTERNAL, "Failed to parse server response");
448
+ }
449
+ settled = true;
450
+ clearTimeout(timer);
451
+ resolve(value);
452
+ });
453
+ stream.end(frame(encode(method2.request, request)));
454
+ });
455
+ },
456
+ close() {
457
+ closed = true;
458
+ session?.close();
459
+ }
460
+ };
461
+ }
462
+
463
+ export { controlService, status, GrpcError, listenGrpc, connectGrpc };
@@ -1,13 +1,13 @@
1
1
  // @bun
2
2
  import {
3
+ connectGrpc,
3
4
  controlService
4
- } from "./chunk-mdnseqsw.js";
5
+ } from "./chunk-xa5bwvyr.js";
5
6
  import {
6
7
  MonoripperError
7
8
  } from "./chunk-4030qem7.js";
8
9
 
9
10
  // src/control-client.ts
10
- import * as grpc from "@grpc/grpc-js";
11
11
  function compact(value, keys) {
12
12
  const out = { ...value };
13
13
  for (const key of keys)
@@ -32,18 +32,10 @@ function createControlClient(options) {
32
32
  const timeout = options.timeoutMs ?? 5000;
33
33
  if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2147483647)
34
34
  throw new MonoripperError("INVALID_CONFIG", "Invalid control timeout");
35
- const credentials2 = options.tls ? grpc.credentials.createSsl(options.tls.ca ? Buffer.from(options.tls.ca) : null) : grpc.credentials.createInsecure();
36
- const client = new grpc.Client(`${address[1]}:${Number(address[2])}`, credentials2, {
37
- "grpc.max_receive_message_length": 1024 * 1024,
38
- ...options.tls?.serverName ? { "grpc.ssl_target_name_override": options.tls.serverName, "grpc.default_authority": options.tls.serverName } : {}
39
- });
40
- const metadata = new grpc.Metadata;
41
- metadata.set("authorization", `Bearer ${options.token}`);
35
+ const client = connectGrpc({ host: address[1], port: Number(address[2]), ...options.tls ? { tls: options.tls } : {} });
36
+ const metadata = { authorization: `Bearer ${options.token}` };
42
37
  const scope = { project: options.project, environment: options.environment ?? "development" };
43
- function call(method, input) {
44
- const definition = controlService[method];
45
- return new Promise((resolve, reject) => client.makeUnaryRequest(definition.path, definition.requestSerialize, definition.responseDeserialize, input, metadata, { deadline: Date.now() + timeout }, (error, value) => error ? reject(error) : resolve(value)));
46
- }
38
+ const call = async (method, input) => await client.call(controlService[method], input, metadata, timeout);
47
39
  return {
48
40
  getStatus: async () => {
49
41
  const status = statusOf(await call("GetStatus", scope));
@@ -4,7 +4,7 @@ import {
4
4
  connectWebSocket,
5
5
  startWorker,
6
6
  websocketLimits
7
- } from "./chunk-9eapbcfj.js";
7
+ } from "./chunk-tqfpxr6n.js";
8
8
  import {
9
9
  forwardingHeaders,
10
10
  leasedBody,
@@ -14,10 +14,10 @@ import {
14
14
  import {
15
15
  registryBase,
16
16
  validToken
17
- } from "./chunk-yhbhg39y.js";
17
+ } from "./chunk-h65ebvhk.js";
18
18
  import {
19
19
  runtimeCompatibility
20
- } from "./chunk-msm046bp.js";
20
+ } from "./chunk-nf80yg42.js";
21
21
  import {
22
22
  assertKeys
23
23
  } from "./chunk-f3hsabcs.js";
package/dist/cli.js CHANGED
@@ -2,18 +2,18 @@
2
2
  // @bun
3
3
  import {
4
4
  serve
5
- } from "./chunk-4pf86ydk.js";
6
- import"./chunk-9eapbcfj.js";
5
+ } from "./chunk-drkhvkha.js";
6
+ import"./chunk-tqfpxr6n.js";
7
7
  import"./chunk-j6t4p7dt.js";
8
- import"./chunk-yhbhg39y.js";
9
- import"./chunk-msm046bp.js";
8
+ import"./chunk-h65ebvhk.js";
9
+ import"./chunk-nf80yg42.js";
10
10
  import {
11
11
  loadApp,
12
12
  loadRuntimeConfig
13
13
  } from "./chunk-f3hsabcs.js";
14
14
  import {
15
15
  checkApp
16
- } from "./chunk-7zgbtyr5.js";
16
+ } from "./chunk-rc52x59s.js";
17
17
  import"./chunk-hagr56n9.js";
18
18
  import {
19
19
  MonoripperError,
@@ -86,7 +86,7 @@ async function remote(command, args) {
86
86
  if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2147483647)
87
87
  throw new MonoripperError("INVALID_COMMAND", "Invalid --timeout-ms");
88
88
  const tls = values["ca-file"] || values["server-name"] || values.tls ? { ...values["ca-file"] ? { ca: await readFile(values["ca-file"], "utf8") } : {}, ...values["server-name"] ? { serverName: values["server-name"] } : {} } : undefined;
89
- const { createControlClient } = await import("./chunk-y4arjxzz.js");
89
+ const { createControlClient } = await import("./chunk-zg6pd8zx.js");
90
90
  const client = createControlClient({ address: values.controller, project: values.project, environment: values.environment, token, ...tls ? { tls } : {} });
91
91
  try {
92
92
  if (command === "status") {
@@ -166,7 +166,7 @@ async function main() {
166
166
  const { values: values2 } = parseArgs({ args, strict: true, options: { app: { type: "string" }, out: { type: "string" }, label: { type: "string" } } });
167
167
  if (!values2.app || !values2.out)
168
168
  throw new MonoripperError("INVALID_COMMAND", "Use pack --app <manifest> --out <release.tar.gz>");
169
- const { pack } = await import("./chunk-2yr46mcw.js");
169
+ const { pack } = await import("./chunk-6y5xjkrr.js");
170
170
  console.log(JSON.stringify(await pack({ app: values2.app, out: values2.out, ...values2.label ? { label: values2.label } : {} })));
171
171
  return;
172
172
  }
@@ -182,7 +182,7 @@ async function main() {
182
182
  const token = process.env[values2["token-env"] ?? "MONORIPPER_REGISTRY_TOKEN"];
183
183
  if (!token)
184
184
  throw new MonoripperError("INVALID_CONFIG", "Registry write credential environment variable is not set");
185
- const { publishRelease } = await import("./chunk-9fwg7ypt.js");
185
+ const { publishRelease } = await import("./chunk-55hr94ee.js");
186
186
  const result = await publishRelease({ url: values2.registry, token, ...values2["ca-file"] ? { ca: await readFile(values2["ca-file"], "utf8") } : {} }, new Uint8Array(await readFile(positionals[0])));
187
187
  const record = { schemaVersion: 1, project: result.project, digest: result.digest, ...result.label ? { label: result.label } : {}, bytes: result.bytes };
188
188
  if (values2.output)
@@ -265,10 +265,10 @@ async function longRunning(command, args) {
265
265
  throw new MonoripperError("INVALID_COMMAND", `Use ${command} --config <file>`);
266
266
  let service;
267
267
  if (command === "registry") {
268
- const { loadRegistryConfig, startRegistry } = await import("./chunk-yct4ca2y.js");
268
+ const { loadRegistryConfig, startRegistry } = await import("./chunk-fmcgpxee.js");
269
269
  service = await startRegistry(await loadRegistryConfig(values.config));
270
270
  } else {
271
- const { loadNodeConfig, startNode } = await import("./chunk-dymmzvy7.js");
271
+ const { loadNodeConfig, startNode } = await import("./chunk-zmrjvbwh.js");
272
272
  service = await startNode(await loadNodeConfig(values.config));
273
273
  }
274
274
  let stopping = false;
@@ -1,2 +1,13 @@
1
- import type { ServiceDefinition } from '@grpc/grpc-js';
2
- export declare const controlService: ServiceDefinition;
1
+ import { type MessageType } from './protobuf';
2
+ export interface ControlMethod {
3
+ path: string;
4
+ request: MessageType;
5
+ response: MessageType;
6
+ }
7
+ export declare const controlService: {
8
+ SetContext: ControlMethod;
9
+ GetStatus: ControlMethod;
10
+ GetOperation: ControlMethod;
11
+ SetAutoscale: ControlMethod;
12
+ };
13
+ export type ControlMethodName = keyof typeof controlService;
package/dist/grpc.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import http2 from 'node:http2';
2
+ import type { ControlMethod } from './control-protocol';
3
+ /** Unary gRPC over node:http2 (https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md). */
4
+ export declare const status: {
5
+ readonly OK: 0;
6
+ readonly CANCELLED: 1;
7
+ readonly UNKNOWN: 2;
8
+ readonly INVALID_ARGUMENT: 3;
9
+ readonly DEADLINE_EXCEEDED: 4;
10
+ readonly NOT_FOUND: 5;
11
+ readonly ALREADY_EXISTS: 6;
12
+ readonly PERMISSION_DENIED: 7;
13
+ readonly RESOURCE_EXHAUSTED: 8;
14
+ readonly FAILED_PRECONDITION: 9;
15
+ readonly ABORTED: 10;
16
+ readonly OUT_OF_RANGE: 11;
17
+ readonly UNIMPLEMENTED: 12;
18
+ readonly INTERNAL: 13;
19
+ readonly UNAVAILABLE: 14;
20
+ readonly DATA_LOSS: 15;
21
+ readonly UNAUTHENTICATED: 16;
22
+ };
23
+ /** Same shape as a grpc-js ServiceError: numeric `code`, `details`, and "<code> <NAME>: <details>" as the message. */
24
+ export declare class GrpcError extends Error {
25
+ readonly code: number;
26
+ readonly details: string;
27
+ constructor(code: number, details: string);
28
+ }
29
+ export type GrpcHandler = (request: Record<string, unknown>, headers: http2.IncomingHttpHeaders) => unknown;
30
+ export interface GrpcServer {
31
+ port: number;
32
+ close(): void;
33
+ }
34
+ export declare function listenGrpc(options: {
35
+ host: string;
36
+ port: number;
37
+ tls?: {
38
+ cert: Buffer;
39
+ key: Buffer;
40
+ };
41
+ methods: [ControlMethod, GrpcHandler][];
42
+ }): Promise<GrpcServer>;
43
+ export interface GrpcClient {
44
+ call(method: ControlMethod, request: object, headers: Record<string, string>, timeoutMs: number): Promise<Record<string, unknown>>;
45
+ close(): void;
46
+ }
47
+ /** `host` is a hostname, an IPv4 address or a bracketed IPv6 address. Without `tls` the connection is plaintext HTTP/2. */
48
+ export declare function connectGrpc(options: {
49
+ host: string;
50
+ port: number;
51
+ tls?: {
52
+ ca?: string;
53
+ serverName?: string;
54
+ };
55
+ }): GrpcClient;
package/dist/index.js CHANGED
@@ -4,18 +4,18 @@ import {
4
4
  requestContext,
5
5
  serve,
6
6
  services
7
- } from "./chunk-4pf86ydk.js";
8
- import"./chunk-9eapbcfj.js";
7
+ } from "./chunk-drkhvkha.js";
8
+ import"./chunk-tqfpxr6n.js";
9
9
  import"./chunk-j6t4p7dt.js";
10
- import"./chunk-yhbhg39y.js";
11
- import"./chunk-msm046bp.js";
10
+ import"./chunk-h65ebvhk.js";
11
+ import"./chunk-nf80yg42.js";
12
12
  import {
13
13
  loadConfig,
14
14
  loadRuntimeConfig
15
15
  } from "./chunk-f3hsabcs.js";
16
16
  import {
17
17
  checkApp
18
- } from "./chunk-7zgbtyr5.js";
18
+ } from "./chunk-rc52x59s.js";
19
19
  import"./chunk-hagr56n9.js";
20
20
  import {
21
21
  MonoripperError,
@@ -27,22 +27,22 @@ import {
27
27
  } from "./chunk-4030qem7.js";
28
28
  // src/index.ts
29
29
  async function connectControl(options) {
30
- const { createControlClient } = await import("./chunk-y4arjxzz.js");
30
+ const { createControlClient } = await import("./chunk-zg6pd8zx.js");
31
31
  return createControlClient(options);
32
32
  }
33
33
  async function pack(options) {
34
- return (await import("./chunk-2yr46mcw.js")).pack(options);
34
+ return (await import("./chunk-6y5xjkrr.js")).pack(options);
35
35
  }
36
36
  async function publishRelease(endpoint, archive) {
37
- return (await import("./chunk-9fwg7ypt.js")).publishRelease(endpoint, archive);
37
+ return (await import("./chunk-55hr94ee.js")).publishRelease(endpoint, archive);
38
38
  }
39
39
  async function startRegistry(config) {
40
- return (await import("./chunk-yct4ca2y.js")).startRegistry(config);
40
+ return (await import("./chunk-fmcgpxee.js")).startRegistry(config);
41
41
  }
42
42
  var defineRegistry = (config) => config;
43
43
  var defineNode = (config) => config;
44
44
  async function startNode(config) {
45
- return (await import("./chunk-dymmzvy7.js")).startNode(config);
45
+ return (await import("./chunk-zmrjvbwh.js")).startNode(config);
46
46
  }
47
47
  var monoripper = { serve };
48
48
  export {
@@ -0,0 +1,18 @@
1
+ /** Minimal proto3 codec for the control schema. Decoding matches @grpc/proto-loader with { defaults: true, longs: Number }. */
2
+ export type Scalar = 'string' | 'bool' | 'uint32' | 'uint64';
3
+ export interface Field {
4
+ name: string;
5
+ type: Scalar | MessageType;
6
+ optional?: boolean;
7
+ repeated?: boolean;
8
+ }
9
+ export interface MessageType {
10
+ fields: Record<number, Field>;
11
+ }
12
+ type Value = Record<string, unknown>;
13
+ export declare const message: (fields: Record<number, Field>) => MessageType;
14
+ export declare class ProtobufError extends Error {
15
+ }
16
+ export declare function encode(type: MessageType, value: Value): Uint8Array;
17
+ export declare function decode(type: MessageType, buffer: Uint8Array): Value;
18
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monoripper",
3
- "version": "0.1.0-prototype",
3
+ "version": "0.2.0-prototype",
4
4
  "description": "Run selected Bun.serve or Elysia application contexts in isolated Bun processes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -44,7 +44,7 @@
44
44
  "prepublishOnly": "bun run build",
45
45
  "test": "bun test tests",
46
46
  "typecheck": "tsc --noEmit",
47
- "build": "rm -rf dist && bun build src/index.ts src/cli.ts src/worker.ts src/pack-build.ts --target bun --external elysia --external @grpc/grpc-js --external @grpc/proto-loader --splitting --outdir dist --entry-naming '[name].js' --chunk-naming 'chunk-[hash].js' && cp src/control.proto dist/control.proto && tsc -p tsconfig.build.json",
47
+ "build": "rm -rf dist && bun build src/index.ts src/cli.ts src/worker.ts src/pack-build.ts --target bun --external elysia --splitting --outdir dist --entry-naming '[name].js' --chunk-naming 'chunk-[hash].js' && cp src/control.proto dist/control.proto && tsc -p tsconfig.build.json",
48
48
  "check:specs": "python3 scripts/check-specs.py",
49
49
  "test:elysia": "bun scripts/test-elysia.ts",
50
50
  "test:elysia:postgres": "bun scripts/test-elysia-postgres.ts",
@@ -54,23 +54,25 @@
54
54
  "test:autobahn": "bun tests/autobahn/run.ts",
55
55
  "nix:lock": "bun2nix -o bun.nix"
56
56
  },
57
- "dependencies": {
58
- "@grpc/grpc-js": "1.14.6",
59
- "@grpc/proto-loader": "0.8.1",
60
- "typescript": "5.9.3"
61
- },
62
57
  "peerDependencies": {
63
- "elysia": "1.4.30"
58
+ "elysia": "1.4.30",
59
+ "typescript": "^5.9.3"
64
60
  },
65
61
  "peerDependenciesMeta": {
66
62
  "elysia": {
67
63
  "optional": true
64
+ },
65
+ "typescript": {
66
+ "optional": true
68
67
  }
69
68
  },
70
69
  "devDependencies": {
71
- "elysia": "1.4.30",
70
+ "@grpc/grpc-js": "1.14.6",
71
+ "@grpc/proto-loader": "0.8.1",
72
72
  "@types/bun": "1.3.13",
73
- "embedded-postgres": "18.4.0-beta.17"
73
+ "elysia": "1.4.30",
74
+ "embedded-postgres": "18.4.0-beta.17",
75
+ "typescript": "5.9.3"
74
76
  },
75
77
  "trustedDependencies": [
76
78
  "@embedded-postgres/linux-x64"
@@ -1,82 +0,0 @@
1
- // @bun
2
- import {
3
- controlService
4
- } from "./chunk-mdnseqsw.js";
5
- import {
6
- MonoripperError
7
- } from "./chunk-4030qem7.js";
8
-
9
- // src/grpc-server.ts
10
- import * as grpc from "@grpc/grpc-js";
11
- import { timingSafeEqual } from "crypto";
12
- import { readFileSync } from "fs";
13
- var codes = {
14
- INVALID_ARGUMENT: grpc.status.INVALID_ARGUMENT,
15
- INVALID_CONFIG: grpc.status.INVALID_ARGUMENT,
16
- PERMISSION_DENIED: grpc.status.PERMISSION_DENIED,
17
- CONFLICT: grpc.status.ABORTED,
18
- BUSY: grpc.status.FAILED_PRECONDITION,
19
- ALREADY_EXISTS: grpc.status.ALREADY_EXISTS,
20
- NOT_FOUND: grpc.status.NOT_FOUND,
21
- CAPACITY_EXCEEDED: grpc.status.RESOURCE_EXHAUSTED,
22
- SHUTTING_DOWN: grpc.status.UNAVAILABLE,
23
- STATE_UNAVAILABLE: grpc.status.UNAVAILABLE,
24
- STATE_WRITE_FAILED: grpc.status.UNAVAILABLE,
25
- UNIMPLEMENTED: grpc.status.UNIMPLEMENTED,
26
- RELEASES_DISABLED: grpc.status.FAILED_PRECONDITION,
27
- AUTOSCALE_ACTIVE: grpc.status.FAILED_PRECONDITION
28
- };
29
- async function startControlServer(controller, config, token) {
30
- const server = new grpc.Server({ "grpc.max_receive_message_length": 1024 * 1024 });
31
- const expected = Buffer.from(`Bearer ${token}`);
32
- function handler(run) {
33
- return (call, callback) => {
34
- const supplied = call.metadata.get("authorization");
35
- const received = Buffer.from(typeof supplied[0] === "string" ? supplied[0] : "");
36
- if (supplied.length !== 1 || received.length !== expected.length || !timingSafeEqual(received, expected)) {
37
- callback({ code: grpc.status.UNAUTHENTICATED, message: "Invalid control credential" });
38
- return;
39
- }
40
- const scope = controller.status();
41
- if (call.request.project !== scope.project || call.request.environment !== scope.environment) {
42
- callback({ code: grpc.status.PERMISSION_DENIED, message: "Wrong project or environment" });
43
- return;
44
- }
45
- Promise.resolve().then(() => run(call.request)).then((value) => callback(null, value), (error) => {
46
- callback({
47
- code: error instanceof MonoripperError ? codes[error.code] ?? grpc.status.INTERNAL : grpc.status.INTERNAL,
48
- message: error instanceof MonoripperError ? error.message : "Control request failed"
49
- });
50
- });
51
- };
52
- }
53
- server.addService(controlService, {
54
- SetContext: handler((input) => controller.set({
55
- project: input.project,
56
- environment: input.environment,
57
- requestId: input.requestId,
58
- context: input.context,
59
- expectedRevision: input.expectedRevision,
60
- ...input.replicas !== undefined && input.replicas !== null ? { replicas: input.replicas } : {},
61
- ...input.release ? { release: input.release } : {}
62
- })),
63
- GetStatus: handler(() => controller.status()),
64
- GetOperation: handler((input) => controller.operation(input.id)),
65
- SetAutoscale: handler((input) => controller.setAutoscale({ project: input.project, environment: input.environment, context: input.context, ...input.policy ? { policy: input.policy } : {} }))
66
- });
67
- const host = config.host ?? "127.0.0.1";
68
- if (!config.tls && !["127.0.0.1", "::1"].includes(host))
69
- throw new MonoripperError("INVALID_CONFIG", "Control without TLS permits loopback only");
70
- const bracketed = host.includes(":") ? `[${host}]` : host;
71
- const credentials = config.tls ? grpc.ServerCredentials.createSsl(null, [{ cert_chain: readFileSync(config.tls.certFile), private_key: readFileSync(config.tls.keyFile) }]) : grpc.ServerCredentials.createInsecure();
72
- try {
73
- const port = await new Promise((resolve, reject) => server.bindAsync(`${bracketed}:${config.port ?? 50051}`, credentials, (error, port2) => error ? reject(error) : resolve(port2)));
74
- return { address: `${bracketed}:${port}`, close: () => server.forceShutdown() };
75
- } catch (error) {
76
- server.forceShutdown();
77
- throw error;
78
- }
79
- }
80
- export {
81
- startControlServer
82
- };
@@ -1,15 +0,0 @@
1
- // @bun
2
- // src/control-protocol.ts
3
- import { loadSync } from "@grpc/proto-loader";
4
- import { fileURLToPath } from "url";
5
- var definitions = loadSync(fileURLToPath(new URL("./control.proto", import.meta.url)), {
6
- keepCase: false,
7
- longs: Number,
8
- enums: String,
9
- defaults: true,
10
- oneofs: true,
11
- arrays: true
12
- });
13
- var controlService = definitions["monoripper.v1.Control"];
14
-
15
- export { controlService };