Files
faunosteo/supabase/migrations/20261013100000_files_foundation.sql
T
bchanot 273914d825 fix(supabase): ceiling measured on bytes present in the bucket plus pending claims without bytes; confirm fails closed on an unsized object; cleartext host must start with a letter
Third audit (BLOCK 1): counting terminal rows while queued let begin spam
pin the ceiling with declared sizes. The ceiling now sums storage.objects
sizes of the bucket (whatever the row's state) plus the declared size of
pending_upload rows whose quarantine object has not landed: a claim dies
with its row, a present object counts whatever its row says, no full scan of
the assets history. confirm_asset_upload treats an object without a size as
upload_missing. pgTAP (plan 138): rejected rows without bytes weigh nothing,
pending claims fill, superseded claims vanish, present bytes fill, unsized
object refused. Worker: a single-label cleartext host must start with an
ASCII letter (0X… hex forms refused, test added); STORAGE.md names the
native-run search-domain residual.
2026-10-13 20:07:22 +02:00

700 lines
29 KiB
PL/PgSQL

-- Files foundation (plan Step 8, docs/development/STORAGE.md): the `assets`
-- table as the authority over every user file, the private buckets, the
-- avatar read / upload policies evaluated through `assets`, the purge queue
-- and the RPCs of the browser and of the Rust worker.
--
-- First consumer: the profile photo (kind profile_avatar, bucket avatars).
-- Every other bucket exists and stays closed (no policy names it) until its
-- own step writes its rules. The sheet bucket of 20261009100000 is untouched.
--
-- Invariants pinned by supabase/tests/010_files_foundation.sql:
-- * no API role reads a quarantine object, ever; a final object is readable
-- only through a `clean` row of the caller whose object_key is the name;
-- * the browser can insert only at the quarantine key of its own
-- pending_upload row; no UPDATE / DELETE policy exists on the bucket;
-- * every status change is an RPC; the worker's RPCs carry a lease token so
-- an old task never overwrites a newer avatar;
-- * a terminal row (deleted, rejected) enqueues its objects for a deferred
-- purge; a clean row's object_key never enters the queue.
-- ---------------------------------------------------------------------------
-- Buckets: all private. Upsert so the migration converges everywhere.
-- ---------------------------------------------------------------------------
insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values ('avatars', 'avatars', false, 5242880, array['image/jpeg', 'image/png', 'image/webp'])
on conflict (id) do update
set public = false, file_size_limit = excluded.file_size_limit,
allowed_mime_types = excluded.allowed_mime_types;
insert into storage.buckets (id, name, public)
values
('logos', 'logos', false),
('professional-documents', 'professional-documents', false),
('client-files', 'client-files', false),
('animal-files', 'animal-files', false),
('report-files', 'report-files', false),
('imports', 'imports', false)
on conflict (id) do update set public = false;
-- ---------------------------------------------------------------------------
-- assets
-- ---------------------------------------------------------------------------
create type public.asset_status as enum
('pending_upload', 'uploaded', 'clean', 'rejected', 'deleted');
create table public.assets (
id uuid primary key default gen_random_uuid(),
owner_id uuid not null references public.profiles (id) on delete cascade,
kind text not null
constraint assets_kind_known check (kind in ('profile_avatar')),
bucket_id text not null
constraint assets_bucket_per_kind check (
(kind = 'profile_avatar' and bucket_id = 'avatars')
),
-- Final key, server-built from uuids; one canonical file name per kind.
object_key text not null unique
constraint assets_object_key_shape check (
object_key ~ '^profiles/[0-9a-f-]{36}/[0-9a-f-]{36}/avatar\.webp$'
),
-- Upload key; null once the worker confirmed the quarantine object is gone.
quarantine_key text unique
constraint assets_quarantine_key_shape check (
quarantine_key ~ '^quarantine/[0-9a-f-]{36}/[0-9a-f-]{36}/upload$'
),
status public.asset_status not null default 'pending_upload',
declared_mime text not null
constraint assets_declared_mime_known check (
declared_mime in ('image/jpeg', 'image/png', 'image/webp')
),
declared_size integer not null
constraint assets_declared_size_range check (declared_size between 1 and 5242880),
-- The clean output, set by complete_avatar_job.
byte_size integer
constraint assets_byte_size_range check (byte_size between 1 and 524288),
sha256 text
constraint assets_sha256_hex check (sha256 ~ '^[0-9a-f]{64}$'),
rejection_reason text
constraint assets_rejection_reason_known check (
rejection_reason in ('unsupported_type', 'decode_failed', 'dimensions', 'processing_error')
),
constraint assets_rejection_reason_iff_rejected check (
(status = 'rejected') = (rejection_reason is not null)
),
-- Lease: claim_avatar_jobs sets both; complete / reject require the token.
attempts smallint not null default 0,
locked_at timestamptz,
lock_token uuid,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.assets is
'One row per user file, created before the bytes exist and kept after they are gone (deleted / rejected) until the purge queue has been served. Writes only through RPCs (docs/development/STORAGE.md).';
comment on column public.assets.object_key is
'Final key in the bucket (profiles/<owner>/<id>/avatar.webp). Readable by the owner while the row is clean.';
comment on column public.assets.quarantine_key is
'Upload key (quarantine/<owner>/<id>/upload). Never readable by an API role; null once purged.';
comment on column public.assets.lock_token is
'Lease token of the worker that claimed the row; complete_avatar_job and reject_avatar_job refuse any other token.';
-- "The" avatar of an account = its single clean row (no profile column).
create unique index assets_one_clean_avatar
on public.assets (owner_id) where kind = 'profile_avatar' and status = 'clean';
create index assets_claimable on public.assets (created_at) where status = 'uploaded';
create index assets_owner_idx on public.assets (owner_id, created_at desc);
create trigger assets_set_updated_at
before update on public.assets
for each row execute function private.set_updated_at();
-- Privileges + RLS: the owner reads the public columns of their rows; nobody
-- writes through the API.
revoke all on public.assets from public, anon, authenticated;
grant select (
id, owner_id, kind, bucket_id, object_key, status, declared_mime, declared_size,
byte_size, sha256, rejection_reason, created_at, updated_at
) on public.assets to authenticated;
alter table public.assets enable row level security;
create policy assets_select_own
on public.assets
for select
to authenticated
using (owner_id = (select auth.uid()));
-- ---------------------------------------------------------------------------
-- Purge queue (private): every object deletion the worker makes comes from
-- here or from the quarantine leftover query; nothing else is ever deleted.
-- ---------------------------------------------------------------------------
create table private.object_purge_queue (
id uuid primary key default gen_random_uuid(),
bucket_id text not null,
object_name text not null,
not_before timestamptz not null,
enqueued_at timestamptz not null default now(),
locked_at timestamptz,
attempts smallint not null default 0,
unique (bucket_id, object_name)
);
comment on table private.object_purge_queue is
'Objects to delete after a grace period (48 h for the final key of a deleted row: longer than a backup run; 1 h for quarantine keys and rejected uploads). Served by claim_purges / ack_purge.';
revoke all on private.object_purge_queue from public, anon, authenticated, service_role;
create or replace function private.enqueue_object_purge(
p_bucket_id text,
p_object_name text,
p_grace interval
)
returns void
language sql
security definer
set search_path = ''
as $$
insert into private.object_purge_queue (bucket_id, object_name, not_before)
values (p_bucket_id, p_object_name, now() + p_grace)
on conflict (bucket_id, object_name) do update
set not_before = least(private.object_purge_queue.not_before, excluded.not_before);
$$;
revoke all on function private.enqueue_object_purge(text, text, interval) from public;
-- A row reaching a terminal status, or disappearing (account cascade),
-- enqueues both of its keys. A clean row's object_key is never enqueued.
create or replace function private.enqueue_asset_objects()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row public.assets;
v_final_grace interval;
begin
if tg_op = 'DELETE' then
v_row := old;
v_final_grace := interval '48 hours';
else
if new.status not in ('deleted', 'rejected') or old.status in ('deleted', 'rejected') then
return new;
end if;
v_row := new;
v_final_grace := case when new.status = 'deleted' then interval '48 hours' else interval '1 hour' end;
end if;
perform private.enqueue_object_purge(v_row.bucket_id, v_row.object_key, v_final_grace);
if v_row.quarantine_key is not null then
perform private.enqueue_object_purge(v_row.bucket_id, v_row.quarantine_key, interval '1 hour');
end if;
return coalesce(new, old);
end;
$$;
revoke all on function private.enqueue_asset_objects() from public;
create trigger assets_enqueue_purge_on_status
after update of status on public.assets
for each row execute function private.enqueue_asset_objects();
create trigger assets_enqueue_purge_on_delete
after delete on public.assets
for each row execute function private.enqueue_asset_objects();
-- Global ceiling on the bytes present in the avatars bucket (10 GiB to start),
-- measured on storage.objects, plus the declared size of uploads still expected.
create or replace function private.storage_ceiling()
returns bigint
language sql
immutable
set search_path = ''
as $$ select 10737418240::bigint; $$;
revoke all on function private.storage_ceiling() from public;
-- ---------------------------------------------------------------------------
-- Storage policies for bucket avatars, evaluated through assets.
-- ---------------------------------------------------------------------------
create or replace function private.can_read_avatar_object(p_user_id uuid, p_object_name text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from public.assets a
where a.owner_id = p_user_id
and a.kind = 'profile_avatar'
and a.status = 'clean'
and a.object_key = p_object_name
);
$$;
comment on function private.can_read_avatar_object(uuid, text) is
'Storage read predicate for bucket avatars: the object_key of a clean row of the caller. Quarantine keys never match.';
create or replace function private.can_upload_avatar_object(p_user_id uuid, p_object_name text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1 from public.assets a
join public.profiles p on p.id = a.owner_id and p.active
where a.owner_id = p_user_id
and a.kind = 'profile_avatar'
and a.status = 'pending_upload'
and a.quarantine_key = p_object_name
);
$$;
comment on function private.can_upload_avatar_object(uuid, text) is
'Storage insert predicate for bucket avatars: the quarantine_key of a pending_upload row of the caller. Final keys never match.';
revoke all on function private.can_read_avatar_object(uuid, text) from public;
revoke all on function private.can_upload_avatar_object(uuid, text) from public;
grant execute on function private.can_read_avatar_object(uuid, text) to authenticated;
grant execute on function private.can_upload_avatar_object(uuid, text) to authenticated;
create policy avatars_read
on storage.objects
for select
to authenticated
using (
bucket_id = 'avatars'
and private.can_read_avatar_object((select auth.uid()), name)
);
create policy avatars_upload
on storage.objects
for insert
to authenticated
with check (
bucket_id = 'avatars'
and private.can_upload_avatar_object((select auth.uid()), name)
);
-- No UPDATE / DELETE policy for API roles on this bucket; no policy at all on
-- the six closed buckets.
-- ---------------------------------------------------------------------------
-- Browser RPCs (authenticated). Business refusals: SQLSTATE P0001 with the
-- closed code as the message; authorisation refusals: 42501.
-- ---------------------------------------------------------------------------
create or replace function public.begin_avatar_upload(declared_mime text, declared_size integer)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_actor uuid := auth.uid();
v_active boolean;
v_id uuid := gen_random_uuid();
v_recent integer;
v_used bigint;
v_expected bigint;
v_object_key text;
v_quarantine_key text;
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
-- Serialises a double click and refuses a deactivated account.
select p.active into v_active from public.profiles p where p.id = v_actor for update;
if v_active is distinct from true then
raise exception 'account inactive or unknown' using errcode = '42501';
end if;
if declared_mime is null or declared_mime not in ('image/jpeg', 'image/png', 'image/webp') then
raise exception using message = 'unsupported_type', errcode = 'P0001';
end if;
if declared_size is null or declared_size < 1 or declared_size > 5242880 then
raise exception using message = 'too_large', errcode = 'P0001';
end if;
select count(*) into v_recent from public.assets a
where a.owner_id = v_actor and a.created_at > now() - interval '1 hour';
if v_recent >= 10 then
raise exception using message = 'rate_limited', errcode = 'P0001';
end if;
-- Bytes that exist (every object of the bucket, whatever its row's state)
-- plus the declared size of pending uploads whose bytes have not landed yet.
-- A claim never outlives the row it belongs to, and a row with no bytes
-- weighs nothing once it moved on, so no account can pin the ceiling.
select coalesce(sum((o.metadata ->> 'size')::bigint), 0) into v_used
from storage.objects o where o.bucket_id = 'avatars';
select coalesce(sum(a.declared_size), 0) into v_expected
from public.assets a
where a.status = 'pending_upload'
and not exists (
select 1 from storage.objects o
where o.bucket_id = a.bucket_id and o.name = a.quarantine_key
);
if v_used + v_expected + declared_size > private.storage_ceiling() then
raise exception using message = 'storage_full', errcode = 'P0001';
end if;
-- One in-flight avatar per account: a new pick supersedes the previous one.
update public.assets a set status = 'deleted'
where a.owner_id = v_actor and a.kind = 'profile_avatar'
and a.status in ('pending_upload', 'uploaded');
v_object_key := 'profiles/' || v_actor || '/' || v_id || '/avatar.webp';
v_quarantine_key := 'quarantine/' || v_actor || '/' || v_id || '/upload';
insert into public.assets (id, owner_id, kind, bucket_id, object_key, quarantine_key, declared_mime, declared_size)
values (v_id, v_actor, 'profile_avatar', 'avatars', v_object_key, v_quarantine_key, declared_mime, declared_size);
return jsonb_build_object('asset_id', v_id, 'bucket_id', 'avatars', 'quarantine_key', v_quarantine_key);
end;
$$;
comment on function public.begin_avatar_upload(text, integer) is
'Reserves an avatar upload: rate (10 per hour), global ceiling, type and size caps, supersedes any in-flight row of the caller, returns {asset_id, bucket_id, quarantine_key}.';
create or replace function public.confirm_asset_upload(asset_id uuid)
returns void
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_actor uuid := auth.uid();
v_active boolean;
v_row public.assets;
v_size bigint;
v_found boolean;
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
select p.active into v_active from public.profiles p where p.id = v_actor;
if v_active is distinct from true then
raise exception 'account inactive or unknown' using errcode = '42501';
end if;
select a.* into v_row from public.assets a
where a.id = asset_id and a.owner_id = v_actor for update;
if v_row.id is null then
raise exception using message = 'not_found', errcode = 'P0001';
end if;
if v_row.status <> 'pending_upload' then
raise exception using message = 'invalid_state', errcode = 'P0001';
end if;
select true, (o.metadata ->> 'size')::bigint into v_found, v_size
from storage.objects o
where o.bucket_id = v_row.bucket_id and o.name = v_row.quarantine_key;
-- No object, or an object the Storage API has not sized: nothing to confirm (fail closed).
if v_found is distinct from true or v_size is null then
raise exception using message = 'upload_missing', errcode = 'P0001';
end if;
-- The object may not exceed the cap nor what the caller declared (the
-- ceiling counted the declared size).
if v_size > 5242880 or v_size > v_row.declared_size then
raise exception using message = 'too_large', errcode = 'P0001';
end if;
update public.assets a set status = 'uploaded' where a.id = v_row.id;
end;
$$;
comment on function public.confirm_asset_upload(uuid) is
'Explicit client signal: the quarantine object of the caller''s pending_upload row exists → uploaded. The worker never guesses from Storage internals whether a PUT finished.';
create or replace function public.remove_avatar()
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
v_actor uuid := auth.uid();
v_count integer;
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
update public.assets a set status = 'deleted'
where a.owner_id = v_actor and a.kind = 'profile_avatar'
and a.status in ('pending_upload', 'uploaded', 'clean');
get diagnostics v_count = row_count;
if v_count > 0 then
perform private.log_event(
v_actor, 'asset.avatar_removed', 'asset', null, v_actor, null,
jsonb_build_object('count', v_count)
);
end if;
return v_count;
end;
$$;
comment on function public.remove_avatar() is
'Every avatar row of the caller still alive (clean or in flight) → deleted; the objects are purged after the grace period. Audited.';
revoke all on function public.begin_avatar_upload(text, integer) from public, anon;
revoke all on function public.confirm_asset_upload(uuid) from public, anon;
revoke all on function public.remove_avatar() from public, anon;
revoke all on function public.begin_avatar_upload(text, integer) from service_role;
revoke all on function public.confirm_asset_upload(uuid) from service_role;
revoke all on function public.remove_avatar() from service_role;
grant execute on function public.begin_avatar_upload(text, integer) to authenticated;
grant execute on function public.confirm_asset_upload(uuid) to authenticated;
grant execute on function public.remove_avatar() to authenticated;
-- ---------------------------------------------------------------------------
-- Worker RPCs (service_role only; EXECUTE is the guard, as for
-- confirm_sheet_asset_upload).
-- ---------------------------------------------------------------------------
create or replace function public.claim_avatar_jobs(max_jobs integer)
returns table (
asset_id uuid, owner_id uuid, bucket_id text, object_key text,
quarantine_key text, lock_token uuid, attempts smallint
)
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_limit integer := least(greatest(coalesce(max_jobs, 1), 1), 10);
v_expired record;
begin
-- A third expired lease is a refusal: the content or the environment
-- defeated the worker three times.
for v_expired in
update public.assets a
set status = 'rejected', rejection_reason = 'processing_error',
locked_at = null, lock_token = null
where a.status = 'uploaded' and a.attempts >= 3
and a.locked_at is not null and a.locked_at < now() - interval '10 minutes'
returning a.id, a.owner_id
loop
perform private.log_event(
null, 'asset.rejected', 'asset', v_expired.id, v_expired.owner_id, null,
jsonb_build_object('reason', 'processing_error', 'cause', 'lease_expired')
);
end loop;
return query
with claimed as (
select a.id
from public.assets a
where a.status = 'uploaded' and a.attempts < 3
and (a.locked_at is null or a.locked_at < now() - interval '10 minutes')
order by a.created_at
limit v_limit
for update skip locked
)
update public.assets a
set locked_at = now(), attempts = a.attempts + 1, lock_token = gen_random_uuid()
from claimed
where a.id = claimed.id
returning a.id, a.owner_id, a.bucket_id, a.object_key, a.quarantine_key, a.lock_token, a.attempts;
end;
$$;
comment on function public.claim_avatar_jobs(integer) is
'Worker: leases uploaded rows oldest first (skip locked, 10 min lease, 3 attempts); rows past their 3rd expired lease become rejected (processing_error). VOLATILE on purpose.';
create or replace function public.complete_avatar_job(
asset_id uuid, lock_token uuid, byte_size integer, sha256 text
)
returns void
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row public.assets;
begin
select a.* into v_row from public.assets a where a.id = asset_id for update;
if v_row.id is null then
raise exception using message = 'not_found', errcode = 'P0001';
end if;
-- A superseded or removed row is no longer uploaded; an expired lease
-- carries a stale token: both refuse, the purge queue owns any object.
if v_row.status <> 'uploaded' or lock_token is null or v_row.lock_token is distinct from lock_token then
raise exception using message = 'invalid_state', errcode = 'P0001';
end if;
if byte_size is null or byte_size < 1 or byte_size > 524288 or sha256 is null or sha256 !~ '^[0-9a-f]{64}$' then
raise exception using message = 'invalid_output', errcode = 'P0001';
end if;
-- Replacement: the previous clean avatar is enqueued (48 h) by the trigger.
update public.assets a set status = 'deleted'
where a.owner_id = v_row.owner_id and a.kind = v_row.kind
and a.status = 'clean' and a.id <> v_row.id;
update public.assets a
set status = 'clean', byte_size = byte_size, sha256 = sha256,
locked_at = null, lock_token = null
where a.id = v_row.id;
perform private.log_event(
null, 'asset.avatar_set', 'asset', v_row.id, v_row.owner_id, null,
jsonb_build_object('byte_size', byte_size)
);
end;
$$;
comment on function public.complete_avatar_job(uuid, uuid, integer, text) is
'Worker: the clean object is in place → the row becomes clean and the previous clean avatar of the owner is deleted, in one transaction. Refused on any status but uploaded or on a stale lease token.';
create or replace function public.reject_avatar_job(asset_id uuid, lock_token uuid, reason text)
returns void
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_row public.assets;
begin
select a.* into v_row from public.assets a where a.id = asset_id for update;
if v_row.id is null then
raise exception using message = 'not_found', errcode = 'P0001';
end if;
if v_row.status <> 'uploaded' or lock_token is null or v_row.lock_token is distinct from lock_token then
raise exception using message = 'invalid_state', errcode = 'P0001';
end if;
if reason is null or reason not in ('unsupported_type', 'decode_failed', 'dimensions', 'processing_error') then
raise exception using message = 'invalid_reason', errcode = 'P0001';
end if;
update public.assets a
set status = 'rejected', rejection_reason = reason, locked_at = null, lock_token = null
where a.id = v_row.id;
perform private.log_event(
null, 'asset.rejected', 'asset', v_row.id, v_row.owner_id, null,
jsonb_build_object('reason', reason)
);
end;
$$;
comment on function public.reject_avatar_job(uuid, uuid, text) is
'Worker: the upload was refused with a closed code. Same guards as complete_avatar_job.';
create or replace function public.mark_quarantine_purged(asset_id uuid)
returns void
language sql
security definer
set search_path = ''
as $$
update public.assets a set quarantine_key = null
where a.id = asset_id and a.status = 'clean';
$$;
comment on function public.mark_quarantine_purged(uuid) is
'Worker: the quarantine object of a clean row was deleted. No-op on any other status.';
create or replace function public.claim_purges(max_items integer)
returns table (purge_id uuid, bucket_id text, object_name text)
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_limit integer := least(greatest(coalesce(max_items, 1), 1), 100);
begin
return query
with claimed as (
select q.id
from private.object_purge_queue q
where q.not_before <= now()
and (q.locked_at is null or q.locked_at < now() - interval '10 minutes')
order by q.not_before
limit v_limit
for update skip locked
)
update private.object_purge_queue q
set locked_at = now(), attempts = q.attempts + 1
from claimed
where q.id = claimed.id
returning q.id, q.bucket_id, q.object_name;
end;
$$;
comment on function public.claim_purges(integer) is
'Worker: due purge entries (grace elapsed), leased for 10 minutes. Delete the object, then ack_purge.';
create or replace function public.ack_purge(purge_id uuid)
returns void
language sql
security definer
set search_path = ''
as $$
delete from private.object_purge_queue q where q.id = purge_id;
$$;
comment on function public.ack_purge(uuid) is
'Worker: the object of a purge entry is gone (a missing object counts as gone).';
create or replace function public.claim_quarantine_leftovers(older_than_seconds integer, max_items integer)
returns table (bucket_id text, object_name text, asset_id uuid)
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_limit integer := least(greatest(coalesce(max_items, 1), 1), 100);
v_age interval := make_interval(secs => greatest(coalesce(older_than_seconds, 0), 0));
begin
-- Bytes under quarantine/ whose row is no longer waiting for them: a slow
-- PUT or a signed upload URL used after the row moved on, or the
-- quarantine object of a clean row the worker could not delete in time.
return query
select o.bucket_id, o.name, a.id
from storage.objects o
left join public.assets a on a.bucket_id = o.bucket_id and a.quarantine_key = o.name
where o.bucket_id = 'avatars'
and o.name like 'quarantine/%'
and o.created_at <= now() - v_age
and (a.id is null or a.status not in ('pending_upload', 'uploaded'))
order by o.created_at
limit v_limit;
end;
$$;
comment on function public.claim_quarantine_leftovers(integer, integer) is
'Worker sweep: quarantine objects older than the grace whose row is not pending_upload / uploaded. The worker deletes them and calls mark_quarantine_purged when asset_id is set.';
create or replace function public.expire_pending_uploads(max_age_seconds integer)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_count integer;
begin
update public.assets a set status = 'deleted'
where a.status = 'pending_upload'
and a.created_at < now() - make_interval(secs => greatest(coalesce(max_age_seconds, 0), 0));
get diagnostics v_count = row_count;
return v_count;
end;
$$;
comment on function public.expire_pending_uploads(integer) is
'Worker sweep: pending_upload rows never confirmed within the age → deleted (their keys are enqueued by the trigger).';
revoke all on function public.claim_avatar_jobs(integer) from public, anon, authenticated;
revoke all on function public.complete_avatar_job(uuid, uuid, integer, text) from public, anon, authenticated;
revoke all on function public.reject_avatar_job(uuid, uuid, text) from public, anon, authenticated;
revoke all on function public.mark_quarantine_purged(uuid) from public, anon, authenticated;
revoke all on function public.claim_purges(integer) from public, anon, authenticated;
revoke all on function public.ack_purge(uuid) from public, anon, authenticated;
revoke all on function public.claim_quarantine_leftovers(integer, integer) from public, anon, authenticated;
revoke all on function public.expire_pending_uploads(integer) from public, anon, authenticated;
grant execute on function public.claim_avatar_jobs(integer) to service_role;
grant execute on function public.complete_avatar_job(uuid, uuid, integer, text) to service_role;
grant execute on function public.reject_avatar_job(uuid, uuid, text) to service_role;
grant execute on function public.mark_quarantine_purged(uuid) to service_role;
grant execute on function public.claim_purges(integer) to service_role;
grant execute on function public.ack_purge(uuid) to service_role;
grant execute on function public.claim_quarantine_leftovers(integer, integer) to service_role;
grant execute on function public.expire_pending_uploads(integer) to service_role;