diff --git a/Dockerfile b/Dockerfile index b36ffa6..c7c8b28 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,8 @@ COPY --from=build /app/web/dist /app/web/dist COPY --from=build /app/node_modules /app/node_modules COPY --from=build /app/bridge/node_modules /app/bridge/node_modules COPY --from=build /app/bridge/package.json /app/bridge/package.json -USER node +COPY scripts/bridge-entrypoint.sh /usr/local/bin/bridge-entrypoint EXPOSE 8080 7600 HEALTHCHECK --interval=15s --timeout=3s CMD node -e "fetch('http://127.0.0.1:8080/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +ENTRYPOINT ["/usr/local/bin/bridge-entrypoint"] CMD ["node","bridge/dist/server.js"] diff --git a/README.md b/README.md index 2fa0866..4b8c17d 100644 --- a/README.md +++ b/README.md @@ -14,16 +14,30 @@ scripts/venue.sh status scripts/venue.sh down ``` -The script builds `gated` in a detached temporary worktree, starts the standalone entrance at http://127.0.0.1:28080, and removes the worktree with `down`. For the Gate 3 crash scenario, build the revision before the fix in a separate detached worktree and pass `--gate3-crash DIR`; `down` includes `compose.gate3-crash.yaml` in cleanup. `scripts/e2e-gatepost.sh` runs the Playwright checks against an active entrance. The ticket file contains only synthetic barcodes. +The script builds `gated` in a detached temporary worktree, starts the standalone entrance at http://127.0.0.1:28080, and removes the worktree with `down`. For a revision with the hub, use `--ref main`. For the Gate 3 crash scenario, build the revision before the fix in a separate detached worktree and pass `--gate3-crash DIR`; `down` includes `compose.gate3-crash.yaml` in cleanup. `GATEPOST_REF=main scripts/e2e-gatepost.sh controls` starts a standalone entrance, checks real Docker network and power actions through the bridge WebSocket, and cleans up. Its other modes run the historical Playwright checks against an active entrance. The ticket file contains only synthetic barcodes. -`SIM_PORT` changes the local page port. `DOCKER_GID` defaults to the socket group. The bridge listens for the page on port 8080 inside its container, publishes only to host loopback, and accepts device TCP on the private `devices` network. `AUTO_PASS_MS` enables automatic passage after a relay opens. The bridge runs as the `node` user; it needs access to the Docker socket, usually via the socket's group ID. +`SIM_PORT` changes the local page port. The bridge listens for the page on port 8080 inside its container, publishes only to host loopback, and accepts device TCP on the private `devices` network. `AUTO_PASS_MS` enables automatic passage after a relay opens. At startup the bridge reads the mounted Docker socket's group inside the container, then runs as `node` with that supplementary group. The health endpoint and page report socket access. ## Browser messages -The browser WebSocket is `/ws`. The bridge sends `{ "type": "snapshot", "gates": [], "events": [], "tickets": [] }` and `{ "type": "error", "message": "..." }`. The browser sends `scan` (`gate`, `barcode`), `simultaneous` (`gates`, `barcode`), `burst` (`count`, `intervalMs`), `pass` (`gate`), `power` (`gate`, `on`), or `network` (`gate`, `on`). Gate IDs must be configured services. The event log records the wire lines and directions. The bridge does not decide ticket validity; `gated` does. +The browser WebSocket is `/ws`. The bridge sends `{ "type": "snapshot", "gates": [], "events": [], "tickets": [], "docker": { "ok": true, "message": "Docker socket accessible" } }` and `{ "type": "error", "message": "..." }`. The browser sends `scan` (`gate`, `barcode`), `simultaneous` (`gates`, `barcode`), `burst` (`count`, `intervalMs`), `pass` (`gate`), `power` (`gate`, `on`), or `network` (`gate`, `on`). Gate IDs must be configured services. The event log records the wire lines and directions. The bridge does not decide ticket validity; `gated` does. ## Development Use Node 26.12.1 and pnpm 10.20.0. Run `pnpm install --frozen-lockfile`, then `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. `pnpm test:e2e` runs browser checks against a running bridge and fake gates. CI also builds the image, produces an SBOM, and scans it. +## Screenshots + +Install headless Chromium with `pnpm exec playwright install chromium`, then capture light and dark pairs for Gate 3 stopping after an unknown barcode, two gates admitting one ticket before the race fix, exactly one gate admitting it after the fix, and offline admission at two gates. In the offline scene, Gate 2 admits a ticket with its cable unplugged and network LED off. Online Gate 1 then admits the same ticket through the hub, which has not heard of Gate 2's local admission. The event log labels each decision from the network LED reported by the gate. + +```sh +GATEPOST_DIR=../gatepost \ +GATE3_WORKING_REF="$gate3_fix" GATE3_CRASH_REF="$gate3_crash" \ +DOUBLE_ADMISSION_BEFORE_REF="$race_before" DOUBLE_ADMISSION_FIXED_REF="$race_after" \ +OFFLINE_ADMISSION_REF=69c5ea6 \ +scripts/screenshots.sh +``` + +Choose each ref from your Gatepost checkout before running: `gate3_fix` is the revision after the Gate 3 crash fix; `gate3_crash` is a revision that still exhibits the crash; `race_after` is the revision with the hub race fix; `race_before` is a revision that still exhibits double admission. `OFFLINE_ADMISSION_REF` needs the hub client and network LED; `69c5ea6` has both. Use `git -C ../gatepost log --oneline --all` to find them, then set those five shell variables. The script builds detached temporary worktrees, checks the historical behavior, writes 1440 × 900 screenshots at 2× device scale under `docs/screenshots/`, and runs Compose `down -v` for every entrance. See [screenshot notes](docs/screenshots/README.md). + The bridge has the Docker Engine socket mounted. Anyone who can use that socket can manage every container on the host. This local development service publishes its page only on 127.0.0.1 and checks the configured Compose project and service allow-list before power or network actions. The network control disconnects and reconnects only the venue network, saving its address, MAC and aliases; the private device network stays connected. The simulator models hardware commands, not radio, power-supply behavior, or scanner optics. diff --git a/README.zh-CN.md b/README.zh-CN.md index 595db35..137e214 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,16 +14,30 @@ scripts/venue.sh status scripts/venue.sh down ``` -脚本在独立的临时 worktree 中构建 `gated`,在 http://127.0.0.1:28080 启动入口;`down` 清理 Compose 项目和 worktree。要运行重现 Gate 3 崩溃的场景,在另一个独立 worktree 中构建崩溃修复前的提交,并以 `--gate3-crash DIR` 传入;`down` 会同时纳入 `compose.gate3-crash.yaml`。`scripts/e2e-gatepost.sh` 检查正在运行的入口。票据文件只含合成条码。 +脚本在独立的临时 worktree 中构建 `gated`,在 http://127.0.0.1:28080 启动入口;`down` 清理 Compose 项目和 worktree。带 hub 的版本使用 `--ref main`。要运行重现 Gate 3 崩溃的场景,在另一个独立 worktree 中构建崩溃修复前的提交,并以 `--gate3-crash DIR` 传入;`down` 会同时纳入 `compose.gate3-crash.yaml`。`GATEPOST_REF=main scripts/e2e-gatepost.sh controls` 会启动独立入口,通过 bridge WebSocket 检查实际 Docker 网络与电源操作,然后清理;其他模式对运行中的入口执行历史 Playwright 检查。票据文件只含合成条码。 -`SIM_PORT` 控制本地页面端口;`DOCKER_GID` 默认取 Docker socket 的组 ID。容器内页面端口为 8080,仅发布到主机回环地址;设备 TCP 只在私有 `devices` 网络监听。`AUTO_PASS_MS` 可配置转闸打开后的自动通行。bridge 以 `node` 用户运行,需要通过 socket 的组权限访问 Docker。 +`SIM_PORT` 控制本地页面端口;容器内页面端口为 8080,仅发布到主机回环地址;设备 TCP 只在私有 `devices` 网络监听。`AUTO_PASS_MS` 可配置转闸打开后的自动通行。bridge 启动时读取容器内 Docker socket 的组 ID,再以带该附加组的 `node` 用户运行。健康检查和页面都会显示 socket 的访问状态。 ## 浏览器消息 -WebSocket 路径是 `/ws`。bridge 发送 `snapshot`(含 `gates`、`events`、`tickets`)或 `error`(含 `message`)。浏览器发送 `scan`(`gate`、`barcode`)、`simultaneous`(`gates`、`barcode`)、`burst`(`count`、`intervalMs`)、`pass`(`gate`)、`power` 或 `network`(`gate`、`on`)。闸机 ID 必须属于配置的服务。事件日志记录协议行与方向。票据是否有效由 `gated` 决定。 +WebSocket 路径是 `/ws`。bridge 发送 `snapshot`(含 `gates`、`events`、`tickets` 和 Docker socket 的 `docker` 状态)或 `error`(含 `message`)。浏览器发送 `scan`(`gate`、`barcode`)、`simultaneous`(`gates`、`barcode`)、`burst`(`count`、`intervalMs`)、`pass`(`gate`)、`power` 或 `network`(`gate`、`on`)。闸机 ID 必须属于配置的服务。事件日志记录协议行与方向。票据是否有效由 `gated` 决定。 ## 开发与限制 使用 Node 26.12.1 与 pnpm 10.20.0。运行 `pnpm install --frozen-lockfile`,再运行 `pnpm lint`、`pnpm typecheck`、`pnpm test`、`pnpm build`。`pnpm test:e2e` 在 bridge 与假闸机运行时检查页面。CI 还构建镜像、生成 SBOM 并扫描漏洞。 +## 截图 + +先运行 `pnpm exec playwright install chromium` 安装无界面 Chromium,再为四个场景生成浅色和深色截图:Gate 3 遇到未知条码停止、修复前两台闸机同时放行同一票据、修复后仅一台闸机放行,以及两台闸机的离线放行。在离线场景中,Gate 2 的网线已拔出、网络灯熄灭,它独立放行一张票据;仍然在线的 Gate 1 随后通过 hub 放行同一票据,因为 hub 没有收到 Gate 2 的记录。事件日志依据闸机报告的网络灯状态标出决策来源。 + +```sh +GATEPOST_DIR=../gatepost \ +GATE3_WORKING_REF="$gate3_fix" GATE3_CRASH_REF="$gate3_crash" \ +DOUBLE_ADMISSION_BEFORE_REF="$race_before" DOUBLE_ADMISSION_FIXED_REF="$race_after" \ +OFFLINE_ADMISSION_REF=69c5ea6 \ +scripts/screenshots.sh +``` + +先用 `git -C ../gatepost log --oneline --all` 选择引用并设置 shell 变量:`gate3_fix` 是 Gate 3 崩溃修复后的版本,`gate3_crash` 是仍会发生该崩溃的版本;`race_after` 是 hub 竞态修复后的版本,`race_before` 是仍会重复放行的版本。`OFFLINE_ADMISSION_REF` 须包含 hub 客户端与网络灯,`69c5ea6` 符合要求。脚本在临时独立 worktree 中构建、验证历史行为,将 1440 × 900、设备缩放比例 2 的截图写入 `docs/screenshots/`,并对每次入口运行执行 Compose `down -v`。详见[截图说明](docs/screenshots/README.zh-CN.md)。 + bridge 挂载了 Docker Engine socket。能够使用该 socket 的进程可以管理主机上的所有容器。因此本工具仅用于本地开发,页面只发布到 127.0.0.1;电源和网络操作会检查 Compose 项目与服务白名单。网络操作只断开并重新连接场馆网络,同时保存地址、MAC 与别名;私有设备网络保持连接。模拟器不模拟无线电、电源供电细节或扫码器光学特性。 diff --git a/bridge/src/docker.ts b/bridge/src/docker.ts index 966859b..0a2ae6c 100644 --- a/bridge/src/docker.ts +++ b/bridge/src/docker.ts @@ -44,10 +44,23 @@ export function request( } async function checked(method: string, path: string, body?: unknown) { const result = await request(method, path, body); - if (result.status >= 300) - throw new Error(`Docker ${method} ${path}: ${result.status} ${JSON.stringify(result.data)}`); + if (result.status >= 300) { + const message = + result.data && typeof result.data === 'object' && 'message' in result.data + ? String(result.data.message) + : JSON.stringify(result.data); + throw new Error(`Docker API ${result.status}: ${message}`); + } return result.data; } +export async function socketHealth(): Promise<{ ok: boolean; message: string }> { + try { + await checked('GET', '/_ping'); + return { ok: true, message: 'Docker socket accessible' }; + } catch (error) { + return { ok: false, message: String(error) }; + } +} type Container = { Id: string; Config: { Labels: Record }; diff --git a/bridge/src/server.ts b/bridge/src/server.ts index 99aeaf0..ce6c097 100644 --- a/bridge/src/server.ts +++ b/bridge/src/server.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { WebSocketServer, WebSocket } from 'ws'; import { hello, Lines } from './protocol.js'; import { Model } from './state.js'; -import { action } from './docker.js'; +import { action, socketHealth } from './docker.js'; const port = Number(process.env.PORT || 8080), devicePort = Number(process.env.DEVICE_PORT || 7600); const webRoot = process.env.WEB_ROOT || path.resolve('web/dist'); @@ -18,13 +18,17 @@ const tickets = ( .filter(Boolean); const gateIds = (process.env.GATE_SERVICES || 'gate1,gate2,gate3,gate4').split(','); const clients = new Set(); -const model = new Model( - () => { - const data = JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets }); - for (const ws of clients) if (ws.readyState === WebSocket.OPEN) ws.send(data); - }, - Number(process.env.AUTO_PASS_MS || 0), -); +let docker = { ok: false, message: 'Checking Docker socket' }; +void socketHealth().then((result) => { + docker = result; + if (!result.ok) console.error(`Docker socket unavailable: ${result.message}`); + publish(); +}); +function publish() { + const data = JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets, docker }); + for (const ws of clients) if (ws.readyState === WebSocket.OPEN) ws.send(data); +} +const model = new Model(publish, Number(process.env.AUTO_PASS_MS || 0)); for (const id of gateIds) model.gate(id); net .createServer((socket) => { @@ -65,7 +69,9 @@ const types: Record = { }; const server = http.createServer((req, res) => { if (req.url === '/health') { - res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ ok: true })); + res + .writeHead(docker.ok ? 200 : 503, { 'Content-Type': 'application/json' }) + .end(JSON.stringify({ ok: docker.ok, docker })); return; } const name = req.url === '/' ? '/index.html' : decodeURIComponent((req.url || '').split('?')[0]); @@ -87,7 +93,7 @@ const server = http.createServer((req, res) => { const wss = new WebSocketServer({ server, path: '/ws' }); wss.on('connection', (ws) => { clients.add(ws); - ws.send(JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets })); + ws.send(JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets, docker })); ws.on('close', () => clients.delete(ws)); ws.on('message', async (raw) => { try { @@ -122,10 +128,13 @@ wss.on('connection', (ws) => { typeof msg.on === 'boolean' ) { await action(msg.gate, msg.type, msg.on); + model.log(msg.gate, 'action', `${msg.type} ${msg.on ? 'on' : 'off'}`); if (msg.type === 'power') model.setPower(msg.gate, msg.on); else model.setNetwork(msg.gate, msg.on); } else throw new Error('Invalid message'); } catch (error) { + console.error('Bridge action failed:', error); + model.log('?', 'error', String(error)); ws.send(JSON.stringify({ type: 'error', message: String(error) })); } }); diff --git a/bridge/src/state.ts b/bridge/src/state.ts index 8ff1965..6f79836 100644 --- a/bridge/src/state.ts +++ b/bridge/src/state.ts @@ -72,8 +72,15 @@ export class Model { this.log(id, 'ignored', line); return; } - if (parsed.kind === 'light') g.light = parsed.value; - else if (parsed.kind === 'net') g.netLed = parsed.value; + if (parsed.kind === 'light') { + g.light = parsed.value; + if (parsed.value !== 'OFF') + this.log( + id, + 'decision', + `${g.netLed === 'ON' ? 'HUB' : 'LOCAL'} ${parsed.value === 'GREEN' ? 'ACCEPT' : 'REJECT'}`, + ); + } else if (parsed.kind === 'net') g.netLed = parsed.value; else { g.relayUntil = Date.now() + parsed.ms; setTimeout(() => { diff --git a/bridge/test/docker.test.ts b/bridge/test/docker.test.ts index 8faa5e2..3885ae8 100644 --- a/bridge/test/docker.test.ts +++ b/bridge/test/docker.test.ts @@ -64,3 +64,26 @@ it('checks inspected labels before a Docker action on a Unix socket', async () = await action('gate1', 'power', false); expect(calls.some((call) => call === 'POST /containers/container-1/kill')).toBe(true); }); + +it('reports Docker API status and message from an inaccessible socket', async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'gatepost-docker-test-')); + directories.push(directory); + const socket = path.join(directory, 'docker.sock'); + process.env.DOCKER_SOCKET = socket; + const server = http.createServer((_req, res) => { + res + .writeHead(403, { 'Content-Type': 'application/json' }) + .end(JSON.stringify({ message: 'permission denied' })); + }); + servers.push(server); + await new Promise((done) => server.listen(socket, done)); + vi.resetModules(); + const { action, socketHealth } = await import('../src/docker.js'); + await expect(action('gate1', 'power', false)).rejects.toThrow( + 'Docker API 403: permission denied', + ); + await expect(socketHealth()).resolves.toEqual({ + ok: false, + message: 'Error: Docker API 403: permission denied', + }); +}); diff --git a/bridge/test/state.test.ts b/bridge/test/state.test.ts index 010f4b0..5c9a517 100644 --- a/bridge/test/state.test.ts +++ b/bridge/test/state.test.ts @@ -21,3 +21,14 @@ it('separates streams, resets outputs on disconnect and does not resend scans af next.destroy(); first.destroy(); }); +it('labels admissions by the network LED reported with the decision', () => { + const model = new Model(() => {}); + model.receive('gate2', 'LED NET OFF'); + model.receive('gate2', 'LIGHT GREEN'); + model.receive('gate1', 'LED NET ON'); + model.receive('gate1', 'LIGHT GREEN'); + expect(model.events.filter((event) => event.direction === 'decision')).toMatchObject([ + { gate: 'gate2', line: 'LOCAL ACCEPT' }, + { gate: 'gate1', line: 'HUB ACCEPT' }, + ]); +}); diff --git a/compose.devices.yaml b/compose.devices.yaml index 931495f..2fd301c 100644 --- a/compose.devices.yaml +++ b/compose.devices.yaml @@ -14,7 +14,6 @@ services: bridge: build: . image: gatepost-sim:local - group_add: ['${DOCKER_GID:-0}'] ports: ['127.0.0.1:${SIM_PORT:-28080}:8080'] volumes: - /var/run/docker.sock:/var/run/docker.sock diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md index c7c95ec..9479298 100644 --- a/docs/screenshots/README.md +++ b/docs/screenshots/README.md @@ -2,8 +2,23 @@ English | [简体中文](README.zh-CN.md) # Demonstration screenshots -All screenshots use a 1440 × 900 light-theme Playwright viewport. +Every scenario has `.png` (light) and `.dark.png` (dark), captured in headless Chromium at a 1440 × 900 viewport and device scale 2. -| File | State and code ref | Command | -| ------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------- | -| `gate3-stopped.png` | Gate 3 crash scenario, `2b4843b` plus Gate 3 crash revision `a058409` adapter | `pnpm exec playwright test e2e/real-gate3-stopped.spec.ts` | +Run from the repository root: + +```sh +GATEPOST_DIR=../gatepost \ +GATE3_WORKING_REF=2b4843b GATE3_CRASH_REF=a058409 \ +DOUBLE_ADMISSION_BEFORE_REF=ed6ea9c DOUBLE_ADMISSION_FIXED_REF=69b11cd \ +OFFLINE_ADMISSION_REF=69c5ea6 \ +scripts/screenshots.sh +``` + +| Pair name | Scenario | Gatepost refs | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | +| `gate3-stopped` | Four accepted scans, a rejection, then Gate 3 stops on `UNKNOWN` while Gate 4 keeps working | `2b4843b` and crash revision `a058409` | +| `offline-double-admission` | Gate 2 admits locally with its cable unplugged and network LED off; online Gate 1 then admits the same ticket through the hub | `69c5ea6` | +| `double-admission-before-fix` | Both gates admit the same ticket | `ed6ea9c`, immediately before race fix `6b7659e` | +| `double-admission-fixed` | Exactly one gate admits on each of 30 tries | `69b11cd` | + +Set the five ref variables to other commits when retaking the pairs. `OFFLINE_ADMISSION_REF` needs a hub client and network LED. The event log labels decisions using the LED reported by each gate. The filenames describe the documented scenarios and remain stable. diff --git a/docs/screenshots/README.zh-CN.md b/docs/screenshots/README.zh-CN.md index 6927310..003f9c7 100644 --- a/docs/screenshots/README.zh-CN.md +++ b/docs/screenshots/README.zh-CN.md @@ -2,8 +2,23 @@ # 演示截图 -所有截图均使用 Playwright 的 1440 × 900 浅色视口。 +每个场景有 `.png`(浅色)和 `.dark.png`(深色)。截图由无界面 Chromium 在 1440 × 900 视口、设备缩放比例 2 下生成。 -| 文件 | 状态与代码版本 | 命令 | -| ------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------- | -| `gate3-stopped.png` | 重现 Gate 3 崩溃的场景,`2b4843b` 加 Gate 3 崩溃修复前的提交 `a058409` 适配器 | `pnpm exec playwright test e2e/real-gate3-stopped.spec.ts` | +在仓库根目录运行: + +```sh +GATEPOST_DIR=../gatepost \ +GATE3_WORKING_REF=2b4843b GATE3_CRASH_REF=a058409 \ +DOUBLE_ADMISSION_BEFORE_REF=ed6ea9c DOUBLE_ADMISSION_FIXED_REF=69b11cd \ +OFFLINE_ADMISSION_REF=69c5ea6 \ +scripts/screenshots.sh +``` + +| 截图名称 | 场景 | Gatepost 引用 | +| ----------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------- | +| `gate3-stopped` | 四次接受、一次拒绝,然后 Gate 3 遇到 `UNKNOWN` 停止,Gate 4 继续运行 | `2b4843b` 与崩溃修复前的提交 `a058409` | +| `offline-double-admission` | Gate 2 网线拔出且网络灯熄灭后独立放行;在线的 Gate 1 随后经 hub 放行同一票据 | `69c5ea6` | +| `double-admission-before-fix` | 两台闸机同时放行同一票据 | `ed6ea9c`,竞态修复 `6b7659e` 之前的提交 | +| `double-admission-fixed` | 30 次尝试中,每次恰好一台闸机放行 | `69b11cd` | + +重拍时可将五个引用变量设为其他提交;`OFFLINE_ADMISSION_REF` 须包含 hub 客户端与网络灯。事件日志依据闸机报告的网络灯状态标出决策来源;文件名保持不变。 diff --git a/docs/screenshots/double-admission-before-fix.dark.png b/docs/screenshots/double-admission-before-fix.dark.png new file mode 100644 index 0000000..2c64f8e Binary files /dev/null and b/docs/screenshots/double-admission-before-fix.dark.png differ diff --git a/docs/screenshots/double-admission-before-fix.png b/docs/screenshots/double-admission-before-fix.png new file mode 100644 index 0000000..eb48acf Binary files /dev/null and b/docs/screenshots/double-admission-before-fix.png differ diff --git a/docs/screenshots/double-admission-fixed.dark.png b/docs/screenshots/double-admission-fixed.dark.png new file mode 100644 index 0000000..c5a7c6b Binary files /dev/null and b/docs/screenshots/double-admission-fixed.dark.png differ diff --git a/docs/screenshots/double-admission-fixed.png b/docs/screenshots/double-admission-fixed.png new file mode 100644 index 0000000..9e672cc Binary files /dev/null and b/docs/screenshots/double-admission-fixed.png differ diff --git a/docs/screenshots/gate3-stopped.dark.png b/docs/screenshots/gate3-stopped.dark.png new file mode 100644 index 0000000..dc5160e Binary files /dev/null and b/docs/screenshots/gate3-stopped.dark.png differ diff --git a/docs/screenshots/gate3-stopped.png b/docs/screenshots/gate3-stopped.png index dd2bd2d..04c54a8 100644 Binary files a/docs/screenshots/gate3-stopped.png and b/docs/screenshots/gate3-stopped.png differ diff --git a/docs/screenshots/offline-double-admission.dark.png b/docs/screenshots/offline-double-admission.dark.png new file mode 100644 index 0000000..545bac8 Binary files /dev/null and b/docs/screenshots/offline-double-admission.dark.png differ diff --git a/docs/screenshots/offline-double-admission.png b/docs/screenshots/offline-double-admission.png new file mode 100644 index 0000000..c1b8f3c Binary files /dev/null and b/docs/screenshots/offline-double-admission.png differ diff --git a/e2e/entrance.spec.ts b/e2e/entrance.spec.ts index fa3f9c2..757a9e2 100644 --- a/e2e/entrance.spec.ts +++ b/e2e/entrance.spec.ts @@ -1,13 +1,23 @@ import { test, expect } from '@playwright/test'; import AxeBuilder from '@axe-core/playwright'; -test('fake gates scan through the page and meet axe checks', async ({ page }) => { - await page.goto('/'); - await expect(page.getByRole('heading', { name: 'Entrance control' })).toBeVisible(); - const lane = page.getByRole('region', { name: 'gate1 lane' }); - await expect(lane.getByText('Scanner: connected')).toBeVisible(); - await lane.getByLabel('Barcode').fill('GP-000000000000'); - await lane.getByRole('button', { name: 'Scan' }).click(); - await expect(lane.getByLabel('Green light on')).toBeVisible(); - const results = await new AxeBuilder({ page }).analyze(); - expect(results.violations).toEqual([]); -}); +for (const scheme of ['light', 'dark'] as const) + test(`fake gates scan and meet axe checks in ${scheme}`, async ({ page }) => { + await page.emulateMedia({ colorScheme: scheme }); + await page.goto('/'); + await expect(page.getByRole('heading', { name: 'Entrance control' })).toBeVisible(); + await expect(page.getByRole('status')).toHaveText(/^Docker: (available|unavailable)$/); + const lane = page.getByRole('region', { name: 'gate1 lane' }); + await expect(lane.getByText('Scanner: connected')).toBeVisible(); + await expect(lane.getByText('Network cable plugged')).toBeVisible(); + await expect(page.getByRole('button', { name: 'Two gates at once' })).toBeDisabled(); + await page.getByLabel('Barcode', { exact: true }).last().fill('GP-000000000001'); + await expect(page.getByRole('button', { name: 'Two gates at once' })).toBeEnabled(); + await lane.getByLabel('Barcode').fill('GP-000000000000'); + await lane.getByRole('button', { name: 'Scan' }).click(); + await expect(lane.getByLabel('Green light on')).toBeVisible(); + await lane.getByRole('button', { name: 'Cut power' }).click(); + await expect(page.getByRole('alert')).toContainText(/Error:/); + await expect(lane.getByRole('button', { name: 'Cut power' })).toBeVisible(); + const results = await new AxeBuilder({ page }).analyze(); + expect(results.violations).toEqual([]); + }); diff --git a/e2e/real-double-admission.spec.ts b/e2e/real-double-admission.spec.ts new file mode 100644 index 0000000..d2f3089 --- /dev/null +++ b/e2e/real-double-admission.spec.ts @@ -0,0 +1,66 @@ +type Gate = { id: string; scanner: boolean; outputs: boolean; netLed: string }; +type Event = { seq: number; gate: string; line: string }; +type Snapshot = { gates: Gate[]; events: Event[] }; +import { screenshotPair } from './screenshot-pair'; +import { test, expect } from '@playwright/test'; +const mode = process.env.ADMISSION_SCENARIO || 'before-fix'; +test(`hub ${mode} simultaneous admission`, async ({ page }) => { + let latest: Snapshot; + page.on('websocket', (socket) => + socket.on('framereceived', (frame) => { + try { + const msg = JSON.parse(String(frame.payload)); + if (msg.type === 'snapshot') latest = msg; + } catch {} + }), + ); + await page.goto('/'); + await expect.poll(() => latest?.gates.filter((g: Gate) => g.scanner && g.outputs).length).toBe(4); + const input = page.getByLabel('Barcode', { exact: true }).last(); + let both = 0, + tries = 0; + const limit = mode === 'before-fix' ? 200 : 30; + for (let i = 0; i < limit; i++) { + const ticket = `GP-${String(100 + i).padStart(12, '0')}`; + const before = latest.events.at(-1)?.seq || 0; + await input.fill(ticket); + await page.getByRole('button', { name: 'Two gates at once' }).click(); + await expect + .poll( + () => + latest?.events.filter( + (e: Event) => + e.seq > before && + ['LIGHT GREEN', 'LIGHT RED'].includes(e.line) && + ['gate1', 'gate2'].includes(e.gate), + ).length, + { timeout: 5000 }, + ) + .toBe(2); + const decisions = latest.events.filter( + (e: Event) => + e.seq > before && + ['LIGHT GREEN', 'LIGHT RED'].includes(e.line) && + ['gate1', 'gate2'].includes(e.gate), + ); + await expect + .poll( + () => + latest?.gates.filter((g: Gate) => ['gate1', 'gate2'].includes(g.id) && g.netLed === 'ON') + .length, + ) + .toBe(2); + const greens = decisions.filter((e: Event) => e.line === 'LIGHT GREEN').length; + tries++; + console.log(`try ${tries}: ${ticket} greens=${greens}`); + if (mode === 'before-fix' && greens === 2) { + both++; + await screenshotPair(page, 'double-admission-before-fix'); + break; + } + if (mode === 'fixed') expect(greens).toBe(1); + } + if (mode === 'before-fix') expect(both).toBe(1); + if (mode === 'fixed') await screenshotPair(page, 'double-admission-fixed'); + console.log(`race ${mode}: tries=${tries}, double-green=${both}`); +}); diff --git a/e2e/real-gate3-stopped.spec.ts b/e2e/real-gate3-stopped.spec.ts index 6e26006..a10e806 100644 --- a/e2e/real-gate3-stopped.spec.ts +++ b/e2e/real-gate3-stopped.spec.ts @@ -1,8 +1,9 @@ type Gate = { id: string; scanner: boolean; outputs: boolean; netLed: string }; type Event = { seq: number; gate: string; line: string }; type Snapshot = { gates: Gate[]; events: Event[] }; +import { screenshotPair } from './screenshot-pair'; import { test, expect } from '@playwright/test'; -test('Gate 3 crash scenario', async ({ page }) => { +test('Gate 3 stops after an unknown barcode', async ({ page }) => { const snapshots: Snapshot[] = []; page.on('websocket', (socket) => socket.on('framereceived', (frame) => { @@ -67,7 +68,7 @@ test('Gate 3 crash scenario', async ({ page }) => { ?.events.some((e: Event) => e.gate === 'gate4' && e.line === 'SCAN GP-000000000005'), ) .toBe(true); - await page.screenshot({ path: 'docs/screenshots/gate3-stopped.png' }); + await screenshotPair(page, 'gate3-stopped'); console.log( 'gate3-stopped: four accepted; repeat rejected; Gate 3 down after UNKNOWN; Gate 4 still scanned', ); diff --git a/e2e/real-offline-double-admission.spec.ts b/e2e/real-offline-double-admission.spec.ts new file mode 100644 index 0000000..1574d3e --- /dev/null +++ b/e2e/real-offline-double-admission.spec.ts @@ -0,0 +1,71 @@ +import { test, expect } from '@playwright/test'; +import { screenshotPair } from './screenshot-pair'; + +type Gate = { + id: string; + scanner: boolean; + outputs: boolean; + network: boolean; + netLed: string; + light: string; +}; +type Event = { seq: number; gate: string; direction: string; line: string }; +type Snapshot = { gates: Gate[]; events: Event[] }; + +test('offline gate admits a ticket before the online hub admits it again', async ({ page }) => { + let latest: Snapshot | undefined; + page.on('websocket', (socket) => + socket.on('framereceived', (frame) => { + try { + const message = JSON.parse(String(frame.payload)); + if (message.type === 'snapshot') latest = message; + } catch {} + }), + ); + const lane = (id: string) => page.getByRole('region', { name: `${id} lane` }); + const gate = (id: string) => latest?.gates.find((item) => item.id === id); + const scan = async (id: string, barcode: string) => { + await lane(id).getByLabel('Barcode').fill(barcode); + await lane(id).getByRole('button', { name: 'Scan' }).click(); + }; + + await page.goto('/'); + await expect + .poll(() => latest?.gates.filter((item) => item.scanner && item.outputs).length) + .toBe(4); + await scan('gate1', 'GP-000000000001'); + await expect.poll(() => gate('gate1')?.netLed).toBe('ON'); + + await lane('gate2').getByRole('button', { name: 'Unplug network' }).click(); + await expect.poll(() => gate('gate2')?.network).toBe(false); + await expect.poll(() => gate('gate2')?.netLed).toBe('OFF'); + + const ticket = 'GP-000000000002'; + const before = latest?.events.at(-1)?.seq ?? 0; + await scan('gate2', ticket); + await expect + .poll(() => + latest?.events.some( + (event) => event.seq > before && event.gate === 'gate2' && event.line === 'LOCAL ACCEPT', + ), + ) + .toBe(true); + await scan('gate1', ticket); + await expect + .poll(() => + latest?.events.some( + (event) => event.seq > before && event.gate === 'gate1' && event.line === 'HUB ACCEPT', + ), + ) + .toBe(true); + expect(gate('gate1')?.light).toBe('GREEN'); + expect(gate('gate2')?.light).toBe('GREEN'); + expect(gate('gate1')?.netLed).toBe('ON'); + expect(gate('gate2')?.netLed).toBe('OFF'); + expect(gate('gate2')?.network).toBe(false); + await page.addStyleTag({ content: '.tickets { display: none; }' }); + await expect(page.getByText('LOCAL ACCEPT')).toBeVisible(); + await expect(page.getByText('HUB ACCEPT').first()).toBeVisible(); + await screenshotPair(page, 'offline-double-admission'); + console.log(`offline double admission: ${ticket}; gate2 LOCAL ACCEPT, gate1 HUB ACCEPT`); +}); diff --git a/e2e/screenshot-pair.ts b/e2e/screenshot-pair.ts new file mode 100644 index 0000000..2b5fce7 --- /dev/null +++ b/e2e/screenshot-pair.ts @@ -0,0 +1,12 @@ +import type { Page } from '@playwright/test'; + +export async function screenshotPair(page: Page, name: string) { + await page.evaluate(() => window.scrollTo(0, 0)); + for (const scheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme: scheme }); + await page.screenshot({ + path: `docs/screenshots/${name}${scheme === 'dark' ? '.dark' : ''}.png`, + animations: 'disabled', + }); + } +} diff --git a/playwright.config.ts b/playwright.config.ts index 6d76fb4..6f553a8 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -4,6 +4,7 @@ export default defineConfig({ use: { baseURL: 'http://127.0.0.1:28080', viewport: { width: 1440, height: 900 }, + deviceScaleFactor: 2, colorScheme: 'light', }, retries: 0, diff --git a/scripts/bridge-entrypoint.sh b/scripts/bridge-entrypoint.sh new file mode 100755 index 0000000..bea4f6b --- /dev/null +++ b/scripts/bridge-entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +socket=${DOCKER_SOCKET:-/var/run/docker.sock} +if [ ! -S "$socket" ]; then + echo "Docker socket is missing: $socket" >&2 + exit 1 +fi +gid=$(stat -c %g "$socket") +echo "Bridge starting as node with Docker socket group $gid" >&2 +exec setpriv --reuid=node --regid=node --groups="$gid" "$@" diff --git a/scripts/e2e-gatepost.sh b/scripts/e2e-gatepost.sh index 03091d3..8c25d0b 100755 --- a/scripts/e2e-gatepost.sh +++ b/scripts/e2e-gatepost.sh @@ -2,6 +2,19 @@ set -euo pipefail cd "$(dirname "$0")/.." case ${1:-} in + controls) + [[ ! -e .venue-state ]] || { echo 'Stop the active venue first' >&2; exit 1; } + cleanup() { if [[ -e .venue-state ]]; then scripts/venue.sh down; fi; } + trap cleanup EXIT + scripts/venue.sh up --gatepost "${GATEPOST_DIR:-../gatepost}" --ref "${GATEPOST_REF:?Set GATEPOST_REF to a revision with the hub client}" --mode devices + node scripts/real-controls.mjs + cleanup + remaining=$(docker ps -a --filter label=com.docker.compose.project=gatepost-sim-devices --format '{{.Names}}') + [[ -z $remaining ]] || { echo "Compose containers remain: $remaining" >&2; exit 1; } + ;; gate3-stopped) pnpm exec playwright test e2e/real-gate3-stopped.spec.ts ;; - *) echo 'Usage: e2e-gatepost.sh gate3-stopped (with the corresponding venue running)' >&2; exit 2 ;; + double-admission-before-fix) ADMISSION_SCENARIO=before-fix pnpm exec playwright test e2e/real-double-admission.spec.ts ;; + double-admission-fixed) ADMISSION_SCENARIO=fixed pnpm exec playwright test e2e/real-double-admission.spec.ts ;; + offline-double-admission) pnpm exec playwright test e2e/real-offline-double-admission.spec.ts ;; + *) echo 'Usage: e2e-gatepost.sh controls|gate3-stopped|double-admission-before-fix|double-admission-fixed|offline-double-admission' >&2; exit 2 ;; esac diff --git a/scripts/hub-proxy.py b/scripts/hub-proxy.py index ea13adb..cd7779a 100644 --- a/scripts/hub-proxy.py +++ b/scripts/hub-proxy.py @@ -14,6 +14,7 @@ def handle(self): if not part: return data += part + print(f'hub proxy request: {data.decode(errors="replace").strip()}', flush=True) hub.sendall(data) response = b'' while not response.endswith(b'\n') and len(response) <= 256: diff --git a/scripts/real-controls.mjs b/scripts/real-controls.mjs new file mode 100644 index 0000000..7e54f8e --- /dev/null +++ b/scripts/real-controls.mjs @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import WebSocket from '../bridge/node_modules/ws/index.js'; + +const docker = (...args) => execFileSync('docker', args, { encoding: 'utf8' }).trim(); +const container = (service) => + docker( + 'ps', + '-aq', + '--filter', + 'label=com.docker.compose.project=gatepost-sim-devices', + '--filter', + `label=com.docker.compose.service=${service}`, + ); +const networks = (id) => + JSON.parse(docker('inspect', '-f', '{{json .NetworkSettings.Networks}}', id)); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +async function until(label, check, timeout = 30000) { + const end = Date.now() + timeout; + while (Date.now() < end) { + if (await check()) { + console.log(`PASS ${label}`); + return; + } + await wait(250); + } + throw new Error(`Timed out: ${label}`); +} +const ws = new WebSocket('ws://127.0.0.1:28080/ws'); +let snapshot; +const errors = []; +ws.on('message', (raw) => { + const message = JSON.parse(raw); + if (message.type === 'snapshot') snapshot = message; + if (message.type === 'error') errors.push(message.message); +}); +await new Promise((resolve, reject) => { + ws.once('open', resolve); + ws.once('error', reject); +}); +const gate = (id) => snapshot?.gates.find((item) => item.id === id); +const send = (message) => ws.send(JSON.stringify(message)); +try { + await until('Docker socket accessible', () => snapshot?.docker.ok); + const gate2Id = container('gate2'); + const gate3Id = container('gate3'); + const hubId = container('gate-hub'); + const venue = 'gatepost-sim-devices_venue'; + await until('gate2 scanner connected', () => gate('gate2')?.scanner); + const offlineTicket = 'GP-000000000020'; + const hubBefore = docker('logs', hubId); + send({ type: 'network', gate: 'gate2', on: false }); + await until('gate2 left venue network', () => !(venue in networks(gate2Id))); + await until('gate2 cable unplugged on page snapshot', () => gate('gate2')?.network === false); + send({ type: 'scan', gate: 'gate2', barcode: offlineTicket }); + await until('gate2 network LED off after hub check', () => gate('gate2')?.netLed === 'OFF'); + await until('gate2 decided offline scan locally', () => gate('gate2')?.light === 'GREEN'); + assert(!docker('logs', hubId).slice(hubBefore.length).includes(`SCAN ${offlineTicket}`)); + console.log('PASS hub did not see offline ticket'); + send({ type: 'network', gate: 'gate2', on: true }); + await until('gate2 rejoined venue network', () => venue in networks(gate2Id)); + for (let i = 21; i < 31 && gate('gate2')?.netLed !== 'ON'; i++) { + await wait(1200); + send({ type: 'scan', gate: 'gate2', barcode: `GP-${String(i).padStart(12, '0')}` }); + await wait(900); + } + if (gate('gate2')?.netLed !== 'ON') { + console.error('gate2 logs:', docker('logs', gate2Id)); + console.error('hub logs:', docker('logs', hubId)); + console.error('bridge logs:', docker('logs', container('bridge'))); + throw new Error('gate2 network LED stayed off after reconnect'); + } + console.log('PASS gate2 network LED on after reconnect'); + send({ type: 'power', gate: 'gate3', on: false }); + await until( + 'gate3 power cut', + () => docker('inspect', '-f', '{{.State.Running}}', gate3Id) === 'false', + ); + send({ type: 'power', gate: 'gate3', on: true }); + await until( + 'gate3 running after power restore', + () => docker('inspect', '-f', '{{.State.Running}}', gate3Id) === 'true', + ); + await until('gate3 device reconnected', () => gate('gate3')?.scanner && gate('gate3')?.outputs); + assert.deepEqual(errors, []); + console.log('PASS no bridge action errors'); +} finally { + ws.close(); +} diff --git a/scripts/screenshots.sh b/scripts/screenshots.sh new file mode 100755 index 0000000..0326d08 --- /dev/null +++ b/scripts/screenshots.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." + +: "${GATEPOST_DIR:?Set GATEPOST_DIR to the Gatepost checkout}" +: "${GATE3_WORKING_REF:?Set GATE3_WORKING_REF to the Gate 3 fix revision}" +: "${GATE3_CRASH_REF:?Set GATE3_CRASH_REF to the revision used by the Gate 3 crash scenario}" +: "${DOUBLE_ADMISSION_BEFORE_REF:?Set DOUBLE_ADMISSION_BEFORE_REF to the commit before the race fix}" +: "${DOUBLE_ADMISSION_FIXED_REF:?Set DOUBLE_ADMISSION_FIXED_REF to the race fix revision}" +: "${OFFLINE_ADMISSION_REF:?Set OFFLINE_ADMISSION_REF to a revision with the hub client and network LED}" +[[ ! -e .venue-state ]] || { echo 'An entrance is already running; stop it first' >&2; exit 1; } +gatepost_dir=$(cd "$GATEPOST_DIR" && pwd) +for ref in "$GATE3_WORKING_REF" "$GATE3_CRASH_REF" "$DOUBLE_ADMISSION_BEFORE_REF" "$DOUBLE_ADMISSION_FIXED_REF" "$OFFLINE_ADMISSION_REF"; do + git -C "$gatepost_dir" show -s --format='%h %s' "$ref" +done + +gate3_crash_tree= +cleanup() { + if [[ -e .venue-state ]]; then scripts/venue.sh down; fi + if [[ -n $gate3_crash_tree ]]; then + git -C "$gatepost_dir" worktree remove --force "$gate3_crash_tree" + gate3_crash_tree= + fi +} +trap cleanup EXIT + +gate3_crash_tree=$(mktemp -d "${TMPDIR:-/tmp}/gatepost-sim-gate3-crash.XXXXXXXX") +git -C "$gatepost_dir" worktree add --detach "$gate3_crash_tree" "$GATE3_CRASH_REF" +scripts/venue.sh up --gatepost "$gatepost_dir" --ref "$GATE3_WORKING_REF" --mode devices --gate3-crash "$gate3_crash_tree" +docker run --rm -v "$gate3_crash_tree:/src" gatepost-build:local sh -c \ + 'mkdir -p build/debug && gcc -std=c17 -g -O0 -Ilibgate libgate/tickets.c gated/main.c -o build/debug/gated' +GATE3_CRASH_DIR=$gate3_crash_tree GATEPOST_DIR=$(sed -n '3p' .venue-state) \ + docker compose -p gatepost-sim-devices -f compose.devices.yaml -f compose.gate3-crash.yaml start gate3 +./node_modules/.bin/playwright test e2e/real-gate3-stopped.spec.ts --reporter=line +scripts/venue.sh down +git -C "$gatepost_dir" worktree remove --force "$gate3_crash_tree" +gate3_crash_tree= + +scripts/venue.sh up --gatepost "$gatepost_dir" --ref "$DOUBLE_ADMISSION_BEFORE_REF" --mode devices +ADMISSION_SCENARIO=before-fix ./node_modules/.bin/playwright test e2e/real-double-admission.spec.ts --reporter=line +scripts/venue.sh down + +scripts/venue.sh up --gatepost "$gatepost_dir" --ref "$DOUBLE_ADMISSION_FIXED_REF" --mode devices +ADMISSION_SCENARIO=fixed ./node_modules/.bin/playwright test e2e/real-double-admission.spec.ts --reporter=line +scripts/venue.sh down + +scripts/venue.sh up --gatepost "$gatepost_dir" --ref "$OFFLINE_ADMISSION_REF" --mode devices +./node_modules/.bin/playwright test e2e/real-offline-double-admission.spec.ts --reporter=line +scripts/venue.sh down + +remaining=$(docker ps -a --filter label=com.docker.compose.project=gatepost-sim-devices --format '{{.Names}} {{.Status}}') +[[ -z $remaining ]] || { echo "Compose containers remain: $remaining" >&2; exit 1; } +echo 'All four screenshot pairs captured; no gatepost-sim-devices containers remain.' diff --git a/scripts/venue.sh b/scripts/venue.sh index ae5d118..c6cd444 100755 --- a/scripts/venue.sh +++ b/scripts/venue.sh @@ -2,10 +2,6 @@ set -euo pipefail cd "$(dirname "$0")/.." export SIM_DIR=$(pwd) -export DOCKER_CONFIG=${DOCKER_CONFIG:-${TMPDIR:-/tmp}/gatepost-sim-docker-cli} -export DOCKER_HOST=${DOCKER_HOST:-unix:///var/run/docker.sock} -mkdir -p "$DOCKER_CONFIG" -[[ -f "$DOCKER_CONFIG/config.json" ]] || printf "{}\n" > "$DOCKER_CONFIG/config.json" action=${1:-status}; shift || true mode=devices; ref=; gate3_crash_dir=; source_dir=${GATEPOST_DIR:-../gatepost} while (($#)); do @@ -28,7 +24,7 @@ if [[ $action == up ]]; then git -C "$source_dir" worktree add --detach "$worktree" "$ref" gatepost_dir=$worktree else gatepost_dir=$source_dir; fi - export GATEPOST_DIR=$gatepost_dir DOCKER_GID=$(stat -f %g /var/run/docker.sock 2>/dev/null || stat -c %g /var/run/docker.sock) SIM_PORT=${SIM_PORT:-28080} + export GATEPOST_DIR=$gatepost_dir SIM_PORT=${SIM_PORT:-28080} project=gatepost-sim-devices if [[ -n $gate3_crash_dir ]]; then gate3_crash_dir=$(cd "$gate3_crash_dir" && pwd); fi printf '%s\n%s\n%s\n%s\n%s\n%s\n' "$source_dir" "$worktree" "$gatepost_dir" "$mode" "$SIM_PORT" "$gate3_crash_dir" > "$state" @@ -42,7 +38,7 @@ if [[ $action == up ]]; then elif [[ $action == down || $action == status ]]; then [[ -e $state ]] || { echo 'No venue state'; exit 0; } source_dir=$(sed -n "1p" "$state");worktree=$(sed -n "2p" "$state");gatepost_dir=$(sed -n "3p" "$state");mode=$(sed -n "4p" "$state");SIM_PORT=$(sed -n "5p" "$state");gate3_crash_dir=$(sed -n "6p" "$state") - export GATEPOST_DIR=$gatepost_dir SIM_PORT DOCKER_GID=$(stat -f %g /var/run/docker.sock 2>/dev/null || stat -c %g /var/run/docker.sock) + export GATEPOST_DIR=$gatepost_dir SIM_PORT project=gatepost-sim-devices files=(-f compose.devices.yaml);if [[ -n $gate3_crash_dir ]];then export GATE3_CRASH_DIR=$gate3_crash_dir;files+=(-f compose.gate3-crash.yaml);fi if [[ $action == down ]]; then diff --git a/web/src/main.tsx b/web/src/main.tsx index 7826eba..0bd6aaf 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -12,7 +12,12 @@ type Gate = { relayUntil: number; }; type Entry = { at: string; gate: string; direction: string; line: string }; -type Snapshot = { gates: Gate[]; events: Entry[]; tickets: string[] }; +type Snapshot = { + gates: Gate[]; + events: Entry[]; + tickets: string[]; + docker: { ok: boolean; message: string }; +}; export function Lane({ gate, send }: { gate: Gate; send: (message: object) => void }) { const [barcode, setBarcode] = useState(''); const open = gate.relayUntil > Date.now(); @@ -23,6 +28,7 @@ export function Lane({ gate, send }: { gate: Gate; send: (message: object) => vo {gate.powered ? (gate.scanner || gate.outputs ? 'Powered' : 'Stopped') : 'Power off'} + Network cable {gate.network ? 'plugged' : 'unplugged'}
Scanner: {gate.scanner ? 'connected' : 'down'} @@ -52,7 +58,8 @@ export function Lane({ gate, send }: { gate: Gate; send: (message: object) => vo onClick={() => send({ type: 'pass', gate: gate.id })} aria-label={`${open ? 'Walk through' : 'Locked'} ${gate.id} turnstile`} > - {open ? 'Walk through' : 'Locked'} +
vo ); } export function App() { - const [state, setState] = useState({ gates: [], events: [], tickets: [] }); + const [state, setState] = useState({ + gates: [], + events: [], + tickets: [], + docker: { ok: false, message: 'Checking Docker socket' }, + }); const [connected, setConnected] = useState(false); const [filter, setFilter] = useState('all'); const [barcode, setBarcode] = useState(''); @@ -132,9 +144,14 @@ export function App() { A live view of the scanner, turnstile, lights and network at each gate.

- - Bridge {connected ? 'connected' : 'disconnected'} - +
+ + Bridge {connected ? 'connected' : 'disconnected'} + + + Docker: {state.docker.ok ? 'available' : connected ? 'unavailable' : 'checking'} + +
@@ -161,6 +178,7 @@ export function App() { placeholder="GP-000000000001" /> -
@@ -202,6 +224,7 @@ export function App() { onChange={(e) => setRate(Number(e.target.value))} /> diff --git a/web/src/style.css b/web/src/style.css index 651dae3..2b946d0 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -1,7 +1,63 @@ :root { font-family: Inter, ui-sans-serif, system-ui, sans-serif; - color: #173041; - background: #f5f8f9; + color-scheme: light dark; + --page: #f5f8f9; + --text: #173041; + --muted: #506875; + --subtle: #376779; + --surface: #fff; + --border: #b8cdd5; + --soft-border: #d8e4e8; + --hover: #e8f5f5; + --accent: #08777d; + --focus: #0866a2; + --status-bg: #eaf3f5; + --scene-top: #eaf3f5; + --scene-bottom: #f5f8f8; + --turnstile: #e9f0f3; + --turnstile-open: #e2f8ee; + --turnstile-border: #8aa9b8; + --turnstile-open-border: #16a579; + --arm: #607d8c; + --lights-housing: #244254; + --green-light: #1eca68; + --red-light: #ff5547; + --net-light: #42b4f6; + --bridge-off-bg: #fce6e0; + --bridge-off-text: #8a2417; + --bridge-on-bg: #d9f3e9; + --bridge-on-text: #086447; + --error: #a12820; + color: var(--text); + background: var(--page); +} +@media (prefers-color-scheme: dark) { + :root { + --page: #101b23; + --text: #e9f2f6; + --muted: #b7cad3; + --subtle: #bed8e4; + --surface: #1d2d38; + --border: #7895a3; + --soft-border: #48616e; + --hover: #2b4854; + --accent: #80dce0; + --focus: #72c8ff; + --status-bg: #2d4652; + --scene-top: #263d49; + --scene-bottom: #1b303a; + --turnstile: #314a58; + --turnstile-open: #194e40; + --turnstile-border: #9cbbc9; + --turnstile-open-border: #6ee6b0; + --arm: #c7dce5; + --lights-housing: #12212b; + --bridge-off-bg: #5a2929; + --bridge-off-text: #ffd2cb; + --bridge-on-bg: #164b3d; + --bridge-on-text: #c1f9de; + --error: #ffaaa1; + } } * { box-sizing: border-box; @@ -16,22 +72,22 @@ select { } button { cursor: pointer; - border: 1px solid #acc5ce; - background: #fff; - color: #153b4c; + border: 1px solid var(--border); + background: var(--surface); + color: var(--text); border-radius: 7px; padding: 9px 12px; font-weight: 600; } button:hover:not(:disabled) { - background: #e8f5f5; + background: var(--hover); } button:disabled { opacity: 0.52; cursor: not-allowed; } :focus-visible { - outline: 3px solid #0866a2; + outline: 3px solid var(--focus); outline-offset: 3px; } main { @@ -45,30 +101,40 @@ main { justify-content: space-between; margin-bottom: 34px; } +.header-status { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; + justify-content: flex-end; + margin-left: 24px; + color: var(--muted); + font-size: 14px; +} .eyebrow { font-size: 12px; font-weight: 800; letter-spacing: 0.16em; - color: #08777d; + color: var(--accent); } .top h1 { font-size: 38px; margin: 4px 0; } .intro { - color: #506875; + color: var(--muted); margin: 0; } .bridge-state { - background: #fce6e0; - color: #8a2417; + background: var(--bridge-off-bg); + color: var(--bridge-off-text); border-radius: 100px; padding: 10px 16px; font-weight: 700; } .bridge-state.online { - background: #d9f3e9; - color: #086447; + background: var(--bridge-on-bg); + color: var(--bridge-on-text); } .layout { display: grid; @@ -84,7 +150,7 @@ main { font-size: 20px; } .section-head span { - color: #516c78; + color: var(--muted); } .lanes { display: grid; @@ -93,10 +159,10 @@ main { } .lane, .panel { - background: #fff; - border: 1px solid #d8e4e8; + background: var(--surface); + border: 1px solid var(--soft-border); border-radius: 14px; - box-shadow: 0 2px 10px #193b4a0a; + box-shadow: 0 2px 10px var(--soft-border); } .lane { padding: 17px; @@ -113,8 +179,8 @@ main { } .status { font-size: 12px; - color: #376779; - background: #eaf3f5; + color: var(--subtle); + background: var(--status-bg); padding: 5px 9px; border-radius: 50px; } @@ -122,14 +188,14 @@ main { display: flex; gap: 15px; font-size: 12px; - color: #526a75; + color: var(--muted); margin: 13px 0; } .scene { height: 139px; - border: 1px solid #dfebed; + border: 1px solid var(--soft-border); border-radius: 10px; - background: linear-gradient(#eaf3f5, #f5f8f8); + background: linear-gradient(var(--scene-top), var(--scene-bottom)); display: flex; align-items: center; justify-content: space-around; @@ -139,7 +205,7 @@ main { display: flex; flex-direction: column; gap: 9px; - background: #244254; + background: var(--lights-housing); padding: 10px; border-radius: 13px; } @@ -151,35 +217,63 @@ main { opacity: 0.25; } .green { - background: #1eca68; + background: var(--green-light); } .red { - background: #ff5547; + background: var(--red-light); } .blue { - background: #42b4f6; + background: var(--net-light); } .bulb.lit { opacity: 1; box-shadow: 0 0 14px currentColor; } +.bulb.green { + color: var(--green-light); +} +.bulb.red { + color: var(--red-light); +} +.bulb.blue { + color: var(--net-light); +} .turnstile { height: 92px; width: 150px; - border: 2px solid #8aa9b8; - background: #e9f0f3; + border: 2px solid var(--turnstile-border); + background: var(--turnstile); position: relative; overflow: hidden; + display: flex; + align-items: flex-end; + justify-content: center; + padding: 0; +} +.turnstile-label { + position: relative; + z-index: 1; + display: block; + width: 100%; + padding: 7px 2px; + background: var(--turnstile); +} +.turnstile.open .turnstile-label { + background: var(--turnstile-open); +} +.turnstile:disabled { + opacity: 1; + cursor: default; } .turnstile.open { - border-color: #16a579; - background: #e2f8ee; + border-color: var(--turnstile-open-border); + background: var(--turnstile-open); } .arm { display: block; height: 5px; width: 85px; - background: #607d8c; + background: var(--arm); position: absolute; top: 25px; left: 30px; @@ -206,11 +300,11 @@ main { .lane input, .scenarios input, select { - border: 1px solid #b8cdd5; + border: 1px solid var(--border); border-radius: 7px; padding: 9px; - background: #fff; - color: #173041; + background: var(--surface); + color: var(--text); } .controls { display: flex; @@ -234,7 +328,7 @@ select { } .tickets p { font-size: 13px; - color: #596e78; + color: var(--muted); } .ticket-list { display: grid; @@ -268,7 +362,7 @@ select { overflow: auto; } .events li { - border-bottom: 1px solid #e7eff1; + border-bottom: 1px solid var(--soft-border); padding: 7px 0; display: flex; flex-wrap: wrap; @@ -276,11 +370,11 @@ select { font-size: 11px; } .events time { - color: #5d7580; + color: var(--muted); } .events code { width: 100%; - color: #233e4b; + color: var(--text); } .scenario-row { display: flex; @@ -303,7 +397,7 @@ select { font-size: 12px; } .error { - color: #a12820; + color: var(--error); } @media (max-width: 1100px) { .layout { diff --git a/web/test/lane.test.tsx b/web/test/lane.test.tsx index f8eace9..e7099db 100644 --- a/web/test/lane.test.tsx +++ b/web/test/lane.test.tsx @@ -19,6 +19,7 @@ it('scans with Enter and shows device state', () => { />, ); expect(screen.getByLabelText('Green light on')).toBeTruthy(); + expect(screen.getByText('Network cable plugged')).toBeTruthy(); fireEvent.change(screen.getByLabelText('Barcode'), { target: { value: 'GP-000000000000' } }); fireEvent.submit(screen.getByLabelText('Barcode').closest('form')!); expect(send).toHaveBeenCalledWith({ type: 'scan', gate: 'gate1', barcode: 'GP-000000000000' });