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
2 changes: 1 addition & 1 deletion apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Nothing to set for the data path: the monitor state lives in the D1 database
# bound as DB in wrangler.jsonc (the committed fixture render — wrangler keeps
# a local SQLite behind it; `pnpm db:init:local` creates the table there — and,
# a local SQLite behind it; `pnpm db:migrate:local` applies the migrations there — and,
# on deploy, rendered from the cloudflare-d1 root's wiring document).
2 changes: 1 addition & 1 deletion apps/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ checker (`monitor/`, upstream's `worker/src`) on the Worker's Cron Trigger.

```bash
pnpm run wire:fixture # render wrangler.jsonc from the fixture (committed)
pnpm db:init:local # create the monitor_state table in wrangler's local D1
pnpm db:migrate:local # apply packages/db's migrations to wrangler's local D1
pnpm build # next build + opennextjs-cloudflare build
pnpm exec wrangler dev --test-scheduled
curl 'http://localhost:8787/__scheduled?cron=*+*+*+*+*' # run the checker once
Expand Down
17 changes: 13 additions & 4 deletions apps/web/component.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,26 @@ spec:
lane: isolated
# INFRA BEFORE APP. The Worker binds the D1 database by id, and the id is
# rendered into its config during the build from the wiring document the
# cloudflare-d1 root lease-publishes after its apply. A job resolves its
# secrets when it STARTS, so on a merge to main this deploy waits for that
# environment's apply (enforced) and the document is there; a pull request
# deploys nothing, so nothing on one waits (advisory).
# cloudflare-d1 root lease-publishes after its apply; and the checker writes
# and the page reads the `monitor_state` table, which db-migrate creates in
# that database. A job resolves its secrets when it STARTS, so on a merge to
# main this deploy waits for both (enforced) — one convergence runs
# cloudflare-d1 → db-migrate → web per environment, and the document and the
# schema are there. A pull request deploys nothing, so nothing on one waits
# (advisory).
dependsOn:
- component: cloudflare-d1
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
- component: db-migrate
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request
secretEnv:
WIRING_CLOUDFLARE_D1_STAGE: "secret://uptimeflare/uptimeflare/stage/WIRING_CLOUDFLARE_D1"
WIRING_CLOUDFLARE_D1_PROD: "secret://uptimeflare/uptimeflare/prod/WIRING_CLOUDFLARE_D1"
Expand Down
6 changes: 0 additions & 6 deletions apps/web/init.sql

This file was deleted.

2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && opennextjs-cloudflare populateCache local",
"start": "next start -p 3000",
"preview": "opennextjs-cloudflare preview",
"db:init:local": "wrangler d1 execute DB --local --config wrangler.jsonc --file init.sql",
"db:migrate:local": "node ../../tooling/migrations/local.mjs",
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json --env stage"
Expand Down
69 changes: 69 additions & 0 deletions infra/db-migrate/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: db-migrate
description: Applies the monitor state's schema (packages/db's migrations) to the stage and prod Cloudflare D1 databases
labels:
domain: infra
scope: database
team: platform
layer: data

spec:
type: db-migrate
lifecycle: production
owner: platform
domain: infra

# THE SCHEMA BETWEEN THE DATABASE AND THE APP. Migrations target the
# database the `cloudflare-d1` component creates, and find it through the
# wiring document that component lease-publishes after its apply — and a
# job resolves its secrets when it STARTS, so on a merge to main this waits
# for that environment's apply (enforced). apps/web waits on this the same
# way, so one convergence runs cloudflare-d1 → db-migrate → web per
# environment. A pull request applies nothing (this plans offline there), so
# nothing on one waits (advisory). `db` is the package this builds and runs;
# a change to it re-plans this.
dependsOn:
- component: db
- component: cloudflare-d1
mode: enforced
modeRules:
- mode: advisory
when:
triggerRef: github-pull-request

path: packages/db/src/migrations

parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"
owner: sourceplane
repo: uptimeflare

# Everything the runner needs to reach D1 over the REST API, all resolved
# from orun secrets: the provider credential is minted fresh per run from the
# Cloudflare integration's d1-edit template (the workers-deploy token cannot
# touch D1), the account id is a non-secret connection fact, and the
# database id arrives in the wiring document the cloudflare-d1 component
# lease-publishes.
secretEnv:
CLOUDFLARE_API_TOKEN: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_D1_TOKEN"
CLOUDFLARE_ACCOUNT_ID: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"
WIRING_CLOUDFLARE_D1: "secret://uptimeflare/uptimeflare/{{ .environment }}/WIRING_CLOUDFLARE_D1"

subscribe:
environments:
- name: stage
profile: plan
profileRules:
- profile: apply
when:
triggerRef: github-push-main

- name: prod
profile: plan
profileRules:
- profile: apply
when:
triggerRef: github-push-main
53 changes: 53 additions & 0 deletions infra/terraform/cloudflare-d1/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
apiVersion: sourceplane.io/v1
kind: Component

metadata:
name: cloudflare-d1
description: Provisions the Cloudflare D1 database the monitor state lives in, for stage and prod
labels:
domain: infra
scope: runtime-database

spec:
type: terraform
lifecycle: production
owner: platform
domain: infra

parameters:
orgName: sourceplane
stackName: cloudflare-d1
terraformDir: terraform
terraformVersion: "1.15.3"
repo: uptimeflare
# SEC-JOB: the wiring document (database id/name) is lease-published
# post-apply; worker deploys read it back as WIRING_CLOUDFLARE_D1_<ENV>,
# and db-migrate reads it to find the database it migrates.
secretOutputs: "WIRING_CLOUDFLARE_D1=wiring"

# The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN
# env var, resolved by orun from the project-rung brokered secret — minted
# fresh per run from the d1-edit template (D1 Write; the workers-deploy token
# deliberately cannot touch D1). Declared at component level because
# plan-only lanes refresh against the live Cloudflare API too, not just apply.
secretEnv:
CLOUDFLARE_API_TOKEN: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_D1_TOKEN"
# Non-secret connection fact (account-id template).
CLOUDFLARE_ACCOUNT_ID: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"
TF_VAR_cloudflare_account_id: "secret://uptimeflare/uptimeflare/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"

subscribe:
environments:
- name: stage
profile: plan-only
profileRules:
- profile: apply
when:
triggerRef: github-push-main

- name: prod
profile: plan-only
profileRules:
- profile: apply
when:
triggerRef: github-push-main
43 changes: 43 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/adopt.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# --- Self-healing adoption ---
#
# When the platform state does not yet track the database but Cloudflare
# already has one under this name (a re-bootstrap after a torn-down workspace,
# or state recovered onto a fresh backend), the create would collide with the
# duplicate-name guard. Instead: look the database up at plan time with the
# job's brokered credentials and import it. Fresh products resolve to id = ""
# and create normally, and a resource already tracked in state short-circuits
# the lookup — so this block is inert everywhere except the one case it exists
# for. Both lookups run inside the job: process env carries the brokered
# CLOUDFLARE_API_TOKEN/CLOUDFLARE_ACCOUNT_ID and the TF_HTTP_* state
# credentials, so no extra secrets are needed.

data "external" "adopt_platform_database" {
program = ["bash", "-c", <<-EOT
set -euo pipefail
name="$(jq -r .name)"
state_file="$(mktemp)"
trap 'rm -f "$state_file"' EXIT
code="$(curl -s -o "$state_file" -w '%%{http_code}' \
-u "$TF_HTTP_USERNAME:$TF_HTTP_PASSWORD" "$TF_HTTP_ADDRESS" || echo 000)"
if [ "$code" = "200" ] && jq -e \
'[.resources[]? | select(.type == "cloudflare_d1_database" and .name == "platform")] | length > 0' \
"$state_file" >/dev/null 2>&1; then
jq -n '{id: ""}'
exit 0
fi
resp="$(curl -fsS --retry 3 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
"https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/d1/database?per_page=100")"
printf '%s' "$resp" | jq -c --arg n "$name" \
'{id: ([.result[] | select(.name == $n) | .uuid] | first // "")}'
EOT
]
query = {
name = local.database_name
}
}

import {
for_each = toset(compact([data.external.adopt_platform_database.result.id]))
to = cloudflare_d1_database.platform
id = "${var.cloudflare_account_id}/${each.value}"
}
5 changes: 5 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/backend.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Terraform backend configuration is provided by Orun at runtime
# through environment variables and automatic backend initialization.
#
# S3 backend details are set via CLI args in the Orun runner.
# Local placeholder file for clarity.
138 changes: 138 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
terraform {
required_version = ">= 1.15.0"

# State lives on the platform (SB1): the runner exports TF_HTTP_* per job, so
# this block stays empty — no S3 bucket, no AWS role, no workspaces.
backend "http" {}

required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 4.30"
}
external = {
source = "hashicorp/external"
version = "~> 2.3"
}
}
}

# --- Providers ---

# Authenticates via the CLOUDFLARE_API_TOKEN env var (provider-native): the
# token is an orun-managed secret resolved into the job env at run time, so it
# never transits Terraform variables.
provider "cloudflare" {}

# --- Variables (standard Orun parameters) ---

variable "cloudflare_account_id" {
type = string
sensitive = true
default = ""
description = "Cloudflare account ID (from CLOUDFLARE_ACCOUNT_ID env var)"
}

variable "orgName" {
type = string
default = "sourceplane"
}

variable "owner" {
type = string
default = "sourceplane"
}

variable "repo" {
type = string
default = "uptimeflare"
}

variable "namespace" {
type = string
default = "sourceplane"
}

variable "namespacePrefix" {
type = string
default = ""
}

variable "lane" {
type = string
default = "verify"
}

variable "environment" {
type = string
default = "stage"
}

variable "component" {
type = string
default = "cloudflare-d1"
}

variable "stackName" {
type = string
default = "cloudflare-d1"
}

variable "terraformDir" {
type = string
default = "terraform"
}

variable "terraformVersion" {
type = string
default = "1.15.3"
}

# --- The monitor state's database ---
#
# One D1 database per deployed environment (stage, prod), bound by apps/web as
# DB. Its schema is not Terraform's: packages/db's migrations create the
# `monitor_state` table, applied by the db-migrate component after this apply and
# before the Worker deploys.

locals {
# Built on var.repo (the product's repository slug) so the name is unique per
# product. D1 database names are unique per account, and two products may
# share an account. The Worker binds this database by ID through the wiring
# secret, so the name is free to change.
database_name = "${var.namespacePrefix}${var.repo}-${var.environment}"
}

resource "cloudflare_d1_database" "platform" {
account_id = var.cloudflare_account_id
name = local.database_name
}

# --- Wiring manifest (BF5, via orun secrets) ---
#
# The consumable outputs are published by the composition's wire-secrets step
# as the WIRING_CLOUDFLARE_D1 secret on the project/{{env}} rung; worker
# deploys read it back as WIRING_CLOUDFLARE_D1_<ENV> secretEnv and render the
# committed @@wiring(...)@@ tokens from it (BF6). The `db-migrate` component
# reads the same document (WIRING_CLOUDFLARE_D1) to find the database it
# migrates.

output "wiring" {
description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)"
value = jsonencode({
d1_database_id = cloudflare_d1_database.platform.id
d1_database_name = cloudflare_d1_database.platform.name
})
}

# --- Outputs (non-secret) ---

output "d1_database_id" {
description = "Cloudflare D1 database ID (the Workers binding's database_id)"
value = cloudflare_d1_database.platform.id
}

output "d1_database_name" {
description = "Cloudflare D1 database name (human-readable identifier)"
value = cloudflare_d1_database.platform.name
}
2 changes: 2 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/outputs.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Output definitions are in main.tf for simplicity.
# This file is a placeholder for consistency with the Orun Terraform pattern.
2 changes: 2 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/variables.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Variable definitions are in main.tf for simplicity.
# This file is a placeholder for consistency with the Orun Terraform pattern.
Loading
Loading