forked from mtusi2026/mtusi2026lab5
60 lines
2.5 KiB
Bash
60 lines
2.5 KiB
Bash
#!/bin/sh
|
|
set -eu
|
|
|
|
attachment_id="${1:?usage: promote-pipeline.sh ATTACHMENT_UUID PIPELINE_VERSION [REQUESTED_BY] [ENV_FILE]}"
|
|
pipeline_version="${2:?pipeline version is required}"
|
|
requested_by="${3:-operator}"
|
|
env_file="${4:-.env}"
|
|
|
|
case "$attachment_id" in
|
|
????????-????-????-????-????????????) ;;
|
|
*) echo "AttachmentId must be a UUID" >&2; exit 2 ;;
|
|
esac
|
|
case "$pipeline_version" in
|
|
1|2) ;;
|
|
*) echo "PipelineVersion must be 1 or 2" >&2; exit 2 ;;
|
|
esac
|
|
case "$requested_by" in
|
|
*[!A-Za-z0-9_.@-]*|'') echo "RequestedBy contains unsupported characters" >&2; exit 2 ;;
|
|
esac
|
|
|
|
sql="WITH candidate AS (
|
|
SELECT id, pipeline_version FROM attachments
|
|
WHERE id = '$attachment_id'::uuid AND pipeline_version < $pipeline_version FOR UPDATE
|
|
), superseded AS (
|
|
UPDATE attachment_jobs j SET status = 'superseded', published = true,
|
|
last_error_code = 'superseded_by_v$pipeline_version',
|
|
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
|
FROM candidate c WHERE j.attachment_id = c.id
|
|
AND j.pipeline_version < $pipeline_version AND j.status IN ('queued', 'processing')
|
|
RETURNING j.id
|
|
), created AS (
|
|
INSERT INTO attachment_jobs
|
|
(id, attachment_id, pipeline_version, attempt, status, published,
|
|
next_attempt_at, created_at, updated_at)
|
|
SELECT gen_random_uuid(), id, $pipeline_version, 1, 'queued', false,
|
|
clock_timestamp(), clock_timestamp(), clock_timestamp() FROM candidate
|
|
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
|
|
RETURNING id, attachment_id
|
|
), promoted AS (
|
|
UPDATE attachments a SET pipeline_version = $pipeline_version,
|
|
status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
|
FROM candidate c, created n WHERE a.id = c.id AND n.attachment_id = c.id
|
|
RETURNING a.id
|
|
), audited AS (
|
|
INSERT INTO attachment_pipeline_promotions
|
|
(attachment_id, from_version, to_version, job_id, requested_by)
|
|
SELECT c.id, c.pipeline_version, $pipeline_version, n.id, '$requested_by'
|
|
FROM candidate c JOIN created n ON n.attachment_id = c.id
|
|
JOIN promoted p ON p.id = c.id RETURNING job_id
|
|
)
|
|
SELECT COALESCE((SELECT job_id::text FROM audited), 'no-op');"
|
|
|
|
result="$(docker compose --env-file "$env_file" exec -T postgres \
|
|
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c "$sql")"
|
|
if [ "$result" = "no-op" ]; then
|
|
echo "No-op: attachment is missing, already at v$pipeline_version, or that version already exists"
|
|
else
|
|
echo "Promoted attachment $attachment_id to pipeline v$pipeline_version with job $result"
|
|
fi
|