This commit is contained in:
+129
@@ -0,0 +1,129 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
const shutdownTimeout = 8 * time.Second
|
||||
|
||||
func main() {
|
||||
shutdownTelemetry, telemetryErr := observability.Init(context.Background(), "messenger-api")
|
||||
if telemetryErr != nil {
|
||||
log.Fatal("telemetry configuration failed")
|
||||
}
|
||||
defer shutdownTelemetry()
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
poolConfig, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid PostgreSQL config")
|
||||
}
|
||||
poolConfig.ConnConfig.Host = cfg.PostgresHost
|
||||
poolConfig.ConnConfig.Port = cfg.PostgresPort
|
||||
poolConfig.ConnConfig.User = cfg.PostgresUser
|
||||
poolConfig.ConnConfig.Database = cfg.PostgresDatabase
|
||||
poolConfig.ConnConfig.Password = cfg.PostgresPassword
|
||||
poolConfig.ConnConfig.ConnectTimeout = cfg.QueryTimeout
|
||||
poolConfig.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprint(cfg.QueryTimeout.Milliseconds())
|
||||
poolConfig.ConnConfig.Tracer = observability.DBTracer{}
|
||||
poolConfig.MaxConns = cfg.PostgresMaxConns
|
||||
poolConfig.MinConns = 1
|
||||
poolConfig.MaxConnLifetime = time.Hour
|
||||
poolConfig.MaxConnIdleTime = 5 * time.Minute
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
log.Fatal("cannot create PostgreSQL pool")
|
||||
}
|
||||
defer pool.Close()
|
||||
observability.ObservePool(pool, 0)
|
||||
redisOptions, err := cfg.RedisOptions()
|
||||
if err != nil {
|
||||
log.Fatal("invalid Redis TLS configuration")
|
||||
}
|
||||
redisClient := redis.NewClient(redisOptions)
|
||||
defer redisClient.Close()
|
||||
repo := postgres.New(pool, cfg.QueryTimeout)
|
||||
sessions := session.NewRedis(redisClient, cfg.QueryTimeout)
|
||||
useCase := chatusecase.New(repo, sessions, cfg.SessionTTL)
|
||||
objectStore, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("invalid S3 config")
|
||||
}
|
||||
options, err := attachment.LoadOptions()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
attachments := attachment.NewAsync(pool, objectStore, options)
|
||||
background, stopPublisher := context.WithCancel(context.Background())
|
||||
defer stopPublisher()
|
||||
go attachments.RunPublisher(background, redisClient)
|
||||
handler := chat.NewChat(useCase, cfg.CursorKey).WithAttachments(attachments).WithLoginLimit(sessions.LoginAllowed)
|
||||
port := cfg.Port
|
||||
e := handler.Router()
|
||||
e.Server.ReadHeaderTimeout = 5 * time.Second
|
||||
e.Server.MaxHeaderBytes = 16 << 10
|
||||
e.Server.ReadTimeout = 50 * time.Second
|
||||
e.Server.WriteTimeout = 55 * time.Second
|
||||
e.Server.IdleTimeout = 60 * time.Second
|
||||
|
||||
e.Server.TLSConfig, err = trust.Server("/trust/ca.crt", "/identity/tls.crt", "/identity/tls.key", "gateway", "/trust/revoked")
|
||||
if err != nil {
|
||||
log.Fatal("invalid API TLS configuration")
|
||||
}
|
||||
e.Server.TLSConfig.NextProtos = []string{"http/1.1"}
|
||||
e.Server.Addr = ":" + port
|
||||
serverErrors := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("HTTP server is listening on :%s", port)
|
||||
serverErrors <- e.Server.ListenAndServeTLS("", "")
|
||||
}()
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||
select {
|
||||
case sig := <-stop:
|
||||
log.Printf("received %s, shutting down", sig)
|
||||
case err := <-serverErrors:
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("HTTP server failed: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
handler.Drain()
|
||||
// Allow two 1-second LB checks to remove this backend before closing the listener.
|
||||
time.Sleep(3 * time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := e.Shutdown(ctx); err != nil {
|
||||
log.Printf("graceful shutdown failed: %v", err)
|
||||
if closeErr := e.Close(); closeErr != nil {
|
||||
log.Printf("forced shutdown failed: %v", closeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Printf("shutdown complete")
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "apply safe repairs; default dry-run")
|
||||
grace := flag.Duration("grace", 2*time.Minute, "minimum object/metadata age (at least 90s)")
|
||||
timeout := flag.Duration("timeout", 10*time.Minute, "whole scan deadline")
|
||||
flag.Parse()
|
||||
if *grace < attachment.MinimumGrace {
|
||||
log.Fatal("grace must be at least 90s")
|
||||
}
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
pc, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid DB config")
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pc.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
pc.MaxConns = 2
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pc)
|
||||
if err != nil {
|
||||
log.Fatal("cannot create DB pool")
|
||||
}
|
||||
defer pool.Close()
|
||||
store, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("invalid S3 config")
|
||||
}
|
||||
result, err := attachment.New(pool, store).Reconcile(ctx, *apply, *grace)
|
||||
_ = json.NewEncoder(os.Stdout).Encode(result)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// tlsproxy terminates TLS in the backend's network namespace. Targets must be loopback.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust"
|
||||
)
|
||||
|
||||
func main() {
|
||||
for _, route := range strings.Split(os.Getenv("TLS_ROUTES"), ";") {
|
||||
fields := strings.SplitN(route, "=", 4)
|
||||
if len(fields) < 3 {
|
||||
log.Fatal("invalid TLS route")
|
||||
}
|
||||
cfg, err := trust.Server("/trust/ca.crt", "/identity/tls.crt", "/identity/tls.key", fields[2], "/trust/revoked")
|
||||
if err != nil {
|
||||
log.Fatal("TLS configuration failed")
|
||||
}
|
||||
listener, err := tls.Listen("tcp", ":"+fields[0], cfg)
|
||||
if err != nil {
|
||||
log.Fatal("TLS listener failed")
|
||||
}
|
||||
target := "127.0.0.1:" + fields[1]
|
||||
if len(fields) == 4 {
|
||||
go serveHTTP(listener, target, fields[3])
|
||||
} else {
|
||||
go serve(listener, target)
|
||||
}
|
||||
}
|
||||
select {}
|
||||
}
|
||||
|
||||
func serve(listener net.Listener, target string) {
|
||||
slots := make(chan struct{}, 256)
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
log.Fatal("TLS accept failed")
|
||||
}
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
go func() {
|
||||
defer func() { <-slots }()
|
||||
tunnel(conn.(*tls.Conn), target)
|
||||
}()
|
||||
default:
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tunnel(client *tls.Conn, target string) {
|
||||
defer client.Close()
|
||||
client.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
if err := client.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
// Bound the lifetime of established connections after a leaf has been revoked.
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
if leafs := client.ConnectionState().PeerCertificates; len(leafs) > 0 && leafs[0].NotAfter.Before(deadline) {
|
||||
deadline = leafs[0].NotAfter
|
||||
}
|
||||
client.SetDeadline(deadline)
|
||||
backend, err := net.DialTimeout("tcp", target, 2*time.Second)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer backend.Close()
|
||||
backend.SetDeadline(deadline)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
io.Copy(backend, client)
|
||||
backend.(*net.TCPConn).CloseWrite()
|
||||
close(done)
|
||||
}()
|
||||
io.Copy(client, backend)
|
||||
client.Close()
|
||||
<-done
|
||||
}
|
||||
|
||||
func serveHTTP(listener net.Listener, target, rule string) {
|
||||
upstream := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: target})
|
||||
upstream.Transport = &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
|
||||
ResponseHeaderTimeout: 10 * time.Second, IdleConnTimeout: 15 * time.Second,
|
||||
}
|
||||
upstream.ErrorHandler = func(w http.ResponseWriter, _ *http.Request, _ error) {
|
||||
http.Error(w, "backend unavailable", http.StatusBadGateway)
|
||||
}
|
||||
allowed := strings.Split(rule, ",")
|
||||
server := &http.Server{
|
||||
ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second,
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for _, candidate := range allowed {
|
||||
method, path, _ := strings.Cut(candidate, ":")
|
||||
if r.Method == method && (r.URL.Path == path ||
|
||||
(strings.HasSuffix(path, "/") && strings.HasPrefix(r.URL.Path, path))) {
|
||||
upstream.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Error(w, "endpoint denied", http.StatusForbidden)
|
||||
}),
|
||||
}
|
||||
if err := server.Serve(listener); err != nil {
|
||||
log.Fatal("TLS HTTP server failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "render" {
|
||||
if len(os.Args) != 5 {
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := attachment.Render(context.Background(), os.Args[2], os.Args[3], os.Args[4]); err != nil {
|
||||
if errors.Is(err, attachment.ErrInvalidImage) {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
failed := flag.Bool("failed", false, "list failed job registry")
|
||||
replay := flag.String("replay", "", "failed job UUID to replay")
|
||||
operator := flag.String("operator", "", "operator identity")
|
||||
reason := flag.String("reason", "", "replay reason")
|
||||
flag.Parse()
|
||||
shutdownTelemetry, telemetryErr := observability.Init(context.Background(), "messenger-worker")
|
||||
if telemetryErr != nil {
|
||||
log.Fatal("telemetry configuration failed")
|
||||
}
|
||||
defer shutdownTelemetry()
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
options, err := attachment.LoadOptions()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
pc, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid DB config")
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pc.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
pc.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
pc.ConnConfig.Tracer = observability.DBTracer{}
|
||||
pc.MaxConns = int32(options.Concurrency + 4)
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pc)
|
||||
if err != nil {
|
||||
log.Fatal("DB configuration failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
observability.ObservePool(pool, options.Concurrency)
|
||||
store, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("S3 configuration failed")
|
||||
}
|
||||
service := attachment.NewAsync(pool, store, options)
|
||||
if *failed {
|
||||
rows, e := pool.Query(ctx, `SELECT id::text,attachment_id::text,attempts,max_attempts,coalesce(last_error,''),updated_at FROM attachment_jobs WHERE state='failed' ORDER BY updated_at DESC LIMIT 100`)
|
||||
if e != nil {
|
||||
log.Fatal("cannot query failed jobs")
|
||||
}
|
||||
defer rows.Close()
|
||||
records := []map[string]interface{}{}
|
||||
for rows.Next() {
|
||||
var id, att, code string
|
||||
var attempt, max int
|
||||
var updated time.Time
|
||||
if e = rows.Scan(&id, &att, &attempt, &max, &code, &updated); e != nil {
|
||||
log.Fatal("invalid failed job")
|
||||
}
|
||||
records = append(records, map[string]interface{}{"job_id": id, "attachment_id": att, "attempts": attempt, "max_attempts": max, "error_code": code, "updated_at": updated.UTC()})
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
log.Fatal("failed jobs query interrupted")
|
||||
}
|
||||
json.NewEncoder(os.Stdout).Encode(records)
|
||||
return
|
||||
}
|
||||
if *replay != "" {
|
||||
operation, stop := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer stop()
|
||||
if err = service.Replay(operation, *replay, *operator, *reason); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Print("Replay committed with audit record")
|
||||
return
|
||||
}
|
||||
redisOptions, err := cfg.RedisOptions()
|
||||
if err != nil {
|
||||
log.Fatal("invalid Redis TLS configuration")
|
||||
}
|
||||
r := redis.NewClient(redisOptions)
|
||||
defer r.Close()
|
||||
log.Printf("Worker started: concurrency=%d prefetch=%d timeout=%s lease=%s pixel_budget=%d", options.Concurrency, options.Prefetch, options.Timeout, options.Lease, options.PixelBudget)
|
||||
for ctx.Err() == nil {
|
||||
err = service.RunWorker(ctx, r)
|
||||
if err != nil {
|
||||
log.Print("worker broker connection will retry")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user