forked from mtusi2026/mtusi2026lab4
Prepare verified laboratory 4 implementation and evidence
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"backend/db"
|
||||
"backend/internal/adapter/handler"
|
||||
"backend/internal/adapter/password"
|
||||
"backend/internal/adapter/repository/postgres"
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/application/usecase"
|
||||
"backend/internal/config"
|
||||
"backend/pkg/logger"
|
||||
"backend/pkg/server"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func main() {
|
||||
healthcheck := flag.Bool("healthcheck", false, "проверить /health/ready и выйти (для Docker HEALTHCHECK)")
|
||||
migrate := flag.Bool("migrate", false, "apply migrations and exit")
|
||||
bootstrapS3 := flag.Bool("bootstrap-s3", false, "initialize private bucket and application IAM credentials")
|
||||
reconcile := flag.Bool("reconcile", false, "reconcile at most 100 metadata rows and 100 objects; dry-run by default")
|
||||
apply := flag.Bool("apply", false, "apply safe reconciliation changes")
|
||||
grace := flag.Duration("grace", 10*time.Minute, "minimum safe object age, at least 60 seconds")
|
||||
after := flag.String("after", "", "metadata UUID cursor")
|
||||
objectAfter := flag.String("object-after", "", "object key cursor")
|
||||
flag.Parse()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "config:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *healthcheck {
|
||||
os.Exit(probe(cfg.Port))
|
||||
}
|
||||
|
||||
log := logger.New(cfg.LogLevel)
|
||||
dsn, err := config.ReadSecret(cfg.DatabaseURLFile)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database secret unavailable")
|
||||
}
|
||||
if *migrate {
|
||||
if err = db.Migrate(context.Background(), dsn); err != nil {
|
||||
log.Fatal().Err(err).Msg("migration failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
s3config, err := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if err != nil {
|
||||
log.Fatal().Msg("S3 application credentials unavailable")
|
||||
}
|
||||
objects, err := storage.FromConfig(s3config)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid S3 endpoint")
|
||||
}
|
||||
if *bootstrapS3 {
|
||||
root, e := storage.ReadConfig("/run/secrets/s3_root")
|
||||
if e != nil {
|
||||
log.Fatal().Msg("S3 bootstrap credentials unavailable")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if e = storage.Bootstrap(ctx, root, s3config); e != nil {
|
||||
log.Fatal().Err(e).Msg("S3 bootstrap failed")
|
||||
}
|
||||
return
|
||||
}
|
||||
pc, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid database configuration")
|
||||
}
|
||||
pc.MaxConns = cfg.MaxConns
|
||||
pc.MinConns = 0
|
||||
pc.ConnConfig.ConnectTimeout = time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
||||
pc.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), pc)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("database initialization failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
var cache *redis.Client
|
||||
if url, e := config.ReadSecret(cfg.CacheURLFile); e == nil {
|
||||
opts, e := redis.ParseURL(url)
|
||||
if e != nil {
|
||||
log.Fatal().Msg("invalid cache configuration")
|
||||
}
|
||||
opts.MaxRetries = 0
|
||||
opts.DialTimeout = 80 * time.Millisecond
|
||||
opts.ReadTimeout = 80 * time.Millisecond
|
||||
opts.WriteTimeout = 80 * time.Millisecond
|
||||
cache = redis.NewClient(opts)
|
||||
defer func() { _ = cache.Close() }()
|
||||
}
|
||||
store := postgres.New(pool, cache)
|
||||
if *reconcile {
|
||||
cursor := uuid.Nil
|
||||
if *after != "" {
|
||||
cursor, err = uuid.Parse(*after)
|
||||
if err != nil {
|
||||
log.Fatal().Msg("invalid metadata cursor")
|
||||
}
|
||||
}
|
||||
if len(*objectAfter) > 64 {
|
||||
log.Fatal().Msg("object cursor too long")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
report, e := usecase.NewReconciler(store, objects, time.Now).Run(ctx, cursor, *objectAfter, *grace, *apply)
|
||||
if err = json.NewEncoder(os.Stdout).Encode(report); err != nil {
|
||||
log.Fatal().Msg("reconciliation report write failed")
|
||||
}
|
||||
if e != nil {
|
||||
log.Fatal().Err(e).Msg("reconciliation incomplete")
|
||||
}
|
||||
return
|
||||
}
|
||||
app := usecase.NewMessenger(store)
|
||||
auth := usecase.NewAuth(store, password.New(), app, time.Duration(cfg.SessionTTLSeconds)*time.Second, time.Now)
|
||||
attachments := usecase.NewAttachments(store, app, objects)
|
||||
probeDependencies := func(ctx context.Context) error {
|
||||
if e := pool.Ping(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
return objects.Ready(ctx)
|
||||
}
|
||||
h := handler.New(app, auth, attachments, probeDependencies, handler.Limits{
|
||||
MaxBodyBytes: cfg.MaxBodyBytes,
|
||||
MaxInflight: cfg.MaxInflight,
|
||||
MaxQueue: cfg.MaxQueue,
|
||||
QueueTimeout: cfg.QueueTimeout,
|
||||
}, func() any {
|
||||
return map[string]any{"pool_total": pool.Stat().TotalConns(), "pool_acquired": pool.Stat().AcquiredConns(), "pool_max": pool.Stat().MaxConns()}
|
||||
}, &log)
|
||||
srv := server.New(cfg.Addr(), h.Router())
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
serveErr := make(chan error, 1)
|
||||
go func() { serveErr <- srv.ListenAndServe() }()
|
||||
log.Info().Str("addr", cfg.Addr()).Str("env", cfg.Env).
|
||||
Int("max_inflight", cfg.MaxInflight).
|
||||
Int("max_queue", cfg.MaxQueue).Msg("server started")
|
||||
|
||||
select {
|
||||
case err := <-serveErr:
|
||||
log.Fatal().Err(err).Msg("server failed")
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
log.Info().Dur("timeout", cfg.ShutdownTimeout).Msg("shutdown signal received, draining")
|
||||
h.Drain()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Error().Err(err).Msg("shutdown timed out, open requests aborted")
|
||||
}
|
||||
if err := <-serveErr; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error().Err(err).Msg("server error")
|
||||
}
|
||||
log.Info().Dur("took", time.Since(started)).Msg("shutdown complete")
|
||||
}
|
||||
|
||||
// probe — healthcheck без curl в образе distroless: сам бинарник ходит в
|
||||
// /health/ready и возвращает код выхода для Docker.
|
||||
func probe(port int) int {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
resp, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d/health/ready", port))
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// An explicit test-only tool, never called by the HTTP server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/adapter/storage"
|
||||
"backend/internal/config"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"os"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if e := run(); e != nil {
|
||||
fmt.Fprintln(os.Stderr, "fixture cleanup failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
if len(os.Args) != 2 || !regexp.MustCompile(`^st_[a-f0-9]{16}$`).MatchString(os.Args[1]) {
|
||||
return fmt.Errorf("explicit synthetic fixture prefix required")
|
||||
}
|
||||
prefix := os.Args[1]
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
dsn, e := config.ReadSecret("/run/secrets/database_url")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer pool.Close()
|
||||
credentials, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
objects, e := storage.FromConfig(credentials)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
rows, e := pool.Query(ctx, `SELECT a.id FROM attachments a JOIN users u ON u.id=a.owner_id WHERE left(u.username,19)=$1 LIMIT 1001`, prefix)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ids := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return e
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
if e = rows.Err(); e != nil {
|
||||
return e
|
||||
}
|
||||
if len(ids) > 1000 {
|
||||
return fmt.Errorf("cleanup bound exceeded")
|
||||
}
|
||||
tx, e := pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
_, e = tx.Exec(ctx, `CREATE TEMP TABLE own_users ON COMMIT DROP AS SELECT id FROM users WHERE left(username,19)=$1`, prefix)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
statements := []string{
|
||||
`DO $$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $$`,
|
||||
`CREATE TEMP TABLE own_chats ON COMMIT DROP AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users))`,
|
||||
`DELETE FROM message_attachments WHERE message_id IN (SELECT id FROM messages WHERE sender_id IN (SELECT id FROM own_users))`,
|
||||
`DELETE FROM idempotency WHERE user_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM attachments WHERE owner_id IN (SELECT id FROM own_users)`,
|
||||
`DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats)`,
|
||||
`DELETE FROM chats WHERE id IN (SELECT id FROM own_chats)`,
|
||||
`DELETE FROM users WHERE id IN (SELECT id FROM own_users)`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if _, e = tx.Exec(ctx, statement); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
// Delete bytes only after confirmed metadata deletion. Failed/uncertain SQL leaves originals intact;
|
||||
// a failed S3 delete leaves an inaccessible orphan for the grace-protected reconciler.
|
||||
for _, id := range ids {
|
||||
if e = objects.Remove(ctx, "originals/"+id.String()); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user