Files
mtusi2026lab5/scripts/promote-pipeline.ps1
T
2026-11-19 10:57:39 +03:00

74 lines
2.6 KiB
PowerShell

param(
[Parameter(Mandatory = $true)]
[string]$AttachmentId,
[Parameter(Mandatory = $true)]
[ValidateRange(1, 2)]
[int]$PipelineVersion,
[string]$RequestedBy = $env:USERNAME,
[string]$EnvFile = ".env"
)
$parsedAttachmentId = [guid]::Empty
if (-not [guid]::TryParse($AttachmentId, [ref]$parsedAttachmentId)) {
throw "AttachmentId must be a UUID"
}
if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') {
throw "RequestedBy contains unsupported characters"
}
$sql = @"
WITH candidate AS (
SELECT id, pipeline_version
FROM attachments
WHERE id = '$parsedAttachmentId'::uuid AND pipeline_version < $PipelineVersion
FOR UPDATE
), superseded AS (
UPDATE attachment_jobs j
SET status = 'superseded', published = true,
last_error_code = 'superseded_by_v$PipelineVersion',
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
FROM candidate c
WHERE j.attachment_id = c.id AND j.pipeline_version < $PipelineVersion
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, $PipelineVersion, 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 = $PipelineVersion, 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, $PipelineVersion, n.id, '$RequestedBy'
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 $EnvFile exec -T postgres `
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql
if ($LASTEXITCODE -ne 0) {
throw "Pipeline promotion transaction failed"
}
$last = ($result | Select-Object -Last 1).Trim()
if ($last -eq "no-op") {
Write-Output "No-op: attachment is missing, already at v$PipelineVersion, or that version already exists"
} else {
Write-Output "Promoted attachment $parsedAttachmentId to pipeline v$PipelineVersion with job $last"
}