Skip to content

Latest commit

 

History

History
213 lines (151 loc) · 17 KB

OPERATIONS.md

File metadata and controls

213 lines (151 loc) · 17 KB

Operations

Selfie has three deployments, the site and the app in Cloudflare account 0a95e814ccf2b6a95d2dc3bea0a4a2b4:

What Where Source Deployed by
The landing page selfie.dev, Pages project selfie-landing site/ .github/workflows/site.yml, on every push to main that touches site/
The npm package @diffplug/selfie on npm cli/, store/, render/, ui/ .github/workflows/npm-release.yml, on a vX.Y.Z tag
The app app.selfie.dev, Worker selfie-app, with built Storybooks on selfieusercontent.com and a redirect from hackathon.selfie.dev ui/, store/ .github/workflows/app-production.yml, run by hand, then tagged app/YYYY-MM-DD

lib.selfie.dev, kdoc.selfie.dev, and pydoc.selfie.dev belong to the earlier library (diffplug/selfie-lib), on their own Pages projects. Never move them here.

The app keeps its data in three places:

  • D1: one database per project, selfie-project-<repository id>, bound in ui/wrangler.toml. A project sets up its own schema on first use.
  • R2: bucket selfie-blobs, one prefix per project (docs/specs/store.md → R2 adapter). A project's D1 lists the images it holds, so never delete their bytes without their rows (docs/specs/store.md → Storage).
  • Postgres on Neon: sign-in only, through pgstencil, reached by the Worker through an uncached Hyperdrive. Its schema is @pgstencil/auth's migrations, listed in ui/pgstencil.json.

Releasing

  • The site: merge to main. The workflow tests the site locally, publishes site/public/, and tests https://selfie.dev.

  • The npm package: on a branch, move what's under ## [Unreleased] in CHANGELOG.md into a new ## [X.Y.Z] - YYYY-MM-DD below it, and merge that pull request. Then, as an admin, tag the merge commit and push the tag, which runs npm release:

    git fetch origin && git tag -a vX.Y.Z -m "@diffplug/selfie X.Y.Z" origin/main && git push origin vX.Y.Z

    What it checks before it stages the package is docs/specs/cli.md → Package. It only stages it, so to publish, approve it with your 2FA: on the package's page on npmjs.com, or with npm stage list @diffplug/selfie and npm stage approve <stage-id>. A failed run publishes nothing: fix it, delete the tag (git push origin :vX.Y.Z, as an admin), and tag again. To build the package on a laptop instead, pnpm build:ui && pnpm npm-package <version> <dir>.

  • The app: every push to main that touches the app runs its tests. To release, run App production release from the Actions tab on main, or gh workflow run app-production.yml --ref main. It checks the Hyperdrive, the Worker's secrets, and that no bucket has a public URL, applies sign-in's migrations, deploys, and then checks the live origins with ui/scripts/production.mjs smoke. When they pass, it tags the commit it deployed (docs/specs/cloud.md → Releases). If only the tag job failed, rerun it alone, and it makes the same tag. Migrations are append-only and run before the new Worker serves, so the Worker that's live during a release must work with the new schema.

From a laptop, the same steps are node ui/scripts/production.mjs preflight|deploy|smoke, with the environment the workflow sets.

Resetting a project store

A release that changes the store's schema version (docs/specs/renders.md → Schema) changes both D1 and the CLI's SQLite schema, and a store at another version is refused until it's reset. Version 1 held hashes, SHAs, and batch IDs as bytes, and made every table STRICT. Version 2 replaced rejections with undoing an approval, as decisions.undone. To keep published batches and approvals, use a machine that still has their local store and the previous CLI.

  1. Take the old Worker offline. Run the SQL below on each project D1 database, then deploy the new Worker. The reset discards batch history, decisions, the names they share, and image and built Storybook metadata. The Worker recreates the tables on first use. The image and Storybook bytes in R2 can be reused.
  2. Once the new Worker is serving, use the previous CLI and its intact local store to run selfie push <batch-id> for each finished, clean batch you want to republish. Use credentials with decision permission to include decisions. A push made before the D1 reset would be erased by step 1.
  3. After those pushes succeed, stop local Selfie processes and run the same SQL on each affected $SELFIE_HOME/<slug>/store.db (default ~/.config/selfie/<slug>/store.db). Then use the upgraded CLI. To restore published decisions reachable from HEAD, run selfie pull. Run selfie review to record a fresh local batch. If all old batch history is disposable, skip step 2.
DROP TABLE IF EXISTS decisions;
DROP TABLE IF EXISTS renders;
DROP TABLE IF EXISTS commit_parents;
DROP TABLE IF EXISTS render_batches;
DROP TABLE IF EXISTS commits;
DROP TABLE IF EXISTS images;
DROP TABLE IF EXISTS built_storybooks;
DROP TABLE IF EXISTS environments;
DROP TABLE IF EXISTS stories;
DROP TABLE IF EXISTS actors;
DROP TABLE IF EXISTS schema_version;
DROP TABLE IF EXISTS note_messages;
DROP TABLE IF EXISTS note_waiters;
DROP TABLE IF EXISTS note_sessions;
DROP TABLE IF EXISTS notes;

The notes tables only matter locally, where no CLI reads them any more, and D1 never had them. The table reset preserves render_keys, whose old batch IDs may refer to discarded batches. Deleting the whole store.db also deletes the render keys.

Deleting R2's diff images

Once, after the app is deployed from a main that includes #120. Until then, each project in R2 holds a diff image and a PixelDiff for every pair a push sent, at projects/<repository id>/diffs/<current>/<golden>.png and .json, which no Worker since reads or writes. Each pair's record is at projects/<repository id>/derived/, and stays. No D1 row refers to anything under diffs/, so its bytes go alone.

  1. Check that nothing live reads it. The newest app/YYYY-MM-DD tag must include #120, and the code it deployed must name no diffs/ key:

    git fetch origin --tags
    tag=$(git tag --list 'app/*' --sort=-creatordate | head -1)
    git merge-base --is-ancestor "$(gh pr view 120 --json mergeCommit -q .mergeCommit.oid)" "$tag" && echo "includes it"
    git grep -n '"diffs/\|`diffs/' "$tag" -- store/src ui/src

    The last command prints nothing. A selfie push from 0.1.0 still asks for diffs/needed, which answers not-found, so it writes nothing there either.

  2. Signed in to Wrangler as an account admin (pnpm --dir ui exec wrangler login), since the deploy token only reads R2, add a rule for each project that expires everything under its diffs/:

    for id in $(pnpm --dir ui exec wrangler d1 list --json | jq -r '.[].name | select(startswith("selfie-project-")) | ltrimstr("selfie-project-")'); do
      pnpm --dir ui exec wrangler r2 bucket lifecycle add selfie-blobs "delete-diffs-$id" "projects/$id/diffs/" --expire-days 1 --force
    done

    The trailing / keeps each rule to diffs/, and away from derived/ and the images. R2 applies a rule within a day or so of adding it.

  3. Once R2 → selfie-blobs → Objects in the dashboard shows nothing under any projects/<id>/diffs/, remove the rules, so none outlives its reason: wrangler r2 bucket lifecycle list selfie-blobs names them, and pnpm --dir ui exec wrangler r2 bucket lifecycle remove selfie-blobs --name delete-diffs-<id> removes each.

Setting up the npm package

Done once:

  1. On npmjs.com, the diffplug organization holds the package. npm only lets a package that exists trust a workflow, so publish the first version by hand: build it as above, then npm login and npm publish --access public in that directory.
  2. In the package's settings on npmjs.com, add a trusted publisher: GitHub Actions, diffplug/selfie, workflow npm-release.yml, environment npm-production, with neither Allow npm publish nor Allow npm dist-tag, so it can only stage.
  3. Create the GitHub environment npm-production, limited to tags matching v*.

Setting up release tags

Done once. Only an admin may create, move, or delete a tag, except that the selfie-tagger App may create app/ tags.

  1. Create a GitHub App in the diffplug organization named selfie-tagger, with no webhook and only Contents: Read and write on repositories, install it on diffplug/selfie alone, and generate a private key.

  2. Create the GitHub environment app-release-tag, with the App's values in Secrets and settings. Keep the key in the password manager, and delete the downloaded file.

  3. Set the tag rulesets to these, where admin is the repository role 5, and <APP_ID> is the App's numeric App ID, on its settings page:

    Ruleset Tags Refuses Except to
    Tag operations all but refs/tags/app/** creation, update, deletion an admin
    App tag creation refs/tags/app/** creation an admin, and selfie-tagger
    App tag history refs/tags/app/** update, deletion an admin

    Tag operations exists already, as ruleset 27667494. With gh:

    gh api -X PUT repos/diffplug/selfie/rulesets/27667494 --input - <<< '{"conditions":{"ref_name":{"include":["~ALL"],"exclude":["refs/tags/app/**"]}},"rules":[{"type":"creation"},{"type":"update"},{"type":"deletion"}]}'
    gh api -X POST repos/diffplug/selfie/rulesets --input - <<< '{"name":"App tag creation","target":"tag","enforcement":"active","conditions":{"ref_name":{"include":["refs/tags/app/**"],"exclude":[]}},"rules":[{"type":"creation"}],"bypass_actors":[{"actor_type":"RepositoryRole","actor_id":5,"bypass_mode":"exempt"},{"actor_type":"Integration","actor_id":<APP_ID>,"bypass_mode":"always"}]}'
    gh api -X POST repos/diffplug/selfie/rulesets --input - <<< '{"name":"App tag history","target":"tag","enforcement":"active","conditions":{"ref_name":{"include":["refs/tags/app/**"],"exclude":[]}},"rules":[{"type":"update"},{"type":"deletion"}],"bypass_actors":[{"actor_type":"RepositoryRole","actor_id":5,"bypass_mode":"exempt"}]}'

Logs

selfie-app keeps what it logs in Workers Logs ([observability] in ui/wrangler.toml), for 3 days on the Workers Free plan and 7 on Paid: in the dashboard, Workers & Pages → selfie-app → Logs. It doesn't keep a line for every request, only what the code logs, which is mostly errors.

Every error a person sees comes with an error code, such as Error code: 7K3MQ9XP, and its log line starts Error 7K3MQ9XP:. To find it, search the logs for the code. A server error's line has the error and its stack. To watch live instead, pnpm --dir ui exec wrangler tail selfie-app.

Secrets and settings

GitHub environment app-production, limited to the main branch:

Name Kind What
CLOUDFLARE_API_TOKEN secret The deploy token, below
DATABASE_URL secret The Neon migration role's direct URL (not the pooler, and not Hyperdrive)
HYPERDRIVE_ID variable The Hyperdrive the Worker reaches Postgres through

GitHub environment app-release-tag, limited to the main branch, which only the tag job of app-production.yml enters:

Name Kind What
TAGGER_CLIENT_ID variable The selfie-tagger App's Client ID
TAGGER_PRIVATE_KEY secret The selfie-tagger App's private key

GitHub environment site-production, limited to the main branch:

Name Kind What
CLOUDFLARE_PAGES_TOKEN secret The Pages token, below

Repository-wide:

Name Kind What
CLOUDFLARE_ACCOUNT_ID variable 0a95e814ccf2b6a95d2dc3bea0a4a2b4
SELFIE_UPLOAD_TOKEN secret What this repository's own CI uploads with, as on every repository the app hosts

The two Cloudflare tokens are kept nowhere else. To rotate one, create a token with the same permissions, set it with pbpaste | gh secret set <NAME> --env <environment>, and delete the old one. Every repository-wide secret is listed in tend's secrets.allowed in .config/tend.yaml, and uvx tend@latest check flags any other.

The deploy token holds exactly: Workers Scripts Edit, Account Settings Read, Hyperdrive Read, D1 Read, and Workers R2 Storage Read on the account, and Workers Routes Edit, DNS Edit, and Zone Read on selfie.dev and selfieusercontent.com. The Pages token holds Pages Edit on the account, and nothing else.

Worker secrets on selfie-app, set with pnpm --dir ui exec wrangler secret put <NAME>, which preflight checks are all there. Cloudflare can't show them again, so keep each in the password manager:

Name What
AUTH_SECRET 32 or more random characters, for pgstencil's cookies and keys; changing it signs everyone out
GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET The GitHub App's OAuth client, for signing in
GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY The GitHub App itself, for commit statuses and checking that a pushed commit is on GitHub
SELFIE_UPLOAD_TOKEN CI's bearer token: uploads, and can't decide anything
SELFIE_WRITER_TOKEN The writer's bearer token, for SELFIE_TOKEN in their own selfie push, pull, and approve

Setting up from nothing

Done once, in this order.

1. GitHub

  1. Rename diffplug/selfie-hackathon to diffplug/selfie. GitHub then redirects the old name, and the Worker answers it too (docs/specs/cloud.md → Projects). Update local checkouts with git remote set-url origin https://github.com/diffplug/selfie, and point other repositories' workflows at diffplug/selfie/.github/actions/selfie@main.

  2. In the GitHub App's settings (Selfie.dev, github.com/apps/selfie-dev, App ID 5607634; "Selfie" alone is reserved by GitHub), then under Identifying and authorizing users:

    • set the Callback URL to exactly https://app.selfie.dev/api/auth/callback/github
    • leave Request user authorization (OAuth) during installation off
    • generate a client secret; it and the app's Client ID are GITHUB_CLIENT_SECRET and GITHUB_CLIENT_ID

    Its permissions are statuses: write, contents: read, and Pull requests: Read-only on repositories, Email addresses: Read-only on accounts, and no webhook. A permission added later takes effect only once each installation's owner accepts it, under the organization's Settings → GitHub Apps → Selfie.dev; until then, a project's page lists no pull requests. Without the email permission, GitHub refuses pgstencil's read of /user/emails, and every sign-in fails with a 500.

  3. Create the app-production and site-production environments, each limited to main, and set the secrets and variables above.

2. Neon

  1. Create a project selfie on PostgreSQL 18, with a database selfie, and turn on point-in-time restore. Keep it apart from Dormouse's.

  2. Its owner role is the migration role: put its direct URL in DATABASE_URL, then apply the schema once: DATABASE_URL=… pnpm --dir ui db:migrate, and db:validate.

  3. Create the runtime role, selfie_app, with only the DML sign-in's tables need, by ui/scripts/runtime-role.mjs as the owner. It runs SQL over the encrypted connection, since Neon's console would give the role neon_superuser. It takes both values from the environment, and running it again sets a new password:

    DATABASE_URL=… SELFIE_APP_PASSWORD="$(openssl rand -hex 24)" node ui/scripts/runtime-role.mjs

3. Cloudflare

  1. Add selfieusercontent.com as a zone, and point its registrar's nameservers at Cloudflare.

  2. Create the R2 bucket, with its r2.dev access left off (docs/specs/access.md → Who can do what): pnpm --dir ui exec wrangler r2 bucket create selfie-blobs --location wnam.

  3. Create the Hyperdrive as selfie_app, with caching off, since a sign-out must be seen at once:

    pnpm --dir ui exec wrangler hyperdrive create selfie-auth --caching-disabled --connection-string='postgres://selfie_app:…@<neon host>/selfie?sslmode=require'

    Use Neon's direct host, not its -pooler one, since Hyperdrive pools. Its ID is HYPERDRIVE_ID. ui/wrangler.toml keeps a placeholder, which deploy replaces.

  4. Set every Worker secret above on selfie-app. Copy GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY, and SELFIE_UPLOAD_TOKEN from the hackathon's Worker's entries in the password manager. Generate AUTH_SECRET and SELFIE_WRITER_TOKEN fresh, with openssl rand -hex 32.

  5. Create the two API tokens above.

4. Moving off the hackathon's Worker

The hackathon's Worker, selfie-hackathon, holds hackathon.selfie.dev as a custom domain, and selfie-app claims it.

  1. In the dashboard, remove hackathon.selfie.dev from selfie-hackathon's domains. The old URL is down until the next step finishes.
  2. Run App production release. Its smoke checks cover the new origins, the redirect, and starting a sign-in.
  3. Sign in at https://app.selfie.dev/sign-in, and check a project page says you can approve.
  4. Push a commit, and check its selfie status links to app.selfie.dev.
  5. Delete the selfie-hackathon Worker, but not its D1 databases, which are selfie-app's now.