forked from mtusi2026/mtusi2026lab3
На 5
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"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"
|
||||
@@ -25,6 +26,8 @@ import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
"github.com/google/uuid"
|
||||
stdhttp "net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -41,9 +44,27 @@ func run() error {
|
||||
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)
|
||||
}
|
||||
// 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
|
||||
}
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})))
|
||||
hostname, _ := os.Hostname()
|
||||
instanceID := hostname + "-" + uuid.NewString()
|
||||
slog.Info("instance_started", "instance_id", instanceID)
|
||||
pgx := postgres.New(cfg.Postgres)
|
||||
rx := cache.New(cfg)
|
||||
postgresMigrator := migrator.New(cfg)
|
||||
defer pgx.Close()
|
||||
defer rx.Close()
|
||||
tm := txmanager.New(pgx)
|
||||
provider := jwtprovider.New(cfg)
|
||||
encryptor := encrypting.New()
|
||||
@@ -61,10 +82,15 @@ func run() error {
|
||||
|
||||
httpRouter := router.New(
|
||||
middleware.NewAuthMiddleware(authSvc),
|
||||
middleware.Instance(instanceID),
|
||||
middleware.RequestIDMiddleware(),
|
||||
middleware.LoggingMiddleware(),
|
||||
middleware.RequestTimeout(cfg.Postgres.QueryTimeout),
|
||||
)
|
||||
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(
|
||||
|
||||
+202
-328
@@ -1,386 +1,260 @@
|
||||
// Command benchmark measures the lab1 HTTP API in fresh, resource-limited containers.
|
||||
// Command benchmark generates paced lab3 traffic through the public load balancer.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
container = "mtusi-inmemory-benchmark"
|
||||
baseURL = "http://127.0.0.1:18093"
|
||||
)
|
||||
|
||||
type runResult struct {
|
||||
History int `json:"history"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
Repetition int `json:"repetition"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
ReadSuccess int `json:"read_success"`
|
||||
WriteSuccess int `json:"write_success"`
|
||||
Errors int `json:"errors"`
|
||||
SuccessfulRPS float64 `json:"successful_rps"`
|
||||
LatencyMS map[string]float64 `json:"latency_ms"`
|
||||
RSSBeforeKiB int `json:"rss_kib_before"`
|
||||
RSSPeakKiB int `json:"rss_kib_peak"`
|
||||
type client struct {
|
||||
base, token string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
type report struct {
|
||||
Image string `json:"image"`
|
||||
Method map[string]any `json:"method"`
|
||||
Runs []runResult `json:"runs"`
|
||||
}
|
||||
|
||||
type workerResult struct {
|
||||
reads int
|
||||
writes int
|
||||
errors int
|
||||
latencies []float64
|
||||
}
|
||||
|
||||
type memoryResult struct {
|
||||
peak int
|
||||
err error
|
||||
}
|
||||
|
||||
func docker(args ...string) (string, error) {
|
||||
command := exec.Command("docker", args...)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("docker %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
func rssKiB() (int, error) {
|
||||
status, err := docker("exec", container, "cat", "/proc/1/status")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for line := range strings.SplitSeq(status, "\n") {
|
||||
if strings.HasPrefix(line, "VmRSS:") {
|
||||
fields := strings.Fields(line)
|
||||
return strconv.Atoi(fields[1])
|
||||
}
|
||||
}
|
||||
return 0, errors.New("VmRSS is unavailable")
|
||||
}
|
||||
|
||||
func newClient(timeout time.Duration) *http.Client {
|
||||
return &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxConnsPerHost: 1,
|
||||
MaxIdleConnsPerHost: 1,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func request(client *http.Client, method, path, user string, body any) (map[string]any, error) {
|
||||
func (c *client) call(method, path string, body any, key string) (map[string]any, int, error) {
|
||||
var data io.Reader
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
b, e := json.Marshal(body)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
data = bytes.NewReader(encoded)
|
||||
data = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, baseURL+path, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if user != "" {
|
||||
req.Header.Set("X-User-Id", user)
|
||||
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")
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
|
||||
return nil, fmt.Errorf("%s %s: HTTP %d: %s", method, path, response.StatusCode, content)
|
||||
// net/http otherwise treats Idempotency-Key + GetBody as permission to retry POST.
|
||||
if method == http.MethodPost {
|
||||
req.GetBody = nil
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(content, &payload); err != nil {
|
||||
return nil, err
|
||||
resp, e := c.http.Do(req)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
return payload, nil
|
||||
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 stringField(payload map[string]any, key string) (string, error) {
|
||||
value, ok := payload[key].(string)
|
||||
if !ok || value == "" {
|
||||
return "", fmt.Errorf("missing %s in API response", key)
|
||||
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
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func percentile(sorted []float64, proportion float64) float64 {
|
||||
if len(sorted) == 0 {
|
||||
return 0
|
||||
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
|
||||
}
|
||||
index := int(math.Ceil(float64(len(sorted))*proportion)) - 1
|
||||
if index < 0 {
|
||||
index = 0
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
return round(sorted[index], 3)
|
||||
}
|
||||
|
||||
func round(value float64, places int) float64 {
|
||||
shift := math.Pow10(places)
|
||||
return math.Round(value*shift) / shift
|
||||
}
|
||||
|
||||
func sampleMemory(stop <-chan struct{}, initial int, result chan<- memoryResult) {
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
peak := initial
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
result <- memoryResult{peak: peak}
|
||||
return
|
||||
case <-ticker.C:
|
||||
rss, err := rssKiB()
|
||||
if err != nil {
|
||||
result <- memoryResult{err: err}
|
||||
return
|
||||
}
|
||||
peak = max(peak, rss)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func runCase(image string, history, concurrency, repetition int, duration time.Duration) (runResult, error) {
|
||||
row := runResult{History: history, Concurrency: concurrency, Repetition: repetition}
|
||||
if _, err := docker("run", "-d", "--name", container, "--cpus=1", "--memory=512m",
|
||||
"-p", "127.0.0.1:18093:8080", image); err != nil {
|
||||
return row, err
|
||||
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
|
||||
}
|
||||
defer func() { _, _ = docker("rm", "-f", container) }()
|
||||
|
||||
setup := newClient(2 * time.Second)
|
||||
defer setup.CloseIdleConnections()
|
||||
readyDeadline := time.Now().Add(20 * time.Second)
|
||||
for {
|
||||
if _, err := request(setup, http.MethodGet, "/health/ready", "", nil); err == nil {
|
||||
break
|
||||
} else if time.Now().After(readyDeadline) {
|
||||
return row, fmt.Errorf("server did not become ready: %w", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
userResponse, err := request(setup, http.MethodPost, "/api/v1/users", "", map[string]any{
|
||||
"username": fmt.Sprintf("bench_%d_%d_%d", time.Now().UnixNano(), history, repetition),
|
||||
"display_name": "Benchmark",
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
user, err := stringField(userResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chatResponse, err := request(setup, http.MethodPost, "/api/v1/chats", user, map[string]any{
|
||||
"title": "Benchmark", "member_ids": []string{user},
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chat, err := stringField(chatResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
for index := range history {
|
||||
if _, err := request(setup, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("seed-%d", index),
|
||||
}); err != nil {
|
||||
return row, fmt.Errorf("seed message %d: %w", index, err)
|
||||
}
|
||||
}
|
||||
row.RSSBeforeKiB, err = rssKiB()
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan workerResult, concurrency)
|
||||
stopSampling := make(chan struct{})
|
||||
memory := make(chan memoryResult, 1)
|
||||
go sampleMemory(stopSampling, row.RSSBeforeKiB, memory)
|
||||
path := "/api/v1/chats/" + chat["id"].(string) + "/messages"
|
||||
// Bounded concurrent setup is excluded from the measured interval.
|
||||
var group sync.WaitGroup
|
||||
group.Add(concurrency)
|
||||
deadline := time.Now().Add(duration)
|
||||
started := time.Now()
|
||||
for workerID := range concurrency {
|
||||
go func() {
|
||||
defer group.Done()
|
||||
local := newClient(5 * time.Second)
|
||||
defer local.CloseIdleConnections()
|
||||
result := workerResult{}
|
||||
<-start
|
||||
for index := 0; time.Now().Before(deadline); index++ {
|
||||
began := time.Now()
|
||||
var err error
|
||||
if index%10 == 0 {
|
||||
_, err = request(local, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("load-%d-%d-%d", repetition, workerID, index),
|
||||
})
|
||||
if err == nil {
|
||||
result.writes++
|
||||
}
|
||||
} else {
|
||||
var page map[string]any
|
||||
page, err = request(local, http.MethodGet, path+"?limit=50", user, nil)
|
||||
if err == nil {
|
||||
items, ok := page["items"].([]any)
|
||||
if !ok || len(items) != 50 {
|
||||
err = errors.New("short first page")
|
||||
} else {
|
||||
result.reads++
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
result.errors++
|
||||
} else {
|
||||
result.latencies = append(result.latencies, float64(time.Since(began).Microseconds())/1000)
|
||||
}
|
||||
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++
|
||||
}
|
||||
results <- result
|
||||
}()
|
||||
}
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
row.ElapsedSeconds = round(time.Since(started).Seconds(), 3)
|
||||
close(stopSampling)
|
||||
memorySample := <-memory
|
||||
if memorySample.err != nil {
|
||||
return row, memorySample.err
|
||||
}
|
||||
row.RSSPeakKiB = memorySample.peak
|
||||
if finalRSS, err := rssKiB(); err == nil {
|
||||
row.RSSPeakKiB = max(row.RSSPeakKiB, finalRSS)
|
||||
} else {
|
||||
return row, err
|
||||
}
|
||||
latencies := make([]float64, 0)
|
||||
for range concurrency {
|
||||
result := <-results
|
||||
row.ReadSuccess += result.reads
|
||||
row.WriteSuccess += result.writes
|
||||
row.Errors += result.errors
|
||||
latencies = append(latencies, result.latencies...)
|
||||
}
|
||||
if len(latencies) == 0 {
|
||||
return row, errors.New("no successful requests")
|
||||
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)
|
||||
row.SuccessfulRPS = round(float64(len(latencies))/row.ElapsedSeconds, 2)
|
||||
row.LatencyMS = map[string]float64{
|
||||
"p95": percentile(latencies, 0.95),
|
||||
"p99": percentile(latencies, 0.99),
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func parseValues(raw string, minimum int) ([]int, error) {
|
||||
values := make([]int, 0)
|
||||
for part := range strings.SplitSeq(raw, ",") {
|
||||
value, err := strconv.Atoi(strings.TrimSpace(part))
|
||||
if err != nil || value < minimum {
|
||||
return nil, fmt.Errorf("invalid value %q", part)
|
||||
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)]
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, nil
|
||||
return out
|
||||
}
|
||||
|
||||
func save(path string, data report) error {
|
||||
encoded, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(encoded, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func main() {
|
||||
image := flag.String("image", "", "Docker image to benchmark")
|
||||
output := flag.String("output", "", "JSON output path")
|
||||
historiesArg := flag.String("histories", "100,500,1500", "Comma-separated history sizes")
|
||||
concurrenciesArg := flag.String("concurrencies", "1,4,10", "Comma-separated client counts")
|
||||
repeats := flag.Int("repeats", 3, "Runs per combination")
|
||||
duration := flag.Duration("duration", 5*time.Second, "Measured duration per run")
|
||||
base := flag.String("base-url", "http://localhost:18080", "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 *image == "" || *output == "" || *repeats < 1 || *duration <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "image, output, positive repeats and duration are required")
|
||||
if *rate < 1 || *rate > 100000 || *duration <= 0 || *warmup < 0 || *maxFlight < 1 || *seed < 0 {
|
||||
fmt.Fprintln(os.Stderr, "invalid benchmark settings")
|
||||
os.Exit(2)
|
||||
}
|
||||
histories, err := parseValues(*historiesArg, 50)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
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)
|
||||
}
|
||||
concurrencies, err := parseValues(*concurrenciesArg, 1)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
if *warmup > 0 {
|
||||
phase(c, path, *rate, *warmup, *maxFlight, "warmup")
|
||||
}
|
||||
data := report{
|
||||
Image: *image,
|
||||
Method: map[string]any{
|
||||
"histories": histories, "concurrencies": concurrencies,
|
||||
"repeats": *repeats, "duration_seconds": duration.Seconds(),
|
||||
"mix": "90% first-page GET, 10% POST per client; persistent HTTP connections",
|
||||
"limits": "1 CPU, 512 MiB; fresh container and history per case",
|
||||
"rss": "VmRSS from /proc/1/status every 250 ms (sampled peak)",
|
||||
"latency": "successful requests only; errors counted separately; closed-loop workload",
|
||||
},
|
||||
Runs: make([]runResult, 0, len(histories)*len(concurrencies)*(*repeats)),
|
||||
row := phase(c, path, *rate, *duration, *maxFlight, *label)
|
||||
b, e := json.MarshalIndent(row, "", " ")
|
||||
if e != nil {
|
||||
panic(e)
|
||||
}
|
||||
for _, history := range histories {
|
||||
for _, concurrency := range concurrencies {
|
||||
for repetition := 1; repetition <= *repeats; repetition++ {
|
||||
row, err := runCase(*image, history, concurrency, repetition, *duration)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
data.Runs = append(data.Runs, row)
|
||||
if err := save(*output, data); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
encoded, _ := json.Marshal(row)
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -17,6 +18,8 @@ import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
)
|
||||
|
||||
var messageKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type ChatHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
@@ -176,6 +179,12 @@ func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
keyValues := r.Header.Values("Idempotency-Key")
|
||||
if len(keyValues) != 1 || !messageKeyPattern.MatchString(keyValues[0]) {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid idempotency key"))
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateMessage
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
@@ -187,9 +196,10 @@ func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
IdempotencyKey: keyValues[0],
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
|
||||
@@ -76,6 +76,7 @@ func (s *server) Stop(ctx context.Context) error {
|
||||
s.ready.Store(false)
|
||||
if err := s.server.Shutdown(ctx); err != nil {
|
||||
slog.Error("rest server shutdown failed", "error", err)
|
||||
_ = s.server.Close()
|
||||
return err
|
||||
}
|
||||
slog.Info("rest server shutdown successfully")
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// The explicit runner supplies a newly created database; never alter the API database.
|
||||
func TestIdempotencyTransactionAndExpiry(t *testing.T) {
|
||||
database := os.Getenv("TEST_DATABASE_NAME")
|
||||
if database == "" {
|
||||
t.Skip("run make test-storage for an isolated PostgreSQL database")
|
||||
}
|
||||
if database == os.Getenv("POSTGRES_DATABASE") {
|
||||
t.Fatal("test database must differ from application database")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Postgres.Database = database
|
||||
cfg.Postgres.RunMigrations = true
|
||||
if err = migrator.New(cfg).Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := postgres.New(cfg.Postgres)
|
||||
defer pool.Close()
|
||||
repo := NewMessagesRepo(pool)
|
||||
user, chat := uuid.New(), uuid.New()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO users(id,name,username,password_hash) VALUES($1,'Synthetic','atomic_test','unused')`, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Atomic test')`, chat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, chat, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := dto.CreateMessage{ChatID: chat, SenderID: user, Text: "atomic", IdempotencyKey: "atomic-key"}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Rollback(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var messages, keys int
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 0 || keys != 0 {
|
||||
t.Fatalf("rollback left %d messages, %d keys", messages, keys)
|
||||
}
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := repo.CreateIdempotentTx(ctx, tx, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Expire the test record only: no shortened production TTL and no wall-clock wait.
|
||||
if _, err = pool.Exec(ctx, `UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1`, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Text = "new after expiry"
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := repo.CreateIdempotentTx(ctx, tx, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.ID == second.ID {
|
||||
t.Fatal("expired key replayed old message")
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 2 || keys != 1 {
|
||||
t.Fatalf("expiry left %d messages, %d keys; want 2,1", messages, keys)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `CREATE FUNCTION reject_test_key() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.key='failure-key' THEN RAISE EXCEPTION 'synthetic failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test_key BEFORE INSERT ON message_idempotency FOR EACH ROW EXECUTE FUNCTION reject_test_key()`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.IdempotencyKey = "failure-key"
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err == nil {
|
||||
t.Fatal("expected injected failure")
|
||||
}
|
||||
if err = tx.Rollback(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 2 || keys != 1 {
|
||||
t.Fatal("failed result persisted a side effect")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DROP TRIGGER reject_test_key ON message_idempotency; DROP FUNCTION reject_test_key()`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
|
||||
t.Fatal("transient failure was cached", err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Log("rollback removed both side effect and key; expired key created one new message")
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
@@ -22,16 +25,43 @@ func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
|
||||
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
// CreateIdempotentTx serializes only requests sharing an idempotency scope.
|
||||
// The transaction commits both the message and its replay record, or neither.
|
||||
func (r *MessagesRepo) CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error) {
|
||||
scope := req.SenderID.String() + ":POST:" + req.ChatID.String() + ":" + req.IdempotencyKey
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, scope); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to lock message key")
|
||||
}
|
||||
return nil
|
||||
hash := sha256.Sum256([]byte(req.Text)) // text is the complete lab3 request model
|
||||
var storedHash []byte
|
||||
var messageID uuid.UUID
|
||||
err := tx.QueryRow(ctx, `SELECT request_hash, message_id FROM message_idempotency
|
||||
WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`,
|
||||
req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&storedHash, &messageID)
|
||||
if err == nil {
|
||||
if !bytes.Equal(hash[:], storedHash) {
|
||||
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
|
||||
}
|
||||
return scanMessage(tx.QueryRow(ctx, `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE id=$1`, messageID))
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, apperr.WrapPostgres(err, "failed to read message key")
|
||||
}
|
||||
message := dto.Message{ID: uuid.New(), ChatID: req.ChatID, SenderID: req.SenderID, Text: req.Text, CreatedAt: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`,
|
||||
message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
|
||||
return nil, apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return nil, apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at)
|
||||
VALUES($1,'POST',$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
|
||||
ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,
|
||||
message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at`, req.SenderID, req.ChatID, req.IdempotencyKey, hash[:], message.ID); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to save message key")
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
|
||||
@@ -15,9 +15,10 @@ type Message struct {
|
||||
}
|
||||
|
||||
type CreateMessage struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
IdempotencyKey string
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
type MessageFilters struct {
|
||||
|
||||
@@ -3,7 +3,9 @@ package encrypting
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -30,13 +32,13 @@ func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, err
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
// EncryptSecretUsingSum256 hashes a high-entropy session token, not a password.
|
||||
func (e *encryptor) EncryptSecretUsingSum256(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(res), nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
@@ -47,11 +49,24 @@ func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password strin
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
if payload, ok := strings.CutPrefix(hash, "sha256:"); ok {
|
||||
stored, err := hex.DecodeString(payload)
|
||||
if err != nil || len(stored) != sha256.Size || subtle.ConstantTimeCompare(stored, sum[:]) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Preserve existing lab2/lab3 sessions across a rolling deployment.
|
||||
// Passwords continue to use Argon2id; only old random-token fingerprints use this fallback.
|
||||
if strings.HasPrefix(hash, "$2") {
|
||||
if err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:]))); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionFingerprints(t *testing.T) {
|
||||
e := New()
|
||||
ctx := context.Background()
|
||||
token := "synthetic-high-entropy-session-value"
|
||||
hash, err := e.EncryptSecretUsingSum256(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, hash, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"sha256:00", "sha256:invalid", "unknown"} {
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, bad, token) == nil {
|
||||
t.Fatal("accepted malformed fingerprint")
|
||||
}
|
||||
}
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, hash, token+"x") == nil {
|
||||
t.Fatal("accepted wrong token")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
legacy, err := bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(sum[:])), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, string(legacy), token); err != nil {
|
||||
t.Fatal("legacy session rejected", err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if e.CompareHashAndSecretUsingSum256(canceled, hash, token) == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,16 @@ func Token(r *http.Request) (string, bool) {
|
||||
return token, true
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func WithVerifiedSession(r *http.Request, data *dto.UserDataInToken) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, *data))
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
if data, ok := r.Context().Value(sessionContextKey{}).(dto.UserDataInToken); ok {
|
||||
return &data, nil
|
||||
}
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
|
||||
@@ -39,12 +39,13 @@ func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
|
||||
|
||||
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := a.verifySession(r); err != nil {
|
||||
data, err := a.verifySession(r)
|
||||
if err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +62,7 @@ func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, nex
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, u))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type sessionVerifier struct {
|
||||
calls int
|
||||
data dto.UserDataInToken
|
||||
err error
|
||||
}
|
||||
|
||||
func (v *sessionVerifier) VerifySession(context.Context, dto.Token) (*dto.UserDataInToken, error) {
|
||||
v.calls++
|
||||
return &v.data, v.err
|
||||
}
|
||||
|
||||
func TestVerifiedSessionIsRequestScoped(t *testing.T) {
|
||||
verifier := &sessionVerifier{data: dto.UserDataInToken{UserID: uuid.New()}}
|
||||
middleware := NewAuthMiddleware(verifier)
|
||||
handled := 0
|
||||
handler := middleware.WithPrivateAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// A nil provider is intentional: the handler must use the verified request identity.
|
||||
data, err := framework.ParseToken(r, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data.UserID != verifier.data.UserID {
|
||||
t.Fatal("verified identity changed")
|
||||
}
|
||||
handled++
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
for range 2 {
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 204 {
|
||||
t.Fatal(recorder.Code)
|
||||
}
|
||||
}
|
||||
if verifier.calls != 2 || handled != 2 {
|
||||
t.Fatal("session verification must run for every request")
|
||||
}
|
||||
verifier.err = apperr.New(apperr.CodeUnauthorized, "revoked session")
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 401 || handled != 2 {
|
||||
t.Fatal("revocation was bypassed by cached request identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingTokenDoesNotCallSessionStore(t *testing.T) {
|
||||
verifier := &sessionVerifier{err: errors.New("must not be called")}
|
||||
handler := NewAuthMiddleware(verifier).WithPrivateAccess(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("handler called without a token") }))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/private", nil))
|
||||
if recorder.Code != 401 || verifier.calls != 0 {
|
||||
t.Fatal("missing token was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func Instance(id string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ type chatsRepo interface {
|
||||
}
|
||||
|
||||
type messagesRepo interface {
|
||||
Create(ctx context.Context, req dto.Message) error
|
||||
CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error)
|
||||
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
|
||||
}
|
||||
|
||||
@@ -169,18 +169,13 @@ func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.M
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message := dto.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: req.ChatID,
|
||||
SenderID: req.SenderID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
if err := c.messagesRepo.Create(ctx, message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
var message *dto.Message
|
||||
err := c.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
var err error
|
||||
message, err = c.messagesRepo.CreateIdempotentTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
return message, err
|
||||
}
|
||||
|
||||
func (c *Chat) ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error) {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
method TEXT NOT NULL CHECK (method = 'POST'),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
key TEXT NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
request_hash BYTEA NOT NULL,
|
||||
message_id UUID NOT NULL REFERENCES messages(id),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (user_id, method, chat_id, key)
|
||||
);
|
||||
CREATE INDEX message_idempotency_expiry ON message_idempotency(expires_at);
|
||||
|
||||
---- create above / drop below ----
|
||||
DROP TABLE message_idempotency;
|
||||
+76
-30
@@ -3,57 +3,89 @@ package tests
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
controller "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
|
||||
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"time"
|
||||
)
|
||||
|
||||
type apiClient struct {
|
||||
handler http.Handler
|
||||
baseURL string
|
||||
prefix string
|
||||
tokens map[string]string
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
status int
|
||||
requestID string
|
||||
body []byte
|
||||
status int
|
||||
requestID string
|
||||
instanceID string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func newAPI(t *testing.T) *apiClient {
|
||||
t.Helper()
|
||||
router := controller.NewRouter()
|
||||
users := inmemory2.NewUserCache()
|
||||
chats := inmemory2.NewChatCache(users)
|
||||
messages := inmemory2.NewMessageCache(chats)
|
||||
base := controller.NewBaseHandler(router)
|
||||
controller.NewAuthHandler(base, users).RegisterRoutes()
|
||||
controller.NewChatHandler(base, users, chats, messages).RegisterRoutes()
|
||||
|
||||
return &apiClient{handler: router}
|
||||
base := os.Getenv("TEST_BASE_URL")
|
||||
if base == "" {
|
||||
base = "http://localhost:18080"
|
||||
}
|
||||
return &apiClient{baseURL: strings.TrimRight(base, "/"), prefix: uuid.NewString()[:8] + "_", tokens: map[string]string{}}
|
||||
}
|
||||
|
||||
func (api *apiClient) request(t *testing.T, method, path, userID, body string) apiResponse {
|
||||
return api.requestKey(t, method, path, userID, body, uuid.NewString())
|
||||
}
|
||||
func (api *apiClient) requestKey(t *testing.T, method, path, userID, body, key string) apiResponse {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
response, err := api.send(method, path, userID, body, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
func (api *apiClient) send(method, path, userID, body, key string) (apiResponse, error) {
|
||||
if path == "/api/v1/users" {
|
||||
var fields map[string]any
|
||||
if json.Unmarshal([]byte(body), &fields) == nil {
|
||||
if name, ok := fields["username"].(string); ok {
|
||||
fields["username"] = api.prefix + name
|
||||
data, err := json.Marshal(fields)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
body = string(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequest(method, api.baseURL+path, strings.NewReader(body))
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if userID != "" {
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
req.Header.Set("Authorization", "Bearer "+api.tokens[userID])
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
api.handler.ServeHTTP(recorder, req)
|
||||
resp := recorder.Result()
|
||||
defer resp.Body.Close()
|
||||
requestID := resp.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
return apiResponse{status: resp.StatusCode, requestID: requestID, body: recorder.Body.Bytes()}
|
||||
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
return apiResponse{}, fmt.Errorf("running lab3 stand required: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
data, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return apiResponse{}, err
|
||||
}
|
||||
requestID, instanceID := response.Header.Get("X-Request-Id"), response.Header.Get("X-Instance-Id")
|
||||
if requestID == "" || instanceID == "" {
|
||||
return apiResponse{}, fmt.Errorf("%s %s: HTTP %d missing response identity", method, path, response.StatusCode)
|
||||
}
|
||||
return apiResponse{status: response.StatusCode, requestID: requestID, instanceID: instanceID, body: data}, nil
|
||||
}
|
||||
|
||||
func jsonString(t *testing.T, value any) string {
|
||||
@@ -98,7 +130,7 @@ func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string
|
||||
func (api *apiClient) createUser(t *testing.T, username string) string {
|
||||
t.Helper()
|
||||
resp := api.request(t, http.MethodPost, "/api/v1/users", "", jsonString(t, map[string]string{
|
||||
"username": username, "display_name": username,
|
||||
"username": username, "display_name": username, "password": "Synthetic-password-123",
|
||||
}))
|
||||
var user struct {
|
||||
ID string `json:"id"`
|
||||
@@ -107,6 +139,20 @@ func (api *apiClient) createUser(t *testing.T, username string) string {
|
||||
if user.ID == "" {
|
||||
t.Fatal("created user has no ID")
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodPost, api.baseURL+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth(api.prefix+username, "Synthetic-password-123")
|
||||
sessionResp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sessionResp.Body.Close()
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err = json.NewDecoder(sessionResp.Body).Decode(&session); err != nil || sessionResp.StatusCode != 201 || session.Token == "" {
|
||||
t.Fatalf("login failed: status %d, error %v", sessionResp.StatusCode, err)
|
||||
}
|
||||
api.tokens[user.ID] = session.Token
|
||||
return user.ID
|
||||
}
|
||||
|
||||
@@ -177,7 +223,7 @@ func TestEmptyMessage(t *testing.T) {
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
api := newAPI(t)
|
||||
api.createUser(t, "alice")
|
||||
resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice"}`)
|
||||
resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice","password":"Synthetic-password-123"}`)
|
||||
assertError(t, resp, http.StatusConflict, "conflict")
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ package tests
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -31,7 +31,8 @@ func postMessage(client *http.Client, endpoint, userID, text string) (createdMes
|
||||
return createdMessage{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
req.Header.Set("Authorization", "Bearer "+userID)
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return createdMessage{}, err
|
||||
@@ -65,9 +66,7 @@ func TestConcurrentMessages(t *testing.T) {
|
||||
users[i] = api.createUser(t, fmt.Sprintf("user%02d", i))
|
||||
}
|
||||
chatID := api.createChat(t, users[0], users...)
|
||||
server := httptest.NewServer(api.handler)
|
||||
t.Cleanup(server.Close)
|
||||
endpoint := server.URL + "/api/v1/chats/" + chatID + "/messages"
|
||||
endpoint := api.baseURL + "/api/v1/chats/" + chatID + "/messages"
|
||||
|
||||
type result struct {
|
||||
message createdMessage
|
||||
@@ -90,7 +89,7 @@ func TestConcurrentMessages(t *testing.T) {
|
||||
<-start
|
||||
for j := range messagesPerClient {
|
||||
text := fmt.Sprintf("client-%02d-message-%02d", workerID, j)
|
||||
message, err := postMessage(client, endpoint, userID, text)
|
||||
message, err := postMessage(client, endpoint, api.tokens[userID], text)
|
||||
results <- result{message: message, wantSenderID: userID, wantText: text, err: err}
|
||||
}
|
||||
}(i, userID)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIdempotencyContract(t *testing.T) {
|
||||
api := newAPI(t)
|
||||
alice := api.createUser(t, "alice")
|
||||
bob := api.createUser(t, "bob")
|
||||
eve := api.createUser(t, "eve")
|
||||
chat := api.createChat(t, alice, alice, bob)
|
||||
other := api.createChat(t, alice, alice)
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
for _, key := range []string{"", "bad key", "кириллица", string(make([]byte, 129))} {
|
||||
// NUL cannot be sent by net/http: use an overlength ASCII key instead.
|
||||
if len(key) == 129 {
|
||||
key = fmt.Sprintf("%0129d", 1)
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 400, "invalid_request")
|
||||
}
|
||||
key := uuid.NewString()
|
||||
first := api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key)
|
||||
var want map[string]any
|
||||
decodeOK(t, first, 201, &want)
|
||||
var got map[string]any
|
||||
decodeOK(t, api.requestKey(t, "POST", path, alice, `{ "text" : "hello" }`, key), 201, &got)
|
||||
if jsonString(t, want) != jsonString(t, got) {
|
||||
t.Fatal("replay changed message")
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"changed"}`, key), 409, "conflict")
|
||||
assertError(t, api.requestKey(t, "POST", path, eve, `{"text":"hello"}`, key), 404, "not_found")
|
||||
for _, tc := range []struct{ user, path string }{{bob, path}, {alice, "/api/v1/chats/" + other + "/messages"}} {
|
||||
var msg map[string]any
|
||||
decodeOK(t, api.requestKey(t, "POST", tc.path, tc.user, `{"text":"hello"}`, key), 201, &msg)
|
||||
if msg["id"] == want["id"] {
|
||||
t.Fatal("scope not isolated")
|
||||
}
|
||||
}
|
||||
resp := api.request(t, http.MethodDelete, "/api/v1/auth/sessions/current", alice, "")
|
||||
if resp.status != 204 {
|
||||
t.Fatal(resp.status)
|
||||
}
|
||||
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 401, "unauthorized")
|
||||
}
|
||||
func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) {
|
||||
api := newAPI(t)
|
||||
user := api.createUser(t, "alice")
|
||||
chat := api.createChat(t, user, user)
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
key := uuid.NewString()
|
||||
const count = 32
|
||||
type result struct {
|
||||
response apiResponse
|
||||
err error
|
||||
}
|
||||
responses := make(chan result, count)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for range count {
|
||||
wg.Go(func() {
|
||||
<-start
|
||||
response, err := api.send("POST", path, user, `{"text":"one logical message"}`, key)
|
||||
responses <- result{response: response, err: err}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(responses)
|
||||
instances := map[string]bool{}
|
||||
var id string
|
||||
for result := range responses {
|
||||
if result.err != nil {
|
||||
t.Fatal(result.err)
|
||||
}
|
||||
resp := result.response
|
||||
var msg struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
decodeOK(t, resp, 201, &msg)
|
||||
if id != "" && id != msg.ID {
|
||||
t.Fatal("duplicate side effect")
|
||||
}
|
||||
id = msg.ID
|
||||
instances[resp.instanceID] = true
|
||||
}
|
||||
if len(instances) < 2 {
|
||||
t.Fatalf("need at least 2 real API replicas, observed %d", len(instances))
|
||||
}
|
||||
var page struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
}
|
||||
decodeOK(t, api.request(t, "GET", path, user, ""), 200, &page)
|
||||
if len(page.Items) != 1 || page.Items[0].ID != id {
|
||||
t.Fatalf("history contains %d messages", len(page.Items))
|
||||
}
|
||||
t.Logf("%d requests across %d replicas created exactly one message", count, len(instances))
|
||||
}
|
||||
Reference in New Issue
Block a user