Skip to content

Commit 282b9fc

Browse files
committed
Serve published WordPress routes without coordination
1 parent 52ecc5f commit 282b9fc

6 files changed

Lines changed: 286 additions & 19 deletions

File tree

packages/runtime-cloudflare/README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@ This candidate integration for [wp-codebox#1838](https://github.com/Automattic/w
44

55
## Runtime Architecture
66

7-
The entry Worker executes PHP-WASM and WordPress. The named `WordPressStateCoordinator` Durable Object remains lightweight: it serializes a bounded lease and atomically promotes the current canonical R2 pointer with token, base-revision, and version checks. It never imports or instantiates PHP-WASM. State reads query the coordinator directly; every request that can observe canonical WordPress state acquires a lease first.
7+
The entry Worker executes PHP-WASM and WordPress. The named `WordPressStateCoordinator` Durable Object remains lightweight: it serializes a bounded lease and atomically promotes the current canonical R2 pointer with token, base-revision, and version checks. It never imports or instantiates PHP-WASM. Dynamic state reads query the coordinator directly; explicitly published anonymous routes use the separate reader path described below.
88

99
On cold start, the entry Worker uses the acquired pointer to rebuild PHP-WASM's disposable SQLite index from canonical MDI Markdown and JSON files. A missing pointer materializes the packaged canonical MDI seed and boots one PHP-WASM primary runtime. The build-time PHP CLI generator creates that archive from `wordpress-install-seed.sqlite` through MDI's public `bootstrap_existing_cache()` API, validates its pinned MDI revision and input digest, and never packages SQLite. The runtime updates `siteurl` and `home` through WordPress APIs using the request origin and sets the admin password from `WORDPRESS_ADMIN_PASSWORD`; only WordPress's password hash is canonical. Bootstrap persists and CAS-promotes this mutation before serving the next request.
1010

1111
Canonical browser, health, and mutation boots require the separately managed `WORDPRESS_AUTH_SECRET` Worker secret. The entry Worker derives the eight WordPress auth keys and salts from that secret with a versioned, site-scoped (`default`) SHA-256 domain separator before `wp-load.php`. It never logs, persists, or returns the secret or derived values. Configure it independently from the bootstrap password with `wrangler secret put WORDPRESS_AUTH_SECRET --config packages/runtime-cloudflare/wrangler.jsonc`; rotating `WORDPRESS_ADMIN_PASSWORD` does not rotate authentication salts or invalidate sessions.
1212

1313
After each mutating HTTP request, the entry runtime invokes MDI's explicit request-boundary flush, collects canonical files, stores immutable content-addressed R2 objects and a revision manifest, then commits the new pointer through the held lease. GET, HEAD, and asset requests release without promotion. Failed requests abort their leases; stale leases recover by token/version/expiry checks. The entry isolate can cache one runtime only for the exact acquired pointer revision and exits it after promotion or when another isolate advances the pointer. It does not persist SQLite. Existing manifests are reused when canonical file hashes have not changed.
1414

15+
Anonymous HTML responses are stored as create-once, host-independent R2 artifacts under their canonical revision. An authorized `POST ?phase=operator-publish` promotes a bounded, sorted set of already-rendered routes by writing an immutable publication descriptor and then replacing one strongly consistent `sites/default/publications/current.json` pointer. Published GET and HEAD requests check a 60-second edge entry and then the R2 publication before constructing the Durable Object stub; authenticated, preview, admin, REST, and unpublished routes continue through WordPress. Promotion rejects missing, stale, duplicate, malformed, or conflicting artifacts. This is the coordinator-free reader boundary, not yet a complete route compiler or global CDN purge pipeline.
16+
1517
The same revision transaction persists bounded user-managed files under `wp-content/plugins`, `themes`, `languages`, and `mu-plugins`. Runtime-owned MDI, SQLite integration, and Codebox adapter files remain reconstructable artifacts and are excluded. Unchanged bundled-theme files are omitted by release hash, while modified files become canonical overrides. Public canonical plugin and theme assets serve directly from revision-addressed R2 cache entries before the immutable release corpus. Nonce-protected `wp-admin` GET actions such as plugin activation are classified as mutations so their filesystem and MDI option changes commit atomically. Existing revisions without `wpContent` remain valid.
1618

1719
The Worker forwards browser cookies directly to Playground and disables Playground's internal cookie store, preventing an empty per-isolate store from replacing a valid browser session after cold restart.
@@ -29,6 +31,6 @@ Canonical Cloudflare boots patch only the assembled PHP MEMFS copy of `/wordpres
2931
2. Run `npm run provision:cloudflare-wordpress-runtime-corpus -- --local --persist-to <directory>` to verify and upload all exact content-addressed artifacts into isolated local R2 storage. For an authorized deployment, run the provisioner with `--remote` and require every upload to succeed before deploying the Worker that imports their manifests.
3032
3. Run `npm run test:cloudflare-runtime` for routing, canonical-state, artifact validation, source contract, and TypeScript coverage.
3133
4. Run `npm run cloudflare:dry-run` to compile the Worker without creating Cloudflare resources.
32-
5. Run `npm run cloudflare:local-gate` for isolated local workerd evidence. It generates and provisions all artifacts before workerd starts, then injects stable test-only admin-password and auth-secret values, uploads and activates a real plugin ZIP, verifies that plugin's REST route before and after Worker restart, and covers login, authenticated REST publication, media, public rendering, representative frontend/admin/editor assets, PHP diagnostics, session recovery, and a fresh login after restart.
34+
5. Run `npm run cloudflare:local-gate` for isolated local workerd evidence. It generates and provisions all artifacts before workerd starts, then injects stable test-only admin-password, auth-secret, and operator-token values, uploads and activates a real plugin ZIP, promotes anonymous homepage and canonical-permalink artifacts, and proves an R2 publication read after Worker restart. It also covers login, authenticated REST publication, media, representative frontend/admin/editor assets, PHP diagnostics, session recovery, and a fresh login after restart.
3335

3436
This document describes local candidate verification only. It does not claim remote deployment.
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
export const PUBLISHED_REVISION_SCHEMA = "wp-codebox/published-revision/v1" as const
2+
export const PUBLISHED_PAGE_SCHEMA = "wp-codebox/wordpress-page/v2" as const
3+
export const R2_PUBLISHED_CURRENT_KEY = "sites/default/publications/current.json"
4+
export const R2_PUBLISHED_REVISION_PREFIX = "sites/default/publications/revisions"
5+
export const MAX_PUBLISHED_ROUTES = 1_000
6+
export const MAX_PUBLISHED_REVISION_BYTES = 512 * 1024
7+
export const MAX_PUBLISHED_PAGE_BYTES = 8 * 1024 * 1024
8+
9+
export interface PublishedRoute {
10+
route: string
11+
objectKey: string
12+
}
13+
14+
export interface PublishedRevision {
15+
schema: typeof PUBLISHED_REVISION_SCHEMA
16+
revision: string
17+
canonicalRevision: string
18+
publishedAt: string
19+
routes: PublishedRoute[]
20+
}
21+
22+
export function canonicalPublicRoute(input: Request | URL | string): string {
23+
const url = input instanceof Request ? new URL(input.url) : input instanceof URL ? new URL(input) : new URL(input, "https://wp-codebox-runtime.invalid")
24+
url.searchParams.sort()
25+
return `${url.pathname}${url.search}`
26+
}
27+
28+
export async function publishedPageObjectKey(canonicalRevision: string, route: string): Promise<string> {
29+
if (!isRevision(canonicalRevision) || !isCanonicalRoute(route)) throw new Error("Published page identity is invalid.")
30+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(route))
31+
const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
32+
return `sites/default/pages/${canonicalRevision}/${hash}.json`
33+
}
34+
35+
export function publishedRevisionObjectKey(revision: string): string {
36+
if (!isRevision(revision)) throw new Error("Published revision identity is invalid.")
37+
return `${R2_PUBLISHED_REVISION_PREFIX}/${revision}.json`
38+
}
39+
40+
export function validatePublishedRevision(value: unknown): PublishedRevision {
41+
if (!value || typeof value !== "object") throw new Error("Published revision is invalid.")
42+
const revision = value as Partial<PublishedRevision>
43+
if (revision.schema !== PUBLISHED_REVISION_SCHEMA || !isRevision(revision.revision) || !isRevision(revision.canonicalRevision)
44+
|| typeof revision.publishedAt !== "string" || !Number.isFinite(Date.parse(revision.publishedAt)) || !Array.isArray(revision.routes)
45+
|| revision.routes.length === 0 || revision.routes.length > MAX_PUBLISHED_ROUTES) throw new Error("Published revision is invalid.")
46+
let previous = ""
47+
for (const route of revision.routes) {
48+
if (!route || typeof route !== "object" || !isCanonicalRoute(route.route) || route.route <= previous
49+
|| route.objectKey !== `sites/default/pages/${revision.canonicalRevision}/${route.objectKey.split("/").at(-1)}`
50+
|| !/^sites\/default\/pages\/[a-f0-9-]{36}\/[a-f0-9]{64}\.json$/.test(route.objectKey)) throw new Error("Published revision route is invalid.")
51+
previous = route.route
52+
}
53+
return revision as PublishedRevision
54+
}
55+
56+
export function normalizePublishedRoutes(value: unknown): string[] {
57+
if (!Array.isArray(value) || value.length === 0 || value.length > MAX_PUBLISHED_ROUTES) throw new Error("Publication requires a bounded routes array.")
58+
const routes = value.map((route) => {
59+
if (typeof route !== "string" || !route.startsWith("/")) throw new Error("Publication route is invalid.")
60+
return canonicalPublicRoute(route)
61+
}).sort()
62+
if (routes.some((route, index) => index > 0 && route === routes[index - 1])) throw new Error("Publication routes must be unique.")
63+
return routes
64+
}
65+
66+
function isCanonicalRoute(route: string): boolean {
67+
if (!route.startsWith("/") || route.includes("#") || route.includes("\\") || route.length > 2_048) return false
68+
try {
69+
return canonicalPublicRoute(route) === route
70+
} catch {
71+
return false
72+
}
73+
}
74+
75+
function isRevision(revision: unknown): revision is string {
76+
return typeof revision === "string" && /^[a-f0-9-]{36}$/.test(revision)
77+
}

packages/runtime-cloudflare/src/request-routing.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export type WorkerRequestRoute =
55
| { kind: "r2-mutate" }
66
| { kind: "operator-reset" }
77
| { kind: "operator-restore" }
8+
| { kind: "operator-publish" }
89
| { kind: "probe"; phase: string }
910

1011
export function routeWorkerRequest(request: Request): WorkerRequestRoute {
@@ -15,5 +16,6 @@ export function routeWorkerRequest(request: Request): WorkerRequestRoute {
1516
if (phase === "r2-mutate") return { kind: "r2-mutate" }
1617
if (phase === "operator-reset") return { kind: "operator-reset" }
1718
if (phase === "operator-restore") return { kind: "operator-restore" }
19+
if (phase === "operator-publish") return { kind: "operator-publish" }
1820
return { kind: "probe", phase }
1921
}

0 commit comments

Comments
 (0)