Skip to content

Commit f226d54

Browse files
committed
Production environment, pull request previews and off-site backups
- docker-compose takes its project name and port from .env so staging (jscm, 3333), production (jscm-prod, 3334) and previews (jscm-pr-<n>, 40000+n) live side by side; the deploy health check uses that port - deploy/dispatch.sh is the only command the CI key may run: deploy staging|production, preview up|down; the preview script is always read from the staging branch, never from the pull request - PR previews on pr-<n>.preview.javascript.cm (label "preview", 3 max), torn down when the PR closes - Caddy: production on javascript.cm (www redirects), noindex only on non-production hosts, preview sites imported from /etc/caddy/previews - Backups cover every environment and are pushed off-site, encrypted, with restic when /etc/jscm/backup.env is configured
1 parent 4f6172f commit f226d54

10 files changed

Lines changed: 301 additions & 47 deletions

File tree

‎.github/workflows/deploy-staging.yml‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
name: CI & staging deploy
1+
name: CI & deploy
22

33
on:
44
push:
55
pull_request:
6+
types: [opened, synchronize, reopened, labeled, closed]
67
workflow_dispatch:
78

89
concurrency:
@@ -12,6 +13,7 @@ concurrency:
1213
jobs:
1314
check:
1415
name: Typecheck, tests & build
16+
if: github.event.action != 'closed'
1517
runs-on: ubuntu-latest
1618
services:
1719
postgres:
@@ -42,16 +44,16 @@ jobs:
4244
- run: node ace build
4345

4446
deploy:
45-
name: Deploy to staging.javascript.cm
47+
name: Deploy ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}
4648
needs: check
47-
if: github.event_name == 'push' && github.ref == 'refs/heads/staging'
49+
if: github.event_name == 'push' && (github.ref == 'refs/heads/staging' || github.ref == 'refs/heads/main')
4850
runs-on: ubuntu-latest
4951
concurrency:
50-
group: staging-deploy
52+
group: deploy-${{ github.ref_name }}
5153
cancel-in-progress: false
5254
environment:
53-
name: staging
54-
url: https://staging.javascript.cm
55+
name: ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}
56+
url: ${{ github.ref == 'refs/heads/main' && 'https://javascript.cm' || 'https://staging.javascript.cm' }}
5557
steps:
5658
- name: Check deploy secrets
5759
id: secrets
@@ -71,7 +73,48 @@ jobs:
7173
echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key
7274
chmod 600 ~/.ssh/deploy_key
7375
echo "${{ secrets.STAGING_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
74-
# The key is restricted server-side (forced command): it can only run the deploy script.
76+
# The key is restricted server-side (forced command deploy/dispatch.sh).
7577
- name: Deploy
7678
if: steps.secrets.outputs.ready == 'true'
77-
run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} deploy
79+
run: |
80+
target=${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}
81+
ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} "deploy $target"
82+
83+
preview:
84+
name: Pull request preview
85+
# Opt-in with the "preview" label; same-repository branches only (forks get no secrets).
86+
# "check" is skipped when the PR is closed: always() still lets this job
87+
# tear the preview down; otherwise it only runs after a green check.
88+
if: >-
89+
always() &&
90+
github.event_name == 'pull_request' &&
91+
github.event.pull_request.head.repo.full_name == github.repository &&
92+
contains(github.event.pull_request.labels.*.name, 'preview') &&
93+
(github.event.action == 'closed' || needs.check.result == 'success')
94+
needs: [check]
95+
runs-on: ubuntu-latest
96+
permissions:
97+
pull-requests: write
98+
concurrency:
99+
group: preview-${{ github.event.pull_request.number }}
100+
cancel-in-progress: true
101+
steps:
102+
- name: Configure SSH
103+
run: |
104+
install -m 700 -d ~/.ssh
105+
echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key
106+
chmod 600 ~/.ssh/deploy_key
107+
echo "${{ secrets.STAGING_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
108+
- name: Create or update the preview
109+
if: github.event.action != 'closed'
110+
run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} "preview up ${{ github.event.pull_request.number }} ${{ github.event.pull_request.head.sha }}"
111+
- name: Comment the preview URL
112+
if: github.event.action == 'opened' || github.event.action == 'labeled'
113+
env:
114+
GH_TOKEN: ${{ github.token }}
115+
run: |
116+
gh pr comment ${{ github.event.pull_request.number }} --repo ${{ github.repository }} \
117+
--body "Aperçu de cette PR : https://pr-${{ github.event.pull_request.number }}.preview.javascript.cm (mis à jour à chaque push, supprimé à la fermeture)."
118+
- name: Remove the preview
119+
if: github.event.action == 'closed'
120+
run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} "preview down ${{ github.event.pull_request.number }}"

‎README.md‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,19 @@ Direction artistique : _un journal technique imprimé de la scène JavaScript ca
7474

7575
## Déploiement
7676

77-
Le serveur exécute `docker-compose.yml` (application + PostgreSQL) ; Caddy, installé sur l’hôte, termine le TLS et relaie vers `127.0.0.1:3333` (`deploy/Caddyfile`).
78-
79-
- Chaque push sur la branche `staging` lance le workflow GitHub Actions _Staging_ : typecheck + build, puis déploiement par SSH. La clé utilisée est restreinte côté serveur à une seule commande (`deploy/deploy.sh`).
80-
- Au démarrage, le conteneur applique les migrations et les seeders idempotents. Le contenu de démonstration (membres et publications fictifs) n’est inséré en production que si `SEED_DEMO=true`.
81-
- Déploiement manuel sur le serveur : `./deploy/deploy.sh staging`.
82-
- Sauvegardes : `deploy/backup.sh` (dump PostgreSQL compressé, rotation 14 jours dans `~/backups/jscm`) est lancé chaque nuit par le timer systemd `jscm-backup` (`deploy/jscm-backup.{service,timer}`). Restauration : `docker compose exec -T db pg_restore -U <user> -d <base> --clean --if-exists < fichier.dump`.
77+
Un même serveur héberge plusieurs environnements, chacun étant un projet Docker Compose (application + PostgreSQL) derrière Caddy, installé sur l’hôte (`deploy/Caddyfile`, HTTPS automatique) :
78+
79+
| Environnement | Branche | Dossier sur le serveur | Port local | Adresse |
80+
| --- | --- | --- | --- | --- |
81+
| Production | `main` | `~/apps/javascript.cm-prod` | 3334 | https://javascript.cm |
82+
| Staging | `staging` | `~/apps/javascript.cm` | 3333 | https://staging.javascript.cm |
83+
| Aperçu de PR | branche de la PR | `~/apps/previews/pr-<n>` | 40000 + n | https://pr-&lt;n&gt;.preview.javascript.cm |
84+
85+
- Le workflow GitHub Actions lance typecheck, tests et build sur chaque push et chaque PR, puis déploie `staging` et `main` sur leur environnement. La clé SSH utilisée est restreinte côté serveur à `deploy/dispatch.sh`, qui n’accepte que `deploy staging`, `deploy production`, `preview up <pr> <sha>` et `preview down <pr>`.
86+
- Aperçus : ajoutez le label `preview` à une PR (branche du dépôt, pas d’un fork) ; l’aperçu est mis à jour à chaque push et supprimé à la fermeture (3 aperçus au maximum). Nécessite un enregistrement DNS `*.preview.javascript.cm` vers le serveur.
87+
- Au démarrage, chaque conteneur applique les migrations et les seeders idempotents. Le contenu de démonstration fictif n’est inséré que si `SEED_DEMO=true` (staging et aperçus).
88+
- Sauvegardes : `deploy/backup.sh` (timer systemd `jscm-backup`, chaque nuit) sauvegarde la base et les fichiers envoyés de chaque environnement, garde 14 jours en local et, si `/etc/jscm/backup.env` est rempli (voir `deploy/backup.env.example`), envoie une copie chiffrée hors du serveur avec restic (Cloudflare R2, Backblaze B2 ou tout stockage S3). Restauration : voir l’en-tête du script.
89+
- Déploiement manuel : `./deploy/deploy.sh <branche>` depuis le dossier de l’environnement.
8390

8491
## Contribuer
8592

‎deploy/Caddyfile‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# /etc/caddy/Caddyfile — managed by javascript.cm deploy
22

3+
# Shared site configuration. {args[0]} = local port of the environment's app
4+
# container (staging 3333, production 3334, previews 40000+<pr>).
35
(app) {
46
encode zstd gzip
57

@@ -27,14 +29,13 @@
2729
X-Content-Type-Options "nosniff"
2830
Referrer-Policy "strict-origin-when-cross-origin"
2931
Permissions-Policy "camera=(), microphone=(), geolocation=()"
30-
X-Robots-Tag "noindex, nofollow"
3132
-Server
3233
}
3334

3435
@assets path /assets/*
3536
header @assets Cache-Control "public, max-age=31536000, immutable"
3637

37-
reverse_proxy 127.0.0.1:3333 {
38+
reverse_proxy 127.0.0.1:{args[0]} {
3839
health_uri /up
3940
health_interval 30s
4041
}
@@ -43,8 +44,22 @@
4344
log
4445
}
4546

47+
# Environments that must stay out of search engines.
48+
(noindex) {
49+
header X-Robots-Tag "noindex, nofollow"
50+
}
51+
52+
javascript.cm {
53+
import app 3334
54+
}
55+
56+
www.javascript.cm {
57+
redir https://javascript.cm{uri} permanent
58+
}
59+
4660
staging.javascript.cm {
47-
import app
61+
import app 3333
62+
import noindex
4863
}
4964

5065
# Temporary: direct access by IP until the staging DNS points here.
@@ -56,5 +71,9 @@ staging.javascript.cm {
5671
profile shortlived
5772
}
5873
}
59-
import app
74+
import app 3333
75+
import noindex
6076
}
77+
78+
# Pull request previews: one site file per PR, written by deploy/preview.sh.
79+
import /etc/caddy/previews/*.caddy

‎deploy/backup.env.example‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# /etc/jscm/backup.env (root:root, chmod 600) — off-site backups with restic.
2+
# Any S3-compatible storage works. Examples:
3+
# Cloudflare R2: s3:https://<account-id>.r2.cloudflarestorage.com/jscm-backups
4+
# Backblaze B2: s3:https://s3.<region>.backblazeb2.com/jscm-backups
5+
RESTIC_REPOSITORY=
6+
# Encryption password: store it in a password manager too, backups are
7+
# unreadable without it.
8+
RESTIC_PASSWORD=
9+
AWS_ACCESS_KEY_ID=
10+
AWS_SECRET_ACCESS_KEY=

‎deploy/backup.sh‎

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,66 @@
11
#!/usr/bin/env bash
2-
# Dump the PostgreSQL database (custom format, compressed) and archive the
3-
# uploaded files (members' CVs, Docker volume "uploads" mounted on
4-
# /app/storage), and keep the last BACKUP_KEEP_DAYS days of both. Run from
5-
# the repository root's deploy/ dir by the jscm-backup systemd timer (see
6-
# deploy/README section in README.md).
2+
# Nightly backups of every environment present on the server (staging in
3+
# ~/apps/javascript.cm, production in ~/apps/javascript.cm-prod):
4+
# 1. PostgreSQL dump (custom format, compressed)
5+
# 2. uploaded files (CVs, images: Docker volume mounted on /app/storage)
6+
# kept locally for BACKUP_KEEP_DAYS days, then — when RESTIC_REPOSITORY is
7+
# configured (systemd EnvironmentFile /etc/jscm/backup.env) — pushed off-site
8+
# with restic: encrypted client-side, deduplicated, retention 7 daily /
9+
# 8 weekly / 12 monthly.
710
#
8-
# Restore:
11+
# Restore (from the environment's directory):
912
# docker compose exec -T db pg_restore -U <user> -d <db> --clean --if-exists < file.dump
1013
# docker compose exec -T app tar -C /app/storage -xzf - < file-uploads.tgz
14+
# restic restore latest --tag <project> --target /tmp/restore (off-site copy)
1115
set -euo pipefail
1216

13-
main() {
14-
cd "$(dirname "$0")/.."
15-
# Dumps and archives contain personal data: owner-only from the start.
16-
umask 077
17-
18-
local dir="${BACKUP_DIR:-$HOME/backups/jscm}"
19-
local keep="${BACKUP_KEEP_DAYS:-14}"
20-
local db_user db_name
17+
backup_environment() {
18+
local project_dir="$1" dir="$2"
19+
cd "$project_dir"
20+
local name db_user db_name
21+
name="$(grep -E '^COMPOSE_PROJECT_NAME=' .env | cut -d= -f2- || true)"
22+
name="${name:-jscm}"
2123
db_user="$(grep -E '^DB_USER=' .env | cut -d= -f2-)"
2224
db_name="$(grep -E '^DB_DATABASE=' .env | cut -d= -f2-)"
2325

24-
install -d -m 700 "$dir"
25-
local file="$dir/jscm-$(date -u +%Y%m%dT%H%M%SZ).dump"
26+
local stamp file uploads
27+
stamp="$(date -u +%Y%m%dT%H%M%SZ)"
28+
file="$dir/$name-$stamp.dump"
29+
uploads="$dir/$name-$stamp-uploads.tgz"
2630

2731
docker compose exec -T db pg_dump -U "$db_user" -d "$db_name" --format=custom --no-owner > "$file.tmp"
2832
mv "$file.tmp" "$file"
29-
chmod 600 "$file"
3033
echo "backup: $file ($(du -h "$file" | cut -f1))"
3134

32-
# Uploaded files (CVs contain personal data: same 600 permissions).
33-
local uploads="${file%.dump}-uploads.tgz"
3435
docker compose exec -T app tar -C /app/storage -czf - . > "$uploads.tmp"
3536
mv "$uploads.tmp" "$uploads"
36-
chmod 600 "$uploads"
3737
echo "backup: $uploads ($(du -h "$uploads" | cut -f1))"
38+
}
39+
40+
main() {
41+
# Dumps and archives contain personal data: owner-only from the start.
42+
umask 077
43+
local dir="${BACKUP_DIR:-$HOME/backups/jscm}"
44+
local keep="${BACKUP_KEEP_DAYS:-14}"
45+
install -d -m 700 "$dir"
46+
47+
local project
48+
for project in "$HOME/apps/javascript.cm" "$HOME/apps/javascript.cm-prod"; do
49+
if [[ -f "$project/.env" ]] && (cd "$project" && docker compose ps --status running -q db | grep -q .); then
50+
backup_environment "$project" "$dir"
51+
fi
52+
done
53+
54+
find "$dir" -type f \( -name '*.dump' -o -name '*-uploads.tgz' \) -mtime +"$keep" -delete
3855

39-
find "$dir" -type f \( -name 'jscm-*.dump' -o -name 'jscm-*-uploads.tgz' \) -mtime +"$keep" -delete
56+
if [[ -n "${RESTIC_REPOSITORY:-}" ]]; then
57+
restic snapshots --latest 1 > /dev/null 2>&1 || restic init
58+
restic backup --quiet --tag jscm --host jscm "$dir"
59+
restic forget --quiet --tag jscm --keep-daily 7 --keep-weekly 8 --keep-monthly 12 --prune
60+
echo "off-site: snapshot pushed to $RESTIC_REPOSITORY"
61+
else
62+
echo "off-site: skipped (RESTIC_REPOSITORY not configured in /etc/jscm/backup.env)"
63+
fi
4064
}
4165

4266
main "$@"

‎deploy/deploy.sh‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ main() {
1919
docker compose build --pull app
2020
docker compose up -d --remove-orphans
2121

22-
echo "==> waiting for health check"
22+
local port
23+
port="$(grep -E '^APP_PORT=' .env | cut -d= -f2- || true)"
24+
port="${port:-3333}"
25+
echo "==> waiting for health check on port ${port}"
2326
for _ in $(seq 1 60); do
24-
if curl -fsS http://127.0.0.1:3333/up >/dev/null 2>&1; then
27+
if curl -fsS "http://127.0.0.1:${port}/up" >/dev/null 2>&1; then
2528
echo "==> healthy"
2629
docker image prune -f >/dev/null
2730
exit 0

‎deploy/dispatch.sh‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env bash
2+
# Forced command of the GitHub Actions SSH key (~/.ssh/authorized_keys):
3+
# command="/home/brightky/bin/deploy-jscm",no-pty,... ssh-ed25519 …
4+
# Installed as ~/bin/deploy-jscm. Accepts exactly one of:
5+
# deploy [staging] deploy the staging branch
6+
# deploy production deploy main to production
7+
# preview up <pr> <sha> create or update the preview of a pull request
8+
# preview down <pr> remove the preview of a pull request
9+
set -euo pipefail
10+
11+
main() {
12+
local -a args
13+
read -r -a args <<< "${SSH_ORIGINAL_COMMAND:-deploy}"
14+
15+
case "${args[0]:-}" in
16+
deploy)
17+
local target="${args[1]:-staging}" dir branch
18+
case "$target" in
19+
staging) dir="$HOME/apps/javascript.cm" branch=staging ;;
20+
production) dir="$HOME/apps/javascript.cm-prod" branch=main ;;
21+
*) echo "unknown target: $target" >&2; exit 2 ;;
22+
esac
23+
cd "$dir"
24+
git fetch -q --prune origin "$branch"
25+
git checkout -q -B "$branch" "origin/$branch"
26+
exec ./deploy/deploy.sh "$branch"
27+
;;
28+
preview)
29+
local action="${args[1]:-}" pr="${args[2]:-}" sha="${args[3]:-}"
30+
[[ "$action" == up || "$action" == down ]] || { echo "bad action" >&2; exit 2; }
31+
[[ "$pr" =~ ^[0-9]{1,5}$ ]] || { echo "bad pull request number" >&2; exit 2; }
32+
[[ "$action" == down || "$sha" =~ ^[0-9a-f]{7,40}$ ]] || { echo "bad commit" >&2; exit 2; }
33+
# The preview script always comes from the staging branch (reviewed code),
34+
# never from the pull request itself.
35+
cd "$HOME/apps/javascript.cm"
36+
git fetch -q origin staging
37+
git show origin/staging:deploy/preview.sh > "$HOME/bin/.preview.sh"
38+
exec bash "$HOME/bin/.preview.sh" "$action" "$pr" "$sha"
39+
;;
40+
*)
41+
echo "unknown command" >&2
42+
exit 2
43+
;;
44+
esac
45+
}
46+
47+
exec < /dev/null > >(tee -a "$HOME/apps/deploy.log") 2>&1
48+
main

‎deploy/jscm-backup.service‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
[Unit]
2-
Description=javascript.cm PostgreSQL backup
2+
Description=javascript.cm backups (databases, uploads, off-site copy)
33
Wants=docker.service
4-
After=docker.service
4+
After=docker.service network-online.target
55

66
[Service]
77
Type=oneshot
88
User=brightky
9+
# Off-site credentials (restic): RESTIC_REPOSITORY, RESTIC_PASSWORD,
10+
# AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY — root-owned, mode 600.
11+
EnvironmentFile=-/etc/jscm/backup.env
912
ExecStart=/home/brightky/apps/javascript.cm/deploy/backup.sh

0 commit comments

Comments
 (0)