Skip to content

Part E. The Node adapter: what will be built

Rule for the whole part: the Worker code runs unchanged. The adapter only supplies the Cloudflare pieces the code calls. No feature is added and no setting default changes in this migration. Building starts only after you review this plan and say go.

  1. List every Cloudflare-only thing used by cloudflare/worker.js and cloudflare/core/*.mjs: the Durable Object calls, WebSocket calls, waitUntil, crypto, fetch to other services, KV or R2 bindings if any, caches, HTMLRewriter, scheduled handlers (cron triggers).
  2. List every environment variable and secret the Worker reads (names only, no values) so the env file in F.3 is complete.
  3. List the ingestion paths, the key header name and the sign-in and control paths, so the Cloudflare rules in D.6 and D.7 are exact.
  4. The result is the page Audit E1 and is repeated in the pull request description. Anything with no Node equivalent gets a written replacement before step E2.

E.2 The files (proposed names; confirmed when built)

Section titled “E.2 The files (proposed names; confirmed when built)”
File Job
node/server.mjs Starts the HTTP server on 127.0.0.1:8080, upgrades WebSockets, wires everything, handles shutdown.
node/do-shim.mjs Imitates the Durable Object state: storage, alarms, WebSocket hibernation calls, blockConcurrencyWhile, waitUntil.
node/pg-kv.mjs The key-value store over PostgreSQL (hub.kv), with the in-memory cache and the write-behind queue.
node/ws-bridge.mjs Connects the ws library to the Durable Object WebSocket API (tags, attachments, ping-pong auto-response).
node/env.mjs Reads the env file and builds the env object the Worker expects (secrets and variables).
node/research-proxy.mjs Forwards /research to 127.0.0.1:8787 and checks the Access header.
node/host-routes.mjs Answers each route only on its own hostname (E.5, item 5) and answers 503 with Retry-After in maintenance mode.
db/migrate.mjs and db/migrations/0001_layer1.sql The migration runner and the Layer 1 tables (C.2).
tests/node-parity.mjs Runs the same test requests against the Worker code in Node and compares answers.
deploy/ The systemd units and timers, the OnFailure drop-in, install.sh, backup.sh (bideward-backup), alert.sh (bideward-alert), watch.sh (bideward-watch), update.sh (bideward-update), maintenance.sh (bideward-maintenance), of Part F, Part J and Part K.
deploy/downpage-worker.js, deploy/wrangler-downpage.toml The free-plan “back shortly” Worker of D.11 and its deploy file.

E.3 The Durable Object calls and what answers them

Section titled “E.3 The Durable Object calls and what answers them”
Worker calls The Node adapter does
storage.get(key or keys) Looks in the cache first; on a miss reads hub.kv and caches the row.
storage.put(key, value) or put(object) Updates the cache at once and queues one upsert. The call returns when the cache is updated, except for durable keys (E.5), which return only after the database commit.
storage.delete(key or keys) Removes from cache; queues the delete (same rule).
storage.list({prefix, start, end, limit, reverse}) Answered from the database with the text_pattern_ops index on k, merged with pending cache changes so results are exact.
storage.setAlarm, getAlarm, deleteAlarm One row in hub.alarms and one timer in the process; at start it re-arms from the row; a due alarm runs at once.
blockConcurrencyWhile, storage.transaction One in-process queue so two requests never interleave inside a critical section, as in a Durable Object.
state.acceptWebSocket(ws, tags) and getWebSockets(tag) The ws bridge keeps a registry by tag.
ws.serializeAttachment and deserializeAttachment Kept with the socket in memory and mirrored to hub.kv so a restart can rebuild it.
setWebSocketAutoResponse (ping to pong) The bridge answers at once without waking the application code.
webSocketMessage, webSocketClose, webSocketError Called from the ws events.
ctx.waitUntil(promise) The promise is tracked; shutdown waits for it (up to a limit).
env.STATS_HUB.idFromName(…).get(…).fetch(…) An in-process stub that calls the one hub object directly.
crypto.subtle, crypto.randomUUID, Request, Response, Headers, fetch Provided by Node 22.

The hub holds its data in memory and writes behind, so two copies running at once would corrupt each other. At start the process takes a PostgreSQL advisory lock (pg_try_advisory_lock on a fixed number) on a connection it keeps open. If it cannot get the lock at start it exits at once with an error. systemd restarts only one copy, and the lock covers the case of a mistaken second start.

If the database goes away while the hub runs (built in branch 3). The lock lives on a database connection, so a database outage also drops the lock. The hub does not exit: it keeps answering from memory, refuses every write with 503 (nothing is written without the lock), and /health says down and /health/detail shows lock.held: false until the lock is back. It re-takes the lock on its own (a retry every 0.5 s, growing to 5 s) and carries on without a restart. If the lock is taken again by another hub, this one exits with an error at once, so systemd starts it fresh and there are never two writers. The check runs every LOCK_CHECK_MS (default 5000 ms). This resolves the conflict between this rule and the database-down test of E.6 item 4 (“recovery without a restart of the hub”).

Class Keys Rule
Durable users, sessions, control secret, loader tokens, releases, instance numbers, bot identity, money and take-profit and ruin records, state mirror The call returns after the database commit with synchronous_commit on. Lost data here is never acceptable.
Fast round log, crash history, rates, realtime flags, statistics snapshots The call returns at once; the queue is flushed every 250 ms in one transaction with synchronous_commit off. A crash of the whole server could lose at most the last fraction of a second of this class, which the bots re-send; PostgreSQL itself never corrupts.
  1. A bet never waits for the database. The receiver records the bet in memory and answers; the commit follows within milliseconds.
  2. If PostgreSQL stops, durable calls fail with a clear 503 and the dashboard shows it; the bots keep betting on their own side (they do not depend on the receiver to bet).
  3. On shutdown (systemctl stop), the process stops accepting, flushes the queue, waits for pending work, then exits. On kill -9 or power loss, only the fast class’s last moments are at risk.
  4. The queue length and the flush time are exposed on the health endpoint (Part K) so a slow database is seen before it hurts.
  5. Host-based routes. The hub reads the Host header. Dashboard, sign-in, admin and /research routes answer only on app.bideward.com; ingestion, loader, release, feed and health routes answer only on api.bideward.com; anything else on either name is 404. This keeps the dashboard and the bots’ API apart without any change to the Worker code (the router is a thin layer in front of it) and leaves the dashboard’s own calls same-origin.

The adapter is in node/; the receiver code is not touched. One process, node node/server.mjs, listens on 127.0.0.1:8080 (setting PORT, HOST must stay loopback).

File Job
node/server.mjs Wiring, the single-writer lock, start and stop
node/pg-kv.mjs The storage on PostgreSQL: durable and fast keys, cache, queue
node/do-shim.mjs ctx, the alarm, the STATS_HUB binding
node/ws-bridge.mjs WebSocket pair, ping/pong, heartbeat
node/host-routes.mjs Which route answers on which host; maintenance mode
node/research-proxy.mjs The Cloudflare Access check on /research
node/env.mjs, node/health.mjs, node/html-hook.mjs Settings, health, page imports

Adapter settings (in the env file, Part F): HOST, PORT, NODE_ENV, APP_HOST, API_HOST, MAINTENANCE_FILE, ACCESS_TEAM, ACCESS_AUD, MAX_BODY_MB, CACHE_MAX_MB, FLUSH_MS, SHUTDOWN_WAIT_SEC, WS_PING_SEC, DB_POOL_MAX, LOG_LEVEL, LOCK_CHECK_MS. A name that looks like ours but is misspelt is reported at start.

Health: GET /health on api.bideward.com (and on the server itself) answers the single word ok. GET /health/detail answers only on the server itself, with the numbers Part K watches. Maintenance mode: create the file named in MAINTENANCE_FILE; every route except /health answers 503 with Retry-After until it is removed.

E.6 Tests that must pass before any deploy

Section titled “E.6 Tests that must pass before any deploy”
  1. The existing receiver test suite, run against the Worker code in Node. Every test that passed on the Worker must pass here.
  2. A parity test: the same recorded requests (sign-in, loader registration, bot stats, round log, release download, backup export) sent to the Node adapter and to a local Worker run; the answers must match in status and body (ignoring time stamps and random ids).
  3. Restart test: send data, stop the hub with SIGTERM, start it, read everything back; nothing missing. Then the same with kill -9: durable data intact, fast data missing at most the last flush interval.
  4. Database-down test: stop PostgreSQL, confirm 503 for durable calls and no crash, start it, confirm recovery without a restart of the hub.
  5. WebSocket test: 20 simulated bots, 30 minutes, with ping-pong, forced disconnect and reconnect.
  6. Load test: 3 bots, then 30 bots, then 100 bots posting every round; p50, p95 and p99 latency recorded. Target: p99 under 150 ms at 30 bots on the 2 GB server, memory steady, no flush backlog.
  7. Security test: the checklist in Part N.
  8. Host-route test: every route answers on its own hostname and gives 404 on the other (for example the sign-in page on api.bideward.com, an ingestion path on app.bideward.com).

E.7 Acceptance: when the adapter is called done

Section titled “E.7 Acceptance: when the adapter is called done”
Check Pass condition
Behaviour Every existing receiver test passes; parity test has zero differences.
Durability Restart tests pass as in E.6.
Speed p99 under 150 ms at 30 simulated bots; queue never above 1,000 entries.
Memory Hub under 900 MB at 100 simulated bots.
Security No open port; no secret in the repository or in logs; the hub runs as bideward-hub with the systemd sandbox.
Review You have read the pull request and merged it.
  1. bot-stats-server branch migrate-lightsail-1: step E1 audit notes and db/migrations/0001_layer1.sql with the runner.
  2. Branch migrate-lightsail-2: the adapter (server, shim, pg-kv, ws bridge, env, research proxy).
  3. Branch migrate-lightsail-3: tests and the deploy folder (units, install and backup scripts).
  4. Each is a separate pull request; you merge each yourself. Nothing is deployed to the server until all three are merged and the tests of E.6 have been shown to you.
  5. The script repository (crashgame) changes only in Part H: the receiver URL in the loader, bootstrap and tab script.

← Previous: Part D. Cloudflare: every setting, in order · Guide index · Next: Part F. Install the hub, the research service and the tunnel on the server →