Prepare verified laboratory 5 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:32:06 +03:00
parent 276dbdad8a
commit 57a253e0b4
122 changed files with 13404 additions and 72 deletions
@@ -0,0 +1,57 @@
package postgres
import (
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"context"
"encoding/json"
"github.com/google/uuid"
)
func attachment(r queries.Attachment) model.Attachment {
var variants []model.Variant
_ = json.Unmarshal(r.Variants, &variants)
return model.Attachment{ID: r.ID, ChatID: r.ChatID, OwnerID: r.OwnerID, Filename: r.Filename, ContentType: r.ContentType, SizeBytes: r.SizeBytes, SHA256: r.Sha256, Status: r.Status, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, PipelineVersion: r.PipelineVersion, ErrorCode: r.ErrorCode, Variants: variants, StagingExpired: r.StagingExpired, StagingCleaned: r.StagingCleaned}
}
func (s *Store) ReserveAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return model.Attachment{}, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, e = q.ChargeAttachment(ctx, a.OwnerID); e != nil {
return model.Attachment{}, model.ErrStorageFull
}
r, e := q.InsertAttachment(ctx, queries.InsertAttachmentParams{ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename, ContentType: a.ContentType, SizeBytes: a.SizeBytes, Sha256: a.SHA256})
if e != nil {
return model.Attachment{}, mapErr(e)
}
if e = tx.Commit(ctx); e != nil {
return model.Attachment{}, mapErr(e)
}
return attachment(r), nil
}
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (model.Attachment, error) {
r, e := s.q.GetAttachment(ctx, id)
return attachment(r), mapErr(e)
}
func (s *Store) SetAttachmentStatus(ctx context.Context, id uuid.UUID, from, to string) (bool, error) {
n, e := s.q.SetAttachmentStatus(ctx, queries.SetAttachmentStatusParams{ID: id, Status: to, Status_2: from})
return n == 1, mapErr(e)
}
func (s *Store) ReconcileAttachments(ctx context.Context, after uuid.UUID) ([]model.Attachment, bool, error) {
rows, e := s.q.ReconcileAttachments(ctx, after)
if e != nil {
return nil, false, mapErr(e)
}
more := len(rows) > 100
if more {
rows = rows[:100]
}
out := make([]model.Attachment, len(rows))
for i, r := range rows {
out[i] = attachment(r)
}
return out, more, nil
}
@@ -0,0 +1,171 @@
package postgres
import (
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"context"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
func job(r queries.AttachmentJob) model.Job {
return model.Job{ID: r.ID, AttachmentID: r.AttachmentID, PipelineVersion: r.PipelineVersion, Attempt: r.Attempt, CreatedAt: r.CreatedAt, Traceparent: r.Traceparent, Tracestate: r.Tracestate}
}
func (s *Store) QueueAttachment(ctx context.Context, a model.Attachment, tp, ts string) (model.Attachment, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return model.Attachment{}, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
r, e := q.QueueAttachment(ctx, a.ID)
if e != nil {
return model.Attachment{}, mapErr(e)
}
if e = q.InsertJob(ctx, queries.InsertJobParams{JobID: uuid.New(), AttachmentID: r.ID, PipelineVersion: r.PipelineVersion, Traceparent: tp, Tracestate: ts}); e != nil {
return model.Attachment{}, mapErr(e)
}
if e = tx.Commit(ctx); e != nil {
return model.Attachment{}, mapErr(e)
}
return attachment(r), nil
}
func (s *Store) PendingJobs(ctx context.Context) ([]model.Job, error) {
rows, e := s.q.PendingJobs(ctx)
if e != nil {
return nil, mapErr(e)
}
out := make([]model.Job, len(rows))
for i, r := range rows {
out[i] = job(r)
}
return out, nil
}
func (s *Store) Published(ctx context.Context, id uuid.UUID) error {
return mapErr(s.q.Published(ctx, id))
}
func (s *Store) AcquireJob(ctx context.Context, j model.Job, lease uuid.UUID, d time.Duration) (model.Job, model.Attachment, bool, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return j, model.Attachment{}, false, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
r, e := q.AcquireJob(ctx, queries.AcquireJobParams{LeaseID: lease, LeaseSeconds: int32(d / time.Second), JobID: j.ID, PipelineVersion: j.PipelineVersion})
if errors.Is(e, pgx.ErrNoRows) {
return j, model.Attachment{}, false, nil
}
if e != nil {
return j, model.Attachment{}, false, mapErr(e)
}
a, e := q.ProcessingAttachment(ctx, queries.ProcessingAttachmentParams{AttachmentID: r.AttachmentID, PipelineVersion: r.PipelineVersion})
if e != nil {
return j, model.Attachment{}, false, mapErr(e)
}
if e = tx.Commit(ctx); e != nil {
return j, model.Attachment{}, false, mapErr(e)
}
return job(r), attachment(a), true, nil
}
func (s *Store) CompleteJob(ctx context.Context, j model.Job, lease uuid.UUID, v []model.Variant) (bool, error) {
raw, e := json.Marshal(v)
if e != nil {
return false, e
}
tx, e := s.pool.Begin(ctx)
if e != nil {
return false, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
n, e := q.CompleteAttachment(ctx, queries.CompleteAttachmentParams{Variants: raw, JobID: j.ID, LeaseID: lease})
if e != nil {
return false, mapErr(e)
}
if n != 1 {
return false, nil
}
if e = q.CompleteJob(ctx, queries.CompleteJobParams{JobID: j.ID, LeaseID: lease}); e != nil {
return false, mapErr(e)
}
return true, mapErr(tx.Commit(ctx))
}
func (s *Store) RetryJob(ctx context.Context, j model.Job, lease uuid.UUID, code string, delay time.Duration, failed bool) error {
status := "queued"
if failed {
status = "failed"
}
tx, e := s.pool.Begin(ctx)
if e != nil {
return mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
n, e := q.RetryAttachment(ctx, queries.RetryAttachmentParams{NextStatus: status, ErrorCode: code, JobID: j.ID, LeaseID: lease})
if e != nil {
return mapErr(e)
}
if n == 0 {
return nil
}
if e = q.RetryJob(ctx, queries.RetryJobParams{DelayMs: int32(delay / time.Millisecond), Completed: failed, JobID: j.ID, LeaseID: lease}); e != nil {
return mapErr(e)
}
return mapErr(tx.Commit(ctx))
}
func (s *Store) ReplayJob(ctx context.Context, id uuid.UUID) (bool, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return false, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
a, e := q.ReplayAttachment(ctx, id)
if errors.Is(e, pgx.ErrNoRows) {
return false, nil
}
if e != nil {
return false, mapErr(e)
}
if e = q.ReplayJobs(ctx, queries.ReplayJobsParams{AttachmentID: id, PipelineVersion: a.PipelineVersion}); e != nil {
return false, mapErr(e)
}
return true, mapErr(tx.Commit(ctx))
}
func (s *Store) AdvancePipeline(ctx context.Context, id uuid.UUID) (bool, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return false, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
a, e := q.AdvancePipeline(ctx, id)
if errors.Is(e, pgx.ErrNoRows) {
return false, nil
}
if e != nil {
return false, mapErr(e)
}
if e = q.InsertJob(ctx, queries.InsertJobParams{JobID: uuid.New(), AttachmentID: id, PipelineVersion: a.PipelineVersion}); e != nil {
return false, mapErr(e)
}
return true, mapErr(tx.Commit(ctx))
}
func (s *Store) StagingCleanup(ctx context.Context) ([]model.Attachment, error) {
rows, e := s.q.StagingCleanup(ctx)
if e != nil {
return nil, mapErr(e)
}
out := make([]model.Attachment, len(rows))
for i, r := range rows {
out[i] = attachment(r)
}
return out, nil
}
func (s *Store) StagingCleaned(ctx context.Context, id uuid.UUID) error {
return mapErr(s.q.StagingCleaned(ctx, id))
}
@@ -0,0 +1,331 @@
package postgres
import (
"backend/internal/adapter/storage"
"backend/internal/application/usecase"
"backend/internal/config"
"backend/internal/domain/model"
"backend/internal/domain/port"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"io"
"os"
"reflect"
"sync"
"syscall"
"testing"
"time"
)
func TestReplayAfterCompletedPreviousVersionCleanup(t *testing.T) {
if os.Getenv("RUN_PIPELINE_DB_TESTS") != "1" {
t.Skip("explicit isolated database required")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
raw, e := config.ReadSecret("/run/secrets/database_url")
if e != nil {
t.Fatal("database file unavailable")
}
pool, e := pgxpool.New(ctx, raw)
if e != nil {
t.Fatal("database connection unavailable")
}
defer pool.Close()
s := New(pool, nil)
user, e := s.CreateUser(ctx, model.UserDraft{Username: "v2_" + uuid.NewString()[:8], DisplayName: "Synthetic version test", PasswordHash: "disabled-synthetic"})
if e != nil {
t.Fatal(e)
}
var chatID, attachmentID uuid.UUID
defer func() {
cleanup, c := context.WithTimeout(context.Background(), 5*time.Second)
defer c()
for _, q := range []struct {
sql string
id uuid.UUID
}{{"DELETE FROM attachment_jobs WHERE attachment_id=$1", attachmentID}, {"DELETE FROM attachments WHERE id=$1", attachmentID}, {"DELETE FROM chat_members WHERE chat_id=$1", chatID}, {"DELETE FROM chats WHERE id=$1", chatID}, {"DELETE FROM users WHERE id=$1", user.ID}} {
if _, e := pool.Exec(cleanup, q.sql, q.id); e != nil {
t.Error("version fixture cleanup failed")
}
}
}()
chat, e := s.CreateChat(ctx, model.ChatDraft{Title: "Owned version fixture", Creator: user.ID, MemberIDs: []uuid.UUID{user.ID}})
if e != nil {
t.Fatal(e)
}
chatID = chat.ID
attachmentID = uuid.New()
a, e := s.ReserveAttachment(ctx, model.Attachment{ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: "test.png", ContentType: "image/png", SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"})
if e != nil {
t.Fatal(e)
}
if _, e = s.QueueAttachment(ctx, a, "", ""); e != nil {
t.Fatal(e)
}
jobs, e := s.PendingJobs(ctx)
if e != nil {
t.Fatal(e)
}
var j model.Job
for _, candidate := range jobs {
if candidate.AttachmentID == attachmentID {
j = candidate
}
}
lease := uuid.New()
j, _, ok, e := s.AcquireJob(ctx, j, lease, 30*time.Second)
if e != nil || !ok {
t.Fatal("version1 acquisition failed")
}
if ok, e = s.CompleteJob(ctx, j, lease, []model.Variant{}); e != nil || !ok {
t.Fatal("version1 completion failed")
}
if _, e = s.StagingCleanup(ctx); e != nil {
t.Fatal(e)
}
if e = s.StagingCleaned(ctx, attachmentID); e != nil {
t.Fatal(e)
}
if ok, e = s.AdvancePipeline(ctx, attachmentID); e != nil || !ok {
t.Fatal("version2 advance failed")
}
jobs, e = s.PendingJobs(ctx)
if e != nil {
t.Fatal(e)
}
for _, candidate := range jobs {
if candidate.AttachmentID == attachmentID && candidate.PipelineVersion == 2 {
j = candidate
}
}
lease = uuid.New()
j, _, ok, e = s.AcquireJob(ctx, j, lease, 30*time.Second)
if e != nil || !ok {
t.Fatal("version2 acquisition failed")
}
if e = s.RetryJob(ctx, j, lease, "retry_exhausted", 0, true); e != nil {
t.Fatal(e)
}
ok, e = s.ReplayJob(ctx, attachmentID)
if e != nil {
t.Fatal(e)
}
if !ok {
t.Fatal("ready version1 staging cleanup permanently blocked replay of failed version2 despite retained original")
}
var replays int
var replayed time.Time
if e = pool.QueryRow(ctx, "SELECT replay_count,replayed_at FROM attachment_jobs WHERE attachment_id=$1 AND pipeline_version=2", attachmentID).Scan(&replays, &replayed); e != nil || replays != 1 || replayed.IsZero() {
t.Fatal("explicit replay has no durable audit count/timestamp")
}
}
// This deterministic transformer makes v1/v2 effects distinguishable; the Store,
// pipeline ownership/leases, transactions and S3 operations remain real.
type versionTransformer struct {
body string
err error
}
func (v versionTransformer) Transform(context.Context, io.Reader) ([]port.ProcessedVariant, error) {
if v.err != nil {
return nil, v.err
}
out := []port.ProcessedVariant{}
for _, name := range []string{"thumbnail", "crop", "optimized"} {
body := []byte(v.body + name)
sum := sha256.Sum256(body)
out = append(out, port.ProcessedVariant{Metadata: model.Variant{Name: name, ContentType: "image/jpeg", SHA256: hex.EncodeToString(sum[:]), SizeBytes: int64(len(body)), Width: 1, Height: 1}, Bytes: body})
}
return out, nil
}
func TestVersionedPipelineDuplicateReorderRetryAndCleanup(t *testing.T) {
if os.Getenv("RUN_PIPELINE_DB_TESTS") != "1" {
t.Skip("explicit isolated database and S3 required")
}
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
raw, e := config.ReadSecret("/run/secrets/database_url")
if e != nil {
t.Fatal("database file unavailable")
}
pool, e := pgxpool.New(ctx, raw)
if e != nil {
t.Fatal("database unavailable")
}
defer pool.Close()
s := New(pool, nil)
cfg, e := storage.ReadConfig("/run/secrets/s3_credentials")
if e != nil {
t.Fatal("S3 config unavailable")
}
objects, e := storage.FromConfig(cfg)
if e != nil {
t.Fatal(e)
}
user, e := s.CreateUser(ctx, model.UserDraft{Username: "matrix_" + uuid.NewString()[:8], DisplayName: "Synthetic fault matrix", PasswordHash: "disabled"})
if e != nil {
t.Fatal(e)
}
chat, e := s.CreateChat(ctx, model.ChatDraft{Title: "Owned pipeline matrix", Creator: user.ID, MemberIDs: []uuid.UUID{user.ID}})
if e != nil {
t.Fatal(e)
}
id := uuid.New()
body := []byte("immutable-original")
sum := sha256.Sum256(body)
defer func() {
c, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
for _, key := range []string{"staging/" + id.String(), usecase.ObjectKey(id)} {
if e := objects.Remove(c, key); e != nil {
t.Error("object fixture cleanup failed")
}
}
for version := int32(1); version <= 3; version++ {
for _, name := range []string{"thumbnail", "crop", "optimized"} {
if e := objects.Remove(c, usecase.VariantKey(id, version, name)); e != nil {
t.Error("variant fixture cleanup failed")
}
}
}
for _, q := range []struct {
sql string
id uuid.UUID
}{{"DELETE FROM attachment_jobs WHERE attachment_id=$1", id}, {"DELETE FROM attachments WHERE id=$1", id}, {"DELETE FROM chat_members WHERE chat_id=$1", chat.ID}, {"DELETE FROM chats WHERE id=$1", chat.ID}, {"DELETE FROM users WHERE id=$1", user.ID}} {
if _, e := pool.Exec(c, q.sql, q.id); e != nil {
t.Error("database fixture cleanup failed")
}
}
}()
a, e := s.ReserveAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "matrix.png", ContentType: "image/png", SizeBytes: int64(len(body)), SHA256: hex.EncodeToString(sum[:])})
if e != nil {
t.Fatal(e)
}
if e = objects.Put(ctx, "staging/"+id.String(), bytes.NewReader(body), int64(len(body)), "image/png"); e != nil {
t.Fatal(e)
}
if _, e = s.QueueAttachment(ctx, a, "", ""); e != nil {
t.Fatal(e)
}
next := func(version int32) model.Job {
t.Helper()
jobs, e := s.PendingJobs(ctx)
if e != nil {
t.Fatal(e)
}
for _, j := range jobs {
if j.AttachmentID == id && j.PipelineVersion == version {
return j
}
}
t.Fatal("owned current job not found")
return model.Job{}
}
j1 := next(1)
p1 := usecase.NewPipeline(s, objects, versionTransformer{body: "version1-"}, 5)
p1.Fault = func(point string) error {
if point == "after_commit" {
return errors.New("synthetic crash after commit")
}
return nil
}
if e = p1.Process(ctx, j1); e == nil {
t.Fatal("fault did not interrupt after commit")
}
a, e = s.GetAttachment(ctx, id)
if e != nil || a.Status != "ready" || a.StagingCleaned {
t.Fatal("commit fault did not preserve ready/pending cleanup")
}
if e = p1.Process(ctx, j1); e != nil {
t.Fatal(e)
}
if _, e = objects.Get(ctx, "staging/"+id.String()); !errors.Is(e, model.ErrNotFound) {
t.Fatal("completed redelivery did not remove staging")
}
if ok, e := s.AdvancePipeline(ctx, id); e != nil || !ok {
t.Fatal("advance v2 failed")
}
j2 := next(2)
// Old delivery arriving before v2 and a fabricated future delivery are no-ops.
if e = p1.Process(ctx, j1); e != nil {
t.Fatal(e)
}
future := j2
future.PipelineVersion = 3
if e = p1.Process(ctx, future); e != nil {
t.Fatal(e)
}
p2 := usecase.NewPipeline(s, objects, versionTransformer{body: "version2-"}, 5)
var group sync.WaitGroup
errs := make(chan error, 2)
for i := 0; i < 2; i++ {
group.Add(1)
go func() { defer group.Done(); errs <- p2.Process(ctx, j2) }()
}
group.Wait()
close(errs)
for e := range errs {
if e != nil {
t.Fatal(e)
}
}
a, e = s.GetAttachment(ctx, id)
if e != nil || a.PipelineVersion != 2 || a.Status != "ready" || len(a.Variants) != 3 {
t.Fatal("duplicate current job lost result")
}
snapshot := a.Variants
for _, j := range []model.Job{j1, j2, j1, future, j2} {
if e = p1.Process(ctx, j); e != nil {
t.Fatal(e)
}
}
a, e = s.GetAttachment(ctx, id)
if e != nil || !reflect.DeepEqual(snapshot, a.Variants) {
t.Fatal("stale or duplicate job overwrote current metadata")
}
for _, v := range a.Variants {
r, e := objects.Get(ctx, usecase.VariantKey(id, 2, v.Name))
if e != nil {
t.Fatal(e)
}
got, e := io.ReadAll(r)
r.Close()
if e != nil || string(got) != "version2-"+v.Name {
t.Fatal("old transformation overwrote v2 objects")
}
}
if ok, e := s.AdvancePipeline(ctx, id); e != nil || !ok {
t.Fatal("advance v3 failed")
}
j3 := next(3)
broken := usecase.NewPipeline(s, objects, versionTransformer{err: syscall.ENOSPC}, 5)
for i := 0; i < 5; i++ {
if _, e = pool.Exec(ctx, "UPDATE attachment_jobs SET next_attempt='epoch' WHERE id=$1", j3.ID); e != nil {
t.Fatal(e)
}
if e = broken.Process(ctx, j3); e != nil {
t.Fatal(e)
}
}
a, e = s.GetAttachment(ctx, id)
if e != nil || a.Status != "failed" || a.ErrorCode != "retry_exhausted" {
t.Fatal("transient infrastructure failure did not exhaust bounded retry")
}
if ok, e := s.ReplayJob(ctx, id); e != nil || !ok {
t.Fatal("explicit replay blocked despite retained immutable source")
}
if e = p2.Process(ctx, j3); e != nil {
t.Fatal(e)
}
a, e = s.GetAttachment(ctx, id)
if e != nil || a.Status != "ready" || a.PipelineVersion != 3 {
t.Fatal("replayed job did not recover")
}
}
@@ -0,0 +1,193 @@
// 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 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,
)
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
`
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,
)
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 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,
); 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,97 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package queries
import (
"time"
"github.com/google/uuid"
)
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
}
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,393 @@
// 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
`
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,
)
return i, err
}
const completeAttachment = `-- name: CompleteAttachment :execrows
UPDATE attachments a SET 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
`
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,
)
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 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
`
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,
)
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
`
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,
)
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
`
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,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,243 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"time"
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"backend/internal/domain/repository"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
//go:generate go tool sqlc generate -f ../../../../db/sqlc/sqlc.yaml
type Store struct {
pool *pgxpool.Pool
q *queries.Queries
cache *redis.Client
}
func New(pool *pgxpool.Pool, cache *redis.Client) repository.Persistent {
return &Store{pool, queries.New(pool), cache}
}
func mapErr(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return model.ErrNotFound
}
var pg *pgconn.PgError
if errors.As(err, &pg) {
switch pg.Code {
case "23505":
return model.ErrUsernameTaken
case "23503":
return model.ErrUnknownMember
case "23514":
return &model.ValidationError{Message: "constraint violation"}
}
}
return model.ErrUnavailable
}
func (s *Store) CreateUser(ctx context.Context, d model.UserDraft) (model.User, error) {
row, err := s.q.CreateUser(ctx, queries.CreateUserParams{ID: uuid.New(), Username: d.Username, DisplayName: d.DisplayName, PasswordHash: d.PasswordHash})
return model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}, mapErr(err)
}
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (model.User, error) {
key := "profile:" + id.String()
if s.cache != nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
raw, err := s.cache.Get(c, key).Bytes()
cancel()
if err == nil {
var u model.User
if json.Unmarshal(raw, &u) == nil && u.ID == id {
return u, nil
}
}
}
row, err := s.q.GetUser(ctx, id)
if err != nil {
return model.User{}, mapErr(err)
}
user := model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}
if s.cache != nil {
raw, e := json.Marshal(user)
if e == nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
_ = s.cache.Set(c, key, raw, time.Minute).Err()
cancel()
}
}
return user, nil
}
func (s *Store) CreateChat(ctx context.Context, d model.ChatDraft) (model.Chat, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, mapErr(err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, err = q.ChargeChat(ctx, d.Creator); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, model.ErrStorageFull
}
return model.Chat{}, mapErr(err)
}
row, err := q.InsertChat(ctx, queries.InsertChatParams{ID: uuid.New(), Title: d.Title})
if err != nil {
return model.Chat{}, mapErr(err)
}
if err = q.InsertMembers(ctx, queries.InsertMembersParams{ChatID: row.ID, Column2: d.MemberIDs}); err != nil {
return model.Chat{}, mapErr(err)
}
if err = tx.Commit(ctx); err != nil {
return model.Chat{}, mapErr(err)
}
return model.Chat{ID: row.ID, Title: row.Title, CreatedAt: row.CreatedAt, MemberIDs: d.MemberIDs}, nil
}
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error) {
r, e := s.q.GetChat(ctx, id)
return model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}, mapErr(e)
}
func position(q model.PageQuery) (time.Time, uuid.UUID) {
if q.After == nil {
return time.Unix(0, 0).UTC(), uuid.Nil
}
return q.After.CreatedAt, q.After.ID
}
func (s *Store) ListChats(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Chat, bool, error) {
at, aid := position(p)
rows, err := s.q.ListChats(ctx, queries.ListChatsParams{MemberID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
if err != nil {
return nil, false, mapErr(err)
}
more := len(rows) > p.Limit
if more {
rows = rows[:p.Limit]
}
out := make([]model.Chat, len(rows))
for i, r := range rows {
out[i] = model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}
}
return out, more, nil
}
func (s *Store) CreateMessage(ctx context.Context, d model.MessageDraft) (model.Message, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, mapErr(err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
messageID := uuid.New()
reserved, e := q.ReserveKey(ctx, queries.ReserveKeyParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key, PayloadHash: d.PayloadHash, MessageID: messageID})
if errors.Is(e, pgx.ErrNoRows) {
r, e := q.ReplayMessage(ctx, queries.ReplayMessageParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key})
if e != nil {
return model.Message{}, mapErr(e)
}
if r.PayloadHash != d.PayloadHash {
return model.Message{}, model.ErrConflict
}
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}, nil
}
if e != nil {
return model.Message{}, mapErr(e)
}
messageID = reserved
for _, id := range d.AttachmentIDs {
a, e := q.GetAttachment(ctx, id)
if errors.Is(e, pgx.ErrNoRows) {
return model.Message{}, model.ErrNotFound
}
if e != nil {
return model.Message{}, mapErr(e)
}
if a.ChatID != d.ChatID {
return model.Message{}, model.ErrNotFound
}
if a.Status != "ready" && a.Status != "queued" && a.Status != "processing" {
return model.Message{}, model.ErrConflict
}
}
if _, err = q.ChargeMessage(ctx, d.SenderID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, model.ErrStorageFull
}
return model.Message{}, mapErr(err)
}
r, err := q.InsertMessage(ctx, queries.InsertMessageParams{ID: messageID, ChatID: d.ChatID, SenderID: d.SenderID, Text: d.Text})
if err != nil {
return model.Message{}, mapErr(err)
}
for i, id := range d.AttachmentIDs {
if e := q.InsertMessageAttachment(ctx, queries.InsertMessageAttachmentParams{MessageID: messageID, AttachmentID: id, Ordinal: int32(i)}); e != nil {
return model.Message{}, mapErr(e)
}
}
if err = tx.Commit(ctx); err != nil {
return model.Message{}, mapErr(err)
}
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: d.AttachmentIDs}, nil
}
func (s *Store) ListMessages(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Message, bool, error) {
at, aid := position(p)
rows, err := s.q.ListMessages(ctx, queries.ListMessagesParams{ChatID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
if err != nil {
return nil, false, mapErr(err)
}
more := len(rows) > p.Limit
if more {
rows = rows[:p.Limit]
}
out := make([]model.Message, len(rows))
for i, r := range rows {
out[i] = model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}
}
return out, more, nil
}
func (s *Store) Credentials(ctx context.Context, name string) (uuid.UUID, string, error) {
r, e := s.q.Credentials(ctx, name)
if errors.Is(e, pgx.ErrNoRows) {
return uuid.Nil, "", model.ErrUnauthorized
}
return r.ID, r.PasswordHash, mapErr(e)
}
func (s *Store) CreateSession(ctx context.Context, hash string, id uuid.UUID, expiry time.Time) error {
tx, e := s.pool.Begin(ctx)
if e != nil {
return mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, e = q.LockSessionOwner(ctx, id); e != nil {
return mapErr(e)
}
if e = q.DeleteExpiredSessions(ctx, id); e != nil {
return mapErr(e)
}
if _, e = q.InsertSession(ctx, queries.InsertSessionParams{TokenHash: hash, UserID: id, ExpiresAt: expiry}); e != nil {
if errors.Is(e, pgx.ErrNoRows) {
return model.ErrStorageFull
}
return mapErr(e)
}
return mapErr(tx.Commit(ctx))
}
func (s *Store) AuthenticateSession(ctx context.Context, hash string) (uuid.UUID, error) {
r, e := s.q.AuthenticateSession(ctx, hash)
if errors.Is(e, pgx.ErrNoRows) {
return uuid.Nil, model.ErrUnauthorized
}
return r, mapErr(e)
}
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
return mapErr(s.q.RevokeSession(ctx, hash))
}