Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ

This commit is contained in:
2026-11-16 12:36:59 +03:00
parent b323f2dab9
commit d761861def
54 changed files with 5061 additions and 102 deletions
+99
View File
@@ -0,0 +1,99 @@
// 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
}
dbConfig, err := config.LoadMigrate(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.Endpoint, s3Config.Region, s3Config.Bucket, s3Config.AccessKey, s3Config.SecretKey)
if err != nil {
fmt.Fprintln(errOut, "configuration error:", err)
return 2
}
db, err := postgres.NewPool(ctx, dbConfig.DatabaseURL, 10)
if err != nil {
fmt.Fprintln(errOut, "reconcile:", err)
return 1
}
defer db.Close()
r, err := attachment.NewReconciler(db, blobs, *grace)
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
stats, runErr := r.Run(scanCtx, *apply, *deep, 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
}
+30
View File
@@ -0,0 +1,30 @@
package main
import (
"context"
"fmt"
"messenger/internal/platform/config"
"messenger/internal/platform/s3store"
"os"
"time"
)
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.Endpoint, cfg.Region, cfg.Bucket, cfg.AccessKey, cfg.SecretKey)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
return s.Bootstrap(ctx)
}
+46
View File
@@ -17,10 +17,12 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/app"
"messenger/internal/attachment"
"messenger/internal/chat"
"messenger/internal/platform/config"
"messenger/internal/platform/ident"
"messenger/internal/platform/postgres"
"messenger/internal/platform/s3store"
"messenger/internal/platform/valkey"
"messenger/internal/server"
)
@@ -59,6 +61,26 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
return err
}
defer sessions.Close()
var blobs attachment.Blobs
var reconciler *attachment.Reconciler
if cfg.S3.Endpoint != "" {
blobs, err = s3store.New(cfg.S3.Endpoint, cfg.S3.Region, cfg.S3.Bucket, cfg.S3.AccessKey, cfg.S3.SecretKey)
if err != nil {
return err
}
reconCfg, e := config.LoadS3(config.ReconcileS3(os.LookupEnv))
if e != nil {
return e
}
reconBlobs, e := s3store.New(reconCfg.Endpoint, reconCfg.Region, reconCfg.Bucket, reconCfg.AccessKey, reconCfg.SecretKey)
if e != nil {
return e
}
reconciler, err = attachment.NewReconciler(pool, reconBlobs, time.Hour)
if err != nil {
return err
}
}
ln, err := net.Listen("tcp", cfg.Addr())
if err != nil {
@@ -77,6 +99,9 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
MaxBodyBytes: cfg.MaxBodyBytes,
InstanceID: alias,
IdempotencyTTL: cfg.IdempotencyTTL,
Blobs: blobs,
MaxUploadBytes: cfg.S3.MaxBytes,
MaxImagePixels: cfg.S3.MaxPixels,
})
var debugLn net.Listener
if cfg.DebugAddr != "" {
@@ -89,6 +114,27 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
ctx, cancel := context.WithCancel(ctx)
var background sync.WaitGroup
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, true, false, 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 {