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
52 changes: 52 additions & 0 deletions infra/terraform/cloudflare-d1/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
apiVersion: sourceplane.io/v1
kind: Component

metadata:
name: cloudflare-d1
description: Provisions the Cloudflare D1 platform database 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"
# 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://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_D1_TOKEN"
# Non-secret connection fact (account-id template).
CLOUDFLARE_ACCOUNT_ID: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID"
TF_VAR_cloudflare_account_id: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/{{ .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
14 changes: 14 additions & 0 deletions infra/terraform/cloudflare-d1/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# cloudflare-d1 — architecture

A `terraform` component rooted at `infra/terraform/cloudflare-d1/terraform`.

- **State** lives in the platform's HTTP state backend (run-token auth) —
no local state, no cloud-vendor state buckets.
- **Credentials are brokered per run** from the workspace's Cloudflare
connection; no long-lived provider secrets exist anywhere in CI.
- **Outputs are published as job-output secrets** on the environment
rungs: `WIRING_CLOUDFLARE_D1` (database id/name for deploy-time binding). Downstream deploy lanes resolve them by name.
- **Self-healing adoption** (`adopt.tf`): when the platform state is
empty but the resource already exists at the provider, plan-time import
adopts it instead of failing with "already exists" — safe re-bootstrap
over half-torn-down attempts.
16 changes: 16 additions & 0 deletions infra/terraform/cloudflare-d1/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# cloudflare-d1

Provisions the Cloudflare D1 platform database for stage and prod

Terraform-managed infrastructure for new-test, per environment (`stage`, `prod`; `dev` is verify-only and provisions nothing).

## Depends on

- (none)

## Depended on by

- **admin-worker** — Internal Cloudflare Worker for audited support/administration diagnostics
- **api-edge** — Cloudflare Worker for the API edge Runtime
- **db-migrate** — Applies database migrations to the stage and prod Cloudflare D1 databases
- **identity-worker** — Cloudflare Worker for the Identity auth runtime
35 changes: 35 additions & 0 deletions infra/terraform/cloudflare-d1/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# cloudflare-d1 — 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

```bash
# published outputs (names only, per environment)
orun secrets list --org <ws> --env stage
orun secrets list --org <ws> --env prod
```

## Common failures

- **"Resource already exists" with empty platform state**: adoption
(`adopt.tf`) imports at plan time; if a root lacks adoption the
resource must be state-migrated or deleted.
- **Provider auth failure**: the workspace's Cloudflare connection is
missing or revoked — reconnect it in the console; secrets are brokered
from it per run.
- **`Authentication error (10000)` on a D1 resource**: the lane resolved
the `workers-deploy` token, which deliberately cannot touch D1 — bind
`CLOUDFLARE_D1_TOKEN` (the `d1-edit` template) instead.
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.
143 changes: 143 additions & 0 deletions infra/terraform/cloudflare-d1/terraform/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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 = "new-test"
}

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 platform database ---
#
# One D1 database per environment holds every bounded context's tables. They
# are separated by name prefix (`identity_users`, `membership_organizations`,
# …) rather than by Postgres schema, because SQLite has no schemas — the
# bounded-context boundary is enforced in the repositories, as it always was.
#
# Why one database and not one per context: D1 offers no cross-database query
# or foreign key, and the console's read paths join across contexts (an org's
# members and their user records, an invoice and its subscription). Splitting
# would move those joins into the workers, which is a much larger change than
# the isolation is worth at this size.

locals {
# Brand-namespaced with var.repo so the name is unique to this fork. D1
# database names are unique per account, and a fork may share an account with
# the baseline. Workers resolve the 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 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