diff --git a/apps/bot/component.yaml b/apps/bot/component.yaml index 7fb3fdb..b7e1d6b 100644 --- a/apps/bot/component.yaml +++ b/apps/bot/component.yaml @@ -27,6 +27,20 @@ spec: change: inputs: - packages/** + # INFRA BEFORE APP. The Worker binds the KV namespace by id, and the id is + # rendered into its config during the build from the wiring document the + # cloudflare-kv root lease-publishes after its apply. A job resolves its + # secrets when it STARTS, so on a merge to main this deploy waits for the + # apply (enforced) — one convergence runs cloudflare-kv → bot per + # environment, and the document is there. A pull request deploys nothing, + # so nothing on one waits (advisory). + dependsOn: + - component: cloudflare-kv + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # The KV namespace's wiring document, per environment: the cloudflare-kv # root lease-publishes it after its apply, and the build renders the # namespace id into wrangler.jsonc from it. diff --git a/apps/bot/docs/overview.md b/apps/bot/docs/overview.md index 09d2c2a..4e31c7b 100644 --- a/apps/bot/docs/overview.md +++ b/apps/bot/docs/overview.md @@ -13,7 +13,7 @@ A Cloudflare Worker, deployed per environment by its CI lane. ## Depends on -- (none) +- **cloudflare-kv** — Provisions the Cloudflare KV namespace the bot binds as DATABASE (stage and prod) ## Depended on by diff --git a/infra/terraform/cloudflare-kv/component.yaml b/infra/terraform/cloudflare-kv/component.yaml new file mode 100644 index 0000000..416c789 --- /dev/null +++ b/infra/terraform/cloudflare-kv/component.yaml @@ -0,0 +1,59 @@ +apiVersion: sourceplane.io/v1 +kind: Component + +metadata: + name: cloudflare-kv + description: Provisions the Cloudflare KV namespace the bot binds as DATABASE (stage and prod) + labels: + domain: infra + scope: app-kv + +spec: + type: terraform + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + domain: infra + + parameters: + orgName: sourceplane + stackName: cloudflare-kv + terraformDir: terraform + terraformVersion: "1.15.3" + # SEC-JOB: the wiring document (KV namespace id/title) is lease-published + # post-apply; app deploys read it back as WIRING_CLOUDFLARE_KV_. + secretOutputs: "WIRING_CLOUDFLARE_KV=wiring" + + # The Cloudflare Terraform provider authenticates via the CLOUDFLARE_API_TOKEN + # env var, resolved by orun from the project-rung brokered secret (fresh per + # run, Deploy Workers scope). Declared at component level because plan-only + # lanes refresh against the live Cloudflare API too, not just apply. + secretEnv: + CLOUDFLARE_API_TOKEN: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/CLOUDFLARE_API_TOKEN" + # Non-secret connection fact (account-id template) — replaces the ambient + # CLOUDFLARE_ACCOUNT_ID / TF_VAR_cloudflare_account_id CI values. + CLOUDFLARE_ACCOUNT_ID: "secret://telegram-ai-bot/telegram-ai-bot/{{ .environment }}/CLOUDFLARE_ACCOUNT_ID" + TF_VAR_cloudflare_account_id: "secret://telegram-ai-bot/telegram-ai-bot/{{ .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 diff --git a/infra/terraform/cloudflare-kv/docs/architecture.md b/infra/terraform/cloudflare-kv/docs/architecture.md new file mode 100644 index 0000000..0726cce --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/architecture.md @@ -0,0 +1,29 @@ +# cloudflare-kv — architecture + +A `terraform` root at `infra/terraform/cloudflare-kv/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `cloudflare_workers_kv_namespace.app_kv` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +| ---------------------- | ---------------- | +| `WIRING_CLOUDFLARE_KV` | `wiring` | + +## Resolved at run time (names only) + +- `CLOUDFLARE_ACCOUNT_ID` +- `CLOUDFLARE_API_TOKEN` +- `TF_VAR_cloudflare_account_id` diff --git a/infra/terraform/cloudflare-kv/docs/overview.md b/infra/terraform/cloudflare-kv/docs/overview.md new file mode 100644 index 0000000..0cad598 --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/overview.md @@ -0,0 +1,19 @@ +# cloudflare-kv + +Provisions the Cloudflare KV namespace the bot binds as DATABASE (stage and prod) + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-kv` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **bot** — The Telegram bot (upstream's Workers entry over its libraries, one plain Cloudflare Worker per environment) diff --git a/infra/terraform/cloudflare-kv/docs/runbook.md b/infra/terraform/cloudflare-kv/docs/runbook.md new file mode 100644 index 0000000..b5db692 --- /dev/null +++ b/infra/terraform/cloudflare-kv/docs/runbook.md @@ -0,0 +1,20 @@ +# cloudflare-kv — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. diff --git a/infra/terraform/cloudflare-kv/terraform/adopt.tf b/infra/terraform/cloudflare-kv/terraform/adopt.tf new file mode 100644 index 0000000..7c1fbba --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/adopt.tf @@ -0,0 +1,43 @@ +# --- Self-healing adoption (AWS-free state seeding) --- +# +# When the platform state does not yet track the namespace but Cloudflare +# already has one under this title (a baseline whose state predates the +# platform backend, or a recovered workspace), the create would collide with +# the duplicate-title guard (error 10014). Instead: look the namespace 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 and no AWS access. + +data "external" "adopt_app_kv" { + program = ["bash", "-c", <<-EOT + set -euo pipefail + title="$(jq -r .title)" + 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_workers_kv_namespace" and .name == "app_kv")] | 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/storage/kv/namespaces?per_page=100")" + printf '%s' "$resp" | jq -c --arg t "$title" \ + '{id: ([.result[] | select(.title == $t) | .id] | first // "")}' + EOT + ] + query = { + title = local.app_kv_title + } +} + +import { + for_each = toset(compact([data.external.adopt_app_kv.result.id])) + to = cloudflare_workers_kv_namespace.app_kv + id = "${var.cloudflare_account_id}/${each.value}" +} diff --git a/infra/terraform/cloudflare-kv/terraform/backend.tf b/infra/terraform/cloudflare-kv/terraform/backend.tf new file mode 100644 index 0000000..ff89f5f --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/backend.tf @@ -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. diff --git a/infra/terraform/cloudflare-kv/terraform/main.tf b/infra/terraform/cloudflare-kv/terraform/main.tf new file mode 100644 index 0000000..8f51831 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/main.tf @@ -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 = "telegram-ai-bot" +} + +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-kv" +} + +variable "stackName" { + type = string + default = "cloudflare-kv" +} + +variable "terraformDir" { + type = string + default = "terraform" +} + +variable "terraformVersion" { + type = string + default = "1.15.3" +} + +# --- The KV namespace the bot keeps everything in --- +# +# Bound by apps/bot as DATABASE (upstream's binding name): the global +# configuration (`config:global` — providers, settings, plugins, custom +# commands, saved from /admin) and each chat's history and state. Keys are +# the bot's; any expiry is per-PUT (`expirationTtl`), owned by the Worker — no +# Terraform-side TTL knob exists for KV namespaces themselves. + +locals { + # Built on var.repo (the product's repository slug) so the title is unique per + # product. Cloudflare KV namespace titles must be unique per account, and two + # products may share an account — without the slug the second create fails + # with "a namespace with this account ID and title already exists" (10014). + # The Worker binds this namespace by ID via the wiring secret, so the title is + # free to change. + app_kv_title = "${var.namespacePrefix}${var.repo}-app-kv-${var.environment}" +} + +resource "cloudflare_workers_kv_namespace" "app_kv" { + account_id = var.cloudflare_account_id + title = local.app_kv_title +} + +# --- Wiring manifest (BF5, via orun secrets) --- +# The consumable outputs are published by the composition's wire-secrets step +# as the WIRING_CLOUDFLARE_KV secret on the project/{{env}} rung; worker +# deploys read it back as WIRING_CLOUDFLARE_KV_ secretEnv (BF6). Same +# document shape the Secrets Manager path carried. + +output "wiring" { + description = "Wiring document for downstream deploy-time binding resolution (pushed to orun secrets)" + value = jsonencode({ + app_kv_id = cloudflare_workers_kv_namespace.app_kv.id + app_kv_title = cloudflare_workers_kv_namespace.app_kv.title + }) +} + +# --- Outputs (non-secret) --- + +output "app_kv_id" { + description = "Cloudflare Workers KV namespace ID the bot keeps its configuration and chats in" + value = cloudflare_workers_kv_namespace.app_kv.id +} + +output "app_kv_title" { + description = "Cloudflare Workers KV namespace title (human-readable identifier)" + value = cloudflare_workers_kv_namespace.app_kv.title +} diff --git a/infra/terraform/cloudflare-kv/terraform/outputs.tf b/infra/terraform/cloudflare-kv/terraform/outputs.tf new file mode 100644 index 0000000..9653334 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/outputs.tf @@ -0,0 +1,2 @@ +# Output definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/infra/terraform/cloudflare-kv/terraform/variables.tf b/infra/terraform/cloudflare-kv/terraform/variables.tf new file mode 100644 index 0000000..9c92c69 --- /dev/null +++ b/infra/terraform/cloudflare-kv/terraform/variables.tf @@ -0,0 +1,2 @@ +# Variable definitions are in main.tf for simplicity. +# This file is a placeholder for consistency with the Orun Terraform pattern. diff --git a/specs/epics/README.md b/specs/epics/README.md index 107cfff..7c13e86 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`telegram-ai-bot/`](./telegram-ai-bot/) | **TB** | In progress (TB1) | TBXark's ChatGPT-Telegram-Workers — a multi-model Telegram bot with a Telegram Mini-App admin — on one Cloudflare Worker, Workers AI its keyless default model and its settings and history in Workers KV, and an Orun baseline that instantiates it in one landing (TB4) | +| [`telegram-ai-bot/`](./telegram-ai-bot/) | **TB** | In progress (TB2) | TBXark's ChatGPT-Telegram-Workers — a multi-model Telegram bot with a Telegram Mini-App admin — on one Cloudflare Worker, Workers AI its keyless default model and its settings and history in Workers KV, and an Orun baseline that instantiates it in one landing (TB4) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/telegram-ai-bot/IMPLEMENTATION-STATUS.md b/specs/epics/telegram-ai-bot/IMPLEMENTATION-STATUS.md index 2b72274..2092d38 100644 --- a/specs/epics/telegram-ai-bot/IMPLEMENTATION-STATUS.md +++ b/specs/epics/telegram-ai-bot/IMPLEMENTATION-STATUS.md @@ -3,8 +3,8 @@ | Milestone | State | Landed | |---|---|---| | TB0 — the spec | ✅ | TB-1 (#1) | -| TB1 — the bot on Workers | ✅ | TB-2 | -| TB2 — the KV namespace from Terraform | planned | TB-3 | +| TB1 — the bot on Workers | ✅ | TB-2 (#2) | +| TB2 — the KV namespace from Terraform | ✅ | TB-3 | | TB3 — ready to instantiate | planned | TB-4 | | TB4 — a baseline | planned | TB-5 | @@ -29,3 +29,4 @@ Upstream: TBXark/ChatGPT-Telegram-Workers v1.10.7 at `0d152e5`. | Webhook binding | the owner opens `/init` and presses bind | also `POST /init/bind`, authenticated by the token, which the deploy's smoke calls | a deploy with a token comes up bound | | `/health` | — | added | the deploy's smoke and the bootstrap's probe | | `wrangler dev` | remote Workers AI by default | `dev` (with an account) and `dev:local` (`--local`, no account) | a local run without a Cloudflare login | +| KV namespace | "Deploy to Cloudflare" creates it; CLI deploys fill its id in by hand | `infra/terraform/cloudflare-kv` per environment (`-app-kv-`), adopting one of the same title; its id rendered into the Worker's config from the wiring document, the deploy waiting on the apply | provisioned and ordered by the product's own plan | diff --git a/specs/epics/telegram-ai-bot/README.md b/specs/epics/telegram-ai-bot/README.md index 3035047..e543a61 100644 --- a/specs/epics/telegram-ai-bot/README.md +++ b/specs/epics/telegram-ai-bot/README.md @@ -13,7 +13,7 @@ the baseline makes a copy of it somebody else's in one landing.** | | | |---|---| -| Status | In progress — TB0 and TB1 on main | +| Status | In progress — TB0–TB2 on main | | Upstream | [TBXark/ChatGPT-Telegram-Workers](https://github.com/TBXark/ChatGPT-Telegram-Workers) (MIT), v1.10.7 at `0d152e5` (2026-09-15) | | Reference | [hono-api](https://github.com/sourceplane/hono-api) — a plain Worker on the `cloudflare-worker-turbo` composition and its bootstrap; [kv-redis-starter](https://github.com/sourceplane/kv-redis-starter) — a KV root and its wiring; [rag-chatbot](https://github.com/sourceplane/rag-chatbot) — Workers AI as the keyless default | | Key | `TB` |