Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions apps/api-edge/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: api-edge
description: Cloudflare Worker for the API edge Runtime
spec:
type: cloudflare-worker-turbo
lifecycle: production
owner: platform
domain: starter-runtime
path: apps/api-edge
dependsOn:
- component: cloudflare-d1
- component: cloudflare-kv
- component: projects-worker
- component: events-worker
- component: config-worker
- component: webhooks-worker
- component: billing-worker
- component: integrations-worker
- component: identity-worker
- component: membership-worker
- component: metering-worker
- component: notifications-worker
# BF6 wiring documents from orun secrets (SEC-JOB): lease-published by
# the infra components; wire-live renders the wrangler template from
# these instead of Secrets Manager documents.
secretEnv:
WIRING_CLOUDFLARE_D1_STAGE: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/stage/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_D1_PROD: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/prod/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_KV_STAGE: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/stage/WIRING_CLOUDFLARE_KV"
WIRING_CLOUDFLARE_KV_PROD: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/prod/WIRING_CLOUDFLARE_KV"

subscribe:
environments:
- name: dev
profile: verify
- name: stage
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
- name: prod
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"

workspaceDir: ../..
appDir: .

turboFilter: "@saas/api-edge"
wranglerConfig: wrangler.jsonc

# BF6 deploy-time wiring (pilot): wrangler.jsonc is rendered, never
# committed. Verify lanes render from wiring.fixture.json (offline);
# deploy lanes resolve real IDs from the Secrets Manager wiring manifest
# published by the named infra components (BF5).
wranglerTemplate: wrangler.template.jsonc
wiringComponents: "cloudflare-d1,cloudflare-kv"
wiringEnvs: "stage,prod"
wiringFixture: wiring.fixture.json
orgName: sourceplane
owner: sourceplane
repo: new-test

installCommand: pnpm install --frozen-lockfile
buildCommand: pnpm exec turbo run build --filter=@saas/api-edge
typecheckCommand: pnpm exec turbo run typecheck --filter=@saas/api-edge

dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod
deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod

preDeployCommand: "echo 'No pre-deploy step configured.'"
migrationCommand: "echo 'No migrations configured.'"
smokeCommand: "echo 'No smoke test configured.'"
labels:
team: platform
layer: runtime
surface: api
runtime: cloudflare
# ci: re-trigger deploy (batch C — integrations + api-edge gateway, 20260622T141448Z)
# ci: re-trigger deploy (batch C — integrations + api-edge gateway, 20260622T141448Z)
21 changes: 21 additions & 0 deletions apps/api-edge/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# api-edge — architecture

A `cloudflare-worker-turbo` component: TypeScript built by the turbo pipeline
from `apps/api-edge`, deployed per environment by its CI lane.

## Bindings and wiring

- **Service bindings** → `projects-worker`, `events-worker`, `config-worker`, `webhooks-worker`, `billing-worker`, `integrations-worker`, `identity-worker`, `membership-worker`, `metering-worker`, `notifications-worker` —
in-process RPC to sibling Workers; no public hops between contexts.
- **Wired configuration** (resolved at deploy time from job-output
secrets published by the infrastructure terraform; names only):
`WIRING_CLOUDFLARE_D1_STAGE`, `WIRING_CLOUDFLARE_D1_PROD`, `WIRING_CLOUDFLARE_KV_STAGE`, `WIRING_CLOUDFLARE_KV_PROD`.
- **`PLATFORM_DB`** is a D1 binding. SQLite types apply: timestamps are
ISO-8601 text, JSON is text, booleans are 0/1, and there is no
interactive transaction (see `packages/db/src/d1`).

## Boundaries

This Worker owns its bounded context: its data, its invariants, its
API surface (exposed to the fleet through the edge). Cross-context calls
go over service bindings; nothing else may reach into its storage.
24 changes: 24 additions & 0 deletions apps/api-edge/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# api-edge

Cloudflare Worker for the API edge Runtime

Part of the new-test runtime: a Cloudflare Worker deployed per environment (`stage`, `prod`; `dev` is verify-only). Not publicly routable — reached only through `api-edge` service bindings.

## Depends on

- **cloudflare-d1** — Provisions the Cloudflare D1 platform database for stage and prod
- **cloudflare-kv** — Provisions Cloudflare KV namespaces backing the api-edge idempotency replay store (stage and prod)
- **projects-worker** — Cloudflare Worker for the Projects runtime
- **events-worker** — Cloudflare Worker for the Events and Audit runtime
- **config-worker** — Cloudflare Worker for the Config read-only API surface
- **webhooks-worker** — Cloudflare Worker for webhook endpoint, subscription, and delivery-attempt management
- **billing-worker** — Cloudflare Worker for the Billing API surface (private, service-binding only)
- **integrations-worker** — Cloudflare Worker for the integrations bounded context — provider connections (GitHub App first), inbound delivery inbox, repo links, and the installation-token broker
- **identity-worker** — Cloudflare Worker for the Identity auth runtime
- **membership-worker** — Cloudflare Worker for the Membership org runtime
- **metering-worker** — Cloudflare Worker for the Metering API surface (usage recording, quota checks)
- **notifications-worker** — Cloudflare Worker for the Notifications bounded context

## Depended on by

- **web-console-next** — Next.js 15 + opennextjs/cloudflare delivery of the new-test web console (per-environment, Workers + Static Assets)
32 changes: 32 additions & 0 deletions apps/api-edge/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# api-edge — runbook

## How it deploys

Merges to `main` converge automatically: CI plans changed components
(`orun plan --changed`) and runs this component's lane via
`orun run --remote-state` with credential-free OIDC auth. The convergence
run is the deployment; the DAG orders this component after everything it
depends on. Failed lanes resume with `gh run rerun --failed`.

## Rollback

Revert the offending commit on `main`; the next convergence applies the
previous desired state. There is no out-of-band mutation to undo — the
repo is the source of truth.

## Verify

The deploy lane's own verify/smoke is the gate. End-to-end behavior is
exercised through `api-edge` (this Worker has no public URL).

## Common failures

- **Missing `WIRING_*` secret at deploy**: the infrastructure terraform
upstream has not applied — check that lane first; within one
convergence run the DAG guarantees order.
- **Service-binding target missing (Cloudflare 10143)**: the target
Worker does not exist yet on this account — converge the fleet before
this lane (the bootstrap's two-pass landing handles first boot).
- **Smoke fails right after a first deploy**: a brand-new workers.dev
route can 4xx for a few seconds; the lane already retries — persistent
failure means a real regression.
2 changes: 2 additions & 0 deletions apps/api-edge/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import config from "../../tooling/eslint/index.js";
export default config;
26 changes: 26 additions & 0 deletions apps/api-edge/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "@saas/api-edge",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"build": "wrangler deploy --dry-run --outdir dist",
"deploy": "wrangler deploy",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"verify-bindings": "node scripts/verify-bindings.mjs",
"wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20250508.0",
"@saas/eslint-config": "workspace:*",
"@saas/tsconfig": "workspace:*",
"typescript": "^5.8.3",
"wrangler": "^4.14.4"
},
"dependencies": {
"@saas/contracts": "workspace:*",
"@saas/db": "workspace:*"
}
}
177 changes: 177 additions & 0 deletions apps/api-edge/scripts/verify-bindings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));

function stripJsoncComments(text) {
return text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
}

// BF6: resource IDs are never committed — wrangler.jsonc is rendered from
// wrangler.template.jsonc, so this checks the rendered shape (valid 32-hex,
// stage and prod distinct), not literal account IDs.
const EXPECTED_D1 = {
stage: { binding: "PLATFORM_DB" },
prod: { binding: "PLATFORM_DB" },
};

// A D1 database id is a UUID; the offline wiring fixture uses the 32-hex form.
const D1_ID_PATTERN =
/^[0-9a-f]{32}$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const seenD1Ids = new Map();

const EXPECTED_KV = {
stage: {
binding: "IDEMPOTENCY_KV",
},
prod: {
binding: "IDEMPOTENCY_KV",
},
};

const KV_ID_PATTERN = /^[0-9a-f]{32}$/;
const KV_ID_SENTINELS = new Set([
"0000000000000000000000000000000a",
"0000000000000000000000000000000b",
]);

// Service-binding targets carry the worker prefix the whole fleet ships with
// (`<brand>-<worker>-<env>`). The brand is NOT hardcoded: it is read from this
// worker's own `name`, so a rebranded fork verifies its own names instead of
// the baseline's. (Hardcoding it here is exactly what made this check pass in
// the baseline and fail in every fork.)
const EXPECTED_SERVICE_BINDINGS = [
{ binding: "IDENTITY_WORKER", worker: "identity-worker" },
{ binding: "MEMBERSHIP_WORKER", worker: "membership-worker" },
{ binding: "PROJECTS_WORKER", worker: "projects-worker" },
];

const configPath = resolve(__dirname, "../wrangler.jsonc");
const raw = readFileSync(configPath, "utf-8");
const config = JSON.parse(stripJsoncComments(raw));

let failures = 0;

for (const [envName, expected] of Object.entries(EXPECTED_D1)) {
const envBlock = config.env?.[envName];
if (!envBlock) {
console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`);
failures++;
continue;
}

const db = envBlock.d1_databases?.find((d) => d.binding === expected.binding);
if (!db) {
console.error(
`FAIL: [${envName}] missing d1_databases binding "${expected.binding}"`
);
failures++;
continue;
}

if (typeof db.database_id !== "string" || !D1_ID_PATTERN.test(db.database_id)) {
console.error(
`FAIL: [${envName}] binding "${expected.binding}" database_id "${db.database_id}" is not a D1 id`
);
failures++;
continue;
}

seenD1Ids.set(envName, db.database_id);

const envVar = envBlock.vars?.ENVIRONMENT;
if (envVar !== envName) {
console.error(
`FAIL: [${envName}] ENVIRONMENT var mismatch: got "${envVar}", want "${envName}"`
);
failures++;
continue;
}

console.log(`OK: [${envName}] PLATFORM_DB → ${db.database_id}`);
}

if (seenD1Ids.has("stage") && seenD1Ids.get("stage") === seenD1Ids.get("prod")) {
console.error(
`FAIL: stage and prod share the same D1 database id "${seenD1Ids.get("stage")}" — ` +
`one environment is bound to the other's data`
);
failures++;
}

for (const [envName, expected] of Object.entries(EXPECTED_KV)) {
const envBlock = config.env?.[envName];
if (!envBlock) {
console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`);
failures++;
continue;
}

const kv = envBlock.kv_namespaces?.find((k) => k.binding === expected.binding);
if (!kv) {
console.error(
`FAIL: [${envName}] missing kv_namespaces binding "${expected.binding}"`
);
failures++;
continue;
}

if (typeof kv.id !== "string" || !KV_ID_PATTERN.test(kv.id)) {
console.error(
`FAIL: [${envName}] kv binding "${expected.binding}" id "${kv.id}" does not match /^[0-9a-f]{32}$/`
);
failures++;
continue;
}

if (KV_ID_SENTINELS.has(kv.id)) {
console.error(
`FAIL: [${envName}] kv binding "${expected.binding}" still uses sentinel id "${kv.id}" — replace with the real Cloudflare KV namespace id`
);
failures++;
continue;
}

console.log(`OK: [${envName}] ${expected.binding} → ${kv.id}`);
}

// `name` is `<brand>-api-edge`; everything before the last "-api-edge" is the
// brand prefix the fleet shares.
const brandPrefix = String(config.name ?? "").replace(/api-edge$/, "");

for (const envName of ["stage", "prod"]) {
const envBlock = config.env?.[envName];
if (!envBlock) {
console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`);
failures++;
continue;
}

for (const expected of EXPECTED_SERVICE_BINDINGS) {
const want = `${brandPrefix}${expected.worker}-${envName}`;
const svc = envBlock.services?.find((s) => s.binding === expected.binding);
if (!svc) {
console.error(
`FAIL: [${envName}] missing service binding "${expected.binding}"`
);
failures++;
continue;
}
if (svc.service !== want) {
console.error(
`FAIL: [${envName}] service binding "${expected.binding}" target mismatch: got "${svc.service}", want "${want}"`
);
failures++;
continue;
}
console.log(`OK: [${envName}] ${expected.binding} → ${svc.service}`);
}
}

if (failures > 0) {
console.error(`\n${failures} binding verification failure(s)`);
process.exit(1);
} else {
console.log("\nAll binding verifications passed.");
}
Loading
Loading