@quolu/lattice 0.118.0 → 0.118.1

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.
@@ -37,16 +37,21 @@ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
37
37
  fail('LATTICE_HUB_PORT_INVALID', 'LATTICE_HUB_PORT must be an integer in 1..65535');
38
38
  }
39
39
 
40
- const allowedHostsValue = env.LATTICE_HUB_ALLOWED_HOSTS ?? '';
41
- const allowedHosts = new Set(allowedHostsValue.split(',').map((host) => host.trim()).filter((host) => host.length > 0));
40
+ function hostSet(value = '') {
41
+ return new Set(value.split(',').map((host) => host.trim()).filter(Boolean));
42
+ }
43
+
44
+ const allowedHosts = hostSet(env.LATTICE_HUB_ALLOWED_HOSTS);
42
45
  if (allowedHosts.size === 0) {
43
46
  fail('LATTICE_HUB_ALLOWED_HOSTS_REQUIRED',
44
47
  'LATTICE_HUB_ALLOWED_HOSTS must list at least one allowed Host (comma-separated), e.g. lattice.kitepon.dev');
45
48
  }
46
49
 
50
+ const readOnlyHosts = hostSet(env.LATTICE_HUB_READ_ONLY_HOSTS);
51
+
47
52
  let hub;
48
53
  try {
49
- hub = await startBridgeHubServer({ port, allowedHosts, listenAddress, env });
54
+ hub = await startBridgeHubServer({ port, allowedHosts, readOnlyHosts, listenAddress, env });
50
55
  } catch (error) {
51
56
  fail(error?.code ?? 'BRIDGE_HUB_START_FAILED', error?.message ?? 'bridge hub server failed to start');
52
57
  }
@@ -210,6 +210,12 @@ hubへ繋いでいる端末では、`runtime.last_heartbeat`が最後にhubへ
210
210
  無いprojectは配信から外れる。heartbeatの90秒TTLは、配信そのものが止まった時
211
211
  (daemon停止)にofflineへ落とすためのもので、鮮度窓ではない。
212
212
 
213
+ The hub keeps the offline status for one further heartbeat interval (30 seconds).
214
+ Starting at 120 seconds since the last heartbeat, its startup or next 30-second
215
+ cleanup removes the route from `terminals.json`. A returning terminal advertises
216
+ its projects again through the normal heartbeat. See the
217
+ [hub registry data flow](https://github.com/kitepon/Lattice/blob/main/docs/architecture/dfd-bridge-persistence.md#public-hub-terminal-registry).
218
+
213
219
  ### 焼き込むnode pathの選び方(ADR 0163)
214
220
 
215
221
  常駐設定へ焼くnodeのpathは、版付きの実体(homebrewの`Cellar/node/<version>/bin/node`、nvm-windowsの
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.118.0",
3
+ "version": "0.118.1",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
@@ -25,9 +25,8 @@
25
25
  * - A project_id already owned by a *different* terminal is a conflict unless
26
26
  * named in `adopt`. Conflicts are collected and reported together — a batch
27
27
  * never partially lands, so a caller is never left unsure which half won.
28
- * - Staleness is read-time only. `projectBridgeHubRegistry` marks an entry
29
- * 'offline' once `last_seen_at` exceeds the TTL; it never deletes the entry.
30
- * The plan's fail-closed requirement is "show offline", not "make it vanish".
28
+ * - `projectBridgeHubRegistry` marks a retained entry 'offline' once its
29
+ * `last_seen_at` exceeds the TTL. The hub server separately expires entries.
31
30
  */
32
31
 
33
32
  const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
@@ -128,7 +127,7 @@ export function applyBridgeHubRegistration({ registry, request, remoteAddress, n
128
127
  //
129
128
  // owner offline (no heartbeat within the TTL) — the entry is very likely a
130
129
  // leftover from a terminal that moved on, so the live claimant takes it
131
- // over. Nothing else ever retracts it: entries are never expired.
130
+ // over. The hub server also sweeps expired entries from disk.
132
131
  // owner online — the project genuinely belongs to another live terminal.
133
132
  // Reject just that id and report it, so the operator can adopt on purpose.
134
133
  // Handing it over unconditionally would make two live terminals trade
@@ -190,10 +189,7 @@ export function applyBridgeHubRegistration({ registry, request, remoteAddress, n
190
189
 
191
190
  /**
192
191
  * Read-time projection for the aggregate `/projects/` view and per-project
193
- * routing. Never mutates or drops entries — a terminal that stopped
194
- * heartbeating shows as 'offline' forever, not gone, until it re-registers, a
195
- * different terminal explicitly adopts the project, or a different terminal
196
- * claims it while this one is past the TTL (see applyBridgeHubRegistration).
192
+ * routing. Marks retained routes offline without mutating the registry.
197
193
  */
198
194
  export function projectBridgeHubRegistry({ registry, now = new Date(), ttlMs = BRIDGE_HUB_HEARTBEAT_TTL_MS }) {
199
195
  if (!validRegistry(registry)) {
@@ -32,7 +32,7 @@ import path from 'node:path';
32
32
  import { domainToASCII } from 'node:url';
33
33
 
34
34
  import {
35
- applyBridgeHubRegistration, BRIDGE_HUB_HEARTBEAT_TTL_MS, BridgeHubProtocolError,
35
+ applyBridgeHubRegistration, BRIDGE_HUB_HEARTBEAT_INTERVAL_MS, BRIDGE_HUB_HEARTBEAT_TTL_MS, BridgeHubProtocolError,
36
36
  projectBridgeHubRegistry, validateBridgeHubRegistryEntry,
37
37
  } from './bridge-hub-protocol.mjs';
38
38
  import { escapeHtml, renderBridgeHubLanding } from './bridge-hub-landing.mjs';
@@ -198,11 +198,9 @@ function respondProjectStatus(incoming, response, status, code, projectId, reque
198
198
  response.end(html);
199
199
  }
200
200
 
201
- // --- A single async mutex guarding the registration critical section
202
- // (read -> apply -> write) against two concurrent registration requests
203
- // racing each other's read before either has written, which would lose one
204
- // terminal's update. File-level durability (atomic rename, 0600, a lock
205
- // file) is a separate concern owned by writeBridgeHubRegistry below. ---
201
+ // Registration and expiry share the read -> apply -> write critical section
202
+ // so a sweep cannot erase a heartbeat it has not seen. File durability is
203
+ // owned by writeBridgeHubRegistry below.
206
204
 
207
205
  function createMutex() {
208
206
  let queue = Promise.resolve();
@@ -426,7 +424,7 @@ export async function writeBridgeHubRegistry({ env = process.env, entries }) {
426
424
  // === HTTP server ===
427
425
 
428
426
  export async function startBridgeHubServer({
429
- registryStore, port = 0, allowedHosts, env = process.env, fetchImpl = fetch,
427
+ registryStore, port = 0, allowedHosts, readOnlyHosts = new Set(), env = process.env, fetchImpl = fetch,
430
428
  now = () => new Date(), ttlMs = BRIDGE_HUB_HEARTBEAT_TTL_MS, listenAddress = LOOPBACK,
431
429
  } = {}) {
432
430
  // fetchImpl is accepted for DI parity with the rest of this codebase's bridge
@@ -450,11 +448,24 @@ export async function startBridgeHubServer({
450
448
  throw new BridgeHubServerError('BRIDGE_HUB_CONFIG_INVALID', 'listenAddress must be an IP literal');
451
449
  }
452
450
  const normalizedAllowedHosts = new Set([...allowedHosts].map(normalizeHubAllowedHost));
451
+ const normalizedReadOnlyHosts = new Set([...readOnlyHosts].map(normalizeHubAllowedHost));
453
452
  const store = registryStore ?? {
454
453
  read: () => readBridgeHubRegistry({ env }),
455
454
  write: (entries) => writeBridgeHubRegistry({ env, entries }),
456
455
  };
457
- const registrationLock = createMutex();
456
+ const registryLock = createMutex();
457
+
458
+ function expireRegistrations() {
459
+ return registryLock(async () => {
460
+ const entries = await store.read();
461
+ const cutoff = now().getTime() - ttlMs - BRIDGE_HUB_HEARTBEAT_INTERVAL_MS;
462
+ const retained = entries.filter((entry) => !(Date.parse(entry.last_seen_at) <= cutoff));
463
+ if (retained.length < entries.length) await store.write(retained);
464
+ }).catch(() => {
465
+ process.emitWarning('hub could not remove expired terminal registrations',
466
+ { code: 'LATTICE_BRIDGE_HUB_EXPIRY_FAILED' });
467
+ });
468
+ }
458
469
 
459
470
  async function handleRegister(incoming, response) {
460
471
  if (incoming.method !== 'POST') {
@@ -480,7 +491,7 @@ export async function startBridgeHubServer({
480
491
  }
481
492
  let result;
482
493
  try {
483
- result = await registrationLock(async () => {
494
+ result = await registryLock(async () => {
484
495
  const entries = await store.read();
485
496
  const applied = applyBridgeHubRegistration({
486
497
  registry: entries, request, remoteAddress, now: now(), ttlMs,
@@ -616,13 +627,19 @@ export async function startBridgeHubServer({
616
627
  respondError(response, 421, 'BRIDGE_HOST_NOT_ALLOWED');
617
628
  return;
618
629
  }
630
+ const readOnly = normalizedReadOnlyHosts.has(host.hostname);
631
+ if (readOnly && incoming.method !== 'GET') {
632
+ response.setHeader('allow', 'GET');
633
+ respondError(response, 405, 'BRIDGE_HUB_METHOD_NOT_ALLOWED');
634
+ return;
635
+ }
619
636
  let requestUrl;
620
637
  try { requestUrl = validatedHubRequestTarget(incoming.url); } catch (error) {
621
638
  respondError(response, 400, error?.code ?? 'BRIDGE_HUB_REQUEST_TARGET_INVALID');
622
639
  return;
623
640
  }
624
641
  const rawPath = requestUrl.split('?', 1)[0];
625
- if (rawPath === '/__lattice/hub/register') { await handleRegister(incoming, response); return; }
642
+ if (!readOnly && rawPath === '/__lattice/hub/register') { await handleRegister(incoming, response); return; }
626
643
  // The landing (ADR 0164) serves the same page at `/` and `/projects/`
627
644
  // (the old `/` -> `/projects/` 301 is retired: both public inbound links
628
645
  // land on the product face), with the EN variant path-separated under
@@ -658,15 +675,29 @@ export async function startBridgeHubServer({
658
675
  const boundAddress = server.address();
659
676
  const actualPort = typeof boundAddress === 'object' && boundAddress !== null ? boundAddress.port : port;
660
677
  let closed = false;
678
+ let expiryTimer;
679
+ let expiry;
680
+ function scheduleExpiry() {
681
+ expiryTimer = setTimeout(() => {
682
+ expiry = expireRegistrations().then(() => {
683
+ if (!closed) scheduleExpiry();
684
+ });
685
+ }, BRIDGE_HUB_HEARTBEAT_INTERVAL_MS);
686
+ expiryTimer.unref();
687
+ }
688
+ await expireRegistrations();
689
+ scheduleExpiry();
661
690
  return Object.freeze({
662
691
  host: listenAddress,
663
692
  port: actualPort,
664
693
  close: async () => {
665
694
  if (closed) return;
666
695
  closed = true;
696
+ clearTimeout(expiryTimer);
667
697
  const completion = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
668
698
  server.closeAllConnections?.();
669
699
  await completion;
700
+ await expiry;
670
701
  },
671
702
  });
672
703
  }