Files
mtusi2026lab6/service/internal/adapter/repository/storage/jobs.go
T
2026-11-17 13:08:13 +03:00

135 lines
5.9 KiB
Go

package storage
import (
"context"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
func (r *AttachmentsRepo) Ping(ctx context.Context) error { return r.Pool.Ping(ctx) }
func (r *AttachmentsRepo) GetTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentRecord, error) {
return ScanAttachment(tx.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1 FOR UPDATE", id))
}
func (r *AttachmentsRepo) InsertTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
p := a.Public
_, e := tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,staging_key,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$10,$11)`, p.Id, p.ChatId, p.OwnerId, p.Filename, p.ContentType, p.SizeBytes, p.Sha256, p.CreatedAt, p.UpdatedAt, a.StagingKey, p.Status)
return e
}
func (r *AttachmentsRepo) UpdateTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
variants, e := json.Marshal(a.Public.Variants)
if e != nil {
return e
}
keys, e := json.Marshal(a.VariantKeys)
if e != nil {
return e
}
_, e = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,pipeline_version=$4,staging_key=$5,object_key=$6,variants=$7,variant_keys=$8,updated_at=$9,integrity_missing=$10 WHERE id=$1`, a.Public.Id, a.Public.Status, a.Public.ErrorCode, a.PipelineVersion, a.StagingKey, a.Key, variants, keys, a.Public.UpdatedAt, a.Missing)
return e
}
const jobColumns = `id,attachment_id,pipeline_version,attempt,created_at,state,token,lease_until,next_attempt_at,attempt_limit,error_code,updated_at,traceparent,tracestate`
func scanJob(row pgx.Row) (*dto.AttachmentJob, error) {
j := new(dto.AttachmentJob)
m := &j.Message
err := row.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt, &j.State, &j.Token, &j.LeaseUntil, &j.NextAttemptAt, &j.AttemptLimit, &j.ErrorCode, &j.UpdatedAt, &m.Traceparent, &m.Tracestate)
m.SchemaVersion = 1
m.Type = "attachment.process.v1"
return j, err
}
func (r *AttachmentsRepo) JobTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentJob, error) {
return scanJob(tx.QueryRow(ctx, `SELECT `+jobColumns+` FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id))
}
func (r *AttachmentsRepo) InsertJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
m := j.Message
_, e := tx.Exec(ctx, `INSERT INTO attachment_jobs(`+jobColumns+`) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)`, m.JobID, m.AttachmentID, m.PipelineVersion, m.Attempt, m.CreatedAt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt, m.Traceparent, m.Tracestate)
return e
}
func (r *AttachmentsRepo) SaveJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
_, e := tx.Exec(ctx, `UPDATE attachment_jobs SET attempt=$2,state=$3,token=$4,lease_until=$5,next_attempt_at=$6,attempt_limit=$7,error_code=$8,updated_at=$9,traceparent=$10,tracestate=$11 WHERE id=$1`, j.Message.JobID, j.Message.Attempt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt, j.Message.Traceparent, j.Message.Tracestate)
return e
}
func (r *AttachmentsRepo) ExpiredJobs(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT id FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() ORDER BY lease_until LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) AuditTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, action string) error {
_, e := tx.Exec(ctx, `INSERT INTO job_audit(job_id,action) VALUES($1,$2)`, id, action)
return e
}
func (r *AttachmentsRepo) ListJobs(ctx context.Context) ([]dto.AttachmentJob, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+jobColumns+` FROM attachment_jobs ORDER BY updated_at DESC LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
out := []dto.AttachmentJob{}
for rows.Next() {
j, e := scanJob(rows)
if e != nil {
return nil, e
}
out = append(out, *j)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) FailedOutbox(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT DISTINCT o.job_id FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.status='dead_letter' AND j.state='queued' AND (o.payload->>'attempt')::integer=j.attempt LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) RetiredSources(ctx context.Context, before time.Time) ([]*dto.AttachmentRecord, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+AttachmentColumns+` FROM attachments WHERE staging_key<>'' AND (status='ready' OR (status='failed' AND updated_at<$1)) LIMIT 100`, before)
if e != nil {
return nil, e
}
defer rows.Close()
var out []*dto.AttachmentRecord
for rows.Next() {
a, e := ScanAttachment(rows)
if e != nil {
return nil, e
}
out = append(out, a)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) SaveVariantTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, version int, name, key, sha string, size int64) error {
_, e := tx.Exec(ctx, `INSERT INTO attachment_variants(attachment_id,pipeline_version,variant,object_key,sha256,size_bytes) VALUES($1,$2,$3,$4,$5,$6)`, id, version, name, key, sha, size)
return e
}
func (r *AttachmentsRepo) PublicationDeadTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, attempt int) (bool, error) {
var dead bool
e := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM outbox WHERE job_id=$1 AND status='dead_letter' AND (payload->>'attempt')::integer=$2)`, id, attempt).Scan(&dead)
return dead, e
}