Реализация на 5

This commit is contained in:
Grbisba
2026-11-17 13:08:13 +03:00
parent 470d9d6f1e
commit 60f48c0337
229 changed files with 74928 additions and 47 deletions
+194
View File
@@ -0,0 +1,194 @@
package broker
import (
"bytes"
"context"
"encoding/json"
"errors"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/fault"
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
"go.opentelemetry.io/otel/trace"
"io"
"log/slog"
"net"
"regexp"
"time"
)
const Queue = "attachments.v1"
var tracePattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
type Rabbit struct{ URL string }
func (r *Rabbit) connect(deadline time.Duration) (*amqp.Connection, *amqp.Channel, error) {
dial := amqp.DefaultDial(5 * time.Second)
if deadline > 0 {
dial = func(network, address string) (net.Conn, error) {
c, e := net.DialTimeout(network, address, 5*time.Second)
if e != nil {
return nil, e
}
if e = c.SetDeadline(time.Now().Add(deadline)); e != nil {
c.Close()
return nil, e
}
return c, nil
}
}
conn, e := amqp.DialConfig(r.URL, amqp.Config{Heartbeat: 10 * time.Second, Dial: dial})
if e != nil {
return nil, nil, errors.New("broker connection unavailable")
}
ch, e := conn.Channel()
if e != nil {
conn.Close()
return nil, nil, errors.New("broker channel unavailable")
}
_, e = ch.QueueDeclare(Queue+".invalid", true, false, false, false, nil)
if e == nil {
e = ch.ExchangeDeclare("attachments.invalid", "direct", true, false, false, false, nil)
}
if e == nil {
e = ch.QueueBind(Queue+".invalid", "invalid", "attachments.invalid", false, nil)
}
if e == nil {
_, e = ch.QueueDeclare(Queue, true, false, false, false, amqp.Table{"x-dead-letter-exchange": "attachments.invalid", "x-dead-letter-routing-key": "invalid"})
}
if e != nil {
ch.Close()
conn.Close()
return nil, nil, errors.New("broker topology unavailable")
}
return conn, ch, nil
}
func (r *Rabbit) Publish(ctx context.Context, m outbox.DeliveryMessage) (err error) {
var job dto.JobMessage
if e := json.Unmarshal(m.Payload, &job); e != nil {
return e
}
ctx, sp := telemetry.Start(telemetry.Extract(ctx, job.Traceparent, job.Tracestate), "attachments publish", trace.SpanKindProducer)
defer func() { telemetry.End(sp, err) }()
job.Traceparent, job.Tracestate = telemetry.Inject(ctx)
body, marshalErr := json.Marshal(job)
if marshalErr != nil {
return marshalErr
}
conn, ch, e := r.connect(20 * time.Second)
if e != nil {
return e
}
defer conn.Close()
defer ch.Close()
if e = ch.Confirm(false); e != nil {
return e
}
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
returns := ch.NotifyReturn(make(chan amqp.Return, 1))
fault.Hit(ctx, "before_publish", job.JobID)
if e = ch.PublishWithContext(ctx, "", Queue, true, false, amqp.Publishing{DeliveryMode: amqp.Persistent, ContentType: "application/json", MessageId: m.ID.String(), Body: body}); e != nil {
return errors.New("broker publish failed")
}
select {
case c, ok := <-confirms:
if !ok || !c.Ack {
return errors.New("broker did not confirm")
}
select {
case <-returns:
return errors.New("unroutable job")
default:
}
case <-time.After(15 * time.Second):
return errors.New("confirm timeout")
case <-ctx.Done():
return ctx.Err()
}
fault.Hit(ctx, "after_publish", job.JobID)
return nil
}
func (r *Rabbit) Consume(ctx context.Context, concurrency, prefetch int, process func(context.Context, dto.JobMessage) error) error {
conn, ch, e := r.connect(0)
if e != nil {
return e
}
defer conn.Close()
defer ch.Close()
if e = ch.Qos(prefetch, 0, false); e != nil {
return e
}
deliveries, e := ch.Consume(Queue, "worker-"+uuid.NewString(), false, false, false, false, nil)
if e != nil {
return e
}
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
conn.Close()
case <-done:
}
}()
defer close(done)
tasks := make(chan amqp.Delivery)
finished := make(chan struct{}, concurrency)
for range concurrency {
go func() {
defer func() { finished <- struct{}{} }()
for d := range tasks {
var m dto.JobMessage
dec := json.NewDecoder(bytes.NewReader(d.Body))
dec.DisallowUnknownFields()
e := dec.Decode(&m)
if e != nil || dec.Decode(new(any)) != io.EOF || m.SchemaVersion != 1 || m.Type != "attachment.process.v1" || m.JobID == uuid.Nil || m.AttachmentID == uuid.Nil || m.Attempt < 1 || m.PipelineVersion < 1 || m.CreatedAt.IsZero() || len(m.Tracestate) > 512 || (m.Traceparent != "" && !tracePattern.MatchString(m.Traceparent)) {
_ = d.Reject(false)
continue
}
jobctx, sp := telemetry.Start(telemetry.Extract(ctx, m.Traceparent, m.Tracestate), "attachments consume", trace.SpanKindConsumer)
slog.InfoContext(jobctx, "job_received", "job_id", m.JobID, "attempt", m.Attempt)
e = process(jobctx, m)
telemetry.End(sp, e)
if e != nil {
slog.WarnContext(jobctx, "job_not_acknowledged", "job_id", m.JobID, "reason", "processing_or_dependency_unavailable")
select {
case <-ctx.Done():
case <-time.After(200 * time.Millisecond):
}
_ = d.Nack(false, true)
continue
}
fault.Hit(ctx, "before_ack", m.JobID)
_ = d.Ack(false)
}
}()
}
for d := range deliveries {
select {
case tasks <- d:
case <-ctx.Done():
}
}
close(tasks)
for range concurrency {
<-finished
}
if ctx.Err() != nil {
return ctx.Err()
}
return errors.New("broker consumer disconnected")
}
func (r *Rabbit) Depth(ctx context.Context) (int, error) {
conn, ch, e := r.connect(2 * time.Second)
if e != nil {
return 0, e
}
defer conn.Close()
defer ch.Close()
q, e := ch.QueueInspect(Queue)
return q.Messages, e
}
@@ -0,0 +1 @@
package http
@@ -0,0 +1,111 @@
package http
import (
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"io"
"mime"
"net/http"
"strconv"
"strings"
)
type AttachmentHandler struct {
router router.Router
provider jwtprovider.Provider
svc *attachment.Service
}
func NewAttachmentHandler(r router.Router, p jwtprovider.Provider, s *attachment.Service) Handler {
return &AttachmentHandler{r, p, s}
}
func (h *AttachmentHandler) RegisterRoutes() {
h.router.Private("POST", "/api/v1/chats/{chat_id}/attachments", h.Upload)
h.router.Private("GET", "/api/v1/attachments/{attachment_id}", h.Get)
h.router.Private("GET", "/api/v1/attachments/{attachment_id}/content", h.Get)
}
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
user, e := framework.ParseToken(r, h.provider)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "chat_id")
if e != nil {
return
}
values := r.URL.Query()["filename"]
if len(values) != 1 {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one filename"))
return
}
if !attachment.ValidFilename(values[0]) {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid filename"))
return
}
mt, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || (mt != "image/png" && mt != "image/jpeg") {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected PNG or JPEG"))
return
}
if r.ContentLength > h.svc.Config.MaxBytes {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodePayloadTooLarge, "upload too large"))
return
}
a, e := h.svc.Upload(r.Context(), dto.UploadAttachment{UserID: user.UserID, ChatID: id, Filename: values[0], ContentType: mt, Body: io.LimitReader(r.Body, h.svc.Config.MaxBytes+1)})
if e != nil {
if apperr.CodeFromError(e) == apperr.CodeTooManyRequests {
w.Header().Set("Retry-After", "1")
}
framework.JSONError(r.Context(), w, e)
return
}
framework.JSONResponse(w, http.StatusAccepted, a)
}
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
user, e := framework.ParseToken(r, h.provider)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "attachment_id")
if e != nil {
return
}
if !strings.HasSuffix(r.URL.Path, "/content") {
a, e := h.svc.Get(r.Context(), user.UserID, id)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
framework.JSONResponse(w, 200, a.Public)
return
}
v := r.URL.Query().Get("variant")
if v == "" {
v = "original"
}
if v != "original" && v != "thumbnail" && v != "crop" && v != "optimized" {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid variant"))
return
}
obj, e := h.svc.Content(r.Context(), user.UserID, id, v)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
defer obj.Body.Close()
w.Header().Set("Content-Type", obj.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(obj.Size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
// Once streaming has started a transport failure terminates the response; no JSON
// error can be appended to an image. Content-Length exposes incomplete downloads.
if _, e = io.Copy(w, obj.Body); e != nil {
panic(http.ErrAbortHandler)
}
}
@@ -0,0 +1,88 @@
package http
import (
"net/http"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
)
type AuthHandler struct {
router router.Router
auth auth.API
}
func NewAuthHandler(r router.Router, api auth.API) Handler {
return &AuthHandler{
router: r,
auth: api,
}
}
func (h *AuthHandler) RegisterRoutes() {
h.router.Public(http.MethodPost, "/api/v1/auth/sessions", h.Login)
h.router.Private(http.MethodDelete, "/api/v1/auth/sessions/current", h.Logout)
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
username, password, ok := r.BasicAuth()
if !ok || username == "" || password == "" {
w.Header().Set(
"WWW-Authenticate",
`Basic realm="messenger", charset="UTF-8"`,
)
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "invalid credentials"))
return
}
resp, err := h.auth.Login(ctx, dto.Login{
Username: username,
Password: password,
})
if err != nil {
if apperr.HTTPStatusFromError(err) == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
}
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Session{
ExpiresAt: resp.ExpiresAt,
Token: resp.Tokens.RefreshToken.Payload,
TokenType: resp.TokenType,
User: contracts.User{
CreatedAt: resp.User.CreatedAt,
DisplayName: resp.User.DisplayName,
Id: resp.User.ID,
Username: resp.User.Username,
},
})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token, exists := framework.Token(r)
if !exists {
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing token in header"))
return
}
err := h.auth.Logout(ctx, dto.RefreshToken{
Payload: token,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusNoContent, nil)
}
@@ -0,0 +1,287 @@
package http
import (
"bytes"
"encoding/json"
"net/http"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
)
var messageKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type ChatHandler struct {
router router.Router
provider jwtprovider.Provider
validator *validator.ValidatorImpl
chat chat.API
}
func NewChatHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api chat.API) Handler {
return &ChatHandler{
router: r,
provider: provider,
validator: v,
chat: api,
}
}
func (h *ChatHandler) RegisterRoutes() {
h.router.Private(http.MethodPost, "/api/v1/chats", h.Create)
h.router.Private(http.MethodGet, "/api/v1/chats", h.Get)
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}", h.GetByID)
h.router.Private(http.MethodPost, "/api/v1/chats/{chat_id}/messages", h.SendMessage)
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}/messages", h.GetMessages)
}
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
var req contracts.CreateChat
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
if userData.UserID == uuid.Nil ||
!validText(req.Title, 100) ||
len(req.MemberIds) < 1 ||
len(req.MemberIds) > 100 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid chat fields"))
return
}
resp, err := h.chat.CreateChat(ctx, dto.CreateChat{
CreatorID: userData.UserID,
Title: req.Title,
MemberIDs: req.MemberIds,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Chat{
Id: resp.ID,
Title: resp.Title,
MemberIds: resp.MemberIDs,
CreatedAt: resp.CreatedAt,
})
}
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
limit, afterID, ok := framework.PageParams(w, r)
if !ok {
return
}
if userData.UserID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
return
}
if afterID != nil && *afterID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
return
}
page, err := h.chat.ListForMember(ctx, dto.ChatFilters{
UserID: userData.UserID,
Limit: limit,
AfterID: afterID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
items := make([]contracts.Chat, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, contracts.Chat{
CreatedAt: item.CreatedAt,
Id: item.ID,
MemberIds: item.MemberIDs,
Title: item.Title,
})
}
framework.JSONResponse(w, http.StatusOK, contracts.ChatPage{
Items: items,
NextCursor: cursorString(page.NextCursorID),
})
}
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
UserID: userData.UserID,
ChatID: chatID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusOK, contracts.Chat{
CreatedAt: resp.CreatedAt,
Id: resp.ID,
MemberIds: resp.MemberIDs,
Title: resp.Title,
})
}
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
keyValues := r.Header.Values("Idempotency-Key")
if len(keyValues) != 1 || !messageKeyPattern.MatchString(keyValues[0]) {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid idempotency key"))
return
}
var req struct {
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
if req.Text == nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "text is required"))
return
}
ids := []uuid.UUID{}
if len(req.AttachmentIDs) > 0 {
if bytes.Equal(bytes.TrimSpace(req.AttachmentIDs), []byte("null")) || json.Unmarshal(req.AttachmentIDs, &ids) != nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid attachment_ids"))
return
}
}
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
IdempotencyKey: keyValues[0],
ChatID: chatID,
SenderID: userData.UserID,
Text: *req.Text,
AttachmentIDs: ids,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Message{
Id: message.ID,
ChatId: message.ChatID,
SenderId: message.SenderID,
Text: message.Text,
CreatedAt: message.CreatedAt,
AttachmentIds: message.AttachmentIDs,
})
}
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
limit, afterID, ok := framework.PageParams(w, r)
if !ok {
return
}
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
ChatID: chatID,
UserID: userData.UserID,
Limit: limit,
AfterID: afterID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
items := make([]contracts.Message, 0, len(page.Items))
for _, message := range page.Items {
items = append(items, contracts.Message{
Id: message.ID,
ChatId: message.ChatID,
SenderId: message.SenderID,
Text: message.Text,
CreatedAt: message.CreatedAt,
AttachmentIds: message.AttachmentIDs,
})
}
framework.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
}
func cursorString(id *uuid.UUID) *string {
if id == nil {
return nil
}
value := id.String()
return &value
}
func validText(value string, maxLength int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
}
@@ -0,0 +1,102 @@
package http
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"sync/atomic"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
)
type Server interface {
ShouldBeRunning() bool
Ready() bool
Start(ctx context.Context) error
Stop(ctx context.Context) error
}
type server struct {
server http.Server
cfg *config.Server
ready atomic.Bool
}
func New(cfg *config.Config, router router.Router) Server {
s := server{
server: http.Server{
Addr: cfg.Server.BindAddress(),
Handler: router,
ReadTimeout: cfg.Server.ReadTimeout,
WriteTimeout: cfg.Server.WriteTimeout,
IdleTimeout: cfg.Server.IdleTimeout,
},
cfg: cfg.Server,
ready: atomic.Bool{},
}
if err := s.validate(); err != nil {
panic(err)
}
return &s
}
func (s *server) Start(_ context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip starting")
return nil
}
listener, err := net.Listen("tcp", s.server.Addr)
if err != nil {
return err
}
s.ready.Store(true)
go func() {
defer s.ready.Store(false)
if err := s.server.Serve(listener); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
slog.Error("rest server failed", "error", err)
}
}()
return nil
}
func (s *server) Stop(ctx context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip stopping")
return nil
}
slog.Info("shutting down rest server...", "address", s.server.Addr)
s.ready.Store(false)
if err := s.server.Shutdown(ctx); err != nil {
slog.Error("rest server shutdown failed", "error", err)
_ = s.server.Close()
return err
}
slog.Info("rest server shutdown successfully")
return nil
}
func (s *server) ShouldBeRunning() bool {
return s.cfg.Enabled
}
func (s *server) Ready() bool {
return s.ready.Load()
}
func (s *server) validate() error {
if s.cfg == nil {
slog.Error("failed to validate server: provided nil config")
return errors.New("failed to validate server: provided nil config")
}
slog.Info("server successfully validated")
return nil
}
@@ -0,0 +1,5 @@
package http
type Handler interface {
RegisterRoutes()
}
@@ -0,0 +1,60 @@
package http
import (
"context"
"net/http"
"time"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
)
type databasePinger interface{ Ping(context.Context) error }
type HealthHandler struct {
router router.Router
server Server
database databasePinger
storage []databasePinger
}
func NewHealthHandler(r router.Router, server Server, database databasePinger, storage ...databasePinger) Handler {
return &HealthHandler{
router: r,
server: server,
database: database,
storage: storage,
}
}
func (h *HealthHandler) RegisterRoutes() {
h.router.Public(http.MethodGet, "/health/ready", h.Ready)
h.router.Public(http.MethodGet, "/health/live", h.Live)
}
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
if !h.server.Ready() {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
return
}
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
defer cancel()
if err := h.database.Ping(ctx); err != nil {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "database unavailable"))
return
}
for _, dependency := range h.storage {
if err := dependency.Ping(ctx); err != nil {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "storage unavailable"))
return
}
}
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
}
@@ -0,0 +1 @@
package http
@@ -0,0 +1,113 @@
package http
import (
"net/http"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
"gitea.privcloud.tech/mtusi2026/internal/service/user"
)
type UserHandler struct {
router router.Router
provider jwtprovider.Provider
validator *validator.ValidatorImpl
user user.API
}
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
return &UserHandler{
router: r,
provider: provider,
validator: v,
user: api,
}
}
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (h *UserHandler) RegisterRoutes() {
h.router.Public(http.MethodPost, "/api/v1/users", h.Create)
h.router.Private(http.MethodGet, "/api/v1/users/me", h.GetMe)
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var req contracts.CreateUser
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
toCreate := dto.CreateUser{
Username: req.Username,
DisplayName: req.DisplayName,
}
if req.Password != nil {
toCreate.Password = *req.Password
}
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user fields"))
return
}
passwordLen := utf8.RuneCountInString(toCreate.Password)
if !utf8.ValidString(toCreate.Password) || strings.TrimSpace(toCreate.Password) == "" || passwordLen < 12 || passwordLen > 128 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid password"))
return
}
resp, err := h.user.Create(ctx, toCreate)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.User{
CreatedAt: resp.CreatedAt,
DisplayName: resp.DisplayName,
Id: resp.ID,
Username: resp.Username,
})
}
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
if userData.UserID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
return
}
resp, err := h.user.GetByID(ctx, userData.UserID)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusOK, contracts.User{
CreatedAt: resp.CreatedAt,
DisplayName: resp.DisplayName,
Id: resp.ID,
Username: resp.Username,
})
}
@@ -0,0 +1,78 @@
package outside
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
)
const (
// chatRedisKey equals "chat:{chat_id}" path
chatRedisKey = "chat:%s"
)
type ChatCache struct {
client *cache.Client
}
func NewChatCache(client *cache.Client) *ChatCache {
return &ChatCache{
client: client,
}
}
type chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
func (r *ChatCache) Create(ctx context.Context, req dto.Chat) error {
data, err := json.Marshal(chat{
ID: req.ID,
Title: req.Title,
MemberIDs: req.MemberIDs,
CreatedAt: req.CreatedAt,
})
if err != nil {
return apperr.Wrap(err, apperr.CodeInternal, "failed to marshal chat cache")
}
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
err = r.client.Set(ctx, fmt.Sprintf(chatRedisKey, req.ID), data, 0).Err()
if err != nil {
return apperr.WrapRedis(err, "failed to create chat cache")
}
return nil
}
func (r *ChatCache) Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
data, err := r.client.Get(ctx, fmt.Sprintf(chatRedisKey, chatID.String())).Bytes()
if err != nil {
return nil, apperr.WrapRedis(err, "failed to read chat cache")
}
var item chat
if err = json.Unmarshal(data, &item); err != nil {
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to unmarshal chat cache")
}
return &dto.Chat{
ID: item.ID,
Title: item.Title,
MemberIDs: item.MemberIDs,
CreatedAt: item.CreatedAt,
}, nil
}
@@ -0,0 +1,39 @@
package storage
import (
"context"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
func (r *AttachmentsRepo) Page(ctx context.Context, after uuid.UUID) ([]*AttachmentRecord, error) {
rows, e := r.Pool.Query(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id>$1 ORDER BY id LIMIT 100", after)
if e != nil {
return nil, apperr.WrapPostgres(e, "scan failed")
}
defer rows.Close()
out := make([]*AttachmentRecord, 0, 100)
for rows.Next() {
a, e := ScanAttachment(rows)
if e != nil {
return nil, e
}
out = append(out, a)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) Exists(ctx context.Context, c *pgxpool.Conn, key string) (bool, error) {
var found bool
e := c.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachment_variants WHERE object_key=$1 UNION ALL SELECT 1 FROM attachments WHERE object_key=$1 OR staging_key=$1 OR variant_keys @> jsonb_build_object('thumbnail',$1::text) OR variant_keys @> jsonb_build_object('crop',$1::text) OR variant_keys @> jsonb_build_object('optimized',$1::text))", key).Scan(&found)
return found, e
}
func (r *AttachmentsRepo) MarkMissing(ctx context.Context, c *pgxpool.Conn, id uuid.UUID, missing bool) (bool, error) {
tag, e := c.Exec(ctx, "UPDATE attachments SET integrity_missing=$2,updated_at=clock_timestamp() WHERE id=$1 AND integrity_missing<>$2", id, missing)
return tag.RowsAffected() == 1, e
}
func (r *AttachmentsRepo) CheckConn(ctx context.Context, c *pgxpool.Conn) error {
_, e := c.Exec(ctx, "SELECT 1")
return e
}
@@ -0,0 +1,65 @@
package storage
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type AttachmentRecord = dto.AttachmentRecord
type AttachmentsRepo struct{ Pool *pgxpool.Pool }
const AttachmentColumns = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,integrity_missing,status,error_code,pipeline_version,staging_key,variants,variant_keys"
func ScanAttachment(row pgx.Row) (*AttachmentRecord, error) {
a := new(AttachmentRecord)
p := &a.Public
var variants, keys []byte
if err := row.Scan(&p.Id, &p.ChatId, &p.OwnerId, &p.Filename, &p.ContentType, &p.SizeBytes, &p.Sha256, &p.CreatedAt, &p.UpdatedAt, &a.Key, &a.Missing, &p.Status, &p.ErrorCode, &a.PipelineVersion, &a.StagingKey, &variants, &keys); err != nil {
return nil, apperr.WrapPostgres(err, "attachment unavailable")
}
if err := json.Unmarshal(variants, &p.Variants); err != nil {
return nil, err
}
if err := json.Unmarshal(keys, &a.VariantKeys); err != nil {
return nil, err
}
return a, nil
}
func (r *AttachmentsRepo) Get(ctx context.Context, id uuid.UUID) (*AttachmentRecord, error) {
return ScanAttachment(r.Pool.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1", id))
}
// Session locks span S3 work and the database commit. A lost connection releases
// the lock; the mandatory grace period also exceeds the maximum upload lifetime.
func (r *AttachmentsRepo) Lock(ctx context.Context, key string) (*pgxpool.Conn, func(), error) {
c, e := r.Pool.Acquire(ctx)
if e != nil {
return nil, nil, apperr.WrapPostgres(e, "database unavailable")
}
if _, e = c.Exec(ctx, "SELECT pg_advisory_lock(hashtextextended($1, 42))", key); e != nil {
// The server may have acquired the session lock before cancellation was
// observed by the client. Never return that uncertain session to the pool.
clean, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = c.Conn().Close(clean)
cancel()
c.Release()
return nil, nil, apperr.WrapPostgres(e, "lock unavailable")
}
return c, func() {
// Close rather than return a possibly locked session when unlock fails.
clean, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if _, e := c.Exec(clean, "SELECT pg_advisory_unlock(hashtextextended($1, 42))", key); e != nil {
_ = c.Conn().Close(clean)
}
c.Release()
}, nil
}
@@ -0,0 +1,91 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type ChatsRepo struct {
pool *pgxpool.Pool
}
func NewChatsRepo(pool *pgxpool.Pool) *ChatsRepo {
return &ChatsRepo{pool: pool}
}
func (r *ChatsRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error {
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
if _, err := tx.Exec(ctx, insertChat, req.ID, req.Title, req.CreatedAt); err != nil {
return apperr.WrapPostgres(err, "failed to create chat")
}
const insertMembers = `INSERT INTO chat_members (chat_id, user_id)
SELECT $1, user_id FROM unnest($2::uuid[]) AS members(user_id)`
if _, err := tx.Exec(ctx, insertMembers, req.ID, req.MemberIDs); err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "chat_members_user_fk" {
return apperr.Wrap(err, apperr.CodeBadRequest, "unknown chat member")
}
return apperr.WrapPostgres(err, "failed to create chat members")
}
return nil
}
func (r *ChatsRepo) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
const query = `SELECT c.id, c.title, c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
FROM chats c
WHERE c.id = $1
AND EXISTS (SELECT 1 FROM chat_members access WHERE access.chat_id = c.id AND access.user_id = $2)`
return scanChat(r.pool.QueryRow(ctx, query, req.ChatID, req.UserID))
}
func (r *ChatsRepo) ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error) {
query := `WITH page AS MATERIALIZED (
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members access ON access.chat_id = c.id
WHERE access.user_id = $1`
args := []any{userID, page.Limit}
if page.After != nil {
query += ` AND (c.created_at, c.id) > ($3, $4)`
args = append(args, page.After.CreatedAt, page.After.ID)
}
query += ` ORDER BY c.created_at, c.id LIMIT $2
)
SELECT p.id, p.title, p.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = p.id ORDER BY m.user_id)
FROM page p ORDER BY p.created_at, p.id`
rows, err := r.pool.Query(ctx, query, args...)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to list chats")
}
defer rows.Close()
chats := make([]dto.Chat, 0)
for rows.Next() {
chat, err := scanChat(rows)
if err != nil {
return nil, err
}
chats = append(chats, *chat)
}
if err = rows.Err(); err != nil {
return nil, apperr.WrapPostgres(err, "failed to list chats")
}
return chats, nil
}
func scanChat(row pgx.Row) (*dto.Chat, error) {
var chat dto.Chat
if err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get chat")
}
return &chat, nil
}
@@ -0,0 +1,303 @@
package storage
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
chatsvc "gitea.privcloud.tech/mtusi2026/internal/service/chat"
"github.com/google/uuid"
)
// The explicit runner supplies a newly created database; never alter the API database.
func TestIdempotencyTransactionAndExpiry(t *testing.T) {
database := os.Getenv("TEST_DATABASE_NAME")
if database == "" {
t.Skip("run make test-storage for an isolated PostgreSQL database")
}
if database == os.Getenv("POSTGRES_DATABASE") {
t.Fatal("test database must differ from application database")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cfg, err := config.New()
if err != nil {
t.Fatal(err)
}
cfg.Postgres.Database = database
cfg.Postgres.RunMigrations = true
if err = migrator.New(cfg).Start(ctx); err != nil {
t.Fatal(err)
}
pool := postgres.New(cfg.Postgres)
defer pool.Close()
repo := NewMessagesRepo(pool)
user, chat := uuid.New(), uuid.New()
if _, err = pool.Exec(ctx, `INSERT INTO users(id,name,username,password_hash) VALUES($1,'Synthetic','atomic_test','unused')`, user); err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Atomic test')`, chat); err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, chat, user); err != nil {
t.Fatal(err)
}
req := dto.CreateMessage{ChatID: chat, SenderID: user, Text: "atomic", IdempotencyKey: "atomic-key"}
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err != nil {
t.Fatal(err)
}
if err = tx.Rollback(ctx); err != nil {
t.Fatal(err)
}
var messages, keys int
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
t.Fatal(err)
}
if messages != 0 || keys != 0 {
t.Fatalf("rollback left %d messages, %d keys", messages, keys)
}
tx, err = pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
first, err := chatsvc.CreateIdempotentTx(ctx, tx, repo, req)
if err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
// Expire the test record only: no shortened production TTL and no wall-clock wait.
if _, err = pool.Exec(ctx, `UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1`, user); err != nil {
t.Fatal(err)
}
req.Text = "new after expiry"
tx, err = pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
second, err := chatsvc.CreateIdempotentTx(ctx, tx, repo, req)
if err != nil {
t.Fatal(err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
if first.ID == second.ID {
t.Fatal("expired key replayed old message")
}
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
t.Fatal(err)
}
if messages != 2 || keys != 1 {
t.Fatalf("expiry left %d messages, %d keys; want 2,1", messages, keys)
}
if _, err = pool.Exec(ctx, `CREATE FUNCTION reject_test_key() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.key='failure-key' THEN RAISE EXCEPTION 'synthetic failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test_key BEFORE INSERT ON message_idempotency FOR EACH ROW EXECUTE FUNCTION reject_test_key()`); err != nil {
t.Fatal(err)
}
req.IdempotencyKey = "failure-key"
tx, err = pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err == nil {
t.Fatal("expected injected failure")
}
if err = tx.Rollback(ctx); err != nil {
t.Fatal(err)
}
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
t.Fatal(err)
}
if messages != 2 || keys != 1 {
t.Fatal("failed result persisted a side effect")
}
if _, err = pool.Exec(ctx, `DROP TRIGGER reject_test_key ON message_idempotency; DROP FUNCTION reject_test_key()`); err != nil {
t.Fatal(err)
}
tx, err = pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
if _, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, req); err != nil {
t.Fatal("transient failure was cached", err)
}
if err = tx.Commit(ctx); err != nil {
t.Fatal(err)
}
t.Run("service owns message content rules", func(t *testing.T) {
svc := chatsvc.New(txmanager.New(pool), NewChatsRepo(pool), repo, uncachedChats{})
own, foreign, missing := uuid.New(), uuid.New(), uuid.New()
otherChat := uuid.New()
if _, err := pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Other chat');`, otherChat); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, otherChat, user); err != nil {
t.Fatal(err)
}
for _, fixture := range []struct {
id, chat uuid.UUID
missing bool
}{{own, chat, false}, {foreign, otherChat, false}, {missing, chat, true}} {
if _, err := pool.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,integrity_missing,created_at,updated_at) VALUES($1,$2,$3,'test.png',$4,'image/png',1,$5,$6,now(),now())`, fixture.id, fixture.chat, user, "originals/"+fixture.id.String(), strings.Repeat("a", 64), fixture.missing); err != nil {
t.Fatal(err)
}
}
counts := func() string {
t.Helper()
var messages, links, keys int
if err := pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_attachments),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &links, &keys); err != nil {
t.Fatal(err)
}
return fmt.Sprintf("%d/%d/%d", messages, links, keys)
}
for _, tc := range []struct {
name, text string
ids []uuid.UUID
code apperr.Code
}{
{"empty", "", nil, apperr.CodeBadRequest},
{"whitespace", " \t\n\u2003", nil, apperr.CodeBadRequest},
{"invalid UTF8", string([]byte{0xff}), nil, apperr.CodeBadRequest},
{"nul", "\x00", nil, apperr.CodeBadRequest},
{"too long", strings.Repeat("я", 4001), nil, apperr.CodeBadRequest},
{"duplicate", "", []uuid.UUID{own, own}, apperr.CodeBadRequest},
{"too many", "text", make([]uuid.UUID, 11), apperr.CodeBadRequest},
{"nil id", "", []uuid.UUID{uuid.Nil}, apperr.CodeBadRequest},
{"unknown", "", []uuid.UUID{uuid.New()}, apperr.CodeNotFound},
{"foreign chat", "", []uuid.UUID{foreign}, apperr.CodeNotFound},
{"missing object", "", []uuid.UUID{missing}, apperr.CodeUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
before := counts()
_, err := svc.CreateMessage(ctx, dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: tc.text, AttachmentIDs: tc.ids})
if err == nil || apperr.CodeFromError(err) != tc.code {
t.Fatalf("got %v, want code %v", err, tc.code)
}
if after := counts(); after != before {
t.Fatalf("rejected message changed counts: %s -> %s", before, after)
}
})
}
for _, text := range []string{"", " \t\u2003"} {
request := dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: text, AttachmentIDs: []uuid.UUID{own}}
first, err := svc.CreateMessage(ctx, request)
if err != nil {
t.Fatal(err)
}
replay, err := svc.CreateMessage(ctx, request)
if err != nil || replay.ID != first.ID || len(replay.AttachmentIDs) != 1 || replay.AttachmentIDs[0] != own {
t.Fatalf("attachment replay failed: %v, %v", replay, err)
}
page, err := svc.ListForChat(ctx, dto.MessageFilters{UserID: user, ChatID: chat})
if err != nil {
t.Fatal(err)
}
found := false
for _, msg := range page.Items {
if msg.ID == first.ID {
found = len(msg.AttachmentIDs) == 1 && msg.AttachmentIDs[0] == own
}
}
if !found {
t.Fatal("history lost attachment")
}
request.AttachmentIDs = []uuid.UUID{foreign}
if _, err = svc.CreateMessage(ctx, request); apperr.CodeFromError(err) != apperr.CodeNotFound {
t.Fatalf("foreign replay: %v", err)
}
}
// Preserve legacy hashes written before the attachment migration.
legacy := dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: "legacy"}
first, err := svc.CreateMessage(ctx, legacy)
if err != nil {
t.Fatal(err)
}
hash := sha256.Sum256([]byte(legacy.Text))
if _, err = pool.Exec(ctx, `UPDATE message_idempotency SET request_hash=$1,hash_version=1 WHERE key=$2`, hash[:], legacy.IdempotencyKey); err != nil {
t.Fatal(err)
}
replay, err := svc.CreateMessage(ctx, legacy)
if err != nil || replay.ID != first.ID {
t.Fatalf("legacy replay failed: %v", err)
}
legacy.AttachmentIDs = []uuid.UUID{own}
if _, err = svc.CreateMessage(ctx, legacy); apperr.CodeFromError(err) != apperr.CodeConflict {
t.Fatalf("legacy hash ignored new attachment: %v", err)
}
textOnly := dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: "text only"}
first, err = svc.CreateMessage(ctx, textOnly)
if err != nil {
t.Fatal(err)
}
textOnly.AttachmentIDs = []uuid.UUID{}
replay, err = svc.CreateMessage(ctx, textOnly)
if err != nil || replay.ID != first.ID {
t.Fatalf("nil and empty attachment lists differ: %v", err)
}
// Force link failure using the relational FK and prove all preceding writes roll back.
before := counts()
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
_, err = chatsvc.CreateIdempotentTx(ctx, tx, repo, dto.CreateMessage{ChatID: chat, SenderID: user, IdempotencyKey: uuid.NewString(), Text: "link rollback", AttachmentIDs: []uuid.UUID{own, uuid.New()}})
if err == nil {
t.Fatal("expected missing attachment FK failure")
}
_ = tx.Rollback(ctx)
if after := counts(); after != before {
t.Fatalf("failed link changed counts: %s -> %s", before, after)
}
var triggers int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM pg_trigger WHERE tgname='message_content'`).Scan(&triggers); err != nil || triggers != 0 {
t.Fatalf("message trigger remains: %d, %v", triggers, err)
}
})
t.Run("object lock cancellation does not leak a pooled lock", func(t *testing.T) {
attachments := &AttachmentsRepo{Pool: pool}
key := "originals/" + uuid.NewString()
_, unlock, err := attachments.Lock(ctx, key)
if err != nil {
t.Fatal(err)
}
waiting, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
_, _, err = attachments.Lock(waiting, key)
cancel()
unlock()
if err == nil {
t.Fatal("contending lock ignored deadline")
}
_, release, err := attachments.Lock(ctx, key)
if err != nil {
t.Fatalf("lock leaked after cancellation: %v", err)
}
release()
})
t.Log("rollback removed both side effect and key; expired key created one new message")
}
type uncachedChats struct{}
func (uncachedChats) Create(context.Context, dto.Chat) error { return nil }
func (uncachedChats) Get(context.Context, uuid.UUID) (*dto.Chat, error) {
return nil, errors.New("cache disabled for storage test")
}
@@ -0,0 +1,134 @@
package storage
import (
"context"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"time"
)
func (r *AttachmentsRepo) Ping(ctx context.Context) error { return r.Pool.Ping(ctx) }
func (r *AttachmentsRepo) GetTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentRecord, error) {
return ScanAttachment(tx.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1 FOR UPDATE", id))
}
func (r *AttachmentsRepo) InsertTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
p := a.Public
_, e := tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,staging_key,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$10,$11)`, p.Id, p.ChatId, p.OwnerId, p.Filename, p.ContentType, p.SizeBytes, p.Sha256, p.CreatedAt, p.UpdatedAt, a.StagingKey, p.Status)
return e
}
func (r *AttachmentsRepo) UpdateTx(ctx context.Context, tx pgx.Tx, a *dto.AttachmentRecord) error {
variants, e := json.Marshal(a.Public.Variants)
if e != nil {
return e
}
keys, e := json.Marshal(a.VariantKeys)
if e != nil {
return e
}
_, e = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,pipeline_version=$4,staging_key=$5,object_key=$6,variants=$7,variant_keys=$8,updated_at=$9,integrity_missing=$10 WHERE id=$1`, a.Public.Id, a.Public.Status, a.Public.ErrorCode, a.PipelineVersion, a.StagingKey, a.Key, variants, keys, a.Public.UpdatedAt, a.Missing)
return e
}
const jobColumns = `id,attachment_id,pipeline_version,attempt,created_at,state,token,lease_until,next_attempt_at,attempt_limit,error_code,updated_at,traceparent,tracestate`
func scanJob(row pgx.Row) (*dto.AttachmentJob, error) {
j := new(dto.AttachmentJob)
m := &j.Message
err := row.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt, &j.State, &j.Token, &j.LeaseUntil, &j.NextAttemptAt, &j.AttemptLimit, &j.ErrorCode, &j.UpdatedAt, &m.Traceparent, &m.Tracestate)
m.SchemaVersion = 1
m.Type = "attachment.process.v1"
return j, err
}
func (r *AttachmentsRepo) JobTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.AttachmentJob, error) {
return scanJob(tx.QueryRow(ctx, `SELECT `+jobColumns+` FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id))
}
func (r *AttachmentsRepo) InsertJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
m := j.Message
_, e := tx.Exec(ctx, `INSERT INTO attachment_jobs(`+jobColumns+`) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)`, m.JobID, m.AttachmentID, m.PipelineVersion, m.Attempt, m.CreatedAt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt, m.Traceparent, m.Tracestate)
return e
}
func (r *AttachmentsRepo) SaveJobTx(ctx context.Context, tx pgx.Tx, j *dto.AttachmentJob) error {
_, e := tx.Exec(ctx, `UPDATE attachment_jobs SET attempt=$2,state=$3,token=$4,lease_until=$5,next_attempt_at=$6,attempt_limit=$7,error_code=$8,updated_at=$9,traceparent=$10,tracestate=$11 WHERE id=$1`, j.Message.JobID, j.Message.Attempt, j.State, j.Token, j.LeaseUntil, j.NextAttemptAt, j.AttemptLimit, j.ErrorCode, j.UpdatedAt, j.Message.Traceparent, j.Message.Tracestate)
return e
}
func (r *AttachmentsRepo) ExpiredJobs(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT id FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() ORDER BY lease_until LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) AuditTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, action string) error {
_, e := tx.Exec(ctx, `INSERT INTO job_audit(job_id,action) VALUES($1,$2)`, id, action)
return e
}
func (r *AttachmentsRepo) ListJobs(ctx context.Context) ([]dto.AttachmentJob, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+jobColumns+` FROM attachment_jobs ORDER BY updated_at DESC LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
out := []dto.AttachmentJob{}
for rows.Next() {
j, e := scanJob(rows)
if e != nil {
return nil, e
}
out = append(out, *j)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) FailedOutbox(ctx context.Context) ([]uuid.UUID, error) {
rows, e := r.Pool.Query(ctx, `SELECT DISTINCT o.job_id FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.status='dead_letter' AND j.state='queued' AND (o.payload->>'attempt')::integer=j.attempt LIMIT 100`)
if e != nil {
return nil, e
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if e = rows.Scan(&id); e != nil {
return nil, e
}
ids = append(ids, id)
}
return ids, rows.Err()
}
func (r *AttachmentsRepo) RetiredSources(ctx context.Context, before time.Time) ([]*dto.AttachmentRecord, error) {
rows, e := r.Pool.Query(ctx, `SELECT `+AttachmentColumns+` FROM attachments WHERE staging_key<>'' AND (status='ready' OR (status='failed' AND updated_at<$1)) LIMIT 100`, before)
if e != nil {
return nil, e
}
defer rows.Close()
var out []*dto.AttachmentRecord
for rows.Next() {
a, e := ScanAttachment(rows)
if e != nil {
return nil, e
}
out = append(out, a)
}
return out, rows.Err()
}
func (r *AttachmentsRepo) SaveVariantTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, version int, name, key, sha string, size int64) error {
_, e := tx.Exec(ctx, `INSERT INTO attachment_variants(attachment_id,pipeline_version,variant,object_key,sha256,size_bytes) VALUES($1,$2,$3,$4,$5,$6)`, id, version, name, key, sha, size)
return e
}
func (r *AttachmentsRepo) PublicationDeadTx(ctx context.Context, tx pgx.Tx, id uuid.UUID, attempt int) (bool, error) {
var dead bool
e := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM outbox WHERE job_id=$1 AND status='dead_letter' AND (payload->>'attempt')::integer=$2)`, id, attempt).Scan(&dead)
return dead, e
}
@@ -0,0 +1,135 @@
package storage
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type MessagesRepo struct {
pool *pgxpool.Pool
}
func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
return &MessagesRepo{pool: pool}
}
// LockKeyTx serializes persistence for one idempotency scope.
func (r *MessagesRepo) LockKeyTx(ctx context.Context, tx pgx.Tx, scope string) error {
_, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, scope)
if err != nil {
return apperr.WrapPostgres(err, "failed to lock message key")
}
return nil
}
func (r *MessagesRepo) ReplayTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.MessageReplay, error) {
v := new(dto.MessageReplay)
err := tx.QueryRow(ctx, `SELECT request_hash,message_id,hash_version FROM message_idempotency WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`, req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&v.Hash, &v.MessageID, &v.HashVersion)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to read message key")
}
return v, nil
}
func (r *MessagesRepo) MessageTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.Message, error) {
return scanMessage(tx.QueryRow(ctx, `SELECT `+messageColumns+` FROM messages WHERE id=$1`, id))
}
func (r *MessagesRepo) InsertMessageTx(ctx context.Context, tx pgx.Tx, message dto.Message) error {
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`, message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
}
return apperr.WrapPostgres(err, "failed to create message")
}
for position, id := range message.AttachmentIDs {
if _, err = tx.Exec(ctx, `INSERT INTO message_attachments(message_id,chat_id,attachment_id,position) VALUES($1,$2,$3,$4)`, message.ID, message.ChatID, id, position); err != nil {
return apperr.WrapPostgres(err, "failed to link attachment")
}
}
return nil
}
func (r *MessagesRepo) SaveKeyTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage, hash []byte, messageID uuid.UUID, expires time.Time) error {
_, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at,hash_version) VALUES($1,'POST',$2,$3,$4,$5,$6,2) ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at,hash_version=EXCLUDED.hash_version`, req.SenderID, req.ChatID, req.IdempotencyKey, hash, messageID, expires)
if err != nil {
return apperr.WrapPostgres(err, "failed to save message key")
}
return nil
}
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
const query = `SELECT ` + messageColumns + ` FROM messages WHERE chat_id = $1 AND id = $2`
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
}
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
query := `SELECT ` + messageColumns + ` FROM messages WHERE chat_id = $1`
args := []any{chatID, page.Limit}
if page.After != nil {
query += ` AND (created_at, id) > ($3, $4)`
args = append(args, page.After.CreatedAt, page.After.ID)
}
query += ` ORDER BY created_at, id LIMIT $2`
rows, err := r.pool.Query(ctx, query, args...)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to list messages")
}
defer rows.Close()
messages := make([]dto.Message, 0)
for rows.Next() {
message, err := scanMessage(rows)
if err != nil {
return nil, err
}
messages = append(messages, *message)
}
if err = rows.Err(); err != nil {
return nil, apperr.WrapPostgres(err, "failed to list messages")
}
return messages, nil
}
func scanMessage(row pgx.Row) (*dto.Message, error) {
var message dto.Message
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get message")
}
return &message, nil
}
const messageColumns = `id, chat_id, sender_id, text, created_at,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=messages.id ORDER BY position)`
func (r *MessagesRepo) AttachmentsForMessageTx(ctx context.Context, tx pgx.Tx, ids []uuid.UUID) ([]dto.MessageAttachment, error) {
// Prevent a concurrent integrity update from invalidating the checked rows
// until the message and its links have committed together.
rows, err := tx.Query(ctx, `SELECT id, chat_id, integrity_missing,status FROM attachments WHERE id=ANY($1) ORDER BY id FOR SHARE`, ids)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to read attachments")
}
defer rows.Close()
result := make([]dto.MessageAttachment, 0, len(ids))
for rows.Next() {
var a dto.MessageAttachment
if err := rows.Scan(&a.ID, &a.ChatID, &a.Missing, &a.Status); err != nil {
return nil, apperr.WrapPostgres(err, "failed to read attachment")
}
result = append(result, a)
}
if err := rows.Err(); err != nil {
return nil, apperr.WrapPostgres(err, "failed to read attachments")
}
return result, nil
}
@@ -0,0 +1,51 @@
package storage
import (
"context"
"gitea.privcloud.tech/mtusi2026/internal/service/observation"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"time"
)
func (r *AttachmentsRepo) AcceptSLO(ctx context.Context, tx pgx.Tx, id uuid.UUID, accepted, deadline time.Time) error {
_, e := tx.Exec(ctx, `INSERT INTO job_slo(job_id,accepted_at,deadline_at)VALUES($1,$2,$3)`, id, accepted, deadline)
return e
}
func (r *AttachmentsRepo) ReadySLO(ctx context.Context, tx pgx.Tx, id uuid.UUID, ready time.Time) error {
_, e := tx.Exec(ctx, `UPDATE job_slo SET ready_at=COALESCE(ready_at,$2) WHERE job_id=$1`, id, ready)
return e
}
type ObservationRepo struct{ Pool *pgxpool.Pool }
func (r *ObservationRepo) Pending(ctx context.Context) ([]observation.Sample, error) {
rows, e := r.Pool.Query(ctx, `SELECT job_id,accepted_at,deadline_at,ready_at,failed_at FROM job_slo WHERE outcome IS NULL ORDER BY deadline_at LIMIT 500`)
if e != nil {
return nil, e
}
defer rows.Close()
out := []observation.Sample{}
for rows.Next() {
var x observation.Sample
if e = rows.Scan(&x.ID, &x.Accepted, &x.Deadline, &x.Ready, &x.Failed); e != nil {
return nil, e
}
out = append(out, x)
}
return out, rows.Err()
}
func (r *ObservationRepo) Decide(ctx context.Context, id uuid.UUID, outcome string, at time.Time) error {
_, e := r.Pool.Exec(ctx, `UPDATE job_slo SET outcome=$2,evaluated_at=$3 WHERE job_id=$1 AND outcome IS NULL`, id, outcome, at)
return e
}
func (r *ObservationRepo) Snapshot(ctx context.Context) (x observation.Snapshot, e error) {
e = r.Pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')), (SELECT count(*) FROM outbox WHERE status IN ('pending','processing','failed')), COALESCE((SELECT EXTRACT(EPOCH FROM clock_timestamp()-min(created_at)) FROM attachment_jobs WHERE state IN ('queued','processing')),0), (SELECT count(*) FROM job_slo WHERE outcome='good'), (SELECT count(*) FROM job_slo WHERE outcome='bad'), (SELECT count(*) FROM pg_stat_activity WHERE wait_event_type='Lock')`).Scan(&x.Queued, &x.Outbox, &x.Oldest, &x.Good, &x.Bad, &x.Locked)
return
}
func (r *AttachmentsRepo) FailSLO(ctx context.Context, tx pgx.Tx, id uuid.UUID, at time.Time) error {
_, e := tx.Exec(ctx, `UPDATE job_slo SET failed_at=COALESCE(failed_at,$2) WHERE job_id=$1`, id, at)
return e
}
@@ -0,0 +1,52 @@
package storage
import (
"context"
"errors"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"time"
)
type OutboxRepo struct{ Pool *pgxpool.Pool }
func (r *OutboxRepo) CreateTx(ctx context.Context, tx pgx.Tx, q outbox.CreateMessageReq) (outbox.CreateMessageRes, error) {
_, e := tx.Exec(ctx, `INSERT INTO outbox(id,job_id,payload,status,max_attempts,token,next_attempt_at,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$7,$7)`, q.ID, q.AggregateID, q.Payload, q.Status, q.MaxAttempts, uuid.New(), q.CreatedAt)
return outbox.CreateMessageRes{ID: q.ID, CreatedAt: q.CreatedAt}, e
}
func scanOutbox(rows pgx.Rows) (out []outbox.AcquiredMessage, err error) {
defer rows.Close()
for rows.Next() {
var m outbox.AcquiredMessage
if err = rows.Scan(&m.ID, &m.AggregateID, &m.Payload, &m.Attempts, &m.MaxAttempts, &m.Token); err != nil {
return
}
out = append(out, m)
}
err = rows.Err()
return
}
func (r *OutboxRepo) AcquireManyForProcessing(ctx context.Context, q outbox.AcquireMessagesForProcessingReq) ([]outbox.AcquiredMessage, error) {
rows, e := r.Pool.Query(ctx, `WITH picked AS (SELECT id FROM outbox WHERE status IN ('pending','failed') AND next_attempt_at<=clock_timestamp() ORDER BY next_attempt_at,id LIMIT $1 FOR UPDATE SKIP LOCKED)
UPDATE outbox o SET status='processing',attempts=attempts+1,token=$2,locked_until=clock_timestamp()+$3::interval,updated_at=clock_timestamp() FROM picked p WHERE o.id=p.id RETURNING o.id,o.job_id,o.payload,o.attempts,o.max_attempts,o.token`, q.Limit, uuid.New(), q.LockDuration.String())
if e != nil {
return nil, e
}
return scanOutbox(rows)
}
func (r *OutboxRepo) Expired(ctx context.Context) ([]outbox.AcquiredMessage, error) {
rows, e := r.Pool.Query(ctx, `SELECT id,job_id,payload,attempts,max_attempts,token FROM outbox WHERE status='processing' AND locked_until<clock_timestamp() LIMIT 100`)
if e != nil {
return nil, e
}
return scanOutbox(rows)
}
func (r *OutboxRepo) Update(ctx context.Context, m outbox.AcquiredMessage, status outbox.Status, next time.Time, code string) error {
tag, e := r.Pool.Exec(ctx, `UPDATE outbox SET status=$3,next_attempt_at=$4,last_error=NULLIF($5,''),locked_until=NULL,updated_at=clock_timestamp() WHERE id=$1 AND token=$2 AND status='processing'`, m.ID, m.Token, status, next, code)
if e == nil && tag.RowsAffected() != 1 {
return errors.New("outbox lease lost")
}
return e
}
@@ -0,0 +1,193 @@
package storage
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
)
type RefreshTokensRepo struct {
pool *pgxpool.Pool
}
func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
return &RefreshTokensRepo{
pool: pool,
}
}
func (r *RefreshTokensRepo) Create(ctx context.Context, req dto.StoredRefreshToken) error {
return r.create(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error {
return r.create(ctx, tx, req)
}
func (r *RefreshTokensRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, r.pool, id, false)
}
func (r *RefreshTokensRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, tx, id, false)
}
func (r *RefreshTokensRepo) GetByIDForUpdate(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, r.pool, id, true)
}
func (r *RefreshTokensRepo) GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, tx, id, true)
}
func (r *RefreshTokensRepo) Revoke(ctx context.Context, req dto.RevokeRefreshToken) error {
return r.revoke(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error {
return r.revoke(ctx, tx, req)
}
func (r *RefreshTokensRepo) RevokeAllByUserID(ctx context.Context, req dto.RevokeRefreshTokensByUserID) error {
return r.revokeAllByUserID(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) RevokeAllByUserIDTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshTokensByUserID) error {
return r.revokeAllByUserID(ctx, tx, req)
}
func (r *RefreshTokensRepo) DeleteExpired(ctx context.Context) error {
const query = `
DELETE FROM refresh_tokens
WHERE expires_at < $1`
_, err := r.pool.Exec(ctx, query, time.Now())
if err != nil {
return apperr.WrapPostgres(err, "failed to delete expired refresh tokens")
}
return nil
}
func (r *RefreshTokensRepo) create(ctx context.Context, conn postgres.Conn, req dto.StoredRefreshToken) error {
const query = `INSERT INTO refresh_tokens (id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`
ct, err := conn.Exec(
ctx,
query,
req.ID,
req.UserID,
req.TokenHash,
req.UserAgent,
req.IPAddress,
req.Role,
req.ExpiresAt,
req.CreatedAt,
)
if err != nil {
return apperr.WrapPostgres(err, "failed to create refresh token")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeAlreadyExists, "refresh token already exists")
}
return nil
}
func (r *RefreshTokensRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID, lock bool) (*dto.StoredRefreshToken, error) {
const query = `SELECT id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
revoked_at,
created_at
FROM refresh_tokens
WHERE id = $1`
const queryLock = `SELECT id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
revoked_at,
created_at
FROM refresh_tokens
WHERE id = $1 FOR UPDATE`
use := query
if lock {
use = queryLock
}
var token dto.StoredRefreshToken
err := conn.QueryRow(ctx, use, id).Scan(
&token.ID,
&token.UserID,
&token.TokenHash,
&token.UserAgent,
&token.IPAddress,
&token.Role,
&token.ExpiresAt,
&token.RevokedAt,
&token.CreatedAt,
)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to get refresh by id")
}
return &token, nil
}
func (r *RefreshTokensRepo) revoke(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshToken) error {
const query = `
UPDATE refresh_tokens
SET revoked_at = $2
WHERE id = $1
AND revoked_at IS NULL`
ct, err := conn.Exec(ctx, query, req.ID, req.RevokedAt)
if err != nil {
return apperr.WrapPostgres(err, "failed to revoke refresh token")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeNotFound, "refresh token not found")
}
return nil
}
func (r *RefreshTokensRepo) revokeAllByUserID(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshTokensByUserID) error {
const query = `
UPDATE refresh_tokens
SET revoked_at = $2
WHERE user_id = $1
AND revoked_at IS NULL`
_, err := conn.Exec(ctx, query, req.UserID, req.RevokedAt)
if err != nil {
return apperr.WrapPostgres(err, "failed to revoke refresh tokens")
}
return nil
}
@@ -0,0 +1,103 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
)
type UsersRepo struct {
pool *pgxpool.Pool
}
func NewUsersRepo(pool *pgxpool.Pool) *UsersRepo {
return &UsersRepo{pool: pool}
}
func (r *UsersRepo) Create(ctx context.Context, req dto.CreateStoredUser) error {
return r.create(ctx, r.pool, req)
}
func (r *UsersRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.CreateStoredUser) error {
return r.create(ctx, tx, req)
}
func (r *UsersRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
return r.getByID(ctx, r.pool, id)
}
func (r *UsersRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.User, error) {
return r.getByID(ctx, tx, id)
}
func (r *UsersRepo) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
const query = `SELECT id, username, name, created_at FROM users WHERE username = $1`
return scanUser(r.pool.QueryRow(ctx, query, username))
}
func (r *UsersRepo) GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error) {
const query = `SELECT id, username, name, created_at, password_hash FROM users WHERE username = $1`
var credentials dto.UserCredentials
err := r.pool.QueryRow(ctx, query, username).Scan(
&credentials.User.ID,
&credentials.User.Username,
&credentials.User.DisplayName,
&credentials.User.CreatedAt,
&credentials.PasswordHash,
)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to get user credentials")
}
return &credentials, nil
}
func (r *UsersRepo) Delete(ctx context.Context, id uuid.UUID) error {
const query = `DELETE FROM users WHERE id = $1`
ct, err := r.pool.Exec(ctx, query, id)
if err != nil {
return apperr.WrapPostgres(err, "failed to delete user")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeNotFound, "user not found")
}
return nil
}
func (r *UsersRepo) create(ctx context.Context, conn postgres.Conn, req dto.CreateStoredUser) error {
const query = `INSERT INTO users (id, username, name, password_hash, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6)`
_, err := conn.Exec(ctx, query, req.ID, req.Username, req.DisplayName, req.PasswordHash, req.CreatedAt, req.UpdatedAt)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
pgErr.Code == pgerrcode.UniqueViolation && pgErr.ConstraintName == "users_username_unique" {
return apperr.Wrap(err, apperr.CodeConflict, "username already exists")
}
return apperr.WrapPostgres(err, "failed to create user")
}
return nil
}
func (r *UsersRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID) (*dto.User, error) {
const query = `SELECT id, username, name, created_at FROM users WHERE id = $1`
return scanUser(conn.QueryRow(ctx, query, id))
}
func scanUser(row pgx.Row) (*dto.User, error) {
var user dto.User
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get user")
}
return &user, nil
}