Prepare verified laboratory 6 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 470d9d6f1e
commit 7d56e52fd0
335 changed files with 31206 additions and 72 deletions
@@ -0,0 +1,199 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: attachments.sql
package queries
import (
"context"
"github.com/google/uuid"
)
const chargeAttachment = `-- name: ChargeAttachment :one
UPDATE users SET attachment_count=attachment_count+1 WHERE id=$1 AND attachment_count<10000 RETURNING id
`
func (q *Queries) ChargeAttachment(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeAttachment, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const getAttachment = `-- name: GetAttachment :one
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at FROM attachments WHERE id=$1 FOR SHARE
`
func (q *Queries) GetAttachment(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachment, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const insertAttachment = `-- name: InsertAttachment :one
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status)
VALUES($1,$2,$3,$4,$5,$6,$7,'uploading') RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at
`
type InsertAttachmentParams struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
Sha256 string
}
func (q *Queries) InsertAttachment(ctx context.Context, arg InsertAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, insertAttachment,
arg.ID,
arg.ChatID,
arg.OwnerID,
arg.Filename,
arg.ContentType,
arg.SizeBytes,
arg.Sha256,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const insertMessageAttachment = `-- name: InsertMessageAttachment :exec
INSERT INTO message_attachments(message_id,attachment_id,ordinal) VALUES($1,$2,$3)
`
type InsertMessageAttachmentParams struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Ordinal int32
}
func (q *Queries) InsertMessageAttachment(ctx context.Context, arg InsertMessageAttachmentParams) error {
_, err := q.db.Exec(ctx, insertMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Ordinal)
return err
}
const messageAttachments = `-- name: MessageAttachments :many
SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY ordinal LIMIT 10
`
func (q *Queries) MessageAttachments(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, messageAttachments, messageID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var attachment_id uuid.UUID
if err := rows.Scan(&attachment_id); err != nil {
return nil, err
}
items = append(items, attachment_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const reconcileAttachments = `-- name: ReconcileAttachments :many
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at FROM attachments WHERE id>$1 ORDER BY id LIMIT 101
`
func (q *Queries) ReconcileAttachments(ctx context.Context, id uuid.UUID) ([]Attachment, error) {
rows, err := q.db.Query(ctx, reconcileAttachments, id)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
for rows.Next() {
var i Attachment
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setAttachmentStatus = `-- name: SetAttachmentStatus :execrows
UPDATE attachments SET status=$2,updated_at=clock_timestamp() WHERE id=$1 AND status=$3 AND pipeline_version=0
`
type SetAttachmentStatusParams struct {
ID uuid.UUID
Status string
Status_2 string
}
func (q *Queries) SetAttachmentStatus(ctx context.Context, arg SetAttachmentStatusParams) (int64, error) {
result, err := q.db.Exec(ctx, setAttachmentStatus, arg.ID, arg.Status, arg.Status_2)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -0,0 +1,358 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: core.sql
package queries
import (
"context"
"time"
"github.com/google/uuid"
)
const authenticateSession = `-- name: AuthenticateSession :one
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()
`
func (q *Queries) AuthenticateSession(ctx context.Context, tokenHash string) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, authenticateSession, tokenHash)
var user_id uuid.UUID
err := row.Scan(&user_id)
return user_id, err
}
const chargeChat = `-- name: ChargeChat :one
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id
`
func (q *Queries) ChargeChat(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeChat, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const chargeMessage = `-- name: ChargeMessage :one
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id
`
func (q *Queries) ChargeMessage(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeMessage, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const createUser = `-- name: CreateUser :one
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
RETURNING id,username,display_name,created_at
`
type CreateUserParams struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
}
type CreateUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
row := q.db.QueryRow(ctx, createUser,
arg.ID,
arg.Username,
arg.DisplayName,
arg.PasswordHash,
)
var i CreateUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const credentials = `-- name: Credentials :one
SELECT id,password_hash FROM users WHERE username=$1
`
type CredentialsRow struct {
ID uuid.UUID
PasswordHash string
}
func (q *Queries) Credentials(ctx context.Context, username string) (CredentialsRow, error) {
row := q.db.QueryRow(ctx, credentials, username)
var i CredentialsRow
err := row.Scan(&i.ID, &i.PasswordHash)
return i, err
}
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp()
`
func (q *Queries) DeleteExpiredSessions(ctx context.Context, userID uuid.UUID) error {
_, err := q.db.Exec(ctx, deleteExpiredSessions, userID)
return err
}
const getChat = `-- name: GetChat :one
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
FROM chats c WHERE c.id=$1
`
type GetChatRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
Members []uuid.UUID
}
func (q *Queries) GetChat(ctx context.Context, id uuid.UUID) (GetChatRow, error) {
row := q.db.QueryRow(ctx, getChat, id)
var i GetChatRow
err := row.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.Members,
)
return i, err
}
const getUser = `-- name: GetUser :one
SELECT id,username,display_name,created_at FROM users WHERE id=$1
`
type GetUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) {
row := q.db.QueryRow(ctx, getUser, id)
var i GetUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const insertChat = `-- name: InsertChat :one
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at
`
type InsertChatParams struct {
ID uuid.UUID
Title string
}
func (q *Queries) InsertChat(ctx context.Context, arg InsertChatParams) (Chat, error) {
row := q.db.QueryRow(ctx, insertChat, arg.ID, arg.Title)
var i Chat
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
return i, err
}
const insertMembers = `-- name: InsertMembers :exec
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])
`
type InsertMembersParams struct {
ChatID uuid.UUID
Column2 []uuid.UUID
}
func (q *Queries) InsertMembers(ctx context.Context, arg InsertMembersParams) error {
_, err := q.db.Exec(ctx, insertMembers, arg.ChatID, arg.Column2)
return err
}
const insertMessage = `-- name: InsertMessage :one
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at
`
type InsertMessageParams struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
}
func (q *Queries) InsertMessage(ctx context.Context, arg InsertMessageParams) (Message, error) {
row := q.db.QueryRow(ctx, insertMessage,
arg.ID,
arg.ChatID,
arg.SenderID,
arg.Text,
)
var i Message
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
const insertSession = `-- name: InsertSession :one
INSERT INTO sessions(token_hash,user_id,expires_at)
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
RETURNING user_id
`
type InsertSessionParams struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, insertSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
var user_id uuid.UUID
err := row.Scan(&user_id)
return user_id, err
}
const listChats = `-- name: ListChats :many
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
FROM chats c JOIN chat_members m ON m.chat_id=c.id
WHERE m.user_id=$1 AND (c.created_at,c.id)>($2::timestamptz,$3::uuid)
ORDER BY c.created_at,c.id LIMIT $4
`
type ListChatsParams struct {
MemberID uuid.UUID
AfterTime time.Time
AfterID uuid.UUID
PageLimit int32
}
type ListChatsRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
Members []uuid.UUID
}
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
rows, err := q.db.Query(ctx, listChats,
arg.MemberID,
arg.AfterTime,
arg.AfterID,
arg.PageLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsRow{}
for rows.Next() {
var i ListChatsRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.Members,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessages = `-- name: ListMessages :many
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
FROM messages m WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2::timestamptz,$3::uuid)
ORDER BY m.created_at,m.id LIMIT $4
`
type ListMessagesParams struct {
ChatID uuid.UUID
AfterTime time.Time
AfterID uuid.UUID
PageLimit int32
}
type ListMessagesRow struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
AttachmentIds []uuid.UUID
}
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]ListMessagesRow, error) {
rows, err := q.db.Query(ctx, listMessages,
arg.ChatID,
arg.AfterTime,
arg.AfterID,
arg.PageLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListMessagesRow{}
for rows.Next() {
var i ListMessagesRow
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
&i.AttachmentIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSessionOwner = `-- name: LockSessionOwner :one
SELECT id FROM users WHERE id=$1 FOR UPDATE
`
func (q *Queries) LockSessionOwner(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, lockSessionOwner, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const revokeSession = `-- name: RevokeSession :exec
DELETE FROM sessions WHERE token_hash=$1
`
func (q *Queries) RevokeSession(ctx context.Context, tokenHash string) error {
_, err := q.db.Exec(ctx, revokeSession, tokenHash)
return err
}
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package queries
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,81 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: idempotency.sql
package queries
import (
"context"
"time"
"github.com/google/uuid"
)
const replayMessage = `-- name: ReplayMessage :one
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,i.payload_hash,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
FROM idempotency i JOIN messages m ON m.id=i.message_id
WHERE i.user_id=$1 AND i.chat_id=$2 AND i.key=$3
`
type ReplayMessageParams struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
}
type ReplayMessageRow struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
PayloadHash string
AttachmentIds []uuid.UUID
}
func (q *Queries) ReplayMessage(ctx context.Context, arg ReplayMessageParams) (ReplayMessageRow, error) {
row := q.db.QueryRow(ctx, replayMessage, arg.UserID, arg.ChatID, arg.Key)
var i ReplayMessageRow
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
&i.PayloadHash,
&i.AttachmentIds,
)
return i, err
}
const reserveKey = `-- name: ReserveKey :one
INSERT INTO idempotency(user_id,chat_id,key,payload_hash,message_id,expires_at)
VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
ON CONFLICT(user_id,chat_id,key) DO UPDATE SET payload_hash=excluded.payload_hash,
message_id=excluded.message_id,expires_at=excluded.expires_at
WHERE idempotency.expires_at<=clock_timestamp()
RETURNING message_id
`
type ReserveKeyParams struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
PayloadHash string
MessageID uuid.UUID
}
func (q *Queries) ReserveKey(ctx context.Context, arg ReserveKeyParams) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, reserveKey,
arg.UserID,
arg.ChatID,
arg.Key,
arg.PayloadHash,
arg.MessageID,
)
var message_id uuid.UUID
err := row.Scan(&message_id)
return message_id, err
}
@@ -0,0 +1,100 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package queries
import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
)
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
PipelineVersion int32
ErrorCode string
Variants []byte
StagingExpired bool
StagingCleaned bool
CreatedAt time.Time
UpdatedAt time.Time
AcceptedAt pgtype.Timestamptz
FirstReadyAt pgtype.Timestamptz
}
type AttachmentJob struct {
ID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int32
Attempt int32
Traceparent string
Tracestate string
LeaseID uuid.UUID
LeaseUntil time.Time
NextAttempt time.Time
PublishedAt time.Time
Completed bool
CreatedAt time.Time
ReplayCount int64
ReplayedAt time.Time
}
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
}
type Idempotency struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
PayloadHash string
MessageID uuid.UUID
ExpiresAt time.Time
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type MessageAttachment struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Ordinal int32
}
type Session struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
type User struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
ChatCount int32
MessageCount int32
AttachmentCount int32
}
@@ -0,0 +1,29 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: observability.sql
package queries
import (
"context"
)
const pipelineMetrics = `-- name: PipelineMetrics :one
SELECT count(*)::bigint AS depth,
COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(j.created_at)),0)::float8 AS oldest
FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
WHERE a.status IN ('queued','processing') AND NOT j.completed
`
type PipelineMetricsRow struct {
Depth int64
Oldest float64
}
func (q *Queries) PipelineMetrics(ctx context.Context) (PipelineMetricsRow, error) {
row := q.db.QueryRow(ctx, pipelineMetrics)
var i PipelineMetricsRow
err := row.Scan(&i.Depth, &i.Oldest)
return i, err
}
@@ -0,0 +1,403 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: pipeline.sql
package queries
import (
"context"
"github.com/google/uuid"
)
const acquireJob = `-- name: AcquireJob :one
UPDATE attachment_jobs j SET attempt=j.attempt+1,lease_id=$1,lease_until=clock_timestamp()+$2::int*interval '1 second'
WHERE j.id=$3 AND j.pipeline_version=$4 AND NOT j.completed
AND j.next_attempt<=clock_timestamp() AND j.lease_until<clock_timestamp()
AND EXISTS(SELECT 1 FROM attachments a WHERE a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version AND a.status IN ('queued','processing'))
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempt, j.traceparent, j.tracestate, j.lease_id, j.lease_until, j.next_attempt, j.published_at, j.completed, j.created_at, j.replay_count, j.replayed_at
`
type AcquireJobParams struct {
LeaseID uuid.UUID
LeaseSeconds int32
JobID uuid.UUID
PipelineVersion int32
}
func (q *Queries) AcquireJob(ctx context.Context, arg AcquireJobParams) (AttachmentJob, error) {
row := q.db.QueryRow(ctx, acquireJob,
arg.LeaseID,
arg.LeaseSeconds,
arg.JobID,
arg.PipelineVersion,
)
var i AttachmentJob
err := row.Scan(
&i.ID,
&i.AttachmentID,
&i.PipelineVersion,
&i.Attempt,
&i.Traceparent,
&i.Tracestate,
&i.LeaseID,
&i.LeaseUntil,
&i.NextAttempt,
&i.PublishedAt,
&i.Completed,
&i.CreatedAt,
&i.ReplayCount,
&i.ReplayedAt,
)
return i, err
}
const advancePipeline = `-- name: AdvancePipeline :one
UPDATE attachments SET status='queued',error_code='',variants='[]',pipeline_version=pipeline_version+1,staging_expired=false,updated_at=clock_timestamp() WHERE id=$1 AND (status='ready' OR (status='failed' AND NOT staging_expired)) RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at
`
func (q *Queries) AdvancePipeline(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, advancePipeline, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const completeAttachment = `-- name: CompleteAttachment :execrows
UPDATE attachments a SET first_ready_at=COALESCE(a.first_ready_at,clock_timestamp()),status='ready',variants=$1::jsonb,error_code='',updated_at=clock_timestamp()
FROM attachment_jobs j WHERE j.id=$2 AND j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
AND j.lease_id=$3 AND j.lease_until>clock_timestamp() AND NOT j.completed AND a.status='processing'
`
type CompleteAttachmentParams struct {
Variants []byte
JobID uuid.UUID
LeaseID uuid.UUID
}
func (q *Queries) CompleteAttachment(ctx context.Context, arg CompleteAttachmentParams) (int64, error) {
result, err := q.db.Exec(ctx, completeAttachment, arg.Variants, arg.JobID, arg.LeaseID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const completeJob = `-- name: CompleteJob :exec
UPDATE attachment_jobs SET completed=true,lease_until='epoch' WHERE id=$1 AND lease_id=$2
`
type CompleteJobParams struct {
JobID uuid.UUID
LeaseID uuid.UUID
}
func (q *Queries) CompleteJob(ctx context.Context, arg CompleteJobParams) error {
_, err := q.db.Exec(ctx, completeJob, arg.JobID, arg.LeaseID)
return err
}
const insertJob = `-- name: InsertJob :exec
INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,traceparent,tracestate)
VALUES($1,$2,$3,$4,$5)
`
type InsertJobParams struct {
JobID uuid.UUID
AttachmentID uuid.UUID
PipelineVersion int32
Traceparent string
Tracestate string
}
func (q *Queries) InsertJob(ctx context.Context, arg InsertJobParams) error {
_, err := q.db.Exec(ctx, insertJob,
arg.JobID,
arg.AttachmentID,
arg.PipelineVersion,
arg.Traceparent,
arg.Tracestate,
)
return err
}
const pendingJobs = `-- name: PendingJobs :many
SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt, j.traceparent, j.tracestate, j.lease_id, j.lease_until, j.next_attempt, j.published_at, j.completed, j.created_at, j.replay_count, j.replayed_at FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version
WHERE NOT j.completed AND a.status IN ('queued','processing') AND j.next_attempt<=clock_timestamp()
AND j.lease_until<clock_timestamp() AND j.published_at<clock_timestamp()-interval '2 seconds'
ORDER BY j.created_at,j.id LIMIT 100
`
func (q *Queries) PendingJobs(ctx context.Context) ([]AttachmentJob, error) {
rows, err := q.db.Query(ctx, pendingJobs)
if err != nil {
return nil, err
}
defer rows.Close()
items := []AttachmentJob{}
for rows.Next() {
var i AttachmentJob
if err := rows.Scan(
&i.ID,
&i.AttachmentID,
&i.PipelineVersion,
&i.Attempt,
&i.Traceparent,
&i.Tracestate,
&i.LeaseID,
&i.LeaseUntil,
&i.NextAttempt,
&i.PublishedAt,
&i.Completed,
&i.CreatedAt,
&i.ReplayCount,
&i.ReplayedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const processingAttachment = `-- name: ProcessingAttachment :one
UPDATE attachments SET status='processing',updated_at=clock_timestamp()
WHERE id=$1 AND pipeline_version=$2 AND status IN ('queued','processing') RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at
`
type ProcessingAttachmentParams struct {
AttachmentID uuid.UUID
PipelineVersion int32
}
func (q *Queries) ProcessingAttachment(ctx context.Context, arg ProcessingAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, processingAttachment, arg.AttachmentID, arg.PipelineVersion)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const published = `-- name: Published :exec
UPDATE attachment_jobs SET published_at=clock_timestamp() WHERE id=$1
`
func (q *Queries) Published(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, published, id)
return err
}
const queueAttachment = `-- name: QueueAttachment :one
UPDATE attachments SET accepted_at=COALESCE(accepted_at,clock_timestamp()),status='queued',updated_at=clock_timestamp() WHERE id=$1 AND status='uploading' AND NOT staging_expired RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at
`
func (q *Queries) QueueAttachment(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, queueAttachment, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const replayAttachment = `-- name: ReplayAttachment :one
UPDATE attachments SET status='queued',error_code='',updated_at=clock_timestamp() WHERE id=$1 AND status='failed' AND NOT staging_expired RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, pipeline_version, error_code, variants, staging_expired, staging_cleaned, created_at, updated_at, accepted_at, first_ready_at
`
func (q *Queries) ReplayAttachment(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, replayAttachment, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
)
return i, err
}
const replayJobs = `-- name: ReplayJobs :exec
UPDATE attachment_jobs SET replay_count=replay_count+1,replayed_at=clock_timestamp(),completed=false,attempt=0,lease_until='epoch',next_attempt='epoch',published_at='epoch' WHERE attachment_id=$1 AND pipeline_version=$2
`
type ReplayJobsParams struct {
AttachmentID uuid.UUID
PipelineVersion int32
}
func (q *Queries) ReplayJobs(ctx context.Context, arg ReplayJobsParams) error {
_, err := q.db.Exec(ctx, replayJobs, arg.AttachmentID, arg.PipelineVersion)
return err
}
const retryAttachment = `-- name: RetryAttachment :execrows
UPDATE attachments a SET status=$1,error_code=$2,updated_at=clock_timestamp()
FROM attachment_jobs j WHERE j.id=$3 AND j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
AND j.lease_id=$4 AND j.lease_until>clock_timestamp() AND NOT j.completed AND a.status='processing'
`
type RetryAttachmentParams struct {
NextStatus string
ErrorCode string
JobID uuid.UUID
LeaseID uuid.UUID
}
func (q *Queries) RetryAttachment(ctx context.Context, arg RetryAttachmentParams) (int64, error) {
result, err := q.db.Exec(ctx, retryAttachment,
arg.NextStatus,
arg.ErrorCode,
arg.JobID,
arg.LeaseID,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const retryJob = `-- name: RetryJob :exec
UPDATE attachment_jobs SET lease_until='epoch',next_attempt=clock_timestamp()+$1::int*interval '1 millisecond',completed=$2
WHERE id=$3 AND lease_id=$4
`
type RetryJobParams struct {
DelayMs int32
Completed bool
JobID uuid.UUID
LeaseID uuid.UUID
}
func (q *Queries) RetryJob(ctx context.Context, arg RetryJobParams) error {
_, err := q.db.Exec(ctx, retryJob,
arg.DelayMs,
arg.Completed,
arg.JobID,
arg.LeaseID,
)
return err
}
const stagingCleaned = `-- name: StagingCleaned :exec
UPDATE attachments SET staging_cleaned=true WHERE id=$1 AND (staging_expired OR status='ready')
`
func (q *Queries) StagingCleaned(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, stagingCleaned, id)
return err
}
const stagingCleanup = `-- name: StagingCleanup :many
WITH candidates AS (
SELECT id FROM attachments WHERE NOT staging_cleaned AND (status='ready' OR (status IN ('failed','uploading') AND updated_at<clock_timestamp()-interval '24 hours'))
ORDER BY updated_at,id LIMIT 20
)
UPDATE attachments a SET staging_expired=(a.status<>'ready') FROM candidates c WHERE a.id=c.id AND NOT a.staging_cleaned
AND (a.status='ready' OR (a.status IN ('failed','uploading') AND a.updated_at<clock_timestamp()-interval '24 hours')) RETURNING a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.pipeline_version, a.error_code, a.variants, a.staging_expired, a.staging_cleaned, a.created_at, a.updated_at, a.accepted_at, a.first_ready_at
`
func (q *Queries) StagingCleanup(ctx context.Context) ([]Attachment, error) {
rows, err := q.db.Query(ctx, stagingCleanup)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
for rows.Next() {
var i Attachment
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.PipelineVersion,
&i.ErrorCode,
&i.Variants,
&i.StagingExpired,
&i.StagingCleaned,
&i.CreatedAt,
&i.UpdatedAt,
&i.AcceptedAt,
&i.FirstReadyAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,46 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: slo.sql
package queries
import (
"context"
)
const readySLI = `-- name: ReadySLI :one
WITH clock AS (SELECT clock_timestamp() AS now), cohort AS (
SELECT a.accepted_at,a.first_ready_at,c.now FROM attachments a CROSS JOIN clock c
WHERE a.accepted_at>c.now-interval '310 seconds' AND a.accepted_at<=c.now-interval '10 seconds'
)
SELECT count(*) FILTER(WHERE accepted_at>now-interval '20 seconds')::bigint AS matured10,
count(*) FILTER(WHERE accepted_at>now-interval '20 seconds' AND first_ready_at>=accepted_at AND first_ready_at<=accepted_at+interval '10 seconds')::bigint AS timely10,
count(*) FILTER(WHERE accepted_at>now-interval '40 seconds')::bigint AS matured30,
count(*) FILTER(WHERE accepted_at>now-interval '40 seconds' AND first_ready_at>=accepted_at AND first_ready_at<=accepted_at+interval '10 seconds')::bigint AS timely30,
count(*)::bigint AS matured300,
count(*) FILTER(WHERE first_ready_at>=accepted_at AND first_ready_at<=accepted_at+interval '10 seconds')::bigint AS timely300 FROM cohort
`
type ReadySLIRow struct {
Matured10 int64
Timely10 int64
Matured30 int64
Timely30 int64
Matured300 int64
Timely300 int64
}
func (q *Queries) ReadySLI(ctx context.Context) (ReadySLIRow, error) {
row := q.db.QueryRow(ctx, readySLI)
var i ReadySLIRow
err := row.Scan(
&i.Matured10,
&i.Timely10,
&i.Matured30,
&i.Timely30,
&i.Matured300,
&i.Timely300,
)
return i, err
}