-- 0003 (lab 3, track 1 improvement): the whole idempotent "send message" as ONE statement. -- Additive (a new function), so replicas of the previous version keep working while it is -- applied, and the previous write path (MESSAGE_WRITE_PATH=multi) stays usable for A/B runs. -- -- Same semantics and the same SQL as repo.post_message (multi-statement path), but executed -- inside the server: the API sends one call instead of ~11 round trips in two transactions -- (membership check, BEGIN, key claim, chat clock, message, COMMIT, pool checks). Called in -- autocommit mode, so the function call IS the transaction: key row, chat clock and message -- commit together or not at all. VOLATILE + READ COMMITTED: every statement inside takes a -- fresh snapshot, so after waiting on a concurrent claim of the same key the stored result -- of the winner is visible, exactly as in the multi-statement path. -- -- o_status: created | replayed | conflict | not_found | retry (key vanished in between: cleanup) CREATE FUNCTION post_message(p_user uuid, p_chat uuid, p_key text, p_hash bytea, p_message uuid, p_text bytea, p_ttl_seconds integer) RETURNS TABLE (o_status text, o_id uuid, o_text bytea, o_created_at timestamptz) LANGUAGE plpgsql VOLATILE AS $$ DECLARE v_created timestamptz; BEGIN PERFORM 1 FROM chat_members m WHERE m.chat_id = p_chat AND m.user_id = p_user; IF NOT FOUND THEN RETURN QUERY SELECT 'not_found'::text, NULL::uuid, NULL::bytea, NULL::timestamptz; RETURN; END IF; INSERT INTO idempotency_keys AS k (user_id, chat_id, key, request_hash, message_id) VALUES (p_user, p_chat, p_key, p_hash, p_message) ON CONFLICT (user_id, chat_id, key) DO UPDATE SET request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() WHERE k.created_at < clock_timestamp() - make_interval(secs => p_ttl_seconds); IF FOUND THEN -- Per-chat clock under the chat row lock (see migrations/0001 and docs/DATA_MODEL.md). UPDATE chats c SET last_message_at = greatest(clock_timestamp(), c.last_message_at + interval '1 microsecond') WHERE c.id = p_chat RETURNING c.last_message_at INTO v_created; INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (p_message, p_chat, p_user, p_text, v_created); RETURN QUERY SELECT 'created'::text, p_message, p_text, v_created; RETURN; END IF; RETURN QUERY SELECT CASE WHEN k.request_hash = p_hash THEN 'replayed' ELSE 'conflict' END, m.id, m.text, m.created_at FROM idempotency_keys k JOIN messages m ON m.id = k.message_id WHERE k.user_id = p_user AND k.chat_id = p_chat AND k.key = p_key; IF NOT FOUND THEN RETURN QUERY SELECT 'retry'::text, NULL::uuid, NULL::bytea, NULL::timestamptz; END IF; END $$;