Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
// Command migrate applies the embedded schema migrations once and exits, so
|
||||
// the API replicas never race each other over the schema.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// poolSize covers the goose session lock and the migration itself.
|
||||
const poolSize = 2
|
||||
|
||||
func main() {
|
||||
cfg, err := config.LoadMigrate(os.LookupEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
log := cfg.NewLogger()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
if err := run(ctx, log, cfg); err != nil {
|
||||
log.Error("migration failed", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(ctx context.Context, log *slog.Logger, cfg config.Migrate) error {
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, poolSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
applied, err := postgres.Migrate(ctx, pool)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("migrations applied", "applied_migrations", applied)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Command reconcile reports attachment inconsistencies as JSON lines. Mutations
|
||||
// require --apply; --deep also streams referenced objects to verify SHA256.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/platform/s3store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
code := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
|
||||
stop()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func run(ctx context.Context, args []string, out, errOut io.Writer) int {
|
||||
flags := flag.NewFlagSet("reconcile", flag.ContinueOnError)
|
||||
flags.SetOutput(errOut)
|
||||
apply := flags.Bool("apply", false, "apply repairs (default: read-only dry run)")
|
||||
deep := flags.Bool("deep", false, "stream referenced objects and verify SHA256 and size")
|
||||
grace := flags.Duration("grace", time.Hour, "minimum file/object age; must be at least 2m")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
if flags.NArg() != 0 || *grace < 2*time.Minute {
|
||||
fmt.Fprintln(errOut, "reconcile: no positional arguments allowed; --grace must be at least 2m")
|
||||
return 2
|
||||
}
|
||||
databaseURL, err := config.LoadDatabaseURL(os.LookupEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(errOut, "configuration error:", err)
|
||||
return 2
|
||||
}
|
||||
// Compose mounts the reconciler identity at the standard credential paths.
|
||||
s3Config, err := config.LoadS3(os.LookupEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(errOut, "configuration error:", err)
|
||||
return 2
|
||||
}
|
||||
blobs, err := s3store.New(s3Config)
|
||||
if err != nil {
|
||||
fmt.Fprintln(errOut, "configuration error:", err)
|
||||
return 2
|
||||
}
|
||||
db, err := postgres.NewPool(ctx, databaseURL, 10)
|
||||
if err != nil {
|
||||
fmt.Fprintln(errOut, "reconcile:", err)
|
||||
return 1
|
||||
}
|
||||
defer db.Close()
|
||||
r, err := attachment.NewReconcilerWithRetention(db, blobs, *grace, s3Config.StagingRetention)
|
||||
if err != nil {
|
||||
fmt.Fprintln(errOut, "reconcile:", err)
|
||||
return 2
|
||||
}
|
||||
// A broken output stream cancels the scan so repairs cannot continue after
|
||||
// the caller loses the audit trail. Print partial statistics on scan errors.
|
||||
scanCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
encoder := json.NewEncoder(out)
|
||||
var outputErr error
|
||||
options := attachment.ReconcileOptions{Apply: *apply, Deep: *deep}
|
||||
stats, runErr := r.Run(scanCtx, options, func(f attachment.Finding) {
|
||||
if outputErr == nil {
|
||||
outputErr = encoder.Encode(f)
|
||||
if outputErr != nil {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
})
|
||||
if outputErr == nil {
|
||||
outputErr = encoder.Encode(stats)
|
||||
}
|
||||
if outputErr != nil {
|
||||
fmt.Fprintln(errOut, "reconcile output:", outputErr)
|
||||
return 1
|
||||
}
|
||||
if runErr != nil {
|
||||
fmt.Fprintln(errOut, "reconcile:", runErr)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReconcileDoesNotValidateUnusedLogging(t *testing.T) {
|
||||
for key, value := range map[string]string{
|
||||
"DATABASE_URL_FILE": "postgres://test:test@127.0.0.1:5432/messenger?sslmode=disable",
|
||||
"S3_ACCESS_KEY_ID_FILE": "test-access",
|
||||
"S3_SECRET_ACCESS_KEY_FILE": "test-secret",
|
||||
} {
|
||||
path := filepath.Join(t.TempDir(), key)
|
||||
if err := os.WriteFile(path, []byte(value), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv(key, path)
|
||||
}
|
||||
t.Setenv("S3_ENDPOINT", "http://127.0.0.1:8333")
|
||||
t.Setenv("S3_REGION", "us-east-1")
|
||||
t.Setenv("S3_BUCKET", "attachments")
|
||||
t.Setenv("APP_LOG_LEVEL", "not-a-log-level")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // Stop before dialing: only configuration relevant to this CLI is checked.
|
||||
var out, errOut bytes.Buffer
|
||||
code := run(ctx, nil, &out, &errOut)
|
||||
if code != 1 || strings.Contains(errOut.String(), "APP_LOG_LEVEL") {
|
||||
t.Fatalf("unused logging prevented the database operation: code=%d error=%s", code, errOut.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/platform/s3store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "bucket bootstrap failed:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
cfg, err := config.LoadS3(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := s3store.New(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
return s.Bootstrap(ctx)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Command server starts the messenger API over PostgreSQL, Valkey and S3.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"expvar"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/app"
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/pipeline"
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/platform/s3store"
|
||||
"messenger/internal/platform/telemetry"
|
||||
"messenger/internal/platform/valkey"
|
||||
"messenger/internal/processing"
|
||||
"messenger/internal/server"
|
||||
)
|
||||
|
||||
const keyCleanupEvery = 10 * time.Minute
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load(os.LookupEnv)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "configuration error:", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
alias := ident.NewAlias()
|
||||
log := cfg.NewLogger().With("instance", alias)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
if err := run(ctx, log, cfg, alias); err != nil {
|
||||
log.Error("server stopped with error", "error", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// run connects the dependencies before it listens, so the port accepts
|
||||
// connections only once they answer.
|
||||
func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string) error {
|
||||
shutdown, err := telemetry.Start(ctx, "messenger-api")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer shutdown()
|
||||
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL, cfg.DBMaxConns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := telemetry.ObservePool(pool); err != nil {
|
||||
return err
|
||||
}
|
||||
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sessions.Close()
|
||||
blobs, reconciler, err := newAttachmentStorage(pool, cfg.S3, os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ln, err := net.Listen("tcp", cfg.Addr())
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen on %s: %w", cfg.Addr(), err)
|
||||
}
|
||||
defer ln.Close()
|
||||
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(),
|
||||
"gomaxprocs", runtime.GOMAXPROCS(0), "db_max_conns", cfg.DBMaxConns,
|
||||
"drain_delay", cfg.DrainDelay.String(), "shutdown_timeout", cfg.ShutdownTimeout.String(),
|
||||
"session_ttl", cfg.SessionTTL.String(), "idempotency_ttl", cfg.IdempotencyTTL.String())
|
||||
a := app.New(app.Deps{
|
||||
Log: log,
|
||||
DB: pool,
|
||||
Sessions: sessions,
|
||||
SessionTTL: cfg.SessionTTL,
|
||||
MaxBodyBytes: cfg.MaxBodyBytes,
|
||||
InstanceID: alias,
|
||||
IdempotencyTTL: cfg.IdempotencyTTL,
|
||||
Blobs: blobs,
|
||||
AttachmentsCfg: attachment.Config{
|
||||
BarrierDir: os.Getenv("LAB5_BARRIERS"),
|
||||
MaxBytes: cfg.S3.MaxBytes,
|
||||
MaxPixels: cfg.S3.MaxPixels,
|
||||
},
|
||||
})
|
||||
var jobs config.Jobs
|
||||
var barrier func(context.Context, pipeline.Job, string) error
|
||||
if dir := os.Getenv("LAB5_BARRIERS"); dir != "" {
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
barrier = processing.FileBarrier(dir)
|
||||
}
|
||||
if blobs != nil {
|
||||
deadline := 5 * time.Second
|
||||
if raw, ok := os.LookupEnv("READY_DEADLINE"); ok {
|
||||
deadline, err = time.ParseDuration(raw)
|
||||
if err != nil || deadline <= 0 {
|
||||
return fmt.Errorf("READY_DEADLINE must be a positive duration")
|
||||
}
|
||||
}
|
||||
if err := pipeline.NewStore(pool).RegisterMetrics(deadline); err != nil {
|
||||
return err
|
||||
}
|
||||
jobs, err = config.LoadJobs(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var debugLn net.Listener
|
||||
if cfg.DebugAddr != "" {
|
||||
if debugLn, err = net.Listen("tcp", cfg.DebugAddr); err != nil {
|
||||
return fmt.Errorf("listen on %s: %w", cfg.DebugAddr, err)
|
||||
}
|
||||
publishDebugVars(alias, pool)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
var background sync.WaitGroup
|
||||
if blobs != nil {
|
||||
background.Go(func() { processing.Dispatch(ctx, log, pipeline.NewStore(pool), jobs, barrier) })
|
||||
}
|
||||
background.Go(func() { chat.RunKeyCleanup(ctx, log, a.Chats, keyCleanupEvery) })
|
||||
if reconciler != nil {
|
||||
background.Go(func() {
|
||||
ticker := time.NewTicker(10 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
scan, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
stats, err := reconciler.Run(scan, attachment.ReconcileOptions{Apply: true}, nil)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Warn("attachment cleanup incomplete", "error", err)
|
||||
} else {
|
||||
log.Info("attachment cleanup", "scanned_files", stats.ScannedFiles, "repaired", stats.Repaired)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
if debugLn != nil {
|
||||
background.Go(func() {
|
||||
if err := server.RunDebug(ctx, log, debugLn, expvar.Handler()); err != nil {
|
||||
log.Error("debug listener stopped", "error", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
err = server.Run(ctx, log, ln, a.Engine, a.Health, cfg.DrainDelay, cfg.ShutdownTimeout)
|
||||
cancel()
|
||||
background.Wait()
|
||||
return err
|
||||
}
|
||||
|
||||
func newAttachmentStorage(pool *pgxpool.Pool, cfg config.S3, lookup config.Lookup) (attachment.Blobs, *attachment.Reconciler, error) {
|
||||
if cfg.Endpoint == "" {
|
||||
return nil, nil, nil
|
||||
}
|
||||
blobs, err := s3store.New(cfg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
reconCfg, err := config.LoadS3(config.ReconcileS3(lookup))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
reconBlobs, err := s3store.New(reconCfg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
reconciler, err := attachment.NewReconcilerWithRetention(pool, reconBlobs, time.Hour, reconCfg.StagingRetention)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return blobs, reconciler, nil
|
||||
}
|
||||
|
||||
// publishDebugVars adds to expvar what the load tests read from a replica.
|
||||
func publishDebugVars(alias string, pool *pgxpool.Pool) {
|
||||
expvar.NewString("instance").Set(alias)
|
||||
expvar.Publish("gomaxprocs", expvar.Func(func() any { return runtime.GOMAXPROCS(0) }))
|
||||
expvar.Publish("pgxpool", expvar.Func(func() any {
|
||||
s := pool.Stat()
|
||||
return map[string]any{
|
||||
"acquire_count": s.AcquireCount(),
|
||||
"acquire_duration_ms": s.AcquireDuration().Milliseconds(),
|
||||
"acquired_conns": s.AcquiredConns(),
|
||||
"idle_conns": s.IdleConns(),
|
||||
"total_conns": s.TotalConns(),
|
||||
"max_conns": s.MaxConns(),
|
||||
"empty_acquire_count": s.EmptyAcquireCount(),
|
||||
"empty_acquire_wait_ms": s.EmptyAcquireWaitTime().Milliseconds(),
|
||||
"canceled_acquire_count": s.CanceledAcquireCount(),
|
||||
"new_conns_count": s.NewConnsCount(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
var (
|
||||
db *testenv.DB
|
||||
kv *testenv.KV
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
var err error
|
||||
if db, err = testenv.StartPostgres(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if kv, err = testenv.StartValkey(ctx); err != nil {
|
||||
db.Close()
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
kv.Close()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// A start-up failure after the background work began must still end the
|
||||
// process with an error, not leave it waiting for a signal.
|
||||
func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
|
||||
if err := runWithBusyDebugAddr(t, 0); err == nil {
|
||||
t.Fatal("run succeeded on a busy debug address")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedStartReleasesTheAPIPort(t *testing.T) {
|
||||
probe, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := probe.Addr().(*net.TCPAddr).Port
|
||||
probe.Close()
|
||||
|
||||
if err := runWithBusyDebugAddr(t, port); err == nil {
|
||||
t.Fatal("run succeeded on a busy debug address")
|
||||
}
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
t.Fatalf("the API port is still taken after the failed start: %v", err)
|
||||
}
|
||||
ln.Close()
|
||||
}
|
||||
|
||||
func runWithBusyDebugAddr(t *testing.T, port int) error {
|
||||
t.Helper()
|
||||
busy, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer busy.Close()
|
||||
cfg := config.Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: port,
|
||||
ShutdownTimeout: time.Second,
|
||||
MaxBodyBytes: 1024,
|
||||
DatabaseURL: db.DSN,
|
||||
SessionStoreURL: kv.URL,
|
||||
SessionTTL: time.Hour,
|
||||
IdempotencyTTL: time.Hour,
|
||||
DBMaxConns: 2,
|
||||
DebugAddr: busy.Addr().String(),
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- run(context.Background(), slog.New(slog.NewTextHandler(io.Discard, nil)), cfg, "alias")
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("run hung instead of returning the listen error")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Command worker runs image consumers or an explicit operator action.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/attachment"
|
||||
"messenger/internal/broker"
|
||||
"messenger/internal/imaging"
|
||||
"messenger/internal/pipeline"
|
||||
"messenger/internal/platform/config"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/platform/s3store"
|
||||
"messenger/internal/platform/telemetry"
|
||||
"messenger/internal/processing"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
if err := run(ctx, os.Args[1:]); err != nil {
|
||||
slog.Error("worker stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
const usage = "use failed, replay <id> <operator>, reprocess <id> <version>, or duplicate <id> <version> <attempt>"
|
||||
|
||||
type command struct {
|
||||
name, actor, barrierDir string
|
||||
id uuid.UUID
|
||||
version, attempt int
|
||||
}
|
||||
|
||||
func parseCommand(args []string) (command, error) {
|
||||
var c command
|
||||
if len(args) == 0 {
|
||||
return c, nil
|
||||
}
|
||||
if dir, ok := strings.CutPrefix(args[0], "--barriers="); ok && len(args) == 1 && dir != "" {
|
||||
c.barrierDir = dir
|
||||
return c, nil
|
||||
}
|
||||
c.name = args[0]
|
||||
switch c.name {
|
||||
case "--prepare-large-png", "failed":
|
||||
if len(args) == 1 {
|
||||
return c, nil
|
||||
}
|
||||
return c, errors.New(usage)
|
||||
case "replay", "reprocess":
|
||||
if len(args) != 3 {
|
||||
return c, errors.New(usage)
|
||||
}
|
||||
case "duplicate":
|
||||
if len(args) != 4 {
|
||||
return c, errors.New(usage)
|
||||
}
|
||||
default:
|
||||
return c, errors.New(usage)
|
||||
}
|
||||
var err error
|
||||
c.id, err = uuid.Parse(args[1])
|
||||
if err != nil {
|
||||
return c, errors.New("invalid attachment UUID")
|
||||
}
|
||||
if c.name == "replay" {
|
||||
c.actor = strings.TrimSpace(args[2])
|
||||
if c.actor == "" || len(c.actor) > 128 {
|
||||
return c, errors.New("replay requires an operator name of up to 128 bytes")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
c.version, err = strconv.Atoi(args[2])
|
||||
if err != nil || c.version < 1 {
|
||||
return c, errors.New("invalid pipeline version")
|
||||
}
|
||||
if c.name == "duplicate" {
|
||||
c.attempt, err = strconv.Atoi(args[3])
|
||||
if err != nil || c.attempt < 1 {
|
||||
return c, errors.New("invalid attempt number")
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, args []string) error {
|
||||
cmd, err := parseCommand(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.name == "--prepare-large-png" {
|
||||
return imaging.PrepareLargePNG(os.Stdin)
|
||||
}
|
||||
if cmd.name == "" {
|
||||
shutdown, err := telemetry.Start(ctx, "messenger-worker")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer shutdown()
|
||||
} else {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
}
|
||||
db, err := config.LoadDatabaseURL(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, db, 5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
store := pipeline.NewStore(pool)
|
||||
switch cmd.name {
|
||||
case "failed":
|
||||
jobs, err := store.Failed(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(os.Stdout).Encode(jobs)
|
||||
case "duplicate":
|
||||
url, err := config.LoadBrokerURL(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return duplicate(ctx, pool, url, cmd.id, cmd.version, cmd.attempt)
|
||||
}
|
||||
s3, err := config.LoadS3(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
blobs, err := s3store.New(s3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
exists := func(ctx context.Context, key string) (bool, error) {
|
||||
_, err := blobs.Stat(ctx, key)
|
||||
if errors.Is(err, attachment.ErrObjectMissing) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
switch cmd.name {
|
||||
case "replay":
|
||||
return store.Replay(ctx, cmd.id, cmd.actor, exists)
|
||||
case "reprocess":
|
||||
return store.Reprocess(ctx, cmd.id, cmd.version, exists)
|
||||
}
|
||||
if err := telemetry.ObservePool(pool); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := config.LoadJobs(os.LookupEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := processing.Worker{Store: store, Blobs: blobs, Config: cfg, Log: slog.Default()}
|
||||
if cmd.barrierDir != "" {
|
||||
if err := os.MkdirAll(cmd.barrierDir, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Checkpoint = processing.FileBarrier(cmd.barrierDir)
|
||||
}
|
||||
if err := imaging.CleanScratch(); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Run(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// duplicate sends a previously issued envelope through the actual broker. It
|
||||
// cannot change SQL state or manufacture a future attempt.
|
||||
func duplicate(ctx context.Context, pool *pgxpool.Pool, url string, id uuid.UUID, version, attempt int) error {
|
||||
j := pipeline.Job{SchemaVersion: 1, Type: "attachment.process.v1", AttachmentID: id, PipelineVersion: version, Attempt: attempt}
|
||||
err := pool.QueryRow(ctx, `SELECT job_id,created_at FROM attachment_jobs
|
||||
WHERE attachment_id=$1 AND pipeline_version=$2 AND $3::integer BETWEEN 1 AND attempt`, id, version, attempt).Scan(&j.JobID, &j.CreatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p, err := broker.NewPublisher(ctx, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer p.Close()
|
||||
body, err := json.Marshal(j)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Publish(ctx, body)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
func TestInvalidCommandBeforeConfig(t *testing.T) {
|
||||
t.Setenv("DATABASE_URL_FILE", "")
|
||||
for _, args := range [][]string{{"unknown"}, {"replay", "bad-id", "admin"}, {"duplicate", "00000000-0000-4000-8000-000000000001", "1", "invalid"}} {
|
||||
err := run(t.Context(), args)
|
||||
if err == nil || strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Errorf("run(%q) must report argument error, got %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedNeedsOnlyPostgres(t *testing.T) {
|
||||
db, err := testenv.StartPostgres(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
path := filepath.Join(t.TempDir(), "dsn")
|
||||
if err := os.WriteFile(path, []byte(db.DSN), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
t.Setenv("BROKER_URL_FILE", "missing-broker")
|
||||
t.Setenv("S3_ENDPOINT", "invalid")
|
||||
t.Setenv("S3_SECRET_ACCESS_KEY_FILE", "")
|
||||
if err := run(t.Context(), []string{"failed"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user