@brickkit/effect 0.16.0-beta.7 → 0.16.0-beta.8

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.
@@ -115,6 +115,8 @@ const SPAN = {
115
115
  actionPrefix: "action ",
116
116
  /** `rpc <service>.<action>` */
117
117
  rpcPrefix: "rpc ",
118
+ /** `socket <service>.<name>`: a raw socket connection, from upgrade to close. */
119
+ socketPrefix: "socket ",
118
120
  exceptionEvent: "exception",
119
121
  /** The span event a `ctx.logger` line becomes. */
120
122
  logEvent: "log"
@@ -139,6 +141,12 @@ const ATTR = {
139
141
  scheduleAttempt: "brick.schedule.attempt",
140
142
  scheduleSlot: "brick.schedule.slot",
141
143
  scheduleOutcome: "brick.schedule.outcome",
144
+ /** A raw socket connection: its route name, id, frames and bytes received, and close code. */
145
+ socketName: "brick.socket.name",
146
+ socketId: "brick.socket.id",
147
+ socketMessages: "brick.socket.messages",
148
+ socketBytes: "brick.socket.bytes",
149
+ socketCloseCode: "brick.socket.close_code",
142
150
  traceId: "brick.trace_id",
143
151
  errorCode: "brick.error.code",
144
152
  errorMessage: "brick.error.message",
@@ -541,6 +549,46 @@ function traceRequest(request, method, route, body) {
541
549
  }, (span) => body(span).pipe(Effect.withParentSpan(span, { captureStackTrace: false })));
542
550
  }
543
551
  /**
552
+ * Start `name` as a server span for a WebSocket upgrade, continuing the
553
+ * caller's trace when a W3C `traceparent` arrives. It stays open until `end`,
554
+ * so it is made by hand: `Effect.useSpan` would end it with its first callback.
555
+ */
556
+ function startSocketSpan(name, request, attributes, tracer = brickTracer) {
557
+ const parent = externalParent(request.headers.get("traceparent"));
558
+ const span = tracer.span({
559
+ name,
560
+ parent: parent ? Option.some(parent) : Option.none(),
561
+ annotations: Context.empty(),
562
+ links: [],
563
+ startTime: nowNanos(),
564
+ kind: "server",
565
+ root: !parent,
566
+ sampled: parent?.sampled ?? true
567
+ });
568
+ const record = (values) => {
569
+ for (const [key, value] of Object.entries(values)) span.attribute(key, value);
570
+ };
571
+ record({
572
+ [ATTR.httpMethod]: "GET",
573
+ [ATTR.urlPath]: new URL(request.url).pathname,
574
+ ...attributes
575
+ });
576
+ return {
577
+ span,
578
+ link(traceparent) {
579
+ const linked = externalParent(traceparent);
580
+ if (linked) span.addLinks([{
581
+ span: linked,
582
+ attributes: {}
583
+ }]);
584
+ },
585
+ end(final, failure) {
586
+ record(final);
587
+ span.end(nowNanos(), failure === void 0 ? Exit.void : Exit.die(failure));
588
+ }
589
+ };
590
+ }
591
+ /**
544
592
  * Wrap a raw route handler so each of its requests gets a server span in
545
593
  * Brick's span store (`spanStore`, which `brick dev` and the dashboard read).
546
594
  * For routes you serve yourself around `app.fetch`: they are outside actions
@@ -3921,6 +3969,8 @@ const SOCKET_CONTROL = {
3921
3969
  const isControlEvent = (event) => event.startsWith("$");
3922
3970
  const SOCKET_CLOSE = {
3923
3971
  normal: 1e3,
3972
+ /** The server is draining: a raw socket still open at the drain deadline. */
3973
+ goingAway: 1001,
3924
3974
  unsupportedData: 1003,
3925
3975
  invalidPayload: 1007,
3926
3976
  policy: 1008,
@@ -4178,6 +4228,368 @@ function socketPath(prefix, service, { schema: { name, path } }) {
4178
4228
  const base = `${prefix.replace(/\/$/, "")}/${kebabCase(service)}`;
4179
4229
  return path === void 0 ? `${base}/${kebabCase(name)}` : `${base}${path === "/" ? "" : path}`;
4180
4230
  }
4231
+ // src/raw-socket.ts
4232
+ /** Frames one connection may have waiting for its handlers. */
4233
+ const RAW_QUEUE_FRAMES = 1024;
4234
+ /** After the drain deadline closes what is left with 1001, time for their `close` callbacks. */
4235
+ const DRAIN_CLOSE_GRACE_MS = 1e3;
4236
+ function defineRawSocket(config, resolve) {
4237
+ if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
4238
+ if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static route (relative to its service) without a query or fragment");
4239
+ if (config.schema && config.parse) throw new Error("A raw socket takes a schema or a parse, not both");
4240
+ const positive = (value, what) => {
4241
+ if (value !== void 0 && !(Number.isInteger(value) && value > 0)) throw new Error(`Raw socket ${what} must be a positive integer`);
4242
+ };
4243
+ positive(config.maxConnections, "maxConnections");
4244
+ positive(config.maxPayloadBytes, "maxPayloadBytes");
4245
+ if (config.preAuth && !(config.preAuth.timeoutMs > 0 && Number.isFinite(config.preAuth.timeoutMs))) throw new Error("Raw socket preAuth.timeoutMs must be a positive number");
4246
+ const decodeJson = config.schema && Schema.decodeUnknownOption(Schema.toCodecJson(config.schema));
4247
+ const mounts = /* @__PURE__ */ new Set();
4248
+ return {
4249
+ schema: {
4250
+ name: config.name,
4251
+ path: config.path
4252
+ },
4253
+ config,
4254
+ maxPayloadBytes: config.maxPayloadBytes ?? 65536,
4255
+ max: config.maxConnections,
4256
+ mounts,
4257
+ handle: {
4258
+ get live() {
4259
+ let live = 0;
4260
+ for (const mount of mounts) live += mount.live;
4261
+ return live;
4262
+ },
4263
+ max: config.maxConnections
4264
+ },
4265
+ decode: decodeJson && ((value) => {
4266
+ const decoded = decodeJson(value);
4267
+ return decoded._tag === "Some" ? { value: decoded.value } : void 0;
4268
+ }),
4269
+ resolve
4270
+ };
4271
+ }
4272
+ /** Turns a failed run into what its callbacks threw: the typed failure, else the defect. */
4273
+ function thrown(cause) {
4274
+ const found = Cause.findError(cause);
4275
+ if (Result.isSuccess(found)) return found.success;
4276
+ const defect = Cause.findDefect(cause);
4277
+ return Result.isSuccess(defect) ? defect.success : Cause.squash(cause);
4278
+ }
4279
+ /**
4280
+ * Mounts the raw routes of the services: each answers a plain WebSocket upgrade
4281
+ * (no subprotocol, no `brick.v1`) and hands its callbacks the frames exactly as
4282
+ * the client sent them. One context is resolved at upgrade and reused for every
4283
+ * callback.
4284
+ */
4285
+ function mountRawSockets(options) {
4286
+ const { run, telemetry } = options;
4287
+ let tracer;
4288
+ const appTracer = () => tracer ??= run(Effect.tracer).then((exit) => Exit.isSuccess(exit) ? exit.value : void 0);
4289
+ const routes = options.services.flatMap((service) => service.listRawSockets().map((definition) => ({
4290
+ service: service.name,
4291
+ path: socketPath(options.prefix, service.name, definition),
4292
+ definition,
4293
+ live: 0,
4294
+ pending: 0,
4295
+ connections: /* @__PURE__ */ new Set()
4296
+ })));
4297
+ const byPath = /* @__PURE__ */ new Map();
4298
+ for (const route of routes) {
4299
+ if (byPath.has(route.path)) throw new Error(`Brick: duplicate socket route '${route.path}'`);
4300
+ byPath.set(route.path, route);
4301
+ }
4302
+ let draining = false;
4303
+ const quiet = /* @__PURE__ */ new Set();
4304
+ const total = () => routes.reduce((n, r) => n + r.live + r.pending, 0);
4305
+ const settled = () => {
4306
+ if (!total()) for (const wake of quiet) wake();
4307
+ };
4308
+ /** Resolves once no connection is open or upgrading, or after `ms`. */
4309
+ const empty = (ms) => total() === 0 ? Promise.resolve() : new Promise((resolve) => {
4310
+ const done = () => {
4311
+ clearTimeout(timer);
4312
+ quiet.delete(done);
4313
+ resolve();
4314
+ };
4315
+ const timer = setTimeout(done, ms);
4316
+ quiet.add(done);
4317
+ });
4318
+ let drained;
4319
+ const drain = (timeoutMs = options.drainTimeoutMs) => drained ??= (async () => {
4320
+ draining = true;
4321
+ await empty(timeoutMs);
4322
+ for (const route of routes) for (const connection of route.connections) connection.close(SOCKET_CLOSE.goingAway, "Server is shutting down");
4323
+ await empty(DRAIN_CLOSE_GRACE_MS);
4324
+ })();
4325
+ const stats = () => {
4326
+ const capped = routes.length > 0 && routes.every((r) => r.definition.max);
4327
+ return {
4328
+ draining,
4329
+ live: routes.reduce((n, r) => n + r.live, 0),
4330
+ ...capped ? { max: routes.reduce((n, r) => n + r.definition.max, 0) } : {},
4331
+ routes: routes.map((r) => ({
4332
+ service: r.service,
4333
+ name: r.definition.schema.name,
4334
+ path: r.path,
4335
+ live: r.live,
4336
+ ...r.definition.max ? { max: r.definition.max } : {}
4337
+ }))
4338
+ };
4339
+ };
4340
+ for (const route of routes) route.definition.mounts.add(route);
4341
+ const refuse = (status, text) => new Response(text, {
4342
+ status,
4343
+ headers: status === 503 ? { "Retry-After": "1" } : void 0
4344
+ });
4345
+ /** The handlers Bun calls for a connection of `route`, through `ws.data.mounted`. */
4346
+ const mountRoute = (route) => {
4347
+ const { service, path, definition } = route;
4348
+ const { config } = definition;
4349
+ const name = definition.schema.name;
4350
+ const origins = config.allowedOrigins ?? [];
4351
+ const fallbackLogger = createLogger();
4352
+ const traced = (conn, effect) => conn.span ? Effect.withParentSpan(effect, conn.span.span, { captureStackTrace: false }) : effect;
4353
+ /** A callback failed: the `error` hook decides, and by default the connection closes with 1011. */
4354
+ const failed = async (conn, at, cause) => {
4355
+ const error = thrown(cause);
4356
+ conn.failure ??= { error };
4357
+ const logger = conn.ctx?.logger ?? fallbackLogger;
4358
+ let outcome;
4359
+ try {
4360
+ if (config.error) {
4361
+ const hook = await run(traced(conn, config.error({
4362
+ ctx: conn.ctx,
4363
+ socket: conn.socket,
4364
+ error,
4365
+ phase: at
4366
+ })));
4367
+ if (Exit.isSuccess(hook)) outcome = hook.value;
4368
+ else if (!Cause.hasInterruptsOnly(hook.cause)) logger.error({
4369
+ error: thrown(hook.cause),
4370
+ service,
4371
+ socket: name
4372
+ });
4373
+ } else logger.error({
4374
+ error,
4375
+ service,
4376
+ socket: name,
4377
+ phase: at
4378
+ });
4379
+ } catch (hookError) {
4380
+ logger.error({
4381
+ error: hookError,
4382
+ service,
4383
+ socket: name
4384
+ });
4385
+ }
4386
+ if (outcome !== "continue" && at !== "close") conn.close(SOCKET_CLOSE.serverError, "Socket handler failed");
4387
+ };
4388
+ /** Runs `work` after the connection's earlier callbacks, in the connection's span. */
4389
+ const enqueue = (conn, phase, work, size = 0) => {
4390
+ conn.frames++;
4391
+ conn.queued += size;
4392
+ conn.tail = conn.tail.then(async () => {
4393
+ try {
4394
+ const at = typeof phase === "function" ? phase() : phase;
4395
+ const exit = await run(traced(conn, Effect.suspend(() => work() ?? Effect.void)));
4396
+ if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) await failed(conn, at, exit.cause);
4397
+ } finally {
4398
+ conn.frames--;
4399
+ conn.queued -= size;
4400
+ }
4401
+ });
4402
+ };
4403
+ /** The frame as `message` gets it, or the close it earns. */
4404
+ const decode = (raw) => {
4405
+ if (config.parse) return { data: config.parse(raw) };
4406
+ if (!definition.decode) return { data: raw };
4407
+ if (typeof raw !== "string") return {
4408
+ close: SOCKET_CLOSE.unsupportedData,
4409
+ reason: "Only JSON text is supported"
4410
+ };
4411
+ let json;
4412
+ try {
4413
+ json = JSON.parse(raw);
4414
+ } catch {
4415
+ return {
4416
+ close: SOCKET_CLOSE.invalidPayload,
4417
+ reason: "Invalid JSON"
4418
+ };
4419
+ }
4420
+ const decoded = definition.decode(json);
4421
+ return decoded ? { data: decoded.value } : {
4422
+ close: SOCKET_CLOSE.invalidPayload,
4423
+ reason: "Invalid message"
4424
+ };
4425
+ };
4426
+ const receive = (conn, raw) => {
4427
+ if (conn.closed) return;
4428
+ const { socket } = conn;
4429
+ const size = typeof raw === "string" ? Buffer.byteLength(raw) : raw.byteLength;
4430
+ conn.messages++;
4431
+ conn.bytes += size;
4432
+ if (size > definition.maxPayloadBytes) return conn.close(SOCKET_CLOSE.tooLarge, "Message too large");
4433
+ if (conn.frames >= RAW_QUEUE_FRAMES || conn.queued + size > Math.max(1048576, definition.maxPayloadBytes)) return conn.close(SOCKET_CLOSE.tryAgainLater, "Socket queue full");
4434
+ let decoded;
4435
+ try {
4436
+ decoded = decode(raw);
4437
+ } catch {
4438
+ return conn.close(SOCKET_CLOSE.invalidPayload, "Invalid message");
4439
+ }
4440
+ if ("close" in decoded) return conn.close(decoded.close, decoded.reason);
4441
+ const early = () => config.preAuth && !socket.authenticated ? "preAuth" : "message";
4442
+ enqueue(conn, early, () => {
4443
+ if (conn.ws.readyState !== 1) return;
4444
+ const frame = {
4445
+ data: decoded.data,
4446
+ ctx: conn.ctx,
4447
+ socket
4448
+ };
4449
+ return early() === "preAuth" ? config.preAuth.message(frame) : config.message(frame);
4450
+ }, size);
4451
+ };
4452
+ /** Gives up a slot taken at upgrade that never became a connection. */
4453
+ const abandon = (conn, status) => {
4454
+ route.pending--;
4455
+ conn.span?.end({ [ATTR.httpStatus]: status }, conn.failure?.error);
4456
+ settled();
4457
+ };
4458
+ const handlers = {
4459
+ open(ws) {
4460
+ const conn = ws.data.connection;
4461
+ conn.ws = ws;
4462
+ route.pending--;
4463
+ route.live++;
4464
+ route.connections.add(conn);
4465
+ if (config.preAuth) conn.deadline = setTimeout(() => conn.close(SOCKET_CLOSE.policy, "Authentication timeout"), config.preAuth.timeoutMs);
4466
+ if (config.open) enqueue(conn, "open", () => config.open({
4467
+ ctx: conn.ctx,
4468
+ socket: conn.socket
4469
+ }));
4470
+ },
4471
+ message(ws, value) {
4472
+ receive(ws.data.connection, value);
4473
+ },
4474
+ async close(ws, code, reason) {
4475
+ const conn = ws.data.connection;
4476
+ if (conn.closed) return;
4477
+ conn.closed = true;
4478
+ clearTimeout(conn.deadline);
4479
+ if (config.close) enqueue(conn, "close", () => config.close({
4480
+ ctx: conn.ctx,
4481
+ socket: conn.socket,
4482
+ code,
4483
+ reason
4484
+ }));
4485
+ await conn.tail;
4486
+ conn.span?.end({
4487
+ [ATTR.httpStatus]: 101,
4488
+ [ATTR.socketMessages]: conn.messages,
4489
+ [ATTR.socketBytes]: conn.bytes,
4490
+ [ATTR.socketCloseCode]: code
4491
+ }, conn.failure?.error);
4492
+ route.connections.delete(conn);
4493
+ route.live--;
4494
+ settled();
4495
+ }
4496
+ };
4497
+ return async (request, server) => {
4498
+ if (draining) return refuse(503, "Server is shutting down");
4499
+ const origin = request.headers.get("origin");
4500
+ if (origin && !origins.includes(origin)) return refuse(403, "Socket origin refused");
4501
+ if (definition.max !== void 0 && route.live + route.pending >= definition.max) return refuse(503, "Too many connections");
4502
+ route.pending++;
4503
+ const id = crypto.randomUUID();
4504
+ const span = telemetry ? startSocketSpan(`${SPAN.socketPrefix}${service}.${name}`, request, {
4505
+ [ATTR.httpRoute]: path,
4506
+ [ATTR.service]: service,
4507
+ [ATTR.socketName]: name,
4508
+ [ATTR.socketId]: id
4509
+ }, await appTracer()) : void 0;
4510
+ const conn = {
4511
+ ctx: void 0,
4512
+ span,
4513
+ closed: false,
4514
+ tail: Promise.resolve(),
4515
+ frames: 0,
4516
+ queued: 0,
4517
+ messages: 0,
4518
+ bytes: 0,
4519
+ socket: void 0,
4520
+ close: (code = SOCKET_CLOSE.normal, reason = "") => conn.ws?.close(code, reason)
4521
+ };
4522
+ let authenticated = !config.preAuth;
4523
+ const socket = {
4524
+ id,
4525
+ request,
4526
+ get authenticated() {
4527
+ return authenticated;
4528
+ },
4529
+ state: void 0,
4530
+ send: (data) => Effect.sync(() => !conn.closed && (conn.ws?.send(data) ?? 0) !== 0),
4531
+ close: (code, reason) => Effect.sync(() => conn.close(code, reason)),
4532
+ authenticate: (patch) => Effect.sync(() => {
4533
+ authenticated = true;
4534
+ clearTimeout(conn.deadline);
4535
+ if (patch) Object.assign(socket.state, patch);
4536
+ }),
4537
+ link: (traceparent) => Effect.sync(() => span?.link(traceparent))
4538
+ };
4539
+ conn.socket = socket;
4540
+ const upgrading = Effect.gen(function* () {
4541
+ conn.ctx = yield* definition.resolve(request);
4542
+ if (config.authorize && !(yield* config.authorize({
4543
+ ctx: conn.ctx,
4544
+ request
4545
+ }))) return 403;
4546
+ socket.state = (config.state ? yield* config.state({
4547
+ ctx: conn.ctx,
4548
+ request
4549
+ }) : void 0) ?? {};
4550
+ return draining ? 503 : void 0;
4551
+ });
4552
+ const exit = await run(traced(conn, upgrading));
4553
+ let status;
4554
+ if (Exit.isSuccess(exit)) status = exit.value;
4555
+ else {
4556
+ const error = thrown(exit.cause);
4557
+ conn.failure = { error };
4558
+ (conn.ctx?.logger ?? fallbackLogger).error({
4559
+ error,
4560
+ service,
4561
+ socket: name
4562
+ });
4563
+ status = 500;
4564
+ }
4565
+ if (status === void 0) try {
4566
+ status = server.upgrade(request, { data: {
4567
+ mounted: handlers,
4568
+ connection: conn
4569
+ } }) ? void 0 : 400;
4570
+ } catch {
4571
+ status = 400;
4572
+ }
4573
+ if (status !== void 0) {
4574
+ abandon(conn, status);
4575
+ return refuse(status, status === 403 ? "Socket connection refused" : status === 503 ? "Server is shutting down" : status === 400 ? "Socket upgrade failed" : "Socket connection failed");
4576
+ }
4577
+ };
4578
+ };
4579
+ const upgrades = new Map(routes.map((route) => [route, mountRoute(route)]));
4580
+ const find = (request) => request.method === "GET" && request.headers.get("upgrade")?.toLowerCase() === "websocket" ? byPath.get(new URL(request.url).pathname) : void 0;
4581
+ return {
4582
+ paths: [...byPath.keys()],
4583
+ maxPayloadBytes: Math.max(SOCKET_MAX_BYTES, ...routes.map(({ definition }) => definition.maxPayloadBytes)),
4584
+ matches: (request) => find(request) !== void 0,
4585
+ upgrade: (request, server) => upgrades.get(find(request))(request, server),
4586
+ drain,
4587
+ stats,
4588
+ dispose() {
4589
+ for (const route of routes) route.definition.mounts.delete(route);
4590
+ }
4591
+ };
4592
+ }
4181
4593
  // src/events/query.ts
4182
4594
  /** A drizzle query on an untyped `db`, as the Effect it is. */
4183
4595
  const query = (builder) => builder;
@@ -6172,6 +6584,9 @@ const seqAfter = (a, b) => {
6172
6584
  * broker with them, and builds the `Bun.serve` handlers that speak the
6173
6585
  * `brick.v1` protocol.
6174
6586
  *
6587
+ * `raw` brings the raw routes in: they share the route checks, the `websocket`
6588
+ * config and the close tracking, and are upgraded by the same `fetch`.
6589
+ *
6175
6590
  * @throws When two sockets share a route, a socket shares one with an action,
6176
6591
  * or a socket has replay and the broker has no history.
6177
6592
  */
@@ -6184,9 +6599,10 @@ function mountSockets(options) {
6184
6599
  path: socketPath(prefix, service.name, definition),
6185
6600
  definition
6186
6601
  })));
6187
- if (!sockets.length && !options.sockets) return void 0;
6602
+ const { raw } = options;
6603
+ if (!sockets.length && !raw?.paths.length && !options.sockets) return void 0;
6188
6604
  const taken = /* @__PURE__ */ new Set();
6189
- for (const { path } of sockets) {
6605
+ for (const path of [...sockets.map((socket) => socket.path), ...raw?.paths ?? []]) {
6190
6606
  if (taken.has(path)) throw new Error(`Brick: duplicate socket route '${path}'`);
6191
6607
  taken.add(path);
6192
6608
  }
@@ -6209,13 +6625,14 @@ function mountSockets(options) {
6209
6625
  const byPath = new Map(mounted.map(({ path, socket }) => [path, socket]));
6210
6626
  const find = (request) => request.method === "GET" && request.headers.get("upgrade")?.toLowerCase() === "websocket" ? byPath.get(new URL(request.url).pathname) : void 0;
6211
6627
  return {
6212
- matches: (request) => find(request) !== void 0,
6628
+ matches: (request) => find(request) !== void 0 || raw?.matches(request) === true,
6213
6629
  async upgrade(request, bun) {
6214
6630
  server = bun;
6215
- return find(request).upgrade(request, bun);
6631
+ const brickSocket = find(request);
6632
+ return brickSocket ? brickSocket.upgrade(request, bun) : raw.upgrade(request, bun);
6216
6633
  },
6217
6634
  websocket: {
6218
- maxPayloadLength: SOCKET_MAX_BYTES,
6635
+ maxPayloadLength: Math.max(SOCKET_MAX_BYTES, raw?.maxPayloadBytes ?? 0),
6219
6636
  backpressureLimit: SOCKET_BUFFER_BYTES,
6220
6637
  closeOnBackpressureLimit: true,
6221
6638
  open: (ws) => ws.data.mounted.open(ws),
@@ -6228,6 +6645,7 @@ function mountSockets(options) {
6228
6645
  },
6229
6646
  async dispose() {
6230
6647
  await Promise.all(closing);
6648
+ raw?.dispose();
6231
6649
  for (const { definition } of sockets) definition.brokers.delete(broker);
6232
6650
  await broker.close?.();
6233
6651
  }
@@ -7493,12 +7911,21 @@ function brick(options = {}) {
7493
7911
  headers
7494
7912
  });
7495
7913
  };
7914
+ const run = (effect) => runtime.runPromiseExit(effect);
7915
+ const raw = mountRawSockets({
7916
+ services,
7917
+ prefix,
7918
+ run,
7919
+ telemetry,
7920
+ drainTimeoutMs: options.drainTimeoutMs ?? 3e4
7921
+ });
7496
7922
  const sockets = mountSockets({
7497
7923
  services,
7498
7924
  prefix,
7499
7925
  routes: [...routes, ...endpointDefs],
7500
7926
  sockets: options.sockets,
7501
- run: (effect) => runtime.runPromiseExit(effect)
7927
+ raw,
7928
+ run
7502
7929
  });
7503
7930
  const plugged = pluginLifecycle(plugins.lifecycles, (effect) => runtime.runPromise(effect));
7504
7931
  let server;
@@ -7526,7 +7953,8 @@ function brick(options = {}) {
7526
7953
  else startEvents();
7527
7954
  return server;
7528
7955
  },
7529
- async stop() {
7956
+ async stop(force) {
7957
+ if (force !== true) await raw.drain();
7530
7958
  await server?.stop(true);
7531
7959
  server = void 0;
7532
7960
  try {
@@ -7553,7 +7981,9 @@ function brick(options = {}) {
7553
7981
  app.listen(port);
7554
7982
  return app;
7555
7983
  },
7556
- shutdown: () => app.stop(),
7984
+ shutdown: (force) => app.stop(force),
7985
+ drain: raw.drain,
7986
+ rawSockets: raw.stats,
7557
7987
  openApiDocument,
7558
7988
  architecture: () => JSON.parse(architectureJson()),
7559
7989
  clientContract: () => describeClientContract(services, routes, prefix),
@@ -7579,7 +8009,7 @@ function brick(options = {}) {
7579
8009
  endpoint(def) {
7580
8010
  if (routeKey(def.method, def.path) === mcpKey) throw mcpRouteTaken();
7581
8011
  if (def.database && !databases.has(def.database.layer)) throw new Error(`Brick: the endpoint '${def.method} ${def.path}' names a database the app does not hold: give it to a service, or pass the endpoint in brick({ endpoints }).`);
7582
- if (def.method === "GET" && definition.sockets.some((socket) => socket.path === def.path)) throw new DuplicateNameError(`Brick: route '${def.method} ${def.path}' conflicts with a socket`);
8012
+ if (def.method === "GET" && (definition.sockets.some((socket) => socket.path === def.path) || raw.paths.includes(def.path))) throw new DuplicateNameError(`Brick: route '${def.method} ${def.path}' conflicts with a socket`);
7583
8013
  if (mountEndpoint(def)) {
7584
8014
  lateRoutes.push(endpointRoute(def));
7585
8015
  stale = true;
@@ -7590,6 +8020,6 @@ function brick(options = {}) {
7590
8020
  };
7591
8021
  return app;
7592
8022
  }
7593
- export { getGlobalRegistry as $, listSecrets as $t, runInTransaction as A, traceRoute as An, invalid$1 as At, claimSegment as B, signDashboardMcp as Bn, frameworkStorage as Bt, scheduleTable as C, createLogger as Cn, reject as Ct, localBroker as D, recordWebhook as Dn, createAction as Dt, defineServiceSocket as E, Telemetry as En, RESET_STAGES as Et, isCrudEvent as F, dashboardKey as Fn, redact as Ft, getPluginEndpoints as G, BrickError as Gn, LOCAL_FILES_ROUTE as Gt, defineResourcePlugin as H, GLOBAL_SYMBOL as Hn, redis as Ht, OPENAPI_DEFAULTS as I, dashboardMcpCaller as In, sensitivePointer as It, validatePath as J, ValidationError as Jn, StorageError as Jt, hasPlugin as K, DuplicateNameError as Kn, s3 as Kt, generateOpenApiSpec as L, dashboardUser as Ln, carryClientRequest as Lt, crudEventSource as M, DASHBOARD_IDENTITY_HEADER as Mn, stagesOf as Mt, defineEvents as N, DASHBOARD_KEY_ENV as Nn, Sensitive as Nt, splitSeq as O, spanStore as On, deny as Ot, encodePayload as P, dashboardIdentity as Pn, hasSensitive as Pt, PLUGIN_KIND as Q, envSource as Qt, requestLoggingPlugin as R, markDashboardArrival as Rn, clientAddress as Rt, outboxTable as S, baseContext as Sn, kindOf as St, SocketDenied as T, SpanStore as Tn, HTTP_METHODS as Tt, defineServicePlugin as U, SPAN as Un, requireStorage as Ut, copyControls as V, ATTR as Vn, memory as Vt, getPluginActionRoute as W, actionMeta as Wn, storageKey as Wt, setInternals as X, toErrorResponse as Xn, SecretRef as Xt, internalsOf$1 as Y, normalizeFailures as Yn, StorageUnavailableError as Yt, PLUGIN_COMMIT as Z, toWireError as Zn, defineSecret as Zt, idSchema as _, isAuditTable as _n, decodeCursor as _t, WORKFLOW_TABLE as a, depsOverride as an, isObjectSchema as at, stopAllEvents as b, recordInline as bn, invalid as bt, workflowEngine as c, useDeps as cn, setActionAccess as ct, createMcpHandler as d, UploadedFiles as dn, SORTABLE_TYPES as dt, overrideSecret as en, resetGlobalRegistry as et, createMcpRegistry as f, fileFields as fn, UNFILTERABLE_TYPES as ft, defineResource as g, inlineAuditOptions as gn, databaseValue as gt, normalizeDashboard as h, bindAuditTarget as hn, columnValue as ht, DurableDeferred as i, definitionSite as in, getActionRoute as it, crudEventName as j, traceScheduleRun as jn, runStages as jt, onTransactionCommit as k, telemetryLayer as kn, errorHelpers as kt, INTERNALS as l, withOverride as ln, setActionAudit as lt, DASHBOARD_MCP_TOOLS as m, auditTableOf as mn, columnSchema as mt, Activity as n, resolveSecrets as nn, DEFAULT_PREFIX as nt, Workflow as o, freezeAsBuiltDeps as on, kebabCase as ot, DASHBOARD_MCP_ROUTE as p, auditTable as pn, checkJsonSchema as pt, installPlugin as q, STANDARD_ERRORS as qn, scopeFiles as qt, DurableClock as r, claimName as rn, actionOwners as rt, WorkflowEngine as s, ownDeps as sn, getActionAccess as st, brick as t, resetSecrets as tn, exportArchitecture as tt, UnknownToolError as u, UploadedFile as un, ORDERED_TYPES as ut, loadRecord as v, isInlineAudit as vn, encodeCursor as vt, defineSchedule as w, defaultLogger as wn, withoutNull as wt, defineListener as x, actorOf as xn, jsonValue as xt, Events as y, recordAudit as yn, idSchema$1 as yt, scalarDocsHTML as z, signDashboardIdentity as zn, defineStorage as zt };
8023
+ export { PLUGIN_KIND as $, envSource as $t, onTransactionCommit as A, telemetryLayer as An, errorHelpers as At, scalarDocsHTML as B, signDashboardIdentity as Bn, defineStorage as Bt, scheduleTable as C, baseContext as Cn, kindOf as Ct, defineServiceSocket as D, Telemetry as Dn, RESET_STAGES as Dt, SocketDenied as E, SpanStore as En, HTTP_METHODS as Et, encodePayload as F, dashboardIdentity as Fn, hasSensitive as Ft, getPluginActionRoute as G, actionMeta as Gn, storageKey as Gt, copyControls as H, ATTR as Hn, memory as Ht, isCrudEvent as I, dashboardKey as In, redact as It, installPlugin as J, STANDARD_ERRORS as Jn, scopeFiles as Jt, getPluginEndpoints as K, BrickError as Kn, LOCAL_FILES_ROUTE as Kt, OPENAPI_DEFAULTS as L, dashboardMcpCaller as Ln, sensitivePointer as Lt, crudEventName as M, traceScheduleRun as Mn, runStages as Mt, crudEventSource as N, DASHBOARD_IDENTITY_HEADER as Nn, stagesOf as Nt, localBroker as O, recordWebhook as On, createAction as Ot, defineEvents as P, DASHBOARD_KEY_ENV as Pn, Sensitive as Pt, PLUGIN_COMMIT as Q, toWireError as Qn, defineSecret as Qt, generateOpenApiSpec as R, dashboardUser as Rn, carryClientRequest as Rt, outboxTable as S, actorOf as Sn, jsonValue as St, defineRawSocket as T, defaultLogger as Tn, withoutNull as Tt, defineResourcePlugin as U, GLOBAL_SYMBOL as Un, redis as Ut, claimSegment as V, signDashboardMcp as Vn, frameworkStorage as Vt, defineServicePlugin as W, SPAN as Wn, requireStorage as Wt, internalsOf$1 as X, normalizeFailures as Xn, StorageUnavailableError as Xt, validatePath as Y, ValidationError as Yn, StorageError as Yt, setInternals as Z, toErrorResponse as Zn, SecretRef as Zt, idSchema as _, inlineAuditOptions as _n, databaseValue as _t, WORKFLOW_TABLE as a, definitionSite as an, getActionRoute as at, stopAllEvents as b, recordAudit as bn, idSchema$1 as bt, workflowEngine as c, ownDeps as cn, getActionAccess as ct, createMcpHandler as d, UploadedFile as dn, ORDERED_TYPES as dt, listSecrets as en, getGlobalRegistry as et, createMcpRegistry as f, UploadedFiles as fn, SORTABLE_TYPES as ft, defineResource as g, bindAuditTarget as gn, columnValue as gt, normalizeDashboard as h, auditTableOf as hn, columnSchema as ht, DurableDeferred as i, claimName as in, actionOwners as it, runInTransaction as j, traceRoute as jn, invalid$1 as jt, splitSeq as k, spanStore as kn, deny as kt, INTERNALS as l, useDeps as ln, setActionAccess as lt, DASHBOARD_MCP_TOOLS as m, auditTable as mn, checkJsonSchema as mt, Activity as n, resetSecrets as nn, exportArchitecture as nt, Workflow as o, depsOverride as on, isObjectSchema as ot, DASHBOARD_MCP_ROUTE as p, fileFields as pn, UNFILTERABLE_TYPES as pt, hasPlugin as q, DuplicateNameError as qn, s3 as qt, DurableClock as r, resolveSecrets as rn, DEFAULT_PREFIX as rt, WorkflowEngine as s, freezeAsBuiltDeps as sn, kebabCase as st, brick as t, overrideSecret as tn, resetGlobalRegistry as tt, UnknownToolError as u, withOverride as un, setActionAudit as ut, loadRecord as v, isAuditTable as vn, decodeCursor as vt, defineSchedule as w, createLogger as wn, reject as wt, defineListener as x, recordInline as xn, invalid as xt, Events as y, isInlineAudit as yn, encodeCursor as yt, requestLoggingPlugin as z, markDashboardArrival as zn, clientAddress as zt };
7594
8024
 
7595
- //# sourceMappingURL=server-BK0CrkGH.js.map
8025
+ //# sourceMappingURL=server-D-fDM98-.js.map