This commit is contained in:
Vladislav Kunetskiy
2026-11-05 20:21:39 +03:00
parent edc2a405ee
commit 71fbb4b321
129 changed files with 10027 additions and 170 deletions
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/telemetry"
)
// PipelineRepository owns the durable job/outbox/variant state. Queries that
@@ -357,13 +358,15 @@ func insertOutboxTx(
kind string,
availableAt time.Time,
) error {
payload, err := domain.NewJobMessage(domain.Job{
message := domain.NewJobMessage(domain.Job{
ID: job.ID,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Attempt: attempt,
CreatedAt: job.CreatedAt,
}).MarshalPayload()
})
message.Traceparent, message.Tracestate = telemetry.Inject(ctx)
payload, err := message.MarshalPayload()
if err != nil {
return fmt.Errorf("marshal job message: %w", err)
}
@@ -1158,6 +1161,37 @@ func (r *PipelineRepository) ReapExpiredLeases(
return reaped, nil
}
// CountOverdueJobs returns queued/processing jobs older than the TTR objective.
func (r *PipelineRepository) CountOverdueJobs(ctx context.Context, olderThan time.Duration) (int64, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var count int64
if err := r.store.pool.QueryRow(ctx, `
SELECT count(*) FROM attachment_jobs
WHERE status IN ('queued', 'processing')
AND created_at < now() - $1::interval`, intervalString(olderThan)).Scan(&count); err != nil {
return 0, fmt.Errorf("count overdue jobs: %w", mapError(err))
}
return count, nil
}
// OldestActiveJobAge returns the age of the oldest queued/processing job.
// It is intentionally a small read-only query with the standard query timeout.
func (r *PipelineRepository) OldestActiveJobAge(ctx context.Context) (float64, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var seconds float64
if err := r.store.pool.QueryRow(ctx, `
SELECT COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0)
FROM attachment_jobs
WHERE status IN ('queued', 'processing')`).Scan(&seconds); err != nil {
return 0, fmt.Errorf("oldest active job age: %w", mapError(err))
}
return seconds, nil
}
func (r *PipelineRepository) ClaimOutbox(
ctx context.Context,
owner string,
@@ -2022,6 +2056,7 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
ctx context.Context,
olderThan time.Duration,
limit int,
traceparent, tracestate string,
) (int, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
@@ -2031,7 +2066,7 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
SELECT j.job_id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at
FROM attachment_jobs j
WHERE j.status = 'queued'
AND j.available_at < now() - $1::interval
AND j.available_at <= now() - $1::interval
AND NOT EXISTS (
SELECT 1 FROM outbox_messages o
WHERE o.job_id = j.job_id AND o.published_at IS NULL
@@ -2049,10 +2084,15 @@ func (r *PipelineRepository) ReconcileQueuedJobs(
'attachment_id', attachment_id,
'pipeline_version', pipeline_version,
'attempt', attempt,
'created_at', created_at),
'created_at', created_at)
|| CASE
WHEN $4::text = '' THEN '{}'::jsonb
WHEN COALESCE($5::text, '') = '' THEN jsonb_build_object('traceparent', $4::text)
ELSE jsonb_build_object('traceparent', $4::text, 'tracestate', $5::text)
END,
now()
FROM lost`,
intervalString(olderThan), limit, defaultRoutingKey)
intervalString(olderThan), limit, defaultRoutingKey, traceparent, tracestate)
if err != nil {
return 0, fmt.Errorf("reconcile queued jobs: %w", mapError(err))
}
@@ -518,7 +518,7 @@ func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
s.Require().Len(claimed, 1)
s.Require().NoError(repo.MarkPublished(s.T().Context(), []int64{claimed[0].ID}))
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10)
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10, "", "")
s.Require().NoError(err)
s.Equal(1, reconciled)
@@ -23,7 +23,7 @@ func (r *SessionRepository) Credentials(ctx context.Context, username string) (d
row, err := r.store.queries.GetUserByUsername(ctx, username)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.UserCredentials{}, fmt.Errorf("%w: username %q", domain.ErrUnauthenticated, username)
return domain.UserCredentials{}, fmt.Errorf("%w", domain.ErrUnauthenticated)
}
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
+30 -2
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi-messenger/internal/config"
@@ -24,7 +25,25 @@ type Store struct {
pipeline *PipelineRepository
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
type options struct {
queryTracer pgx.QueryTracer
}
// Option customizes the PostgreSQL store without leaking telemetry into the
// storage package's public API.
type Option func(*options)
// WithQueryTracer installs a pgx tracer (nil means no tracing).
func WithQueryTracer(tracer pgx.QueryTracer) Option {
return func(o *options) { o.queryTracer = tracer }
}
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration, opts ...Option) (*Store, error) {
options := options{}
for _, opt := range opts {
opt(&options)
}
cfg, err := normalize(cfg)
if err != nil {
return nil, fmt.Errorf("normalize database config: %w", err)
@@ -40,6 +59,9 @@ func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration)
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
if options.queryTracer != nil {
poolCfg.ConnConfig.Tracer = options.queryTracer
}
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
@@ -82,13 +104,19 @@ func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
func (s *Store) Ping(ctx context.Context) error {
if err := s.pool.Ping(ctx); err != nil {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err := s.pool.Ping(pingCtx); err != nil {
return fmt.Errorf("ping database: %w", err)
}
return nil
}
// PoolStats exposes a point-in-time pgxpool snapshot for telemetry callbacks.
func (s *Store) PoolStats() *pgxpool.Stat { return s.pool.Stat() }
func (s *Store) Close() { s.pool.Close() }
// sweepLockKey is a process-independent constant: every replica contends for the