ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const (
|
||||
Exchange = "images"
|
||||
Queue = "image.jobs"
|
||||
Route = "process"
|
||||
dead = "image.invalid"
|
||||
)
|
||||
|
||||
type boundedConn struct{ net.Conn }
|
||||
|
||||
func (c boundedConn) Write(p []byte) (int, error) {
|
||||
if err := c.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
|
||||
// Connect supplies a freshly declared channel after a broker connection loss.
|
||||
func Connect(url string) (*amqp.Connection, *amqp.Channel, error) {
|
||||
dial := amqp.DefaultDial(5 * time.Second)
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{
|
||||
Heartbeat: 10 * time.Second, Locale: "en_US",
|
||||
Dial: func(network, addr string) (net.Conn, error) {
|
||||
c, err := dial(network, addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return boundedConn{c}, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
// Connection errors may include credentials in a URL.
|
||||
return nil, nil, errors.New("RabbitMQ connection unavailable")
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err == nil {
|
||||
err = declare(ch)
|
||||
}
|
||||
if err != nil {
|
||||
Close(conn)
|
||||
return nil, nil, err
|
||||
}
|
||||
return conn, ch, nil
|
||||
}
|
||||
|
||||
func Close(conn *amqp.Connection) {
|
||||
_ = conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
}
|
||||
|
||||
func declare(ch *amqp.Channel) error {
|
||||
if err := ch.ExchangeDeclare(Exchange, "direct", true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := ch.QueueDeclare(dead, true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := ch.QueueDeclare(Queue, true, false, false, false, amqp.Table{
|
||||
"x-queue-type": "classic", "x-dead-letter-exchange": "", "x-dead-letter-routing-key": dead,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ch.QueueBind(Queue, Route, Exchange, false, nil)
|
||||
}
|
||||
|
||||
// Publisher has exactly one in-flight publish. A failed/ambiguous publish
|
||||
// invalidates its channel before the next event can be attempted.
|
||||
type Publisher struct {
|
||||
ch *amqp.Channel
|
||||
returns <-chan amqp.Return
|
||||
confirms <-chan amqp.Confirmation
|
||||
}
|
||||
|
||||
func NewPublisher(ch *amqp.Channel) (*Publisher, error) {
|
||||
if err := ch.Confirm(false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Publisher{
|
||||
ch: ch, returns: ch.NotifyReturn(make(chan amqp.Return, 1)),
|
||||
confirms: ch.NotifyPublish(make(chan amqp.Confirmation, 1)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Publisher) Publish(ctx context.Context, id string, payload []byte) error {
|
||||
seq := p.ch.GetNextPublishSeqNo()
|
||||
if err := p.ch.PublishWithContext(ctx, Exchange, Route, true, false, amqp.Publishing{
|
||||
ContentType: "application/json", DeliveryMode: amqp.Persistent, MessageId: id, Body: payload,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-p.returns:
|
||||
return errors.New("outbox message was not routed")
|
||||
case confirm, ok := <-p.confirms:
|
||||
if !ok || confirm.DeliveryTag != seq || !confirm.Ack {
|
||||
return errors.New("outbox publish was not confirmed")
|
||||
}
|
||||
// RabbitMQ sends basic.return before its confirm for an unrouted
|
||||
// mandatory publish. The client's frame reader enqueues both in order.
|
||||
// With a single in-flight message any queued return is for this ID.
|
||||
select {
|
||||
case <-p.returns:
|
||||
return errors.New("outbox message was not routed")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Database struct {
|
||||
PostgresURL string
|
||||
RedisAddr string
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
JobMaxAttempts int
|
||||
HTTP struct {
|
||||
Host string
|
||||
Port string
|
||||
}
|
||||
Database Database
|
||||
|
||||
Session struct {
|
||||
TTL time.Duration
|
||||
Store string
|
||||
}
|
||||
|
||||
S3 S3
|
||||
|
||||
AppEnv string
|
||||
CacheURL string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
config := &Config{}
|
||||
sessionTTL, err := getSessionTTL()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config.Session.TTL = sessionTTL
|
||||
config.JobMaxAttempts, err = EnvInt("JOB_MAX_ATTEMPTS", 5, 1, 20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config.HTTP.Host = os.Getenv("APP_HOST")
|
||||
if config.HTTP.Host == "" {
|
||||
config.HTTP.Host = "0.0.0.0"
|
||||
}
|
||||
|
||||
config.HTTP.Port = os.Getenv("APP_PORT")
|
||||
if config.HTTP.Port == "" {
|
||||
config.HTTP.Port = "8080"
|
||||
}
|
||||
|
||||
config.AppEnv = os.Getenv("APP_ENV")
|
||||
if config.AppEnv == "" {
|
||||
config.AppEnv = "lab"
|
||||
}
|
||||
|
||||
store := os.Getenv("SESSION_STORE")
|
||||
|
||||
config.Session.Store = strings.TrimSpace(string(store))
|
||||
if config.Session.Store == "" {
|
||||
return nil, fmt.Errorf("empty session store data")
|
||||
}
|
||||
|
||||
config.Database, err = getDatabaseURL()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config.S3, err = getS3Data()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
|
||||
}
|
||||
|
||||
func getSessionTTL() (time.Duration, error) {
|
||||
value, ok := os.LookupEnv("SESSION_TTL_SECONDS")
|
||||
if !ok {
|
||||
return time.Hour, nil
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds <= 0 || seconds > int64((1<<63-1)/int64(time.Second)) {
|
||||
return 0, fmt.Errorf("invalid SESSION_TTL_SECONDS: %q", value)
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
|
||||
func LoadAttachmentCleanup() (postgresURL string, objectStorage S3, err error) {
|
||||
postgresURL, err = LoadPostgresURL()
|
||||
if err != nil {
|
||||
return "", S3{}, err
|
||||
}
|
||||
objectStorage, err = getS3Data()
|
||||
return postgresURL, objectStorage, err
|
||||
}
|
||||
|
||||
func LoadPostgresURL() (string, error) {
|
||||
postgresData, err := os.ReadFile(os.Getenv("DATABASE_URL_FILE"))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read database URL: %w", err)
|
||||
}
|
||||
postgresURL := strings.TrimSpace(string(postgresData))
|
||||
if postgresURL == "" {
|
||||
return "", fmt.Errorf("empty database URL")
|
||||
}
|
||||
return postgresURL, nil
|
||||
}
|
||||
|
||||
func getDatabaseURL() (Database, error) {
|
||||
postgresURL, err := LoadPostgresURL()
|
||||
if err != nil {
|
||||
return Database{}, err
|
||||
}
|
||||
db := Database{PostgresURL: postgresURL}
|
||||
|
||||
redisData := os.Getenv("REDIS_ADDR")
|
||||
|
||||
db.RedisAddr = strings.TrimSpace(string(redisData))
|
||||
|
||||
if db.RedisAddr == "" {
|
||||
return db, fmt.Errorf("redis addres is empty")
|
||||
}
|
||||
|
||||
return db, nil
|
||||
|
||||
}
|
||||
|
||||
func getS3Data() (S3, error) {
|
||||
s3 := S3{
|
||||
Endpoint: os.Getenv("S3_ENDPOINT"),
|
||||
Region: os.Getenv("S3_REGION"),
|
||||
Bucket: os.Getenv("S3_BUCKET"),
|
||||
}
|
||||
|
||||
if s3.Endpoint == "" {
|
||||
return s3, fmt.Errorf("empty s3 endpoint")
|
||||
}
|
||||
if s3.Region == "" {
|
||||
return s3, fmt.Errorf("empty s3 region")
|
||||
}
|
||||
if s3.Bucket == "" {
|
||||
return s3, fmt.Errorf("emtpy s3 bucket")
|
||||
}
|
||||
accessKeyIDPath := os.Getenv("S3_ACCESS_KEY_ID_FILE")
|
||||
|
||||
accessKeyID, err := os.ReadFile(accessKeyIDPath)
|
||||
if err != nil {
|
||||
return s3, fmt.Errorf("empty s3 access_key_id")
|
||||
}
|
||||
s3.AccessKeyID = strings.TrimSpace(string(accessKeyID))
|
||||
|
||||
secretAccessKeyPath := os.Getenv("S3_SECRET_ACCESS_KEY_FILE")
|
||||
secretAccessKey, err := os.ReadFile(secretAccessKeyPath)
|
||||
if err != nil {
|
||||
return s3, fmt.Errorf("empty s3 secret_access_key_file")
|
||||
}
|
||||
s3.SecretAccessKey = strings.TrimSpace(string(secretAccessKey))
|
||||
|
||||
return s3, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Pipeline struct {
|
||||
BrokerURL string
|
||||
Concurrency int
|
||||
Prefetch int
|
||||
Timeout time.Duration
|
||||
Lease time.Duration
|
||||
Retention time.Duration
|
||||
CleanupGrace time.Duration
|
||||
CleanupPeriod time.Duration
|
||||
RetryBase time.Duration
|
||||
}
|
||||
|
||||
func EnvInt(name string, fallback, minimum, maximum int) (int, error) {
|
||||
value := os.Getenv(name)
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < minimum || n > maximum {
|
||||
return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func LoadPipeline() (Pipeline, error) {
|
||||
var cfg Pipeline
|
||||
path := os.Getenv("BROKER_URL_FILE")
|
||||
if path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("cannot read broker URL file: %w", err)
|
||||
}
|
||||
cfg.BrokerURL = strings.TrimSpace(string(data))
|
||||
}
|
||||
duration := func(dst *time.Duration, name string, fallback, minimum, maximum int) error {
|
||||
n, err := EnvInt(name, fallback, minimum, maximum)
|
||||
*dst = time.Duration(n) * time.Second
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
if cfg.Concurrency, err = EnvInt("WORKER_CONCURRENCY", 1, 1, 4); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.Prefetch, err = EnvInt("WORKER_PREFETCH", 1, 1, 16); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
for _, d := range []struct {
|
||||
dst *time.Duration
|
||||
name string
|
||||
fallback, minimum, maximum int
|
||||
}{
|
||||
{&cfg.Timeout, "JOB_TIMEOUT_SECONDS", 60, 1, 600},
|
||||
{&cfg.Lease, "JOB_LEASE_SECONDS", 90, 2, 900},
|
||||
{&cfg.Retention, "STAGING_RETENTION_SECONDS", 86400, 1, 604800},
|
||||
{&cfg.CleanupGrace, "CLEANUP_GRACE_SECONDS", 600, 1, 604800},
|
||||
{&cfg.CleanupPeriod, "CLEANUP_INTERVAL_SECONDS", 5, 1, 600},
|
||||
{&cfg.RetryBase, "JOB_RETRY_BASE_SECONDS", 2, 1, 15},
|
||||
} {
|
||||
if err := duration(d.dst, d.name, d.fallback, d.minimum, d.maximum); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
}
|
||||
if cfg.Lease < cfg.Timeout+time.Second {
|
||||
return cfg, fmt.Errorf("JOB_LEASE_SECONDS must exceed JOB_TIMEOUT_SECONDS")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgres(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func NewRedis(ctx context.Context, addr string) (*redis.Client, error) {
|
||||
|
||||
options := &redis.Options{
|
||||
Addr: addr,
|
||||
DialTimeout: 3 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 2 * time.Second,
|
||||
PoolSize: 10,
|
||||
PoolTimeout: 2 * time.Second,
|
||||
ContextTimeoutEnabled: true,
|
||||
}
|
||||
|
||||
client := redis.NewClient(options)
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachment_variants.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createAttachmentVariant = `-- name: CreateAttachmentVariant :exec
|
||||
INSERT INTO attachment_variants (
|
||||
attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9
|
||||
)
|
||||
`
|
||||
|
||||
type CreateAttachmentVariantParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
Name string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int32
|
||||
Height int32
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachmentVariant(ctx context.Context, arg CreateAttachmentVariantParams) error {
|
||||
_, err := q.db.Exec(ctx, createAttachmentVariant,
|
||||
arg.AttachmentID,
|
||||
arg.PipelineVersion,
|
||||
arg.Name,
|
||||
arg.ObjectKey,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Width,
|
||||
arg.Height,
|
||||
arg.Sha256,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAttachmentVariants = `-- name: ListAttachmentVariants :many
|
||||
SELECT attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256 FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = $2
|
||||
ORDER BY name
|
||||
`
|
||||
|
||||
type ListAttachmentVariantsParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentVariants(ctx context.Context, arg ListAttachmentVariantsParams) ([]AttachmentVariant, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentVariants, arg.AttachmentID, arg.PipelineVersion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AttachmentVariant
|
||||
for rows.Next() {
|
||||
var i AttachmentVariant
|
||||
if err := rows.Scan(
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.Name,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.Sha256,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const attachmentExistsByObjectKey = `-- name: AttachmentExistsByObjectKey :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM attachments
|
||||
WHERE object_key = $1::text OR staging_key = $1::text
|
||||
UNION ALL
|
||||
SELECT 1 FROM attachment_variants WHERE object_key = $1::text
|
||||
UNION ALL
|
||||
SELECT 1 FROM attachment_jobs WHERE published_original_key = $1::text
|
||||
)
|
||||
`
|
||||
|
||||
func (q *Queries) AttachmentExistsByObjectKey(ctx context.Context, objectKey string) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, attachmentExistsByObjectKey, objectKey)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const createAttachment = `-- name: CreateAttachment :one
|
||||
WITH legacy AS (
|
||||
INSERT INTO attachments
|
||||
(chat_id, owner_id, filename, object_key, staging_key, content_type, size_bytes, sha256)
|
||||
VALUES ($1, $2, $3,
|
||||
$4::text, $4::text,
|
||||
$5, $6, $7)
|
||||
RETURNING id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version
|
||||
), job AS (
|
||||
INSERT INTO attachment_jobs (attachment_id, pipeline_version)
|
||||
SELECT id, pipeline_version FROM legacy
|
||||
RETURNING id, attachment_id, pipeline_version, attempts_started, max_attempts, next_attempt_at, lease_generation, lease_until, created_at, updated_at, published_original_key
|
||||
), event AS (
|
||||
INSERT INTO outbox (job_id, payload, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
|
||||
'initial/' || id
|
||||
FROM job
|
||||
RETURNING job_id
|
||||
)
|
||||
SELECT legacy.id, legacy.chat_id, legacy.owner_id, legacy.filename, legacy.object_key, legacy.content_type, legacy.size_bytes, legacy.sha256, legacy.created_at, legacy.updated_at, legacy.status, legacy.error_code, legacy.staging_key, legacy.pipeline_version FROM legacy CROSS JOIN event
|
||||
`
|
||||
|
||||
type CreateAttachmentParams struct {
|
||||
ChatID pgtype.UUID
|
||||
OwnerID pgtype.UUID
|
||||
Filename string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
type CreateAttachmentRow struct {
|
||||
ID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
OwnerID pgtype.UUID
|
||||
Filename string
|
||||
ObjectKey pgtype.Text
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
Status string
|
||||
ErrorCode pgtype.Text
|
||||
StagingKey pgtype.Text
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
// Compatibility for the synchronous API until CreateQueuedAttachment is wired in.
|
||||
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (CreateAttachmentRow, error) {
|
||||
row := q.db.QueryRow(ctx, createAttachment,
|
||||
arg.ChatID,
|
||||
arg.OwnerID,
|
||||
arg.Filename,
|
||||
arg.ObjectKey,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
)
|
||||
var i CreateAttachmentRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const createQueuedAttachment = `-- name: CreateQueuedAttachment :one
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key, status
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, 'queued'
|
||||
) RETURNING id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version
|
||||
`
|
||||
|
||||
type CreateQueuedAttachmentParams struct {
|
||||
ID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
OwnerID pgtype.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
StagingKey pgtype.Text
|
||||
}
|
||||
|
||||
func (q *Queries) CreateQueuedAttachment(ctx context.Context, arg CreateQueuedAttachmentParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, createQueuedAttachment,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.OwnerID,
|
||||
arg.Filename,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
arg.StagingKey,
|
||||
)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentByID = `-- name: GetAttachmentByID :one
|
||||
SELECT id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version FROM attachments WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetAttachmentByID(ctx context.Context, attachmentID pgtype.UUID) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentByID, attachmentID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentForUser = `-- name: GetAttachmentForUser :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.object_key, a.content_type, a.size_bytes, a.sha256, a.created_at, a.updated_at, a.status, a.error_code, a.staging_key, a.pipeline_version
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm ON cm.chat_id = a.chat_id
|
||||
WHERE a.id = $1
|
||||
AND cm.user_id = $2
|
||||
`
|
||||
|
||||
type GetAttachmentForUserParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForUser(ctx context.Context, arg GetAttachmentForUserParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForUser, arg.AttachmentID, arg.UserID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentsForMessages = `-- name: GetAttachmentsForMessages :many
|
||||
SELECT message_id, attachment_id, position
|
||||
FROM messages_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
|
||||
type GetAttachmentsForMessagesRow struct {
|
||||
MessageID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentsForMessages(ctx context.Context, messageIds []pgtype.UUID) ([]GetAttachmentsForMessagesRow, error) {
|
||||
rows, err := q.db.Query(ctx, getAttachmentsForMessages, messageIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []GetAttachmentsForMessagesRow
|
||||
for rows.Next() {
|
||||
var i GetAttachmentsForMessagesRow
|
||||
if err := rows.Scan(&i.MessageID, &i.AttachmentID, &i.Position); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAttachmentKeys = `-- name: ListAttachmentKeys :many
|
||||
SELECT id, object_key, created_at
|
||||
FROM attachments
|
||||
WHERE object_key > $1
|
||||
ORDER BY object_key
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListAttachmentKeysParams struct {
|
||||
AfterKey pgtype.Text
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
type ListAttachmentKeysRow struct {
|
||||
ID pgtype.UUID
|
||||
ObjectKey pgtype.Text
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentKeys(ctx context.Context, arg ListAttachmentKeysParams) ([]ListAttachmentKeysRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentKeys, arg.AfterKey, arg.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListAttachmentKeysRow
|
||||
for rows.Next() {
|
||||
var i ListAttachmentKeysRow
|
||||
if err := rows.Scan(&i.ID, &i.ObjectKey, &i.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const tryLockAttachmentObjectKey = `-- name: TryLockAttachmentObjectKey :one
|
||||
SELECT pg_try_advisory_xact_lock(
|
||||
hashtextextended($1::text, 0)
|
||||
)::boolean AS locked
|
||||
`
|
||||
|
||||
func (q *Queries) TryLockAttachmentObjectKey(ctx context.Context, objectKey string) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, tryLockAttachmentObjectKey, objectKey)
|
||||
var locked bool
|
||||
err := row.Scan(&locked)
|
||||
return locked, err
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments_jobs.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const claimJob = `-- name: ClaimJob :one
|
||||
WITH claimed AS (
|
||||
UPDATE attachment_jobs AS j
|
||||
SET lease_generation = j.lease_generation + 1,
|
||||
lease_until = $1::timestamptz,
|
||||
attempts_started = j.attempts_started + 1,
|
||||
next_attempt_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
FROM attachments AS a
|
||||
WHERE j.id = $2
|
||||
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
AND j.attempts_started < j.max_attempts
|
||||
AND $1::timestamptz > clock_timestamp()
|
||||
AND (
|
||||
(a.status = 'queued' AND j.lease_until IS NULL AND j.next_attempt_at <= clock_timestamp())
|
||||
OR (a.status = 'processing' AND j.lease_until <= clock_timestamp())
|
||||
)
|
||||
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
), expired AS (
|
||||
UPDATE attachment_attempts AS attempt
|
||||
SET outcome = 'lease_expired', error_code = 'lease_expired', finished_at = claimed.updated_at
|
||||
FROM claimed
|
||||
WHERE attempt.job_id = claimed.id
|
||||
AND attempt.lease_generation = claimed.lease_generation - 1 AND attempt.finished_at IS NULL
|
||||
), recorded AS (
|
||||
INSERT INTO attachment_attempts (job_id, lease_generation, attempt, started_at)
|
||||
SELECT id, lease_generation, attempts_started, updated_at FROM claimed
|
||||
RETURNING job_id
|
||||
), processing AS (
|
||||
UPDATE attachments AS a
|
||||
SET status = 'processing', updated_at = claimed.updated_at
|
||||
FROM claimed
|
||||
WHERE a.id = claimed.attachment_id
|
||||
RETURNING a.id
|
||||
)
|
||||
SELECT claimed.id, claimed.attachment_id, claimed.pipeline_version, claimed.attempts_started, claimed.max_attempts, claimed.next_attempt_at, claimed.lease_generation, claimed.lease_until, claimed.created_at, claimed.updated_at, claimed.published_original_key FROM claimed JOIN recorded ON recorded.job_id = claimed.id
|
||||
JOIN processing ON processing.id = claimed.attachment_id
|
||||
`
|
||||
|
||||
type ClaimJobParams struct {
|
||||
NewLeaseUntil pgtype.Timestamptz
|
||||
JobID pgtype.UUID
|
||||
}
|
||||
|
||||
type ClaimJobRow struct {
|
||||
ID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
AttemptsStarted int32
|
||||
MaxAttempts int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LeaseGeneration int32
|
||||
LeaseUntil pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PublishedOriginalKey pgtype.Text
|
||||
}
|
||||
|
||||
func (q *Queries) ClaimJob(ctx context.Context, arg ClaimJobParams) (ClaimJobRow, error) {
|
||||
row := q.db.QueryRow(ctx, claimJob, arg.NewLeaseUntil, arg.JobID)
|
||||
var i ClaimJobRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PublishedOriginalKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const clearStagingReference = `-- name: ClearStagingReference :execrows
|
||||
UPDATE attachments
|
||||
SET object_key = CASE WHEN status = 'failed' AND object_key = staging_key THEN NULL ELSE object_key END,
|
||||
staging_key = NULL
|
||||
WHERE id = $1 AND staging_key = $2
|
||||
`
|
||||
|
||||
type ClearStagingReferenceParams struct {
|
||||
ID pgtype.UUID
|
||||
StagingKey pgtype.Text
|
||||
}
|
||||
|
||||
func (q *Queries) ClearStagingReference(ctx context.Context, arg ClearStagingReferenceParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, clearStagingReference, arg.ID, arg.StagingKey)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const completeJob = `-- name: CompleteJob :execrows
|
||||
WITH completed AS (
|
||||
UPDATE attachment_jobs AS j
|
||||
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp(),
|
||||
published_original_key = $1::text
|
||||
FROM attachments AS a
|
||||
WHERE j.id = $2
|
||||
AND j.lease_generation = $3 AND j.lease_until > clock_timestamp()
|
||||
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
|
||||
AND (SELECT count(*) FROM attachment_variants AS v
|
||||
WHERE v.attachment_id = a.id AND v.pipeline_version = j.pipeline_version) = 3
|
||||
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
), recorded AS (
|
||||
UPDATE attachment_attempts AS attempt
|
||||
SET outcome = 'ready', finished_at = completed.updated_at
|
||||
FROM completed
|
||||
WHERE attempt.job_id = completed.id AND attempt.lease_generation = completed.lease_generation
|
||||
)
|
||||
UPDATE attachments AS a
|
||||
SET status = 'ready', object_key = $1::text, updated_at = completed.updated_at
|
||||
FROM completed
|
||||
WHERE a.id = completed.attachment_id
|
||||
`
|
||||
|
||||
type CompleteJobParams struct {
|
||||
ObjectKey string
|
||||
JobID pgtype.UUID
|
||||
LeaseGeneration int32
|
||||
}
|
||||
|
||||
func (q *Queries) CompleteJob(ctx context.Context, arg CompleteJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, completeJob, arg.ObjectKey, arg.JobID, arg.LeaseGeneration)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const createAttachmentJob = `-- name: CreateAttachmentJob :one
|
||||
INSERT INTO attachment_jobs (attachment_id, pipeline_version, next_attempt_at, max_attempts)
|
||||
VALUES ($1, $2,
|
||||
$3::timestamptz, $4)
|
||||
RETURNING id, attachment_id, pipeline_version, attempts_started, max_attempts, next_attempt_at, lease_generation, lease_until, created_at, updated_at, published_original_key
|
||||
`
|
||||
|
||||
type CreateAttachmentJobParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
AvailableAt pgtype.Timestamptz
|
||||
MaxAttempts int32
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachmentJob(ctx context.Context, arg CreateAttachmentJobParams) (AttachmentJob, error) {
|
||||
row := q.db.QueryRow(ctx, createAttachmentJob,
|
||||
arg.AttachmentID,
|
||||
arg.PipelineVersion,
|
||||
arg.AvailableAt,
|
||||
arg.MaxAttempts,
|
||||
)
|
||||
var i AttachmentJob
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PublishedOriginalKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const failJob = `-- name: FailJob :execrows
|
||||
WITH failed AS (
|
||||
UPDATE attachment_jobs AS j
|
||||
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
|
||||
FROM attachments AS a
|
||||
WHERE j.id = $2
|
||||
AND j.lease_generation = $3
|
||||
AND (
|
||||
j.lease_until > clock_timestamp()
|
||||
OR (j.lease_until <= clock_timestamp() AND j.attempts_started = j.max_attempts
|
||||
AND $1::text = 'retry_exhausted')
|
||||
)
|
||||
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
|
||||
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
), recorded AS (
|
||||
UPDATE attachment_attempts AS attempt
|
||||
SET outcome = 'failed', error_code = $1::text, finished_at = failed.updated_at
|
||||
FROM failed
|
||||
WHERE attempt.job_id = failed.id AND attempt.lease_generation = failed.lease_generation
|
||||
)
|
||||
UPDATE attachments AS a
|
||||
SET status = 'failed', error_code = $1::text, updated_at = failed.updated_at
|
||||
FROM failed WHERE a.id = failed.attachment_id
|
||||
`
|
||||
|
||||
type FailJobParams struct {
|
||||
ErrorCode string
|
||||
JobID pgtype.UUID
|
||||
LeaseGeneration int32
|
||||
}
|
||||
|
||||
func (q *Queries) FailJob(ctx context.Context, arg FailJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, failJob, arg.ErrorCode, arg.JobID, arg.LeaseGeneration)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getAttachmentByStagingKey = `-- name: GetAttachmentByStagingKey :one
|
||||
SELECT id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version FROM attachments WHERE staging_key = $1::text
|
||||
`
|
||||
|
||||
func (q *Queries) GetAttachmentByStagingKey(ctx context.Context, stagingKey string) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentByStagingKey, stagingKey)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentJobState = `-- name: GetAttachmentJobState :one
|
||||
SELECT
|
||||
j.id, j.attachment_id, j.pipeline_version,
|
||||
CASE WHEN a.pipeline_version = j.pipeline_version THEN a.status ELSE 'superseded' END::text AS status,
|
||||
j.lease_generation,
|
||||
j.lease_until,
|
||||
coalesce(j.lease_until <= clock_timestamp(), false)::boolean AS lease_expired,
|
||||
j.attempts_started,
|
||||
j.max_attempts,
|
||||
j.next_attempt_at
|
||||
FROM attachment_jobs AS j
|
||||
JOIN attachments AS a ON a.id = j.attachment_id
|
||||
WHERE j.id = $1::uuid
|
||||
`
|
||||
|
||||
type GetAttachmentJobStateRow struct {
|
||||
ID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
Status string
|
||||
LeaseGeneration int32
|
||||
LeaseUntil pgtype.Timestamptz
|
||||
LeaseExpired bool
|
||||
AttemptsStarted int32
|
||||
MaxAttempts int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentJobState(ctx context.Context, jobID pgtype.UUID) (GetAttachmentJobStateRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentJobState, jobID)
|
||||
var i GetAttachmentJobStateRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.Status,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.LeaseExpired,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listFailedAttachmentJobs = `-- name: ListFailedAttachmentJobs :many
|
||||
SELECT j.id, j.attachment_id, j.attempts_started, a.error_code, a.updated_at
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
WHERE a.status = 'failed'
|
||||
ORDER BY a.updated_at DESC, j.id
|
||||
LIMIT $1
|
||||
`
|
||||
|
||||
type ListFailedAttachmentJobsRow struct {
|
||||
ID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
AttemptsStarted int32
|
||||
ErrorCode pgtype.Text
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) ListFailedAttachmentJobs(ctx context.Context, batchSize int32) ([]ListFailedAttachmentJobsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listFailedAttachmentJobs, batchSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListFailedAttachmentJobsRow
|
||||
for rows.Next() {
|
||||
var i ListFailedAttachmentJobsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.AttemptsStarted,
|
||||
&i.ErrorCode,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockActiveAttachmentJob = `-- name: LockActiveAttachmentJob :one
|
||||
SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
FROM attachment_jobs AS j JOIN attachments AS a ON a.id = j.attachment_id
|
||||
WHERE j.id = $1
|
||||
AND j.lease_generation = $2
|
||||
AND j.lease_until > clock_timestamp()
|
||||
AND a.status = 'processing' AND a.pipeline_version = j.pipeline_version
|
||||
FOR UPDATE OF j
|
||||
`
|
||||
|
||||
type LockActiveAttachmentJobParams struct {
|
||||
JobID pgtype.UUID
|
||||
LeaseGeneration int32
|
||||
}
|
||||
|
||||
// Hold this lock through variant insertion and CompleteJob. Roll back on a zero-row completion.
|
||||
func (q *Queries) LockActiveAttachmentJob(ctx context.Context, arg LockActiveAttachmentJobParams) (AttachmentJob, error) {
|
||||
row := q.db.QueryRow(ctx, lockActiveAttachmentJob, arg.JobID, arg.LeaseGeneration)
|
||||
var i AttachmentJob
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PublishedOriginalKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockAttachmentJobForPipeline = `-- name: LockAttachmentJobForPipeline :one
|
||||
SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
FROM attachment_jobs j
|
||||
WHERE j.attachment_id = $1 AND j.pipeline_version = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockAttachmentJobForPipelineParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
func (q *Queries) LockAttachmentJobForPipeline(ctx context.Context, arg LockAttachmentJobForPipelineParams) (AttachmentJob, error) {
|
||||
row := q.db.QueryRow(ctx, lockAttachmentJobForPipeline, arg.AttachmentID, arg.PipelineVersion)
|
||||
var i AttachmentJob
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PublishedOriginalKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockAttachmentJobForReplay = `-- name: LockAttachmentJobForReplay :one
|
||||
SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
FROM attachment_jobs j WHERE j.id = $1
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
func (q *Queries) LockAttachmentJobForReplay(ctx context.Context, id pgtype.UUID) (AttachmentJob, error) {
|
||||
row := q.db.QueryRow(ctx, lockAttachmentJobForReplay, id)
|
||||
var i AttachmentJob
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.AttachmentID,
|
||||
&i.PipelineVersion,
|
||||
&i.AttemptsStarted,
|
||||
&i.MaxAttempts,
|
||||
&i.NextAttemptAt,
|
||||
&i.LeaseGeneration,
|
||||
&i.LeaseUntil,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PublishedOriginalKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const replayFailed = `-- name: ReplayFailed :execrows
|
||||
WITH replayed AS (
|
||||
UPDATE attachment_jobs AS j
|
||||
SET max_attempts = j.attempts_started + $1::int,
|
||||
next_attempt_at = clock_timestamp(), updated_at = clock_timestamp()
|
||||
FROM attachments AS a
|
||||
WHERE j.id = $2
|
||||
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
AND a.status = 'failed' AND a.staging_key IS NOT NULL
|
||||
AND j.lease_until IS NULL AND j.next_attempt_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM attachment_replays AS r WHERE r.request_id = $3::uuid
|
||||
)
|
||||
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
), recorded AS (
|
||||
INSERT INTO attachment_replays (request_id, job_id, operator_id, reason, extra_attempts)
|
||||
SELECT $3::uuid, id, $4, $5, $1
|
||||
FROM replayed
|
||||
), event AS (
|
||||
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at),
|
||||
next_attempt_at, 'replay/' || id || '/' || $3::uuid
|
||||
FROM replayed
|
||||
)
|
||||
UPDATE attachments AS a
|
||||
SET status = 'queued', error_code = NULL, updated_at = replayed.updated_at
|
||||
FROM replayed WHERE a.id = replayed.attachment_id
|
||||
`
|
||||
|
||||
type ReplayFailedParams struct {
|
||||
ExtraAttempts int32
|
||||
JobID pgtype.UUID
|
||||
RequestID pgtype.UUID
|
||||
OperatorID string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (q *Queries) ReplayFailed(ctx context.Context, arg ReplayFailedParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, replayFailed,
|
||||
arg.ExtraAttempts,
|
||||
arg.JobID,
|
||||
arg.RequestID,
|
||||
arg.OperatorID,
|
||||
arg.Reason,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const scheduleRetry = `-- name: ScheduleRetry :execrows
|
||||
WITH scheduled AS (
|
||||
UPDATE attachment_jobs AS j
|
||||
SET lease_until = NULL, next_attempt_at = $1::timestamptz,
|
||||
updated_at = clock_timestamp()
|
||||
FROM attachments AS a
|
||||
WHERE j.id = $2
|
||||
AND j.lease_generation = $3 AND j.lease_until > clock_timestamp()
|
||||
AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing'
|
||||
AND j.attempts_started < j.max_attempts
|
||||
AND $1::timestamptz > clock_timestamp()
|
||||
RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key
|
||||
), recorded AS (
|
||||
UPDATE attachment_attempts AS attempt
|
||||
SET outcome = 'retry', error_code = $4::text, finished_at = scheduled.updated_at
|
||||
FROM scheduled
|
||||
WHERE attempt.job_id = scheduled.id AND attempt.lease_generation = scheduled.lease_generation
|
||||
), event AS (
|
||||
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at),
|
||||
next_attempt_at, 'retry/' || id || '/' || (attempts_started + 1)
|
||||
FROM scheduled
|
||||
)
|
||||
UPDATE attachments AS a
|
||||
SET status = 'queued', updated_at = scheduled.updated_at
|
||||
FROM scheduled WHERE a.id = scheduled.attachment_id
|
||||
`
|
||||
|
||||
type ScheduleRetryParams struct {
|
||||
AvailableAt pgtype.Timestamptz
|
||||
JobID pgtype.UUID
|
||||
LeaseGeneration int32
|
||||
ErrorCode string
|
||||
}
|
||||
|
||||
func (q *Queries) ScheduleRetry(ctx context.Context, arg ScheduleRetryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, scheduleRetry,
|
||||
arg.AvailableAt,
|
||||
arg.JobID,
|
||||
arg.LeaseGeneration,
|
||||
arg.ErrorCode,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chat_members.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createChatMember = `-- name: CreateChatMember :exec
|
||||
INSERT INTO chat_members(chat_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
`
|
||||
|
||||
type CreateChatMemberParams struct {
|
||||
ChatID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) CreateChatMember(ctx context.Context, arg CreateChatMemberParams) error {
|
||||
_, err := q.db.Exec(ctx, createChatMember, arg.ChatID, arg.UserID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chats.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
RETURNING id, title, created_at
|
||||
`
|
||||
|
||||
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, createChat, title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatByID = `-- name: GetChatByID :one
|
||||
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
GROUP BY c.id
|
||||
`
|
||||
|
||||
type GetChatByIDRow struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
MemberIds []pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatByID(ctx context.Context, id pgtype.UUID) (GetChatByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChatByID, id)
|
||||
var i GetChatByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatsByUserID = `-- name: GetChatsByUserID :many
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE EXISTS (SELECT 1
|
||||
FROM chat_members membership
|
||||
WHERE membership.chat_id = c.id
|
||||
AND membership.user_id = $1)
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (c.created_at, c.id) >
|
||||
(
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type GetChatsByUserIDParams struct {
|
||||
UserID pgtype.UUID
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
type GetChatsByUserIDRow struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
MemberIds []pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatsByUserID(ctx context.Context, arg GetChatsByUserIDParams) ([]GetChatsByUserIDRow, error) {
|
||||
rows, err := q.db.Query(ctx, getChatsByUserID,
|
||||
arg.UserID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []GetChatsByUserIDRow
|
||||
for rows.Next() {
|
||||
var i GetChatsByUserIDRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
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,99 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: message_idempotence.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteExpiredMessageIdempotency = `-- name: DeleteExpiredMessageIdempotency :exec
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3 AND expires_at <= now()
|
||||
`
|
||||
|
||||
type DeleteExpiredMessageIdempotencyParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteExpiredMessageIdempotency(ctx context.Context, arg DeleteExpiredMessageIdempotencyParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteExpiredMessageIdempotency, arg.UserID, arg.ChatID, arg.IdempotencyKey)
|
||||
return err
|
||||
}
|
||||
|
||||
const getIdempotentMessage = `-- name: GetIdempotentMessage :one
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency AS i
|
||||
JOIN messages AS m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1
|
||||
AND i.chat_id = $2
|
||||
AND i.idempotency_key = $3
|
||||
`
|
||||
|
||||
type GetIdempotentMessageParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func (q *Queries) GetIdempotentMessage(ctx context.Context, arg GetIdempotentMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, getIdempotentMessage, arg.UserID, arg.ChatID, arg.IdempotencyKey)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertMessageIdempotency = `-- name: InsertMessageIdempotency :execrows
|
||||
INSERT INTO message_idempotency(user_id, chat_id, idempotency_key, message_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (user_id, chat_id, idempotency_key) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertMessageIdempotencyParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
MessageID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMessageIdempotency(ctx context.Context, arg InsertMessageIdempotencyParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertMessageIdempotency,
|
||||
arg.UserID,
|
||||
arg.ChatID,
|
||||
arg.IdempotencyKey,
|
||||
arg.MessageID,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const lockMessageRequest = `-- name: LockMessageRequest :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'message/' || ($1::uuid)::text || '/' ||
|
||||
($2::uuid)::text || '/' || $3::text, 0))
|
||||
`
|
||||
|
||||
type LockMessageRequestParams struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func (q *Queries) LockMessageRequest(ctx context.Context, arg LockMessageRequestParams) error {
|
||||
_, err := q.db.Exec(ctx, lockMessageRequest, arg.UserID, arg.ChatID, arg.IdempotencyKey)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: messages.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createMessage = `-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`
|
||||
|
||||
type CreateMessageParams struct {
|
||||
ChatID pgtype.UUID
|
||||
SenderID pgtype.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, createMessage, 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 getMessagesByChatID = `-- name: GetMessagesByChatID :many
|
||||
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (created_at, id) >
|
||||
($2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type GetMessagesByChatIDParams struct {
|
||||
ChatID pgtype.UUID
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
func (q *Queries) GetMessagesByChatID(ctx context.Context, arg GetMessagesByChatIDParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, getMessagesByChatID,
|
||||
arg.ChatID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: messages_attachments.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createMessagesAttachments = `-- name: CreateMessagesAttachments :execrows
|
||||
INSERT INTO messages_attachments (message_id, attachment_id, chat_id, position)
|
||||
SELECT $1, $2, $3, $4
|
||||
FROM attachments
|
||||
WHERE id = $2 AND chat_id = $3
|
||||
`
|
||||
|
||||
type CreateMessagesAttachmentsParams struct {
|
||||
MessageID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMessagesAttachments(ctx context.Context, arg CreateMessagesAttachmentsParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, createMessagesAttachments,
|
||||
arg.MessageID,
|
||||
arg.AttachmentID,
|
||||
arg.ChatID,
|
||||
arg.Position,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getMessagesAttachments = `-- name: GetMessagesAttachments :many
|
||||
SELECT attachment_id, position
|
||||
FROM messages_attachments
|
||||
WHERE message_id = $1
|
||||
ORDER BY position ASC
|
||||
`
|
||||
|
||||
type GetMessagesAttachmentsRow struct {
|
||||
AttachmentID pgtype.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
func (q *Queries) GetMessagesAttachments(ctx context.Context, messageID pgtype.UUID) ([]GetMessagesAttachmentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, getMessagesAttachments, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []GetMessagesAttachmentsRow
|
||||
for rows.Next() {
|
||||
var i GetMessagesAttachmentsRow
|
||||
if err := rows.Scan(&i.AttachmentID, &i.Position); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockAttachmentsForMessage = `-- name: LockAttachmentsForMessage :many
|
||||
SELECT id, status FROM attachments
|
||||
WHERE chat_id = $1 AND id = ANY($2::uuid[])
|
||||
ORDER BY id FOR SHARE
|
||||
`
|
||||
|
||||
type LockAttachmentsForMessageParams struct {
|
||||
ChatID pgtype.UUID
|
||||
AttachmentIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type LockAttachmentsForMessageRow struct {
|
||||
ID pgtype.UUID
|
||||
Status string
|
||||
}
|
||||
|
||||
func (q *Queries) LockAttachmentsForMessage(ctx context.Context, arg LockAttachmentsForMessageParams) ([]LockAttachmentsForMessageRow, error) {
|
||||
rows, err := q.db.Query(ctx, lockAttachmentsForMessage, arg.ChatID, arg.AttachmentIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []LockAttachmentsForMessageRow
|
||||
for rows.Next() {
|
||||
var i LockAttachmentsForMessageRow
|
||||
if err := rows.Scan(&i.ID, &i.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
OwnerID pgtype.UUID
|
||||
Filename string
|
||||
ObjectKey pgtype.Text
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
Status string
|
||||
ErrorCode pgtype.Text
|
||||
StagingKey pgtype.Text
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
type AttachmentAttempt struct {
|
||||
JobID pgtype.UUID
|
||||
LeaseGeneration int32
|
||||
Attempt int32
|
||||
StartedAt pgtype.Timestamptz
|
||||
FinishedAt pgtype.Timestamptz
|
||||
Outcome pgtype.Text
|
||||
ErrorCode pgtype.Text
|
||||
}
|
||||
|
||||
type AttachmentJob struct {
|
||||
ID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
AttemptsStarted int32
|
||||
MaxAttempts int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LeaseGeneration int32
|
||||
LeaseUntil pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PublishedOriginalKey pgtype.Text
|
||||
}
|
||||
|
||||
type AttachmentReplay struct {
|
||||
RequestID pgtype.UUID
|
||||
JobID pgtype.UUID
|
||||
OperatorID string
|
||||
Reason string
|
||||
ExtraAttempts int32
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
Name string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int32
|
||||
Height int32
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID pgtype.UUID
|
||||
Title string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
SenderID pgtype.UUID
|
||||
Text string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type MessageIdempotency struct {
|
||||
UserID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
IdempotencyKey string
|
||||
MessageID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type MessagesAttachment struct {
|
||||
MessageID pgtype.UUID
|
||||
AttachmentID pgtype.UUID
|
||||
ChatID pgtype.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
type Outbox struct {
|
||||
ID pgtype.UUID
|
||||
JobID pgtype.UUID
|
||||
Payload []byte
|
||||
AvailableAt pgtype.Timestamptz
|
||||
SentAt pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
DedupKey string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID pgtype.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: outbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createInitialOutboxEvent = `-- name: CreateInitialOutboxEvent :exec
|
||||
INSERT INTO outbox (job_id, payload, available_at, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, 1, created_at),
|
||||
next_attempt_at, 'initial/' || id
|
||||
FROM attachment_jobs WHERE id = $1::uuid
|
||||
`
|
||||
|
||||
func (q *Queries) CreateInitialOutboxEvent(ctx context.Context, jobID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, createInitialOutboxEvent, jobID)
|
||||
return err
|
||||
}
|
||||
|
||||
const enqueueExpiredLeases = `-- name: EnqueueExpiredLeases :many
|
||||
WITH expired AS (
|
||||
SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key, 'recovery/' || j.id || '/' || j.lease_generation AS recovery_key
|
||||
FROM attachment_jobs AS j
|
||||
JOIN attachments AS a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
WHERE a.status = 'processing' AND j.lease_until <= clock_timestamp()
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM outbox AS o WHERE o.dedup_key = 'recovery/' || j.id || '/' || j.lease_generation
|
||||
)
|
||||
ORDER BY j.lease_until, j.id
|
||||
LIMIT $1
|
||||
FOR UPDATE OF j SKIP LOCKED
|
||||
)
|
||||
INSERT INTO outbox (job_id, payload, dedup_key)
|
||||
SELECT id, attachment_job_payload(id, attachment_id, pipeline_version,
|
||||
LEAST(attempts_started + 1, max_attempts), clock_timestamp()),
|
||||
recovery_key
|
||||
FROM expired
|
||||
ON CONFLICT (dedup_key) DO NOTHING
|
||||
RETURNING id, job_id, payload, available_at, sent_at, created_at, dedup_key
|
||||
`
|
||||
|
||||
func (q *Queries) EnqueueExpiredLeases(ctx context.Context, batchSize int32) ([]Outbox, error) {
|
||||
rows, err := q.db.Query(ctx, enqueueExpiredLeases, batchSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Outbox
|
||||
for rows.Next() {
|
||||
var i Outbox
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.JobID,
|
||||
&i.Payload,
|
||||
&i.AvailableAt,
|
||||
&i.SentAt,
|
||||
&i.CreatedAt,
|
||||
&i.DedupKey,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markOutboxEventSent = `-- name: MarkOutboxEventSent :execrows
|
||||
UPDATE outbox SET sent_at = clock_timestamp()
|
||||
WHERE id = $1 AND sent_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) MarkOutboxEventSent(ctx context.Context, id pgtype.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markOutboxEventSent, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const nextPendingOutboxEvent = `-- name: NextPendingOutboxEvent :one
|
||||
SELECT id, job_id, payload, available_at, sent_at, created_at, dedup_key
|
||||
FROM outbox
|
||||
WHERE sent_at IS NULL AND available_at <= statement_timestamp()
|
||||
ORDER BY available_at, id
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`
|
||||
|
||||
func (q *Queries) NextPendingOutboxEvent(ctx context.Context) (Outbox, error) {
|
||||
row := q.db.QueryRow(ctx, nextPendingOutboxEvent)
|
||||
var i Outbox
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.JobID,
|
||||
&i.Payload,
|
||||
&i.AvailableAt,
|
||||
&i.SentAt,
|
||||
&i.CreatedAt,
|
||||
&i.DedupKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: users.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, password_hash, created_at
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByID = `-- name: GetUserByID :one
|
||||
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByID, id)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUsername, username)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: versioned_pipeline.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getPipelineJobID = `-- name: GetPipelineJobID :one
|
||||
SELECT id FROM attachment_jobs
|
||||
WHERE attachment_id = $1::uuid AND pipeline_version = $2::int
|
||||
`
|
||||
|
||||
type GetPipelineJobIDParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
func (q *Queries) GetPipelineJobID(ctx context.Context, arg GetPipelineJobIDParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, getPipelineJobID, arg.AttachmentID, arg.PipelineVersion)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const getPublishedOriginalKey = `-- name: GetPublishedOriginalKey :one
|
||||
SELECT published_original_key FROM attachment_jobs
|
||||
WHERE attachment_id = $1::uuid AND pipeline_version = $2::int
|
||||
AND published_original_key IS NOT NULL
|
||||
`
|
||||
|
||||
type GetPublishedOriginalKeyParams struct {
|
||||
AttachmentID pgtype.UUID
|
||||
PipelineVersion int32
|
||||
}
|
||||
|
||||
func (q *Queries) GetPublishedOriginalKey(ctx context.Context, arg GetPublishedOriginalKeyParams) (pgtype.Text, error) {
|
||||
row := q.db.QueryRow(ctx, getPublishedOriginalKey, arg.AttachmentID, arg.PipelineVersion)
|
||||
var published_original_key pgtype.Text
|
||||
err := row.Scan(&published_original_key)
|
||||
return published_original_key, err
|
||||
}
|
||||
|
||||
const isPublishedOriginalKey = `-- name: IsPublishedOriginalKey :one
|
||||
SELECT EXISTS (SELECT 1 FROM attachment_jobs WHERE published_original_key = $1::text)
|
||||
`
|
||||
|
||||
func (q *Queries) IsPublishedOriginalKey(ctx context.Context, objectKey string) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, isPublishedOriginalKey, objectKey)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const queueAttachmentUpgrade = `-- name: QueueAttachmentUpgrade :one
|
||||
UPDATE attachments
|
||||
SET pipeline_version = 2, status = 'queued', staging_key = $1::text,
|
||||
object_key = NULL, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $2::uuid AND pipeline_version = 1
|
||||
RETURNING id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version
|
||||
`
|
||||
|
||||
type QueueAttachmentUpgradeParams struct {
|
||||
SourceKey string
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) QueueAttachmentUpgrade(ctx context.Context, arg QueueAttachmentUpgradeParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, queueAttachmentUpgrade, arg.SourceKey, arg.ID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.Filename,
|
||||
&i.ObjectKey,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.StagingKey,
|
||||
&i.PipelineVersion,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const supersedeAttachmentJob = `-- name: SupersedeAttachmentJob :exec
|
||||
WITH superseded AS (
|
||||
UPDATE attachment_jobs
|
||||
SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1::uuid
|
||||
RETURNING id, updated_at
|
||||
)
|
||||
UPDATE attachment_attempts AS attempt
|
||||
SET outcome = 'superseded', error_code = 'superseded', finished_at = superseded.updated_at
|
||||
FROM superseded
|
||||
WHERE attempt.job_id = superseded.id AND attempt.finished_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) SupersedeAttachmentJob(ctx context.Context, jobID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, supersedeAttachmentJob, jobID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Package fault provides one-shot pause points for an isolated lab Compose project.
|
||||
package fault
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Pause(ctx context.Context, point, id string) error {
|
||||
dir := os.Getenv("LAB5_FAULT_DIR")
|
||||
if dir == "" {
|
||||
return nil
|
||||
}
|
||||
base := filepath.Join(dir, point)
|
||||
if err := os.Rename(base+".arm", base+".used"); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(base+".hit", []byte(id+"\n"), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
wait, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
poll := time.NewTicker(50 * time.Millisecond)
|
||||
defer poll.Stop()
|
||||
for {
|
||||
if _, err := os.Stat(base + ".release"); err == nil {
|
||||
return nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-wait.Done():
|
||||
return wait.Err()
|
||||
case <-poll.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package imageproc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"highload/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxBytes = 10 * 1024 * 1024
|
||||
MaxPixels = 40_000_000
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidImage = errors.New("invalid image")
|
||||
ErrResourceLimit = errors.New("image processing resource limit")
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Path string
|
||||
Variant model.AttachmentVariant
|
||||
}
|
||||
|
||||
type variantSpec struct {
|
||||
name, extension, mime string
|
||||
width, height int
|
||||
args []string
|
||||
}
|
||||
|
||||
func Generate(ctx context.Context, dir, input, mime string, version int32) ([]File, error) {
|
||||
var jpegQuality, webpQuality string
|
||||
switch version {
|
||||
case 1:
|
||||
jpegQuality, webpQuality = "85", "80"
|
||||
case 2:
|
||||
jpegQuality, webpQuality = "90", "72"
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported image pipeline version %d", version)
|
||||
}
|
||||
f, err := os.Open(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, format, decodeErr := image.DecodeConfig(io.LimitReader(f, MaxBytes))
|
||||
_ = f.Close()
|
||||
if decodeErr != nil || (format != "png" && format != "jpeg") || mime != "image/"+format ||
|
||||
cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > MaxPixels/cfg.Height {
|
||||
return nil, ErrInvalidImage
|
||||
}
|
||||
// Paths are generated on the server; input format is independently verified.
|
||||
source := format + ":" + input
|
||||
orient, err := magick(ctx, "identify", "-ping", "-format", "%[orientation]", source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w, h := cfg.Width, cfg.Height
|
||||
switch strings.TrimSpace(orient) {
|
||||
case "LeftTop", "RightTop", "RightBottom", "LeftBottom":
|
||||
w, h = h, w
|
||||
}
|
||||
tw, th := fit(w, h, 256)
|
||||
ow, oh := fit(w, h, 1280)
|
||||
side := min(w, h)
|
||||
specs := []variantSpec{
|
||||
{name: "thumbnail", extension: "jpg", mime: "image/jpeg", width: tw, height: th,
|
||||
args: []string{"-resize", geometry(tw, th), "-quality", jpegQuality}},
|
||||
{name: "crop", extension: "jpg", mime: "image/jpeg", width: 128, height: 128,
|
||||
args: []string{"-gravity", "center", "-crop", fmt.Sprintf("%dx%d+0+0", side, side), "+repage", "-resize", "128x128!", "-quality", jpegQuality}},
|
||||
{name: "optimized", extension: "webp", mime: "image/webp", width: ow, height: oh,
|
||||
args: []string{"-resize", geometry(ow, oh), "-quality", webpQuality, "-define", "webp:method=4"}},
|
||||
}
|
||||
files := make([]File, 0, len(specs))
|
||||
for _, spec := range specs {
|
||||
out := filepath.Join(dir, spec.name+"."+spec.extension)
|
||||
args := []string{"-regard-warnings", source, "-auto-orient"}
|
||||
if spec.mime == "image/jpeg" {
|
||||
args = append(args, "-background", "white", "-alpha", "remove", "-alpha", "off")
|
||||
}
|
||||
args = append(args, spec.args...)
|
||||
args = append(args, "-strip", out)
|
||||
if _, err := magick(ctx, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, err := inspectFile(ctx, out, spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files = append(files, File{Path: out, Variant: meta})
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func fit(w, h, bound int) (int, int) {
|
||||
if max(w, h) <= bound {
|
||||
return w, h
|
||||
}
|
||||
if w >= h {
|
||||
return bound, max(1, h*bound/w)
|
||||
}
|
||||
return max(1, w*bound/h), bound
|
||||
}
|
||||
|
||||
func geometry(w, h int) string {
|
||||
return fmt.Sprintf("%dx%d!", w, h)
|
||||
}
|
||||
|
||||
func inspectFile(ctx context.Context, path string, spec variantSpec) (model.AttachmentVariant, error) {
|
||||
var meta model.AttachmentVariant
|
||||
desc, err := magick(ctx, "identify", "-ping", "-format", "%m %w %h", path)
|
||||
if err != nil {
|
||||
return meta, err
|
||||
}
|
||||
format := strings.ToUpper(strings.TrimPrefix(spec.mime, "image/"))
|
||||
if strings.TrimSpace(desc) != format+" "+strconv.Itoa(spec.width)+" "+strconv.Itoa(spec.height) {
|
||||
return meta, fmt.Errorf("generated variant has unexpected format or size")
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return meta, err
|
||||
}
|
||||
defer f.Close()
|
||||
sum := sha256.New()
|
||||
size, err := io.Copy(sum, f)
|
||||
if err != nil {
|
||||
return meta, err
|
||||
}
|
||||
return model.AttachmentVariant{Name: spec.name, ContentType: spec.mime, Width: spec.width, Height: spec.height,
|
||||
SizeBytes: size, SHA256: hex.EncodeToString(sum.Sum(nil))}, nil
|
||||
}
|
||||
|
||||
func magick(ctx context.Context, args ...string) (string, error) {
|
||||
cmd := exec.CommandContext(ctx, "magick", args...)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if err == nil {
|
||||
return string(out), nil
|
||||
}
|
||||
message := strings.ToLower(string(out))
|
||||
if strings.Contains(message, "cache resources exhausted") || strings.Contains(message, "time limit") ||
|
||||
strings.Contains(message, "memory allocation") || strings.Contains(message, "list length exceeds") {
|
||||
return "", ErrResourceLimit
|
||||
}
|
||||
if strings.Contains(message, "corrupt") || strings.Contains(message, "unexpected end") ||
|
||||
strings.Contains(message, "insufficient image data") || strings.Contains(message, "decode") {
|
||||
return "", ErrInvalidImage
|
||||
}
|
||||
return "", fmt.Errorf("ImageMagick command failed: %w", err)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Attachment struct {
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ObjectKey string
|
||||
StagingKey string
|
||||
ErrorCode *string
|
||||
Variants []AttachmentVariant
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
Status string
|
||||
PipelineVersion int32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
Name string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int
|
||||
Height int
|
||||
SHA256 string
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type AttachmentJob struct {
|
||||
ID string
|
||||
AttachmentID string
|
||||
PipelineVersion int32
|
||||
AttemptsStarted int32
|
||||
MaxAttempts int32
|
||||
LeaseGeneration int32
|
||||
LeaseUntil time.Time
|
||||
}
|
||||
|
||||
type AttachmentJobState struct {
|
||||
AttachmentID string
|
||||
PipelineVersion int32
|
||||
ID string
|
||||
Status string
|
||||
LeaseGeneration int32
|
||||
AttemptsStarted int32
|
||||
MaxAttempts int32
|
||||
LeaseUntil *time.Time
|
||||
LeaseExpired bool
|
||||
NextAttemptAt *time.Time
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
AttachmentIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
RevokedAt *time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/storage"
|
||||
)
|
||||
|
||||
type Cleanup struct {
|
||||
Repo *postgres.AttachmentRepository
|
||||
Objects storage.ObjectCleanup
|
||||
Grace time.Duration
|
||||
Retention time.Duration
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
func (c Cleanup) RunOnce(ctx context.Context) (int, error) {
|
||||
policy := postgres.CleanupPolicy{Now: time.Now(), Grace: c.Grace, Retention: c.Retention, DryRun: c.DryRun}
|
||||
removed := 0
|
||||
for _, prefix := range []string{"staging/", "results/", "attachments/"} {
|
||||
var token *string
|
||||
for {
|
||||
pageCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
objects, next, err := c.Objects.ListPage(pageCtx, token, prefix)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return removed, err
|
||||
}
|
||||
for _, obj := range objects {
|
||||
eligible, err := c.Repo.CleanupObject(ctx, obj, policy, c.Objects.Delete)
|
||||
if err != nil {
|
||||
return removed, err
|
||||
}
|
||||
if eligible {
|
||||
removed++
|
||||
}
|
||||
}
|
||||
if next == nil {
|
||||
break
|
||||
}
|
||||
token = next
|
||||
}
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
func (c Cleanup) Serve(ctx context.Context, period time.Duration) {
|
||||
for ctx.Err() == nil {
|
||||
count, err := c.RunOnce(ctx)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
slog.Warn("cleanup pass failed", "error", err)
|
||||
}
|
||||
if count > 0 {
|
||||
slog.Info("cleanup pass", "objects", count, "dry_run", c.DryRun)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(period):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"highload/internal/broker"
|
||||
"highload/internal/config"
|
||||
"highload/internal/fault"
|
||||
"highload/internal/imageproc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type WorkerRepository interface {
|
||||
ClaimJob(context.Context, string, time.Time) (*model.AttachmentJob, error)
|
||||
GetAttachmentJobState(context.Context, string) (*model.AttachmentJobState, error)
|
||||
GetAttachmentByID(context.Context, string) (*model.Attachment, error)
|
||||
CompleteJob(context.Context, string, int32, string, []model.AttachmentVariant) (bool, error)
|
||||
PublishedObjectKeys(context.Context, string, int32) ([]string, error)
|
||||
ScheduleRetry(context.Context, string, int32, string, time.Time) (bool, error)
|
||||
FailJob(context.Context, string, int32, string) (bool, error)
|
||||
}
|
||||
|
||||
type WorkerObjects interface {
|
||||
storage.ObjectWriter
|
||||
Head(context.Context, string) error
|
||||
}
|
||||
|
||||
type Worker struct {
|
||||
Repo WorkerRepository
|
||||
Objects WorkerObjects
|
||||
Config config.Pipeline
|
||||
}
|
||||
|
||||
type message struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Type string `json:"type"`
|
||||
JobID string `json:"job_id"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int32 `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
Tracestate string `json:"tracestate,omitempty"`
|
||||
}
|
||||
|
||||
func decodeMessage(payload []byte) (message, error) {
|
||||
var msg message
|
||||
if len(payload) > 4096 {
|
||||
return msg, errors.New("oversize job")
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(payload))
|
||||
d.DisallowUnknownFields()
|
||||
if err := d.Decode(&msg); err != nil {
|
||||
return msg, err
|
||||
}
|
||||
if err := d.Decode(new(any)); err != io.EOF {
|
||||
return msg, errors.New("trailing job data")
|
||||
}
|
||||
jobID, err1 := uuid.Parse(msg.JobID)
|
||||
attachmentID, err2 := uuid.Parse(msg.AttachmentID)
|
||||
if err1 != nil || err2 != nil || msg.SchemaVersion != 1 || msg.Type != "attachment.process.v1" ||
|
||||
msg.PipelineVersion <= 0 || msg.Attempt <= 0 || msg.CreatedAt.IsZero() {
|
||||
return msg, errors.New("invalid job envelope")
|
||||
}
|
||||
msg.JobID, msg.AttachmentID = jobID.String(), attachmentID.String()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (w Worker) Serve(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
if err := w.consume(ctx); err != nil && ctx.Err() == nil {
|
||||
slog.Warn("worker consumer reconnecting", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w Worker) consume(ctx context.Context) error {
|
||||
conn, ch, err := broker.Connect(w.Config.BrokerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer broker.Close(conn)
|
||||
if err := ch.Qos(w.Config.Prefetch, 0, false); err != nil {
|
||||
return err
|
||||
}
|
||||
deliveries, err := ch.ConsumeWithContext(ctx, broker.Queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case delivery, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("broker delivery channel closed")
|
||||
}
|
||||
msg, err := decodeMessage(delivery.Body)
|
||||
if err != nil {
|
||||
slog.Warn("rejecting invalid job envelope")
|
||||
if err := delivery.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
reject, err := w.handle(ctx, msg)
|
||||
switch {
|
||||
case err != nil:
|
||||
// Closing the channel requeues an unacknowledged delivery.
|
||||
return err
|
||||
case reject:
|
||||
if err := delivery.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
if err := delivery.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w Worker) handle(ctx context.Context, msg message) (bool, error) {
|
||||
state, err := w.Repo.GetAttachmentJobState(ctx, msg.JobID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if state.AttachmentID != msg.AttachmentID || state.PipelineVersion != msg.PipelineVersion {
|
||||
return true, nil
|
||||
}
|
||||
if state.Status == "superseded" {
|
||||
return false, nil
|
||||
}
|
||||
job, err := w.Repo.ClaimJob(ctx, msg.JobID, time.Now().Add(w.Config.Lease))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if job == nil {
|
||||
return false, w.handleUnclaimed(ctx, msg)
|
||||
}
|
||||
slog.Info("job claimed", "job_id", job.ID, "attempt", job.AttemptsStarted, "lease_generation", job.LeaseGeneration)
|
||||
|
||||
attemptCtx, cancel := context.WithTimeout(ctx, w.Config.Timeout)
|
||||
err = w.process(attemptCtx, job)
|
||||
cancel()
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, errLostLease) {
|
||||
return false, w.handleUnclaimed(ctx, msg)
|
||||
}
|
||||
return false, w.saveFailure(ctx, job, err)
|
||||
}
|
||||
|
||||
pauseCtx, pauseCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer pauseCancel()
|
||||
return false, fault.Pause(pauseCtx, "before_ack", job.ID)
|
||||
}
|
||||
|
||||
func (w Worker) handleUnclaimed(ctx context.Context, msg message) error {
|
||||
state, err := w.Repo.GetAttachmentJobState(ctx, msg.JobID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch state.Status {
|
||||
case "ready":
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
keys, err := w.Repo.PublishedObjectKeys(checkCtx, state.AttachmentID, state.PipelineVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, key := range keys {
|
||||
if err := w.Objects.Head(checkCtx, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case "failed", "queued", "superseded":
|
||||
return nil // A queued retry is already in the transactionally durable outbox.
|
||||
case "processing":
|
||||
if state.AttemptsStarted >= state.MaxAttempts && state.LeaseExpired {
|
||||
_, err = w.Repo.FailJob(ctx, msg.JobID, state.LeaseGeneration, "retry_exhausted")
|
||||
return err
|
||||
}
|
||||
return nil // The recovery loop publishes one event for this expired lease.
|
||||
default:
|
||||
return errors.New("unrecognized job state")
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
errLostLease = errors.New("job lease lost")
|
||||
errOriginalMismatch = errors.New("staging hash or size differs")
|
||||
)
|
||||
|
||||
func (w Worker) process(ctx context.Context, job *model.AttachmentJob) error {
|
||||
att, err := w.Repo.GetAttachmentByID(ctx, job.AttachmentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if att.PipelineVersion != job.PipelineVersion {
|
||||
return errLostLease
|
||||
}
|
||||
if att.StagingKey == "" {
|
||||
return errOriginalMismatch
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "attachment-job-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
source := filepath.Join(dir, "input")
|
||||
if err := w.download(ctx, att, source); err != nil {
|
||||
return err
|
||||
}
|
||||
files, err := imageproc.Generate(ctx, dir, source, att.ContentType, job.PipelineVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := fault.Pause(ctx, "before_objects", job.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
prefix := fmt.Sprintf("results/%s/v%d/%d/", job.AttachmentID, job.PipelineVersion, job.LeaseGeneration)
|
||||
originalKey := prefix + "original"
|
||||
if err := w.putFile(ctx, originalKey, att.ContentType, source, att.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
variants := make([]model.AttachmentVariant, 0, len(files))
|
||||
for _, f := range files {
|
||||
v := f.Variant
|
||||
v.ObjectKey = prefix + filepath.Base(f.Path)
|
||||
if err := w.putFile(ctx, v.ObjectKey, v.ContentType, f.Path, v.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
variants = append(variants, v)
|
||||
}
|
||||
if err := fault.Pause(ctx, "after_objects", job.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
done, err := w.Repo.CompleteJob(ctx, job.ID, job.LeaseGeneration, originalKey, variants)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !done {
|
||||
slog.Info("job finalization rejected", "job_id", job.ID, "lease_generation", job.LeaseGeneration)
|
||||
return errLostLease
|
||||
}
|
||||
slog.Info("job ready", "job_id", job.ID, "lease_generation", job.LeaseGeneration)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w Worker) download(ctx context.Context, att *model.Attachment, path string) error {
|
||||
if att.SizeBytes <= 0 || att.SizeBytes > imageproc.MaxBytes {
|
||||
return errOriginalMismatch
|
||||
}
|
||||
|
||||
reader, err := w.Objects.Get(ctx, att.StagingKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.New()
|
||||
n, copyErr := io.Copy(io.MultiWriter(f, sum), io.LimitReader(reader, att.SizeBytes+1))
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if n != att.SizeBytes || hex.EncodeToString(sum.Sum(nil)) != att.SHA256 {
|
||||
return errOriginalMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w Worker) putFile(ctx context.Context, key, mime, path string, size int64) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return w.Objects.Put(ctx, key, mime, f, size)
|
||||
}
|
||||
|
||||
func (w Worker) saveFailure(ctx context.Context, job *model.AttachmentJob, failure error) error {
|
||||
code := "processing_failed"
|
||||
permanent := false
|
||||
switch {
|
||||
case errors.Is(failure, errOriginalMismatch), errors.Is(failure, imageproc.ErrInvalidImage):
|
||||
code, permanent = "invalid_image", true
|
||||
case errors.Is(failure, imageproc.ErrResourceLimit):
|
||||
code, permanent = "resource_limit", true
|
||||
case errors.Is(failure, storage.ErrObjectNotFound):
|
||||
code, permanent = "original_missing", true
|
||||
case errors.Is(failure, storage.ErrServiceUnavailable):
|
||||
code = "s3_unavailable"
|
||||
case errors.Is(failure, context.DeadlineExceeded):
|
||||
code = "processing_timeout"
|
||||
}
|
||||
dbCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if permanent || job.AttemptsStarted >= job.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
changed, err := w.Repo.FailJob(dbCtx, job.ID, job.LeaseGeneration, code)
|
||||
if changed {
|
||||
slog.Warn("job failed", "job_id", job.ID, "error_code", code)
|
||||
}
|
||||
return err
|
||||
}
|
||||
// The floor avoids immediate requeue loops. The upper bound grows with
|
||||
// each attempt and is capped to keep the lab recoverable.
|
||||
upper := min(30*time.Second, w.Config.RetryBase<<min(job.AttemptsStarted-1, 4))
|
||||
delay := time.Second + time.Duration(rand.Int64N(int64(upper-time.Second+1)))
|
||||
changed, err := w.Repo.ScheduleRetry(dbCtx, job.ID, job.LeaseGeneration, code, time.Now().Add(delay))
|
||||
if changed {
|
||||
slog.Info("job retry scheduled", "job_id", job.ID, "error_code", code, "delay_ms", delay.Milliseconds())
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateAttachment(ctx context.Context, params CreateAttachmentParams) (*model.Attachment, error)
|
||||
GetAttachmentForUser(ctx context.Context, userID, attachmentID string) (*model.Attachment, error)
|
||||
ExistsByObjectKey(ctx context.Context, key string) (bool, error)
|
||||
WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, AttachmentTx) error) (bool, error)
|
||||
}
|
||||
|
||||
type AttachmentKey struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentReconcileRepository interface {
|
||||
ListAttachmentKeys(ctx context.Context, afterKey string, pageSize int32) ([]AttachmentKey, error)
|
||||
GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error)
|
||||
WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, AttachmentTx) error) (bool, error)
|
||||
}
|
||||
|
||||
type CreateAttachmentParams struct {
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
Sha256 string
|
||||
SizeBytes int64
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
)
|
||||
|
||||
type AttachmentTx interface {
|
||||
CreateAttachment(ctx context.Context, params CreateAttachmentParams) (*model.Attachment, error)
|
||||
CreateQueued(ctx context.Context, id, chatID, ownerID, mime, sha256, key, filename string, size int64) (*model.Attachment, error)
|
||||
ExistsByObjectKey(ctx context.Context, key string) (bool, error)
|
||||
GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error)
|
||||
GetChatByID(ctx context.Context, id string) (*model.Chat, error)
|
||||
GetChatsByUserID(ctx context.Context, userID string, limit int, after *ChatPosition) ([]*model.Chat, error)
|
||||
}
|
||||
|
||||
type ChatPosition struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrAlreadyExists = errors.New("already exists")
|
||||
ErrDatabase = errors.New("database error")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrServiceUnavailable = errors.New("database unavailable")
|
||||
ErrServerError = errors.New("server error")
|
||||
ErrRedisNotAnswer = errors.New("redis not not answer")
|
||||
ErrConflict = errors.New("data conflict")
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text, key string, attachmentIDs []string) (*model.Message, error)
|
||||
GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *MessagePosition) ([]*model.Message, error)
|
||||
}
|
||||
|
||||
type MessagePosition struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const attachmentTransactionTimeout = 5 * time.Second
|
||||
|
||||
type AttachmentRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
maxAttempts int32
|
||||
}
|
||||
|
||||
func NewAttachmentRepository(queries *sqlc.Queries, pool *pgxpool.Pool, attemptLimit ...int32) *AttachmentRepository {
|
||||
maxAttempts := int32(5)
|
||||
if len(attemptLimit) > 0 {
|
||||
maxAttempts = attemptLimit[0]
|
||||
}
|
||||
return &AttachmentRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
maxAttempts: maxAttempts,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) CreateAttachment(ctx context.Context, params repository.CreateAttachmentParams) (*model.Attachment, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
chatUUID, err := getUUIDFromString(params.ChatID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
ownerUUID, err := getUUIDFromString(params.OwnerID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
sqlcParams := sqlc.CreateAttachmentParams{
|
||||
ChatID: *chatUUID,
|
||||
OwnerID: *ownerUUID,
|
||||
Filename: params.Filename,
|
||||
ObjectKey: params.ObjectKey,
|
||||
ContentType: params.ContentType,
|
||||
SizeBytes: params.SizeBytes,
|
||||
Sha256: params.Sha256,
|
||||
}
|
||||
|
||||
sqlcAttachment, err := r.queries.CreateAttachment(dbCtx, sqlcParams)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
attachment := mapAttachmentSqlcToModel(sqlc.Attachment(sqlcAttachment))
|
||||
return attachment, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetAttachmentForUser(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
|
||||
userUUID, err := getUUIDFromString(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attachmentUUID, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
params := sqlc.GetAttachmentForUserParams{
|
||||
AttachmentID: *attachmentUUID,
|
||||
UserID: *userUUID,
|
||||
}
|
||||
|
||||
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{
|
||||
IsoLevel: pgx.RepeatableRead,
|
||||
AccessMode: pgx.ReadOnly,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
sqlcAttachment, err := txQueries.GetAttachmentForUser(txCtx, params)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
attachment := mapAttachmentSqlcToModel(sqlcAttachment)
|
||||
|
||||
if sqlcAttachment.Status == "ready" {
|
||||
variants, err := txQueries.ListAttachmentVariants(txCtx, sqlc.ListAttachmentVariantsParams{
|
||||
AttachmentID: sqlcAttachment.ID,
|
||||
PipelineVersion: sqlcAttachment.PipelineVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
for _, v := range variants {
|
||||
attachment.Variants = append(attachment.Variants, model.AttachmentVariant{
|
||||
Name: v.Name,
|
||||
ObjectKey: v.ObjectKey,
|
||||
ContentType: v.ContentType,
|
||||
SizeBytes: v.SizeBytes,
|
||||
Width: int(v.Width),
|
||||
Height: int(v.Height),
|
||||
SHA256: v.Sha256,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err = tx.Commit(txCtx); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
exists, err := r.queries.AttachmentExistsByObjectKey(dbCtx, key)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListAttachmentKeys(ctx context.Context, afterKey string, pageSize int32) ([]repository.AttachmentKey, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.queries.ListAttachmentKeys(dbCtx, sqlc.ListAttachmentKeysParams{
|
||||
AfterKey: pgtype.Text{String: afterKey, Valid: true},
|
||||
PageSize: pageSize,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
keys := make([]repository.AttachmentKey, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
keys = append(keys, repository.AttachmentKey{
|
||||
ID: row.ID.String(), ObjectKey: row.ObjectKey.String, CreatedAt: row.CreatedAt.Time,
|
||||
})
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
attachmentID, err := getUUIDFromString(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err := r.queries.GetAttachmentByID(dbCtx, *attachmentID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
return mapAttachmentSqlcToModel(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
|
||||
defer rollbackTx(ctx, tx)
|
||||
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
locked, err := txQueries.TryLockAttachmentObjectKey(txCtx, key)
|
||||
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
|
||||
if !locked {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
txRepo := &AttachmentRepository{queries: txQueries, maxAttempts: r.maxAttempts}
|
||||
|
||||
if err = fn(txCtx, txRepo); err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
if err = tx.Commit(txCtx); err != nil {
|
||||
return true, convertDBError(err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) CreateQueued(ctx context.Context, queuedID, chatID, ownerID, mime, sha256, key, filename string, size int64) (*model.Attachment, error) {
|
||||
queuedUUID, err := getUUIDFromString(queuedID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chatUUID, err := getUUIDFromString(chatID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
ownerUUID, err := getUUIDFromString(ownerID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
cqaParams := sqlc.CreateQueuedAttachmentParams{
|
||||
ID: *queuedUUID,
|
||||
ChatID: *chatUUID,
|
||||
OwnerID: *ownerUUID,
|
||||
Filename: filename,
|
||||
ContentType: mime,
|
||||
SizeBytes: size,
|
||||
Sha256: sha256,
|
||||
StagingKey: pgtype.Text{String: key, Valid: true},
|
||||
}
|
||||
|
||||
// The upload path already holds the object lock in a transaction.
|
||||
if r.pool == nil {
|
||||
return r.insertQueued(ctx, r.queries, cqaParams)
|
||||
}
|
||||
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
queued, err := r.insertQueued(txCtx, r.queries.WithTx(tx), cqaParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
return queued, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) insertQueued(txCtx context.Context, txQueries *sqlc.Queries, cqaParams sqlc.CreateQueuedAttachmentParams) (*model.Attachment, error) {
|
||||
|
||||
sqlcAttachment, err := txQueries.CreateQueuedAttachment(txCtx, cqaParams)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
if _, err := r.createPipelineJob(txCtx, txQueries, sqlcAttachment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return mapAttachmentSqlcToModel(sqlcAttachment), nil
|
||||
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ClaimJob(ctx context.Context, jobID string, leaseUntil time.Time) (*model.AttachmentJob, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
jobUUID, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
arg := sqlc.ClaimJobParams{
|
||||
NewLeaseUntil: pgtype.Timestamptz{Time: leaseUntil, Valid: true},
|
||||
JobID: *jobUUID,
|
||||
}
|
||||
|
||||
row, err := r.queries.ClaimJob(dbCtx, arg)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
return &model.AttachmentJob{
|
||||
ID: row.ID.String(),
|
||||
AttachmentID: row.AttachmentID.String(),
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
AttemptsStarted: row.AttemptsStarted,
|
||||
MaxAttempts: row.MaxAttempts,
|
||||
LeaseGeneration: row.LeaseGeneration,
|
||||
LeaseUntil: row.LeaseUntil.Time,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetAttachmentJobState(ctx context.Context, jobID string) (*model.AttachmentJobState, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
jobUUID, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
row, err := r.queries.GetAttachmentJobState(dbCtx, *jobUUID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
state := &model.AttachmentJobState{
|
||||
AttachmentID: row.AttachmentID.String(),
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
ID: row.ID.String(),
|
||||
Status: row.Status,
|
||||
LeaseGeneration: row.LeaseGeneration,
|
||||
AttemptsStarted: row.AttemptsStarted,
|
||||
MaxAttempts: row.MaxAttempts,
|
||||
LeaseExpired: row.LeaseExpired,
|
||||
}
|
||||
|
||||
if row.LeaseUntil.Valid {
|
||||
state.LeaseUntil = &row.LeaseUntil.Time
|
||||
}
|
||||
if row.NextAttemptAt.Valid {
|
||||
state.NextAttemptAt = &row.NextAttemptAt.Time
|
||||
}
|
||||
|
||||
return state, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) CompleteJob(
|
||||
ctx context.Context, jobID string, leaseGeneration int32,
|
||||
originalKey string, variants []model.AttachmentVariant,
|
||||
) (bool, error) {
|
||||
jobUUID, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
lockedJob, err := txQueries.LockActiveAttachmentJob(txCtx, sqlc.LockActiveAttachmentJobParams{
|
||||
JobID: *jobUUID,
|
||||
LeaseGeneration: leaseGeneration,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
|
||||
const maxDimension = 1<<31 - 1
|
||||
for _, variant := range variants {
|
||||
if variant.Width <= 0 || variant.Width > maxDimension ||
|
||||
variant.Height <= 0 || variant.Height > maxDimension {
|
||||
return false, repository.ErrInvalidInput
|
||||
}
|
||||
err := txQueries.CreateAttachmentVariant(txCtx, sqlc.CreateAttachmentVariantParams{
|
||||
AttachmentID: lockedJob.AttachmentID,
|
||||
PipelineVersion: lockedJob.PipelineVersion,
|
||||
Name: variant.Name,
|
||||
ObjectKey: variant.ObjectKey,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Width: int32(variant.Width),
|
||||
Height: int32(variant.Height),
|
||||
Sha256: variant.SHA256,
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := txQueries.CompleteJob(txCtx, sqlc.CompleteJobParams{
|
||||
JobID: *jobUUID,
|
||||
LeaseGeneration: leaseGeneration,
|
||||
ObjectKey: originalKey,
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if rows == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return true, nil
|
||||
|
||||
}
|
||||
|
||||
func mapAttachmentSqlcToModel(sa sqlc.Attachment) *model.Attachment {
|
||||
var errorCode *string
|
||||
if sa.ErrorCode.Valid {
|
||||
errorCode = &sa.ErrorCode.String
|
||||
}
|
||||
return &model.Attachment{
|
||||
Variants: []model.AttachmentVariant{},
|
||||
ErrorCode: errorCode,
|
||||
StagingKey: sa.StagingKey.String,
|
||||
ID: sa.ID.String(),
|
||||
ChatID: sa.ChatID.String(),
|
||||
OwnerID: sa.OwnerID.String(),
|
||||
Filename: sa.Filename,
|
||||
ObjectKey: sa.ObjectKey.String,
|
||||
ContentType: sa.ContentType,
|
||||
SizeBytes: sa.SizeBytes,
|
||||
Status: sa.Status,
|
||||
PipelineVersion: sa.PipelineVersion,
|
||||
SHA256: sa.Sha256,
|
||||
CreatedAt: sa.CreatedAt.Time,
|
||||
UpdatedAt: sa.UpdatedAt.Time,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx),
|
||||
time.Second,
|
||||
)
|
||||
defer rollbackCancel()
|
||||
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}()
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
sqlcChat, err := txQueries.CreateChat(txCtx, title)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
Title: sqlcChat.Title,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
}
|
||||
|
||||
for _, id := range memberIDs {
|
||||
userID, err := getUUIDFromString(id)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
err = txQueries.CreateChatMember(txCtx, sqlc.CreateChatMemberParams{ChatID: sqlcChat.ID, UserID: *userID})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chat.MemberIDs = slices.Clone(memberIDs)
|
||||
|
||||
err = tx.Commit(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatByID(ctx context.Context, id string) (*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
sqlcChat, err := r.queries.GetChatByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := mapChatSqlcToModel(&sqlcChat)
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatsByUserID(ctx context.Context, userID string, limit int, after *repository.ChatPosition) ([]*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidUserID, err := getUUIDFromString(userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chats, err := r.queries.GetChatsByUserID(dbCtx, sqlc.GetChatsByUserIDParams{UserID: *uuidUserID, AfterCreatedAt: afterCreatedAt, AfterID: afterID, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
resultChats := make([]*model.Chat, len(chats))
|
||||
for index, sqlcChat := range chats {
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
resultChats[index] = &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
}
|
||||
|
||||
return resultChats, nil
|
||||
}
|
||||
|
||||
func mapChatSqlcToModel(sqlcChat *sqlc.GetChatByIDRow) *model.Chat {
|
||||
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
return &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func convertDBError(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
var netErr *net.OpError
|
||||
var dnsErr *net.DNSError
|
||||
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return fmt.Errorf("%w: %v", repository.ErrServiceUnavailable, err)
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return repository.ErrNotFound
|
||||
case errors.As(err, &pgErr):
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return repository.ErrAlreadyExists
|
||||
case "53300", "57P03", "08006", "08001", "57P01", "57P02":
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
case errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, pgconn.ErrConnClosed):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.Is(err, repository.ErrInvalidInput):
|
||||
return repository.ErrInvalidInput
|
||||
case errors.As(err, &netErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.As(err, &dnsErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) CreateMessage(ctx context.Context, chatID, senderID, text, key string, attachmentIDs []string) (*model.Message, error) {
|
||||
chat, err := getUUIDFromString(chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sender, err := getUUIDFromString(senderID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids := make([]pgtype.UUID, 0, len(attachmentIDs))
|
||||
canonical := make([]string, 0, len(attachmentIDs))
|
||||
for _, attachmentID := range attachmentIDs {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, *id)
|
||||
canonical = append(canonical, id.String())
|
||||
}
|
||||
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
|
||||
if err := q.LockMessageRequest(txCtx, sqlc.LockMessageRequestParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if err := q.DeleteExpiredMessageIdempotency(txCtx, sqlc.DeleteExpiredMessageIdempotencyParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
message, err := q.GetIdempotentMessage(txCtx, sqlc.GetIdempotentMessageParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key})
|
||||
switch {
|
||||
case err == nil:
|
||||
rows, err := q.GetMessagesAttachments(txCtx, message.ID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
saved := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
saved = append(saved, row.AttachmentID.String())
|
||||
}
|
||||
if message.Text != text || !slices.Equal(saved, canonical) {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
if len(ids) > 0 {
|
||||
rows, err := q.LockAttachmentsForMessage(txCtx, sqlc.LockAttachmentsForMessageParams{ChatID: *chat, AttachmentIds: ids})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if len(rows) != len(ids) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Status == "failed" {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
}
|
||||
}
|
||||
message, err = q.CreateMessage(txCtx, sqlc.CreateMessageParams{ChatID: *chat, SenderID: *sender, Text: text})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
for i, id := range ids {
|
||||
n, err := q.CreateMessagesAttachments(txCtx, sqlc.CreateMessagesAttachmentsParams{
|
||||
MessageID: message.ID, AttachmentID: id, ChatID: *chat, Position: int16(i),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
}
|
||||
n, err := q.InsertMessageIdempotency(txCtx, sqlc.InsertMessageIdempotencyParams{
|
||||
UserID: *sender, ChatID: *chat, IdempotencyKey: key, MessageID: message.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
default:
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
return &model.Message{
|
||||
ID: message.ID.String(), ChatID: message.ChatID.String(), SenderID: message.SenderID.String(),
|
||||
Text: message.Text, CreatedAt: message.CreatedAt.Time, AttachmentIDs: canonical,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *repository.MessagePosition) ([]*model.Message, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidChatID, err := getUUIDFromString(chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sqlcMessages, err := r.queries.GetMessagesByChatID(dbCtx, sqlc.GetMessagesByChatIDParams{ChatID: *uuidChatID, AfterID: afterID, AfterCreatedAt: afterCreatedAt, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
messageIDs := make([]pgtype.UUID, len(sqlcMessages))
|
||||
for index, _ := range sqlcMessages {
|
||||
messageIDs[index] = sqlcMessages[index].ID
|
||||
}
|
||||
|
||||
messageRow, err := r.queries.GetAttachmentsForMessages(dbCtx, messageIDs)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
mapMessagesAtt := make(map[string][]string)
|
||||
for index, _ := range messageRow {
|
||||
messageID := messageRow[index].MessageID.String()
|
||||
attachmentID := messageRow[index].AttachmentID.String()
|
||||
|
||||
mapMessagesAtt[messageID] = append(mapMessagesAtt[messageID], attachmentID)
|
||||
|
||||
}
|
||||
|
||||
messages := make([]*model.Message, len(sqlcMessages))
|
||||
|
||||
for index, sqlcMessage := range sqlcMessages {
|
||||
messages[index] = &model.Message{
|
||||
ID: sqlcMessage.ID.String(),
|
||||
ChatID: sqlcMessage.ChatID.String(),
|
||||
SenderID: sqlcMessage.SenderID.String(),
|
||||
Text: sqlcMessage.Text,
|
||||
AttachmentIDs: mapMessagesAtt[sqlcMessage.ID.String()],
|
||||
CreatedAt: sqlcMessage.CreatedAt.Time}
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func (r *AttachmentRepository) ScheduleRetry(ctx context.Context, jobID string, generation int32, code string, at time.Time) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := r.queries.ScheduleRetry(ctx, sqlc.ScheduleRetryParams{
|
||||
JobID: *id, LeaseGeneration: generation, ErrorCode: code,
|
||||
AvailableAt: pgtype.Timestamptz{Time: at, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return n == 1, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) FailJob(ctx context.Context, jobID string, generation int32, code string) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := r.queries.FailJob(ctx, sqlc.FailJobParams{
|
||||
JobID: *id, LeaseGeneration: generation, ErrorCode: code,
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return n == 1, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) EnqueueExpiredLeases(ctx context.Context, batchSize int32) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
rows, err := r.queries.EnqueueExpiredLeases(ctx, batchSize)
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
}
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// PublishPending holds the outbox row until the broker confirms delivery.
|
||||
func (r *AttachmentRepository) PublishPending(ctx context.Context, publish func(context.Context, sqlc.Outbox) error) (bool, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
row, err := q.NextPendingOutboxEvent(txCtx)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if err := publish(txCtx, row); err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := q.MarkOutboxEventSent(txCtx, row.ID)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return false, fmt.Errorf("outbox row disappeared during publish")
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListFailedJobs(ctx context.Context) ([]sqlc.ListFailedAttachmentJobsRow, error) {
|
||||
return r.queries.ListFailedAttachmentJobs(ctx, 100)
|
||||
}
|
||||
|
||||
// ReplayFailed checks the staged object while holding the same job lock as cleanup.
|
||||
func (r *AttachmentRepository) ReplayFailed(ctx context.Context, jobID, requestID, operator, reason string, extra int32, check func(context.Context, string) error) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
request, err := getUUIDFromString(requestID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
job, err := q.LockAttachmentJobForReplay(txCtx, *id)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
att, err := q.GetAttachmentByID(txCtx, job.AttachmentID)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if att.Status != "failed" || att.PipelineVersion != job.PipelineVersion {
|
||||
return false, nil
|
||||
}
|
||||
if !att.StagingKey.Valid {
|
||||
return false, fmt.Errorf("staging has expired: %w", repository.ErrNotFound)
|
||||
}
|
||||
if err := check(txCtx, att.StagingKey.String); err != nil {
|
||||
return false, err
|
||||
}
|
||||
rows, err := q.ReplayFailed(txCtx, sqlc.ReplayFailedParams{
|
||||
JobID: *id, RequestID: *request, OperatorID: operator, Reason: reason, ExtraAttempts: extra,
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if rows == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) PublishedObjectKeys(ctx context.Context, attachmentID string, version int32) ([]string, error) {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
original, err := r.queries.GetPublishedOriginalKey(ctx, sqlc.GetPublishedOriginalKeyParams{
|
||||
AttachmentID: *id, PipelineVersion: version,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
variants, err := r.queries.ListAttachmentVariants(ctx, sqlc.ListAttachmentVariantsParams{
|
||||
AttachmentID: *id, PipelineVersion: version,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
keys := []string{original.String}
|
||||
for _, v := range variants {
|
||||
keys = append(keys, v.ObjectKey)
|
||||
}
|
||||
if len(keys) != 4 {
|
||||
return nil, fmt.Errorf("ready job has an incomplete variant set")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/storage"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type CleanupPolicy struct {
|
||||
Now time.Time
|
||||
Grace time.Duration
|
||||
Retention time.Duration
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// CleanupObject synchronizes with upload, finalization and operator replay.
|
||||
// All candidate metadata is rechecked while holding the relevant lock.
|
||||
func (r *AttachmentRepository) CleanupObject(ctx context.Context, obj storage.ObjectInfo, policy CleanupPolicy, deleteObject func(context.Context, string) error) (bool, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
locked, err := q.TryLockAttachmentObjectKey(txCtx, obj.Key)
|
||||
if err != nil || !locked {
|
||||
return false, err
|
||||
}
|
||||
|
||||
staging, err := q.GetAttachmentByStagingKey(txCtx, obj.Key)
|
||||
keepObject := false
|
||||
switch {
|
||||
case err == nil:
|
||||
version := staging.PipelineVersion
|
||||
_, err = q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: staging.ID, PipelineVersion: staging.PipelineVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
staging, err = q.GetAttachmentByID(txCtx, staging.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if staging.PipelineVersion != version || staging.StagingKey.String != obj.Key ||
|
||||
(staging.Status == "ready" && staging.ObjectKey.String == obj.Key) {
|
||||
return false, nil
|
||||
}
|
||||
if staging.Status != "ready" && (staging.Status != "failed" || staging.UpdatedAt.Time.Add(policy.Retention).After(policy.Now)) {
|
||||
return false, nil
|
||||
}
|
||||
// An upgrade can stage the original published by the previous version.
|
||||
keepObject, err = q.IsPublishedOriginalKey(txCtx, obj.Key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return false, err
|
||||
default:
|
||||
if obj.LastModified.IsZero() || obj.LastModified.Add(policy.Grace).After(policy.Now) {
|
||||
return false, nil
|
||||
}
|
||||
if strings.HasPrefix(obj.Key, "results/") {
|
||||
// Keys include the job version and the generating lease.
|
||||
parts := strings.Split(obj.Key, "/")
|
||||
if len(parts) != 5 {
|
||||
return false, nil
|
||||
}
|
||||
id, idErr := getUUIDFromString(parts[1])
|
||||
version, versionErr := strconv.ParseInt(strings.TrimPrefix(parts[2], "v"), 10, 32)
|
||||
generation, generationErr := strconv.ParseInt(parts[3], 10, 32)
|
||||
if idErr != nil || versionErr != nil || generationErr != nil || version < 1 || generation < 1 {
|
||||
return false, nil
|
||||
}
|
||||
job, err := q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: *id, PipelineVersion: int32(version),
|
||||
})
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, err
|
||||
}
|
||||
if err == nil && job.LeaseGeneration == int32(generation) && job.LeaseUntil.Valid {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
exists, err := q.AttachmentExistsByObjectKey(txCtx, obj.Key)
|
||||
if err != nil || exists {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if policy.DryRun {
|
||||
return true, nil
|
||||
}
|
||||
if !keepObject {
|
||||
if err := deleteObject(txCtx, obj.Key); err != nil && !errors.Is(err, storage.ErrObjectNotFound) {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if staging.StagingKey.Valid {
|
||||
if _, err = q.ClearStagingReference(txCtx, sqlc.ClearStagingReferenceParams{
|
||||
ID: staging.ID, StagingKey: staging.StagingKey,
|
||||
}); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return !keepObject, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewUserRepository(queries *sqlc.Queries) *UserRepository {
|
||||
return &UserRepository{queries: queries}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, username, displayName string, passwordHash string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.CreateUser(dbCtx, sqlc.CreateUserParams{Username: username, DisplayName: displayName, PasswordHash: passwordHash})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
sqlcUser, err := r.queries.GetUserByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.GetUserByUsername(dbCtx, username)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/repository"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func getUUIDFromString(id string) (*pgtype.UUID, error) {
|
||||
var uuidID pgtype.UUID
|
||||
|
||||
if err := uuidID.Scan(id); err != nil {
|
||||
return nil, repository.ErrInvalidInput
|
||||
}
|
||||
|
||||
return &uuidID, nil
|
||||
}
|
||||
|
||||
func rollbackTx(ctx context.Context, tx pgx.Tx) {
|
||||
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
|
||||
defer cancel()
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func (r *AttachmentRepository) createPipelineJob(ctx context.Context, q *sqlc.Queries, att sqlc.Attachment) (pgtype.UUID, error) {
|
||||
job, err := q.CreateAttachmentJob(ctx, sqlc.CreateAttachmentJobParams{
|
||||
AttachmentID: att.ID, PipelineVersion: att.PipelineVersion,
|
||||
AvailableAt: att.UpdatedAt, MaxAttempts: r.maxAttempts,
|
||||
})
|
||||
if err != nil {
|
||||
return pgtype.UUID{}, convertDBError(err)
|
||||
}
|
||||
if err := q.CreateInitialOutboxEvent(ctx, job.ID); err != nil {
|
||||
return pgtype.UUID{}, convertDBError(err)
|
||||
}
|
||||
return job.ID, nil
|
||||
}
|
||||
|
||||
// UpgradePipeline serializes the version switch with version 1's finalization,
|
||||
// retries and staging cleanup on its job row. The version 2 job starts fresh.
|
||||
func (r *AttachmentRepository) UpgradePipeline(ctx context.Context, attachmentID string, checkSource func(context.Context, string) error) (string, bool, error) {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
oldJob, err := q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: *id, PipelineVersion: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
att, err := q.GetAttachmentByID(txCtx, *id)
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
if att.PipelineVersion == 2 {
|
||||
jobID, err := q.GetPipelineJobID(txCtx, sqlc.GetPipelineJobIDParams{AttachmentID: *id, PipelineVersion: 2})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
return jobID.String(), false, nil
|
||||
}
|
||||
if att.PipelineVersion != 1 {
|
||||
return "", false, fmt.Errorf("cannot upgrade pipeline version %d", att.PipelineVersion)
|
||||
}
|
||||
source := att.StagingKey
|
||||
if att.Status == "ready" {
|
||||
source = att.ObjectKey
|
||||
}
|
||||
if !source.Valid {
|
||||
return "", false, fmt.Errorf("original has expired: %w", repository.ErrNotFound)
|
||||
}
|
||||
if err := checkSource(txCtx, source.String); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := q.SupersedeAttachmentJob(txCtx, oldJob.ID); err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
upgraded, err := q.QueueAttachmentUpgrade(txCtx, sqlc.QueueAttachmentUpgradeParams{ID: *id, SourceKey: source.String})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
jobID, err := r.createPipelineJob(txCtx, q, upgraded)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
return jobID.String(), true, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func convertDBError(err error) error {
|
||||
|
||||
category := repository.ErrDatabase
|
||||
|
||||
var netErr *net.OpError
|
||||
|
||||
if errors.Is(err, redis.Nil) {
|
||||
category = repository.ErrNotFound
|
||||
}
|
||||
if errors.As(err, &netErr) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, redis.ErrPoolTimeout) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
if errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
category = repository.ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json/v2"
|
||||
"fmt"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewSessionRepository(client *redis.Client) *SessionRepository {
|
||||
return &SessionRepository{client: client}
|
||||
}
|
||||
|
||||
type sessionData struct {
|
||||
UserID string `json:"user_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, tokenHash []byte, userID string, sessionTTL time.Duration) (*model.Session, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
now := time.Now().UTC()
|
||||
data := sessionData{
|
||||
UserID: userID,
|
||||
CreatedAt: now,
|
||||
ExpiresAt: now.Add(sessionTTL),
|
||||
}
|
||||
value, err := json.Marshal(data)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: encoding session %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
|
||||
err = r.client.Set(ctx, key, value, sessionTTL).Err()
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
session := &model.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: data.UserID,
|
||||
CreatedAt: data.CreatedAt,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
RevokedAt: nil,
|
||||
}
|
||||
|
||||
return session, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *SessionRepository) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (*model.Session, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
|
||||
value, err := r.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
var data sessionData
|
||||
|
||||
err = json.Unmarshal([]byte(value), &data)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: decode session %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
|
||||
session := &model.Session{
|
||||
TokenHash: tokenHash,
|
||||
UserID: data.UserID,
|
||||
CreatedAt: data.CreatedAt,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
RevokedAt: nil,
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
func (r *SessionRepository) RevokeSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (int, error) {
|
||||
key := "session:" + hex.EncodeToString(tokenHash)
|
||||
|
||||
conn := r.client.Conn()
|
||||
defer conn.Close()
|
||||
|
||||
deleted, err := conn.Del(ctx, key).Result()
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
|
||||
}
|
||||
|
||||
result, err := conn.Do(ctx, "WAITAOF", 1, 0, 2000).Slice()
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
|
||||
}
|
||||
|
||||
if len(result) != 2 {
|
||||
return 0, fmt.Errorf(
|
||||
"%w: WAITAOF: expected 2 counters, got %d",
|
||||
repository.ErrDatabase, len(result),
|
||||
)
|
||||
}
|
||||
|
||||
local, ok := result[0].(int64)
|
||||
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("%w: expected int64, got %T", repository.ErrDatabase, result[0])
|
||||
}
|
||||
if local != 1 {
|
||||
return 0, fmt.Errorf("%w: WAITAOF expected local fsync = 1, got %d", repository.ErrServiceUnavailable, local)
|
||||
}
|
||||
|
||||
return int(deleted), nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SessionRepository interface {
|
||||
Create(ctx context.Context, tokenHash []byte, userID string, sessionTTL time.Duration) (*model.Session, error)
|
||||
GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (*model.Session, error)
|
||||
RevokeSession(ctx context.Context, tokenHash []byte) (int, error)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
Create(ctx context.Context, username, displayName string, passwordHash string) (*model.User, error)
|
||||
GetUserByID(ctx context.Context, id string) (*model.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*model.User, error)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memory = 64 * 1024
|
||||
iterations = 3
|
||||
parallelism = 2
|
||||
saltLength = 16
|
||||
hashLength = 32
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
|
||||
salt := make([]byte, saltLength)
|
||||
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
iterations,
|
||||
memory,
|
||||
parallelism,
|
||||
hashLength,
|
||||
)
|
||||
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
hashPassword := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
memory,
|
||||
iterations,
|
||||
parallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return hashPassword, nil
|
||||
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encodedHash string) (bool, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
versionStr, ok := strings.CutPrefix(parts[2], "v=")
|
||||
if !ok {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
version, err := strconv.ParseUint(versionStr, 10, 32)
|
||||
if err != nil || version != uint64(argon2.Version) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
params := strings.Split(parts[3], ",")
|
||||
if len(params) != 3 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
parseParam := func(value, prefix string, bits int) (uint64, error) {
|
||||
number, ok := strings.CutPrefix(value, prefix)
|
||||
if !ok {
|
||||
return 0, ErrInvalidHash
|
||||
}
|
||||
|
||||
return strconv.ParseUint(number, 10, bits)
|
||||
}
|
||||
|
||||
m, err := parseParam(params[0], "m=", 32)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
t, err := parseParam(params[1], "t=", 32)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
p, err := parseParam(params[2], "p=", 8)
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
memory := uint32(m)
|
||||
iterations := uint32(t)
|
||||
parallelism := uint8(p)
|
||||
|
||||
if memory < 8*uint32(parallelism) ||
|
||||
memory > 256*1024 ||
|
||||
iterations < 1 || iterations > 10 ||
|
||||
parallelism < 1 || parallelism > 8 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
if len(salt) != saltLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
if len(expectedHash) != hashLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
computedHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
iterations,
|
||||
memory,
|
||||
parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
return subtle.ConstantTimeCompare(computedHash, expectedHash) == 1, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"highload/internal/fault"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const MaxAttachmentBytes = 10 * 1024 * 1024
|
||||
const maxImagePixels = 40_000_000
|
||||
const attachmentObjectPrefix = "attachments/"
|
||||
|
||||
type AttachmentService struct {
|
||||
repo repository.AttachmentRepository
|
||||
chatService *ChatService
|
||||
objects storage.ObjectWriter
|
||||
}
|
||||
|
||||
func NewAttachmentService(repo repository.AttachmentRepository, chatService *ChatService, objects storage.ObjectWriter) *AttachmentService {
|
||||
return &AttachmentService{repo: repo, chatService: chatService, objects: objects}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) CreateAttachment(ctx context.Context, chatID, userID, filename, declaredContentType string, body io.ReadSeeker, size int64) (*model.Attachment, error) {
|
||||
|
||||
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mimeType, err := validateAttachment(filename, declaredContentType, body, size)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
key := "staging/" + id + "/original"
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.New()
|
||||
n, err := io.Copy(sum, io.LimitReader(body, size+1))
|
||||
if err != nil || n != size {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
sumString := hex.EncodeToString(sum.Sum(nil))
|
||||
|
||||
var attachment *model.Attachment
|
||||
fn := func(ctx context.Context, tx repository.AttachmentTx) error {
|
||||
err := s.objects.Put(ctx, key, mimeType, body, size)
|
||||
|
||||
if err != nil {
|
||||
return convertStorageError(err)
|
||||
}
|
||||
|
||||
if err := fault.Pause(ctx, "after_staging", id); err != nil {
|
||||
return err
|
||||
}
|
||||
attachment, err = tx.CreateQueued(ctx, id, chat.ID, userID, mimeType, sumString, key, filename, size)
|
||||
return err
|
||||
}
|
||||
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, key, fn)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
if !acquired {
|
||||
return nil, ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetAttachment(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
|
||||
_, err := uuid.Parse(attachmentID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(userID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
attachment, err := s.repo.GetAttachmentForUser(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetAttachmentContent(ctx context.Context, userID, attachmentID, variant string) (string, io.ReadCloser, error) {
|
||||
attachment, err := s.GetAttachment(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if attachment.Status != "ready" {
|
||||
return "", nil, ErrConflict
|
||||
}
|
||||
key, mime := attachment.ObjectKey, attachment.ContentType
|
||||
if variant != "" && variant != "original" {
|
||||
key = ""
|
||||
for _, candidate := range attachment.Variants {
|
||||
if candidate.Name == variant {
|
||||
key, mime = candidate.ObjectKey, candidate.ContentType
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if key == "" {
|
||||
return "", nil, ErrNotFound
|
||||
}
|
||||
contentReader, err := s.objects.Get(ctx, key)
|
||||
if err != nil {
|
||||
return "", nil, convertStorageError(err)
|
||||
}
|
||||
return mime, contentReader, nil
|
||||
}
|
||||
|
||||
func validateAttachment(filename, declaredContentType string, body io.ReadSeeker, size int64) (string, error) {
|
||||
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
|
||||
return "", ErrInvalidInput
|
||||
}
|
||||
|
||||
if strings.ContainsAny(filename, "/\\") || containsControlChars(filename) {
|
||||
return "", ErrInvalidInput
|
||||
}
|
||||
|
||||
if size > MaxAttachmentBytes {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
if size <= 0 {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(io.LimitReader(body, size))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if imageConfig.Height <= 0 || imageConfig.Width <= 0 {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
if imageConfig.Width > maxImagePixels/imageConfig.Height {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
|
||||
var mimeType string
|
||||
switch format {
|
||||
case "png":
|
||||
mimeType = "image/png"
|
||||
case "jpeg":
|
||||
mimeType = "image/jpeg"
|
||||
default:
|
||||
return "", ErrUnsupportMediaType
|
||||
|
||||
}
|
||||
if mimeType != declaredContentType {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
_, _, err = image.Decode(io.LimitReader(body, size))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportMediaType
|
||||
}
|
||||
|
||||
if _, err := body.Seek(0, io.SeekStart); err != nil {
|
||||
return "", ErrServerError
|
||||
}
|
||||
return mimeType, nil
|
||||
}
|
||||
|
||||
func containsControlChars(s string) bool {
|
||||
for _, r := range s {
|
||||
if (r >= 0 && r <= 31) || r == 127 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AttachmentCleanupOptions struct {
|
||||
GracePeriod time.Duration
|
||||
DryRun bool
|
||||
ListTimeout time.Duration
|
||||
}
|
||||
|
||||
type AttachmentCleanupService struct {
|
||||
repo repository.AttachmentRepository
|
||||
objects storage.ObjectCleanup
|
||||
options *AttachmentCleanupOptions
|
||||
}
|
||||
|
||||
type OrphanReport struct {
|
||||
Pages int `json:"s3_pages"`
|
||||
Objects int `json:"objects_scanned"`
|
||||
Checked int `json:"checked_in_db"`
|
||||
Busy int `json:"busy"`
|
||||
Candidates int `json:"orphan_candidates"`
|
||||
Deleted int `json:"objects_deleted"`
|
||||
}
|
||||
|
||||
func NewAttachmentCleanupService(repo repository.AttachmentRepository, objects storage.ObjectCleanup, options *AttachmentCleanupOptions) *AttachmentCleanupService {
|
||||
return &AttachmentCleanupService{repo: repo, objects: objects, options: options}
|
||||
}
|
||||
|
||||
func (s *AttachmentCleanupService) RunOnce(ctx context.Context) error {
|
||||
_, err := s.ScanOrphans(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AttachmentCleanupService) ScanOrphans(ctx context.Context) (OrphanReport, error) {
|
||||
var report OrphanReport
|
||||
cutoff := time.Now().Add(-s.options.GracePeriod)
|
||||
var token *string
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
listCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
objects, nextToken, err := s.objects.ListPage(listCtx, token, attachmentObjectPrefix)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages++
|
||||
|
||||
for _, obj := range objects {
|
||||
report.Objects++
|
||||
if !strings.HasPrefix(obj.Key, attachmentObjectPrefix) ||
|
||||
obj.LastModified.IsZero() || !obj.LastModified.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, obj.Key, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
|
||||
exists, err := txRepo.ExistsByObjectKey(txCtx, obj.Key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
report.Checked++
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
report.Candidates++
|
||||
if s.options.DryRun {
|
||||
return nil
|
||||
}
|
||||
if err := s.objects.Delete(txCtx, obj.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
report.Deleted++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if !acquired {
|
||||
report.Busy++
|
||||
}
|
||||
}
|
||||
|
||||
if nextToken == nil {
|
||||
return report, ctx.Err()
|
||||
}
|
||||
token = nextToken
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const attachmentReconcilePageSize = 200
|
||||
const missingSampleLimit = 32
|
||||
|
||||
type attachmentReconcileStorage interface {
|
||||
Check(context.Context) error
|
||||
Head(context.Context, string) error
|
||||
PutIfAbsent(context.Context, string, string, io.ReadSeeker, int64) error
|
||||
}
|
||||
|
||||
type AttachmentReconciler struct {
|
||||
repo repository.AttachmentReconcileRepository
|
||||
objects attachmentReconcileStorage
|
||||
options AttachmentCleanupOptions
|
||||
}
|
||||
|
||||
type MissingReport struct {
|
||||
Pages int `json:"db_pages"`
|
||||
Rows int `json:"rows_scanned"`
|
||||
Heads int `json:"s3_head_attempts"`
|
||||
Missing int `json:"missing_objects"`
|
||||
SampleIDs []string `json:"missing_attachment_ids"`
|
||||
}
|
||||
|
||||
func NewAttachmentReconciler(repo repository.AttachmentReconcileRepository, objects attachmentReconcileStorage, options AttachmentCleanupOptions) *AttachmentReconciler {
|
||||
return &AttachmentReconciler{repo: repo, objects: objects, options: options}
|
||||
}
|
||||
|
||||
// ScanMissing checks old committed attachment rows using S3 metadata requests.
|
||||
func (s *AttachmentReconciler) ScanMissing(ctx context.Context) (MissingReport, error) {
|
||||
report := MissingReport{SampleIDs: []string{}}
|
||||
cutoff := time.Now().Add(-s.options.GracePeriod)
|
||||
if err := s.checkBucket(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
var afterKey string
|
||||
for {
|
||||
rows, err := s.repo.ListAttachmentKeys(ctx, afterKey, attachmentReconcilePageSize)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages++
|
||||
for _, row := range rows {
|
||||
report.Rows++
|
||||
if !strings.HasPrefix(row.ObjectKey, attachmentObjectPrefix) ||
|
||||
row.CreatedAt.IsZero() || !row.CreatedAt.Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
report.Heads++
|
||||
present, err := s.objectPresent(ctx, row.ObjectKey)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
if !present {
|
||||
report.Missing++
|
||||
if len(report.SampleIDs) < missingSampleLimit {
|
||||
report.SampleIDs = append(report.SampleIDs, row.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(rows) < attachmentReconcilePageSize {
|
||||
return report, ctx.Err()
|
||||
}
|
||||
afterKey = rows[len(rows)-1].ObjectKey
|
||||
}
|
||||
}
|
||||
|
||||
// Restore verifies the original bytes before writing a missing object under its existing key.
|
||||
func (s *AttachmentReconciler) Restore(ctx context.Context, id string, original io.Reader) (string, error) {
|
||||
attachment, err := s.repo.GetAttachmentByID(ctx, id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !strings.HasPrefix(attachment.ObjectKey, attachmentObjectPrefix) ||
|
||||
attachment.CreatedAt.IsZero() || !attachment.CreatedAt.Before(time.Now().Add(-s.options.GracePeriod)) {
|
||||
return "", errors.New("attachment is outside the restore scope or still within grace")
|
||||
}
|
||||
if attachment.SizeBytes <= 0 || attachment.SizeBytes > MaxAttachmentBytes {
|
||||
return "", errors.New("invalid original size in attachment metadata")
|
||||
}
|
||||
if err := s.checkBucket(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Read at most one original. Keep the verified bytes stable until Put completes.
|
||||
data, err := io.ReadAll(io.LimitReader(original, attachment.SizeBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read backup original: %w", err)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if int64(len(data)) != attachment.SizeBytes || hex.EncodeToString(sum[:]) != attachment.SHA256 {
|
||||
return "", errors.New("backup original does not match the stored size and SHA-256")
|
||||
}
|
||||
|
||||
var result string
|
||||
acquired, err := s.repo.WithObjectKeyLock(ctx, attachment.ObjectKey, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
|
||||
current, err := txRepo.GetAttachmentByID(txCtx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.ObjectKey != attachment.ObjectKey || current.SizeBytes != attachment.SizeBytes ||
|
||||
current.SHA256 != attachment.SHA256 || current.ContentType != attachment.ContentType ||
|
||||
!current.CreatedAt.Equal(attachment.CreatedAt) {
|
||||
return errors.New("attachment metadata changed during restore")
|
||||
}
|
||||
present, err := s.objectPresent(txCtx, current.ObjectKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if present {
|
||||
result = "already_present"
|
||||
return nil
|
||||
}
|
||||
if s.options.DryRun {
|
||||
result = "would_restore"
|
||||
return nil
|
||||
}
|
||||
if err := s.objects.PutIfAbsent(txCtx, current.ObjectKey, current.ContentType, bytes.NewReader(data), current.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
result = "restored"
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !acquired {
|
||||
return "", errors.New("attachment key is busy; retry the restore")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentReconciler) checkBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
defer cancel()
|
||||
return s.objects.Check(ctx)
|
||||
}
|
||||
|
||||
func (s *AttachmentReconciler) objectPresent(ctx context.Context, key string) (bool, error) {
|
||||
headCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
||||
defer cancel()
|
||||
err := s.objects.Head(headCtx, key)
|
||||
if errors.Is(err, storage.ErrObjectNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/security"
|
||||
"time"
|
||||
)
|
||||
|
||||
const tokenType = "Bearer"
|
||||
|
||||
type AuthService struct {
|
||||
userRepo repository.UserRepository
|
||||
sessionRepo repository.SessionRepository
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(userRepo repository.UserRepository, sessionRepo repository.SessionRepository, sessionTTL time.Duration) *AuthService {
|
||||
return &AuthService{
|
||||
userRepo: userRepo,
|
||||
sessionRepo: sessionRepo,
|
||||
sessionTTL: sessionTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) Authenticate(ctx context.Context, username, password string) (*model.User, error) {
|
||||
|
||||
userOK := checkUsername(username)
|
||||
passwordOK := checkPassword(password)
|
||||
|
||||
if !userOK || !passwordOK {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
user, err := s.userRepo.GetUserByUsername(ctx, username)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
isVerify, err := security.VerifyPassword(password, user.PasswordHash)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
if !isVerify {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type CreatedSession struct {
|
||||
Token string
|
||||
TokenType string
|
||||
ExpiresAt time.Time
|
||||
User *model.User
|
||||
}
|
||||
|
||||
func (s *AuthService) CreateSession(ctx context.Context, username, password string) (*CreatedSession, error) {
|
||||
user, err := s.Authenticate(ctx, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if s.sessionTTL <= 0 {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
tokenBytes := make([]byte, 32)
|
||||
_, err = rand.Read(tokenBytes)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
session, err := s.sessionRepo.Create(ctx, tokenHash[:], user.ID, s.sessionTTL)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
createdSession := &CreatedSession{
|
||||
Token: token,
|
||||
TokenType: tokenType,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
User: user,
|
||||
}
|
||||
|
||||
return createdSession, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (string, error) {
|
||||
|
||||
if token == "" {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
session, err := s.sessionRepo.GetSessionByTokenHash(ctx, tokenHash[:])
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
return "", convertRepoError(err)
|
||||
}
|
||||
|
||||
if session.RevokedAt != nil {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
if !time.Now().Before(session.ExpiresAt) {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
|
||||
return session.UserID, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) RevokeSession(ctx context.Context, token string) error {
|
||||
tokenHash := sha256.Sum256([]byte(token))
|
||||
|
||||
_, err := s.sessionRepo.RevokeSession(ctx, tokenHash[:])
|
||||
|
||||
if err != nil {
|
||||
return convertRepoError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
repo repository.ChatRepository
|
||||
userRepo repository.UserRepository
|
||||
userService *UserService
|
||||
}
|
||||
|
||||
func NewChatService(repo repository.ChatRepository, userRepo repository.UserRepository, userService *UserService) *ChatService {
|
||||
return &ChatService{repo: repo, userRepo: userRepo, userService: userService}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, title string, memberIDs []string, userID string) (*model.Chat, error) {
|
||||
|
||||
trimTitle := strings.TrimSpace(title)
|
||||
|
||||
lenTitle := utf8.RuneCountInString(title)
|
||||
if lenTitle < 1 || lenTitle > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if trimTitle == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if memberIDs == nil || len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{})
|
||||
for _, memberID := range memberIDs {
|
||||
parsedID, err := uuid.Parse(memberID)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
normalizedID := parsedID.String()
|
||||
|
||||
if _, exist := seen[normalizedID]; exist {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen[normalizedID] = struct{}{}
|
||||
|
||||
_, err = s.userRepo.GetUserByID(ctx, memberID)
|
||||
if err != nil {
|
||||
// NOTE: MemberNotFound –> InvalidInput
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
parsedUserID, err := uuid.Parse(userID)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
normalizedUserID := parsedUserID.String()
|
||||
|
||||
_, creatorExists := seen[normalizedUserID]
|
||||
if !creatorExists {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.repo.CreateChat(ctx, title, memberIDs)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) GetChatsByUserID(ctx context.Context, userID string, limit *int, cursor *string) ([]*model.Chat, *string, error) {
|
||||
|
||||
actualLimit := 50
|
||||
|
||||
if limit != nil {
|
||||
actualLimit = *limit
|
||||
}
|
||||
|
||||
if actualLimit <= 0 || actualLimit > 100 {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
var chatPosition *repository.ChatPosition
|
||||
|
||||
if cursor != nil {
|
||||
chCursor, err := decodeCursor[chatCursor](*cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(chCursor.ChatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if chCursor.CreatedAt.IsZero() {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(chCursor.UserID)
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if chCursor.UserID != userID {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chatPosition = &repository.ChatPosition{
|
||||
CreatedAt: chCursor.CreatedAt,
|
||||
ID: chCursor.ChatID,
|
||||
}
|
||||
}
|
||||
|
||||
chats, err := s.repo.GetChatsByUserID(ctx, userID, actualLimit+1, chatPosition)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
var chCursor *chatCursor
|
||||
|
||||
if len(chats) > actualLimit {
|
||||
chCursor = &chatCursor{
|
||||
ChatID: chats[actualLimit-1].ID,
|
||||
UserID: userID,
|
||||
CreatedAt: chats[actualLimit-1].CreatedAt,
|
||||
}
|
||||
cursor, err = encodeCursor[chatCursor](*chCursor)
|
||||
if err != nil {
|
||||
return nil, nil, ErrServerError
|
||||
}
|
||||
|
||||
return chats[:actualLimit], cursor, nil
|
||||
}
|
||||
|
||||
return chats, nil, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *ChatService) GetChatByID(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
|
||||
_, err := uuid.Parse(chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
_, err = uuid.Parse(userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.repo.GetChatByID(ctx, chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
index := slices.Index(chat.MemberIDs, userID)
|
||||
|
||||
if index == -1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
type chatCursor struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ChatID string `json:"chat_id"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrAlreadyExists = errors.New("user already exists")
|
||||
ErrNotFound = errors.New("user not found")
|
||||
ErrServerError = errors.New("server error")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrServiceUnavailable = errors.New("service unavailable")
|
||||
ErrConflict = errors.New("data conflict")
|
||||
ErrUnsupportMediaType = errors.New("unsupported mediaType")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
)
|
||||
|
||||
func convertRepoError(err error) error {
|
||||
|
||||
var category error
|
||||
|
||||
switch {
|
||||
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
category = ErrNotFound
|
||||
case errors.Is(err, repository.ErrAlreadyExists):
|
||||
category = ErrAlreadyExists
|
||||
case errors.Is(err, repository.ErrInvalidInput):
|
||||
category = ErrInvalidInput
|
||||
case errors.Is(err, repository.ErrDatabase) || errors.Is(err, repository.ErrServerError):
|
||||
category = ErrServerError
|
||||
case errors.Is(err, repository.ErrServiceUnavailable):
|
||||
category = ErrServiceUnavailable
|
||||
case errors.Is(err, repository.ErrConflict):
|
||||
category = ErrConflict
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
}
|
||||
|
||||
func convertStorageError(err error) error {
|
||||
var category error
|
||||
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrObjectNotFound):
|
||||
category = ErrNotFound
|
||||
case errors.Is(err, storage.ErrServiceUnavailable):
|
||||
category = ErrServiceUnavailable
|
||||
case errors.Is(err, storage.ErrStorage):
|
||||
category = ErrServerError
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json/v2"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func encodeCursor[C any](cursor C) (*string, error) {
|
||||
data, err := json.Marshal(cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded := base64.RawURLEncoding.EncodeToString(data)
|
||||
|
||||
return &encoded, nil
|
||||
|
||||
}
|
||||
|
||||
func decodeCursor[C any](cursor string) (*C, error) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
var decoded C
|
||||
|
||||
err = json.Unmarshal(data, &decoded)
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
return &decoded, nil
|
||||
}
|
||||
|
||||
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func checkUsername(username string) bool {
|
||||
return usernameRegex.MatchString(username)
|
||||
}
|
||||
|
||||
func checkPassword(password string) bool {
|
||||
|
||||
if !utf8.ValidString(password) {
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.TrimSpace(password) == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
passwordLength := utf8.RuneCountInString(password)
|
||||
if passwordLength < 12 || passwordLength > 128 {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
repo repository.MessageRepository
|
||||
userService *UserService
|
||||
chatService *ChatService
|
||||
}
|
||||
|
||||
func NewMessageService(repo repository.MessageRepository, chatService *ChatService, userService *UserService) *MessageService {
|
||||
return &MessageService{repo: repo, chatService: chatService, userService: userService}
|
||||
}
|
||||
|
||||
func (s *MessageService) CreateMessage(ctx context.Context, text, chatID, userID, key string, attachmentIDs []string) (*model.Message, error) {
|
||||
|
||||
_, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lenText := utf8.RuneCountInString(text)
|
||||
|
||||
if lenText > 4000 || (strings.TrimSpace(text) == "" && len(attachmentIDs) == 0) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 10 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(attachmentIDs))
|
||||
for _, rawID := range attachmentIDs {
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
|
||||
}
|
||||
|
||||
message, err := s.repo.CreateMessage(ctx, chatID, userID, text, key, attachmentIDs)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) GetMessagesByChatID(ctx context.Context, chatID, userID string, limit *int, cursor *string) ([]*model.Message, *string, error) {
|
||||
|
||||
actualLimit := 50
|
||||
|
||||
if limit != nil {
|
||||
actualLimit = *limit
|
||||
}
|
||||
|
||||
if actualLimit <= 0 || actualLimit > 100 {
|
||||
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
chat, err := s.chatService.GetChatByID(ctx, chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var messagePosition *repository.MessagePosition
|
||||
|
||||
if cursor != nil {
|
||||
mesCursor, err := decodeCursor[messageCursor](*cursor)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if _, err := uuid.Parse(mesCursor.ChatID); err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if _, err := uuid.Parse(mesCursor.MessageID); err != nil {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if mesCursor.CreatedAt.IsZero() {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if mesCursor.ChatID != chat.ID {
|
||||
return nil, nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
messagePosition = &repository.MessagePosition{
|
||||
ID: mesCursor.MessageID,
|
||||
CreatedAt: mesCursor.CreatedAt,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
messages, err := s.repo.GetMessagesByChatID(ctx, chat.ID, actualLimit+1, messagePosition)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
if len(messages) > actualLimit {
|
||||
mesCursor := &messageCursor{
|
||||
MessageID: messages[actualLimit-1].ID,
|
||||
ChatID: chat.ID,
|
||||
CreatedAt: messages[actualLimit-1].CreatedAt,
|
||||
}
|
||||
cursor, err = encodeCursor[messageCursor](*mesCursor)
|
||||
if err != nil {
|
||||
return nil, nil, ErrServerError
|
||||
}
|
||||
return messages[:actualLimit], cursor, nil
|
||||
}
|
||||
|
||||
return messages, nil, nil
|
||||
|
||||
}
|
||||
|
||||
type messageCursor struct {
|
||||
MessageID string `json:"message_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/security"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo repository.UserRepository) *UserService {
|
||||
return &UserService{repo}
|
||||
}
|
||||
|
||||
func (s *UserService) CreateUser(ctx context.Context, username, displayName, password string) (*model.User, error) {
|
||||
|
||||
userOK := checkUsername(username)
|
||||
passwordOK := checkPassword(password)
|
||||
|
||||
if !userOK || !passwordOK {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if !utf8.ValidString(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
if utf8.RuneCountInString(displayName) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
return nil, ErrServerError
|
||||
}
|
||||
|
||||
user, err := s.repo.Create(ctx, username, displayName, passwordHash)
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *UserService) GetUser(ctx context.Context, id string) (*model.User, error) {
|
||||
|
||||
_, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
user, err := s.repo.GetUserByID(ctx, id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertRepoError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package storage
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrServiceUnavailable = errors.New("object storage unavailable")
|
||||
ErrStorage = errors.New("storage error")
|
||||
ErrObjectNotFound = errors.New("object not found")
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ObjectCleanup interface {
|
||||
ListPage(ctx context.Context, token *string, prefix string) ([]ObjectInfo, *string, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
LastModified time.Time
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
)
|
||||
|
||||
type ObjectWriter interface {
|
||||
Put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"highload/internal/config"
|
||||
"highload/internal/storage"
|
||||
"io"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
|
||||
awsconfig "github.com/aws/aws-sdk-go-v2/config"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
Client *awss3.Client
|
||||
Bucket string
|
||||
}
|
||||
|
||||
func NewStorage(ctx context.Context, cfg *config.S3) (*Storage, error) {
|
||||
provider := credentials.NewStaticCredentialsProvider(
|
||||
cfg.AccessKeyID,
|
||||
cfg.SecretAccessKey,
|
||||
"",
|
||||
)
|
||||
sdkConfig, err := awsconfig.LoadDefaultConfig(
|
||||
ctx,
|
||||
awsconfig.WithRegion(cfg.Region),
|
||||
awsconfig.WithCredentialsProvider(provider),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := awss3.NewFromConfig(sdkConfig, func(opts *awss3.Options) {
|
||||
opts.BaseEndpoint = aws.String(cfg.Endpoint)
|
||||
opts.UsePathStyle = true
|
||||
})
|
||||
|
||||
return &Storage{
|
||||
Client: client,
|
||||
Bucket: cfg.Bucket,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Storage) Check(ctx context.Context) error {
|
||||
_, err := s.Client.HeadBucket(ctx, &awss3.HeadBucketInput{
|
||||
Bucket: aws.String(s.Bucket),
|
||||
})
|
||||
if err != nil {
|
||||
return convertS3Error(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Storage) Head(ctx context.Context, key string) error {
|
||||
_, err := s.Client.HeadObject(ctx, &awss3.HeadObjectInput{
|
||||
Bucket: &s.Bucket,
|
||||
Key: &key,
|
||||
})
|
||||
if err != nil {
|
||||
return convertS3Error(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Storage) Put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error {
|
||||
return s.put(ctx, key, contentType, body, size, nil)
|
||||
}
|
||||
|
||||
func (s *Storage) PutIfAbsent(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64) error {
|
||||
return s.put(ctx, key, contentType, body, size, aws.String("*"))
|
||||
}
|
||||
|
||||
func (s *Storage) put(ctx context.Context, key, contentType string, body io.ReadSeeker, size int64, ifNoneMatch *string) error {
|
||||
_, err := s.Client.PutObject(ctx, &awss3.PutObjectInput{
|
||||
Bucket: &s.Bucket,
|
||||
Key: &key,
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
IfNoneMatch: ifNoneMatch,
|
||||
ContentType: &contentType})
|
||||
|
||||
if err != nil {
|
||||
return convertS3Error(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Storage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
params := &awss3.GetObjectInput{
|
||||
Bucket: &s.Bucket,
|
||||
Key: &key,
|
||||
}
|
||||
objectOutput, err := s.Client.GetObject(ctx, params)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertS3Error(err)
|
||||
}
|
||||
|
||||
return objectOutput.Body, nil
|
||||
|
||||
}
|
||||
|
||||
func (s *Storage) Delete(ctx context.Context, key string) error {
|
||||
|
||||
params := &awss3.DeleteObjectInput{
|
||||
Bucket: &s.Bucket,
|
||||
Key: &key,
|
||||
}
|
||||
_, err := s.Client.DeleteObject(ctx, params)
|
||||
|
||||
if err != nil {
|
||||
return convertS3Error(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (s *Storage) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) {
|
||||
input := awss3.ListObjectsV2Input{
|
||||
Bucket: &s.Bucket,
|
||||
Prefix: aws.String(prefix),
|
||||
ContinuationToken: token,
|
||||
}
|
||||
|
||||
output, err := s.Client.ListObjectsV2(ctx, &input)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, convertS3Error(err)
|
||||
}
|
||||
|
||||
var objects []storage.ObjectInfo
|
||||
|
||||
for _, obj := range output.Contents {
|
||||
if obj.Key == nil || obj.LastModified == nil || *obj.Key == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
objects = append(objects, storage.ObjectInfo{
|
||||
Key: *obj.Key,
|
||||
LastModified: *obj.LastModified,
|
||||
})
|
||||
}
|
||||
if !aws.ToBool(output.IsTruncated) {
|
||||
return objects, nil, nil
|
||||
}
|
||||
|
||||
nextToken := output.NextContinuationToken
|
||||
|
||||
if nextToken == nil || aws.ToString(nextToken) == "" || aws.ToString(nextToken) == aws.ToString(token) {
|
||||
return nil, nil, fmt.Errorf("%w: invalid next token", storage.ErrStorage)
|
||||
}
|
||||
|
||||
return objects, nextToken, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/storage"
|
||||
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
)
|
||||
|
||||
func convertS3Error(err error) error {
|
||||
category := storage.ErrStorage
|
||||
|
||||
var sendErr *smithyhttp.RequestSendError
|
||||
var responseErr *smithyhttp.ResponseError
|
||||
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
//Ошибка storage.ErrStorage
|
||||
case errors.Is(err, context.DeadlineExceeded) || errors.As(err, &sendErr):
|
||||
category = storage.ErrServiceUnavailable
|
||||
|
||||
case errors.As(err, &responseErr):
|
||||
code := responseErr.HTTPStatusCode()
|
||||
switch code {
|
||||
case 404:
|
||||
category = storage.ErrObjectNotFound
|
||||
case 429, 500, 503, 504, 502:
|
||||
category = storage.ErrServiceUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", category, err)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
attachmentService *service.AttachmentService
|
||||
uploadSlots chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(attachmentService *service.AttachmentService) *AttachmentHandler {
|
||||
uploadSlots := make(chan struct{}, 1)
|
||||
return &AttachmentHandler{attachmentService: attachmentService, uploadSlots: uploadSlots}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) CreateAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
filename := r.URL.Query().Get("filename")
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
select {
|
||||
case h.uploadSlots <- struct{}{}:
|
||||
defer func() { <-h.uploadSlots }()
|
||||
case <-time.After(1 * time.Second):
|
||||
w.Header().Set("Retry-After", "1")
|
||||
httputils.WriteError(w, http.StatusTooManyRequests, httputils.ErrorDetails{
|
||||
Code: "rate_limited",
|
||||
Message: "too many concurrent uploads, try again later",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
|
||||
file, err := os.CreateTemp("", "attachment-*")
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if err := os.Remove(file.Name()); err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
body := http.MaxBytesReader(w, r.Body, service.MaxAttachmentBytes)
|
||||
defer body.Close()
|
||||
size, err := io.Copy(file, uploadBodyReader{body})
|
||||
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
httputils.WriteError(w, http.StatusRequestEntityTooLarge, httputils.ErrorDetails{
|
||||
Code: "payload_too_large",
|
||||
Message: "payload_too_large",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
var readErr *uploadBodyReadError
|
||||
if !errors.As(err, &readErr) {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "invalid_request",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.attachmentService.CreateAttachment(r.Context(), chatID, userID, filename, contentType, file, size)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertAttachmentModelToResponse(attachment)
|
||||
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusAccepted, *response)
|
||||
if wrErr != nil {
|
||||
slog.Error("failed to write create attachment response", "error", wrErr, "requestID", requestID)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type uploadBodyReader struct{ io.Reader }
|
||||
|
||||
func (r uploadBodyReader) Read(p []byte) (int, error) {
|
||||
n, err := r.Reader.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, &uploadBodyReadError{err}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type uploadBodyReadError struct{ cause error }
|
||||
|
||||
func (e *uploadBodyReadError) Error() string { return e.cause.Error() }
|
||||
func (e *uploadBodyReadError) Unwrap() error { return e.cause }
|
||||
|
||||
func (h *AttachmentHandler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
attachmentID := r.PathValue("attachment_id")
|
||||
|
||||
attachment, err := h.attachmentService.GetAttachment(r.Context(), userID, attachmentID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
wrErr := httputils.WriteJSON[attachmentResponse](w, http.StatusOK, *convertAttachmentModelToResponse(attachment))
|
||||
if wrErr != nil {
|
||||
slog.Error("failed to write get attachment response", "error", wrErr, "requestID", requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
attachmentID := r.PathValue("attachment_id")
|
||||
variant := r.URL.Query().Get("variant")
|
||||
|
||||
contentType, stream, err := h.attachmentService.GetAttachmentContent(r.Context(), userID, attachmentID, variant)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
defer stream.Close()
|
||||
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
_, err = io.Copy(w, stream)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("failed to copy attachment content to w", "error", err, "request_id", requestID)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type attachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []attachmentVariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
type attachmentVariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
func convertAttachmentModelToResponse(attachment *model.Attachment) *attachmentResponse {
|
||||
variants := make([]attachmentVariantResponse, 0, len(attachment.Variants))
|
||||
for _, v := range attachment.Variants {
|
||||
variants = append(variants, attachmentVariantResponse{
|
||||
Name: v.Name, ContentType: v.ContentType, SizeBytes: v.SizeBytes,
|
||||
Width: v.Width, Height: v.Height, SHA256: v.SHA256,
|
||||
})
|
||||
}
|
||||
return &attachmentResponse{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
Status: attachment.Status,
|
||||
Variants: variants,
|
||||
ErrorCode: attachment.ErrorCode,
|
||||
CreatedAt: httputils.FormatTime(attachment.CreatedAt),
|
||||
UpdatedAt: httputils.FormatTime(attachment.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{authService: authService}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var probe [1]byte
|
||||
|
||||
n, err := r.Body.Read(probe[:])
|
||||
|
||||
if n > 0 || (err != nil && !errors.Is(err, io.EOF)) {
|
||||
_ = httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "Request body must be empty",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
createdSession, err := h.authService.CreateSession(r.Context(), username, password)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := createSessionResponse{
|
||||
Token: createdSession.Token,
|
||||
TokenType: createdSession.TokenType,
|
||||
ExpiresAt: httputils.FormatTime(createdSession.ExpiresAt),
|
||||
User: UserResponse{
|
||||
Username: createdSession.User.Username,
|
||||
ID: createdSession.User.ID,
|
||||
DisplayName: createdSession.User.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(createdSession.User.CreatedAt),
|
||||
},
|
||||
}
|
||||
|
||||
httputils.WriteJSON[createSessionResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *AuthHandler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.RevokeSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handler
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type createSessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chatService *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chatService *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chatService: chatService}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[chatCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.chatService.Create(r.Context(), req.Title, req.MemberIDs, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := chatResponse{
|
||||
Title: result.Title,
|
||||
MemberIDs: result.MemberIDs,
|
||||
ID: result.ID,
|
||||
CreatedAt: httputils.FormatTime(result.CreatedAt),
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusCreated, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatsByUserID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
chats, nextCursor, err := h.chatService.GetChatsByUserID(r.Context(), userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chatResponses := make([]chatResponse, len(chats))
|
||||
for index, chat := range chats {
|
||||
chatResponses[index] = *convertChatModelToResponse(chat)
|
||||
}
|
||||
|
||||
response := chatGetByUserIDResponse{
|
||||
Items: chatResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[chatGetByUserIDResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChatByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
chat, err := h.chatService.GetChatByID(r.Context(), chatID, userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertChatModelToResponse(chat)
|
||||
_ = httputils.WriteJSON[chatResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type chatCreateRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
ID string `json:"id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatGetByUserIDResponse struct {
|
||||
Items []chatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertChatModelToResponse(model *model.Chat) *chatResponse {
|
||||
return &chatResponse{
|
||||
Title: model.Title,
|
||||
ID: model.ID,
|
||||
MemberIDs: model.MemberIDs,
|
||||
CreatedAt: httputils.FormatTime(model.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/storage/s3"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redisClient *redis.Client
|
||||
s3Storage *s3.Storage
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, s3Storage *s3.Storage) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redisClient: redisClient, s3Storage: s3Storage}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
slog.Error("database readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.redisClient.Ping(ctx).Err(); err != nil {
|
||||
slog.Error("redis readiness check failed", "error", err)
|
||||
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.s3Storage.Check(ctx); err != nil {
|
||||
slog.Error("s3 storage check failed", "error", err)
|
||||
if writeErr := httputils.WriteServiceUnavailable(w, requestID); writeErr != nil {
|
||||
slog.Error("failed to write readiness response", "error", writeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
response := HealthResponse{Status: "ok"}
|
||||
err := httputils.WriteJSON[HealthResponse](w, http.StatusOK, response)
|
||||
if err != nil {
|
||||
slog.Error("failed to write health response", "error", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (h *HealthHandler) NotFoundRoute(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
err := httputils.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
httputils.ErrorDetails{
|
||||
Code: "not_found",
|
||||
Message: "Not Found",
|
||||
RequestID: requestID,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("failed to write not found response", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package handler
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messageService *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messageService *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messageService: messageService}
|
||||
}
|
||||
|
||||
func (h *MessageHandler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
req, code := httputils.Decode[messageCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
|
||||
if ok := httputils.CheckIdempotencyKeyPattern(key); !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{
|
||||
Code: "invalid_request",
|
||||
Message: "wrong Idempotency-Key",
|
||||
RequestID: requestID,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.messageService.CreateMessage(r.Context(), req.Text, chatID, userID, key, req.AttachmentIDs)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertMessageModelToResponse(message)
|
||||
|
||||
_ = httputils.WriteJSON[messageResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *MessageHandler) GetMessagesByChatID(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
|
||||
limit, cursor, ok := httputils.GetLimitAndCursor(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteError(w, http.StatusBadRequest, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
messages, nextCursor, err := h.messageService.GetMessagesByChatID(r.Context(), chatID, userID, limit, cursor)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
messageResponses := make([]messageResponse, len(messages))
|
||||
for index, message := range messages {
|
||||
messageResponses[index] = *convertMessageModelToResponse(message)
|
||||
}
|
||||
|
||||
response := messageGetResponse{
|
||||
Items: messageResponses,
|
||||
NextCursor: nextCursor,
|
||||
}
|
||||
|
||||
_ = httputils.WriteJSON[messageGetResponse](w, http.StatusOK, response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type messageCreateRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type messageGetResponse struct {
|
||||
Items []messageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func convertMessageModelToResponse(message *model.Message) *messageResponse {
|
||||
attachmentIDs := message.AttachmentIDs
|
||||
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
|
||||
return &messageResponse{
|
||||
ID: message.ID,
|
||||
ChatID: message.ChatID,
|
||||
SenderID: message.SenderID,
|
||||
Text: message.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
CreatedAt: httputils.FormatTime(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
userService *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(service *service.UserService) *UserHandler {
|
||||
return &UserHandler{userService: service}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
|
||||
req, code := httputils.Decode[userCreateRequest](r)
|
||||
|
||||
if code != http.StatusOK {
|
||||
if code == http.StatusUnsupportedMediaType {
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "unsupported_media_type", Message: "Неверный media type", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
httputils.WriteError(w, code, httputils.ErrorDetails{Code: "invalid_request", Message: "Неверный запрос", RequestID: requestID})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userService.CreateUser(r.Context(), req.Username, req.DisplayName, req.Password)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusCreated, *response)
|
||||
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetCurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.RequestIDFromContext(r.Context())
|
||||
userID := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
user, err := h.userService.GetUser(r.Context(), userID)
|
||||
|
||||
if err != nil {
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := convertUserModelToResponse(user)
|
||||
|
||||
_ = httputils.WriteJSON[userResponse](w, http.StatusOK, *response)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"highload/internal/model"
|
||||
"highload/internal/transport/http/httputils"
|
||||
)
|
||||
|
||||
type userCreateRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func convertUserModelToResponse(user *model.User) *userResponse {
|
||||
return &userResponse{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: httputils.FormatTime(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"encoding/json/v2"
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type ErrorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func Decode[T any](r *http.Request) (*T, int) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return nil, http.StatusUnsupportedMediaType
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
req := new(T)
|
||||
|
||||
err = json.Unmarshal(body, req, json.RejectUnknownMembers(true))
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
return req, http.StatusOK
|
||||
|
||||
}
|
||||
|
||||
func GetLimitAndCursor(r *http.Request) (limit *int, cursor *string, ok bool) {
|
||||
query := r.URL.Query()
|
||||
|
||||
var currentLimit *int
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
|
||||
if limitStr == "" {
|
||||
return nil, nil, false
|
||||
}
|
||||
limitInt, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
currentLimit = &limitInt
|
||||
|
||||
}
|
||||
|
||||
var currentCursor *string
|
||||
if query.Has("cursor") {
|
||||
cursor := query.Get("cursor")
|
||||
currentCursor = &cursor
|
||||
}
|
||||
|
||||
return currentLimit, currentCursor, true
|
||||
}
|
||||
|
||||
func WriteJSON[T any](w http.ResponseWriter, status int, response T) error {
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func ErrorFromService(err error) (int, string) {
|
||||
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
|
||||
case errors.Is(err, service.ErrAlreadyExists):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrServiceUnavailable):
|
||||
return http.StatusServiceUnavailable, "unavailable"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrPayloadTooLarge):
|
||||
return http.StatusRequestEntityTooLarge, "payload_too_large"
|
||||
case errors.Is(err, service.ErrUnsupportMediaType):
|
||||
return http.StatusUnsupportedMediaType, "unsupported_media_type"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func WriteBasicUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteBearerUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Bearer realm="messenger"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, code int, errorDetails ErrorDetails) error {
|
||||
return WriteJSON(w, code, ErrorResponse{Error: errorDetails})
|
||||
|
||||
}
|
||||
|
||||
func WriteServiceUnavailable(w http.ResponseWriter, requestID string) error {
|
||||
return WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
ErrorDetails{
|
||||
Message: "unavailable",
|
||||
Code: "unavailable",
|
||||
RequestID: requestID,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func WriteServiceError(w http.ResponseWriter, err error, requestID string) error {
|
||||
status, code := ErrorFromService(err)
|
||||
|
||||
if status >= http.StatusInternalServerError {
|
||||
slog.Error("request failed",
|
||||
"error", err,
|
||||
"request_id", requestID,
|
||||
"status", status,
|
||||
"code", code,
|
||||
)
|
||||
}
|
||||
|
||||
return WriteJSON(w, status, ErrorResponse{
|
||||
Error: ErrorDetails{
|
||||
Code: code,
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func ExtractBearerToken(r *http.Request) (string, bool) {
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok ||
|
||||
!strings.EqualFold(scheme, "Bearer") ||
|
||||
token == "" ||
|
||||
strings.ContainsAny(token, " \t\r\n") {
|
||||
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func CheckIdempotencyKeyPattern(key string) bool {
|
||||
patternReg := regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
return patternReg.MatchString(key)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/httputils"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Middleware struct {
|
||||
authService *service.AuthService
|
||||
instanceID string
|
||||
}
|
||||
|
||||
func NewMiddleware(authService *service.AuthService, instanceID string) *Middleware {
|
||||
|
||||
return &Middleware{
|
||||
authService: authService,
|
||||
instanceID: instanceID,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (m *Middleware) Auth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := RequestIDFromContext(r.Context())
|
||||
|
||||
token, ok := httputils.ExtractBearerToken(r)
|
||||
|
||||
if !ok {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := m.authService.ValidateSession(r.Context(), token)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
httputils.WriteBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
httputils.WriteServiceError(w, err, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := WithUserID(r.Context(), userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := uuid.NewString()
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := WithRequestID(r.Context(), requestID)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Middleware) InstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", m.instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import "context"
|
||||
|
||||
// UserID
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func WithUserID(ctx context.Context, userID string) context.Context {
|
||||
return context.WithValue(ctx, userIDKey, userID)
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) string {
|
||||
userID, _ := ctx.Value(userIDKey).(string)
|
||||
return userID
|
||||
}
|
||||
|
||||
// RequestIDKey
|
||||
const requestIDKey contextKey = "requestID"
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) string {
|
||||
requestID, _ := ctx.Value(requestIDKey).(string)
|
||||
return requestID
|
||||
}
|
||||
|
||||
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey, requestID)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (m *Middleware) Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
rw := &responseWriter{
|
||||
ResponseWriter: w,
|
||||
status: http.StatusOK,
|
||||
}
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
|
||||
slog.Info(
|
||||
"http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", rw.status,
|
||||
"duration", time.Since(start),
|
||||
"request_id", RequestIDFromContext(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
middleware *middleware.Middleware
|
||||
authHandler *handler.AuthHandler
|
||||
healthHandler *handler.HealthHandler
|
||||
chatHandler *handler.ChatHandler
|
||||
userHandler *handler.UserHandler
|
||||
messageHandler *handler.MessageHandler
|
||||
attachmentHandler *handler.AttachmentHandler
|
||||
}
|
||||
|
||||
func NewRouter(middleware *middleware.Middleware, authHandler *handler.AuthHandler, healthHandler *handler.HealthHandler, chatHandler *handler.ChatHandler, userHandler *handler.UserHandler, messageHandler *handler.MessageHandler, attachmentHandler *handler.AttachmentHandler) *Router {
|
||||
return &Router{chatHandler: chatHandler, authHandler: authHandler, healthHandler: healthHandler, middleware: middleware, userHandler: userHandler, messageHandler: messageHandler, attachmentHandler: attachmentHandler}
|
||||
}
|
||||
|
||||
func (r *Router) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
protectedMux := http.NewServeMux()
|
||||
|
||||
protectedMux.HandleFunc("/", r.healthHandler.NotFoundRoute)
|
||||
mux.HandleFunc("GET /health/live", r.healthHandler.Live)
|
||||
mux.HandleFunc("GET /health/ready", r.healthHandler.Ready)
|
||||
|
||||
//Auth
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", r.authHandler.CreateSession)
|
||||
protectedMux.HandleFunc("DELETE /api/v1/auth/sessions/current", r.authHandler.DeleteSession)
|
||||
|
||||
//User
|
||||
mux.HandleFunc("POST /api/v1/users", r.userHandler.CreateUser)
|
||||
protectedMux.HandleFunc("GET /api/v1/users/me", r.userHandler.GetCurrentUser)
|
||||
|
||||
//Chat
|
||||
protectedMux.HandleFunc("POST /api/v1/chats", r.chatHandler.CreateChat)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats", r.chatHandler.GetChatsByUserID)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}", r.chatHandler.GetChatByChatID)
|
||||
|
||||
//Message
|
||||
protectedMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", r.messageHandler.CreateMessage)
|
||||
protectedMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", r.messageHandler.GetMessagesByChatID)
|
||||
|
||||
//Attachment
|
||||
protectedMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", r.attachmentHandler.CreateAttachment)
|
||||
protectedMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", r.attachmentHandler.GetAttachment)
|
||||
protectedMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", r.attachmentHandler.GetAttachmentContent)
|
||||
|
||||
mux.Handle("/api/v1/", r.middleware.Auth(protectedMux))
|
||||
return r.middleware.InstanceID(r.middleware.RequestID(
|
||||
r.middleware.Logging(mux),
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user