Реализация на 5

This commit is contained in:
Grbisba
2026-11-18 11:36:21 +03:00
parent 20afc2c790
commit de4d471d80
255 changed files with 21516 additions and 124 deletions
+194
View File
@@ -0,0 +1,194 @@
package main
import (
"context"
"fmt"
"gitea.privcloud.tech/mtusi2026/internal/pkg/openbao"
"gitea.privcloud.tech/mtusi2026/internal/pkg/ratelimit"
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/outside"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"gitea.privcloud.tech/mtusi2026/internal/service/user"
stdhttp "net/http"
)
func main() {
time.Local = time.UTC
if err := run(); err != nil {
slog.Error("application stopped", "error", err)
os.Exit(1)
}
}
func run() error {
if os.Getenv("APPLICATION_ENVIRONMENT") == "prod" && !transportsecurity.Enabled() {
return fmt.Errorf("production TLS is required")
}
processCtx, stopProcess := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stopProcess()
ctx, stopSecrets, err := openbao.Connect(processCtx)
if err != nil {
return err
}
defer stopSecrets()
if err = encrypting.ValidateProfile(); err != nil {
return err
}
cfg, err := config.New()
if err != nil {
return fmt.Errorf("load server config: %w", err)
}
if len(os.Args) > 1 && os.Args[1] == "migrate" {
cfg.Postgres.RunMigrations = true
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
return migrator.New(cfg).Start(ctx)
}
name := "messenger-api"
if len(os.Args) > 1 {
name = "messenger-" + os.Args[1]
}
shutdown, err := telemetry.Init(context.Background(), name)
if err != nil {
return err
}
defer shutdown()
attachmentConfig, err := config.LoadAttachment()
if err != nil {
return err
}
if len(os.Args) > 1 && (os.Args[1] == "worker" || os.Args[1] == "dispatcher" || os.Args[1] == "jobs" || os.Args[1] == "outbox") {
return runPipeline(ctx, cfg, attachmentConfig, os.Args[1:])
}
if len(os.Args) > 1 && os.Args[1] == "storage" {
return runStorage(cfg, attachmentConfig, os.Args[2:])
}
// API processes never run migrations; the one-shot migrator owns schema changes.
cfg.Postgres.RunMigrations = false
var level slog.Level
if err := level.UnmarshalText([]byte(cfg.Application.LogLevel)); err != nil {
return err
}
// Logging is initialized for every process by telemetry.Init.
instanceID := telemetry.InstanceID
slog.Info("instance_started", "instance_id", instanceID)
pgx := postgres.New(cfg.Postgres)
rx := cache.New(cfg)
postgresMigrator := migrator.New(cfg)
defer pgx.Close()
telemetry.ObservePool(pgx, 0)
defer rx.Close()
tm := txmanager.New(pgx)
provider := jwtprovider.New(cfg)
encryptor := encrypting.New()
chatsRepo := storage.NewChatsRepo(pgx)
messageRepo := storage.NewMessagesRepo(pgx)
refreshTokensRepo := storage.NewRefreshTokensRepo(pgx)
userRepo := storage.NewUsersRepo(pgx)
chatCache := outside.NewChatCache(rx)
authSvc := auth.New(provider, tm, encryptor, userRepo, refreshTokensRepo)
authSvc.SetLimiter(&ratelimit.Limiter{Client: rx.Client})
userSvc := user.New(encryptor, userRepo)
chatSvc := chat.New(tm, chatsRepo, messageRepo, chatCache)
objectStore := objectstore.New(attachmentConfig)
attachmentSvc := attachment.New(&storage.AttachmentsRepo{Pool: pgx}, objectStore, attachmentConfig, chatSvc)
pipelineConfig, err := config.LoadPipeline()
if err != nil {
return err
}
outboxSvc := outbox.New(&storage.OutboxRepo{Pool: pgx}, tm, nil)
attachmentSvc.Configure(tm, outboxSvc, pipelineConfig)
httpRouter := router.New(
middleware.NewAuthMiddleware(authSvc),
middleware.Instance(instanceID),
middleware.RequestIDMiddleware(),
telemetry.HTTP,
middleware.RequestTimeout(cfg.Postgres.QueryTimeout, attachmentConfig.Timeout),
)
httpRouter.Get("/internal/metrics", func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
stat := pgx.Stat()
_ = json.NewEncoder(w).Encode(map[string]any{"instance_id": instanceID, "acquire_count": stat.AcquireCount(), "acquire_duration_ns": stat.AcquireDuration().Nanoseconds(), "empty_acquire_count": stat.EmptyAcquireCount(), "acquired_conns": stat.AcquiredConns(), "total_conns": stat.TotalConns(), "max_conns": stat.MaxConns()})
})
server := http.New(cfg, httpRouter)
requestValidator := validator.NewValidatorImpl()
registerRoutes(
http.NewAuthHandler(httpRouter, authSvc),
http.NewHealthHandler(httpRouter, server, pgx, objectStore),
http.NewChatHandler(httpRouter, provider, requestValidator, chatSvc),
http.NewUserHandler(httpRouter, provider, requestValidator, userSvc),
http.NewAttachmentHandler(httpRouter, provider, attachmentSvc),
)
// The only plaintext listener is loopback and exposes exactly the two health routes.
localHealth := &stdhttp.Server{Addr: "127.0.0.1:8081", ReadHeaderTimeout: time.Second, Handler: stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) {
if r.URL.Path != "/health/live" && r.URL.Path != "/health/ready" {
stdhttp.NotFound(w, r)
return
}
httpRouter.ServeHTTP(w, r)
})}
go func() { _ = localHealth.ListenAndServe() }()
defer localHealth.Close()
if err = postgresMigrator.Start(ctx); err != nil {
return fmt.Errorf("start postgres migrator: %w", err)
}
if err = server.Start(ctx); err != nil {
return fmt.Errorf("start HTTP server: %w", err)
}
if err = rx.Start(ctx); err != nil {
slog.Warn("redis unavailable at startup; continuing without cache", "error", err)
}
slog.Info("HTTP server started", "address", cfg.Server.BindAddress())
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
defer cancel()
if err = server.Stop(shutdownCtx); err != nil {
return fmt.Errorf("stop HTTP server: %w", err)
}
if err = postgresMigrator.Close(shutdownCtx); err != nil {
return fmt.Errorf("close postgres migrator: %w", err)
}
if err = rx.Close(); err != nil {
return fmt.Errorf("close redis: %w", err)
}
pgx.Close()
return nil
}
func registerRoutes(handlers ...http.Handler) {
for _, handler := range handlers {
handler.RegisterRoutes()
}
}
+156
View File
@@ -0,0 +1,156 @@
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/broker"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
"gitea.privcloud.tech/mtusi2026/internal/pkg/telemetry"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/observation"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
)
func runPipeline(lifetime context.Context, cfg *config.Config, a *config.Attachment, args []string) error {
c, e := config.LoadPipeline()
if e != nil {
return e
}
ctx, stop := signal.NotifyContext(lifetime, os.Interrupt, syscall.SIGTERM)
defer stop()
pool := postgres.New(cfg.Postgres)
defer pool.Close()
telemetry.ObservePool(pool, c.Concurrency)
tm := txmanager.New(pool)
repo := &storage.AttachmentsRepo{Pool: pool}
rabbit := &broker.Rabbit{URL: c.BrokerURL}
ob := outbox.New(&storage.OutboxRepo{Pool: pool}, tm, rabbit)
svc := attachment.New(repo, objectstore.New(a), a, nil)
svc.Configure(tm, ob, c)
ob.OnDead = svc.PublishFailed
if args[0] == "jobs" || args[0] == "outbox" {
if len(args) < 2 {
return errors.New("operator action required")
}
fs := flag.NewFlagSet(args[1], flag.ContinueOnError)
idText := fs.String("id", "", "job ID (attachment ID for reprocess)")
version := fs.Int("pipeline-version", 2, "new pipeline version")
if e = fs.Parse(args[2:]); e != nil {
return e
}
if args[1] == "list" {
jobs, e := repo.ListJobs(ctx)
if e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(jobs)
}
id, e := uuid.Parse(*idText)
if e != nil {
return e
}
switch args[1] {
case "redeliver":
if os.Getenv("LAB5_FAULTS") != "1" {
return errors.New("redeliver is restricted to the explicit fault profile")
}
var payload []byte
e = tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
j, e := repo.JobTx(ctx, tx, id)
if e != nil {
return e
}
payload, e = json.Marshal(j.Message)
return e
})
if e == nil {
e = rabbit.Publish(ctx, outbox.DeliveryMessage{ID: uuid.New(), AggregateID: id, Payload: payload})
}
case "replay":
e = svc.Replay(ctx, id)
case "reprocess":
e = svc.Reprocess(ctx, id, *version)
default:
return errors.New("unknown operator action")
}
if e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"accepted": true, "id": id})
}
if c.BrokerURL == "" {
return errors.New("BROKER_URL_FILE is required")
}
if args[0] == "worker" {
// Recovery continues while the consumer is disconnected or a delivery is paused.
recoveryDone := make(chan struct{})
defer func() { stop(); <-recoveryDone }()
go func() {
defer close(recoveryDone)
tick := time.NewTicker(time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if e := svc.Recover(ctx); e != nil {
slog.Warn("job_recovery_failed")
}
if e := svc.Cleanup(ctx); e != nil {
slog.Warn("source_cleanup_failed")
}
}
}
}()
for ctx.Err() == nil {
if e = rabbit.Consume(ctx, c.Concurrency, c.Prefetch, svc.Process); e != nil && ctx.Err() == nil {
slog.Warn("consumer_reconnecting")
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
return nil
}
observer := &observation.Service{Repo: &storage.ObservationRepo{Pool: pool}, Publish: func(s observation.Snapshot) {
telemetry.PublishObservation(s.Queued, s.Outbox, s.Good, s.Bad, s.Oldest, s.Locked)
}}
telemetry.RegisterObservation()
nextObservation := time.Time{}
for ctx.Err() == nil {
if time.Now().After(nextObservation) {
if err := observer.Observe(ctx); err != nil {
slog.Warn("observation_unavailable")
}
depth, err := rabbit.Depth(ctx)
if err == nil {
telemetry.QueueDepth.Store(int64(depth))
}
nextObservation = time.Now().Add(time.Second)
}
_, e = ob.ProcessOnce(ctx)
if e != nil {
slog.Warn("dispatcher_retry")
}
select {
case <-ctx.Done():
case <-time.After(100 * time.Millisecond):
}
}
return nil
}
+183
View File
@@ -0,0 +1,183 @@
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"gitea.privcloud.tech/mtusi2026/internal/service/outbox"
)
func runStorage(cfg *config.Config, c *config.Attachment, args []string) error {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})))
if len(args) == 0 {
return fmt.Errorf("storage command required")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
store := objectstore.New(c)
if args[0] == "bootstrap" {
var err error
for i := 0; i < 60; i++ {
_, err = store.Client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: &c.Bucket})
var api smithy.APIError
if err == nil || (errors.As(err, &api) && (api.ErrorCode() == "BucketAlreadyOwnedByYou" || api.ErrorCode() == "BucketAlreadyExists")) {
if store.Ping(ctx) == nil {
// HEAD alone can succeed before the restarted master/volume write path.
// This constant key is outside the application's immutable originals prefix.
key := "bootstrap/write-check"
if store.Put(ctx, key, "application/octet-stream", strings.NewReader("ready"), 5) == nil && store.Delete(ctx, key) == nil {
return json.NewEncoder(os.Stdout).Encode(map[string]any{"bucket_ready": true, "write_checked": true})
}
}
}
time.Sleep(time.Second)
}
return fmt.Errorf("storage bootstrap failed: %w", err)
}
if args[0] == "private-check" {
// Unsigned requests must reach the S3 server and receive an auth failure,
// rather than passing because a network error hid a public object.
fs := flag.NewFlagSet("private-check", flag.ContinueOnError)
key := fs.String("key", "", "known object key")
if e := fs.Parse(args[1:]); e != nil {
return e
}
client := http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
resp, e := client.Get(c.Endpoint + "/" + c.Bucket + "/" + *key)
if e != nil {
return e
}
defer resp.Body.Close()
if resp.StatusCode != 401 && resp.StatusCode != 403 {
return fmt.Errorf("unsigned GET returned %d", resp.StatusCode)
}
_, e = store.Client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: new("forbidden-" + uuid.NewString())})
var api smithy.APIError
if !errors.As(e, &api) || api.ErrorCode() != "AccessDenied" {
return fmt.Errorf("API key bucket creation was not denied")
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"anonymous_status": resp.StatusCode, "api_create_bucket_denied": true})
}
if args[0] == "object-check" {
fs := flag.NewFlagSet("object-check", flag.ContinueOnError)
key := fs.String("key", "", "synthetic object key")
if e := fs.Parse(args[1:]); e != nil {
return e
}
head, e := store.Head(ctx, *key)
if objectstore.Missing(e) {
return json.NewEncoder(os.Stdout).Encode(map[string]any{"exists": false})
}
if e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"exists": true, "last_modified": head.LastModified, "size_bytes": head.ContentLength})
}
pool := postgres.New(cfg.Postgres)
defer pool.Close()
svc := attachment.New(&storage.AttachmentsRepo{Pool: pool}, store, c, nil)
jobs, e := config.LoadPipeline()
if e != nil {
return e
}
tm := txmanager.New(pool)
svc.Configure(tm, outbox.New(&storage.OutboxRepo{Pool: pool}, tm, nil), jobs)
switch args[0] {
case "reconcile":
fs := flag.NewFlagSet("reconcile", flag.ContinueOnError)
apply := fs.Bool("apply", false, "apply safe changes")
if e := fs.Parse(args[1:]); e != nil {
return e
}
result, e := svc.Reconcile(ctx, *apply)
_ = json.NewEncoder(os.Stdout).Encode(result)
return e
case "restore":
fs := flag.NewFlagSet("restore", flag.ContinueOnError)
id := fs.String("id", "", "attachment id")
source := fs.String("source", "", "original file")
if e := fs.Parse(args[1:]); e != nil {
return e
}
uid, e := uuid.Parse(*id)
if e != nil {
return e
}
if e = svc.Restore(ctx, uid, *source); e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"restored": uid})
case "seed":
fs := flag.NewFlagSet("seed", flag.ContinueOnError)
count := fs.Int("count", 1, "synthetic orphan count")
keyOverride := fs.String("key", "", "explicit key for a single synthetic object")
if e := fs.Parse(args[1:]); e != nil {
return e
}
if *count < 1 || *count > 10000 {
return fmt.Errorf("count must be 1..10000")
}
keys := []string{}
for i := 0; i < *count; i++ {
key := attachment.Prefix + uuid.NewString()
if *keyOverride != "" {
if *count != 1 {
return fmt.Errorf("explicit key requires count=1")
}
key = *keyOverride
}
if e := store.Put(ctx, key, "image/png", strings.NewReader("synthetic-orphan"), 16); e != nil {
return e
}
if *count == 1 {
keys = append(keys, key)
}
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"seeded": *count, "keys": keys})
case "remove-object":
fs := flag.NewFlagSet("remove-object", flag.ContinueOnError)
id := fs.String("id", "", "synthetic attachment id")
if e := fs.Parse(args[1:]); e != nil {
return e
}
uid, e := uuid.Parse(*id)
if e != nil {
return e
}
a, e := svc.Repo.Get(ctx, uid)
if e != nil {
return e
}
conn, unlock, e := svc.Repo.Lock(ctx, a.Key)
_ = conn
if e != nil {
return e
}
defer unlock()
if e = store.Delete(ctx, a.Key); e != nil {
return e
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"removed_object": uid})
default:
return fmt.Errorf("unknown storage command")
}
}
+260
View File
@@ -0,0 +1,260 @@
// Command benchmark generates paced lab5 traffic through the public load balancer.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"math"
"net/http"
"os"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
)
type client struct {
base, token string
http *http.Client
}
func (c *client) call(method, path string, body any, key string) (map[string]any, int, error) {
var data io.Reader
if body != nil {
b, e := json.Marshal(body)
if e != nil {
return nil, 0, e
}
data = bytes.NewReader(b)
}
req, e := http.NewRequest(method, c.base+path, data)
if e != nil {
return nil, 0, e
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
// net/http otherwise treats Idempotency-Key + GetBody as permission to retry POST.
if method == http.MethodPost {
req.GetBody = nil
}
resp, e := c.http.Do(req)
if e != nil {
return nil, 0, e
}
defer resp.Body.Close()
b, e := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if e != nil {
return nil, resp.StatusCode, e
}
if resp.StatusCode != 200 && resp.StatusCode != 201 {
return nil, resp.StatusCode, fmt.Errorf("HTTP %d", resp.StatusCode)
}
var out map[string]any
e = json.Unmarshal(b, &out)
return out, resp.StatusCode, e
}
func (c *client) setup(seed int) (string, error) {
username := "bench_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
password := "Synthetic-benchmark-123"
user, _, e := c.call("POST", "/api/v1/users", map[string]string{"username": username, "display_name": "Benchmark", "password": password}, "")
if e != nil {
return "", e
}
req, _ := http.NewRequest("POST", c.base+"/api/v1/auth/sessions", nil)
req.SetBasicAuth(username, password)
resp, e := c.http.Do(req)
if e != nil {
return "", e
}
var session struct {
Token string `json:"token"`
}
e = json.NewDecoder(resp.Body).Decode(&session)
resp.Body.Close()
if e != nil || resp.StatusCode != 201 || session.Token == "" {
return "", fmt.Errorf("login status %d: %v", resp.StatusCode, e)
}
c.token = session.Token
chat, _, e := c.call("POST", "/api/v1/chats", map[string]any{"title": "Benchmark", "member_ids": []any{user["id"]}}, "")
if e != nil {
return "", e
}
path := "/api/v1/chats/" + chat["id"].(string) + "/messages"
// Bounded concurrent setup is excluded from the measured interval.
var group sync.WaitGroup
slots := make(chan struct{}, 8)
errs := make(chan error, seed)
for i := range seed {
slots <- struct{}{}
group.Go(func() {
defer func() { <-slots }()
_, _, e := c.call("POST", path, map[string]string{"text": fmt.Sprintf("seed-%d", i)}, uuid.NewString())
if e != nil {
errs <- e
}
})
}
group.Wait()
close(errs)
for e := range errs {
if e != nil {
return "", e
}
}
return path, nil
}
type result struct {
MeasurementUnix float64 `json:"measurement_started_unix"`
Label string `json:"label"`
TargetRate int `json:"target_rps"`
Duration float64 `json:"duration_seconds"`
Elapsed float64 `json:"elapsed_including_drain_seconds"`
Scheduled int `json:"scheduled"`
Dropped int `json:"generator_dropped"`
Success int `json:"successful_requests"`
Errors int `json:"failed_requests"`
ReadSuccess int `json:"read_success"`
WriteSuccess int `json:"write_success"`
SuccessfulRPS float64 `json:"successful_rps"`
ErrorRatio float64 `json:"error_ratio_including_drops"`
Latency map[string]float64 `json:"successful_latency_ms"`
Statuses map[int]int `json:"statuses"`
PeakInFlight int64 `json:"peak_in_flight"`
Note string `json:"note"`
}
func phase(c *client, path string, rate int, duration time.Duration, maxInFlight int, label string) result {
out := result{Label: label, TargetRate: rate, Duration: duration.Seconds(), Statuses: map[int]int{}, Latency: map[string]float64{}, Note: "Paced open-loop, 10ms dispatch batches; 90% first-page GET, 10% POST; no POST retries. Percentiles of successes include scheduler delay; failures and capacity drops reported separately. RPS denominator includes drain."}
start := time.Now()
out.MeasurementUnix = float64(start.UnixNano()) / 1e9
end := start.Add(duration)
slots := make(chan struct{}, maxInFlight)
var group sync.WaitGroup
var mu sync.Mutex
var active atomic.Int64
var peak atomic.Int64
latencies := make([]float64, 0, rate*int(duration.Seconds()))
index := 0
for tick := 0; ; tick++ {
now := time.Now()
if !now.Before(end) {
break
}
target := start.Add(time.Duration(tick) * 10 * time.Millisecond)
if target.After(now) {
time.Sleep(time.Until(target))
}
until := min(int(time.Since(start).Seconds()*float64(rate))+1, int(duration.Seconds()*float64(rate)))
for index < until {
i := index
index++
out.Scheduled++
scheduled := start.Add(time.Duration(float64(i) / float64(rate) * float64(time.Second)))
select {
case slots <- struct{}{}:
group.Go(func() {
n := active.Add(1)
for old := peak.Load(); n > old; old = peak.Load() {
if peak.CompareAndSwap(old, n) {
break
}
}
defer func() { active.Add(-1); <-slots }()
method, p := "GET", path+"?limit=50"
var body any
key := ""
if i%10 == 0 {
method = "POST"
p = path
key = uuid.NewString()
body = map[string]string{"text": key}
}
_, status, err := c.call(method, p, body, key)
latency := float64(time.Since(scheduled).Microseconds()) / 1000
mu.Lock()
defer mu.Unlock()
out.Statuses[status]++
if err != nil {
out.Errors++
} else {
out.Success++
if method == "GET" {
out.ReadSuccess++
} else {
out.WriteSuccess++
}
latencies = append(latencies, max(0, latency))
}
})
default:
out.Dropped++
}
}
}
group.Wait()
out.Elapsed = time.Since(start).Seconds()
out.PeakInFlight = peak.Load()
out.SuccessfulRPS = float64(out.Success) / out.Elapsed
if out.Scheduled > 0 {
out.ErrorRatio = float64(out.Errors+out.Dropped) / float64(out.Scheduled)
}
slices.Sort(latencies)
for name, p := range map[string]float64{"p50": .5, "p95": .95, "p99": .99} {
if len(latencies) > 0 {
out.Latency[name] = latencies[max(0, int(math.Ceil(p*float64(len(latencies))))-1)]
}
}
return out
}
func main() {
base := flag.String("base-url", "http://localhost:18086", "public LB URL")
rate := flag.Int("rate", 100, "scheduled requests per second")
duration := flag.Duration("duration", 30*time.Second, "measured time")
warmup := flag.Duration("warmup", 5*time.Second, "warmup excluded from results")
seed := flag.Int("seed", 1000, "initial messages")
maxFlight := flag.Int("max-in-flight", 256, "bounded in-flight limit")
label := flag.String("label", "manual", "case label")
output := flag.String("output", "", "JSON destination")
flag.Parse()
if *rate < 1 || *rate > 100000 || *duration <= 0 || *warmup < 0 || *maxFlight < 1 || *seed < 0 {
fmt.Fprintln(os.Stderr, "invalid benchmark settings")
os.Exit(2)
}
c := &client{base: *base, http: &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{MaxIdleConns: 512, MaxIdleConnsPerHost: 512, MaxConnsPerHost: *maxFlight, IdleConnTimeout: 60 * time.Second}}}
path, e := c.setup(*seed)
if e != nil {
fmt.Fprintln(os.Stderr, "setup:", e)
os.Exit(1)
}
if *warmup > 0 {
phase(c, path, *rate, *warmup, *maxFlight, "warmup")
}
row := phase(c, path, *rate, *duration, *maxFlight, *label)
b, e := json.MarshalIndent(row, "", " ")
if e != nil {
panic(e)
}
if *output != "" {
if e = os.WriteFile(*output, append(b, '\n'), 0644); e != nil {
panic(e)
}
}
fmt.Println(string(b))
if row.Success == 0 {
os.Exit(1)
}
}
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestLostPostResponseIsNotRetried(t *testing.T) {
var posts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
return
}
posts.Add(1)
_, _ = io.Copy(io.Discard, r.Body)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
t.Error(err)
return
}
_ = conn.Close()
}))
defer server.Close()
transport := &http.Transport{MaxIdleConnsPerHost: 1}
defer transport.CloseIdleConnections()
c := &client{base: server.URL, http: &http.Client{Timeout: time.Second, Transport: transport}}
if _, _, err := c.call(http.MethodGet, "/warm", nil, ""); err != nil {
t.Fatal(err)
}
if _, _, err := c.call(http.MethodPost, "/message", map[string]string{"text": "uncertain result"}, "same-key"); err == nil {
t.Fatal("lost response must be reported as an error")
}
if posts.Load() != 1 {
t.Fatalf("transport sent %d POSTs, want exactly 1", posts.Load())
}
}
+335
View File
@@ -0,0 +1,335 @@
// securityprobe exercises real dependency authorization and emits no secrets.
package main
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
"gitea.privcloud.tech/mtusi2026/internal/pkg/objectstore"
"gitea.privcloud.tech/mtusi2026/internal/pkg/openbao"
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
"github.com/aws/smithy-go"
"github.com/jackc/pgx/v5"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/redis/go-redis/v9"
"io"
"net"
"net/http"
"os"
"sort"
"strings"
"syscall"
"time"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
mode := os.Getenv("PROBE_MODE")
target := os.Getenv("PROBE_TARGET")
expect := os.Getenv("PROBE_EXPECT")
if mode == "hash" || mode == "kdf" {
encryptor := encrypting.New()
if mode == "hash" {
h, e := encryptor.EncryptSecretUsingArgon2id(ctx, os.Getenv("PROBE_PASSWORD"))
if e != nil {
return e
}
fmt.Print(h)
return nil
}
times := []float64{}
for i := 0; i < 12; i++ {
start := time.Now()
_, e := encryptor.EncryptSecretUsingArgon2id(ctx, "synthetic-benchmark-password")
if e != nil {
return e
}
times = append(times, float64(time.Since(start).Microseconds())/1000)
}
sort.Float64s(times)
return json.NewEncoder(os.Stdout).Encode(map[string]any{"samples": 12, "memory_kib": 65536, "iterations": 3, "parallelism": 1, "max_parallel_kdf": 2, "p50_ms": times[6], "p95_ms": times[11], "max_ms": times[11]})
}
tc, err := transportsecurity.Client()
if err != nil {
return fmt.Errorf("probe TLS material unavailable")
}
if os.Getenv("PROBE_UNTRUST_SERVER") == "1" {
tc.RootCAs = x509.NewCertPool()
}
if os.Getenv("PROBE_NO_CERT") == "1" {
tc.Certificates = nil
}
if mode == "telemetry" {
client := http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: tc}}
endpoints := map[string]string{"metrics": "https://prometheus:9443/api/v1/query?query=up", "logs": "https://loki:9443/loki/api/v1/query_range?query=%7Bservice_name%3D%22messenger-worker%22%7D&limit=5", "traces": "https://tempo:9443/api/traces/" + os.Getenv("PROBE_TRACE_ID")}
result := map[string]any{}
for name, url := range endpoints {
r, e := client.Get(url)
if e != nil {
return fmt.Errorf("telemetry %s transport failed", name)
}
b, e := io.ReadAll(io.LimitReader(r.Body, 2<<20))
r.Body.Close()
if e != nil || r.StatusCode != 200 {
return fmt.Errorf("telemetry %s query failed", name)
}
var data map[string]json.RawMessage
if json.Unmarshal(b, &data) != nil {
return fmt.Errorf("invalid telemetry response")
}
result[name] = json.RawMessage(b)
}
return json.NewEncoder(os.Stdout).Encode(result)
}
if mode == "db-tls" {
raw, e := net.DialTimeout("tcp", "postgres:5432", 3*time.Second)
if e != nil {
return fmt.Errorf("DB listener unreachable")
}
defer raw.Close()
raw.SetDeadline(time.Now().Add(3 * time.Second))
packet := make([]byte, 8)
binary.BigEndian.PutUint32(packet, 8)
binary.BigEndian.PutUint32(packet[4:], 80877103)
if _, e = raw.Write(packet); e != nil {
return e
}
answer := make([]byte, 1)
if _, e = io.ReadFull(raw, answer); e != nil || answer[0] != 'S' {
return fmt.Errorf("Postgres SSLRequest failed")
}
tc.ServerName = "postgres"
if v := os.Getenv("PROBE_SERVER_NAME"); v != "" {
tc.ServerName = v
}
e = tls.Client(raw, tc).HandshakeContext(ctx)
if (e != nil) != (expect == "deny") {
return fmt.Errorf("DB TLS expectation failed")
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "matched": true})
}
if mode == "amqp-tls" {
conn, e := amqp.DialConfig("amqps://broker:5671/attachments", amqp.Config{TLSClientConfig: tc, SASL: []amqp.Authentication{&amqp.ExternalAuth{}}})
if conn != nil {
defer conn.Close()
}
if (e != nil) != (expect == "deny") {
return fmt.Errorf("AMQP identity expectation failed")
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "expect": expect, "matched": true})
}
if mode == "tls" {
if name := os.Getenv("PROBE_SERVER_NAME"); name != "" {
tc.ServerName = name
}
req, _ := http.NewRequestWithContext(ctx, "GET", target, nil)
if strings.Contains(target, "otel-collector") && strings.Contains(target, "/v1/") {
req, _ = http.NewRequestWithContext(ctx, "POST", target, strings.NewReader("{}"))
req.Header.Set("Content-Type", "application/json")
}
if method := os.Getenv("PROBE_METHOD"); method != "" {
req.Method = method
}
client := http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{TLSClientConfig: tc}}
r, e := client.Do(req)
denied := e != nil
if e != nil {
var n net.Error
if errors.As(e, &n) && n.Timeout() {
return fmt.Errorf("timeout is not identity denial")
}
if errors.Is(e, syscall.ECONNREFUSED) {
return fmt.Errorf("connection refused is not identity denial")
}
}
if r != nil {
defer r.Body.Close()
io.Copy(io.Discard, r.Body)
denied = r.StatusCode == 401 || r.StatusCode == 403
}
if expect == "deny" && !denied {
return fmt.Errorf("TLS/identity denial missing")
}
if expect != "deny" && denied {
return fmt.Errorf("authorized TLS request failed")
}
// Prove a reachable TLS listener independently: a failed TCP connect is never accepted as an identity denial.
if denied {
address := strings.TrimPrefix(strings.Split(target[8:], "/")[0], "https://")
c, e := net.DialTimeout("tcp", address, 2*time.Second)
if e != nil {
return fmt.Errorf("network failure is not a security denial")
}
c.Close()
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"mode": mode, "expect": expect, "matched": true})
}
stop, err := openbao.Start(ctx)
if err != nil {
return err
}
defer stop()
role := os.Getenv("SERVICE_ROLE")
out := map[string]any{"mode": mode, "role": role}
check := func(name string, allowed bool, err error) error {
ok := (err == nil) == allowed
out[name] = ok
if !ok {
return fmt.Errorf("authorization mismatch: %s", name)
}
return nil
}
switch mode {
case "db":
cfg, e := config.New()
if e != nil {
return e
}
conn, e := pgx.Connect(ctx, cfg.Postgres.GetURI())
if e != nil {
return fmt.Errorf("DB connection failed")
}
defer conn.Close(ctx)
for _, q := range []struct {
name, sql string
allow bool
}{{"jobs_read", "SELECT id FROM attachment_jobs LIMIT 0", true}, {"password_read_denied", "SELECT password_hash FROM users LIMIT 0", false}, {"session_read_denied", "SELECT token_hash FROM refresh_tokens LIMIT 0", false}, {"messages_read_denied", "SELECT id FROM messages LIMIT 0", false}, {"ddl_denied", "CREATE TABLE security_probe_should_not_exist(id int)", false}} {
_, e := conn.Exec(ctx, q.sql)
if e = check(q.name, q.allow, e); e != nil {
return e
}
}
case "s3":
cfg, e := config.LoadAttachment()
if e != nil {
return e
}
s := objectstore.New(cfg)
key := "results/security-probe/" + fmt.Sprint(time.Now().UnixNano())
e = s.Put(ctx, key, "application/octet-stream", bytes.NewReader([]byte("synthetic")), 9)
if os.Getenv("PROBE_OLD_SECRET") == "1" {
var denied smithy.APIError
if !errors.As(e, &denied) || (denied.ErrorCode() != "InvalidAccessKeyId" && denied.ErrorCode() != "AccessDenied" && denied.ErrorCode() != "SignatureDoesNotMatch") {
return fmt.Errorf("old S3 secret was not explicitly denied")
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{"old_s3_secret_rejected": true})
}
if e = check("results_write", true, e); e != nil {
return e
}
_, e = s.Get(ctx, key)
if e = check("results_read", true, e); e != nil {
return e
}
defer s.Delete(ctx, key)
for _, key := range []string{"originals/security-denied", "forbidden/security-denied"} {
if os.Getenv("PROBE_BASELINE") == "1" {
defer s.Delete(ctx, key)
}
e = s.Put(ctx, key, "application/octet-stream", bytes.NewReader([]byte("x")), 1)
if e = check(key, os.Getenv("PROBE_BASELINE") == "1", e); e != nil {
return e
}
}
case "redis":
cfg, e := config.New()
if e != nil {
return e
}
r := redis.NewClient(cfg.Redis.BuildRedisOptions())
defer r.Close()
if e = check("ping", true, r.Ping(ctx).Err()); e != nil {
return e
}
if e = check("foreign_key_denied", false, r.Get(ctx, "forbidden:security-probe").Err()); e != nil {
return e
}
if e = check("config_denied", false, r.ConfigGet(ctx, "*").Err()); e != nil {
return e
}
case "amqp":
dial := func() (*amqp.Connection, *amqp.Channel, error) {
conn, e := amqp.DialConfig("amqps://broker:5671/attachments", amqp.Config{TLSClientConfig: tc, SASL: []amqp.Authentication{&amqp.ExternalAuth{}}})
if e != nil {
return nil, nil, e
}
ch, e := conn.Channel()
return conn, ch, e
}
conn, ch, e := dial()
if e != nil {
return fmt.Errorf("authorized AMQP connection failed")
}
defer conn.Close()
_, e = ch.QueueInspect("attachments.v1")
if e = check("queue_read", true, e); e != nil {
return e
}
ch.Close()
ch, _ = conn.Channel()
baseline := os.Getenv("PROBE_BASELINE") == "1"
queue := "attachments.security-probe"
_, e = ch.QueueDeclare(queue, true, false, false, false, nil)
if e = check("configure_profile", baseline, e); e != nil {
return e
}
ch, _ = conn.Channel()
destination := "attachments.v1"
if baseline {
destination = queue
}
// Synchronous confirm/error reporting avoids accepting an async ACL failure as success.
if e = ch.Confirm(false); e != nil {
return e
}
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
closed := ch.NotifyClose(make(chan *amqp.Error, 1))
e = ch.PublishWithContext(ctx, "", destination, false, false, amqp.Publishing{Body: []byte("synthetic-probe")})
if e == nil {
select {
case ack := <-confirms:
if !ack.Ack {
e = fmt.Errorf("not confirmed")
}
case <-closed:
e = fmt.Errorf("broker denied publish")
case <-ctx.Done():
return fmt.Errorf("broker probe timed out")
}
}
time.Sleep(200 * time.Millisecond)
if e == nil && ch.IsClosed() {
e = fmt.Errorf("denied")
}
if e = check("publish_profile", baseline, e); e != nil {
return e
}
if baseline {
cleanup, _ := conn.Channel()
defer cleanup.Close()
_, e = cleanup.QueueDelete(queue, false, false, false)
if e != nil {
return e
}
}
default:
return fmt.Errorf("unknown probe mode")
}
return json.NewEncoder(os.Stdout).Encode(out)
}
var _ = tls.VersionTLS12