From 42ee52ad566b40f44a4aff7b80770460177b4fcb Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:12:42 +0300 Subject: [PATCH 1/2] feat(selfhost): OTLP traces labelled per instance, and /api/metrics (#293) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Traces: OTEL_EXPORTER_OTLP_ENDPOINT now takes https:// and refuses a path (workerd posts to /v1/traces), OTEL_EXPORTER_OTLP_HEADERS (also _FILE) adds a backend's headers, and every export carries x-cloudhal-instance (the advertise name) and x-cloudhal-version through injectRequestHeaders: workerd sets only service.name, so the collector turns those into service.instance.id and service.version. Metrics (the decision, as an RFC-0047 §7a amendment, follows the PM's recommendation): the admin Worker's GET /api/metrics, Prometheus text of one instance, off unless CLOUDHAL_METRICS_TOKEN is set and then answering only that bearer token (404/401 otherwise). Requests and durations of the admin and site Workers (the site's through SITE and /__cloudhal/metrics), publish durations over the API and MCP, scheduler lag/last tick/health, D1 and R2 errors (D1Driver onError, a watched R2 bucket). Counters live in the isolate (core-ts RequestMetrics, Histogram), labels are a fixed set. Recipes: compose's otel profile (otel-collector-contrib pinned, with otel-collector.yaml: include_metadata and the resource processor's from_context), Caddy answers 404 for /api/metrics on the public host, Helm otel.headersSecret and metrics.enabled. CI validates the collector config and the new chart values, and scripts/otel-smoke.ts checks spans of both Workers at the collector with instance and version, and /api/metrics for its token holder only. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/selfhost-observability.md | 13 + .github/workflows/docker.yml | 18 +- AGENTS.md | 2 +- deploy/docker/.dockerignore | 1 + deploy/docker/.env.example | 7 +- deploy/docker/Caddyfile | 2 + deploy/docker/README.md | 3 +- deploy/docker/compose.yml | 18 ++ deploy/docker/otel-collector.yaml | 46 +++ deploy/helm/cloudhal/README.md | 7 + deploy/helm/cloudhal/templates/secret.yaml | 3 + .../helm/cloudhal/templates/statefulset.yaml | 7 + deploy/helm/cloudhal/values.yaml | 13 + deploy/swarm/README.md | 3 + docs/guides/self-host.md | 40 ++- docs/rfcs/0047-self-host-on-workerd.md | 22 ++ .../astro-renderer/src/cloudflare-entry.ts | 21 +- packages/cli/src/selfhost/otel.ts | 111 +++++++ packages/cli/src/selfhost/settings.ts | 26 +- packages/cli/src/selfhost/workerd-config.ts | 4 +- packages/cli/test/selfhost-otel.test.ts | 77 +++++ packages/cloudflare/src/admin-worker.ts | 17 +- packages/cloudflare/src/metrics.ts | 301 ++++++++++++++++++ packages/cloudflare/test/metrics.test.ts | 133 ++++++++ packages/core-ts/src/index.ts | 1 + packages/core-ts/src/request-metrics.ts | 61 ++++ packages/storage/src/sql/d1.ts | 23 +- packages/storage/test/d1-retry.test.ts | 18 ++ scripts/otel-smoke.ts | 218 +++++++++++++ 29 files changed, 1184 insertions(+), 32 deletions(-) create mode 100644 .changeset/selfhost-observability.md create mode 100644 deploy/docker/otel-collector.yaml create mode 100644 packages/cli/src/selfhost/otel.ts create mode 100644 packages/cli/test/selfhost-otel.test.ts create mode 100644 packages/cloudflare/src/metrics.ts create mode 100644 packages/cloudflare/test/metrics.test.ts create mode 100644 packages/core-ts/src/request-metrics.ts create mode 100644 scripts/otel-smoke.ts diff --git a/.changeset/selfhost-observability.md b/.changeset/selfhost-observability.md new file mode 100644 index 00000000..15dafef8 --- /dev/null +++ b/.changeset/selfhost-observability.md @@ -0,0 +1,13 @@ +--- +"@cloudhal/cloudflare": minor +"@cloudhal/core-ts": minor +"@cloudhal/astro-renderer": minor +"@cloudhal/storage": minor +"@cloudhal/cli": minor +--- + +Observability for self-host (#293; RFC-0047 §7a). +- **Traces.** `OTEL_EXPORTER_OTLP_ENDPOINT` takes `https://` too, and `OTEL_EXPORTER_OTLP_HEADERS` adds a backend's headers. Every export carries `x-cloudhal-instance` and `x-cloudhal-version` headers for the collector to turn into resource attributes. +- **Metrics.** The admin Worker gains `GET /api/metrics` (Prometheus text). It is off unless `CLOUDHAL_METRICS_TOKEN` is set, and then answers only that bearer token. It covers requests of the admin and site Workers (the site's through `/__cloudhal/metrics`), publish durations, scheduler lag and health, and store errors. +- **Supporting changes.** `D1Driver` takes an `onError` hook, and `@cloudhal/core-ts` exports the per-isolate counters (`RequestMetrics`, `Histogram`). +- **Recipes.** The compose file gains an `otel` profile (an OpenTelemetry Collector with `otel-collector.yaml`), Caddy no longer serves `/api/metrics` publicly, and the Helm chart gains `otel.headersSecret` and `metrics.enabled`. diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 37e904f9..15da39bc 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -13,7 +13,8 @@ name: Docker image # first stops), scripts/failover-smoke.ts (three instances, one killed with SIGKILL while a release # is due, then graceful handoffs under load; #290), scripts/mail-smoke.ts (an invite and a reset # through Mailpit with STARTTLS and AUTH; #291), scripts/render-smoke.ts (render_page through -# the Chrome sidecar; #292) and Trivy, which fails the job on a CRITICAL +# the Chrome sidecar; #292), scripts/otel-smoke.ts (spans at the collector, /api/metrics; #293) and +# Trivy, which fails the job on a CRITICAL # vulnerability with a fix; # - `smoke-arm64` runs the same smoke test on the arm64 image, on GitHub's native arm64 runner; # - `tag` adds the release tags to the very digest that passed, with `imagetools create`, writes @@ -56,6 +57,7 @@ on: - "scripts/failover-smoke.ts" - "scripts/mail-smoke.ts" - "scripts/render-smoke.ts" + - "scripts/otel-smoke.ts" - "scripts/pack-packages.ts" - "scripts/selfhost-edge-bundle.ts" - "packages/cli/src/selfhost/**" @@ -117,6 +119,13 @@ jobs: docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile caddy config --quiet docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile mail config --quiet docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile chrome config --quiet + docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile otel config --quiet + # The otel profile's collector config, in the collector the compose file runs (a few seconds). + - name: Validate otel-collector.yaml + run: | + collector=$(sed -n 's/^ *image: \(otel\/opentelemetry-collector-contrib:.*\)$/\1/p' deploy/docker/compose.yml) + docker run --rm -v "$PWD/deploy/docker/otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro" \ + "$collector" validate --config=/etc/otelcol-contrib/config.yaml - name: Lint the Helm chart run: | helm lint deploy/helm/cloudhal @@ -124,6 +133,8 @@ jobs: helm template t deploy/helm/cloudhal --set httpRoute.enabled=true --set baseUrl=https://studio.example.com --set 'httpRoute.parentRefs[0].name=gw' > /dev/null helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp --set mail.from=cloudhal@example.com --set mail.caConfigMap.name=ca \ | grep -q 'CLOUDHAL_SMTP_CA_FILE' || { echo "::error::the chart's mail values render no CLOUDHAL_SMTP_CA_FILE"; exit 1; } + helm template t deploy/helm/cloudhal --set metrics.enabled=true | grep -q 'CLOUDHAL_METRICS_TOKEN:' \ + || { echo "::error::metrics.enabled puts no CLOUDHAL_METRICS_TOKEN in the Secret"; exit 1; } helm template t deploy/helm/cloudhal --set chrome.enabled=true \ | grep -q 'value: "http://t-cloudhal-chrome:9222"' || { echo "::error::chrome.enabled renders no CLOUDHAL_BROWSER_URL"; exit 1; } if helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp > /dev/null 2>&1; then @@ -274,6 +285,11 @@ jobs: - name: render_page smoke test (Chrome sidecar) timeout-minutes: 10 run: node scripts/render-smoke.ts --image cloudhal:ci + # Observability (#293): spans reach the otel profile's collector with service.name and the + # instance; /api/metrics answers its token holder in Prometheus text, and nobody else. CI only. + - name: Observability smoke test (collector, /api/metrics) + timeout-minutes: 10 + run: node scripts/otel-smoke.ts --image cloudhal:ci - name: Trivy scan timeout-minutes: 15 uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 diff --git a/AGENTS.md b/AGENTS.md index 4e63e61b..e3e77bf2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ node scripts/release-bundle.ts build|verify … # RFC-0046 release bundle: det - `packages/core-ts` — `SiteGraphStore` (CAS on `rev`, snapshots, diff, publish, rollback). Behavioural suite in `src/testing.ts` runs on sqlite and Miniflare D1. `./local` opens the offline store; `seedStarterSite` seeds a demo. `./surfaces` is RFC-0020's generative UI: the catalog (primitives + block types), eval-free surface checks, bindings, repairs, JSON Patch (`patchPage`), `catalogPrompt`; `./interop` converts A2UI v0.9 and json-render to and from surfaces; `./design` is RFC-0021's DESIGN.md lint and guidance. `./fields` is RFC-0041's typed custom fields (definition and value checks, `resolveFields`, `formatFieldValue`, the agents' JSON Schema, the conversion table); `src/fields-operations/` runs rename/retype/localize/remove. `search.ts` is RFC-0019's FTS5 site search (index written with the publish batch; articles, pages, terms and authors, RFC-0029); `search-provider.ts` is RFC-0029's `SearchProvider` (`fts5`, `memory`, `withFallback`), set with `SiteGraphStoreOptions.search`; `search-ai.ts` is the experimental Cloudflare AI Search provider (`hybridProvider`, `searchProviderFromEnv`, `cloudhal.json` `search`, docs/guides/search.md). - `packages/schedules` — RFC-0008: time model (only `temporal-polyfill/implementation`, `now` injected, never `Temporal.Now`), RRULE subset, release model (`rl1:`), automation/run state, taint and budgets, `runDue`; `./sql` is `SqlScheduleStore`, `./engine` the Temporal-free part core-ts and the site Worker use. Worker-safe; conformance suites in `src/testing.ts` on sqlite and Miniflare D1. - `packages/astro-renderer` — `GraphSource` (live/snapshot), `cloudhal()` integration (virtual config + dev route-cache watcher), `.astro` section components (`Surface.astro` for RFC-0020 surfaces; `./surfaces` renders them, `./kit` has the table of contents and reading time; `./fields` and `EntryFields.astro` render typed field values, RFC-0041). `./status-page` is RFC-0043's status pages (`statusPage(state, input) → Response`, served by the Site Worker entry before Astro and by `cloudhal dev` at `/__cloudhal/status/`; the optional `statusPage` theme hook; the catalog in `src/status-strings/` where only `en.ts` is hand-edited and the other languages come from `pnpm i18n:import`). Routes live in starters, not here. -- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard, the first site and the SMTP sender behind `EMAIL` (`smtp-*.ts`, #291: STARTTLS or TLS only; `smtp-client.ts` has no imports because the config embeds it as a Worker module); `browser-sidecar.ts` binds the optional Chrome for `render_page` as `BROWSER_CDP` (#292, `@cloudhal/cloudflare`'s `browser-cdp.ts`); `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. +- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard, the first site and the SMTP sender behind `EMAIL` (`smtp-*.ts`, #291: STARTTLS or TLS only; `smtp-client.ts` has no imports because the config embeds it as a Worker module); `browser-sidecar.ts` binds the optional Chrome for `render_page` as `BROWSER_CDP` (#292, `@cloudhal/cloudflare`'s `browser-cdp.ts`); `otel.ts` is the trace exporter (instance and version headers) and `CLOUDHAL_METRICS_TOKEN` for the admin Worker's `/api/metrics` (#293, `@cloudhal/cloudflare`'s `metrics.ts`, counters in `@cloudhal/core-ts`'s `request-metrics.ts`); `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. - `packages/cloudflare` — the admin Worker (`createAdminWorker`); `./playground` is RFC-0036's playground Worker (`createPlaygroundWorker`, the `PlaygroundSite` Durable Object, signed session cookies). Generated entries must import `@cloudhal/cloudflare/workerd-prelude` first (ADR-0012). - `packages/agent-runtime` / `packages/mcp-server` — policy, skills, audit; MCP tools and transports (ADR-0011). `@cloudhal/mcp-server/render` is RFC-0021's `render_page` core: a small DevTools client, the in-page checks and limits; the CLI drives local Chrome with it (`render-chrome.ts`), the admin Worker Browser Rendering (`browser-render.ts`). - `starters/blog` — the theme boundary: `src/pages/[...path].astro`, `src/layouts`, `src/theme.ts`. diff --git a/deploy/docker/.dockerignore b/deploy/docker/.dockerignore index d8fdcf21..74da6f9d 100644 --- a/deploy/docker/.dockerignore +++ b/deploy/docker/.dockerignore @@ -3,6 +3,7 @@ README.md compose.yml Caddyfile +otel-collector.yaml .env.example .env .DS_Store diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example index daaacea1..d970d613 100644 --- a/deploy/docker/.env.example +++ b/deploy/docker/.env.example @@ -53,5 +53,10 @@ #CLOUDHAL_BROWSER_URL=http://chrome:9222 #CLOUDHAL_RENDER_ORIGIN=http://cloudhal:8788 -# Traces of every Worker invocation to an OTLP/HTTP collector. +# Traces of every Worker invocation to an OTLP/HTTP collector (http:// or https://, no path; the +# otel profile runs one), and a backend's own headers (name=value,…; also _FILE). #OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 +#OTEL_EXPORTER_OTLP_HEADERS= +# GET /api/metrics, Prometheus text of this instance, for whoever holds this token (32+ characters: +# openssl rand -hex 32). Empty: off. Scrape each instance on the private network, never the proxy. +#CLOUDHAL_METRICS_TOKEN= diff --git a/deploy/docker/Caddyfile b/deploy/docker/Caddyfile index c9ce61f9..3d62d210 100644 --- a/deploy/docker/Caddyfile +++ b/deploy/docker/Caddyfile @@ -4,6 +4,8 @@ # CLOUDHAL_BEHIND_PROXY=1. Caddy appends the client's address to X-Forwarded-For, whose last hop # the image then takes as the client's (RFC-0047 §8). {$CLOUDHAL_BASE_URL} { + # Metrics are for a scraper on the private network (cloudhal:8787), never the public host. + respond /api/metrics 404 reverse_proxy cloudhal:8787 { # Build chat streams server-sent events flush_interval -1 diff --git a/deploy/docker/README.md b/deploy/docker/README.md index 68bb6d45..b3820249 100644 --- a/deploy/docker/README.md +++ b/deploy/docker/README.md @@ -18,6 +18,7 @@ The official self-host image, `ghcr.io/cloudhal-dev/cloudhal`, built from each r - With the `caddy` profile, Caddy proxies both hosts with TLS and sets `CF-Connecting-IP`. - With the `mail` profile, Mailpit catches every message at http://127.0.0.1:8025. It requires STARTTLS, with a certificate the `mail-tls` one-shot makes once. - With the `chrome` profile, a headless Chrome serves `render_page` (`CLOUDHAL_BROWSER_URL=http://chrome:9222`). It publishes no port and shares a network with Cloudhal only. + - With the `otel` profile, an OpenTelemetry Collector (`otel-collector.yaml`) prints the traces and labels them with the instance and version. Caddy never serves `/api/metrics` publicly. Build a release: @@ -33,4 +34,4 @@ node scripts/pack-packages.ts deploy/docker/tarballs && pnpm --filter @cloudhal/ `node scripts/docker-smoke.ts --image cloudhal:local` runs what CI runs after every build (`.github/workflows/docker.yml`); `--platform linux/arm64` runs the other architecture where Docker can. -`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. So does `scripts/mail-smoke.ts` (#291), which sends an invite and a password reset through Mailpit with STARTTLS and AUTH required, and `scripts/render-smoke.ts` (#292), which calls `render_page` through the Chrome sidecar. +`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. So does `scripts/mail-smoke.ts` (#291), which sends an invite and a password reset through Mailpit with STARTTLS and AUTH required, `scripts/render-smoke.ts` (#292), which calls `render_page` through the Chrome sidecar, and `scripts/otel-smoke.ts` (#293), which checks spans at the collector and `/api/metrics`. diff --git a/deploy/docker/compose.yml b/deploy/docker/compose.yml index e8717e93..a53d275e 100644 --- a/deploy/docker/compose.yml +++ b/deploy/docker/compose.yml @@ -9,6 +9,8 @@ # (http://127.0.0.1:8025; see the mailpit service) # docker compose --profile chrome up -d + a headless Chrome for render_page (see the chrome # service) +# docker compose --profile otel up -d + an OpenTelemetry Collector that prints Cloudhal's +# traces (otel-collector.yaml next to this file) # Every instance of an installation needs the same .env; this file runs one instance (the cluster # of one). More instances: deploy/swarm or deploy/helm. x-store: &store @@ -53,7 +55,11 @@ services: CLOUDHAL_BEHIND_PROXY: ${CLOUDHAL_BEHIND_PROXY:-0} CLOUDHAL_SITE_NAME: ${CLOUDHAL_SITE_NAME:-My site} CLOUDHAL_AUTOMATIONS: ${CLOUDHAL_AUTOMATIONS:-} + # Traces (the otel profile: http://otel-collector:4318) and a backend's own headers. OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-} + OTEL_EXPORTER_OTLP_HEADERS: ${OTEL_EXPORTER_OTLP_HEADERS:-} + # GET /api/metrics (Prometheus text) for whoever holds this token; empty keeps it off. + CLOUDHAL_METRICS_TOKEN: ${CLOUDHAL_METRICS_TOKEN:-} # Mail (invites, password resets): off unless CLOUDHAL_SMTP_URL is set. smtp:// is STARTTLS, # smtps:// TLS from the start; there is no unencrypted mode. CLOUDHAL_SMTP_CA_FILE adds # certificates to trust (the mail profile's, a private relay's). @@ -176,6 +182,18 @@ services: security_opt: ["no-new-privileges:true"] networks: [render] + # The otel profile: an OpenTelemetry Collector on this network only (no published port), with + # otel-collector.yaml next to this file. Set in .env: + # OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 + otel-collector: + profiles: [otel] + image: otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f + restart: unless-stopped + volumes: + - ./otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + networks: default: # Cloudhal and the chrome profile's browser, nothing else. diff --git a/deploy/docker/otel-collector.yaml b/deploy/docker/otel-collector.yaml new file mode 100644 index 00000000..997374a6 --- /dev/null +++ b/deploy/docker/otel-collector.yaml @@ -0,0 +1,46 @@ +# The OpenTelemetry Collector of compose.yml's `otel` profile (docs/guides/self-host.md, +# "Observability"). Cloudhal's workerd exports every Worker invocation's spans here over OTLP/HTTP +# (OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318). workerd sets `service.name` to the +# Worker (admin, site, d1, …); each export also carries x-cloudhal-instance and +# x-cloudhal-version headers, which the resource processor below turns into +# `service.instance.id` and `service.version`. +# +# The debug exporter prints spans to the collector's log (`docker compose logs otel-collector`). +# For a real backend, add an exporter and list it in the pipeline, for example: +# otlphttp/jaeger: { endpoint: http://jaeger:4318 } +# otlphttp/tempo: { endpoint: http://tempo:4318 } +# otlphttp/honeycomb: +# endpoint: https://api.honeycomb.io +# headers: { x-honeycomb-team: ${env:HONEYCOMB_API_KEY} } +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + # keeps the request headers as client metadata, for the resource processor + include_metadata: true + +processors: + resource/cloudhal: + attributes: + - key: service.namespace + value: cloudhal + action: upsert + - key: service.instance.id + from_context: metadata.x-cloudhal-instance + action: upsert + - key: service.version + from_context: metadata.x-cloudhal-version + action: upsert + batch: {} + +exporters: + debug: + verbosity: detailed + +service: + pipelines: + traces: + receivers: [otlp] + processors: [resource/cloudhal, batch] + exporters: [debug] diff --git a/deploy/helm/cloudhal/README.md b/deploy/helm/cloudhal/README.md index 3223f044..27beb94b 100644 --- a/deploy/helm/cloudhal/README.md +++ b/deploy/helm/cloudhal/README.md @@ -79,6 +79,13 @@ helm upgrade cloudhal deploy/helm/cloudhal --reuse-values \ The instances open in it only a page's signed preview link, at `http://:8788` (`chrome.renderOrigin`). `chrome.url` names a browser of your own instead. +## Traces and metrics + +- **Traces:** `otel.endpoint` points at an OTLP/HTTP collector, and `otel.headersSecret` takes a backend's headers from a Secret. Each export carries `x-cloudhal-instance` (the pod's peer name) and `x-cloudhal-version`, for the collector to turn into resource attributes. +- **Metrics:** `metrics.enabled=true` adds `CLOUDHAL_METRICS_TOKEN` to the generated Secret. Each pod then answers `GET /api/metrics` (Prometheus text) on port 8787 for that bearer token. + - Scrape the pods, not the Service: the numbers are per instance. + - With `secrets.existingSecret`, add the key yourself. + ## Upgrades ```bash diff --git a/deploy/helm/cloudhal/templates/secret.yaml b/deploy/helm/cloudhal/templates/secret.yaml index 9207e2ad..d46e38f3 100644 --- a/deploy/helm/cloudhal/templates/secret.yaml +++ b/deploy/helm/cloudhal/templates/secret.yaml @@ -19,4 +19,7 @@ data: {{- range $key := splitList " " (include "cloudhal.secretKeys" .) }} {{ $key }}: {{ get $data $key | default (randAlphaNum 64 | b64enc) }} {{- end }} + {{- if .Values.metrics.enabled }} + CLOUDHAL_METRICS_TOKEN: {{ get $data "CLOUDHAL_METRICS_TOKEN" | default (randAlphaNum 64 | b64enc) }} + {{- end }} {{- end }} diff --git a/deploy/helm/cloudhal/templates/statefulset.yaml b/deploy/helm/cloudhal/templates/statefulset.yaml index 2f050dd8..8e54610b 100644 --- a/deploy/helm/cloudhal/templates/statefulset.yaml +++ b/deploy/helm/cloudhal/templates/statefulset.yaml @@ -72,6 +72,13 @@ spec: - name: OTEL_EXPORTER_OTLP_ENDPOINT value: {{ . | quote }} {{- end }} + {{- with .Values.otel.headersSecret.name }} + - name: OTEL_EXPORTER_OTLP_HEADERS + valueFrom: + secretKeyRef: + name: {{ . | quote }} + key: {{ $.Values.otel.headersSecret.key | quote }} + {{- end }} {{- with .Values.mail.smtpUrlSecret.name }} - name: CLOUDHAL_SMTP_URL valueFrom: diff --git a/deploy/helm/cloudhal/values.yaml b/deploy/helm/cloudhal/values.yaml index 621fc3cf..93b15ea3 100644 --- a/deploy/helm/cloudhal/values.yaml +++ b/deploy/helm/cloudhal/values.yaml @@ -83,9 +83,22 @@ podDisruptionBudget: enabled: true maxUnavailable: 1 +# Traces of every Worker invocation over OTLP/HTTP (http:// or https://, no path). Each export +# carries x-cloudhal-instance and x-cloudhal-version headers for the collector to turn into +# service.instance.id and service.version (deploy/docker/otel-collector.yaml shows how). otel: # http://otel-collector.observability:4318 endpoint: "" + # A backend's own headers (name=value,…) from a Secret of your own, e.g. an API key. + headersSecret: + name: "" + key: OTEL_EXPORTER_OTLP_HEADERS + +# GET /api/metrics on each pod's Studio port: Prometheus text of that instance, for whoever holds +# CLOUDHAL_METRICS_TOKEN. `enabled` adds the token to the generated Secret (with +# secrets.existingSecret, add the key there yourself). Scrape the pods, not the Service. +metrics: + enabled: false # Mail (invites and password resets by email): off unless smtpUrlSecret.name is set. The URL is # smtp://user:password@host:587 (STARTTLS) or smtps://user:password@host:465 (TLS from the start); diff --git a/deploy/swarm/README.md b/deploy/swarm/README.md index 875fcf15..7bea9494 100644 --- a/deploy/swarm/README.md +++ b/deploy/swarm/README.md @@ -53,4 +53,7 @@ ``` Add `CLOUDHAL_BROWSER_URL: http://chrome:9222` to the `cloudhal` service's `environment`. The browser opens only the page's signed preview link, at `http://cloudhal:8788` (`CLOUDHAL_RENDER_ORIGIN`). Pin the image by digest as `deploy/docker/compose.yml` does. +- **Traces and metrics:** set `OTEL_EXPORTER_OTLP_ENDPOINT` when you deploy (the stack passes it on). + - For `/api/metrics`, create a `cloudhal_metrics_token` secret (`openssl rand -hex 32`). Add it to the service's `secrets` and the file's list, and set `CLOUDHAL_METRICS_TOKEN_FILE: /run/secrets/cloudhal_metrics_token`. + - Scrape each task on the stack's network (`tasks.cloudhal:8787` in DNS service discovery), never through the routing mesh. - **External store:** to use an external S3 store, set `CLOUDHAL_S3_ENDPOINT` and the bucket, put its keys in the two `cloudhal_aws_*` secrets, and remove the `seaweedfs` service. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index d2e9fb20..97b838c5 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -113,7 +113,8 @@ location / { | `CLOUDHAL_SMTP_CA_FILE` | PEM certificates to trust besides the browser CAs, for a relay with a private CA. | | `CLOUDHAL_BROWSER_URL` | Chrome's DevTools port for `render_page` ([screenshots](#screenshots-for-agents)), such as `http://chrome:9222`. Unset, the tool reports itself unavailable. | | `CLOUDHAL_RENDER_ORIGIN` | Where that Chrome reaches the site, the same on every instance. Default: `http://cloudhal:`. | -| `OTEL_EXPORTER_OTLP_ENDPOINT` | Traces of every Worker invocation to an OTLP/HTTP collector. | +| `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_HEADERS` | Traces of every Worker invocation to an OTLP/HTTP collector (`http://` or `https://`, no path), and a backend's own headers (`name=value,…`, `_FILE` too) ([observability](#observability)). | +| `CLOUDHAL_METRICS_TOKEN` | Turns `GET /api/metrics` (Prometheus text) on for whoever holds it; 32 characters or more, `_FILE` too. | | `CLOUDHAL_BIND`, `CLOUDHAL_PORT`, `CLOUDHAL_SITE_PORT` | Compose only: the host address and ports for Studio (8787) and the site (8788). | `docker compose exec cloudhal cloudhal-selfhost config` prints the workerd config the instance runs. Its output contains the cluster key, so do not share it. @@ -217,6 +218,43 @@ docker compose --profile chrome up -d On Kubernetes, set `chrome.enabled=true` (or `chrome.url` for a browser of your own). Swarm's README shows the service to add. CI calls `render_page` through the sidecar with every image ([`scripts/render-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/render-smoke.ts)). +## Observability + +Logs are JSON lines on stdout, as before. Traces and metrics are both optional. + +**Traces.** Set `OTEL_EXPORTER_OTLP_ENDPOINT` to an OTLP/HTTP collector, and workerd exports a span for every Worker invocation, subrequest and binding operation. +- **Resource attributes.** `service.name` is the Worker (`admin`, `site`, `d1`, `r2`, …). Each export also carries `x-cloudhal-instance` (the instance's advertise name) and `x-cloudhal-version` headers. A collector turns them into `service.instance.id` and `service.version`, as [`otel-collector.yaml`](https://github.com/cloudhal-dev/cloudhal/blob/main/deploy/docker/otel-collector.yaml) does with `include_metadata` and the resource processor's `from_context`. +- **Backend headers.** `OTEL_EXPORTER_OTLP_HEADERS` adds a backend's own headers, such as an API key. They are part of the generated config, so keep `cloudhal-selfhost config` output private. +- **No path.** workerd always posts to `/v1/traces`, so for a backend with a path prefix, send to a collector first. + +The compose file's `otel` profile runs that collector with a debug exporter: `docker compose logs otel-collector` shows the spans. Download `otel-collector.yaml` next to `compose.yml`, add an exporter for your backend (Jaeger, Tempo, Honeycomb, Grafana Cloud; the file names a few), set `OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318`, and start the profile: + +```bash +curl -fsSLO https://raw.githubusercontent.com/cloudhal-dev/cloudhal/main/deploy/docker/otel-collector.yaml +``` + +```bash +docker compose --profile otel up -d +``` + +**Metrics.** Set `CLOUDHAL_METRICS_TOKEN` (`openssl rand -hex 32`), and `GET /api/metrics` on Studio's port answers whoever sends `Authorization: Bearer `, in Prometheus text format. It covers: +- requests and their durations, of the admin and site Workers, by area and status class; +- publish durations (`cloudhal_publish_duration_seconds`); +- the scheduler's lag, its last tick and whether it is healthy; +- failed database and media operations (`cloudhal_store_errors_total`). + +The numbers are the instance's own, from its start, so scrape every instance directly (`cloudhal:8787` in compose, each pod or task), never through the proxy. The compose file's Caddy answers 404 for `/api/metrics` on the public host. Without the token, the route answers 404. + +```yaml +scrape_configs: + - job_name: cloudhal + metrics_path: /api/metrics + authorization: { credentials_file: /etc/prometheus/cloudhal-metrics-token } + static_configs: [{ targets: ["cloudhal:8787"] }] +``` + +CI checks both with every image ([`scripts/otel-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/otel-smoke.ts)): spans of both Workers reach the collector with the instance and the version, and `/api/metrics` answers its token holder and nobody else. + ## Upgrades The image carries the same version as the npm packages and the release bundle. Tags are `X.Y.Z`, `X.Y` and `latest`; in production, pin `X.Y` (`CLOUDHAL_TAG=0.11`). diff --git a/docs/rfcs/0047-self-host-on-workerd.md b/docs/rfcs/0047-self-host-on-workerd.md index 5f544456..0eaa27a6 100644 --- a/docs/rfcs/0047-self-host-on-workerd.md +++ b/docs/rfcs/0047-self-host-on-workerd.md @@ -154,6 +154,28 @@ The site Worker needs the site's id in its config (`CLOUDHAL_SITE_ID`). Open que - **Shutdown:** on SIGTERM workerd hands its Durable Objects to its peers, keeps accepting requests for at least 5 s, and exits within `stopTimeoutMs`, which stays at 8 s. The recipes set `stop_grace_period: 15s` (Compose and Swarm) and keep Kubernetes' 30 s grace period. - **A killed instance:** its objects move only when its lease expires, after about 20 s. The spike measured about 16 s of 500 answers for D1-backed routes, which needs at least two replicas behind a readiness-aware load balancer. +### 7a. Observability + +*Amended 2026-11-29 (#293). The metrics decision follows the PM's recommendation.* + +- **Traces.** `OTEL_EXPORTER_OTLP_ENDPOINT` (`http://` or `https://`, host and port; workerd POSTs to `/v1/traces`) becomes the `otlp` `ExternalServer` of `tracing`, and `OTEL_EXPORTER_OTLP_HEADERS` adds a backend's headers. + - workerd sets `service.name` to each Worker's service (`admin`, `site`, `d1`, …) and offers no other resource attributes. + - So every export carries `x-cloudhal-instance` (the instance's advertise name) and `x-cloudhal-version` headers (`injectRequestHeaders`). A collector turns them into `service.instance.id` and `service.version`; `deploy/docker/otel-collector.yaml` does. + - That header is the only per-instance part of the config besides the sockets and `advertise`. It labels spans and changes no Worker's behaviour, so the identical-config rule (§2, invariant 2) holds. +- **Metrics: an authenticated `/api/metrics` on the admin Worker, not traces alone.** It is Prometheus text (0.0.4) of one instance. + - **Requests:** `cloudhal_http_requests_total` and `cloudhal_http_request_duration_seconds`, by Worker (admin, and site through `SITE` and `/__cloudhal/metrics`), area and status class. + - **Publishes:** `cloudhal_publish_duration_seconds`, for API and MCP publishes, by how and outcome. + - **Scheduler:** `cloudhal_scheduler_lag_seconds`, `cloudhal_scheduler_seconds_since_tick` and `cloudhal_scheduler_healthy`. + - **Store errors:** `cloudhal_store_errors_total`, for D1 statements after retries and R2 operations. + - **Process start:** `cloudhal_process_start_time_seconds`. +- **Why not traces only.** Alerting on scheduler lag or error rates from spans needs a span-metrics pipeline in every operator's stack. A scrape endpoint works with any Prometheus-compatible agent. +- **Why per instance.** Counters live in the isolate (workerd runs one per Worker per instance) and reset on restart, which `rate()` handles. Gauges are read at scrape time. A scraper therefore reaches each instance directly (pods, Swarm tasks), never through the load balancer. +- **Not public.** + - `/api/metrics` answers 404 unless `CLOUDHAL_METRICS_TOKEN` (32+ characters, `_FILE` too) is set, and 401 to anyone without `Authorization: Bearer `. The token grants nothing else, so a scraper never holds the deploy token. + - The compose file's Caddy answers 404 for `/api/metrics` on the public host. + - Labels are a small fixed set: no paths, site ids, users or agents. +- **Not on Cloudflare.** Many isolates make per-isolate counters meaningless there. The route stays off unless the token is set, and Workers' own analytics and traces serve that platform. + ### 8. Client address *Amended 2026-11-23, in phase 3:* a small front Worker sits in front of each socket (`packages/cli/src/selfhost/front-worker.ts`). It always removes an incoming `CF-Connecting-IP`. Behind a proxy it sets the header to the last `X-Forwarded-For` hop, which is how `cloudhal studio --behind-proxy` read the address on Node (#165). So no proxy needs to set `CF-Connecting-IP`, and an ingress that passes client headers through cannot be spoofed. The text below describes the first design. diff --git a/packages/astro-renderer/src/cloudflare-entry.ts b/packages/astro-renderer/src/cloudflare-entry.ts index 57f595f0..efca381a 100644 --- a/packages/astro-renderer/src/cloudflare-entry.ts +++ b/packages/astro-renderer/src/cloudflare-entry.ts @@ -59,6 +59,7 @@ import { withRequestSite, } from "@cloudhal/astro-renderer/runtime"; import { SqlCommentStore } from "@cloudhal/comments/sql"; +import { RequestMetrics } from "@cloudhal/core-ts"; import { GATES_FEATURE_VERSION } from "@cloudhal/core-ts/availability"; import { FIELDS_FEATURE_VERSION } from "@cloudhal/core-ts/fields"; import { D1Driver } from "@cloudhal/storage/d1"; @@ -282,6 +283,14 @@ function fromAdmin(request: Request, env: Env): boolean { return !!expected && timingSafeEqual(given, expected); } +/** This isolate's request counters (#293), for the admin Worker's `/api/metrics`. Never cached. */ +function metricsJson(request: Request, env: Env, metrics: RequestMetrics): Response { + const headers = { "cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store" }; + if (!fromAdmin(request, env)) + return Response.json({ error: "unauthorized" }, { status: 401, headers }); + return Response.json(metrics.toJSON(), { headers }); +} + /** * What this site Worker enforces (RFC-0008 §7.6–§7.7): the admin Worker asks before it lets anyone * write time gates, and (RFC-0045 §1) the `fields` feature: 2 for reference and repeater fields, @@ -626,10 +635,12 @@ async function siteless(request: Request, state: StatusState): Promise export function createSiteWorker(options: { siteId?: string } = {}) { const searchLimiter = new SearchLimiter(); + const metrics = new RequestMetrics(); async function route(request: Request, env: Env, ctx: ExecutionContext): Promise { const url = new URL(request.url); if (url.pathname === "/__cloudhal/purge") return purge(request, env, options.siteId); if (url.pathname === "/__cloudhal/features") return features(request, env); + if (url.pathname === "/__cloudhal/metrics") return metricsJson(request, env, metrics); const moved = hostRedirect(request, env); if (moved) return moved; // RFC-0034 §4: the hostname picks the site on a multi-site Worker; everything the request @@ -665,12 +676,18 @@ export function createSiteWorker(options: { siteId?: string } = {}) { return { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { // #62: the edge cache is shared by every host this Worker answers on, unless told to vary. + const started = Date.now(); + let response: Response; try { - return varyByHost(await route(request, env, ctx)); + response = varyByHost(await route(request, env, ctx)); } catch (error) { // RFC-0043 §1.8: whatever failed, the visitor gets a page and a reference to quote. - return varyByHost(errorPage(request, error)); + response = varyByHost(errorPage(request, error)); } + // the admin Worker's scrape of these counters is not one of them + if (!request.url.endsWith("/__cloudhal/metrics")) + metrics.record("", response.status, (Date.now() - started) / 1000); + return response; }, }; } diff --git a/packages/cli/src/selfhost/otel.ts b/packages/cli/src/selfhost/otel.ts new file mode 100644 index 00000000..a43245eb --- /dev/null +++ b/packages/cli/src/selfhost/otel.ts @@ -0,0 +1,111 @@ +/** + * #293: observability settings of the self-host image (RFC-0047 §7, amended 2026-11-29). + * + * - **Traces.** `OTEL_EXPORTER_OTLP_ENDPOINT` (`http://` or `https://`, host and port; workerd + * POSTs to `/v1/traces` itself) becomes the `otlp` `ExternalServer` of `tracing`. workerd sets + * `service.name` to each Worker's service (`admin`, `site`, `d1`, …) and has no setting for + * other resource attributes, so every export carries `x-cloudhal-instance` (this instance's + * advertise name) and `x-cloudhal-version` headers, which a collector turns into + * `service.instance.id` and `service.version` (deploy/docker/otel-collector.yaml). + * `OTEL_EXPORTER_OTLP_HEADERS` (`name=value,…`, also `_FILE`) adds a backend's own headers. + * - **Metrics.** `CLOUDHAL_METRICS_TOKEN` (also `_FILE`, at least 32 characters) turns the admin + * Worker's `GET /api/metrics` on for its holder (`@cloudhal/cloudflare`'s `metrics.ts`). + * + * The instance header is the only part of the config that differs between instances besides the + * sockets and `advertise`. It changes no Worker's behaviour, only how its spans are labelled, so + * the cluster's "identical configuration" rule holds. + */ + +export interface OtlpSettings { + /** `host:port` of the collector's OTLP/HTTP port. */ + readonly address: string; + readonly tls: boolean; + /** Sent with every export: the backend's own, then the instance's. */ + readonly headers: readonly (readonly [string, string])[]; +} + +type Env = Readonly>; + +const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/; + +/** `OTEL_EXPORTER_OTLP_HEADERS`: `name=value` pairs, comma-separated, values URL-encoded (OTel). */ +export function otlpHeaders(raw: string | undefined, problems: string[]): [string, string][] { + const out: [string, string][] = []; + for (const part of (raw ?? "").split(",")) { + const pair = part.trim(); + if (pair === "") continue; + const eq = pair.indexOf("="); + const name = pair.slice(0, Math.max(eq, 0)).trim(); + let value = ""; + try { + value = decodeURIComponent(pair.slice(eq + 1).trim()); + } catch { + value = "\n"; + } + // never the value: it is usually an API key + if (eq < 1 || !HEADER_NAME.test(name) || /[\r\n]/.test(value)) + problems.push(`OTEL_EXPORTER_OTLP_HEADERS: a malformed pair (${name || "no name"})`); + else out.push([name.toLowerCase(), value]); + } + return out; +} + +/** The trace exporter, or `undefined` when `OTEL_EXPORTER_OTLP_ENDPOINT` is unset. */ +export function readOtlp(env: Env, instance: string, problems: string[]): OtlpSettings | undefined { + const raw = env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim(); + if (!raw) return undefined; + let url: URL; + try { + url = new URL(/^[a-z]+:\/\//i.test(raw) ? raw : `http://${raw}`); + } catch { + problems.push("OTEL_EXPORTER_OTLP_ENDPOINT is not a URL (http://otel-collector:4318)"); + return undefined; + } + if (url.protocol !== "http:" && url.protocol !== "https:") + problems.push("OTEL_EXPORTER_OTLP_ENDPOINT is an http:// or https:// OTLP/HTTP endpoint"); + const path = url.pathname.replace(/\/$/, ""); + if (path !== "" && path !== "/v1/traces") + problems.push( + "OTEL_EXPORTER_OTLP_ENDPOINT takes no path: workerd posts to /v1/traces on it (use a collector for a backend with a path prefix)", + ); + const tls = url.protocol === "https:"; + const headers = otlpHeaders(env.OTEL_EXPORTER_OTLP_HEADERS, problems).filter( + ([n]) => n !== "x-cloudhal-instance" && n !== "x-cloudhal-version", + ); + return { + address: `${url.hostname}:${url.port || (tls ? "443" : "80")}`, + tls, + headers: [...headers, ["x-cloudhal-instance", instance]], + }; +} + +/** `CLOUDHAL_METRICS_TOKEN`, checked; `undefined` keeps `/api/metrics` off. */ +export function readMetricsToken(env: Env, problems: string[]): string | undefined { + const token = env.CLOUDHAL_METRICS_TOKEN; + if (!token) return undefined; + if (token.length < 32) + problems.push("CLOUDHAL_METRICS_TOKEN: at least 32 characters (openssl rand -hex 32)"); + return token; +} + +const q = (s: string) => JSON.stringify(s); + +/** The `otlp` service, with the version header of this image's bundle. */ +export function otlpService(o: OtlpSettings | undefined, version: string): string[] { + if (!o) return []; + const inject = [...o.headers, ["x-cloudhal-version", version] as const] + .map(([n, v]) => `(name = ${q(n)}, value = ${q(v)})`) + .join(", "); + const options = `(injectRequestHeaders = [${inject}])`; + const transport = o.tls + ? `https = (options = ${options}, tlsOptions = (trustBrowserCas = true))` + : `http = ${options}`; + return [`(name = "otlp", external = (address = ${q(o.address)}, ${transport}))`]; +} + +/** The admin Worker's metrics binding, only when the token is set (never in the config text). */ +export function metricsBindings(token: string | undefined): string[] { + return token + ? [`(name = "CLOUDHAL_METRICS_TOKEN", fromEnvironment = "CLOUDHAL_METRICS_TOKEN")`] + : []; +} diff --git a/packages/cli/src/selfhost/settings.ts b/packages/cli/src/selfhost/settings.ts index 9713004b..8a88a6ba 100644 --- a/packages/cli/src/selfhost/settings.ts +++ b/packages/cli/src/selfhost/settings.ts @@ -8,6 +8,7 @@ import { readFileSync } from "node:fs"; import { resolveAdvertise } from "./advertise.ts"; import { type BrowserSettings, readBrowserSettings } from "./browser-sidecar.ts"; +import { type OtlpSettings, readMetricsToken, readOtlp } from "./otel.ts"; import { type MailSettings, readMailSettings } from "./smtp-settings.ts"; /** The manifest's secrets (RFC-0046 `bindingTemplates.*.secrets`) the image requires. */ @@ -47,8 +48,10 @@ export interface SelfhostSettings { /** Writable: Durable Object SQLite files, the marker of a v2 volume. */ readonly dataDir: string; readonly ports: { readonly studio: number; readonly site: number }; - /** `host:port` of an OTLP/HTTP collector, from `OTEL_EXPORTER_OTLP_ENDPOINT`. */ - readonly otlp: string | undefined; + /** The trace exporter, from `OTEL_EXPORTER_OTLP_ENDPOINT` (#293). */ + readonly otlp: OtlpSettings | undefined; + /** `CLOUDHAL_METRICS_TOKEN`: `/api/metrics` is on for its holder (#293). */ + readonly metricsToken: string | undefined; /** Optional admin vars passed through when set (`CLOUDHAL_AUTOMATIONS`, …). */ readonly adminVars: Readonly>; /** The SMTP sender behind `EMAIL` (#291), when `CLOUDHAL_SMTP_URL` is set. */ @@ -77,6 +80,8 @@ export function resolveSecretFiles( "CLOUDHAL_CLUSTER_KEY", "CLOUDHAL_SITE_ID", "CLOUDHAL_SMTP_URL", + "CLOUDHAL_METRICS_TOKEN", + "OTEL_EXPORTER_OTLP_HEADERS", ]) { const file = env[`${name}_FILE`]; if (file === undefined || file === "") continue; @@ -104,13 +109,6 @@ function port(env: Env, name: string, fallback: number): number { return n; } -/** `https://host:port/path` or `host:port` → `host:port` (the OTLP collector). */ -function hostPort(value: string): string { - const url = /^[a-z]+:\/\//i.test(value) ? new URL(value) : new URL(`http://${value}`); - const p = url.port || (url.protocol === "https:" ? "443" : "80"); - return `${url.hostname}:${p}`; -} - /** Every missing or malformed setting, so the operator fixes them in one go. */ function problems(env: Env): string[] { const out: string[] = []; @@ -139,10 +137,13 @@ export function readSettings( const mail = readMailSettings(env, found, read); const sitePort = port(env, "CLOUDHAL_SITE_PORT", 8788); const browser = readBrowserSettings(env, sitePort, found); + const clusterPort = port(env, "CLOUDHAL_CLUSTER_PORT", 7000); + const advertise = resolveAdvertise(env.CLOUDHAL_CLUSTER_ADVERTISE, clusterPort); + const otlp = readOtlp(env, advertise, found); + const metricsToken = readMetricsToken(env, found); if (found.length > 0) throw new Error(`the self-host settings are incomplete:\n - ${found.join("\n - ")}`); const prefix = (env.CLOUDHAL_S3_PREFIX ?? "").replace(/^\/+/, ""); - const clusterPort = port(env, "CLOUDHAL_CLUSTER_PORT", 7000); const adminVars: Record = {}; for (const name of PASSED_VARS) if (env[name]) adminVars[name] = env[name] as string; return { @@ -155,7 +156,7 @@ export function readSettings( cluster: { key: env.CLOUDHAL_CLUSTER_KEY as string, address: `0.0.0.0:${clusterPort}`, - advertise: resolveAdvertise(env.CLOUDHAL_CLUSTER_ADVERTISE, clusterPort), + advertise, }, siteId: env.CLOUDHAL_SITE_ID as string, siteName: env.CLOUDHAL_SITE_NAME || "My site", @@ -166,7 +167,8 @@ export function readSettings( studio: port(env, "CLOUDHAL_PORT", 8787), site: sitePort, }, - otlp: env.OTEL_EXPORTER_OTLP_ENDPOINT ? hostPort(env.OTEL_EXPORTER_OTLP_ENDPOINT) : undefined, + otlp, + metricsToken, adminVars, mail, browser, diff --git a/packages/cli/src/selfhost/workerd-config.ts b/packages/cli/src/selfhost/workerd-config.ts index 269bc55f..682b27ce 100644 --- a/packages/cli/src/selfhost/workerd-config.ts +++ b/packages/cli/src/selfhost/workerd-config.ts @@ -11,6 +11,7 @@ import path from "node:path"; import type { ReleaseManifest } from "@cloudhal/release-verify"; import { BROWSER_FLAGS, browserAdminBindings, browserServices } from "./browser-sidecar.ts"; import { FRONT_WORKER_SOURCE } from "./front-worker.ts"; +import { metricsBindings, otlpService } from "./otel.ts"; import type { SelfhostSettings } from "./settings.ts"; import { smtpAdminBindings, smtpServices } from "./smtp-service.ts"; @@ -150,6 +151,7 @@ export function workerdConfig(input: ConfigInput): string { ...Object.entries(s.adminVars).map(([k, v]) => text(k, v)), ...smtpAdminBindings(s), ...browserAdminBindings(s.browser), + ...metricsBindings(s.metricsToken), ], ...(s.browser ? { flags: BROWSER_FLAGS } : {}), }); @@ -172,7 +174,7 @@ export function workerdConfig(input: ConfigInput): string { front("admin", s), ...smtpServices(s), ...browserServices(s.browser), - ...(s.otlp ? [`(name = "otlp", external = (address = ${q(s.otlp)}, http = ()))`] : []), + ...otlpService(s.otlp, m.version), ].map((x) => x.replaceAll("{DATA}", s.dataDir)); const bucket = `s3://${s.s3.bucket}/${s.s3.prefix}cluster`; return `# Generated by \`cloudhal selfhost\` (RFC-0047) for Cloudhal ${m.version}. Do not edit. diff --git a/packages/cli/test/selfhost-otel.test.ts b/packages/cli/test/selfhost-otel.test.ts new file mode 100644 index 00000000..070dea51 --- /dev/null +++ b/packages/cli/test/selfhost-otel.test.ts @@ -0,0 +1,77 @@ +/** #293: the self-host image's trace exporter and metrics token settings. */ +import { describe, expect, it } from "vitest"; +import { metricsBindings, otlpHeaders, otlpService } from "../src/selfhost/otel.ts"; +import { secretsEnv } from "../src/selfhost/secrets.ts"; +import { readSettings } from "../src/selfhost/settings.ts"; + +const ENV: Record = { + ...Object.fromEntries( + secretsEnv() + .split("\n") + .filter((l) => l && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ), + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", + CLOUDHAL_CLUSTER_ADVERTISE: "cloudhal-1:7000", +}; + +describe("the trace exporter", () => { + it("is off without OTEL_EXPORTER_OTLP_ENDPOINT", () => { + const s = readSettings(ENV); + expect(s.otlp).toBeUndefined(); + expect(otlpService(s.otlp, "0.12.0")).toEqual([]); + }); + + it("labels every export with this instance and version, plus the backend's own headers", () => { + const s = readSettings({ + ...ENV, + OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", + OTEL_EXPORTER_OTLP_HEADERS: "X-Api-Key=abc%3D123, x-cloudhal-instance=spoofed", + }); + expect(s.otlp).toEqual({ + address: "otel-collector:4318", + tls: false, + headers: [ + ["x-api-key", "abc=123"], + ["x-cloudhal-instance", "cloudhal-1:7000"], + ], + }); + expect(otlpService(s.otlp, "0.12.0")).toEqual([ + '(name = "otlp", external = (address = "otel-collector:4318", http = (injectRequestHeaders = [(name = "x-api-key", value = "abc=123"), (name = "x-cloudhal-instance", value = "cloudhal-1:7000"), (name = "x-cloudhal-version", value = "0.12.0")])))', + ]); + const tls = readSettings({ ...ENV, OTEL_EXPORTER_OTLP_ENDPOINT: "https://otlp.example.com" }); + expect(otlpService(tls.otlp, "0.12.0")[0]).toContain( + 'address = "otlp.example.com:443", https = (options = (injectRequestHeaders = [', + ); + expect(otlpService(tls.otlp, "0.12.0")[0]).toContain("tlsOptions = (trustBrowserCas = true)"); + }); + + it("refuses a path prefix, another scheme and a malformed header, never echoing a value", () => { + expect(() => + readSettings({ ...ENV, OTEL_EXPORTER_OTLP_ENDPOINT: "https://otlp.example.com/otlp" }), + ).toThrow(/takes no path/); + expect(() => + readSettings({ ...ENV, OTEL_EXPORTER_OTLP_ENDPOINT: "grpc://collector:4317" }), + ).toThrow(/http:\/\/ or https:\/\//); + const problems: string[] = []; + expect(otlpHeaders("novalue, Bad Name=secret-value, ok=1", problems)).toEqual([["ok", "1"]]); + expect(problems).toHaveLength(2); + expect(problems.join()).not.toContain("secret-value"); + }); +}); + +describe("the metrics token", () => { + it("binds the admin Worker through fromEnvironment only, and wants 32 characters", () => { + expect(readSettings(ENV).metricsToken).toBeUndefined(); + expect(metricsBindings(undefined)).toEqual([]); + const token = "m".repeat(40); + expect(readSettings({ ...ENV, CLOUDHAL_METRICS_TOKEN: token }).metricsToken).toBe(token); + expect(metricsBindings(token)).toEqual([ + '(name = "CLOUDHAL_METRICS_TOKEN", fromEnvironment = "CLOUDHAL_METRICS_TOKEN")', + ]); + expect(() => readSettings({ ...ENV, CLOUDHAL_METRICS_TOKEN: "short" })).toThrow( + /at least 32 characters/, + ); + }); +}); diff --git a/packages/cloudflare/src/admin-worker.ts b/packages/cloudflare/src/admin-worker.ts index bd7a9ce4..6cde0f7a 100644 --- a/packages/cloudflare/src/admin-worker.ts +++ b/packages/cloudflare/src/admin-worker.ts @@ -61,7 +61,7 @@ import { type BlockType, createBlockRegistry, type PropsSchema } from "@cloudhal import { workersTransport } from "@cloudhal/core-ts/media"; import { SqlScheduleStore } from "@cloudhal/schedules/sql"; import { migrate, migrations, type SqlDriver } from "@cloudhal/storage"; -import { D1Driver } from "@cloudhal/storage/d1"; +import type { D1Driver } from "@cloudhal/storage/d1"; import { R2BlobStore } from "@cloudhal/storage/r2"; import { adminRender, type DevtoolsBinding } from "./browser-cdp.ts"; import type { BrowserBinding } from "./browser-render.ts"; @@ -69,6 +69,7 @@ import { type BuildRoomsEnv, buildRoomClass, createDurableBuildHub } from "./bui import { adminComments, type CommentsEnv, commentsOn, flushCommentPurges } from "./comments.ts"; import { featureRoute, type SiteConfirmations, siteSupport } from "./features.ts"; import { adminMail, type MailEnv } from "./mail.ts"; +import { adminSql, instrumentAdmin, watchedBucket } from "./metrics.ts"; import { purgeSiteCache } from "./purge.ts"; import { type BackstopState, @@ -115,6 +116,8 @@ export interface AdminEnv extends CommentsEnv, SchedulerEnv, MailEnv, BuildRooms BROWSER_CDP?: DevtoolsBinding; /** Where that Chrome reaches the site: `render_page` opens the signed preview link there. */ CLOUDHAL_RENDER_ORIGIN?: string; + /** Turns `GET /api/metrics` on for whoever holds it (self-host, #293); absent: 404. */ + CLOUDHAL_METRICS_TOKEN?: string; /** `off` keeps `render_page` unavailable even with a `BROWSER` binding. */ CLOUDHAL_RENDER?: string; /** `off` turns the OAuth authorization server for remote MCP clients off (RFC-0044 §10). */ @@ -357,7 +360,7 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { migrated = true; }; - return { + return instrumentAdmin({ async fetch(request: Request, env: AdminEnv, ctx: ExecutionContext): Promise { const url = new URL(request.url); // The assets layer answers existing files before the Worker runs, so a request for a file @@ -377,8 +380,8 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { ); } - const sql = new D1Driver(env.DB); - const blobs = new R2BlobStore(env.BLOBS); + const sql = adminSql(env); + const blobs = new R2BlobStore(watchedBucket(env.BLOBS)); await ensureMigrated(sql); // A takedown (RFC-0004 §4.6) purges the asset's media URLs at once, not at the next publish. @@ -558,7 +561,7 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { env: AdminEnv, ctx: ExecutionContext, ): Promise { - const sql = new D1Driver(env.DB); + const sql = adminSql(env); await ensureMigrated(sql); const tick = (now: Date) => runAdminTick(env, { @@ -582,7 +585,7 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { log(`schedules tick (cron) failed: ${e instanceof Error ? e.message : String(e)}`); } }, - }; + }); } /** @@ -602,7 +605,7 @@ let clockMigrated = false; */ export const SchedulerClock = schedulerClockClass(async (env, o) => { const e = env as AdminEnv; - const sql = new D1Driver(e.DB); + const sql = adminSql(e); if (!clockMigrated) { await migrate(sql, migrations); clockMigrated = true; diff --git a/packages/cloudflare/src/metrics.ts b/packages/cloudflare/src/metrics.ts new file mode 100644 index 00000000..5972457c --- /dev/null +++ b/packages/cloudflare/src/metrics.ts @@ -0,0 +1,301 @@ +/** + * `GET /api/metrics` (#293; RFC-0047 §7, amended 2026-11-29): one instance's metrics in the + * Prometheus text format (0.0.4), for a scraper that reaches each instance directly. Off unless + * `CLOUDHAL_METRICS_TOKEN` is set; then only `Authorization: Bearer ` reads it (any + * other caller gets 401, and 404 while it is off). The token grants nothing else. + * + * - **Counters live in the isolate.** workerd runs one isolate per Worker per instance, so they + * are that instance's, from `cloudhal_process_start_time_seconds` on; a restart resets them, + * which Prometheus' `rate()` handles. On Cloudflare, with many isolates, they mean little, and + * traces and Workers Analytics are the tools there. + * - **Gauges are read when scraped:** the scheduler's last tick (D1), and the site Worker's own + * counters through `SITE` (`/__cloudhal/metrics`, Bearer `CLOUDHAL_PURGE_TOKEN`). + * - **Bounded labels only:** Worker, area of the path, status class, outcome, store. No paths, + * site ids, users or agents. + */ +import { + METRIC_BUCKETS as BUCKETS, + Histogram, + RequestMetrics, + type RequestMetricsJson, + type MetricSeries as Series, +} from "@cloudhal/core-ts"; +import { type SchedulerMode, schedulerHealthReport } from "@cloudhal/core-ts/releases"; +import { D1Driver } from "@cloudhal/storage/d1"; + +export const METRICS_PATH = "/api/metrics"; +export const SITE_METRICS_URL = "https://site.internal/__cloudhal/metrics"; +/** A Prometheus text line's number. */ +const num = (n: number) => (Number.isFinite(n) ? String(Math.round(n * 1e6) / 1e6) : "NaN"); + +function histogramLines(name: string, all: Record): string[] { + const out: string[] = []; + for (const [labels, s] of Object.entries(all)) { + const pre = labels ? `${labels},` : ""; + BUCKETS.forEach((le, i) => { + out.push(`${name}_bucket{${pre}le="${le}"} ${s.buckets[i]}`); + }); + out.push(`${name}_bucket{${pre}le="+Inf"} ${s.count}`); + out.push(`${name}_sum${labels ? `{${labels}}` : ""} ${num(s.sum)}`); + out.push(`${name}_count${labels ? `{${labels}}` : ""} ${s.count}`); + } + return out; +} + +const family = (name: string, type: string, help: string, lines: string[]) => + [`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, ...lines].join("\n"); + +/** The site Worker's counters, as `/__cloudhal/metrics` answers them. */ +export type SiteMetrics = RequestMetricsJson; + +/** Which part of Studio's origin a path belongs to: a small, fixed set of labels. */ +export function area(pathname: string): string { + if (pathname === "/mcp" || pathname.startsWith("/mcp/")) return "mcp"; + if (pathname.startsWith("/api/auth/")) return "auth"; + if (pathname.startsWith("/api/admin/")) return "admin"; + if (pathname.startsWith("/api/")) return "api"; + if (pathname.startsWith("/.well-known/")) return "oauth"; + return "studio"; +} + +/** This isolate's admin metrics. */ +export class AdminMetrics { + readonly requests = new RequestMetrics(); + readonly publishes = new Histogram(); + readonly #storeErrors = new Map(); + readonly startedAt = Date.now(); + + storeError(store: "d1" | "r2"): void { + this.#storeErrors.set(store, (this.#storeErrors.get(store) ?? 0) + 1); + } + + /** The exposition, with what was read at scrape time. */ + text(read: { + scheduler?: { secondsSinceTick?: number; lagSeconds?: number; healthy: boolean }; + site?: SiteMetrics; + }) { + const reqs = this.requests.toJSON(); + const counts = Object.entries(reqs.requests).map(([l, n]) => + `{worker="admin",${l}}`.concat(` ${n}`), + ); + const durations: Record = {}; + for (const [l, s] of Object.entries(reqs.durations)) durations[`worker="admin",${l}`] = s; + for (const [l, n] of Object.entries(read.site?.requests ?? {})) + counts.push(`{worker="site",${l}} ${n}`); + for (const [l, s] of Object.entries(read.site?.durations ?? {})) + durations[l ? `worker="site",${l}` : `worker="site"`] = s; + const errors = ["d1", "r2"].map((s) => `{store="${s}"} ${this.#storeErrors.get(s) ?? 0}`); + const out = [ + family( + "cloudhal_http_requests_total", + "counter", + "Requests this instance's admin and site Workers answered, by area and status class.", + counts.map((c) => `cloudhal_http_requests_total${c}`), + ), + family( + "cloudhal_http_request_duration_seconds", + "histogram", + "Time to answer a request.", + histogramLines("cloudhal_http_request_duration_seconds", durations), + ), + family( + "cloudhal_publish_duration_seconds", + "histogram", + "Time of a publish asked for over the API or MCP, by how and outcome.", + histogramLines("cloudhal_publish_duration_seconds", this.publishes.toJSON()), + ), + family( + "cloudhal_store_errors_total", + "counter", + "Database statements and media operations that failed (after any retries).", + errors.map((e) => `cloudhal_store_errors_total${e}`), + ), + ]; + if (read.scheduler) { + const s = read.scheduler; + out.push( + family("cloudhal_scheduler_healthy", "gauge", "1 while the scheduler ticks on time.", [ + `cloudhal_scheduler_healthy ${s.healthy ? 1 : 0}`, + ]), + ); + if (s.lagSeconds !== undefined) + out.push( + family( + "cloudhal_scheduler_lag_seconds", + "gauge", + "How late the oldest due release or automation run was at the last tick.", + [`cloudhal_scheduler_lag_seconds ${num(s.lagSeconds)}`], + ), + ); + if (s.secondsSinceTick !== undefined) + out.push( + family( + "cloudhal_scheduler_seconds_since_tick", + "gauge", + "Seconds since the scheduler's last tick (it ticks every minute).", + [`cloudhal_scheduler_seconds_since_tick ${num(s.secondsSinceTick)}`], + ), + ); + } + out.push( + family( + "cloudhal_process_start_time_seconds", + "gauge", + "When this isolate's counters started.", + [`cloudhal_process_start_time_seconds ${num(this.startedAt / 1000)}`], + ), + ); + return `${out.join("\n")}\n`; + } +} + +/** One per isolate. */ +export const ADMIN_METRICS = new AdminMetrics(); + +/** Equal tokens, compared without an early exit. */ +export function sameToken(given: string, expected: string): boolean { + const a = new TextEncoder().encode(given); + const b = new TextEncoder().encode(expected); + let diff = a.length ^ b.length; + for (let i = 0; i < b.length; i++) diff |= (a[i] ?? 0) ^ (b[i] as number); + return diff === 0; +} + +export interface MetricsEnv { + CLOUDHAL_METRICS_TOKEN?: string; + CLOUDHAL_PURGE_TOKEN?: string; + CLOUDHAL_SCHEDULER?: string; + DB: D1Database; + SITE?: { fetch(input: string, init?: RequestInit): Promise }; +} + +const plain = (status: number, text: string, extra: Record = {}) => + new Response(text, { + status, + headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...extra }, + }); + +async function readNow(env: MetricsEnv, metrics: AdminMetrics) { + const sql = new D1Driver(env.DB, { onError: () => metrics.storeError("d1") }); + const mode: SchedulerMode = env.CLOUDHAL_SCHEDULER === "cron" ? "cron" : "alarm"; + const scheduler = await schedulerHealthReport(sql, { now: new Date(), mode }) + .then((h) => ({ + healthy: h.healthy, + ...(h.lagSeconds !== undefined ? { lagSeconds: h.lagSeconds } : {}), + ...(h.lastTickAt + ? { secondsSinceTick: Math.max(0, (Date.now() - Date.parse(h.lastTickAt)) / 1000) } + : {}), + })) + .catch(() => undefined); + let site: SiteMetrics | undefined; + if (env.SITE && env.CLOUDHAL_PURGE_TOKEN) { + const res = await env.SITE.fetch(SITE_METRICS_URL, { + headers: { authorization: `Bearer ${env.CLOUDHAL_PURGE_TOKEN}` }, + }).catch(() => undefined); + if (res?.ok) site = (await res.json().catch(() => undefined)) as SiteMetrics | undefined; + } + return { ...(scheduler ? { scheduler } : {}), ...(site ? { site } : {}) }; +} + +/** The `/api/metrics` answer. */ +export async function metricsResponse( + request: Request, + env: MetricsEnv, + metrics: AdminMetrics = ADMIN_METRICS, +): Promise { + const token = env.CLOUDHAL_METRICS_TOKEN; + if (!token) return plain(404, "not found"); + const auth = request.headers.get("authorization") ?? ""; + if (!auth.startsWith("Bearer ") || !sameToken(auth.slice(7), token)) + return plain(401, "unauthorized", { "www-authenticate": 'Bearer realm="metrics"' }); + if (request.method !== "GET") return plain(405, "method not allowed", { allow: "GET" }); + return plain(200, metrics.text(await readNow(env, metrics)), { + "content-type": "text/plain; version=0.0.4; charset=utf-8", + }); +} + +/** `api` for a publish in Studio's API, `mcp` for the `publish` tool; undefined otherwise. */ +async function publishVia(request: Request, url: URL): Promise { + if (request.method !== "POST") return undefined; + const parts = url.pathname.split("/"); + if ( + parts.length === 7 && + parts[2] === "sites" && + parts[4] === "releases" && + parts[6] === "publish-now" + ) + return "api"; + const snapshots = parts.length === 5 && parts[2] === "sites" && parts[4] === "snapshots"; + if (!snapshots && url.pathname !== "/mcp") return undefined; + const body = (await request + .clone() + .json() + .catch(() => undefined)) as { + publish?: unknown; + method?: unknown; + params?: { name?: unknown }; + }; + if (snapshots) return body?.publish === true ? "api" : undefined; + return body?.method === "tools/call" && body.params?.name === "publish" ? "mcp" : undefined; +} + +type AnyFetch = (request: Request, env: never, ctx: ExecutionContext) => Promise; + +/** The admin Worker with `/api/metrics` and its counters around every request. */ +export function instrumentAdmin( + worker: W, + metrics: AdminMetrics = ADMIN_METRICS, +): W { + const fetch = async ( + request: Request, + env: Parameters[1] & MetricsEnv, + ctx: ExecutionContext, + ): Promise => { + const url = new URL(request.url); + if (url.pathname === METRICS_PATH) return metricsResponse(request, env, metrics); + const started = Date.now(); + const via = await publishVia(request, url); + const done = (status: number) => { + const seconds = (Date.now() - started) / 1000; + metrics.requests.record(`area="${area(url.pathname)}"`, status, seconds); + if (via) + metrics.publishes.observe( + `via="${via}",outcome="${status < 400 ? "ok" : "failed"}"`, + seconds, + ); + }; + try { + const res = await worker.fetch(request, env as never, ctx); + done(res.status); + return res; + } catch (error) { + done(500); + throw error; + } + }; + return { ...worker, fetch } as W; +} + +/** An R2 bucket whose failed operations count as store errors. */ +export function watchedBucket(bucket: R2Bucket, metrics: AdminMetrics = ADMIN_METRICS): R2Bucket { + return new Proxy(bucket, { + get(target, prop) { + const value = Reflect.get(target, prop); + if (typeof value !== "function") return value; + return (...args: unknown[]) => { + const out = (value as (...a: unknown[]) => unknown).apply(target, args); + return out instanceof Promise + ? out.catch((e: unknown) => { + metrics.storeError("r2"); + throw e; + }) + : out; + }; + }, + }); +} + +/** The admin Worker's database, its failures counted. */ +export function adminSql(env: { DB: D1Database }, metrics: AdminMetrics = ADMIN_METRICS): D1Driver { + return new D1Driver(env.DB, { onError: () => metrics.storeError("d1") }); +} diff --git a/packages/cloudflare/test/metrics.test.ts b/packages/cloudflare/test/metrics.test.ts new file mode 100644 index 00000000..0a8e70bf --- /dev/null +++ b/packages/cloudflare/test/metrics.test.ts @@ -0,0 +1,133 @@ +/** #293: `/api/metrics`, the admin Worker's Prometheus exposition of one instance. */ +import { RequestMetrics } from "@cloudhal/core-ts"; +import { describe, expect, it } from "vitest"; +import { AdminMetrics, area, instrumentAdmin, sameToken, watchedBucket } from "../src/metrics.ts"; + +const TOKEN = "metrics-token-at-least-32-characters-long"; +/** A D1 binding that fails every statement (no scheduler data). */ +const brokenDb = { + prepare: () => ({ + bind() { + return this; + }, + first: async () => { + throw new Error("D1_ERROR: no such table"); + }, + all: async () => { + throw new Error("D1_ERROR: no such table"); + }, + run: async () => { + throw new Error("D1_ERROR: no such table"); + }, + }), +} as unknown as D1Database; + +const ctx = {} as ExecutionContext; +const call = + (worker: { fetch: (r: Request, e: never, c: ExecutionContext) => Promise }) => + (path: string, env: Record, init: RequestInit = {}) => + worker.fetch(new Request(`https://studio.example${path}`, init), env as never, ctx); + +describe("/api/metrics", () => { + it("is off without a token, and answers only its holder", async () => { + const metrics = new AdminMetrics(); + const worker = instrumentAdmin({ fetch: async () => new Response("ok") }, metrics); + const get = call(worker); + expect((await get("/api/metrics", { DB: brokenDb })).status).toBe(404); + const env = { DB: brokenDb, CLOUDHAL_METRICS_TOKEN: TOKEN }; + expect((await get("/api/metrics", env)).status).toBe(401); + const wrong = await get("/api/metrics", env, { headers: { authorization: "Bearer nope" } }); + expect(wrong.status).toBe(401); + expect(wrong.headers.get("www-authenticate")).toContain("Bearer"); + const ok = await get("/api/metrics", env, { headers: { authorization: `Bearer ${TOKEN}` } }); + expect(ok.status).toBe(200); + expect(ok.headers.get("content-type")).toBe("text/plain; version=0.0.4; charset=utf-8"); + expect(ok.headers.get("cache-control")).toBe("no-store"); + expect(sameToken(TOKEN, TOKEN)).toBe(true); + expect(sameToken(`${TOKEN}x`, TOKEN)).toBe(false); + }); + + it("counts requests by area and class, publishes by how, store errors, and the site's own", async () => { + const metrics = new AdminMetrics(); + const worker = instrumentAdmin( + { + fetch: async (r: Request) => { + if (new URL(r.url).pathname === "/api/broken") throw new Error("boom"); + return new Response("ok", { status: r.method === "POST" ? 201 : 200 }); + }, + }, + metrics, + ); + const go = call(worker); + await go("/api/sites", {}); + await go( + "/mcp", + {}, + { + method: "POST", + body: JSON.stringify({ method: "tools/call", params: { name: "publish" } }), + }, + ); + await go( + "/api/sites/site_x/snapshots", + {}, + { method: "POST", body: JSON.stringify({ publish: true }) }, + ); + await go("/api/sites/site_x/snapshots", {}, { method: "POST", body: JSON.stringify({}) }); + await expect(go("/api/broken", {})).rejects.toThrow("boom"); + const site = new RequestMetrics(); + site.record("", 200, 0.02); + site.record("", 503, 0.002); + const env = { + DB: brokenDb, + CLOUDHAL_METRICS_TOKEN: TOKEN, + CLOUDHAL_PURGE_TOKEN: "purge", + SITE: { + fetch: async (_u: string, init?: RequestInit) => + new Headers(init?.headers).get("authorization") === "Bearer purge" + ? Response.json(site.toJSON()) + : new Response("no", { status: 401 }), + }, + }; + const text = await ( + await go("/api/metrics", env, { headers: { authorization: `Bearer ${TOKEN}` } }) + ).text(); + expect(text).toContain('cloudhal_http_requests_total{worker="admin",area="api",class="2xx"} 3'); + expect(text).toContain('cloudhal_http_requests_total{worker="admin",area="api",class="5xx"} 1'); + expect(text).toContain('cloudhal_http_requests_total{worker="admin",area="mcp",class="2xx"} 1'); + expect(text).toContain('cloudhal_http_requests_total{worker="site",class="2xx"} 1'); + expect(text).toContain('cloudhal_http_requests_total{worker="site",class="5xx"} 1'); + expect(text).toContain('cloudhal_http_request_duration_seconds_count{worker="site"} 2'); + expect(text).toContain( + 'cloudhal_http_request_duration_seconds_bucket{worker="site",le="0.025"} 2', + ); + expect(text).toContain('cloudhal_publish_duration_seconds_count{via="api",outcome="ok"} 1'); + expect(text).toContain('cloudhal_publish_duration_seconds_count{via="mcp",outcome="ok"} 1'); + // the scheduler could not be read: no scheduler gauges, and the failure counted + expect(text).not.toContain("cloudhal_scheduler_healthy"); + expect(text).toMatch(/cloudhal_store_errors_total\{store="d1"\} [1-9]/); + expect(text).toContain("# TYPE cloudhal_http_request_duration_seconds histogram"); + expect(text.endsWith("\n")).toBe(true); + // the scrape itself is not a request it counts + expect(text).not.toContain('area="api",class="4xx"'); + }); + + it("labels areas from a fixed set and counts failed media operations", async () => { + expect( + ["/mcp", "/api/auth/x", "/api/admin/sites", "/api/x", "/.well-known/y", "/login"].map(area), + ).toEqual(["mcp", "auth", "admin", "api", "oauth", "studio"]); + const metrics = new AdminMetrics(); + const bucket = watchedBucket( + { + get: async () => { + throw new Error("down"); + }, + head: async () => null, + } as unknown as R2Bucket, + metrics, + ); + expect(await bucket.head("k")).toBeNull(); + await expect(bucket.get("k")).rejects.toThrow("down"); + expect(metrics.text({})).toContain('cloudhal_store_errors_total{store="r2"} 1'); + }); +}); diff --git a/packages/core-ts/src/index.ts b/packages/core-ts/src/index.ts index 603d991b..1ab6acd9 100644 --- a/packages/core-ts/src/index.ts +++ b/packages/core-ts/src/index.ts @@ -114,6 +114,7 @@ export type { PublishReleaseResult, ReleasePurge, } from "./release-apply.ts"; +export * from "./request-metrics.ts"; export * from "./search.ts"; export * from "./search-ai.ts"; export * from "./search-provider.ts"; diff --git a/packages/core-ts/src/request-metrics.ts b/packages/core-ts/src/request-metrics.ts new file mode 100644 index 00000000..d3c1e3cd --- /dev/null +++ b/packages/core-ts/src/request-metrics.ts @@ -0,0 +1,61 @@ +/** + * Per-isolate request counters (#293): the admin Worker's `/api/metrics` renders them, and the + * site Worker hands its own over as JSON (`/__cloudhal/metrics`). Plain numbers only, no I/O, so + * they are safe in any Worker. Labels are preformatted Prometheus label text (`a="x",b="y"`) from + * a small fixed set; never paths, ids or users. + */ + +/** Seconds: from a cached read to a slow publish. */ +export const METRIC_BUCKETS: readonly number[] = [ + 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, +]; + +export interface MetricSeries { + buckets: number[]; + sum: number; + count: number; +} + +/** A histogram per label set (`a="x",b="y"`), in fixed buckets. */ +export class Histogram { + readonly #series = new Map(); + + observe(labels: string, seconds: number): void { + let s = this.#series.get(labels); + if (!s) { + s = { buckets: METRIC_BUCKETS.map(() => 0), sum: 0, count: 0 }; + this.#series.set(labels, s); + } + for (let i = 0; i < METRIC_BUCKETS.length; i++) + if (seconds <= (METRIC_BUCKETS[i] as number)) s.buckets[i] = (s.buckets[i] ?? 0) + 1; + s.sum += seconds; + s.count++; + } + + /** The series as JSON (the site Worker hands its own over this way). */ + toJSON(): Record { + return Object.fromEntries(this.#series); + } +} + +/** What a Worker counts about the requests it answers. */ +export class RequestMetrics { + readonly #counts = new Map(); + readonly durations = new Histogram(); + + record(labels: string, status: number, seconds: number): void { + const key = `${labels ? `${labels},` : ""}class="${Math.min(5, Math.max(1, Math.floor(status / 100)))}xx"`; + this.#counts.set(key, (this.#counts.get(key) ?? 0) + 1); + this.durations.observe(labels, seconds); + } + + toJSON(): { requests: Record; durations: Record } { + return { requests: Object.fromEntries(this.#counts), durations: this.durations.toJSON() }; + } +} + +/** The site Worker's counters, as `/__cloudhal/metrics` answers them. */ +export type SiteMetrics = ReturnType; + +/** A Worker's counters as JSON. */ +export type RequestMetricsJson = ReturnType; diff --git a/packages/storage/src/sql/d1.ts b/packages/storage/src/sql/d1.ts index 978d1440..574da4cd 100644 --- a/packages/storage/src/sql/d1.ts +++ b/packages/storage/src/sql/d1.ts @@ -12,6 +12,8 @@ import { isReadOnlySql, retryRead } from "./d1-retry.ts"; export interface D1DriverOptions { /** Waits between attempts of a read that failed in transit (`d1-retry.ts`); `[]` turns it off. */ readonly readRetryDelaysMs?: readonly number[]; + /** Told of every statement or batch that failed (after any retries): store-error metrics (#293). */ + readonly onError?: (error: unknown) => void; } /** @@ -23,14 +25,25 @@ export class D1Driver implements SqlDriver { readonly name = "d1"; readonly #db: D1Database; readonly #delays: readonly number[] | undefined; + readonly #onError: ((error: unknown) => void) | undefined; constructor(db: D1Database, options: D1DriverOptions = {}) { this.#db = db; this.#delays = options.readRetryDelaysMs; + this.#onError = options.onError; + } + + async #watch(work: () => Promise): Promise { + try { + return await work(); + } catch (error) { + this.#onError?.(error); + throw error; + } } #read(sql: string, read: () => Promise): Promise { - return isReadOnlySql(sql) ? retryRead(read, this.#delays) : read(); + return this.#watch(() => (isReadOnlySql(sql) ? retryRead(read, this.#delays) : read())); } #prepare(sql: string, params: readonly SqlValue[] = []): D1PreparedStatement { @@ -57,8 +70,8 @@ export class D1Driver implements SqlDriver { } async run(sql: string, params?: readonly SqlValue[]): Promise { - const res = await this.#prepare(sql, params).run(); - return toRunResult(res); + const statement = this.#prepare(sql, params); + return toRunResult(await this.#watch(() => statement.run())); } async batch(statements: readonly SqlStatement[]): Promise { @@ -66,7 +79,7 @@ export class D1Driver implements SqlDriver { const prepared = statements.map((s) => this.#prepare(s.sql, s.params)); let results: D1Result[]; try { - results = await this.#db.batch(prepared); + results = await this.#watch(() => this.#db.batch(prepared)); } catch (cause) { throw new StorageError(`batch failed: ${(cause as Error).message}`, cause); } @@ -74,7 +87,7 @@ export class D1Driver implements SqlDriver { } async exec(sql: string): Promise { - await this.#db.exec(sql); + await this.#watch(() => this.#db.exec(sql)); } async close(): Promise { diff --git a/packages/storage/test/d1-retry.test.ts b/packages/storage/test/d1-retry.test.ts index aceba7e9..4af67659 100644 --- a/packages/storage/test/d1-retry.test.ts +++ b/packages/storage/test/d1-retry.test.ts @@ -97,3 +97,21 @@ describe("D1 read retries (#290)", () => { expect(Date.now() - started).toBeGreaterThanOrEqual(35); }); }); + +describe("D1 error hook (#293)", () => { + it("is told of each failed statement once, after the retries, and of nothing else", async () => { + const errors: unknown[] = []; + const flaky = fakeD1(1); + const sql = new D1Driver(flaky.db, { readRetryDelaysMs: [0], onError: (e) => errors.push(e) }); + await sql.get("SELECT 1"); + expect(errors).toEqual([]); + const down = fakeD1(10); + const failing = new D1Driver(down.db, { + readRetryDelaysMs: [0], + onError: (e) => errors.push(e), + }); + await expect(failing.get("SELECT 1")).rejects.toThrow(); + await expect(failing.run("UPDATE t SET a = 1")).rejects.toThrow(); + expect(errors).toHaveLength(2); + }); +}); diff --git a/scripts/otel-smoke.ts b/scripts/otel-smoke.ts new file mode 100644 index 00000000..2c3f1392 --- /dev/null +++ b/scripts/otel-smoke.ts @@ -0,0 +1,218 @@ +/** + * Observability of the self-host image, end to end (#293). CI only: .github/workflows/docker.yml + * runs it on the candidate image, and it refuses to start outside GitHub Actions. + * + * 1. Starts SeaweedFS, the otel profile's collector (deploy/docker/otel-collector.yaml, the image + * compose.yml pins), and one instance with OTEL_EXPORTER_OTLP_ENDPOINT and + * CLOUDHAL_METRICS_TOKEN. + * 2. Requests to Studio and the site produce spans that reach the collector with + * `service.name` (the Worker), `service.instance.id` (the instance) and `service.version`. + * 3. `GET /api/metrics` answers its token holder in Prometheus text (requests of both Workers, + * the scheduler, store errors), and anyone else 401. + * + * node scripts/otel-smoke.ts --image [--port ] + */ +import { execFile } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +if (process.env.GITHUB_ACTIONS !== "true") { + console.error("otel-smoke runs in CI only (.github/workflows/docker.yml), never locally"); + process.exit(2); +} + +const arg = (name: string): string | undefined => { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? undefined : process.argv[i + 1]; +}; +const image = arg("image") ?? "cloudhal:ci"; +const port = Number(arg("port") ?? 58797); +const id = `cloudhal-otel-${process.pid}`; +const names = { store: `${id}-store`, collector: `${id}-collector`, cloudhal: `${id}-cloudhal` }; +// 127.0.0.1, never localhost (#306) +const studio = `http://127.0.0.1:${port}`; +const site = `http://127.0.0.1:${port + 1}`; +const docker_ = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker"); +const compose = readFileSync(path.join(docker_, "compose.yml"), "utf8"); +const pinned = (repo: string) => { + const at = compose.indexOf(`image: ${repo}:`); + if (at === -1) throw new Error(`compose.yml names no ${repo} image`); + return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); +}; +const STORE_IMAGE = pinned("chrislusf/seaweedfs"); +const COLLECTOR_IMAGE = pinned("otel/opentelemetry-collector-contrib"); +const metricsToken = randomBytes(24).toString("hex"); + +const run = promisify(execFile); +async function docker(args: string[], timeout = 120_000): Promise { + const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); + return stdout.trim(); +} +async function dockerLogs(name: string, tail = "2000"): Promise { + const { stdout, stderr } = await run("docker", ["logs", "--tail", tail, name], { + encoding: "utf8", + timeout: 30_000, + maxBuffer: 64 << 20, + }); + return `${stdout}${stderr}`; +} +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const step = (text: string) => console.log(`✓ ${text}`); +function expect(ok: boolean, what: string, detail?: unknown): void { + if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); +} + +const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-otel-")); +function envFile(name: string, env: Record): string { + const file = path.join(work, `${name}.env`); + writeFileSync( + file, + Object.entries(env) + .map(([k, v]) => `${k}=${v}\n`) + .join(""), + { mode: 0o600 }, + ); + return file; +} + +async function req(url: string, init: RequestInit = {}): Promise<{ status: number; text: string }> { + try { + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(20_000) }); + return { status: res.status, text: await res.text() }; + } catch (e) { + return { status: 0, text: (e as { cause?: { code?: string } }).cause?.code ?? String(e) }; + } +} +async function until(what: string, seconds: number, check: () => Promise) { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const v = await check().catch(() => undefined); + if (v !== undefined) return v; + await sleep(2000); + } + throw new Error(`${what} within ${seconds} s`); +} + +async function start(env: Record): Promise { + await docker(["network", "create", id]); + const s3 = JSON.stringify({ + identities: [ + { + name: "cloudhal", + credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], + actions: ["Admin", "Read", "Write", "List", "Tagging"], + }, + ], + }); + await docker([ + ...["run", "-d", "--name", names.store, "--network", id, "--network-alias", "seaweedfs"], + ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], + STORE_IMAGE, + "-c", + 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', + ]); + await docker([ + ...[ + "run", + "-d", + "--name", + names.collector, + "--network", + id, + "--network-alias", + "otel-collector", + ], + ...["-v", `${path.join(docker_, "otel-collector.yaml")}:/etc/otelcol-contrib/config.yaml:ro`], + COLLECTOR_IMAGE, + ]); + await docker([ + ...["run", "-d", "--name", names.cloudhal, "--network", id, "--read-only", "--tmpfs", "/tmp"], + ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], + "--env-file", + envFile("cloudhal", { + ...env, + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", + CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, + CLOUDHAL_SITE_NAME: "Otel Site", + CLOUDHAL_BASE_URL: studio, + OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318", + CLOUDHAL_METRICS_TOKEN: metricsToken, + }), + ...["-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], + image, + ]); +} + +async function main(env: Record): Promise { + await start(env); + const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; + await until("the instance did not create its site", 180, async () => { + const r = await req(`${studio}/api/admin/sites`, { headers: admin }); + return r.status === 200 && r.text.includes(env.CLOUDHAL_SITE_ID as string) ? true : undefined; + }); + for (let i = 0; i < 5; i++) { + await req(`${studio}/api/health`); + await req(`${site}/`); + } + step("an instance exporting to the otel profile's collector is up and answered requests"); + + const instance = `service.instance.id: Str(${names.cloudhal}:7000)`; + const logs = await until("no span with the instance reached the collector", 90, async () => { + const text = await dockerLogs(names.collector); + return text.includes(instance) ? text : undefined; + }); + expect(logs.includes("service.name: Str(admin)"), "a span of the admin Worker"); + expect(logs.includes("service.name: Str(site)"), "a span of the site Worker"); + expect(/service\.version: Str\(\S+\)/.test(logs), "the version on the spans"); + expect(logs.includes("service.namespace: Str(cloudhal)"), "the namespace on the spans"); + step("spans of both Workers reached the collector with the instance and the version"); + + const anonymous = await req(`${studio}/api/metrics`); + expect(anonymous.status === 401, "/api/metrics without the token", anonymous.status); + const wrong = await req(`${studio}/api/metrics`, { headers: { authorization: "Bearer nope" } }); + expect(wrong.status === 401, "/api/metrics with a wrong token", wrong.status); + const metrics = await until("/api/metrics did not show the scheduler", 90, async () => { + const r = await req(`${studio}/api/metrics`, { + headers: { authorization: `Bearer ${metricsToken}` }, + }); + return r.status === 200 && r.text.includes("cloudhal_scheduler_healthy") ? r.text : undefined; + }); + for (const line of [ + /^cloudhal_http_requests_total\{worker="admin",area="api",class="2xx"\} [1-9]/m, + /^cloudhal_http_requests_total\{worker="site",class="5xx"\} [1-9]/m, + /^cloudhal_http_request_duration_seconds_count\{worker="site"\} [1-9]/m, + /^cloudhal_store_errors_total\{store="d1"\} \d+$/m, + /^cloudhal_scheduler_healthy [01]$/m, + /^# TYPE cloudhal_publish_duration_seconds histogram$/m, + ]) + expect(line.test(metrics), `/api/metrics has ${line.source}`, metrics.slice(0, 3000)); + step("/api/metrics answers its token holder in Prometheus text, and nobody else"); + console.log("\nObservability smoke test passed."); +} + +const env = Object.fromEntries( + (await docker(["run", "--rm", image, "secrets"])) + .split("\n") + .filter((l) => l.includes("=") && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), +) as Record; +try { + await main(env); +} catch (e) { + console.error(`\n✗ ${e instanceof Error ? e.message : String(e)}`); + for (const name of Object.values(names)) { + const text = await dockerLogs(name, "150").catch((d: Error) => `error: ${d.message}`); + console.error(`--- ${name} logs\n${text.slice(-12_000)}`); + } + process.exitCode = 1; +} finally { + for (const name of Object.values(names)) + await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); + await docker(["network", "rm", id], 30_000).catch(() => undefined); + rmSync(work, { recursive: true, force: true }); +} From 527502d6140e7cc9b204f201c9e1aefc47d06af2 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:50:10 +0300 Subject: [PATCH 2/2] test(otel-smoke): read the collector's whole log and name the services seen The first run found the instance, version and namespace on the spans but read only the last 2,000 lines of the debug exporter, which workerd's own d1 spans filled; the admin and site spans were older. The smoke now reads the whole log, keeps requests flowing while it waits, wants a span of the admin and of the site Worker (their own service or its front or assets service), and names the spans seen per service.name, in the step on success and in the error on failure. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- scripts/otel-smoke.ts | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/scripts/otel-smoke.ts b/scripts/otel-smoke.ts index 2c3f1392..0fbd2311 100644 --- a/scripts/otel-smoke.ts +++ b/scripts/otel-smoke.ts @@ -60,6 +60,19 @@ async function dockerLogs(name: string, tail = "2000"): Promise { }); return `${stdout}${stderr}`; } +/** How many resource spans the debug exporter printed per `service.name`. */ +function servicesSeen(text: string): Map { + const out = new Map(); + const marker = "service.name: Str("; + for (let at = text.indexOf(marker); at !== -1; at = text.indexOf(marker, at + 1)) { + const end = text.indexOf(")", at + marker.length); + if (end === -1 || end - at > 100) continue; + const name = text.slice(at + marker.length, end); + out.set(name, (out.get(name) ?? 0) + 1); + } + out.delete("otelcol-contrib"); + return out; +} const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const step = (text: string) => console.log(`✓ ${text}`); function expect(ok: boolean, what: string, detail?: unknown): void { @@ -161,16 +174,29 @@ async function main(env: Record): Promise { } step("an instance exporting to the otel profile's collector is up and answered requests"); + // The whole log, never a tail: workerd's own Workers (d1, cron) export many spans, and the + // debug exporter prints each over dozens of lines (#343's first run read only a tail). const instance = `service.instance.id: Str(${names.cloudhal}:7000)`; - const logs = await until("no span with the instance reached the collector", 90, async () => { - const text = await dockerLogs(names.collector); - return text.includes(instance) ? text : undefined; + let seen = new Map(); + const wanted = (prefix: string) => [...seen.keys()].some((n) => n.split("-")[0] === prefix); + const logs = await until( + "no span of the admin and site Workers with the instance reached the collector", + 120, + async () => { + await req(`${studio}/api/health`); + await req(`${site}/`); + const text = await dockerLogs(names.collector, "all"); + seen = servicesSeen(text); + return text.includes(instance) && wanted("admin") && wanted("site") ? text : undefined; + }, + ).catch((e: Error) => { + throw new Error(`${e.message}; services seen: ${JSON.stringify(Object.fromEntries(seen))}`); }); - expect(logs.includes("service.name: Str(admin)"), "a span of the admin Worker"); - expect(logs.includes("service.name: Str(site)"), "a span of the site Worker"); expect(/service\.version: Str\(\S+\)/.test(logs), "the version on the spans"); expect(logs.includes("service.namespace: Str(cloudhal)"), "the namespace on the spans"); - step("spans of both Workers reached the collector with the instance and the version"); + step( + `spans reached the collector with the instance and the version, by service: ${JSON.stringify(Object.fromEntries(seen))}`, + ); const anonymous = await req(`${studio}/api/metrics`); expect(anonymous.status === 401, "/api/metrics without the token", anonymous.status);