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
100 changes: 100 additions & 0 deletions .github/scripts/d1-migrations.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Emits the setup-route migrations for a TABLE_PREFIX as JSON, for
// d1-prefixed-migrations.sh. The migrations come straight from
// apps/worker/src/lib/migrations.ts (loaded via Node's TypeScript type
// stripping), so the deploy workflow and POST /setup can never drift apart.
//
// node d1-migrations.mjs <prefix>
// -> { "historyTable": "_SL_schema_migrations",
// "migrations": [{ "name": "schema_v1", "sql": "<migration + history row>" }, ...] }
//
// The production D1 database is shared with other applications, so every
// statement is checked before anything is emitted: only additive statements
// (CREATE TABLE/INDEX IF NOT EXISTS, ALTER TABLE ... ADD, INSERT INTO) are
// allowed, and each must target a table carrying this app's prefix. Anything
// else aborts the deploy.

import {
createMigrationsTableSql,
getMigrations,
migrationsTable,
} from '../../apps/worker/src/lib/migrations.ts';

const prefix = process.argv[2] ?? '';
if (!/^[A-Za-z0-9_]+$/.test(prefix)) {
console.error(
`Invalid table prefix ${JSON.stringify(prefix)}: expected [A-Za-z0-9_]+`,
);
process.exit(1);
}

const ownTable = (name) => name.startsWith(`${prefix}_`);

// Statement shapes allowed in a migration; the capture group is the table
// written to. Quoted identifiers deliberately do not match.
const ALLOWED = [
/^CREATE TABLE IF NOT EXISTS (\w+) ?\(/i,
/^CREATE INDEX IF NOT EXISTS \w+ ON (\w+) ?\(/i,
/^ALTER TABLE (\w+) ADD (?:COLUMN )?\w+ /i,
/^INSERT OR IGNORE INTO (\w+) ?\(/i,
];

function statements(sql) {
return sql
.replace(/'(?:[^']|'')*'/g, "''") // string literals can't hide SQL
.replace(/--[^\n]*/g, '')
.split(';')
.map((s) => s.replace(/\s+/g, ' ').trim())
.filter(Boolean);
}

function check(migration) {
if (!/^schema_v\d+$/.test(migration.name)) {
throw new Error(`unexpected migration name ${migration.name}`);
}
for (const stmt of statements(migration.sql)) {
const match = ALLOWED.map((re) => stmt.match(re)).find(Boolean);
if (!match) {
throw new Error(
`${migration.name}: statement is not additive: ${stmt.slice(0, 120)}`,
);
}
const touched = [
match[1],
...Array.from(stmt.matchAll(/REFERENCES (\w+)/gi), (m) => m[1]),
];
const foreign = touched.filter((t) => !ownTable(t));
if (foreign.length > 0) {
throw new Error(
`${migration.name}: references table(s) without prefix "${prefix}_": ${foreign.join(', ')}`,
);
}
}
}

try {
const historyTable = migrationsTable(prefix);
const migrations = getMigrations(prefix);
const names = migrations.map((m) => m.name);
if (new Set(names).size !== names.length) {
throw new Error(`duplicate migration names: ${names.join(', ')}`);
}
for (const m of migrations) check(m);

// Same history table and row format as POST /setup. The history row goes in
// the same request, after the DDL: D1 stops at the first failing statement,
// so a migration is never recorded without having run.
const out = migrations.map((m) => ({
name: m.name,
sql: [
`${createMigrationsTableSql(prefix)};`,
m.sql.trim(),
`INSERT INTO ${historyTable} (name) VALUES ('${m.name}');`,
].join('\n'),
}));
process.stdout.write(
`${JSON.stringify({ historyTable, migrations: out }, null, 2)}\n`,
);
} catch (err) {
console.error(`Refusing to emit migrations: ${err.message}`);
process.exit(1);
}
136 changes: 136 additions & 0 deletions .github/scripts/d1-prefixed-migrations.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#!/usr/bin/env bash
# Applies the setup-route migrations (apps/worker/src/lib/migrations.ts) to a
# D1 database whose tables carry TABLE_PREFIX. Runs before the new code is
# deployed, so migrations must stay additive (expand → deploy → contract).
# Applied migrations are recorded in `_<prefix>_schema_migrations`, exactly
# like POST /setup does, so both paths stay interchangeable.
# Run from apps/worker (needs wrangler.toml with real IDs injected).
#
# The production database is shared with other applications, hence:
# - d1-migrations.mjs rejects any statement that is not additive or that
# targets a table without this app's prefix;
# - every deployed Worker version must use the same TABLE_PREFIX, so a
# mistyped GitHub variable can't migrate another app's tables;
# - prefixed tables without a migration history are never touched.
#
# D1_LOCATION=local targets the local D1 database instead (for testing this
# script); the deployed-Worker check is skipped then.
set -euo pipefail

prefix="${TABLE_PREFIX:-}"
location="${D1_LOCATION:-remote}"
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if ! [[ "$prefix" =~ ^[A-Za-z0-9_]+$ ]]; then
echo "::error::TABLE_PREFIX must be set and may only contain letters, digits and underscores (got '$prefix')."
exit 1
fi
if [[ "$location" != remote && "$location" != local ]]; then
echo "::error::D1_LOCATION must be 'remote' or 'local', got '$location'"
exit 1
fi

d1_query() {
pnpm exec wrangler d1 execute DB "--$location" --json --command "$1" |
jq -r '.[0].results[] | .name'
}

# Fails (and so aborts the deploy) if any migration is not additive or touches
# a table outside this app's prefix.
plan="$(node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON "$here/d1-migrations.mjs" "$prefix")"
history="$(jq -r '.historyTable' <<<"$plan")"
known=()
while IFS= read -r name; do
known+=("$name")
done < <(jq -r '.migrations[].name' <<<"$plan")

tables="$(d1_query "SELECT name FROM sqlite_master WHERE type = 'table'")"
# SQLite identifiers are case-insensitive, so match the prefix the same way.
own_tables="$(grep -i "^${prefix}_" <<<"$tables" || true)"
has_history=false
if grep -qixF "$history" <<<"$tables"; then
has_history=true
fi

if [[ "$location" == remote ]]; then
err="$(mktemp)"
trap 'rm -f "$err"' EXIT
if status="$(pnpm exec wrangler deployments status --json 2>"$err")"; then
versions="$(jq -er '.versions | select(length > 0) | .[].version_id | strings | select(length > 0)' <<<"$status")"
if [[ -z "$versions" ]]; then
echo "::error::No active Worker versions returned; refusing to migrate."
exit 1
fi
for version in $versions; do
live="$(bash "$here/worker-table-prefix.sh" "$version")"
live="${live//[^A-Za-z0-9_]/}"
if [[ "$live" != "$prefix" ]]; then
echo "::error::Deployed Worker version $version uses TABLE_PREFIX='$live', but the GitHub variable is '$prefix'. Make them match before deploying; refusing to migrate."
exit 1
fi
done
echo "Deployed Worker uses TABLE_PREFIX=$prefix (version(s): $(tr '\n' ' ' <<<"$versions"))."
elif [[ "$has_history" == false && -z "$own_tables" ]]; then
cat "$err" >&2
echo "::warning::Could not read the deployed Worker (first deploy?). The database has no ${prefix}_ tables yet, so creating them is safe."
else
cat "$err" >&2
echo "::error::Could not read the deployed Worker's TABLE_PREFIX to confirm which tables belong to this app; refusing to migrate existing ${prefix}_ tables."
exit 1
fi
fi

if [[ "$has_history" == true ]]; then
applied="$(d1_query "SELECT name FROM $history ORDER BY applied_at, name")"
elif [[ -n "$own_tables" ]]; then
echo "::error::Found ${prefix}_ tables but no $history table: $(tr '\n' ' ' <<<"$own_tables")"
echo "::error::They may belong to another application or predate the migration history; refusing to migrate. Record the applied migrations in $history first."
exit 1
else
applied=""
echo "No ${prefix}_ tables yet — fresh install."
fi

# Don't guess a baseline for existing tables, even if the history table exists
# but is empty. Replaying v1 could silently record a partial or foreign schema.
if [[ -n "$own_tables" ]] && ! grep -qxF schema_v1 <<<"$applied"; then
echo "::error::Existing ${prefix}_ tables have no schema_v1 record in $history; refusing to baseline or replay migrations."
exit 1
fi

pending=()
for name in "${known[@]}"; do
if ! grep -qxF "$name" <<<"$applied"; then
pending+=("$name")
fi
done
while IFS= read -r name; do
if [[ -n "$name" ]] && ! printf '%s\n' "${known[@]}" | grep -qxF "$name"; then
echo "::warning::$history records '$name', which this commit does not know (deploying older code?). Ignoring it."
fi
done <<<"$applied"

echo "Migration history ($history, $location): $(tr '\n' ' ' <<<"${applied:-<none>}")"
if [[ ${#pending[@]} -eq 0 ]]; then
echo "Planned migrations: none — schema is up to date."
exit 0
fi
echo "Planned migrations: ${pending[*]}"

for name in "${pending[@]}"; do
sql="$(jq -r --arg n "$name" '.migrations[] | select(.name == $n) | .sql' <<<"$plan")"
echo "::group::$name"
echo "$sql"
echo "::endgroup::"
echo "Applying ${name}..."
pnpm exec wrangler d1 execute DB "--$location" --command "$sql"
done

recorded="$(d1_query "SELECT name FROM $history")"
for name in "${known[@]}"; do
if ! grep -qxF "$name" <<<"$recorded"; then
echo "::error::$name is not recorded in $history after applying migrations."
exit 1
fi
done
echo "Applied: ${pending[*]}"
33 changes: 24 additions & 9 deletions .github/scripts/d1-prepare-migrations.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,37 @@
#
# setup.ts migration `schema_vN` <=> migrations/NNNN_*.sql (N zero-padded)
#
# Writes `mode=apply` or `mode=skip` to $GITHUB_OUTPUT (stdout if unset).
# apply — wrangler migrations can run safely
# skip — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware, so
# the schema must keep being managed through the setup route
# Writes `mode=apply`, `mode=prefixed` or `mode=skip` to $GITHUB_OUTPUT
# (stdout if unset).
# apply — wrangler migrations can run safely
# prefixed — TABLE_PREFIX is in use; migrations/*.sql are not prefix-aware,
# so d1-prefixed-migrations.sh applies the setup-route migrations
# skip — prefixed tables found but TABLE_PREFIX is not set here; the
# schema must keep being managed through the setup route
#
# D1_LOCATION=local runs the queries against the local D1 database instead of
# the remote one (for testing this script).
set -euo pipefail

out="${GITHUB_OUTPUT:-/dev/stdout}"
location="${D1_LOCATION:-remote}"
if [[ "$location" != remote && "$location" != local ]]; then
echo "::error::D1_LOCATION must be 'remote' or 'local', got '$location'"
exit 1
fi

if [[ -n "${TABLE_PREFIX:-}" ]]; then
echo "::warning::TABLE_PREFIX is set; skipping wrangler D1 migrations. Run the setup route after deploy to apply schema changes."
echo "mode=skip" >>"$out"
if ! [[ "$TABLE_PREFIX" =~ ^[A-Za-z0-9_]+$ ]]; then
echo "::error::TABLE_PREFIX '$TABLE_PREFIX' may only contain letters, digits and underscores."
exit 1
fi
echo "TABLE_PREFIX=$TABLE_PREFIX — prefixed setup-route migrations will be applied instead of wrangler's."
echo "mode=prefixed" >>"$out"
exit 0
fi

d1_query() {
pnpm exec wrangler d1 execute DB --remote --json --command "$1" |
pnpm exec wrangler d1 execute DB "--$location" --json --command "$1" |
jq -r '.[0].results[] | .name'
}

Expand All @@ -41,7 +56,7 @@ fi

if ! has_table users; then
if grep -Eq '^(_[A-Za-z0-9_]+_schema_migrations|[A-Za-z0-9_]+_users)$' <<<"$tables"; then
echo "::warning::Found prefixed tables but no unprefixed schema; looks like TABLE_PREFIX is in use. Set the TABLE_PREFIX variable on the production environment. Skipping wrangler D1 migrations."
echo "::warning::Found prefixed tables but no unprefixed schema; looks like TABLE_PREFIX is in use. Set the TABLE_PREFIX variable on the production environment so deploys apply prefixed migrations. Skipping D1 migrations."
echo "mode=skip" >>"$out"
exit 0
fi
Expand Down Expand Up @@ -88,7 +103,7 @@ if [[ ${#values[@]} -eq 0 ]]; then
fi

echo "Baselining d1_migrations with: ${values[*]}"
pnpm exec wrangler d1 execute DB --remote --command "
pnpm exec wrangler d1 execute DB "--$location" --command "
CREATE TABLE IF NOT EXISTS d1_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE,
Expand Down
50 changes: 50 additions & 0 deletions .github/scripts/smoke-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# Public-hostname probes. A 403 with Cloudflare's documented challenge header is
# inconclusive (warning), not an application failure. The separate control-plane
# deployment check must succeed even if every HTTP probe is challenged.
set -euo pipefail

if [[ -z "${APP_URL:-}" ]]; then
echo "::error::Variable APP_URL is not set; cannot verify the deployment"
exit 1
fi
base="${APP_URL%/}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

probe() { # probe <path> [jq filter the JSON body must satisfy]
local path="$1" filter="${2:-}" code attempt
for attempt in 1 2 3 4 5 6; do
# One request per attempt keeps the headers/body/status together: curl's
# built-in retries can leave earlier responses in the headers file.
if ! code="$(curl -sS --connect-timeout 10 --max-time 15 \
-D "$tmp/headers" -o "$tmp/body" -w '%{http_code}' "$base$path")"; then
code=000
fi
if [[ "$code" == 2?? ]]; then
if [[ -n "$filter" ]] && ! jq -e "$filter" "$tmp/body" >/dev/null; then
echo "::error::GET $path -> $code, but the response failed the check: $filter"
return 1
fi
echo "GET $path -> $code"
return 0
fi
if [[ "$code" == 403 ]] && grep -qiE '^cf-mitigated:[[:blank:]]*challenge[[:space:]]*$' "$tmp/headers"; then
echo "::warning::GET $path -> 403 Cloudflare challenge (cf-mitigated: challenge). HTTP check inconclusive; relying on the API-side deployment check. Keep Bot Fight Mode enabled."
return 0
fi
if [[ $attempt -lt 6 ]]; then
sleep 5
fi
done
echo "::error::GET $path -> HTTP $code (000 means transport failure)"
return 1
}

probe /api/health '.status == "ok"'
probe /
# This reads the settings table for both migration paths, including TABLE_PREFIX.
# A challenge still means inconclusive, NOT that the DB check passed.
if [[ "${CHECK_DB:-false}" == true ]]; then
probe /api/config 'has("appName")'
fi
Loading
Loading