@tool-bridge/server 0.26.1 → 0.27.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/admin.js +1 -1
- package/dist/{chunk-FH7ST6SW.js → chunk-IZZ5C42L.js} +446 -228
- package/dist/{chunk-6F7TBJQ2.js → chunk-TMO3OAV5.js} +47 -34
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -2
- package/dist/main.js +5 -3
- package/package.json +2 -2
package/dist/admin.js
CHANGED
|
@@ -8,9 +8,10 @@ import {
|
|
|
8
8
|
pkceChallenge
|
|
9
9
|
} from "./chunk-U7PTOA3U.js";
|
|
10
10
|
import {
|
|
11
|
+
BootstrapLockBusyError,
|
|
11
12
|
BootstrapStateStore,
|
|
12
13
|
package_default
|
|
13
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-TMO3OAV5.js";
|
|
14
15
|
import {
|
|
15
16
|
createGuardedFetch
|
|
16
17
|
} from "./chunk-NXLE6ZEK.js";
|
|
@@ -18231,9 +18232,10 @@ var PgStateStore = class {
|
|
|
18231
18232
|
|
|
18232
18233
|
// src/keyManager.ts
|
|
18233
18234
|
import { randomBytes, randomUUID as randomUUID2 } from "crypto";
|
|
18234
|
-
import
|
|
18235
|
+
import postgres2 from "postgres";
|
|
18235
18236
|
|
|
18236
18237
|
// src/pgMaintenanceFence.ts
|
|
18238
|
+
import postgres from "postgres";
|
|
18237
18239
|
import { createHash } from "crypto";
|
|
18238
18240
|
function routerIdentity(url3) {
|
|
18239
18241
|
return createHash("sha256").update(url3 ? new URL(url3).href : "local-only").digest("hex");
|
|
@@ -18248,6 +18250,7 @@ async function ensureRuntimeCoordinationSchema(sql) {
|
|
|
18248
18250
|
await tx`CREATE TABLE IF NOT EXISTS tb_runtime_router (
|
|
18249
18251
|
instance_id text PRIMARY KEY, identity text NOT NULL, enforce_identity boolean NOT NULL DEFAULT false)`;
|
|
18250
18252
|
await tx`ALTER TABLE tb_runtime_replicas ADD COLUMN IF NOT EXISTS router_identity text`;
|
|
18253
|
+
await tx`ALTER TABLE tb_runtime_replicas ADD COLUMN IF NOT EXISTS session_fenced boolean NOT NULL DEFAULT false`;
|
|
18251
18254
|
await tx`CREATE OR REPLACE FUNCTION tb_check_runtime_router() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
18252
18255
|
BEGIN
|
|
18253
18256
|
IF EXISTS (SELECT 1 FROM tb_runtime_router WHERE instance_id=NEW.instance_id AND enforce_identity
|
|
@@ -18272,74 +18275,100 @@ async function assertRuntimeAuthority(sql, replicaId) {
|
|
|
18272
18275
|
AND (owner_replica_id<>${replicaId} OR (purpose='database' AND phase<>'copying'))`;
|
|
18273
18276
|
if (rows.length) throw new TBError("unavailable", "database authority is fenced for protected maintenance");
|
|
18274
18277
|
}
|
|
18275
|
-
|
|
18276
|
-
|
|
18277
|
-
|
|
18278
|
-
|
|
18279
|
-
|
|
18278
|
+
var RuntimeHandoffPendingError = class extends TBError {
|
|
18279
|
+
constructor(message = "another runtime still holds the database session lock") {
|
|
18280
|
+
super("unavailable", message, { retryable: true });
|
|
18281
|
+
this.name = "RuntimeHandoffPendingError";
|
|
18282
|
+
}
|
|
18283
|
+
};
|
|
18284
|
+
function lockConnection(sql, onclose) {
|
|
18285
|
+
const options = { ...sql.options, max: 1, idle_timeout: 0, max_lifetime: null, onclose };
|
|
18286
|
+
return postgres(options);
|
|
18287
|
+
}
|
|
18288
|
+
async function tryRuntimeLock(sql, shared) {
|
|
18289
|
+
const [row] = await sql`SELECT pg_backend_pid() AS pid, key::text,
|
|
18290
|
+
CASE WHEN ${shared}::boolean THEN pg_try_advisory_lock_shared(key) ELSE pg_try_advisory_lock(key) END AS acquired
|
|
18291
|
+
FROM (SELECT hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}) AS key) AS runtime`;
|
|
18292
|
+
return row?.acquired ? row : void 0;
|
|
18293
|
+
}
|
|
18294
|
+
async function runtimeLockHeld(sql, lock, shared) {
|
|
18295
|
+
const rows = await sql`SELECT 1 FROM pg_catalog.pg_locks
|
|
18296
|
+
WHERE locktype='advisory' AND granted AND pid=pg_backend_pid() AND pid=${lock.pid}
|
|
18297
|
+
AND database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database())
|
|
18298
|
+
AND mode=${shared ? "ShareLock" : "ExclusiveLock"} AND objsubid=1
|
|
18299
|
+
AND classid=((${lock.key}::bigint >> 32) & 4294967295)::oid
|
|
18300
|
+
AND objid=(${lock.key}::bigint & 4294967295)::oid`;
|
|
18301
|
+
return rows.length === 1;
|
|
18280
18302
|
}
|
|
18281
18303
|
async function acquireRuntimeLease(sql, input) {
|
|
18282
|
-
await ensureRuntimeCoordinationSchema(sql);
|
|
18283
|
-
const session = await sql.reserve();
|
|
18284
|
-
let released = false;
|
|
18285
|
-
let admitted = false;
|
|
18286
18304
|
const router = routerIdentity(input.redisUrl);
|
|
18287
|
-
|
|
18288
|
-
|
|
18289
|
-
let
|
|
18290
|
-
|
|
18291
|
-
|
|
18292
|
-
|
|
18293
|
-
|
|
18294
|
-
|
|
18295
|
-
|
|
18296
|
-
|
|
18297
|
-
|
|
18298
|
-
pg_try_advisory_lock_shared(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK})) AS acquired`;
|
|
18299
|
-
if (!row?.acquired) throw new TBError("unavailable", "database migration is draining its previous authority");
|
|
18300
|
-
held = true;
|
|
18301
|
-
backendPid = row.pid;
|
|
18302
|
-
} else {
|
|
18303
|
-
if (!await runtimeLockHeld(tx, backendPid)) {
|
|
18304
|
-
lost = true;
|
|
18305
|
-
throw new TBError("unavailable", "runtime database session was lost; drain and restart this replica");
|
|
18306
|
-
}
|
|
18307
|
-
}
|
|
18308
|
-
if (!admitted) {
|
|
18309
|
-
await tx`INSERT INTO tb_runtime_router(instance_id,identity) VALUES(${input.instanceId},${router}) ON CONFLICT DO NOTHING`;
|
|
18310
|
-
const [current] = await tx`SELECT identity FROM tb_runtime_router WHERE instance_id=${input.instanceId}`;
|
|
18311
|
-
if (current?.identity !== router) throw new TBError("conflict", "Redis configuration differs from the active router; update this replica before joining");
|
|
18312
|
-
const duplicate = await tx`SELECT 1 FROM tb_runtime_replicas WHERE replica_id=${input.replicaId}`;
|
|
18313
|
-
if (duplicate.length) throw new TBError("conflict", "runtime replica ID is already registered; drain the previous runtime");
|
|
18314
|
-
}
|
|
18315
|
-
const others = await tx`SELECT 1 FROM tb_runtime_replicas
|
|
18316
|
-
WHERE instance_id=${input.instanceId} AND replica_id<>${input.replicaId} AND expires_at>now()`;
|
|
18317
|
-
if (others.length && !input.redisUrl) throw new TBError("unavailable", "multiple replicas require a configured Redis device router");
|
|
18318
|
-
await tx`INSERT INTO tb_runtime_replicas(replica_id,instance_id,expires_at,router_identity)
|
|
18319
|
-
VALUES(${input.replicaId},${input.instanceId},now()+interval '60 seconds',${router})
|
|
18320
|
-
ON CONFLICT(replica_id) DO UPDATE SET expires_at=excluded.expires_at`;
|
|
18321
|
-
});
|
|
18305
|
+
const shared = Boolean(input.redisUrl);
|
|
18306
|
+
await ensureRuntimeCoordinationSchema(sql);
|
|
18307
|
+
let registered = false;
|
|
18308
|
+
let lost;
|
|
18309
|
+
let releasing;
|
|
18310
|
+
const markLost = () => {
|
|
18311
|
+
if (!lost) {
|
|
18312
|
+
lost = new TBError("unavailable", "runtime database session was lost; drain and restart this replica");
|
|
18313
|
+
if (registered && !releasing) input.onLost?.();
|
|
18314
|
+
}
|
|
18315
|
+
return lost;
|
|
18322
18316
|
};
|
|
18323
|
-
const
|
|
18324
|
-
|
|
18325
|
-
|
|
18317
|
+
const session = lockConnection(sql, markLost);
|
|
18318
|
+
const checkSession = () => {
|
|
18319
|
+
if (releasing) throw new TBError("unavailable", "runtime lease has been released");
|
|
18320
|
+
if (lost) throw lost;
|
|
18321
|
+
};
|
|
18322
|
+
const release = () => releasing ??= (async () => {
|
|
18326
18323
|
try {
|
|
18327
|
-
if (
|
|
18324
|
+
if (registered) await sql`DELETE FROM tb_runtime_replicas WHERE replica_id=${input.replicaId}`;
|
|
18328
18325
|
} finally {
|
|
18329
|
-
|
|
18330
|
-
if (held && await runtimeLockHeld(sql, backendPid)) await session`SELECT pg_advisory_unlock_shared(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}))`;
|
|
18331
|
-
} finally {
|
|
18332
|
-
session.release();
|
|
18333
|
-
}
|
|
18326
|
+
await session.end({ timeout: 5 });
|
|
18334
18327
|
}
|
|
18335
|
-
};
|
|
18328
|
+
})();
|
|
18336
18329
|
try {
|
|
18337
|
-
await
|
|
18338
|
-
|
|
18339
|
-
|
|
18340
|
-
|
|
18341
|
-
|
|
18330
|
+
const lock = await session.begin(async (tx) => {
|
|
18331
|
+
await tx`SELECT pg_advisory_xact_lock(${COORDINATION_LOCK})`;
|
|
18332
|
+
await assertRuntimeAuthority(tx, input.replicaId);
|
|
18333
|
+
await tx`INSERT INTO tb_runtime_router(instance_id,identity) VALUES(${input.instanceId},${router}) ON CONFLICT DO NOTHING`;
|
|
18334
|
+
const [current] = await tx`SELECT identity FROM tb_runtime_router WHERE instance_id=${input.instanceId}`;
|
|
18335
|
+
if (current?.identity !== router) throw new TBError("conflict", "Redis configuration differs from the active router; update this replica before joining");
|
|
18336
|
+
const lock2 = await tryRuntimeLock(tx, shared);
|
|
18337
|
+
if (!lock2) {
|
|
18338
|
+
const maintenance = await tx`SELECT 1 FROM tb_runtime_maintenance WHERE id=1 AND expires_at>now()`;
|
|
18339
|
+
if (shared || maintenance.length) throw new TBError("unavailable", "database authority is held by another runtime or maintenance");
|
|
18340
|
+
throw new RuntimeHandoffPendingError();
|
|
18341
|
+
}
|
|
18342
|
+
if (!shared) {
|
|
18343
|
+
const legacy = await tx`SELECT 1 FROM tb_runtime_replicas WHERE instance_id=${input.instanceId}
|
|
18344
|
+
AND session_fenced=false AND expires_at>now() LIMIT 1`;
|
|
18345
|
+
if (legacy.length) throw new RuntimeHandoffPendingError("waiting for the previous gateway version to drain");
|
|
18346
|
+
}
|
|
18347
|
+
const inserted = await tx`INSERT INTO tb_runtime_replicas(replica_id,instance_id,expires_at,router_identity,session_fenced)
|
|
18348
|
+
VALUES(${input.replicaId},${input.instanceId},now()+interval '60 seconds',${router},true)
|
|
18349
|
+
ON CONFLICT(replica_id) DO NOTHING RETURNING replica_id`;
|
|
18350
|
+
if (!inserted.length) throw new TBError("conflict", "runtime replica ID is already registered; drain the previous runtime");
|
|
18351
|
+
return lock2;
|
|
18342
18352
|
});
|
|
18353
|
+
registered = true;
|
|
18354
|
+
checkSession();
|
|
18355
|
+
return {
|
|
18356
|
+
heartbeat: async () => {
|
|
18357
|
+
checkSession();
|
|
18358
|
+
await session.begin(async (tx) => {
|
|
18359
|
+
await tx`SELECT pg_advisory_xact_lock(${COORDINATION_LOCK})`;
|
|
18360
|
+
checkSession();
|
|
18361
|
+
await assertRuntimeAuthority(tx, input.replicaId);
|
|
18362
|
+
const updated = await tx`UPDATE tb_runtime_replicas SET expires_at=now()+interval '60 seconds'
|
|
18363
|
+
WHERE replica_id=${input.replicaId} RETURNING replica_id`;
|
|
18364
|
+
if (!updated.length || !await runtimeLockHeld(tx, lock, shared)) throw markLost();
|
|
18365
|
+
});
|
|
18366
|
+
checkSession();
|
|
18367
|
+
},
|
|
18368
|
+
release
|
|
18369
|
+
};
|
|
18370
|
+
} catch (error) {
|
|
18371
|
+
await release();
|
|
18343
18372
|
throw error;
|
|
18344
18373
|
}
|
|
18345
18374
|
}
|
|
@@ -18358,27 +18387,24 @@ async function acquireMaintenanceFence(sql, input, purpose) {
|
|
|
18358
18387
|
purpose=excluded.purpose,phase=excluded.phase,operation_id=excluded.operation_id`;
|
|
18359
18388
|
});
|
|
18360
18389
|
let session;
|
|
18361
|
-
let locked = false;
|
|
18362
|
-
let backendPid;
|
|
18363
18390
|
const releaseLock = async () => {
|
|
18364
18391
|
const previous = session;
|
|
18365
18392
|
session = void 0;
|
|
18366
|
-
|
|
18367
|
-
try {
|
|
18368
|
-
if (locked && await runtimeLockHeld(sql, backendPid, "ExclusiveLock")) await previous`SELECT pg_advisory_unlock(hashtextextended(current_schema() || ':tool-bridge-runtime',${RUNTIME_LOCK}))`;
|
|
18369
|
-
} finally {
|
|
18370
|
-
locked = false;
|
|
18371
|
-
previous.release();
|
|
18372
|
-
}
|
|
18393
|
+
await previous?.end();
|
|
18373
18394
|
};
|
|
18374
18395
|
return {
|
|
18375
18396
|
drain: async () => {
|
|
18376
|
-
session
|
|
18377
|
-
const
|
|
18378
|
-
|
|
18379
|
-
|
|
18380
|
-
|
|
18381
|
-
|
|
18397
|
+
if (session) throw new TBError("conflict", "maintenance already has a drain in progress");
|
|
18398
|
+
const attempt2 = lockConnection(sql);
|
|
18399
|
+
session = attempt2;
|
|
18400
|
+
try {
|
|
18401
|
+
if (!await tryRuntimeLock(attempt2, false))
|
|
18402
|
+
throw new TBError("conflict", "another runtime still holds this database; stop it before migration");
|
|
18403
|
+
} catch (error) {
|
|
18404
|
+
if (session === attempt2) session = void 0;
|
|
18405
|
+
await attempt2.end();
|
|
18406
|
+
throw error;
|
|
18407
|
+
}
|
|
18382
18408
|
},
|
|
18383
18409
|
retire: async () => {
|
|
18384
18410
|
const rows = await sql`UPDATE tb_runtime_maintenance SET phase='retired'
|
|
@@ -18436,7 +18462,7 @@ var KeyManager = class {
|
|
|
18436
18462
|
constructor(hooks, options = {}) {
|
|
18437
18463
|
this.hooks = hooks;
|
|
18438
18464
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
18439
|
-
this.connect = options.connect ?? ((url3) =>
|
|
18465
|
+
this.connect = options.connect ?? ((url3) => postgres2(url3, { max: 3, connect_timeout: 5, onnotice: () => {
|
|
18440
18466
|
} }));
|
|
18441
18467
|
}
|
|
18442
18468
|
hooks;
|
|
@@ -18640,7 +18666,7 @@ var KeyManager = class {
|
|
|
18640
18666
|
// src/maintenanceManager.ts
|
|
18641
18667
|
import { chmod, mkdtemp, rm, writeFile } from "fs/promises";
|
|
18642
18668
|
import { execFile } from "child_process";
|
|
18643
|
-
import
|
|
18669
|
+
import postgres3 from "postgres";
|
|
18644
18670
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
18645
18671
|
import { promisify } from "util";
|
|
18646
18672
|
import { tmpdir } from "os";
|
|
@@ -18731,7 +18757,7 @@ async function probeRedis(redisUrl) {
|
|
|
18731
18757
|
}
|
|
18732
18758
|
}
|
|
18733
18759
|
function sqlClient(url3) {
|
|
18734
|
-
return
|
|
18760
|
+
return postgres3(url3, {
|
|
18735
18761
|
max: 2,
|
|
18736
18762
|
connect_timeout: 5,
|
|
18737
18763
|
idle_timeout: 5,
|
|
@@ -20600,9 +20626,9 @@ var PgSearchIndex = class extends SqlSearchIndex {
|
|
|
20600
20626
|
};
|
|
20601
20627
|
|
|
20602
20628
|
// src/server.ts
|
|
20603
|
-
import { serve } from "@hono/node-server";
|
|
20604
20629
|
import { AsyncLocalStorage } from "async_hooks";
|
|
20605
|
-
import
|
|
20630
|
+
import postgres4 from "postgres";
|
|
20631
|
+
import { serve } from "@hono/node-server";
|
|
20606
20632
|
import { randomUUID as randomUUID10 } from "crypto";
|
|
20607
20633
|
import { Hono as Hono4 } from "hono";
|
|
20608
20634
|
|
|
@@ -21153,7 +21179,7 @@ function consentPage(action, redirectUri, invalidKey = false) {
|
|
|
21153
21179
|
}
|
|
21154
21180
|
|
|
21155
21181
|
// src/mcpOAuth.ts
|
|
21156
|
-
var
|
|
21182
|
+
var MCP_AUTHORIZE_PATH = "/~oauth/mcp/authorize";
|
|
21157
21183
|
var TOKEN = "/~oauth/mcp/token";
|
|
21158
21184
|
var FORM_TYPE = "application/x-www-form-urlencoded";
|
|
21159
21185
|
var MAX_REQUEST = 8192;
|
|
@@ -21280,7 +21306,7 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
|
|
|
21280
21306
|
scopesSupported: [MCP_OAUTH_SCOPE],
|
|
21281
21307
|
oauthMetadata: {
|
|
21282
21308
|
issuer,
|
|
21283
|
-
authorization_endpoint: issuer +
|
|
21309
|
+
authorization_endpoint: issuer + MCP_AUTHORIZE_PATH,
|
|
21284
21310
|
token_endpoint: issuer + TOKEN,
|
|
21285
21311
|
scopes_supported: [MCP_OAUTH_SCOPE],
|
|
21286
21312
|
response_types_supported: ["code"],
|
|
@@ -21307,7 +21333,7 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
|
|
|
21307
21333
|
}
|
|
21308
21334
|
return Response.json({ error: "server_error" }, { status: 500, headers: noStore });
|
|
21309
21335
|
});
|
|
21310
|
-
routes.all(
|
|
21336
|
+
routes.all(MCP_AUTHORIZE_PATH, async (c) => {
|
|
21311
21337
|
const request2 = c.req.raw;
|
|
21312
21338
|
if (!["GET", "POST"].includes(request2.method)) return methodError("GET, POST");
|
|
21313
21339
|
if (request2.method === "POST" && request2.headers.get("origin") !== issuer) {
|
|
@@ -21321,7 +21347,7 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
|
|
|
21321
21347
|
throw new EndpointError("invalid_request");
|
|
21322
21348
|
}
|
|
21323
21349
|
if (params.has("state") && !/^[\x20-\x7e]+$/.test(params.get("state"))) throw new EndpointError("invalid_request");
|
|
21324
|
-
const action = issuer +
|
|
21350
|
+
const action = issuer + MCP_AUTHORIZE_PATH + "?" + params.toString();
|
|
21325
21351
|
if (request2.method === "GET") return consentPage(action, MCP_OAUTH_REDIRECT_URI);
|
|
21326
21352
|
const body = await form(request2, ["sk", "decision"]);
|
|
21327
21353
|
if (body.get("decision") === "deny") return authorizationResponse(issuer, params, { error: "access_denied" });
|
|
@@ -21358,7 +21384,7 @@ function createMcpOAuth(state, canonicalOrigin, fetchClientMetadata) {
|
|
|
21358
21384
|
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resourceServerUrl),
|
|
21359
21385
|
async handlePublic(request2) {
|
|
21360
21386
|
const path = new URL(request2.url).pathname;
|
|
21361
|
-
if (path ===
|
|
21387
|
+
if (path === MCP_AUTHORIZE_PATH || path === TOKEN) return routes.fetch(request2);
|
|
21362
21388
|
return oauthMetadataResponse(request2, metadata);
|
|
21363
21389
|
},
|
|
21364
21390
|
identify: (authorization, now) => identifyMcpToken(state, issuer, authorization, now)
|
|
@@ -21459,13 +21485,13 @@ function resolveUiAssets(uiDirOverride) {
|
|
|
21459
21485
|
// src/server.ts
|
|
21460
21486
|
var providerOAuthFetch = createGuardedFetch({ crossOriginRedirect: "error" });
|
|
21461
21487
|
var chatGptMetadataFetch = createGuardedFetch({ maxRedirects: 0 });
|
|
21462
|
-
function createTbServer(config) {
|
|
21488
|
+
function createTbServer(config, onOwnershipLost) {
|
|
21463
21489
|
if (!config.databaseUrl)
|
|
21464
21490
|
throw new TBError(
|
|
21465
21491
|
"unavailable",
|
|
21466
21492
|
"PostgreSQL must be configured before starting business services"
|
|
21467
21493
|
);
|
|
21468
|
-
const sql =
|
|
21494
|
+
const sql = postgres4(config.databaseUrl, {
|
|
21469
21495
|
onnotice: () => {
|
|
21470
21496
|
},
|
|
21471
21497
|
connect_timeout: 5
|
|
@@ -21486,6 +21512,7 @@ function createTbServer(config) {
|
|
|
21486
21512
|
const storeRepository = new PgStoreRepository(sql);
|
|
21487
21513
|
const eventRepository = new PgEventRepository(sql);
|
|
21488
21514
|
const eventStreamShutdown = new AbortController();
|
|
21515
|
+
const shutdown = new AbortController();
|
|
21489
21516
|
const mailboxRepository = new PgMailboxRepository(sql);
|
|
21490
21517
|
const storage = new StorageManager(sql, secrets, {
|
|
21491
21518
|
...config.internalS3Origin ? { internalOrigin: config.internalS3Origin } : {}
|
|
@@ -21507,6 +21534,14 @@ function createTbServer(config) {
|
|
|
21507
21534
|
}
|
|
21508
21535
|
});
|
|
21509
21536
|
let draining = false;
|
|
21537
|
+
let closing = false;
|
|
21538
|
+
let preparedForTraffic = false;
|
|
21539
|
+
const ownershipLost = new AbortController();
|
|
21540
|
+
const accepting = () => preparedForTraffic && !closing && !ownershipLost.signal.aborted;
|
|
21541
|
+
const assertOpen = () => {
|
|
21542
|
+
if (closing || ownershipLost.signal.aborted)
|
|
21543
|
+
throw new TBError("unavailable", "runtime is closed");
|
|
21544
|
+
};
|
|
21510
21545
|
const probeOne = async (fn) => {
|
|
21511
21546
|
let timer;
|
|
21512
21547
|
try {
|
|
@@ -21528,18 +21563,12 @@ function createTbServer(config) {
|
|
|
21528
21563
|
}
|
|
21529
21564
|
};
|
|
21530
21565
|
const readiness = async () => {
|
|
21566
|
+
if (!accepting()) return { ready: false, checks: { runtime: { ok: false, detail: "runtime not accepting requests" } } };
|
|
21531
21567
|
const checks = {};
|
|
21532
21568
|
const probes = [];
|
|
21533
|
-
|
|
21534
|
-
|
|
21535
|
-
};
|
|
21536
|
-
if (statePing !== void 0) {
|
|
21537
|
-
probes.push(
|
|
21538
|
-
probeOne(statePing).then((r) => {
|
|
21539
|
-
checks.state = r;
|
|
21540
|
-
})
|
|
21541
|
-
);
|
|
21542
|
-
}
|
|
21569
|
+
probes.push(probeOne(() => assertRuntimeAuthority(sql, replicaId)).then((r) => {
|
|
21570
|
+
checks.state = r;
|
|
21571
|
+
}));
|
|
21543
21572
|
if (redisBackend !== void 0) {
|
|
21544
21573
|
probes.push(
|
|
21545
21574
|
probeOne(async () => await redisBackend.ping()).then((r) => {
|
|
@@ -21579,6 +21608,8 @@ function createTbServer(config) {
|
|
|
21579
21608
|
mailboxRepository,
|
|
21580
21609
|
eventRepository,
|
|
21581
21610
|
eventStreamShutdown: eventStreamShutdown.signal,
|
|
21611
|
+
// In-process MCP calls can also enter the inner HTBP app.
|
|
21612
|
+
ensureReady: async () => ownershipLost.signal.throwIfAborted(),
|
|
21582
21613
|
storageManagement: storage,
|
|
21583
21614
|
deploymentManagement: deployment,
|
|
21584
21615
|
...config.adminAudit ? { adminAudit: config.adminAudit } : {},
|
|
@@ -21638,20 +21669,24 @@ function createTbServer(config) {
|
|
|
21638
21669
|
deps.storeCallAllowedContentTypes = config.storeCallAllowedContentTypes;
|
|
21639
21670
|
}
|
|
21640
21671
|
let server;
|
|
21672
|
+
let listening;
|
|
21641
21673
|
let maintenanceTimer;
|
|
21642
21674
|
let maintenancePromise;
|
|
21643
21675
|
let replicaTimer;
|
|
21644
|
-
let heartbeatInFlight
|
|
21676
|
+
let heartbeatInFlight;
|
|
21645
21677
|
let applied;
|
|
21646
21678
|
const runMaintenance = async () => {
|
|
21679
|
+
if (closing) return;
|
|
21647
21680
|
if (maintenancePromise) return maintenancePromise;
|
|
21648
21681
|
const snapshot = deps;
|
|
21649
21682
|
maintenancePromise = (async () => {
|
|
21650
21683
|
await sql`DELETE FROM tb_kv WHERE key >= 'mcp-inbound:' AND key < 'mcp-inbound;'
|
|
21651
21684
|
AND value->>'expiresAt' <= ${(/* @__PURE__ */ new Date()).toISOString()}`;
|
|
21685
|
+
if (ownershipLost.signal.aborted) return;
|
|
21652
21686
|
await eventRepository.cleanup();
|
|
21687
|
+
if (ownershipLost.signal.aborted) return;
|
|
21653
21688
|
await cleanupDefaultStore(snapshot);
|
|
21654
|
-
if (snapshot.encryptionKey !== void 0)
|
|
21689
|
+
if (!ownershipLost.signal.aborted && snapshot.encryptionKey !== void 0)
|
|
21655
21690
|
await cleanupDeviceMailbox(snapshot);
|
|
21656
21691
|
})().finally(() => {
|
|
21657
21692
|
maintenancePromise = void 0;
|
|
@@ -21662,6 +21697,7 @@ function createTbServer(config) {
|
|
|
21662
21697
|
console.warn(JSON.stringify({ event: "tool_bridge_store_cleanup_failed" }));
|
|
21663
21698
|
};
|
|
21664
21699
|
function scheduleStoreCleanup() {
|
|
21700
|
+
if (closing) return;
|
|
21665
21701
|
void runMaintenance().catch(reportStoreCleanupFailure);
|
|
21666
21702
|
maintenanceTimer = setInterval(
|
|
21667
21703
|
() => {
|
|
@@ -21684,6 +21720,7 @@ function createTbServer(config) {
|
|
|
21684
21720
|
};
|
|
21685
21721
|
currentApp = buildApp();
|
|
21686
21722
|
}, async (next) => {
|
|
21723
|
+
ownershipLost.signal.throwIfAborted();
|
|
21687
21724
|
await hub.setReclaimSec(next.deviceReclaimSec);
|
|
21688
21725
|
const reschedule = applied?.storeCleanupIntervalSec !== next.storeCleanupIntervalSec;
|
|
21689
21726
|
applied = next;
|
|
@@ -21699,7 +21736,17 @@ function createTbServer(config) {
|
|
|
21699
21736
|
const drainWaiters = [];
|
|
21700
21737
|
const requestContext = new AsyncLocalStorage();
|
|
21701
21738
|
const app = new Hono4();
|
|
21702
|
-
app.
|
|
21739
|
+
app.mount("/", async (raw, env, executionCtx) => {
|
|
21740
|
+
const path = new URL(raw.url).pathname;
|
|
21741
|
+
const read = raw.method === "GET" || raw.method === "HEAD";
|
|
21742
|
+
const probe = read && ["/healthz", "/livez", "/readyz"].includes(path);
|
|
21743
|
+
const unavailable = (message) => Response.json({ code: "unavailable", message }, { status: 503 });
|
|
21744
|
+
if (!accepting()) {
|
|
21745
|
+
if (probe) return currentApp.fetch(raw, env, executionCtx);
|
|
21746
|
+
return unavailable("runtime not accepting requests");
|
|
21747
|
+
}
|
|
21748
|
+
const transport = AbortSignal.any([raw.signal, ownershipLost.signal]);
|
|
21749
|
+
const signal = AbortSignal.any([transport, shutdown.signal]);
|
|
21703
21750
|
activeRequests++;
|
|
21704
21751
|
let released = false;
|
|
21705
21752
|
const request2 = {
|
|
@@ -21712,45 +21759,114 @@ function createTbServer(config) {
|
|
|
21712
21759
|
};
|
|
21713
21760
|
return requestContext.run(request2, async () => {
|
|
21714
21761
|
try {
|
|
21715
|
-
|
|
21716
|
-
if (!["/healthz", "/livez", "/readyz"].includes(path) && !path.startsWith("/ui")) {
|
|
21762
|
+
if (!probe && !(read && (path === "/ui" || path.startsWith("/ui/")))) {
|
|
21717
21763
|
try {
|
|
21718
21764
|
await assertRuntimeAuthority(sql, replicaId);
|
|
21765
|
+
transport.throwIfAborted();
|
|
21719
21766
|
await settings.sync();
|
|
21720
21767
|
} catch {
|
|
21721
|
-
|
|
21722
|
-
|
|
21723
|
-
code: "unavailable",
|
|
21724
|
-
message: "configuration authority unavailable"
|
|
21725
|
-
},
|
|
21726
|
-
503
|
|
21727
|
-
), request2.release, c.req.raw.signal);
|
|
21768
|
+
request2.release();
|
|
21769
|
+
return unavailable("configuration authority unavailable");
|
|
21728
21770
|
}
|
|
21729
21771
|
}
|
|
21730
|
-
|
|
21731
|
-
|
|
21772
|
+
if (transport.aborted) {
|
|
21773
|
+
request2.release();
|
|
21774
|
+
return unavailable("request interrupted before dispatch");
|
|
21775
|
+
}
|
|
21776
|
+
const body = !raw.keepalive && raw.mode !== "no-cors" ? raw.body?.pipeThrough(new TransformStream(), { signal: transport }) : void 0;
|
|
21777
|
+
try {
|
|
21778
|
+
const init = { signal, ...body && { body, duplex: "half" } };
|
|
21779
|
+
const forwarded = new Request(raw, init);
|
|
21780
|
+
if (forwarded.method !== raw.method) Object.defineProperty(forwarded, "method", { value: raw.method });
|
|
21781
|
+
const response = await currentApp.fetch(forwarded, env, executionCtx);
|
|
21782
|
+
const sse = response.headers.get("content-type")?.split(";")[0] === "text/event-stream";
|
|
21783
|
+
return trackResponseBody(response, request2.release, sse ? AbortSignal.any([transport, eventStreamShutdown.signal]) : transport);
|
|
21784
|
+
} finally {
|
|
21785
|
+
if (body && !body.locked) void body.cancel().catch(() => {
|
|
21786
|
+
});
|
|
21787
|
+
}
|
|
21732
21788
|
} catch (error) {
|
|
21733
21789
|
request2.release();
|
|
21734
21790
|
throw error;
|
|
21735
21791
|
}
|
|
21736
21792
|
});
|
|
21737
|
-
});
|
|
21793
|
+
}, { replaceRequest: false });
|
|
21738
21794
|
let prepared;
|
|
21739
21795
|
let runtimeLease;
|
|
21740
21796
|
let closePromise;
|
|
21797
|
+
let listenerClosed;
|
|
21798
|
+
const stopListening = async (listener) => {
|
|
21799
|
+
if (!listener.listening) await listening?.catch(() => {
|
|
21800
|
+
});
|
|
21801
|
+
if (!listener.listening) return;
|
|
21802
|
+
await new Promise((resolve2, reject) => {
|
|
21803
|
+
listener.close((err) => err ? reject(err) : resolve2());
|
|
21804
|
+
listener.closeIdleConnections();
|
|
21805
|
+
});
|
|
21806
|
+
};
|
|
21807
|
+
const close = async (options) => {
|
|
21808
|
+
const caller = options?.excludeCurrentRequest ? requestContext.getStore() : void 0;
|
|
21809
|
+
caller?.release();
|
|
21810
|
+
if (!closePromise) {
|
|
21811
|
+
closing = true;
|
|
21812
|
+
draining = true;
|
|
21813
|
+
if (server) listenerClosed = stopListening(server);
|
|
21814
|
+
closePromise = Promise.resolve().then(async () => {
|
|
21815
|
+
eventStreamShutdown.abort();
|
|
21816
|
+
if (!caller) shutdown.abort(new TBError("unavailable", "runtime is shutting down"));
|
|
21817
|
+
if (maintenanceTimer !== void 0) {
|
|
21818
|
+
clearInterval(maintenanceTimer);
|
|
21819
|
+
maintenanceTimer = void 0;
|
|
21820
|
+
}
|
|
21821
|
+
if (!preparedForTraffic) await prepared?.catch(() => {
|
|
21822
|
+
});
|
|
21823
|
+
await hub.close();
|
|
21824
|
+
if (activeRequests > 0)
|
|
21825
|
+
await new Promise((resolve2) => drainWaiters.push(resolve2));
|
|
21826
|
+
await maintenancePromise?.catch(() => {
|
|
21827
|
+
});
|
|
21828
|
+
if (replicaTimer) clearInterval(replicaTimer);
|
|
21829
|
+
await heartbeatInFlight;
|
|
21830
|
+
try {
|
|
21831
|
+
await runtimeLease?.release();
|
|
21832
|
+
} finally {
|
|
21833
|
+
storage.close();
|
|
21834
|
+
await eventRepository.close().finally(() => sql.end({ timeout: 5 }));
|
|
21835
|
+
}
|
|
21836
|
+
});
|
|
21837
|
+
}
|
|
21838
|
+
await Promise.all([closePromise, caller ? void 0 : listenerClosed]);
|
|
21839
|
+
};
|
|
21741
21840
|
const prepare = async () => {
|
|
21841
|
+
assertOpen();
|
|
21742
21842
|
prepared ??= (async () => {
|
|
21743
|
-
await
|
|
21744
|
-
runtimeLease = await acquireRuntimeLease(sql, {
|
|
21843
|
+
const lease = await acquireRuntimeLease(sql, {
|
|
21745
21844
|
instanceId: config.instanceId ?? "embedded",
|
|
21746
21845
|
replicaId,
|
|
21747
|
-
redisUrl: config.redisUrl
|
|
21846
|
+
redisUrl: config.redisUrl,
|
|
21847
|
+
onLost: () => {
|
|
21848
|
+
if (ownershipLost.signal.aborted) return;
|
|
21849
|
+
ownershipLost.abort(new TBError("unavailable", "runtime ownership lost"));
|
|
21850
|
+
if (replicaTimer) clearInterval(replicaTimer);
|
|
21851
|
+
console.error(JSON.stringify({ event: "tool_bridge_runtime_ownership_lost" }));
|
|
21852
|
+
void close().catch(() => {
|
|
21853
|
+
console.error(JSON.stringify({ event: "tool_bridge_runtime_close_failed" }));
|
|
21854
|
+
});
|
|
21855
|
+
server?.closeAllConnections();
|
|
21856
|
+
onOwnershipLost?.();
|
|
21857
|
+
}
|
|
21748
21858
|
});
|
|
21859
|
+
runtimeLease = lease;
|
|
21860
|
+
assertOpen();
|
|
21749
21861
|
replicaTimer = setInterval(() => {
|
|
21750
|
-
|
|
21862
|
+
if (heartbeatInFlight) return;
|
|
21863
|
+
heartbeatInFlight = lease.heartbeat().catch(() => {
|
|
21864
|
+
}).finally(() => {
|
|
21865
|
+
heartbeatInFlight = void 0;
|
|
21751
21866
|
});
|
|
21752
21867
|
}, 15e3);
|
|
21753
21868
|
replicaTimer.unref();
|
|
21869
|
+
await state.ensureSchema();
|
|
21754
21870
|
await storeRepository.ensureSchema();
|
|
21755
21871
|
await state.ensureContextReferencesSchema();
|
|
21756
21872
|
await eventRepository.ensureSchema();
|
|
@@ -21768,6 +21884,7 @@ function createTbServer(config) {
|
|
|
21768
21884
|
)
|
|
21769
21885
|
)
|
|
21770
21886
|
);
|
|
21887
|
+
assertOpen();
|
|
21771
21888
|
await runBootstrap(state, {
|
|
21772
21889
|
management: true,
|
|
21773
21890
|
additionalModules: [
|
|
@@ -21776,6 +21893,7 @@ function createTbServer(config) {
|
|
|
21776
21893
|
],
|
|
21777
21894
|
...config.adminSk ? { adminSk: config.adminSk } : {}
|
|
21778
21895
|
});
|
|
21896
|
+
assertOpen();
|
|
21779
21897
|
const backends = (await storage.list()).items;
|
|
21780
21898
|
let active2 = backends.find((backend) => backend.active);
|
|
21781
21899
|
if (!active2 && config.objectStore) {
|
|
@@ -21810,12 +21928,17 @@ function createTbServer(config) {
|
|
|
21810
21928
|
if (!active2)
|
|
21811
21929
|
throw new TBError("unavailable", "no active storage backend");
|
|
21812
21930
|
await storage.resolveBackend(active2.id);
|
|
21931
|
+
assertOpen();
|
|
21813
21932
|
await hub.startRouter();
|
|
21814
21933
|
await settings.sync();
|
|
21934
|
+
assertOpen();
|
|
21815
21935
|
await hub.sweepOrphans();
|
|
21936
|
+
assertOpen();
|
|
21816
21937
|
scheduleStoreCleanup();
|
|
21938
|
+
preparedForTraffic = true;
|
|
21817
21939
|
})();
|
|
21818
21940
|
await prepared;
|
|
21941
|
+
assertOpen();
|
|
21819
21942
|
};
|
|
21820
21943
|
return {
|
|
21821
21944
|
app,
|
|
@@ -21827,15 +21950,20 @@ function createTbServer(config) {
|
|
|
21827
21950
|
deviceHub: hub,
|
|
21828
21951
|
async start() {
|
|
21829
21952
|
await prepare();
|
|
21830
|
-
|
|
21953
|
+
assertOpen();
|
|
21954
|
+
listening ??= new Promise((resolve2, reject) => {
|
|
21831
21955
|
server = serve(
|
|
21832
21956
|
{ fetch: app.fetch, port: config.port, hostname: config.host },
|
|
21833
21957
|
(info) => {
|
|
21958
|
+
if (!closing) hub.attach(server);
|
|
21834
21959
|
resolve2({ port: info.port });
|
|
21835
21960
|
}
|
|
21836
21961
|
);
|
|
21837
|
-
|
|
21962
|
+
server.once("error", reject);
|
|
21838
21963
|
});
|
|
21964
|
+
const address = await listening;
|
|
21965
|
+
assertOpen();
|
|
21966
|
+
return address;
|
|
21839
21967
|
},
|
|
21840
21968
|
startDraining() {
|
|
21841
21969
|
draining = true;
|
|
@@ -21843,43 +21971,7 @@ function createTbServer(config) {
|
|
|
21843
21971
|
get shutdownDrainSec() {
|
|
21844
21972
|
return applied?.shutdownDrainSec ?? config.shutdownDrainSec ?? 0;
|
|
21845
21973
|
},
|
|
21846
|
-
|
|
21847
|
-
if (options?.excludeCurrentRequest) requestContext.getStore()?.release();
|
|
21848
|
-
return closePromise ??= (async () => {
|
|
21849
|
-
draining = true;
|
|
21850
|
-
eventStreamShutdown.abort();
|
|
21851
|
-
if (maintenanceTimer !== void 0) {
|
|
21852
|
-
clearInterval(maintenanceTimer);
|
|
21853
|
-
maintenanceTimer = void 0;
|
|
21854
|
-
}
|
|
21855
|
-
let closed;
|
|
21856
|
-
if (server !== void 0) {
|
|
21857
|
-
const s = server;
|
|
21858
|
-
closed = new Promise((resolve2, reject) => {
|
|
21859
|
-
s.close((err) => err ? reject(err) : resolve2());
|
|
21860
|
-
});
|
|
21861
|
-
s.closeIdleConnections?.();
|
|
21862
|
-
}
|
|
21863
|
-
await hub.close();
|
|
21864
|
-
if (activeRequests > 0)
|
|
21865
|
-
await new Promise((resolve2) => drainWaiters.push(resolve2));
|
|
21866
|
-
await maintenancePromise?.catch(() => {
|
|
21867
|
-
});
|
|
21868
|
-
if (replicaTimer) clearInterval(replicaTimer);
|
|
21869
|
-
await heartbeatInFlight;
|
|
21870
|
-
try {
|
|
21871
|
-
await runtimeLease?.release();
|
|
21872
|
-
} finally {
|
|
21873
|
-
try {
|
|
21874
|
-
if (closed !== void 0) await closed;
|
|
21875
|
-
} finally {
|
|
21876
|
-
server = void 0;
|
|
21877
|
-
storage.close();
|
|
21878
|
-
await eventRepository.close().finally(() => sql.end({ timeout: 5 }));
|
|
21879
|
-
}
|
|
21880
|
-
}
|
|
21881
|
-
})();
|
|
21882
|
-
}
|
|
21974
|
+
close
|
|
21883
21975
|
};
|
|
21884
21976
|
}
|
|
21885
21977
|
|
|
@@ -22123,52 +22215,90 @@ function builtinPluginBindings(env, opts = {}) {
|
|
|
22123
22215
|
}
|
|
22124
22216
|
|
|
22125
22217
|
// src/managedServer.ts
|
|
22126
|
-
import { serve as serve2 } from "@hono/node-server";
|
|
22127
22218
|
import { setTimeout as delay } from "timers/promises";
|
|
22128
22219
|
import { secureHeaders } from "hono/secure-headers";
|
|
22129
22220
|
import { bodyLimit } from "hono/body-limit";
|
|
22221
|
+
import { serve as serve2 } from "@hono/node-server";
|
|
22130
22222
|
import { randomUUID as randomUUID11 } from "crypto";
|
|
22131
|
-
import
|
|
22223
|
+
import postgres5 from "postgres";
|
|
22224
|
+
import pRetry from "p-retry";
|
|
22132
22225
|
import { Hono as Hono5 } from "hono";
|
|
22133
22226
|
async function createManagedServer(options) {
|
|
22134
22227
|
const store = new BootstrapStateStore(options.directory);
|
|
22135
22228
|
let state;
|
|
22136
22229
|
let phase = "setup";
|
|
22230
|
+
const startup = new AbortController();
|
|
22231
|
+
const ownershipLost = new AbortController();
|
|
22232
|
+
const drainDelay = new AbortController();
|
|
22137
22233
|
let business;
|
|
22138
22234
|
let listener;
|
|
22235
|
+
let listening;
|
|
22236
|
+
let closePromise;
|
|
22237
|
+
let managementTask;
|
|
22238
|
+
let managementClosed = false;
|
|
22139
22239
|
let maintaining = false;
|
|
22140
22240
|
let draining = false;
|
|
22141
22241
|
let shutdownPromise;
|
|
22142
22242
|
let lastShutdownDrainSec = 0;
|
|
22143
|
-
let actualPort = options.port ?? 8787;
|
|
22144
22243
|
const replicaId = randomUUID11();
|
|
22145
22244
|
const assets = resolveUiAssets(options.uiDir);
|
|
22146
22245
|
const app = new Hono5();
|
|
22147
|
-
|
|
22148
|
-
|
|
22246
|
+
const defaults = secureHeaders();
|
|
22247
|
+
const consent = secureHeaders({ referrerPolicy: "same-origin" });
|
|
22248
|
+
app.use("*", (c, next) => c.req.path === MCP_AUTHORIZE_PATH ? consent(c, next) : defaults(c, next));
|
|
22149
22249
|
app.use("/~setup/*", async (c, next) => {
|
|
22150
22250
|
c.header("Cache-Control", "no-store");
|
|
22151
22251
|
await next();
|
|
22152
22252
|
});
|
|
22253
|
+
const assertOwnershipIntact = () => {
|
|
22254
|
+
if (ownershipLost.signal.aborted) throw new TBError("unavailable", "runtime ownership lost; restart required");
|
|
22255
|
+
};
|
|
22256
|
+
const handoffBlocked = () => ownershipLost.signal.aborted || phase === "starting";
|
|
22257
|
+
const runtimeState = () => ownershipLost.signal.aborted ? "ownership_lost" : phase;
|
|
22153
22258
|
const status = () => ({
|
|
22154
|
-
state: phase,
|
|
22259
|
+
state: handoffBlocked() ? "installing" : phase,
|
|
22155
22260
|
instanceId: state?.instanceId,
|
|
22156
|
-
pairingRequired: phase !== "ready"
|
|
22261
|
+
pairingRequired: !handoffBlocked() && phase !== "ready"
|
|
22157
22262
|
});
|
|
22158
22263
|
const management = {};
|
|
22159
|
-
const
|
|
22264
|
+
const withManagementLock = (run) => store.exclusive(async () => {
|
|
22265
|
+
if (managementClosed) throw new TBError("unavailable", "server is closed");
|
|
22266
|
+
const task = run();
|
|
22267
|
+
managementTask = task;
|
|
22268
|
+
try {
|
|
22269
|
+
return await task;
|
|
22270
|
+
} finally {
|
|
22271
|
+
managementTask = void 0;
|
|
22272
|
+
}
|
|
22273
|
+
});
|
|
22274
|
+
const launch = async (current, input, restoredKeys, signal) => {
|
|
22275
|
+
let candidateLost = false;
|
|
22276
|
+
const checkLaunch = () => {
|
|
22277
|
+
signal?.throwIfAborted();
|
|
22278
|
+
assertOwnershipIntact();
|
|
22279
|
+
if (candidateLost) throw new TBError("unavailable", "runtime ownership lost during preparation");
|
|
22280
|
+
};
|
|
22281
|
+
checkLaunch();
|
|
22282
|
+
if (!current.databaseUrl)
|
|
22283
|
+
throw new TBError("unavailable", "bootstrap database connection is unavailable");
|
|
22160
22284
|
const keys = restoredKeys ?? await store.read("keys.json");
|
|
22161
|
-
if (!keys
|
|
22285
|
+
if (!keys)
|
|
22162
22286
|
throw new TBError(
|
|
22163
22287
|
"unavailable",
|
|
22164
|
-
"local bootstrap secrets
|
|
22288
|
+
"local bootstrap secrets are unavailable"
|
|
22165
22289
|
);
|
|
22166
|
-
|
|
22290
|
+
checkLaunch();
|
|
22291
|
+
const sql = postgres5(current.databaseUrl, {
|
|
22167
22292
|
max: 1,
|
|
22168
22293
|
connect_timeout: 5,
|
|
22169
22294
|
onnotice: () => {
|
|
22170
22295
|
}
|
|
22171
22296
|
});
|
|
22297
|
+
const cancelIdentityCheck = () => {
|
|
22298
|
+
void sql.end({ timeout: 0 }).catch(() => {
|
|
22299
|
+
});
|
|
22300
|
+
};
|
|
22301
|
+
signal?.addEventListener("abort", cancelIdentityCheck, { once: true });
|
|
22172
22302
|
try {
|
|
22173
22303
|
await sql.begin(async (tx) => {
|
|
22174
22304
|
await tx`SELECT pg_advisory_xact_lock(7283020)`;
|
|
@@ -22190,8 +22320,10 @@ async function createManagedServer(options) {
|
|
|
22190
22320
|
await tx`INSERT INTO tb_instance(id,instance_id) VALUES(1,${current.instanceId})`;
|
|
22191
22321
|
});
|
|
22192
22322
|
} finally {
|
|
22323
|
+
signal?.removeEventListener("abort", cancelIdentityCheck);
|
|
22193
22324
|
await sql.end({ timeout: 1 });
|
|
22194
22325
|
}
|
|
22326
|
+
checkLaunch();
|
|
22195
22327
|
const settings = input?.settings ?? runtimeConfigSchema.parse({});
|
|
22196
22328
|
const candidate = createTbServer({
|
|
22197
22329
|
databaseUrl: current.databaseUrl,
|
|
@@ -22224,7 +22356,7 @@ async function createManagedServer(options) {
|
|
|
22224
22356
|
const current2 = await store.state();
|
|
22225
22357
|
if (!current2?.databaseUrl)
|
|
22226
22358
|
throw new TBError("unavailable", "audit authority unavailable");
|
|
22227
|
-
const auditSql =
|
|
22359
|
+
const auditSql = postgres5(current2.databaseUrl, {
|
|
22228
22360
|
max: 1,
|
|
22229
22361
|
connect_timeout: 5,
|
|
22230
22362
|
onnotice: () => {
|
|
@@ -22241,20 +22373,32 @@ async function createManagedServer(options) {
|
|
|
22241
22373
|
pluginCatalog: BUILTIN_CATALOG,
|
|
22242
22374
|
pluginRunnerSocket: options.pluginRunnerSocket,
|
|
22243
22375
|
...options.uiDir ? { uiDir: options.uiDir } : {}
|
|
22376
|
+
}, () => {
|
|
22377
|
+
candidateLost = true;
|
|
22378
|
+
if (business === candidate) ownershipLost.abort();
|
|
22244
22379
|
});
|
|
22380
|
+
const cancelPreparation = () => {
|
|
22381
|
+
void candidate.close().catch(() => {
|
|
22382
|
+
});
|
|
22383
|
+
};
|
|
22384
|
+
signal?.addEventListener("abort", cancelPreparation, { once: true });
|
|
22245
22385
|
try {
|
|
22246
22386
|
await candidate.prepare();
|
|
22387
|
+
checkLaunch();
|
|
22388
|
+
if (business) await business.close();
|
|
22389
|
+
checkLaunch();
|
|
22247
22390
|
} catch (error) {
|
|
22248
22391
|
await candidate.close();
|
|
22249
22392
|
throw error;
|
|
22393
|
+
} finally {
|
|
22394
|
+
signal?.removeEventListener("abort", cancelPreparation);
|
|
22250
22395
|
}
|
|
22251
|
-
await business?.close();
|
|
22252
22396
|
business = candidate;
|
|
22253
22397
|
if (draining) business.startDraining();
|
|
22254
22398
|
if (listener) business.deviceHub.attach(listener);
|
|
22255
22399
|
};
|
|
22256
22400
|
const maintenanceHooks = {
|
|
22257
|
-
exclusive:
|
|
22401
|
+
exclusive: withManagementLock,
|
|
22258
22402
|
readSnapshot: async () => {
|
|
22259
22403
|
const current = await store.state();
|
|
22260
22404
|
if (!current?.databaseUrl)
|
|
@@ -22317,7 +22461,7 @@ async function createManagedServer(options) {
|
|
|
22317
22461
|
};
|
|
22318
22462
|
management.maintenance = new MaintenanceManager(maintenanceHooks);
|
|
22319
22463
|
management.keys = new KeyManager({
|
|
22320
|
-
exclusive:
|
|
22464
|
+
exclusive: withManagementLock,
|
|
22321
22465
|
readSnapshot: async () => ({
|
|
22322
22466
|
...await maintenanceHooks.readSnapshot(),
|
|
22323
22467
|
replicaId
|
|
@@ -22348,41 +22492,78 @@ async function createManagedServer(options) {
|
|
|
22348
22492
|
phase = "ready";
|
|
22349
22493
|
}
|
|
22350
22494
|
});
|
|
22351
|
-
|
|
22352
|
-
state = await store.initialize();
|
|
22353
|
-
if (state.phase === "initialized") {
|
|
22354
|
-
try {
|
|
22355
|
-
await launch(state);
|
|
22356
|
-
phase = "ready";
|
|
22357
|
-
} catch {
|
|
22358
|
-
phase = "recovery";
|
|
22359
|
-
}
|
|
22360
|
-
} else phase = state.phase;
|
|
22361
|
-
} catch {
|
|
22495
|
+
const recover = (stage2, error) => {
|
|
22362
22496
|
phase = "recovery";
|
|
22363
|
-
|
|
22497
|
+
let reason = "dependency_or_io_failure";
|
|
22498
|
+
if (isTBError(error)) reason = error.code;
|
|
22499
|
+
else if (error instanceof SyntaxError) reason = "invalid_json";
|
|
22500
|
+
else if (error instanceof Error && error.name === "ZodError") reason = "invalid_configuration";
|
|
22501
|
+
console.error(JSON.stringify({ event: "tool_bridge_recovery_required", stage: stage2, reason }));
|
|
22502
|
+
};
|
|
22503
|
+
let stage = "bootstrap";
|
|
22504
|
+
const attemptStartup = () => store.withStartupState(state?.instanceId, async (current) => {
|
|
22505
|
+
startup.signal.throwIfAborted();
|
|
22506
|
+
state = current;
|
|
22507
|
+
if (state.phase !== "initialized") {
|
|
22508
|
+
phase = state.phase;
|
|
22509
|
+
return;
|
|
22510
|
+
}
|
|
22511
|
+
stage = "launch";
|
|
22512
|
+
await launch(state, void 0, void 0, startup.signal);
|
|
22513
|
+
phase = "ready";
|
|
22514
|
+
});
|
|
22515
|
+
let reportContention;
|
|
22516
|
+
const contention = new Promise((resolve2) => {
|
|
22517
|
+
reportContention = resolve2;
|
|
22518
|
+
});
|
|
22519
|
+
const startupTask = pRetry(attemptStartup, {
|
|
22520
|
+
signal: startup.signal,
|
|
22521
|
+
retries: Infinity,
|
|
22522
|
+
minTimeout: 1e3,
|
|
22523
|
+
maxTimeout: 1e4,
|
|
22524
|
+
randomize: true,
|
|
22525
|
+
unref: true,
|
|
22526
|
+
shouldRetry: ({ error, attemptNumber }) => {
|
|
22527
|
+
if (!(error instanceof BootstrapLockBusyError || error instanceof RuntimeHandoffPendingError)) return false;
|
|
22528
|
+
if (attemptNumber === 1) {
|
|
22529
|
+
phase = "starting";
|
|
22530
|
+
console.info(JSON.stringify({ event: "tool_bridge_waiting_for_runtime_owner" }));
|
|
22531
|
+
reportContention();
|
|
22532
|
+
}
|
|
22533
|
+
return true;
|
|
22534
|
+
}
|
|
22535
|
+
}).catch((error) => {
|
|
22536
|
+
if (!startup.signal.aborted && !ownershipLost.signal.aborted) recover(stage, error);
|
|
22537
|
+
});
|
|
22538
|
+
await Promise.race([startupTask, contention]);
|
|
22364
22539
|
app.get("/~setup/status", (c) => c.json(status()));
|
|
22540
|
+
app.use("/~setup/*", async (c, next) => {
|
|
22541
|
+
if (handoffBlocked())
|
|
22542
|
+
return c.json({ code: "unavailable", state: runtimeState() }, 503);
|
|
22543
|
+
await next();
|
|
22544
|
+
});
|
|
22545
|
+
app.use("/~setup/*", bodyLimit({ maxSize: 65536 }));
|
|
22365
22546
|
app.get("/~setup/defaults", async (c) => {
|
|
22366
22547
|
await store.authorize(
|
|
22367
22548
|
c.req.header("x-tb-setup-token"),
|
|
22368
22549
|
phase === "recovery" ? "recovery" : "setup"
|
|
22369
22550
|
);
|
|
22370
|
-
const
|
|
22551
|
+
const defaults2 = await store.defaults();
|
|
22371
22552
|
return c.json({
|
|
22372
|
-
databaseConfigured: Boolean(
|
|
22373
|
-
storageConfigured: Boolean(
|
|
22374
|
-
...
|
|
22375
|
-
...
|
|
22553
|
+
databaseConfigured: Boolean(defaults2?.databaseUrl),
|
|
22554
|
+
storageConfigured: Boolean(defaults2?.storage),
|
|
22555
|
+
...defaults2?.databaseUrl ? { databaseHost: new URL(defaults2.databaseUrl).hostname } : {},
|
|
22556
|
+
...defaults2?.storage ? {
|
|
22376
22557
|
storage: {
|
|
22377
|
-
endpoint:
|
|
22378
|
-
bucket:
|
|
22379
|
-
region:
|
|
22558
|
+
endpoint: defaults2.storage.endpoint,
|
|
22559
|
+
bucket: defaults2.storage.bucket,
|
|
22560
|
+
region: defaults2.storage.region
|
|
22380
22561
|
}
|
|
22381
22562
|
} : {},
|
|
22382
|
-
redisConfigured: Boolean(
|
|
22563
|
+
redisConfigured: Boolean(defaults2?.redisUrl)
|
|
22383
22564
|
});
|
|
22384
22565
|
});
|
|
22385
|
-
const configure = async (request2, recovery) =>
|
|
22566
|
+
const configure = async (request2, recovery) => withManagementLock(async () => {
|
|
22386
22567
|
const current = await store.authorize(
|
|
22387
22568
|
request2.headers.get("x-tb-setup-token") ?? void 0,
|
|
22388
22569
|
recovery ? "recovery" : "setup"
|
|
@@ -22416,12 +22597,12 @@ async function createManagedServer(options) {
|
|
|
22416
22597
|
...backup.signingRetireAfter ? { signingRetireAfter: backup.signingRetireAfter } : {}
|
|
22417
22598
|
};
|
|
22418
22599
|
}
|
|
22419
|
-
const
|
|
22600
|
+
const defaults2 = await store.defaults();
|
|
22420
22601
|
const input = {
|
|
22421
|
-
...
|
|
22602
|
+
...defaults2,
|
|
22422
22603
|
...body,
|
|
22423
|
-
databaseUrl: body.databaseUrl ??
|
|
22424
|
-
storage: body.storage ??
|
|
22604
|
+
databaseUrl: body.databaseUrl ?? defaults2?.databaseUrl,
|
|
22605
|
+
storage: body.storage ?? defaults2?.storage
|
|
22425
22606
|
};
|
|
22426
22607
|
if (!input.databaseUrl || !recovery && !input.storage) {
|
|
22427
22608
|
throw new TBError(
|
|
@@ -22435,9 +22616,10 @@ async function createManagedServer(options) {
|
|
|
22435
22616
|
databaseUrl: input.databaseUrl,
|
|
22436
22617
|
redisUrl: input.redisUrl,
|
|
22437
22618
|
// Trust comes only from the local installer defaults, never from the web form.
|
|
22438
|
-
internalS3Origin:
|
|
22619
|
+
internalS3Origin: defaults2?.storage ? new URL(defaults2.storage.endpoint).origin : current.internalS3Origin,
|
|
22439
22620
|
revision: current.revision + 1
|
|
22440
22621
|
};
|
|
22622
|
+
assertOwnershipIntact();
|
|
22441
22623
|
phase = "installing";
|
|
22442
22624
|
await store.write(
|
|
22443
22625
|
recovery ? "bootstrap-pending.json" : "bootstrap.json",
|
|
@@ -22446,6 +22628,7 @@ async function createManagedServer(options) {
|
|
|
22446
22628
|
if (!recovery) state = next;
|
|
22447
22629
|
try {
|
|
22448
22630
|
await launch(next, input, restoredKeys);
|
|
22631
|
+
assertOwnershipIntact();
|
|
22449
22632
|
if (restoredKeys) await store.write("keys.json", restoredKeys);
|
|
22450
22633
|
await store.finish(next);
|
|
22451
22634
|
state = await store.state();
|
|
@@ -22475,17 +22658,19 @@ async function createManagedServer(options) {
|
|
|
22475
22658
|
(c) => c.json({
|
|
22476
22659
|
healthy: true,
|
|
22477
22660
|
version: package_default.version,
|
|
22478
|
-
state:
|
|
22661
|
+
state: runtimeState(),
|
|
22479
22662
|
instanceId: state?.instanceId
|
|
22480
22663
|
})
|
|
22481
22664
|
);
|
|
22482
22665
|
app.get(
|
|
22483
22666
|
"/readyz",
|
|
22484
|
-
async (c) => business && phase === "ready" && !maintaining ? business.app.fetch(c.req.raw) : c.json({ ready: false, state:
|
|
22667
|
+
async (c) => business && phase === "ready" && !maintaining && !ownershipLost.signal.aborted ? business.app.fetch(c.req.raw) : c.json({ ready: false, state: runtimeState() }, 503)
|
|
22485
22668
|
);
|
|
22486
22669
|
app.all("*", async (c) => {
|
|
22487
|
-
if (phase === "ready" && business && !maintaining)
|
|
22670
|
+
if (phase === "ready" && business && !maintaining && !ownershipLost.signal.aborted)
|
|
22488
22671
|
return business.app.fetch(c.req.raw);
|
|
22672
|
+
if (handoffBlocked())
|
|
22673
|
+
return c.json({ code: "unavailable", state: runtimeState() }, 503);
|
|
22489
22674
|
const path = new URL(c.req.url).pathname;
|
|
22490
22675
|
if ((path === "/ui" || path.startsWith("/ui/")) && assets)
|
|
22491
22676
|
return serveUiAssets(c.req.raw, assets);
|
|
@@ -22528,47 +22713,80 @@ async function createManagedServer(options) {
|
|
|
22528
22713
|
});
|
|
22529
22714
|
const startDraining = () => {
|
|
22530
22715
|
draining = true;
|
|
22716
|
+
startup.abort();
|
|
22531
22717
|
business?.startDraining();
|
|
22532
22718
|
};
|
|
22533
|
-
const close = async () => {
|
|
22534
|
-
|
|
22535
|
-
|
|
22536
|
-
|
|
22719
|
+
const close = () => closePromise ??= (async () => {
|
|
22720
|
+
startDraining();
|
|
22721
|
+
drainDelay.abort();
|
|
22722
|
+
await listening?.catch(() => {
|
|
22723
|
+
});
|
|
22724
|
+
const socket = listener;
|
|
22725
|
+
const closed = socket?.listening ? new Promise((resolve2, reject) => {
|
|
22726
|
+
socket.close((error) => error ? reject(error) : resolve2());
|
|
22727
|
+
socket.closeIdleConnections();
|
|
22537
22728
|
}) : Promise.resolve();
|
|
22538
|
-
|
|
22539
|
-
|
|
22540
|
-
|
|
22541
|
-
|
|
22542
|
-
|
|
22543
|
-
|
|
22544
|
-
|
|
22729
|
+
let previous;
|
|
22730
|
+
const closeRuntime = async () => {
|
|
22731
|
+
await startupTask;
|
|
22732
|
+
previous = business;
|
|
22733
|
+
await previous?.close();
|
|
22734
|
+
};
|
|
22735
|
+
const disconnectClients = () => socket?.closeAllConnections();
|
|
22736
|
+
ownershipLost.signal.addEventListener("abort", disconnectClients, { once: true });
|
|
22737
|
+
if (ownershipLost.signal.aborted) disconnectClients();
|
|
22738
|
+
try {
|
|
22739
|
+
const [runtime, connections] = await Promise.allSettled([closeRuntime(), closed]);
|
|
22740
|
+
managementClosed = true;
|
|
22741
|
+
await managementTask?.catch(() => {
|
|
22742
|
+
});
|
|
22743
|
+
if (business !== previous) await business?.close();
|
|
22744
|
+
if (runtime.status === "rejected") throw runtime.reason;
|
|
22745
|
+
if (connections.status === "rejected") throw connections.reason;
|
|
22746
|
+
} finally {
|
|
22747
|
+
ownershipLost.signal.removeEventListener("abort", disconnectClients);
|
|
22748
|
+
listener = void 0;
|
|
22749
|
+
business = void 0;
|
|
22750
|
+
}
|
|
22751
|
+
})();
|
|
22545
22752
|
return {
|
|
22546
22753
|
app,
|
|
22547
22754
|
store,
|
|
22755
|
+
ownershipLost: ownershipLost.signal,
|
|
22548
22756
|
async start() {
|
|
22549
|
-
|
|
22550
|
-
|
|
22551
|
-
|
|
22552
|
-
|
|
22553
|
-
|
|
22554
|
-
|
|
22555
|
-
|
|
22556
|
-
|
|
22557
|
-
|
|
22558
|
-
|
|
22559
|
-
|
|
22560
|
-
|
|
22561
|
-
|
|
22562
|
-
|
|
22563
|
-
|
|
22757
|
+
if (draining) throw new TBError("unavailable", "server is shutting down");
|
|
22758
|
+
return listening ??= (async () => {
|
|
22759
|
+
const bind = state ?? (phase === "starting" ? await store.state() : void 0);
|
|
22760
|
+
return new Promise((resolve2, reject) => {
|
|
22761
|
+
listener = serve2(
|
|
22762
|
+
{
|
|
22763
|
+
fetch: app.fetch,
|
|
22764
|
+
port: options.port ?? bind?.port ?? 8787,
|
|
22765
|
+
hostname: options.host ?? bind?.host ?? "0.0.0.0"
|
|
22766
|
+
},
|
|
22767
|
+
(info) => {
|
|
22768
|
+
if (listener && !draining && !ownershipLost.signal.aborted) business?.deviceHub.attach(listener);
|
|
22769
|
+
resolve2({ port: info.port });
|
|
22770
|
+
}
|
|
22771
|
+
);
|
|
22772
|
+
listener.once("error", reject);
|
|
22773
|
+
});
|
|
22774
|
+
})();
|
|
22564
22775
|
},
|
|
22565
22776
|
startDraining,
|
|
22566
22777
|
close,
|
|
22567
22778
|
shutdown() {
|
|
22779
|
+
if (closePromise) return closePromise;
|
|
22568
22780
|
shutdownPromise ??= (async () => {
|
|
22569
22781
|
startDraining();
|
|
22570
22782
|
const seconds = business?.shutdownDrainSec ?? lastShutdownDrainSec;
|
|
22571
|
-
if (seconds > 0)
|
|
22783
|
+
if (seconds > 0) {
|
|
22784
|
+
try {
|
|
22785
|
+
await delay(seconds * 1e3, void 0, { signal: drainDelay.signal });
|
|
22786
|
+
} catch (error) {
|
|
22787
|
+
if (!drainDelay.signal.aborted) throw error;
|
|
22788
|
+
}
|
|
22789
|
+
}
|
|
22572
22790
|
await close();
|
|
22573
22791
|
})();
|
|
22574
22792
|
return shutdownPromise;
|
|
@@ -25,6 +25,11 @@ var stateSchema = z.strictObject({
|
|
|
25
25
|
port: z.number().int().min(0).max(65535).default(8787),
|
|
26
26
|
host: z.string().default("0.0.0.0")
|
|
27
27
|
});
|
|
28
|
+
var BootstrapLockBusyError = class extends TBError {
|
|
29
|
+
constructor() {
|
|
30
|
+
super("conflict", "another local maintenance operation is running");
|
|
31
|
+
}
|
|
32
|
+
};
|
|
28
33
|
var BootstrapStateStore = class {
|
|
29
34
|
constructor(directory) {
|
|
30
35
|
this.directory = directory;
|
|
@@ -41,7 +46,7 @@ var BootstrapStateStore = class {
|
|
|
41
46
|
update: 1e4
|
|
42
47
|
}).catch((error) => {
|
|
43
48
|
if (error.code === "ELOCKED") {
|
|
44
|
-
throw new
|
|
49
|
+
throw new BootstrapLockBusyError();
|
|
45
50
|
}
|
|
46
51
|
throw error;
|
|
47
52
|
});
|
|
@@ -78,38 +83,45 @@ var BootstrapStateStore = class {
|
|
|
78
83
|
return value === void 0 ? void 0 : stateSchema.parse(value);
|
|
79
84
|
}
|
|
80
85
|
async initialize() {
|
|
81
|
-
return this.exclusive(
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
86
|
+
return this.exclusive(() => this.readOrInitialize(), 5);
|
|
87
|
+
}
|
|
88
|
+
/** Keep bootstrap reads, including the first initialization, locked through admission. */
|
|
89
|
+
async withStartupState(initializedInstanceId, admit) {
|
|
90
|
+
return this.exclusive(async () => admit(await this.readOrInitialize(initializedInstanceId)));
|
|
91
|
+
}
|
|
92
|
+
async readOrInitialize(initializedInstanceId) {
|
|
93
|
+
const current = await this.state();
|
|
94
|
+
if (initializedInstanceId && current?.instanceId !== initializedInstanceId)
|
|
95
|
+
throw new TBError("conflict", "bootstrap identity changed during handoff");
|
|
96
|
+
if (current) {
|
|
97
|
+
if (initializedInstanceId || await this.read("initialized.json"))
|
|
98
|
+
return { ...current, phase: "initialized" };
|
|
99
|
+
return current;
|
|
100
|
+
}
|
|
101
|
+
if (await this.read("identity.json"))
|
|
102
|
+
throw new TBError(
|
|
103
|
+
"unavailable",
|
|
104
|
+
"bootstrap state requires local recovery"
|
|
105
|
+
);
|
|
106
|
+
const state = {
|
|
107
|
+
instanceId: randomUUID(),
|
|
108
|
+
revision: 1,
|
|
109
|
+
phase: "setup",
|
|
110
|
+
port: 8787,
|
|
111
|
+
host: "0.0.0.0"
|
|
112
|
+
};
|
|
113
|
+
await this.write("identity.json", { instanceId: state.instanceId });
|
|
114
|
+
await this.write("keys.json", {
|
|
115
|
+
keyring: createEncryptionKeyring(randomBytes(32).toString("base64url")),
|
|
116
|
+
storeTokenKeyring: createEncryptionKeyring(
|
|
117
|
+
randomBytes(32).toString("base64url")
|
|
118
|
+
),
|
|
119
|
+
oauthKey: randomBytes(32).toString("base64url"),
|
|
120
|
+
adminSk: `tb_sk_${randomBytes(32).toString("base64url")}`
|
|
121
|
+
});
|
|
122
|
+
await this.write("bootstrap.json", state);
|
|
123
|
+
await this.pair(state.instanceId, "setup");
|
|
124
|
+
return state;
|
|
113
125
|
}
|
|
114
126
|
async pair(instanceId, mode) {
|
|
115
127
|
const token = randomBytes(32).toString("base64url");
|
|
@@ -216,7 +228,7 @@ var BootstrapStateStore = class {
|
|
|
216
228
|
// package.json
|
|
217
229
|
var package_default = {
|
|
218
230
|
name: "@tool-bridge/server",
|
|
219
|
-
version: "0.
|
|
231
|
+
version: "0.27.0",
|
|
220
232
|
description: "Self-hosted Tool Bridge Node server with PostgreSQL, S3 object storage and WebSocket device channels",
|
|
221
233
|
type: "module",
|
|
222
234
|
license: "MIT",
|
|
@@ -299,6 +311,7 @@ var package_default = {
|
|
|
299
311
|
};
|
|
300
312
|
|
|
301
313
|
export {
|
|
314
|
+
BootstrapLockBusyError,
|
|
302
315
|
BootstrapStateStore,
|
|
303
316
|
package_default
|
|
304
317
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1764,6 +1764,9 @@ declare class BootstrapStateStore {
|
|
|
1764
1764
|
write(name: string, value: unknown): Promise<void>;
|
|
1765
1765
|
state(): Promise<BootstrapState | undefined>;
|
|
1766
1766
|
initialize(): Promise<BootstrapState>;
|
|
1767
|
+
/** Keep bootstrap reads, including the first initialization, locked through admission. */
|
|
1768
|
+
withStartupState(initializedInstanceId: string | undefined, admit: (state: BootstrapState) => Promise<void>): Promise<void>;
|
|
1769
|
+
private readOrInitialize;
|
|
1767
1770
|
private pair;
|
|
1768
1771
|
createLocalPairing(mode: Pairing['mode']): Promise<string>;
|
|
1769
1772
|
private hash;
|
|
@@ -2327,6 +2330,7 @@ interface ManagedServerOptions {
|
|
|
2327
2330
|
declare function createManagedServer(options: ManagedServerOptions): Promise<{
|
|
2328
2331
|
app: Hono<hono_types.BlankEnv, hono_types.BlankSchema, "/">;
|
|
2329
2332
|
store: BootstrapStateStore;
|
|
2333
|
+
ownershipLost: AbortSignal;
|
|
2330
2334
|
start(): Promise<{
|
|
2331
2335
|
port: number;
|
|
2332
2336
|
}>;
|
|
@@ -2632,6 +2636,6 @@ interface TbServer {
|
|
|
2632
2636
|
state: StateStore;
|
|
2633
2637
|
storage: StorageManager;
|
|
2634
2638
|
}
|
|
2635
|
-
declare function createTbServer(config: ServerConfig): TbServer;
|
|
2639
|
+
declare function createTbServer(config: ServerConfig, onOwnershipLost?: () => void): TbServer;
|
|
2636
2640
|
|
|
2637
2641
|
export { BootstrapStateStore, DEVICE_FORWARD_TIMEOUT_MS, DEVICE_ROUTE_TTL_SEC, DEVICE_WS_PATH, DeviceHub, type DeviceLocalCall, DeviceRouter, type DeviceRouterBackend, type KeyManagementHooks, KeyManager, type MaintenanceHooks, MaintenanceManager, type ManagedServerOptions, PgEventRepository, PgKeyRotation, PgMailboxRepository, PgSearchIndex, PgStateStore, PgStoreRepository, RedisDeviceRouterBackend, type S3ObjectStore, type S3ObjectStoreOptions, type S3ProbeResult, type ServerConfig, StorageManager, type TbServer, createManagedServer, createS3ObjectStore, createTbServer, probeS3ObjectStore, runtimeAppSettings };
|
package/dist/index.js
CHANGED
|
@@ -19,11 +19,11 @@ import {
|
|
|
19
19
|
createTbServer,
|
|
20
20
|
probeS3ObjectStore,
|
|
21
21
|
runtimeAppSettings
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-IZZ5C42L.js";
|
|
23
23
|
import "./chunk-U7PTOA3U.js";
|
|
24
24
|
import {
|
|
25
25
|
BootstrapStateStore
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-TMO3OAV5.js";
|
|
27
27
|
import "./chunk-NXLE6ZEK.js";
|
|
28
28
|
import "./chunk-6W5WJCKR.js";
|
|
29
29
|
import "./chunk-4WDQGEOC.js";
|
package/dist/main.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
createManagedServer
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-IZZ5C42L.js";
|
|
5
5
|
import "./chunk-U7PTOA3U.js";
|
|
6
6
|
import {
|
|
7
7
|
package_default
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-TMO3OAV5.js";
|
|
9
9
|
import "./chunk-NXLE6ZEK.js";
|
|
10
10
|
import "./chunk-6W5WJCKR.js";
|
|
11
11
|
import "./chunk-4WDQGEOC.js";
|
|
@@ -51,12 +51,14 @@ var program = new Command("tool-bridge-server").version(package_default.version)
|
|
|
51
51
|
stopping = true;
|
|
52
52
|
console.log(JSON.stringify({ event: "tool_bridge_draining" }));
|
|
53
53
|
void server.shutdown().then(
|
|
54
|
-
() => process.exit(0),
|
|
54
|
+
() => process.exit(server.ownershipLost.aborted ? 1 : 0),
|
|
55
55
|
() => process.exit(1)
|
|
56
56
|
);
|
|
57
57
|
};
|
|
58
58
|
process.on("SIGINT", shutdown);
|
|
59
59
|
process.on("SIGTERM", shutdown);
|
|
60
|
+
server.ownershipLost.addEventListener("abort", shutdown, { once: true });
|
|
61
|
+
if (server.ownershipLost.aborted) shutdown();
|
|
60
62
|
});
|
|
61
63
|
try {
|
|
62
64
|
await program.parseAsync();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tool-bridge/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"description": "Self-hosted Tool Bridge Node server with PostgreSQL, S3 object storage and WebSocket device channels",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -60,8 +60,8 @@
|
|
|
60
60
|
"@types/write-file-atomic": "^4.0.3",
|
|
61
61
|
"@types/proper-lockfile": "^4.1.4",
|
|
62
62
|
"@types/negotiator": "^0.6.4",
|
|
63
|
-
"@tool-bridge/app": "0.25.0",
|
|
64
63
|
"@tool-bridge/core": "0.1.0",
|
|
64
|
+
"@tool-bridge/app": "0.25.0",
|
|
65
65
|
"@tool-bridge/plugins": "0.1.0"
|
|
66
66
|
},
|
|
67
67
|
"repository": {
|