feat: deploy script with rollback; crop command contract (8/10)
ci / typescript (push) Failing after 34s
ci / rust (push) Successful in 1m41s

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
sparkandClaude Opus 5.5 committed 2026-10-11 14:48:58 +01:00
1 parent 74f8ee8704
commit 29e96b3023
6 files changed
+171 -1

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env bash
# Deploys one PhotoReport service at a given commit, on the container that runs it.
# Called by the deploy receiver: deploy.sh <service> <sha>
# Rules (docs/DEPLOY.md): never touch .env files or data; migrations only move forward;
# a failed health check rolls the code back to the previous commit and reloads it.
set -Eeuo pipefail
SERVICE="${1:?usage: deploy.sh <api|app|site|workers|ml> <sha>}"
SHA="${2:?usage: deploy.sh <service> <sha>}"
REPO_DIR="${DEPLOY_REPO_DIR:-/srv/photoreport}"
BRANCH="${DEPLOY_BRANCH:-main}"
API_PORT="${API_PORT:-3000}"
WEB_ROOT="${DEPLOY_WEB_ROOT:-/var/www/photoreport-app}"
HEALTH_TRIES="${DEPLOY_HEALTH_TRIES:-30}"
log() { printf '[%s] %s\n' "$(date -u +%FT%TZ)" "$*"; }
die() { log "ERROR: $*"; exit 1; }
[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || die "invalid sha: $SHA"
cd "$REPO_DIR"
# Keep a copy of every .env before touching anything (norm BIT-25005). Deploys never write them.
backup_env() {
while IFS= read -r -d '' f; do cp -p "$f" "$f.bak.deploy"; done \
< <(find . -name .env -not -path './node_modules/*' -print0)
}
checkout() {
local target="$1"
git fetch --quiet origin "$BRANCH"
git merge-base --is-ancestor "$target" "origin/$BRANCH" || die "$target is not on origin/$BRANCH"
git reset --quiet --hard "$target"
}
node_install() { pnpm install --frozen-lockfile --prefer-offline; }
wait_for_version() {
local url="$1" want="$2" i
for ((i = 1; i <= HEALTH_TRIES; i++)); do
if curl -fsS --max-time 3 "$url" 2>/dev/null | grep -q "\"version\":\"$want\""; then return 0; fi
sleep 2
done
return 1
}
deploy_api() {
local sha="$1"
node_install
pnpm --filter @photoreport/api build
(cd apps/api && pnpm exec prisma migrate deploy)
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
}
deploy_app() {
local sha="$1" release="$WEB_ROOT/releases/$1"
node_install
rm -rf apps/app/dist # never publish a stale build
VITE_APP_VERSION="$sha" pnpm --filter @photoreport/app build
mkdir -p "$release"
cp -a apps/app/dist/. "$release/"
ln -sfn "$release" "$WEB_ROOT/current.tmp" && mv -Tf "$WEB_ROOT/current.tmp" "$WEB_ROOT/current"
[[ -f "$WEB_ROOT/current/index.html" ]]
# Keep the last 5 releases.
ls -1dt "$WEB_ROOT"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf
}
deploy_pending() { log "service $SERVICE has no deployable build yet; nothing to do"; }
run_service() {
case "$SERVICE" in
api) deploy_api "$1" ;;
app) deploy_app "$1" ;;
site | workers | ml) deploy_pending ;;
*) die "unknown service: $SERVICE" ;;
esac
}
PREVIOUS="$(git rev-parse HEAD)"
log "deploying $SERVICE: $PREVIOUS -> $SHA"
backup_env
checkout "$SHA"
# Bash ignores `set -e` in anything called from `if`, `&&` or `||` (including subshells), so each attempt
# runs as a plain statement in a subshell and its exit code is read afterwards.
set +e
(set -e; run_service "$SHA")
rc=$?
set -e
if [[ $rc -eq 0 ]]; then
log "deploy of $SERVICE at $SHA succeeded"
exit 0
fi
log "deploy failed (exit $rc); rolling back to $PREVIOUS"
checkout "$PREVIOUS"
set +e
(set -e; run_service "$PREVIOUS")
rc=$?
set -e
if [[ $rc -eq 0 ]]; then
log "rolled back to $PREVIOUS"
else
log "rollback to $PREVIOUS also failed (exit $rc); service needs attention"
fi
exit 1
+10
View File
@@ -0,0 +1,10 @@
# Include inside the container's server {} block. Only Gitea needs to reach this path.
location = /_deploy/gitea {
proxy_pass http://127.0.0.1:9010;
client_max_body_size 5m;
}
location = /_deploy/status {
allow 127.0.0.1;
deny all;
proxy_pass http://127.0.0.1:9010;
}
+18
View File
@@ -0,0 +1,18 @@
// PM2 process for the API. Environment comes from apps/api/.env (never written by deploys)
// plus APP_VERSION set by infra/deploy/deploy.sh.
const path = require("node:path");
module.exports = {
apps: [
{
name: "photoreport-api",
cwd: path.join(__dirname, "../../apps/api"),
script: "dist/server.js",
node_args: "--env-file=.env",
instances: 2,
exec_mode: "cluster",
max_memory_restart: "1G",
kill_timeout: 10000,
},
],
};
@@ -0,0 +1,15 @@
# One per container. Set DEPLOY_SERVICE to the service this container runs.
# The secret lives in /etc/photoreport/deploy-receiver.env (root:root 0600), never in the repo.
[Unit]
Description=PhotoReport deploy receiver (Gitea webhook)
After=network-online.target
[Service]
EnvironmentFile=/etc/photoreport/deploy-receiver.env
WorkingDirectory=/srv/photoreport/infra/deploy-receiver
ExecStart=/usr/bin/node dist/server.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
+7
View File
@@ -11,6 +11,13 @@ describe("EditCommand", () => {
expect(() => EditCommand.parse({ command: "develop.set", params: { values: { "light.exposure": "x" } } })).toThrow();
});
it("accepts a crop and rejects an inverted rect", () => {
const ok = EditCommand.safeParse({ command: "crop.set", params: { rect: { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.9 }, aspect: [3, 2] } });
expect(ok.success).toBe(true);
const bad = EditCommand.safeParse({ command: "crop.set", params: { rect: { x0: 0.9, y0: 0.1, x1: 0.1, y1: 0.9 } } });
expect(bad.success).toBe(false);
});
it("wraps commands in an envelope", () => {
const ok = EditEnvelope.safeParse({
photoId: "3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90",
+15 -1
View File
@@ -4,11 +4,25 @@ import { z } from "zod";
* Edit commands mirror `engine/core` (`EditCommand`). They carry no pixels: only control ids and values,
* so they are cheap to broadcast and to store in the op log.
*/
/** Control ids follow LightCraft (`light.exposure`, `mixer.red.hue`); see `controls.ts`. */
export const DevelopSetCommand = z.object({
command: z.literal("develop.set"),
params: z.object({ values: z.record(z.string().regex(/^[a-z]+(\.[a-zA-Z0-9_]+)+$/), z.number().finite()) }),
});
export const CropRect = z
.object({ x0: z.number().min(0).max(1), y0: z.number().min(0).max(1), x1: z.number().min(0).max(1), y1: z.number().min(0).max(1) })
.refine((r) => r.x0 < r.x1 && r.y0 < r.y1, { message: "crop rect must have positive size" });
export const CropSetCommand = z.object({
command: z.literal("crop.set"),
params: z.object({
rect: CropRect,
angle: z.number().min(-45).max(45).default(0),
aspect: z.tuple([z.number().int().positive(), z.number().int().positive()]).nullable().default(null),
}),
});
export const DevelopMergeCommand = z.object({
command: z.literal("develop.merge"),
params: z.object({ partial: z.record(z.string(), z.unknown()) }),
@@ -16,7 +30,7 @@ export const DevelopMergeCommand = z.object({
export const DevelopResetCommand = z.object({ command: z.literal("develop.reset") });
export const EditCommand = z.discriminatedUnion("command", [DevelopSetCommand, DevelopMergeCommand, DevelopResetCommand]);
export const EditCommand = z.discriminatedUnion("command", [DevelopSetCommand, CropSetCommand, DevelopMergeCommand, DevelopResetCommand]);
export type EditCommand = z.infer<typeof EditCommand>;
/** What a client sends over the realtime channel. */