This commit is contained in:
Vladislav Kunetskiy
2026-10-15 20:52:43 +03:00
parent 4300d49c20
commit 4e84354642
125 changed files with 12049 additions and 2120 deletions
+12
View File
@@ -12,6 +12,12 @@ include-auto-generated: false
log-level: info
packages:
mtusi-messenger/internal/platform/cache:
config:
all: true
mtusi-messenger/internal/storage/redis:
config:
all: true
mtusi-messenger/internal/service/user:
config:
all: true
@@ -21,3 +27,9 @@ packages:
mtusi-messenger/internal/service/message:
config:
all: true
mtusi-messenger/internal/service/session:
config:
all: true
mtusi-messenger/internal/transport/rest:
config:
all: true
+8 -9
View File
@@ -17,7 +17,11 @@ COPY . .
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -buildvcs=false -tags timetzdata \
-ldflags="-s -w -X main.version=${VERSION}" \
-o /out/messenger ./cmd/messenger
-o /out/messenger ./cmd/messenger \
&& CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
go build -trimpath -buildvcs=false -tags timetzdata \
-ldflags="-s -w -X main.version=${VERSION}" \
-o /out/migrate ./cmd/migrate
FROM alpine:${ALPINE_VERSION} AS runtime
RUN apk add --no-cache ca-certificates wget \
@@ -25,18 +29,13 @@ RUN apk add --no-cache ca-certificates wget \
&& adduser -S -D -H -u 10001 -G app app
COPY --from=build --chown=10001:10001 /out/messenger /usr/local/bin/messenger
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_READ_HEADER_TIMEOUT=10s \
APP_SHUTDOWN_TIMEOUT=10s \
APP_LOG_LEVEL=info \
APP_LOG_FORMAT=json
COPY --from=build --chown=10001:10001 /out/migrate /usr/local/bin/migrate
COPY --chown=10001:10001 config/dev/config.yaml /etc/messenger/dev/config.yaml
USER 10001:10001
EXPOSE 8080
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/live" || exit 1
CMD wget -q -O /dev/null "http://127.0.0.1:${SERVER_PORT:-8080}/health/live" || exit 1
ENTRYPOINT ["/usr/local/bin/messenger"]
+83 -12
View File
@@ -9,13 +9,19 @@ import (
"os"
"os/signal"
"syscall"
"time"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/health"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/platform/cache"
"mtusi-messenger/internal/platform/token"
"mtusi-messenger/internal/service/chat"
"mtusi-messenger/internal/service/message"
"mtusi-messenger/internal/service/session"
"mtusi-messenger/internal/service/user"
"mtusi-messenger/internal/storage/memory"
"mtusi-messenger/internal/storage/postgres"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/transport/rest"
)
@@ -41,16 +47,61 @@ func main() {
}
func run(cfg config.Config, log *slog.Logger) error {
store := memory.NewStore()
userService := user.NewService(store.Users())
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
store, err := postgres.New(ctx, cfg.Postgres)
if err != nil {
return fmt.Errorf("connect database: %w", err)
}
defer store.Close()
redisCache, err := connectRedis(cfg.Redis)
if err != nil {
return err
}
defer func() { _ = redisCache.Close() }()
sessionRepo := session.Repository(store.Sessions())
chatRepo := chat.Repository(store.Chats())
pingers := []health.Pinger{store}
if cfg.Redis.Enabled {
if cfg.Cache.Enabled {
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{
LockTTL: cfg.Cache.LockTTL,
WaitTimeout: cfg.Cache.LockWaitTimeout,
}, log)
if err != nil {
return fmt.Errorf("build distributed cache: %w", err)
}
chatRepo = storageredis.NewChatRepository(
store.Chats(),
distributed,
cfg.Cache.ChatListTTL,
log,
)
}
log.Info("redis cache enabled", slog.String("host", cfg.Redis.Host), slog.Int("port", cfg.Redis.Port))
}
ttl := time.Duration(cfg.Session.TTLSeconds) * time.Second
sessionService := session.NewService(sessionRepo, token.New(), ttl)
router, err := rest.NewRouter(
rest.NewHandler(
userService,
chat.NewService(store.Chats()),
user.NewService(store.Users()),
chat.NewService(chatRepo),
message.NewService(store.Messages()),
health.New(pingers...),
sessionService,
),
rest.NewSecurityHandler(userService),
rest.NewSecurityHandler(sessionService),
log,
)
if err != nil {
@@ -60,12 +111,9 @@ func run(cfg config.Config, log *slog.Logger) error {
server := &http.Server{
Addr: cfg.Addr(),
Handler: router,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout,
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
errc := make(chan error, 1)
go func() {
@@ -88,9 +136,9 @@ func run(cfg config.Config, log *slog.Logger) error {
case <-ctx.Done():
}
log.Info("shutdown signal received", slog.Duration("timeout", cfg.ShutdownTimeout))
log.Info("shutdown signal received", slog.Duration("timeout", cfg.Server.ShutdownTimeout))
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
@@ -101,3 +149,26 @@ func run(cfg config.Config, log *slog.Logger) error {
return nil
}
func connectRedis(cfg config.Redis) (cache.LockStore, error) {
if !cfg.Enabled {
return cache.NoOpCache{}, nil
}
client, err := cache.NewRedis(cache.RedisConfig{
Host: cfg.Host,
Port: cfg.Port,
Password: cfg.Password,
DB: cfg.DB,
MaxRetries: cfg.MaxRetries,
DialTimeout: cfg.DialTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
PoolSize: cfg.PoolSize,
})
if err != nil {
return nil, fmt.Errorf("connect redis: %w", err)
}
return client, nil
}
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"os"
"github.com/pressly/goose/v3"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/storage/postgres/migrations"
_ "github.com/jackc/pgx/v5/stdlib"
)
func main() {
log := logger.New()
if err := run(os.Args[1:]); err != nil {
log.Error("migrate failed", slog.Any("error", err))
os.Exit(1)
}
}
func run(args []string) error {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("load config: %w", err)
}
slog.SetDefault(logger.New(
logger.WithLevel(cfg.SlogLevel()),
logger.WithFormat(cfg.LoggerFormat()),
))
command := "up"
if len(args) > 0 {
command = args[0]
}
db, err := sql.Open("pgx", cfg.Postgres.DSN())
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer func() { _ = db.Close() }()
pingCtx, cancel := context.WithTimeout(context.Background(), cfg.Postgres.ConnectTimeout)
defer cancel()
if err := db.PingContext(pingCtx); err != nil {
return fmt.Errorf("ping database: %w", err)
}
goose.SetBaseFS(migrations.FS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("set dialect: %w", err)
}
if err := goCommand(db, command); err != nil {
return err
}
return nil
}
func goCommand(db *sql.DB, command string) error {
switch command {
case "up":
return goose.Up(db, ".")
case "up-by-one":
return goose.UpByOne(db, ".")
case "down":
return goose.Down(db, ".")
case "status":
return goose.Status(db, ".")
case "version":
return goose.Version(db, ".")
case "redo":
return goose.Redo(db, ".")
default:
return errors.New("unknown command: " + command + " (up, up-by-one, down, status, version, redo)")
}
}
+47
View File
@@ -0,0 +1,47 @@
env: dev
server:
host: 0.0.0.0
port: 8080
read_header_timeout: 10s
shutdown_timeout: 10s
log:
level: info
format: json
postgres:
host: localhost
port: 5432
database: messenger
user: messenger
# Dev default for a local run without environment overrides; POSTGRES_PASSWORD wins.
password: messenger
ssl_mode: disable
max_conns: 10
min_conns: 1
max_conn_lifetime: 1h
max_conn_idle_time: 30m
connect_timeout: 5s
query_timeout: 5s
redis:
enabled: true
host: localhost
port: 6379
db: 0
# -1 disables go-redis retries; 0 keeps the library default (3 retries).
max_retries: -1
dial_timeout: 300ms
read_timeout: 200ms
write_timeout: 200ms
pool_size: 10
cache:
enabled: true
chat_list_ttl: 5m
lock_ttl: 10s
lock_wait_timeout: 2s
session:
ttl_seconds: 3600
+104
View File
@@ -0,0 +1,104 @@
name: mtusi-messenger-lab2
x-app: &app
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab2
services:
postgres:
image: postgres:18-alpine@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
ports:
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres18-data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
start_period: 5s
restart: unless-stopped
redis:
image: redis:7.4-alpine
command:
- redis-server
- --appendonly
- "yes"
- --appendfsync
- everysec
- --save
- "60"
- "1"
ports:
- "127.0.0.1:${REDIS_PORT:-6379}:6379"
volumes:
- redis7-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 10
start_period: 3s
restart: unless-stopped
migrate:
<<: *app
entrypoint: ["/usr/local/bin/migrate"]
command: ["up"]
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
depends_on:
postgres:
condition: service_healthy
restart: "no"
api:
<<: *app
env_file:
- path: .env
required: false
environment:
APP_CONFIG: /etc/messenger/dev/config.yaml
POSTGRES_HOST: postgres
POSTGRES_PORT: "5432"
POSTGRES_DATABASE: ${POSTGRES_DB:-messenger}
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
POSTGRES_SSL_MODE: disable
REDIS_ENABLED: "${REDIS_ENABLED:-true}"
REDIS_HOST: redis
REDIS_PORT: "6379"
CACHE_ENABLED: "${CACHE_ENABLED:-true}"
ports:
- "127.0.0.1:${SERVER_PORT:-8080}:8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
interval: 10s
timeout: 3s
retries: 5
start_period: 5s
restart: unless-stopped
volumes:
postgres18-data:
name: mtusi-messenger-lab2-postgres18-data
redis7-data:
name: mtusi-messenger-lab2-redis7-data
+11
View File
@@ -0,0 +1,11 @@
# API cache performance experiment
# generated: 2026-10-09T21:41:31Z
running trial 1, cache=False, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}
running trial 1, cache=True, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}
running trial 2, cache=False, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}
running trial 2, cache=True, requests=1000
{"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}
{"results": [{"requests": 1000, "workers": 8, "duration_seconds": 0.455918375053443, "rps": 2193.375074831716, "p50_ms": 3.3378750667907298, "p95_ms": 5.237665958702564, "p99_ms": 7.377958972938359, "trial": 1, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.424924207967706, "rps": 2353.360861182094, "p50_ms": 3.075250016991049, "p95_ms": 5.355541012249887, "p99_ms": 6.619499996304512, "trial": 1, "cache_enabled": true}, {"requests": 1000, "workers": 8, "duration_seconds": 0.5072490000165999, "rps": 1971.4183763147382, "p50_ms": 3.680104040540755, "p95_ms": 6.2174160266295075, "p99_ms": 8.554207975976169, "trial": 2, "cache_enabled": false}, {"requests": 1000, "workers": 8, "duration_seconds": 0.4116047500865534, "rps": 2429.51520795063, "p50_ms": 2.9188335174694657, "p95_ms": 5.480541964061558, "p99_ms": 7.245125016197562, "trial": 2, "cache_enabled": true}], "users": 4, "chats": 60, "sessions_cached_in_both_modes": true}
+36
View File
@@ -0,0 +1,36 @@
# Cache consistency evidence (track 1)
# generated: 2026-10-09T21:38:43Z
# redis: localhost:6379 db=1
=== RUN TestChatRepositorySuite
=== RUN TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated
=== RUN TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated
chat_repository_test.go:226: distributed lock: 100 concurrent cold reads -> 1 source load
=== RUN TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede
chat_repository_test.go:427: stampede demonstration: 100 concurrent reads -> 100 source loads
=== RUN TestChatRepositorySuite/TestCreateInvalidatesMemberCaches
=== RUN TestChatRepositorySuite/TestDeeperPagesBypassCache
=== RUN TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource
=== RUN TestChatRepositorySuite/TestFirstPageIsCached
=== RUN TestChatRepositorySuite/TestLimitIsPartOfCacheKey
=== RUN TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock
chat_repository_test.go:276: multi-instance distributed lock: 3 instances x 30 reads -> 1 source load
=== RUN TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData
=== RUN TestChatRepositorySuite/TestSourceErrorIsNotRetried
--- PASS: TestChatRepositorySuite (0.83s)
--- PASS: TestChatRepositorySuite/TestBrokenCacheEntryIsDroppedAndRepopulated (0.00s)
--- PASS: TestChatRepositorySuite/TestCacheUnavailableFallsBackToSource (0.00s)
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsAreDeduplicated (0.03s)
--- PASS: TestChatRepositorySuite/TestConcurrentColdReadsWithoutProtectionStampede (0.02s)
--- PASS: TestChatRepositorySuite/TestCreateInvalidatesMemberCaches (0.01s)
--- PASS: TestChatRepositorySuite/TestDeeperPagesBypassCache (0.00s)
--- PASS: TestChatRepositorySuite/TestEvictedCacheEntryReloadsFromSource (0.00s)
--- PASS: TestChatRepositorySuite/TestFirstPageIsCached (0.00s)
--- PASS: TestChatRepositorySuite/TestLimitIsPartOfCacheKey (0.00s)
--- PASS: TestChatRepositorySuite/TestMultipleInstancesShareDistributedLock (0.05s)
--- PASS: TestChatRepositorySuite/TestSlowLoaderBeyondCacheBudgetReturnsData (0.70s)
--- PASS: TestChatRepositorySuite/TestSourceErrorIsNotRetried (0.00s)
PASS
ok mtusi-messenger/internal/storage/redis 1.338s
? mtusi-messenger/internal/storage/redis/mocks [no test files]
+22
View File
@@ -0,0 +1,22 @@
# Cache latency experiment
# generated: 2026-10-06T15:53:09Z
go version go1.27.1 darwin/arm64
Darwin arm64
2026/10/06 18:53:10 OK 00001_init.sql (10.27ms)
2026/10/06 18:53:10 goose: successfully migrated database to version: 1
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=317.209µs p95=343.542µs p99=377.625µs
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=411.791µs p95=527.709µs p99=565.625µs
--- PASS: TestCacheLatencyExperiment (0.97s)
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=271.125µs p95=330.584µs p99=389.209µs
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=388µs p95=453.959µs p99=512.625µs
--- PASS: TestCacheLatencyExperiment (0.86s)
=== RUN TestCacheLatencyExperiment
cache_latency_experiment_test.go:83: baseline: requests=1000 source_loads=1000 p50=268.541µs p95=318.417µs p99=367.083µs
cache_latency_experiment_test.go:84: redis cache: requests=1000 source_loads=1 p50=408.833µs p95=473.125µs p99=541.042µs
--- PASS: TestCacheLatencyExperiment (0.88s)
PASS
ok mtusi-messenger/internal/storage/postgres 3.097s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
+26
View File
@@ -0,0 +1,26 @@
# Cache performance experiment
# generated: 2026-10-09T21:41:14Z
go version go1.27.1 darwin/arm64
Darwin arm64
2026/10/10 00:41:15 OK 00001_init.sql (10.03ms)
2026/10/10 00:41:15 OK 00002_user_chat_versions.sql (2.17ms)
2026/10/10 00:41:15 goose: successfully migrated database to version: 2
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.528s rps=6542 p50=7.490875ms p95=9.302792ms p99=10.779ms
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=851ms rps=11749 p50=4.192709ms p95=5.318916ms p99=5.905625ms
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=751ms rps=13320 p50=3.670958ms p95=4.644958ms p99=5.21475ms
--- PASS: TestCachePerformanceExperiment (3.50s)
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.415s rps=7066 p50=6.901958ms p95=8.697666ms p99=10.560416ms
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=846ms rps=11815 p50=4.033083ms p95=6.0305ms p99=6.963417ms
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12234 p50=3.999959ms p95=5.060959ms p99=5.802042ms
--- PASS: TestCachePerformanceExperiment (3.39s)
=== RUN TestCachePerformanceExperiment
cache_performance_experiment_test.go:115: baseline (no cache): requests=10000 concurrency=50 sql=10000 duration=1.511s rps=6618 p50=7.302667ms p95=9.420708ms p99=12.437917ms
cache_performance_experiment_test.go:116: redis cache (cold): requests=10000 concurrency=50 sql=1 duration=827ms rps=12093 p50=3.984125ms p95=5.655167ms p99=6.8085ms
cache_performance_experiment_test.go:117: redis cache (hot): requests=10000 concurrency=50 sql=0 duration=817ms rps=12247 p50=3.946959ms p95=5.363208ms p99=6.508458ms
--- PASS: TestCachePerformanceExperiment (3.55s)
PASS
ok mtusi-messenger/internal/storage/postgres 10.978s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files]
+8
View File
@@ -0,0 +1,8 @@
baseline: 6ms
after stop: 476ms
stop: n=1 max=476ms p95=476ms budget=2000ms
pause parallel: n=30 max=215ms p95=214ms budget=2000ms
create during pause: 201
after recovery: new chat visible, 5ms
lock keys without TTL: 0
PASS: redis outage handled within budget
+64
View File
@@ -0,0 +1,64 @@
# EXPLAIN (ANALYZE, BUFFERS)
## history_first_page
Limit (cost=0.29..5.40 rows=51 width=73) (actual time=0.007..0.012 rows=51.00 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..1002.85 rows=10000 width=73) (actual time=0.006..0.009 rows=51.00 loops=1)
Index Cond: (chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid)
Index Searches: 1
Buffers: shared hit=4
Planning:
Buffers: shared hit=44
Planning Time: 0.147 ms
Execution Time: 0.019 ms
## history_next_page
Limit (cost=0.29..7.71 rows=51 width=73) (actual time=0.004..0.010 rows=51.00 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.29..524.01 rows=3599 width=73) (actual time=0.004..0.008 rows=51.00 loops=1)
Index Cond: ((chat_id = '01a0f77e-9381-736f-9a2b-af3b1e1e87fd'::uuid) AND (ROW(created_at, id) > ROW('2026-10-01 11:44:23.146682+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
Index Searches: 1
Buffers: shared hit=4
Planning Time: 0.021 ms
Execution Time: 0.027 ms
## chats_list_for_member
Limit (cost=0.57..446.14 rows=51 width=70) (actual time=0.018..0.081 rows=51.00 loops=1)
Buffers: shared hit=309
-> Nested Loop (cost=0.57..87375.78 rows=10001 width=70) (actual time=0.018..0.079 rows=51.00 loops=1)
Buffers: shared hit=309
-> Index Scan using chats_created_at_id_idx on chats c (cost=0.29..554.24 rows=10001 width=38) (actual time=0.004..0.007 rows=51.00 loops=1)
Index Searches: 1
Buffers: shared hit=3
-> Index Only Scan using chat_members_user_id_chat_id_idx on chat_members visible (cost=0.29..0.36 rows=1 width=16) (actual time=0.001..0.001 rows=1.00 loops=51)
Index Cond: ((user_id = '01a0f77e-937a-7d1e-aacb-8909b9a65779'::uuid) AND (chat_id = c.id))
Heap Fetches: 51
Index Searches: 51
Buffers: shared hit=153
SubPlan 1
-> Aggregate (cost=8.31..8.32 rows=1 width=32) (actual time=0.001..0.001 rows=1.00 loops=51)
Buffers: shared hit=153
-> Index Only Scan using chat_members_pkey on chat_members m (cost=0.29..8.30 rows=1 width=16) (actual time=0.000..0.000 rows=1.00 loops=51)
Index Cond: (chat_id = c.id)
Heap Fetches: 51
Index Searches: 51
Buffers: shared hit=153
Planning:
Buffers: shared hit=95
Planning Time: 0.250 ms
Execution Time: 0.098 ms
## user_by_username
Index Scan using users_username_key on users (cost=0.29..8.30 rows=1 width=42) (actual time=0.005..0.005 rows=1.00 loops=1)
Index Cond: (username = 'bulk_5000'::text)
Index Searches: 1
Buffers: shared hit=3
Planning:
Buffers: shared hit=43
Planning Time: 0.085 ms
Execution Time: 0.008 ms
+42 -4
View File
@@ -7,30 +7,48 @@ require (
github.com/go-faster/jx v1.2.0
github.com/go-playground/validator/v10 v10.30.5
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/ogen-go/ogen v1.24.0
github.com/pressly/goose/v3 v3.28.0
github.com/redis/go-redis/v9 v9.22.0
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.12.1
go.uber.org/zap v1.28.0
go.uber.org/zap/exp v0.3.0
golang.org/x/crypto v0.57.0
golang.org/x/sync v0.23.0
)
require (
cel.dev/expr v0.25.2 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/brunoga/deep v1.3.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/clipperhouse/uax29/v2 v2.2.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/cubicdaiya/gonp v1.0.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dlclark/regexp2 v1.12.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-faster/yaml v0.4.6 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-sql-driver/mysql v1.10.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/cel-go v0.28.0 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jedib0t/go-pretty/v6 v6.7.8 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/knadh/koanf/maps v0.1.2 // indirect
github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect
github.com/knadh/koanf/providers/env v1.1.0 // indirect
@@ -42,41 +60,61 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/ncruces/go-sqlite3 v0.32.0 // indirect
github.com/ncruces/julianday v1.0.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect
github.com/pingcap/log v1.1.0 // indirect
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 // indirect
github.com/riza-io/grpc-go v0.2.0 // indirect
github.com/rs/zerolog v1.34.0 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/sqlc-dev/doubleclick v1.0.0 // indirect
github.com/sqlc-dev/sqlc v1.31.1 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tetratelabs/wazero v1.11.0 // indirect
github.com/vektra/mockery/v3 v3.8.0 // indirect
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yuin/goldmark v1.8.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a // indirect
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/term v0.46.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
tool (
github.com/ogen-go/ogen/cmd/ogen
github.com/sqlc-dev/sqlc/cmd/sqlc
github.com/vektra/mockery/v3
)
+152 -2
View File
@@ -1,18 +1,41 @@
cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs=
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/brunoga/deep v1.3.1 h1:bSrL6FhAZa6JlVv4vsi7Hg8SLwroDb1kgDERRVipBCo=
github.com/brunoga/deep v1.3.1/go.mod h1:GDV6dnXqn80ezsLSZ5Wlv1PdKAWAO4L5PnKYtv2dgaI=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY=
github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cubicdaiya/gonp v1.0.4 h1:ky2uIAJh81WiLcGKBVD5R7KsM/36W6IqqTy6Bo6rGws=
github.com/cubicdaiya/gonp v1.0.4/go.mod h1:iWGuP/7+JVTn02OWhRemVbMmG1DOUnmrGTYYACpOI0I=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
@@ -27,6 +50,10 @@ github.com/go-faster/jx v1.2.0 h1:T2YHJPrFaYu21fJtUxC9GzmluKu8rVIFDwwGBKTDseI=
github.com/go-faster/jx v1.2.0/go.mod h1:UWLOVDmMG597a5tBFPLIWJdUxz5/2emOpfsj9Neg0PE=
github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I=
github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -35,9 +62,15 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/cel-go v0.28.0 h1:KjSWstCpz/MN5t4a8gnGJNIYUsJRpdi/r97xWDphIQc=
github.com/google/cel-go v0.28.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -46,8 +79,20 @@ github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jedib0t/go-pretty/v6 v6.7.8 h1:BVYrDy5DPBA3Qn9ICT+PokP9cvCv1KaHv2i+Hc8sr5o=
github.com/jedib0t/go-pretty/v6 v6.7.8/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=
github.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
github.com/knadh/koanf/parsers/yaml v1.1.0 h1:3ltfm9ljprAHt4jxgeYLlFPmUaunuCgu1yILuTXRdM4=
@@ -62,8 +107,11 @@ github.com/knadh/koanf/providers/structs v1.0.0 h1:DznjB7NQykhqCar2LvNug3MuxEQsZ
github.com/knadh/koanf/providers/structs v1.0.0/go.mod h1:kjo5TFtgpaZORlpoJqcbeLowM2cINodv8kX+oFAeQ1w=
github.com/knadh/koanf/v2 v2.3.2 h1:Ee6tuzQYFwcZXQpc2MiVeC6qHMandf5SMUJJNoFp/c4=
github.com/knadh/koanf/v2 v2.3.2/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
@@ -77,16 +125,44 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/ncruces/go-sqlite3 v0.32.0 h1:hNBUXp88LrfQCsuyXLqWTbTUG35sUuktDsqhhgHvU20=
github.com/ncruces/go-sqlite3 v0.32.0/go.mod h1:MIWTK60ONDl0oVY073zYvJP21C3Dly6P9bxVpgkLwdQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
github.com/ogen-go/ogen v1.24.0 h1:NehBG/8s0JeM6jYHPJeFJntBG3cE/xQgZd1q8BchPNM=
github.com/ogen-go/ogen v1.24.0/go.mod h1:hcg4aTzLcu/MS1SGGahUriPBEOZB3c82RGIC6dYcdFU=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo=
github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0=
github.com/pingcap/errors v0.11.0/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee h1:/IDPbpzkzA97t1/Z1+C3KlxbevjMeaI6BQYxvivu4u8=
github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee/go.mod h1:X2r9ueLEUZgtx2cIogM0v4Zj5uvvzhuuiu7Pn8HzMPg=
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 h1:tdMsjOqUR7YXHoBitzdebTvOjs/swniBTOLy5XiMtuE=
github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86/go.mod h1:exzhVYca3WRtd6gclGNErRWb1qEgff3LYta0LvRmON4=
github.com/pingcap/log v1.1.0 h1:ELiPxACz7vdo1qAvvaWJg1NrYFoY6gqAh/+Uo6aXdD8=
github.com/pingcap/log v1.1.0/go.mod h1:DWQW5jICDR7UJh4HtxXSM20Churx4CQL0fwL/SoOSA4=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124 h1:zYmP5fBH+i2yhhU6f5uOol6zxHtR2/sD47BsJLfy0oU=
github.com/pingcap/tidb/pkg/parser v0.0.0-20260418072757-ce92298d1124/go.mod h1:zDLDsfNBU5+L6T4J9/OgWAHc/WZvMUjbpgHqQ/t3yKo=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.28.0 h1:D2M+iL31GmpZxSHOhX8mqyqAT3CXnokUmm0eKoSP+Vc=
github.com/pressly/goose/v3 v3.28.0/go.mod h1:v26MOuB8bL3kzzrt3Vqhb3R0PRVsl8hFQKdrht/L6Rk=
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
@@ -97,6 +173,8 @@ github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDc
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
@@ -112,16 +190,28 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/sqlc-dev/doubleclick v1.0.0 h1:2/OApfQ2eLgcfa/Fqs8WSMA6atH0G8j9hHbQIgMfAXI=
github.com/sqlc-dev/doubleclick v1.0.0/go.mod h1:ODHRroSrk/rr5neRHlWMSRijqOak8YmNaO3VAZCNl5Y=
github.com/sqlc-dev/sqlc v1.31.1 h1:+V+BjBJfFNPX/RFfL8eiZD9jk9lVJUEGGllWvnYNqbc=
github.com/sqlc-dev/sqlc v1.31.1/go.mod h1:6ZPww/Jd3G6MzJeW6NrqizjL+52vYNaaXP9yMeJ/Nao=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
github.com/vektra/mockery/v3 v3.8.0 h1:Tklqcx844iV8GtYziqJXam1a8RdcKip4UErMa66Nxps=
github.com/vektra/mockery/v3 v3.8.0/go.mod h1:K+L72OoFVizA9eWtO4L+kU65oylgreiJEJ57Gu8g9Ew=
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07 h1:mJdDDPblDfPe7z7go8Dvv1AJQDI3eQ/5xith3q2mFlo=
github.com/wasilibs/go-pgquery v0.0.0-20250409022910-10ac41983c07/go.mod h1:Ak17IJ037caFp4jpCw/iQQ7/W74Sqpb1YuKJU6HTKfM=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 h1:OvLBa8SqJnZ6P+mjlzc2K7PM22rRUPE1x32G9DTPrC4=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
@@ -131,10 +221,33 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
@@ -142,16 +255,22 @@ go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a h1:ovFr6Z0MNmU7nH8VaX5xqw+05ST2uO1exVfZPVqRC5o=
golang.org/x/exp v0.0.0-20260212183809-81e46e3db34a/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa h1:QSyA8ishJCyT21kER9KwNt0b7BM3iRK4x9QXhjN5Fdk=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -159,14 +278,45 @@ golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a h1:3Dnd1cDaZlB68lziofO+bJXpjOy8UfRv8Unt+yH8tQ4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.75.6 h1:yKk8qo+Di4gkmvRboK8ocCqH22FiUCR6jRy2OwtCRus=
modernc.org/libc v1.75.6/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg=
modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
+162 -16
View File
@@ -1,9 +1,13 @@
package config
import (
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
@@ -15,35 +19,134 @@ import (
"mtusi-messenger/internal/logger"
)
const envPrefix = "APP"
const (
configEnvKey = "APP_CONFIG"
envKey = "APP_ENV"
configName = "config"
defaultEnv = "dev"
configDir = "./config/"
)
type Config struct {
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
Server Server `mapstructure:"server"`
Log Log `mapstructure:"log"`
Postgres Postgres `mapstructure:"postgres"`
Redis Redis `mapstructure:"redis"`
Cache Cache `mapstructure:"cache"`
Session Session `mapstructure:"session"`
}
type Session struct {
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
}
type Redis struct {
Enabled bool `mapstructure:"enabled"`
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
}
type Cache struct {
Enabled bool `mapstructure:"enabled"`
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
}
type Server struct {
Host string `mapstructure:"host" validate:"required,hostname|ip"`
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
LogLevel string `mapstructure:"log_level" validate:"required,oneof=debug info warn error"`
LogFormat string `mapstructure:"log_format" validate:"required,oneof=json console"`
}
type Log struct {
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
Format string `mapstructure:"format" validate:"required,oneof=json console"`
}
type Postgres struct {
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Database string `mapstructure:"database" validate:"omitempty,min=1"`
User string `mapstructure:"user" validate:"omitempty,min=1"`
Password string `mapstructure:"password"`
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
}
func (p Postgres) DSN() string {
u := &url.URL{
Scheme: "postgres",
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
Path: "/" + p.Database,
}
if p.Password == "" {
u.User = url.User(p.User)
} else {
u.User = url.UserPassword(p.User, p.Password)
}
query := url.Values{}
query.Set("sslmode", p.SSLMode)
u.RawQuery = query.Encode()
return u.String()
}
var defaults = map[string]any{
"host": "0.0.0.0",
"port": 8080,
"read_header_timeout": "10s",
"shutdown_timeout": "10s",
"log_level": "info",
"log_format": "json",
"env": "dev",
"server.host": "0.0.0.0",
"server.port": 8080,
"server.read_header_timeout": "10s",
"server.shutdown_timeout": "10s",
"log.level": "info",
"log.format": "json",
"session.ttl_seconds": 3600,
"redis.enabled": false,
"redis.host": "localhost",
"redis.port": 6379,
"redis.db": 0,
"redis.max_retries": -1,
"redis.dial_timeout": "300ms",
"redis.read_timeout": "200ms",
"redis.write_timeout": "200ms",
"redis.pool_size": 10,
"cache.enabled": false,
"cache.chat_list_ttl": "5m",
"cache.lock_ttl": "10s",
"cache.lock_wait_timeout": "2s",
}
func Load() (Config, error) {
v := viper.New()
v.SetEnvPrefix(envPrefix)
if err := configureSource(v); err != nil {
return Config{}, err
}
v.AllowEmptyEnv(true)
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
for key, value := range defaults {
v.SetDefault(key, value)
for key := range defaults {
if err := v.BindEnv(key); err != nil {
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
}
}
var cfg Config
@@ -55,21 +158,64 @@ func Load() (Config, error) {
return Config{}, fmt.Errorf("validate config: %w", err)
}
if err := cfg.validateDependencies(); err != nil {
return Config{}, err
}
return cfg, nil
}
func (c Config) validateDependencies() error {
if c.Cache.Enabled && !c.Redis.Enabled {
return errors.New("validate config: cache.enabled requires redis.enabled")
}
return nil
}
func configureSource(v *viper.Viper) error {
for key, value := range defaults {
v.SetDefault(key, value)
}
v.SetConfigType("yaml")
if path := os.Getenv(configEnvKey); path != "" {
v.SetConfigFile(path)
} else {
env := os.Getenv(envKey)
if env == "" {
env = defaultEnv
}
v.SetConfigName(configName)
v.AddConfigPath(filepath.Join(configDir, env))
}
if err := v.ReadInConfig(); err != nil {
var notFound viper.ConfigFileNotFoundError
if errors.As(err, &notFound) {
return nil
}
return fmt.Errorf("read config: %w", err)
}
return nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
}
func (c Config) SlogLevel() slog.Level {
level, _ := logger.ParseLevel(c.LogLevel)
level, _ := logger.ParseLevel(c.Log.Level)
return level
}
func (c Config) LoggerFormat() logger.Format {
format, _ := logger.ParseFormat(c.LogFormat)
format, _ := logger.ParseFormat(c.Log.Format)
return format
}
@@ -89,5 +235,5 @@ func envName(field reflect.StructField) string {
return field.Name
}
return envPrefix + "_" + strings.ToUpper(key)
return strings.ToUpper(key)
}
+296 -137
View File
@@ -1,178 +1,274 @@
package config_test
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger"
)
type ConfigSuite struct {
suite.Suite
}
func TestConfigSuite(t *testing.T) {
suite.Run(t, new(ConfigSuite))
}
func (s *ConfigSuite) TestDefaults() {
func TestDefaults(t *testing.T) {
cfg, err := config.Load()
s.Require().NoError(err)
require.NoError(t, err)
s.Equal("0.0.0.0", cfg.Host)
s.Equal(8080, cfg.Port)
s.Equal(10*time.Second, cfg.ReadHeaderTimeout)
s.Equal(10*time.Second, cfg.ShutdownTimeout)
s.Equal("info", cfg.LogLevel)
s.Equal("json", cfg.LogFormat)
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
assert.Equal(t, 8080, cfg.Server.Port)
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "info", cfg.Log.Level)
assert.Equal(t, "json", cfg.Log.Format)
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
}
func (s *ConfigSuite) TestEnvOverridesDefaults() {
s.T().Setenv("APP_HOST", "127.0.0.1")
s.T().Setenv("APP_PORT", "9090")
s.T().Setenv("APP_READ_HEADER_TIMEOUT", "3s")
s.T().Setenv("APP_SHUTDOWN_TIMEOUT", "30s")
s.T().Setenv("APP_LOG_LEVEL", "debug")
s.T().Setenv("APP_LOG_FORMAT", "console")
func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("SERVER_PORT", "9090")
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("LOG_LEVEL", "debug")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
s.Require().NoError(err)
require.NoError(t, err)
s.Equal("127.0.0.1", cfg.Host)
s.Equal(9090, cfg.Port)
s.Equal(3*time.Second, cfg.ReadHeaderTimeout)
s.Equal(30*time.Second, cfg.ShutdownTimeout)
s.Equal("debug", cfg.LogLevel)
s.Equal("console", cfg.LogFormat)
assert.Equal(t, "127.0.0.1", cfg.Server.Host)
assert.Equal(t, 9090, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
}
func (s *ConfigSuite) TestLoggerSettings() {
s.T().Setenv("APP_LOG_LEVEL", "warn")
s.T().Setenv("APP_LOG_FORMAT", "console")
cfg, err := config.Load()
s.Require().NoError(err)
level, err := logger.ParseLevel(cfg.LogLevel)
s.Require().NoError(err)
s.Equal(level, cfg.SlogLevel())
format, err := logger.ParseFormat(cfg.LogFormat)
s.Require().NoError(err)
s.Equal(format, cfg.LoggerFormat())
}
func (s *ConfigSuite) TestAddr() {
s.T().Setenv("APP_HOST", "0.0.0.0")
s.T().Setenv("APP_PORT", "8080")
cfg, err := config.Load()
s.Require().NoError(err)
s.Equal("0.0.0.0:8080", cfg.Addr())
}
func (s *ConfigSuite) TestAddrWithIPv6Host() {
s.T().Setenv("APP_HOST", "::1")
cfg, err := config.Load()
s.Require().NoError(err)
s.Equal("[::1]:8080", cfg.Addr())
}
func (s *ConfigSuite) TestInvalidValues() {
tests := map[string]struct {
env map[string]string
wantField string
wantTag string
}{
"пустой host": {
env: map[string]string{"APP_HOST": ""},
wantField: "APP_HOST",
wantTag: "required",
},
"host не адрес и не имя": {
env: map[string]string{"APP_HOST": "не адрес"},
wantField: "APP_HOST",
wantTag: "hostname|ip",
},
"порт ниже диапазона": {
env: map[string]string{"APP_PORT": "0"},
wantField: "APP_PORT",
wantTag: "required",
},
"порт выше диапазона": {
env: map[string]string{"APP_PORT": "65536"},
wantField: "APP_PORT",
wantTag: "max",
},
"нулевой read header timeout": {
env: map[string]string{"APP_READ_HEADER_TIMEOUT": "0s"},
wantField: "APP_READ_HEADER_TIMEOUT",
wantTag: "required",
},
"отрицательный shutdown timeout": {
env: map[string]string{"APP_SHUTDOWN_TIMEOUT": "-1s"},
wantField: "APP_SHUTDOWN_TIMEOUT",
wantTag: "gt",
},
"неизвестный уровень логирования": {
env: map[string]string{"APP_LOG_LEVEL": "trace"},
wantField: "APP_LOG_LEVEL",
wantTag: "oneof",
},
"неизвестный формат логирования": {
env: map[string]string{"APP_LOG_FORMAT": "xml"},
wantField: "APP_LOG_FORMAT",
wantTag: "oneof",
},
func TestDsnEncodesCredentials(t *testing.T) {
cfg := config.Postgres{
Host: "db",
Port: 5432,
Database: "app",
User: "user",
Password: "p@ss:w/rd",
SSLMode: "disable",
}
for name, tt := range tests {
s.Run(name, func() {
for key, value := range tt.env {
s.T().Setenv(key, value)
}
_, err := config.Load()
s.Require().Error(err)
var validationErrs validator.ValidationErrors
s.Require().ErrorAs(err, &validationErrs)
s.Require().Len(validationErrs, 1)
s.Equal(tt.wantField, validationErrs[0].Field())
s.Equal(tt.wantTag, validationErrs[0].Tag())
})
}
assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
}
func (s *ConfigSuite) TestUnparsableValues() {
func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}
func TestLoadsYAMLFile(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: secret
ssl_mode: disable
max_conns: 7
min_conns: 2
max_conn_lifetime: 2h
max_conn_idle_time: 10m
connect_timeout: 2s
query_timeout: 3s
`)
t.Setenv("APP_CONFIG", path)
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "10.0.0.1", cfg.Server.Host)
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
assert.Equal(t, "db", cfg.Postgres.Host)
assert.Equal(t, 5433, cfg.Postgres.Port)
assert.Equal(t, "app", cfg.Postgres.Database)
assert.Equal(t, int32(7), cfg.Postgres.MaxConns)
assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout)
}
func TestEnvOverridesYAML(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: file
ssl_mode: disable
`)
t.Setenv("APP_CONFIG", path)
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("POSTGRES_PASSWORD", "env")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, "env", cfg.Postgres.Password)
}
func TestSessionTTLFromContractEnv(t *testing.T) {
t.Setenv("SESSION_TTL_SECONDS", "2")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, 2, cfg.Session.TTLSeconds)
}
func TestInvalidValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"APP_PORT": "не-число"},
"timeout не длительность": {"APP_READ_HEADER_TIMEOUT": "быстро"},
"пустой server.host": {"SERVER_HOST": ""},
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"SERVER_PORT": "0"},
"порт выше диапазона": {"SERVER_PORT": "65536"},
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"LOG_LEVEL": "trace"},
"неизвестный log format": {"LOG_FORMAT": "xml"},
}
for name, env := range tests {
s.Run(name, func() {
t.Run(name, func(t *testing.T) {
for key, value := range env {
s.T().Setenv(key, value)
t.Setenv(key, value)
}
_, err := config.Load()
s.Require().Error(err)
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestInvalidPostgresValues(t *testing.T) {
path := writeConfig(t, `
env: dev
postgres:
host: db
port: 5432
database: messenger
user: messenger
ssl_mode: disable
max_conns: 10
`)
tests := map[string]map[string]string{
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
t.Setenv("APP_CONFIG", path)
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestUnparsableValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"SERVER_PORT": "не-число"},
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
})
}
}
func TestLoggerSettings(t *testing.T) {
t.Setenv("LOG_LEVEL", "warn")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
level, err := logger.ParseLevel(cfg.Log.Level)
require.NoError(t, err)
assert.Equal(t, level, cfg.SlogLevel())
format, err := logger.ParseFormat(cfg.Log.Format)
require.NoError(t, err)
assert.Equal(t, format, cfg.LoggerFormat())
}
func TestAddr(t *testing.T) {
t.Setenv("SERVER_HOST", "0.0.0.0")
t.Setenv("SERVER_PORT", "8080")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "0.0.0.0:8080", cfg.Addr())
}
func TestAddrWithIPv6Host(t *testing.T) {
t.Setenv("SERVER_HOST", "::1")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "[::1]:8080", cfg.Addr())
}
func TestLoadIsIndependentOfProcessState(t *testing.T) {
t.Setenv("APP_PORT", "7070")
t.Setenv("SERVER_PORT", "7070")
first, err := config.Load()
require.NoError(t, err)
@@ -180,5 +276,68 @@ func TestLoadIsIndependentOfProcessState(t *testing.T) {
second, err := config.Load()
require.NoError(t, err)
require.Equal(t, first, second)
assert.Equal(t, first, second)
}
func TestRedisDefaultsDisabled(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.False(t, cfg.Redis.Enabled)
assert.Equal(t, "localhost", cfg.Redis.Host)
assert.Equal(t, 6379, cfg.Redis.Port)
assert.Equal(t, -1, cfg.Redis.MaxRetries)
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
assert.False(t, cfg.Cache.Enabled)
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
}
func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("REDIS_ENABLED", "true")
t.Setenv("REDIS_HOST", "cache")
t.Setenv("REDIS_PORT", "6380")
t.Setenv("CACHE_ENABLED", "true")
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("CACHE_LOCK_TTL", "7s")
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
cfg, err := config.Load()
require.NoError(t, err)
assert.True(t, cfg.Redis.Enabled)
assert.Equal(t, "cache", cfg.Redis.Host)
assert.Equal(t, 6380, cfg.Redis.Port)
assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
}
func TestInvalidCacheTTL(t *testing.T) {
for _, key := range []string{
"CACHE_CHAT_LIST_TTL",
"CACHE_LOCK_TTL",
"CACHE_LOCK_WAIT_TIMEOUT",
} {
for _, value := range []string{"0s", "-1s"} {
t.Run(key+"/"+value, func(t *testing.T) {
t.Setenv(key, value)
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
})
}
}
}
func TestCacheRequiresRedis(t *testing.T) {
t.Setenv("CACHE_ENABLED", "true")
_, err := config.Load()
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
}
+14 -1
View File
@@ -30,7 +30,20 @@ func (d ChatDraft) Validate() error {
return err
}
if !slices.Contains(d.MemberIDs, d.CallerID) {
if len(d.MemberIDs) == 0 {
return fmt.Errorf("member_ids must not be empty: %w", ErrValidation)
}
seen := make(map[uuid.UUID]struct{}, len(d.MemberIDs))
for _, id := range d.MemberIDs {
if _, ok := seen[id]; ok {
return fmt.Errorf("member_ids contains duplicates: %w", ErrValidation)
}
seen[id] = struct{}{}
}
if _, ok := seen[d.CallerID]; !ok {
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
}
+8 -5
View File
@@ -3,9 +3,12 @@ package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("member does not exist")
ErrValidation = errors.New("validation failed")
ErrInvalidCursor = errors.New("invalid cursor")
ErrNotFound = errors.New("not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("member does not exist")
ErrValidation = errors.New("validation failed")
ErrInvalidCursor = errors.New("invalid cursor")
ErrConflict = errors.New("conflict")
ErrUnauthenticated = errors.New("unauthenticated")
ErrUnavailable = errors.New("temporarily unavailable")
)
+19
View File
@@ -0,0 +1,19 @@
package domain
import (
"time"
"github.com/google/uuid"
)
type Session struct {
Token string
ExpiresAt time.Time
User User
}
type NewSession struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
+22 -1
View File
@@ -1,6 +1,7 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
@@ -16,8 +17,28 @@ type User struct {
type UserDraft struct {
Username string
DisplayName string
Password string
}
func (d UserDraft) Validate() error {
return validateNotBlank("display_name", d.DisplayName)
if err := validateNotBlank("display_name", d.DisplayName); err != nil {
return err
}
if length := len([]rune(d.Password)); length < 12 || length > 128 {
return fmt.Errorf("password length must be between 12 and 128 code points: %w", ErrValidation)
}
return nil
}
type NewUser struct {
Username string
DisplayName string
PasswordHash string
}
type UserCredentials struct {
User User
PasswordHash string
}
+22 -1
View File
@@ -26,7 +26,28 @@ func TestUserDraftRejectsBlankDisplayName(t *testing.T) {
func TestUserDraftAcceptsVisibleName(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
assert.NoError(t, draft.Validate())
}
func TestUserDraftRejectsShortPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftRejectsTooLongPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 129)}
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
}
func TestUserDraftAcceptsMinimalPassword(t *testing.T) {
t.Parallel()
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 12)}
assert.NoError(t, draft.Validate())
}
+28
View File
@@ -0,0 +1,28 @@
package health
import (
"context"
"fmt"
)
type Pinger interface {
Ping(ctx context.Context) error
}
type Checker struct {
pingers []Pinger
}
func New(pingers ...Pinger) *Checker {
return &Checker{pingers: pingers}
}
func (c *Checker) Ping(ctx context.Context) error {
for _, pinger := range c.pingers {
if err := pinger.Ping(ctx); err != nil {
return fmt.Errorf("ping %T: %w", pinger, err)
}
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package health_test
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/health"
)
type stubPinger struct {
err error
}
func (s stubPinger) Ping(context.Context) error { return s.err }
func TestCheckerPassesWhenAllHealthy(t *testing.T) {
t.Parallel()
checker := health.New(stubPinger{}, stubPinger{})
require.NoError(t, checker.Ping(context.Background()))
}
func TestCheckerReturnsFirstFailure(t *testing.T) {
t.Parallel()
sentinel := errors.New("dependency down")
checker := health.New(stubPinger{}, stubPinger{err: sentinel}, stubPinger{err: errors.New("later")})
require.ErrorIs(t, checker.Ping(context.Background()), sentinel)
}
+31
View File
@@ -0,0 +1,31 @@
package cache
import (
"context"
"errors"
"time"
)
var ErrCacheMiss = errors.New("cache miss")
type Cache interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Delete(ctx context.Context, keys ...string) error
Ping(ctx context.Context) error
Close() error
}
type NoOpCache struct{}
func (NoOpCache) Get(context.Context, string) ([]byte, error) { return nil, ErrCacheMiss }
func (NoOpCache) Set(context.Context, string, []byte, time.Duration) error { return nil }
func (NoOpCache) Delete(context.Context, ...string) error { return nil }
func (NoOpCache) AcquireLock(context.Context, string, string, time.Duration) (bool, error) {
return true, nil
}
func (NoOpCache) ReleaseLock(context.Context, string, string) (bool, error) { return true, nil }
func (NoOpCache) LockHeld(context.Context, string) (bool, error) { return false, nil }
func (NoOpCache) Ping(context.Context) error { return nil }
func (NoOpCache) Close() error { return nil }
+31
View File
@@ -0,0 +1,31 @@
package cache_test
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/cache"
)
func TestNoOpCache(t *testing.T) {
t.Parallel()
ctx := t.Context()
store := cache.NoOpCache{}
require.NoError(t, store.Set(ctx, "key", []byte("value"), time.Minute))
_, err := store.Get(ctx, "key")
require.ErrorIs(t, err, cache.ErrCacheMiss)
require.NoError(t, store.Delete(ctx, "key"))
acquired, err := store.AcquireLock(ctx, "lock", "token", time.Second)
require.NoError(t, err)
require.True(t, acquired)
held, err := store.LockHeld(ctx, "lock")
require.NoError(t, err)
require.False(t, held)
released, err := store.ReleaseLock(ctx, "lock", "token")
require.NoError(t, err)
require.True(t, released)
require.NoError(t, store.Ping(ctx))
require.NoError(t, store.Close())
}
+307
View File
@@ -0,0 +1,307 @@
package cache
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log/slog"
mathrand "math/rand/v2"
"strconv"
"sync/atomic"
"time"
"golang.org/x/sync/singleflight"
)
const (
DefaultLockTTL = 10 * time.Second
DefaultWaitTimeout = 2 * time.Second
minLockTTL = time.Second
redisOpTimeout = 200 * time.Millisecond
releaseTimeout = 300 * time.Millisecond
)
type DistributedConfig struct {
LockTTL time.Duration
WaitTimeout time.Duration
}
type LockStore interface {
Cache
AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
ReleaseLock(ctx context.Context, key, token string) (bool, error)
LockHeld(ctx context.Context, key string) (bool, error)
}
type DistributedCache struct {
store LockStore
lockTTL time.Duration
waitTimeout time.Duration
log *slog.Logger
group singleflight.Group
}
var fallbackTokenCounter atomic.Uint64
func NewDistributed(store LockStore, cfg DistributedConfig, log *slog.Logger) (*DistributedCache, error) {
if cfg.LockTTL <= 0 {
cfg.LockTTL = DefaultLockTTL
}
if cfg.WaitTimeout <= 0 {
cfg.WaitTimeout = DefaultWaitTimeout
}
if cfg.LockTTL <= minLockTTL {
return nil, fmt.Errorf("cache: lock ttl %s must be greater than %s", cfg.LockTTL, minLockTTL)
}
if cfg.WaitTimeout > cfg.LockTTL {
return nil, fmt.Errorf("cache: wait timeout %s must not exceed lock ttl %s", cfg.WaitTimeout, cfg.LockTTL)
}
return &DistributedCache{
store: store,
lockTTL: cfg.LockTTL,
waitTimeout: cfg.WaitTimeout,
log: log,
}, nil
}
func (d *DistributedCache) GetOrLoad(
ctx context.Context,
key string,
ttl time.Duration,
loader func(ctx context.Context) ([]byte, error),
) ([]byte, error) {
ch := d.group.DoChan(key, func() (any, error) {
lctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), d.lockTTL+d.waitTimeout)
defer cancel()
return d.getOrLoad(lctx, key, ttl, loader)
})
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-ch:
if result.Err != nil {
return nil, result.Err
}
value, ok := result.Val.([]byte)
if !ok {
return nil, errors.New("cache: unexpected singleflight result")
}
return bytes.Clone(value), nil
}
}
func (d *DistributedCache) getOrLoad(
ctx context.Context,
key string,
ttl time.Duration,
loader func(ctx context.Context) ([]byte, error),
) ([]byte, error) {
lockKey := "lock:" + key
for {
if err := ctx.Err(); err != nil {
return nil, err
}
if value, err := d.store.Get(ctx, key); err == nil {
return value, nil
} else if !errors.Is(err, ErrCacheMiss) {
return loader(ctx)
}
token := randomToken()
acquired, err := d.store.AcquireLock(ctx, lockKey, token, d.lockTTL)
if err != nil {
return loader(ctx)
}
if acquired {
return d.fill(ctx, key, lockKey, token, ttl, loader)
}
value, outcome, err := d.await(ctx, key, lockKey)
if err != nil {
return nil, err
}
switch outcome {
case waitHit:
return value, nil
case waitDegraded:
return loader(ctx)
case waitTimeout:
return loader(ctx)
case waitRetry:
if ctx.Err() != nil {
return nil, ctx.Err()
}
case waitNone:
return nil, errors.New("cache: unexpected wait outcome")
}
}
}
func (d *DistributedCache) fill(
ctx context.Context,
key, lockKey, token string,
ttl time.Duration,
loader func(ctx context.Context) ([]byte, error),
) ([]byte, error) {
base := context.WithoutCancel(ctx)
defer func() {
rctx, cancel := context.WithTimeout(base, releaseTimeout)
defer cancel()
held, err := d.store.ReleaseLock(rctx, lockKey, token)
switch {
case err != nil:
d.warn(base, "lock release failed", key, err)
case !held:
d.warn(base, "lock expired before release: loader slower than lock ttl", key, nil)
}
}()
getCtx, cancelGet := context.WithTimeout(base, redisOpTimeout)
value, err := d.store.Get(getCtx, key)
cancelGet()
if err == nil {
return value, nil
}
loadCtx, cancel := context.WithTimeout(base, d.lockTTL-minLockTTL)
defer cancel()
value, err = loader(loadCtx)
if err != nil {
return nil, err
}
setCtx, cancelSet := context.WithTimeout(base, redisOpTimeout)
setErr := d.store.Set(setCtx, key, value, ttl)
cancelSet()
if setErr != nil {
d.warn(base, "distributed cache write failed", key, setErr)
}
return value, nil
}
type waitOutcome int
const (
waitNone waitOutcome = iota
waitHit
waitRetry
waitTimeout
waitDegraded
)
func (d *DistributedCache) await(ctx context.Context, key, lockKey string) ([]byte, waitOutcome, error) {
wctx, cancel := context.WithTimeout(ctx, d.waitTimeout)
defer cancel()
for attempt := 1; ; attempt++ {
value, err := d.store.Get(wctx, key)
switch {
case err == nil:
return value, waitHit, nil
case ctx.Err() != nil:
return nil, waitNone, ctx.Err()
case wctx.Err() != nil:
return nil, waitTimeout, nil
case !errors.Is(err, ErrCacheMiss):
return nil, waitDegraded, nil
}
if held, err := d.store.LockHeld(wctx, lockKey); err == nil && !held {
return nil, waitRetry, nil
}
select {
case <-wctx.Done():
if err := ctx.Err(); err != nil {
return nil, waitNone, err
}
return nil, waitTimeout, nil
case <-time.After(jittered(waitBackoff(attempt))):
}
}
}
func (d *DistributedCache) Get(ctx context.Context, key string) ([]byte, error) {
return d.store.Get(ctx, key)
}
func (d *DistributedCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
return d.store.Set(ctx, key, value, ttl)
}
func (d *DistributedCache) Delete(ctx context.Context, keys ...string) error {
return d.store.Delete(ctx, keys...)
}
func (d *DistributedCache) Ping(ctx context.Context) error {
return d.store.Ping(ctx)
}
func (d *DistributedCache) Close() error {
return d.store.Close()
}
func (d *DistributedCache) warn(ctx context.Context, msg, key string, err error) {
if d.log == nil {
return
}
attrs := []slog.Attr{slog.String("key", key)}
if err != nil {
attrs = append(attrs, slog.Any("error", err))
}
d.log.LogAttrs(ctx, slog.LevelWarn, msg, attrs...)
}
func waitBackoff(attempt int) time.Duration {
const base, maxWait = 50 * time.Millisecond, 500 * time.Millisecond
if attempt > 4 {
return maxWait
}
return base << (attempt - 1)
}
func jittered(d time.Duration) time.Duration {
half := d / 2
if half <= 0 {
return d
}
return half + mathrand.N(half)
}
func randomToken() string {
raw := make([]byte, 16)
if _, err := rand.Read(raw); err != nil {
counter := fallbackTokenCounter.Add(1)
return strconv.FormatInt(time.Now().UnixNano(), 10) + ":" + strconv.FormatUint(counter, 10)
}
return hex.EncodeToString(raw)
}
+43
View File
@@ -0,0 +1,43 @@
package cache
import (
"testing"
"time"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/cache/mocks"
)
func TestAwaitChecksCacheBeforePolling(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
store.EXPECT().Get(mock.Anything, "key").Return([]byte("ready"), nil).Once()
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: time.Second}, nil)
require.NoError(t, err)
started := time.Now()
value, outcome, err := d.await(t.Context(), "key", "lock:key")
require.NoError(t, err)
require.Equal(t, waitHit, outcome)
require.Equal(t, "ready", string(value))
require.Less(t, time.Since(started), 25*time.Millisecond, "cache must be checked before the first sleep")
}
func TestAwaitReturnsTimeoutWhileLockHeld(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
store.EXPECT().Get(mock.Anything, "key").Return(nil, ErrCacheMiss).Maybe()
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: 60 * time.Millisecond}, nil)
require.NoError(t, err)
_, outcome, err := d.await(t.Context(), "key", "lock:key")
require.NoError(t, err)
require.Equal(t, waitTimeout, outcome)
}
+374
View File
@@ -0,0 +1,374 @@
package cache_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/cache"
"mtusi-messenger/internal/platform/cache/mocks"
)
func newDistributed(t *testing.T, store cache.LockStore, cfg cache.DistributedConfig) *cache.DistributedCache {
t.Helper()
dc, err := cache.NewDistributed(store, cfg, nil)
require.NoError(t, err)
return dc
}
func expectFill(store *mocks.MockLockStore, key string) {
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
store.EXPECT().AcquireLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
store.EXPECT().Set(mock.Anything, key, mock.Anything, mock.Anything).Return(nil).Once()
store.EXPECT().ReleaseLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string")).Return(true, nil).Once()
}
// sharedWaitTimeout bounds every wait in these tests: a stuck helper must fail
// the test instead of hanging the whole package until -timeout fires.
const sharedWaitTimeout = 5 * time.Second
func awaitSignal(t *testing.T, ch <-chan struct{}, message string) {
t.Helper()
select {
case <-ch:
case <-time.After(sharedWaitTimeout):
t.Fatal("timed out: " + message)
}
}
func awaitValue[T any](t *testing.T, ch <-chan T) T {
t.Helper()
select {
case value := <-ch:
return value
case <-time.After(sharedWaitTimeout):
var zero T
t.Fatal("timed out waiting for the shared load to report its result")
return zero
}
}
func awaitWaitGroup(t *testing.T, wg *sync.WaitGroup) {
t.Helper()
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
awaitSignal(t, done, "goroutines did not finish")
}
func TestDistributedCachesResult(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{})
ctx := context.Background()
var calls atomic.Int32
loader := func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("payload"), nil
}
expectFill(store, "key")
store.EXPECT().Get(mock.Anything, "key").Return([]byte("payload"), nil).Once()
first, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
require.NoError(t, err)
require.Equal(t, []byte("payload"), first)
second, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
require.NoError(t, err)
require.Equal(t, []byte("payload"), second)
require.Equal(t, int32(1), calls.Load())
}
func TestDistributedDeduplicatesConcurrentMisses(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{})
ctx := context.Background()
var calls atomic.Int32
loader := func(context.Context) ([]byte, error) {
calls.Add(1)
time.Sleep(30 * time.Millisecond)
return []byte("payload"), nil
}
store.EXPECT().Get(mock.Anything, "shared").Return(nil, cache.ErrCacheMiss).Twice()
store.EXPECT().AcquireLock(mock.Anything, "lock:shared", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
store.EXPECT().Set(mock.Anything, "shared", mock.Anything, mock.Anything).Return(nil).Once()
store.EXPECT().ReleaseLock(mock.Anything, "lock:shared", mock.AnythingOfType("string")).Return(true, nil).Once()
const workers = 50
var (
wg sync.WaitGroup
failures atomic.Int32
)
wg.Add(workers)
for range workers {
go func() {
defer wg.Done()
value, err := dc.GetOrLoad(ctx, "shared", time.Minute, loader)
if err != nil || string(value) != "payload" {
failures.Add(1)
}
}()
}
awaitWaitGroup(t, &wg)
require.Zero(t, failures.Load())
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
}
func TestDistributedFallsBackOnWaitTimeout(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{WaitTimeout: 100 * time.Millisecond})
ctx := context.Background()
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
var calls atomic.Int32
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("fallback"), nil
})
require.NoError(t, err)
require.Equal(t, []byte("fallback"), value)
require.Equal(t, int32(1), calls.Load(), "a wait timeout must fall back to a direct load")
}
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{})
leaderCtx, cancelLeader := context.WithCancel(context.Background())
defer cancelLeader()
var calls atomic.Int32
started := make(chan struct{})
release := make(chan struct{})
loader := func(loadCtx context.Context) ([]byte, error) {
calls.Add(1)
close(started)
<-release
if err := loadCtx.Err(); err != nil {
return nil, err
}
return []byte("value"), nil
}
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Twice()
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
leaderErr := make(chan error, 1)
go func() {
_, err := dc.GetOrLoad(leaderCtx, "key", time.Minute, loader)
leaderErr <- err
}()
awaitSignal(t, started, "leader must reach the loader")
// The follower starts while the leader's loader is still blocked, so the
// singleflight call cannot complete: the signal below means DoChan was
// already called, i.e. the follower joined the leader's in-flight call
// instead of starting its own load.
followerJoined := make(chan struct{})
var (
wg sync.WaitGroup
followerV []byte
followerE error
)
wg.Add(1)
go func() {
defer wg.Done()
ctx := newJoiningContext(followerJoined)
followerV, followerE = dc.GetOrLoad(ctx, "key", time.Minute, loader)
}()
awaitSignal(t, followerJoined, "follower must join the in-flight load")
cancelLeader()
close(release)
require.ErrorIs(t, awaitValue(t, leaderErr), context.Canceled)
awaitWaitGroup(t, &wg)
require.NoError(t, followerE)
require.Equal(t, []byte("value"), followerV)
require.Equal(t, int32(1), calls.Load())
}
// joiningContext reports when GetOrLoad reaches the shared-result wait path. The
// delegate is kept as function fields so no struct holds a context.Context.
type joiningContext struct {
deadline func() (time.Time, bool)
done func() <-chan struct{}
err func() error
value func(any) any
once *sync.Once
joined chan struct{}
}
func newJoiningContext(joined chan struct{}) joiningContext {
base := context.Background()
return joiningContext{
deadline: base.Deadline,
done: base.Done,
err: base.Err,
value: base.Value,
once: new(sync.Once),
joined: joined,
}
}
func (c joiningContext) Deadline() (time.Time, bool) { return c.deadline() }
func (c joiningContext) Done() <-chan struct{} {
c.once.Do(func() { close(c.joined) })
return c.done()
}
func (c joiningContext) Err() error { return c.err() }
func (c joiningContext) Value(key any) any { return c.value(key) }
func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{})
ctx := context.Background()
var released atomic.Bool
time.AfterFunc(120*time.Millisecond, func() { released.Store(true) })
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
store.EXPECT().LockHeld(mock.Anything, "lock:key").RunAndReturn(func(context.Context, string) (bool, error) {
return !released.Load(), nil
}).Maybe()
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
var calls atomic.Int32
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("recovered"), nil
})
require.NoError(t, err)
require.Equal(t, []byte("recovered"), value)
require.Equal(t, int32(1), calls.Load())
}
func TestFillStoreCallsAreBoundedByDeadline(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{})
var (
mu sync.Mutex
getBudgets []time.Duration
setBudget time.Duration
setHasDead bool
)
store.EXPECT().Get(mock.Anything, "key").RunAndReturn(func(ctx context.Context, _ string) ([]byte, error) {
mu.Lock()
defer mu.Unlock()
if deadline, ok := ctx.Deadline(); ok {
getBudgets = append(getBudgets, time.Until(deadline))
}
return nil, cache.ErrCacheMiss
}).Twice()
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).
RunAndReturn(func(ctx context.Context, _ string, _ []byte, _ time.Duration) error {
mu.Lock()
defer mu.Unlock()
deadline, ok := ctx.Deadline()
setHasDead = ok
if ok {
setBudget = time.Until(deadline)
}
return nil
}).Once()
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
_, err := dc.GetOrLoad(context.Background(), "key", time.Minute, func(context.Context) ([]byte, error) {
return []byte("value"), nil
})
require.NoError(t, err)
mu.Lock()
defer mu.Unlock()
require.True(t, setHasDead, "Set must receive a bounded context")
require.LessOrEqual(t, setBudget, 300*time.Millisecond)
minGetBudget := time.Hour
for _, budget := range getBudgets {
if budget < minGetBudget {
minGetBudget = budget
}
}
require.LessOrEqual(t, minGetBudget, 300*time.Millisecond, "fill's Get must receive a bounded context")
}
+346
View File
@@ -0,0 +1,346 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"time"
mock "github.com/stretchr/testify/mock"
)
// NewMockCache creates a new instance of MockCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockCache(t interface {
mock.TestingT
Cleanup(func())
}) *MockCache {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockCache{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockCache is an autogenerated mock type for the Cache type
type MockCache struct {
mock.Mock
}
type MockCache_Expecter struct {
mock *mock.Mock
}
func (_m *MockCache) EXPECT() *MockCache_Expecter {
return &MockCache_Expecter{mock: &_m.Mock}
}
// Close provides a mock function for the type MockCache
func (_mock *MockCache) Close() error {
ret := _mock.Called()
if len(ret) == 0 {
panic("no return value specified for Close")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func() error); ok {
r0 = returnFunc()
} else {
r0 = ret.Error(0)
}
return r0
}
// MockCache_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
type MockCache_Close_Call struct {
*mock.Call
}
// Close is a helper method to define mock.On call
func (_e *MockCache_Expecter) Close() *MockCache_Close_Call {
return &MockCache_Close_Call{Call: _e.mock.On("Close")}
}
func (_c *MockCache_Close_Call) Run(run func()) *MockCache_Close_Call {
_c.Call.Run(func(args mock.Arguments) {
run()
})
return _c
}
func (_c *MockCache_Close_Call) Return(err error) *MockCache_Close_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockCache_Close_Call) RunAndReturn(run func() error) *MockCache_Close_Call {
_c.Call.Return(run)
return _c
}
// Delete provides a mock function for the type MockCache
func (_mock *MockCache) Delete(ctx context.Context, keys ...string) error {
var tmpRet mock.Arguments
if len(keys) > 0 {
tmpRet = _mock.Called(ctx, keys)
} else {
tmpRet = _mock.Called(ctx)
}
ret := tmpRet
if len(ret) == 0 {
panic("no return value specified for Delete")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
r0 = returnFunc(ctx, keys...)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockCache_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
type MockCache_Delete_Call struct {
*mock.Call
}
// Delete is a helper method to define mock.On call
// - ctx context.Context
// - keys ...string
func (_e *MockCache_Expecter) Delete(ctx any, keys ...any) *MockCache_Delete_Call {
return &MockCache_Delete_Call{Call: _e.mock.On("Delete",
append([]any{ctx}, keys...)...)}
}
func (_c *MockCache_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockCache_Delete_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []string
var variadicArgs []string
if len(args) > 1 {
variadicArgs = args[1].([]string)
}
arg1 = variadicArgs
run(
arg0,
arg1...,
)
})
return _c
}
func (_c *MockCache_Delete_Call) Return(err error) *MockCache_Delete_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockCache_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockCache_Delete_Call {
_c.Call.Return(run)
return _c
}
// Get provides a mock function for the type MockCache
func (_mock *MockCache) Get(ctx context.Context, key string) ([]byte, error) {
ret := _mock.Called(ctx, key)
if len(ret) == 0 {
panic("no return value specified for Get")
}
var r0 []byte
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
return returnFunc(ctx, key)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
r0 = returnFunc(ctx, key)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, key)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
type MockCache_Get_Call struct {
*mock.Call
}
// Get is a helper method to define mock.On call
// - ctx context.Context
// - key string
func (_e *MockCache_Expecter) Get(ctx any, key any) *MockCache_Get_Call {
return &MockCache_Get_Call{Call: _e.mock.On("Get", ctx, key)}
}
func (_c *MockCache_Get_Call) Run(run func(ctx context.Context, key string)) *MockCache_Get_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockCache_Get_Call) Return(bytes []byte, err error) *MockCache_Get_Call {
_c.Call.Return(bytes, err)
return _c
}
func (_c *MockCache_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockCache_Get_Call {
_c.Call.Return(run)
return _c
}
// Ping provides a mock function for the type MockCache
func (_mock *MockCache) Ping(ctx context.Context) error {
ret := _mock.Called(ctx)
if len(ret) == 0 {
panic("no return value specified for Ping")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
r0 = returnFunc(ctx)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockCache_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
type MockCache_Ping_Call struct {
*mock.Call
}
// Ping is a helper method to define mock.On call
// - ctx context.Context
func (_e *MockCache_Expecter) Ping(ctx any) *MockCache_Ping_Call {
return &MockCache_Ping_Call{Call: _e.mock.On("Ping", ctx)}
}
func (_c *MockCache_Ping_Call) Run(run func(ctx context.Context)) *MockCache_Ping_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
run(
arg0,
)
})
return _c
}
func (_c *MockCache_Ping_Call) Return(err error) *MockCache_Ping_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockCache_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockCache_Ping_Call {
_c.Call.Return(run)
return _c
}
// Set provides a mock function for the type MockCache
func (_mock *MockCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
ret := _mock.Called(ctx, key, value, ttl)
if len(ret) == 0 {
panic("no return value specified for Set")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
r0 = returnFunc(ctx, key, value, ttl)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockCache_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
type MockCache_Set_Call struct {
*mock.Call
}
// Set is a helper method to define mock.On call
// - ctx context.Context
// - key string
// - value []byte
// - ttl time.Duration
func (_e *MockCache_Expecter) Set(ctx any, key any, value any, ttl any) *MockCache_Set_Call {
return &MockCache_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
}
func (_c *MockCache_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockCache_Set_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
var arg2 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
var arg3 time.Duration
if args[3] != nil {
arg3 = args[3].(time.Duration)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockCache_Set_Call) Return(err error) *MockCache_Set_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockCache_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockCache_Set_Call {
_c.Call.Return(run)
return _c
}
+562
View File
@@ -0,0 +1,562 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"time"
mock "github.com/stretchr/testify/mock"
)
// NewMockLockStore creates a new instance of MockLockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockLockStore(t interface {
mock.TestingT
Cleanup(func())
}) *MockLockStore {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockLockStore{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockLockStore is an autogenerated mock type for the LockStore type
type MockLockStore struct {
mock.Mock
}
type MockLockStore_Expecter struct {
mock *mock.Mock
}
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
return &MockLockStore_Expecter{mock: &_m.Mock}
}
// AcquireLock provides a mock function for the type MockLockStore
func (_mock *MockLockStore) AcquireLock(ctx context.Context, key string, token string, ttl time.Duration) (bool, error) {
ret := _mock.Called(ctx, key, token, ttl)
if len(ret) == 0 {
panic("no return value specified for AcquireLock")
}
var r0 bool
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) (bool, error)); ok {
return returnFunc(ctx, key, token, ttl)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) bool); ok {
r0 = returnFunc(ctx, key, token, ttl)
} else {
r0 = ret.Get(0).(bool)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, time.Duration) error); ok {
r1 = returnFunc(ctx, key, token, ttl)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockLockStore_AcquireLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireLock'
type MockLockStore_AcquireLock_Call struct {
*mock.Call
}
// AcquireLock is a helper method to define mock.On call
// - ctx context.Context
// - key string
// - token string
// - ttl time.Duration
func (_e *MockLockStore_Expecter) AcquireLock(ctx any, key any, token any, ttl any) *MockLockStore_AcquireLock_Call {
return &MockLockStore_AcquireLock_Call{Call: _e.mock.On("AcquireLock", ctx, key, token, ttl)}
}
func (_c *MockLockStore_AcquireLock_Call) Run(run func(ctx context.Context, key string, token string, ttl time.Duration)) *MockLockStore_AcquireLock_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
var arg2 string
if args[2] != nil {
arg2 = args[2].(string)
}
var arg3 time.Duration
if args[3] != nil {
arg3 = args[3].(time.Duration)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockLockStore_AcquireLock_Call) Return(b bool, err error) *MockLockStore_AcquireLock_Call {
_c.Call.Return(b, err)
return _c
}
func (_c *MockLockStore_AcquireLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string, ttl time.Duration) (bool, error)) *MockLockStore_AcquireLock_Call {
_c.Call.Return(run)
return _c
}
// Close provides a mock function for the type MockLockStore
func (_mock *MockLockStore) Close() error {
ret := _mock.Called()
if len(ret) == 0 {
panic("no return value specified for Close")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func() error); ok {
r0 = returnFunc()
} else {
r0 = ret.Error(0)
}
return r0
}
// MockLockStore_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
type MockLockStore_Close_Call struct {
*mock.Call
}
// Close is a helper method to define mock.On call
func (_e *MockLockStore_Expecter) Close() *MockLockStore_Close_Call {
return &MockLockStore_Close_Call{Call: _e.mock.On("Close")}
}
func (_c *MockLockStore_Close_Call) Run(run func()) *MockLockStore_Close_Call {
_c.Call.Run(func(args mock.Arguments) {
run()
})
return _c
}
func (_c *MockLockStore_Close_Call) Return(err error) *MockLockStore_Close_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockLockStore_Close_Call) RunAndReturn(run func() error) *MockLockStore_Close_Call {
_c.Call.Return(run)
return _c
}
// Delete provides a mock function for the type MockLockStore
func (_mock *MockLockStore) Delete(ctx context.Context, keys ...string) error {
var tmpRet mock.Arguments
if len(keys) > 0 {
tmpRet = _mock.Called(ctx, keys)
} else {
tmpRet = _mock.Called(ctx)
}
ret := tmpRet
if len(ret) == 0 {
panic("no return value specified for Delete")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
r0 = returnFunc(ctx, keys...)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockLockStore_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
type MockLockStore_Delete_Call struct {
*mock.Call
}
// Delete is a helper method to define mock.On call
// - ctx context.Context
// - keys ...string
func (_e *MockLockStore_Expecter) Delete(ctx any, keys ...any) *MockLockStore_Delete_Call {
return &MockLockStore_Delete_Call{Call: _e.mock.On("Delete",
append([]any{ctx}, keys...)...)}
}
func (_c *MockLockStore_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockLockStore_Delete_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []string
var variadicArgs []string
if len(args) > 1 {
variadicArgs = args[1].([]string)
}
arg1 = variadicArgs
run(
arg0,
arg1...,
)
})
return _c
}
func (_c *MockLockStore_Delete_Call) Return(err error) *MockLockStore_Delete_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockLockStore_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockLockStore_Delete_Call {
_c.Call.Return(run)
return _c
}
// Get provides a mock function for the type MockLockStore
func (_mock *MockLockStore) Get(ctx context.Context, key string) ([]byte, error) {
ret := _mock.Called(ctx, key)
if len(ret) == 0 {
panic("no return value specified for Get")
}
var r0 []byte
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
return returnFunc(ctx, key)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
r0 = returnFunc(ctx, key)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, key)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockLockStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
type MockLockStore_Get_Call struct {
*mock.Call
}
// Get is a helper method to define mock.On call
// - ctx context.Context
// - key string
func (_e *MockLockStore_Expecter) Get(ctx any, key any) *MockLockStore_Get_Call {
return &MockLockStore_Get_Call{Call: _e.mock.On("Get", ctx, key)}
}
func (_c *MockLockStore_Get_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_Get_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockLockStore_Get_Call) Return(bytes []byte, err error) *MockLockStore_Get_Call {
_c.Call.Return(bytes, err)
return _c
}
func (_c *MockLockStore_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockLockStore_Get_Call {
_c.Call.Return(run)
return _c
}
// LockHeld provides a mock function for the type MockLockStore
func (_mock *MockLockStore) LockHeld(ctx context.Context, key string) (bool, error) {
ret := _mock.Called(ctx, key)
if len(ret) == 0 {
panic("no return value specified for LockHeld")
}
var r0 bool
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (bool, error)); ok {
return returnFunc(ctx, key)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) bool); ok {
r0 = returnFunc(ctx, key)
} else {
r0 = ret.Get(0).(bool)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, key)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockLockStore_LockHeld_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LockHeld'
type MockLockStore_LockHeld_Call struct {
*mock.Call
}
// LockHeld is a helper method to define mock.On call
// - ctx context.Context
// - key string
func (_e *MockLockStore_Expecter) LockHeld(ctx any, key any) *MockLockStore_LockHeld_Call {
return &MockLockStore_LockHeld_Call{Call: _e.mock.On("LockHeld", ctx, key)}
}
func (_c *MockLockStore_LockHeld_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_LockHeld_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockLockStore_LockHeld_Call) Return(b bool, err error) *MockLockStore_LockHeld_Call {
_c.Call.Return(b, err)
return _c
}
func (_c *MockLockStore_LockHeld_Call) RunAndReturn(run func(ctx context.Context, key string) (bool, error)) *MockLockStore_LockHeld_Call {
_c.Call.Return(run)
return _c
}
// Ping provides a mock function for the type MockLockStore
func (_mock *MockLockStore) Ping(ctx context.Context) error {
ret := _mock.Called(ctx)
if len(ret) == 0 {
panic("no return value specified for Ping")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
r0 = returnFunc(ctx)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockLockStore_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
type MockLockStore_Ping_Call struct {
*mock.Call
}
// Ping is a helper method to define mock.On call
// - ctx context.Context
func (_e *MockLockStore_Expecter) Ping(ctx any) *MockLockStore_Ping_Call {
return &MockLockStore_Ping_Call{Call: _e.mock.On("Ping", ctx)}
}
func (_c *MockLockStore_Ping_Call) Run(run func(ctx context.Context)) *MockLockStore_Ping_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
run(
arg0,
)
})
return _c
}
func (_c *MockLockStore_Ping_Call) Return(err error) *MockLockStore_Ping_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockLockStore_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockLockStore_Ping_Call {
_c.Call.Return(run)
return _c
}
// ReleaseLock provides a mock function for the type MockLockStore
func (_mock *MockLockStore) ReleaseLock(ctx context.Context, key string, token string) (bool, error) {
ret := _mock.Called(ctx, key, token)
if len(ret) == 0 {
panic("no return value specified for ReleaseLock")
}
var r0 bool
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) (bool, error)); ok {
return returnFunc(ctx, key, token)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) bool); ok {
r0 = returnFunc(ctx, key, token)
} else {
r0 = ret.Get(0).(bool)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
r1 = returnFunc(ctx, key, token)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockLockStore_ReleaseLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReleaseLock'
type MockLockStore_ReleaseLock_Call struct {
*mock.Call
}
// ReleaseLock is a helper method to define mock.On call
// - ctx context.Context
// - key string
// - token string
func (_e *MockLockStore_Expecter) ReleaseLock(ctx any, key any, token any) *MockLockStore_ReleaseLock_Call {
return &MockLockStore_ReleaseLock_Call{Call: _e.mock.On("ReleaseLock", ctx, key, token)}
}
func (_c *MockLockStore_ReleaseLock_Call) Run(run func(ctx context.Context, key string, token string)) *MockLockStore_ReleaseLock_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
var arg2 string
if args[2] != nil {
arg2 = args[2].(string)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockLockStore_ReleaseLock_Call) Return(b bool, err error) *MockLockStore_ReleaseLock_Call {
_c.Call.Return(b, err)
return _c
}
func (_c *MockLockStore_ReleaseLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string) (bool, error)) *MockLockStore_ReleaseLock_Call {
_c.Call.Return(run)
return _c
}
// Set provides a mock function for the type MockLockStore
func (_mock *MockLockStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
ret := _mock.Called(ctx, key, value, ttl)
if len(ret) == 0 {
panic("no return value specified for Set")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
r0 = returnFunc(ctx, key, value, ttl)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockLockStore_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
type MockLockStore_Set_Call struct {
*mock.Call
}
// Set is a helper method to define mock.On call
// - ctx context.Context
// - key string
// - value []byte
// - ttl time.Duration
func (_e *MockLockStore_Expecter) Set(ctx any, key any, value any, ttl any) *MockLockStore_Set_Call {
return &MockLockStore_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
}
func (_c *MockLockStore_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockLockStore_Set_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
var arg2 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
var arg3 time.Duration
if args[3] != nil {
arg3 = args[3].(time.Duration)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockLockStore_Set_Call) Return(err error) *MockLockStore_Set_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockLockStore_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockLockStore_Set_Call {
_c.Call.Return(run)
return _c
}
+139
View File
@@ -0,0 +1,139 @@
package cache
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
type RedisConfig struct {
Host string
Port int
Password string
DB int
MaxRetries int
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
}
type RedisCache struct {
client *redis.Client
}
func NewRedis(cfg RedisConfig) (*RedisCache, error) {
client := redis.NewClient(newClientOptions(cfg))
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err)
}
return &RedisCache{client: client}, nil
}
func newClientOptions(cfg RedisConfig) *redis.Options {
return &redis.Options{
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
Password: cfg.Password,
DB: cfg.DB,
MaxRetries: cfg.MaxRetries,
DialTimeout: cfg.DialTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
PoolSize: cfg.PoolSize,
}
}
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
value, err := r.client.Get(ctx, key).Bytes()
if errors.Is(err, redis.Nil) {
return nil, ErrCacheMiss
}
if err != nil {
return nil, fmt.Errorf("redis get %q: %w", key, err)
}
return value, nil
}
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
if err := r.client.Set(ctx, key, value, ttl).Err(); err != nil {
return fmt.Errorf("redis set %q: %w", key, err)
}
return nil
}
func (r *RedisCache) Delete(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
if err := r.client.Del(ctx, keys...).Err(); err != nil {
return fmt.Errorf("redis delete: %w", err)
}
return nil
}
var releaseLockScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`)
func (r *RedisCache) AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {
acquired, err := r.client.SetNX(ctx, key, token, ttl).Result()
if err != nil {
return false, fmt.Errorf("redis acquire lock %q: %w", key, err)
}
return acquired, nil
}
func (r *RedisCache) ReleaseLock(ctx context.Context, key, token string) (bool, error) {
deleted, err := releaseLockScript.Run(ctx, r.client, []string{key}, token).Int64()
if err != nil {
return false, fmt.Errorf("redis release lock %q: %w", key, err)
}
return deleted > 0, nil
}
func (r *RedisCache) LockHeld(ctx context.Context, key string) (bool, error) {
exists, err := r.client.Exists(ctx, key).Result()
if err != nil {
return false, fmt.Errorf("redis check lock %q: %w", key, err)
}
return exists > 0, nil
}
func (r *RedisCache) Ping(ctx context.Context) error {
if err := r.client.Ping(ctx).Err(); err != nil {
return fmt.Errorf("redis ping: %w", err)
}
return nil
}
func (r *RedisCache) Close() error {
if err := r.client.Close(); err != nil {
return fmt.Errorf("redis close: %w", err)
}
return nil
}
+32
View File
@@ -0,0 +1,32 @@
package cache
import (
"testing"
"time"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
func TestNewClientOptionsAppliesTimeoutsAndRetries(t *testing.T) {
t.Parallel()
client := redis.NewClient(newClientOptions(RedisConfig{
Host: "localhost",
Port: 6379,
MaxRetries: -1,
DialTimeout: 300 * time.Millisecond,
ReadTimeout: 200 * time.Millisecond,
WriteTimeout: 200 * time.Millisecond,
PoolSize: 5,
}))
defer func() { _ = client.Close() }()
opts := client.Options()
require.Equal(t, 0, opts.MaxRetries, "go-redis: -1 disables retries, 0 would restore the default of 3")
require.Equal(t, 300*time.Millisecond, opts.DialTimeout)
require.Equal(t, 200*time.Millisecond, opts.ReadTimeout)
require.Equal(t, 200*time.Millisecond, opts.WriteTimeout)
require.Equal(t, 5, opts.PoolSize)
}
+52
View File
@@ -0,0 +1,52 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime = 1
argonMemory = 64 * 1024
argonThreads = 4
argonKeyLen = 32
argonSaltLen = 16
)
func Hash(plain string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return "argon2id$" +
base64.RawStdEncoding.EncodeToString(salt) + "$" +
base64.RawStdEncoding.EncodeToString(hash), nil
}
func Verify(plain, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 3 || parts[0] != "argon2id" {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
if err != nil || len(salt) != argonSaltLen || len(expected) != argonKeyLen {
return false
}
actual := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return subtle.ConstantTimeCompare(actual, expected) == 1
}
@@ -0,0 +1,33 @@
package password_test
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/password"
)
func TestHashVerifyRoundTrip(t *testing.T) {
encoded, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.True(t, password.Verify("very-secret-password", encoded))
require.False(t, password.Verify("wrong-password-value", encoded))
}
func TestHashIsSalted(t *testing.T) {
first, err := password.Hash("very-secret-password")
require.NoError(t, err)
second, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.NotEqual(t, first, second)
}
func TestVerifyRejectsMalformedHash(t *testing.T) {
require.False(t, password.Verify("very-secret-password", ""))
require.False(t, password.Verify("very-secret-password", "plain-text"))
require.False(t, password.Verify("very-secret-password", strings.Repeat("x", 64)))
}
+40
View File
@@ -0,0 +1,40 @@
package token
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
)
const size = 32
var ErrInvalid = errors.New("invalid token")
type Token struct{}
func New() Token {
return Token{}
}
func (Token) Generate() (string, []byte, error) {
raw := make([]byte, size)
if _, err := rand.Read(raw); err != nil {
return "", nil, err
}
sum := sha256.Sum256(raw)
return base64.RawURLEncoding.EncodeToString(raw), sum[:], nil
}
func (Token) Hash(raw string) ([]byte, error) {
decoded, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil || len(decoded) != size {
return nil, ErrInvalid
}
sum := sha256.Sum256(decoded)
return sum[:], nil
}
+44
View File
@@ -0,0 +1,44 @@
package token_test
import (
"crypto/sha256"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/token"
)
func TestGenerateProducesUniqueOpaqueTokens(t *testing.T) {
tokens := token.New()
first, firstHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEmpty(t, first)
require.Len(t, firstHash, sha256.Size)
second, secondHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEqual(t, first, second)
require.NotEqual(t, firstHash, secondHash)
}
func TestHashMatchesGeneratedHash(t *testing.T) {
tokens := token.New()
raw, hash, err := tokens.Generate()
require.NoError(t, err)
actual, err := tokens.Hash(raw)
require.NoError(t, err)
require.Equal(t, hash, actual)
}
func TestHashRejectsMalformed(t *testing.T) {
tokens := token.New()
for _, raw := range []string{"", "not-base64!", "c2hvcnQ"} {
_, err := tokens.Hash(raw)
require.ErrorIs(t, err, token.ErrInvalid, raw)
}
}
-2
View File
@@ -9,8 +9,6 @@ import (
"mtusi-messenger/internal/domain"
)
//go:generate go tool mockery
type Repository interface {
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
-2
View File
@@ -9,8 +9,6 @@ import (
"mtusi-messenger/internal/domain"
)
//go:generate go tool mockery
type Repository interface {
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
ListVisible(
@@ -0,0 +1,310 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
)
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockRepository(t interface {
mock.TestingT
Cleanup(func())
}) *MockRepository {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockRepository{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockRepository is an autogenerated mock type for the Repository type
type MockRepository struct {
mock.Mock
}
type MockRepository_Expecter struct {
mock *mock.Mock
}
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
return &MockRepository_Expecter{mock: &_m.Mock}
}
// Create provides a mock function for the type MockRepository
func (_mock *MockRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
ret := _mock.Called(ctx, session)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
return returnFunc(ctx, session)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
r0 = returnFunc(ctx, session)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
r1 = returnFunc(ctx, session)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
type MockRepository_Create_Call struct {
*mock.Call
}
// Create is a helper method to define mock.On call
// - ctx context.Context
// - session domain.NewSession
func (_e *MockRepository_Expecter) Create(ctx any, session any) *MockRepository_Create_Call {
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, session)}
}
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockRepository_Create_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.NewSession
if args[1] != nil {
arg1 = args[1].(domain.NewSession)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Create_Call) Return(session1 domain.Session, err error) *MockRepository_Create_Call {
_c.Call.Return(session1, err)
return _c
}
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockRepository_Create_Call {
_c.Call.Return(run)
return _c
}
// Credentials provides a mock function for the type MockRepository
func (_mock *MockRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ret := _mock.Called(ctx, username)
if len(ret) == 0 {
panic("no return value specified for Credentials")
}
var r0 domain.UserCredentials
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
return returnFunc(ctx, username)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
r0 = returnFunc(ctx, username)
} else {
r0 = ret.Get(0).(domain.UserCredentials)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, username)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
type MockRepository_Credentials_Call struct {
*mock.Call
}
// Credentials is a helper method to define mock.On call
// - ctx context.Context
// - username string
func (_e *MockRepository_Expecter) Credentials(ctx any, username any) *MockRepository_Credentials_Call {
return &MockRepository_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
}
func (_c *MockRepository_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockRepository_Credentials_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockRepository_Credentials_Call {
_c.Call.Return(userCredentials, err)
return _c
}
func (_c *MockRepository_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockRepository_Credentials_Call {
_c.Call.Return(run)
return _c
}
// Resolve provides a mock function for the type MockRepository
func (_mock *MockRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ret := _mock.Called(ctx, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Resolve")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
return returnFunc(ctx, tokenHash)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
r0 = returnFunc(ctx, tokenHash)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
r1 = returnFunc(ctx, tokenHash)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockRepository_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
type MockRepository_Resolve_Call struct {
*mock.Call
}
// Resolve is a helper method to define mock.On call
// - ctx context.Context
// - tokenHash []byte
func (_e *MockRepository_Expecter) Resolve(ctx any, tokenHash any) *MockRepository_Resolve_Call {
return &MockRepository_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
}
func (_c *MockRepository_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockRepository_Resolve_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []byte
if args[1] != nil {
arg1 = args[1].([]byte)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockRepository_Resolve_Call) Return(session domain.Session, err error) *MockRepository_Resolve_Call {
_c.Call.Return(session, err)
return _c
}
func (_c *MockRepository_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockRepository_Resolve_Call {
_c.Call.Return(run)
return _c
}
// Revoke provides a mock function for the type MockRepository
func (_mock *MockRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ret := _mock.Called(ctx, userID, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Revoke")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
r0 = returnFunc(ctx, userID, tokenHash)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockRepository_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
type MockRepository_Revoke_Call struct {
*mock.Call
}
// Revoke is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
// - tokenHash []byte
func (_e *MockRepository_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockRepository_Revoke_Call {
return &MockRepository_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
}
func (_c *MockRepository_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockRepository_Revoke_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockRepository_Revoke_Call) Return(err error) *MockRepository_Revoke_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockRepository_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockRepository_Revoke_Call {
_c.Call.Return(run)
return _c
}
+168
View File
@@ -0,0 +1,168 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
mock "github.com/stretchr/testify/mock"
)
// NewMockTokens creates a new instance of MockTokens. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockTokens(t interface {
mock.TestingT
Cleanup(func())
}) *MockTokens {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockTokens{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockTokens is an autogenerated mock type for the Tokens type
type MockTokens struct {
mock.Mock
}
type MockTokens_Expecter struct {
mock *mock.Mock
}
func (_m *MockTokens) EXPECT() *MockTokens_Expecter {
return &MockTokens_Expecter{mock: &_m.Mock}
}
// Generate provides a mock function for the type MockTokens
func (_mock *MockTokens) Generate() (string, []byte, error) {
ret := _mock.Called()
if len(ret) == 0 {
panic("no return value specified for Generate")
}
var r0 string
var r1 []byte
var r2 error
if returnFunc, ok := ret.Get(0).(func() (string, []byte, error)); ok {
return returnFunc()
}
if returnFunc, ok := ret.Get(0).(func() string); ok {
r0 = returnFunc()
} else {
r0 = ret.Get(0).(string)
}
if returnFunc, ok := ret.Get(1).(func() []byte); ok {
r1 = returnFunc()
} else {
if ret.Get(1) != nil {
r1 = ret.Get(1).([]byte)
}
}
if returnFunc, ok := ret.Get(2).(func() error); ok {
r2 = returnFunc()
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// MockTokens_Generate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Generate'
type MockTokens_Generate_Call struct {
*mock.Call
}
// Generate is a helper method to define mock.On call
func (_e *MockTokens_Expecter) Generate() *MockTokens_Generate_Call {
return &MockTokens_Generate_Call{Call: _e.mock.On("Generate")}
}
func (_c *MockTokens_Generate_Call) Run(run func()) *MockTokens_Generate_Call {
_c.Call.Run(func(args mock.Arguments) {
run()
})
return _c
}
func (_c *MockTokens_Generate_Call) Return(s string, bytes []byte, err error) *MockTokens_Generate_Call {
_c.Call.Return(s, bytes, err)
return _c
}
func (_c *MockTokens_Generate_Call) RunAndReturn(run func() (string, []byte, error)) *MockTokens_Generate_Call {
_c.Call.Return(run)
return _c
}
// Hash provides a mock function for the type MockTokens
func (_mock *MockTokens) Hash(raw string) ([]byte, error) {
ret := _mock.Called(raw)
if len(ret) == 0 {
panic("no return value specified for Hash")
}
var r0 []byte
var r1 error
if returnFunc, ok := ret.Get(0).(func(string) ([]byte, error)); ok {
return returnFunc(raw)
}
if returnFunc, ok := ret.Get(0).(func(string) []byte); ok {
r0 = returnFunc(raw)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]byte)
}
}
if returnFunc, ok := ret.Get(1).(func(string) error); ok {
r1 = returnFunc(raw)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockTokens_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash'
type MockTokens_Hash_Call struct {
*mock.Call
}
// Hash is a helper method to define mock.On call
// - raw string
func (_e *MockTokens_Expecter) Hash(raw any) *MockTokens_Hash_Call {
return &MockTokens_Hash_Call{Call: _e.mock.On("Hash", raw)}
}
func (_c *MockTokens_Hash_Call) Run(run func(raw string)) *MockTokens_Hash_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 string
if args[0] != nil {
arg0 = args[0].(string)
}
run(
arg0,
)
})
return _c
}
func (_c *MockTokens_Hash_Call) Return(bytes []byte, err error) *MockTokens_Hash_Call {
_c.Call.Return(bytes, err)
return _c
}
func (_c *MockTokens_Hash_Call) RunAndReturn(run func(raw string) ([]byte, error)) *MockTokens_Hash_Call {
_c.Call.Return(run)
return _c
}
+95
View File
@@ -0,0 +1,95 @@
package session
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
)
type Repository interface {
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
}
type Tokens interface {
Generate() (string, []byte, error)
Hash(raw string) ([]byte, error)
}
type Service struct {
sessions Repository
tokens Tokens
ttl time.Duration
}
func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service {
return &Service{sessions: sessions, tokens: tokens, ttl: ttl}
}
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
credentials, err := s.sessions.Credentials(ctx, username)
if err != nil {
return domain.User{}, fmt.Errorf("authenticate: %w", err)
}
if !password.Verify(plain, credentials.PasswordHash) {
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
}
return credentials.User, nil
}
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
hash, err := s.tokens.Hash(raw)
if err != nil {
return domain.User{}, fmt.Errorf("resolve session: %w", domain.ErrUnauthenticated)
}
session, err := s.sessions.Resolve(ctx, hash)
if err != nil {
return domain.User{}, fmt.Errorf("resolve session: %w", err)
}
return session.User, nil
}
func (s *Service) Create(ctx context.Context, user domain.User) (domain.Session, error) {
raw, hash, err := s.tokens.Generate()
if err != nil {
return domain.Session{}, fmt.Errorf("generate token: %w", err)
}
session, err := s.sessions.Create(ctx, domain.NewSession{
TokenHash: hash,
UserID: user.ID,
ExpiresAt: time.Now().UTC().Add(s.ttl),
})
if err != nil {
return domain.Session{}, fmt.Errorf("create session: %w", err)
}
session.Token = raw
session.User = user
return session, nil
}
func (s *Service) Revoke(ctx context.Context, userID uuid.UUID, raw string) error {
hash, err := s.tokens.Hash(raw)
if err != nil {
return fmt.Errorf("revoke session: %w", domain.ErrUnauthenticated)
}
if err := s.sessions.Revoke(ctx, userID, hash); err != nil {
return fmt.Errorf("revoke session: %w", err)
}
return nil
}
+146
View File
@@ -0,0 +1,146 @@
package session_test
import (
"bytes"
"errors"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/service/session"
"mtusi-messenger/internal/service/session/mocks"
)
type ServiceSuite struct {
suite.Suite
sessions *mocks.MockRepository
tokens *mocks.MockTokens
service *session.Service
ttl time.Duration
user domain.User
}
func TestServiceSuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(ServiceSuite))
}
func (s *ServiceSuite) SetupTest() {
s.sessions = mocks.NewMockRepository(s.T())
s.tokens = mocks.NewMockTokens(s.T())
s.ttl = time.Hour
s.service = session.NewService(s.sessions, s.tokens, s.ttl)
s.user = domain.User{
ID: uuid.New(),
Username: "alice",
DisplayName: "Алиса",
CreatedAt: time.Now().UTC(),
}
}
func (s *ServiceSuite) TestResolveHashesTokenBeforeStorage() {
hash := []byte("hashed-token")
stored := domain.Session{ExpiresAt: time.Now().Add(time.Hour), User: s.user}
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
s.sessions.EXPECT().Resolve(mock.Anything, hash).Return(stored, nil).Once()
got, err := s.service.Resolve(s.T().Context(), "raw-token")
s.Require().NoError(err)
s.Equal(s.user, got)
}
func (s *ServiceSuite) TestResolveRejectsMalformedTokenWithoutStorage() {
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
_, err := s.service.Resolve(s.T().Context(), "garbage")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestCreateGeneratesTokenAndReturnsIt() {
hash := []byte("hashed-token")
expiresAt := time.Now().Add(s.ttl)
s.tokens.EXPECT().Generate().Return("raw-token", hash, nil).Once()
s.sessions.EXPECT().
Create(mock.Anything, mock.MatchedBy(func(candidate domain.NewSession) bool {
return bytes.Equal(candidate.TokenHash, hash) &&
candidate.UserID == s.user.ID &&
candidate.ExpiresAt.After(time.Now())
})).
Return(domain.Session{ExpiresAt: expiresAt}, nil).
Once()
got, err := s.service.Create(s.T().Context(), s.user)
s.Require().NoError(err)
s.Equal("raw-token", got.Token)
s.Equal(s.user, got.User)
s.Equal(expiresAt, got.ExpiresAt)
}
func (s *ServiceSuite) TestCreatePropagatesTokenGenerationError() {
s.tokens.EXPECT().Generate().Return("", nil, errors.New("no entropy")).Once()
_, err := s.service.Create(s.T().Context(), s.user)
s.Require().Error(err)
}
func (s *ServiceSuite) TestRevokeHashesTokenBeforeStorage() {
hash := []byte("hashed-token")
userID := uuid.New()
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
s.sessions.EXPECT().Revoke(mock.Anything, userID, hash).Return(nil).Once()
s.Require().NoError(s.service.Revoke(s.T().Context(), userID, "raw-token"))
}
func (s *ServiceSuite) TestRevokeRejectsMalformedToken() {
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
err := s.service.Revoke(s.T().Context(), uuid.New(), "garbage")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestAuthenticateVerifiesPassword() {
hash, err := password.Hash("secret-password-123")
s.Require().NoError(err)
s.sessions.EXPECT().
Credentials(mock.Anything, "alice").
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
Once()
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
s.Require().NoError(err)
s.Equal(s.user, got)
}
func (s *ServiceSuite) TestAuthenticateRejectsWrongPassword() {
hash, err := password.Hash("secret-password-123")
s.Require().NoError(err)
s.sessions.EXPECT().
Credentials(mock.Anything, "alice").
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
Once()
_, err = s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *ServiceSuite) TestAuthenticatePropagatesUnknownUser() {
s.sessions.EXPECT().
Credentials(mock.Anything, "nobody").
Return(domain.UserCredentials{}, domain.ErrUnauthenticated).
Once()
_, err := s.service.Authenticate(s.T().Context(), "nobody", "secret-password-123")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
+9 -9
View File
@@ -49,7 +49,7 @@ func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
}
// Create provides a mock function for the type MockRepository
func (_mock *MockRepository) Create(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
func (_mock *MockRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
ret := _mock.Called(ctx, draft)
if len(ret) == 0 {
@@ -58,15 +58,15 @@ func (_mock *MockRepository) Create(ctx context.Context, draft domain.UserDraft)
var r0 domain.User
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) (domain.User, error)); ok {
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) (domain.User, error)); ok {
return returnFunc(ctx, draft)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.UserDraft) domain.User); ok {
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) domain.User); ok {
r0 = returnFunc(ctx, draft)
} else {
r0 = ret.Get(0).(domain.User)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.UserDraft) error); ok {
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewUser) error); ok {
r1 = returnFunc(ctx, draft)
} else {
r1 = ret.Error(1)
@@ -81,20 +81,20 @@ type MockRepository_Create_Call struct {
// Create is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.UserDraft
// - draft domain.NewUser
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
}
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.UserDraft)) *MockRepository_Create_Call {
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.NewUser)) *MockRepository_Create_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.UserDraft
var arg1 domain.NewUser
if args[1] != nil {
arg1 = args[1].(domain.UserDraft)
arg1 = args[1].(domain.NewUser)
}
run(
arg0,
@@ -109,7 +109,7 @@ func (_c *MockRepository_Create_Call) Return(user domain.User, err error) *MockR
return _c
}
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.UserDraft) (domain.User, error)) *MockRepository_Create_Call {
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.NewUser) (domain.User, error)) *MockRepository_Create_Call {
_c.Call.Return(run)
return _c
}
+12 -4
View File
@@ -7,12 +7,11 @@ import (
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
)
//go:generate go tool mockery
type Repository interface {
Create(ctx context.Context, draft domain.UserDraft) (domain.User, error)
Create(ctx context.Context, draft domain.NewUser) (domain.User, error)
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
}
@@ -29,7 +28,16 @@ func (s *Service) Register(ctx context.Context, draft domain.UserDraft) (domain.
return domain.User{}, err
}
user, err := s.users.Create(ctx, draft)
hash, err := password.Hash(draft.Password)
if err != nil {
return domain.User{}, fmt.Errorf("hash password: %w", err)
}
user, err := s.users.Create(ctx, domain.NewUser{
Username: draft.Username,
DisplayName: draft.DisplayName,
PasswordHash: hash,
})
if err != nil {
return domain.User{}, fmt.Errorf("create user: %w", err)
}
+25 -6
View File
@@ -6,6 +6,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
@@ -34,8 +35,8 @@ func (s *ServiceSuite) SetupTest() {
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
}
func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
func (s *ServiceSuite) TestRegisterHashesPasswordAndReturnsStoredUser() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
stored := domain.User{
ID: uuid.New(),
Username: draft.Username,
@@ -43,7 +44,15 @@ func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
CreatedAt: s.now,
}
s.users.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
s.users.EXPECT().
Create(s.T().Context(), mock.MatchedBy(func(candidate domain.NewUser) bool {
return candidate.Username == draft.Username &&
candidate.DisplayName == draft.DisplayName &&
candidate.PasswordHash != "" &&
candidate.PasswordHash != draft.Password
})).
Return(stored, nil).
Once()
got, err := s.service.Register(s.T().Context(), draft)
s.Require().NoError(err)
@@ -51,16 +60,26 @@ func (s *ServiceSuite) TestRegisterReturnsStoredUser() {
}
func (s *ServiceSuite) TestRegisterRejectsBlankDisplayNameWithoutRepositoryCall() {
draft := domain.UserDraft{Username: "alice", DisplayName: " "}
draft := domain.UserDraft{Username: "alice", DisplayName: " ", Password: "very-secret-password"}
_, err := s.service.Register(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrValidation)
}
func (s *ServiceSuite) TestRegisterRejectsShortPasswordWithoutRepositoryCall() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
_, err := s.service.Register(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrValidation)
}
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса"}
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
s.users.EXPECT().Create(s.T().Context(), draft).Return(domain.User{}, domain.ErrUsernameTaken).Once()
s.users.EXPECT().
Create(s.T().Context(), mock.Anything).
Return(domain.User{}, domain.ErrUsernameTaken).
Once()
_, err := s.service.Register(s.T().Context(), draft)
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
@@ -1,95 +0,0 @@
package memory
import (
"context"
"slices"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type ChatRepository struct {
store *Store
}
func (r *ChatRepository) Create(_ context.Context, draft domain.ChatDraft) (domain.Chat, error) {
s := r.store
s.mu.Lock()
defer s.mu.Unlock()
for _, id := range draft.MemberIDs {
if _, ok := s.usersByID[id]; !ok {
return domain.Chat{}, domain.ErrUnknownMember
}
}
chat := domain.Chat{
ID: s.ids.NewID(),
Title: draft.Title,
MemberIDs: slices.Clone(draft.MemberIDs),
CreatedAt: s.clock.Now(),
}
s.chatsByID[chat.ID] = chat
at, _ := slices.BinarySearchFunc(s.chatsOrdered, chat, func(a, b domain.Chat) int {
return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID)
})
s.chatsOrdered = slices.Insert(s.chatsOrdered, at, chat)
return cloneChat(chat), nil
}
func (r *ChatRepository) GetVisible(_ context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
s := r.store
s.mu.RLock()
defer s.mu.RUnlock()
chat, ok := s.chatsByID[chatID]
if !ok || !chat.HasMember(callerID) {
return domain.Chat{}, domain.ErrNotFound
}
return cloneChat(chat), nil
}
func (r *ChatRepository) ListVisible(
_ context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
s := r.store
s.mu.RLock()
defer s.mu.RUnlock()
visible := make([]domain.Chat, 0, len(s.chatsOrdered))
for _, chat := range s.chatsOrdered {
if chat.HasMember(callerID) {
visible = append(visible, chat)
}
}
page := paginate(visible, callerID, chatKey, after, limit)
for i, chat := range page.Items {
page.Items[i] = cloneChat(chat)
}
return page, nil
}
func chatKey(chat domain.Chat) (time.Time, uuid.UUID) {
return chat.CreatedAt, chat.ID
}
func cloneChat(chat domain.Chat) domain.Chat {
chat.MemberIDs = slices.Clone(chat.MemberIDs)
return chat
}
@@ -1,51 +0,0 @@
package memory
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type benchmarkClock struct{ now time.Time }
func (c benchmarkClock) Now() time.Time { return c.now }
func BenchmarkMessageCreate(b *testing.B) {
for _, size := range []int{1000, 10000, 50000} {
b.Run(fmt.Sprintf("history=%d", size), func(b *testing.B) {
base := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
store := NewStore(WithClock(benchmarkClock{now: base.Add(time.Hour)}))
chatID, senderID := uuid.New(), uuid.New()
store.chatsByID[chatID] = domain.Chat{ID: chatID, MemberIDs: []uuid.UUID{senderID}}
history := make([]domain.Message, size, size+1)
for i := range history {
history[i] = domain.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
CreatedAt: base.Add(time.Duration(i) * time.Microsecond),
}
}
store.messagesByChat[chatID] = history
draft := domain.MessageDraft{ChatID: chatID, SenderID: senderID, Text: "benchmark"}
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
created, err := store.Messages().Create(context.Background(), draft)
if err != nil {
b.Fatal(err)
}
if len(store.messagesByChat[chatID]) != size+1 ||
compareKeyset(history[size-1].CreatedAt, history[size-1].ID, created.CreatedAt, created.ID) >= 0 {
b.Fatal("message not appended in keyset order")
}
store.messagesByChat[chatID] = store.messagesByChat[chatID][:size]
}
})
}
}
@@ -1,77 +0,0 @@
package memory
import (
"context"
"slices"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type MessageRepository struct {
store *Store
}
func (r *MessageRepository) Create(_ context.Context, draft domain.MessageDraft) (domain.Message, error) {
s := r.store
s.mu.Lock()
defer s.mu.Unlock()
chat, ok := s.chatsByID[draft.ChatID]
if !ok || !chat.HasMember(draft.SenderID) {
return domain.Message{}, domain.ErrNotFound
}
message := domain.Message{
ID: s.ids.NewID(),
ChatID: draft.ChatID,
SenderID: draft.SenderID,
Text: draft.Text,
CreatedAt: s.clock.Now(),
}
history := s.messagesByChat[message.ChatID]
if len(history) == 0 || compareKeyset(
history[len(history)-1].CreatedAt,
history[len(history)-1].ID,
message.CreatedAt,
message.ID,
) < 0 {
s.messagesByChat[message.ChatID] = append(history, message)
return message, nil
}
at, _ := slices.BinarySearchFunc(history, message, func(a, b domain.Message) int {
return compareKeyset(a.CreatedAt, a.ID, b.CreatedAt, b.ID)
})
s.messagesByChat[message.ChatID] = slices.Insert(history, at, message)
return message, nil
}
func (r *MessageRepository) ListVisible(
_ context.Context,
chatID, callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Message], error) {
s := r.store
s.mu.RLock()
defer s.mu.RUnlock()
chat, ok := s.chatsByID[chatID]
if !ok || !chat.HasMember(callerID) {
return domain.Page[domain.Message]{}, domain.ErrNotFound
}
return paginate(s.messagesByChat[chatID], chatID, messageKey, after, limit), nil
}
func messageKey(message domain.Message) (time.Time, uuid.UUID) {
return message.CreatedAt, message.ID
}
-378
View File
@@ -1,378 +0,0 @@
package memory_test
import (
"context"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/service/chat"
"mtusi-messenger/internal/service/message"
"mtusi-messenger/internal/service/user"
"mtusi-messenger/internal/storage/memory"
)
type stepClock struct {
mu sync.Mutex
next time.Time
}
func newStepClock() *stepClock {
return &stepClock{next: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)}
}
func (c *stepClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
out := c.next
c.next = c.next.Add(time.Second)
return out
}
type RepositorySuite struct {
suite.Suite
store *memory.Store
}
func (s *RepositorySuite) ctx() context.Context { return s.T().Context() }
func TestRepositorySuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(RepositorySuite))
}
func (s *RepositorySuite) SetupTest() {
s.store = memory.NewStore(memory.WithClock(newStepClock()))
}
func (s *RepositorySuite) createUser(username string) domain.User {
s.T().Helper()
created, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
Username: username,
DisplayName: "Пользователь",
})
s.Require().NoError(err)
return created
}
func (s *RepositorySuite) createChat(title string, members ...uuid.UUID) domain.Chat {
s.T().Helper()
created, err := s.store.Chats().Create(s.ctx(), domain.ChatDraft{
Title: title,
MemberIDs: members,
CallerID: members[0],
})
s.Require().NoError(err)
return created
}
func (s *RepositorySuite) TestCreateAssignsIdentityAndTime() {
created := s.createUser("alice")
s.NotEqual(uuid.Nil, created.ID, "идентификатор назначает хранилище")
s.False(created.CreatedAt.IsZero(), "время назначает хранилище")
got, err := s.store.Users().GetByID(s.ctx(), created.ID)
s.Require().NoError(err)
s.Equal(created, got)
}
func (s *RepositorySuite) TestGetUnknownUser() {
_, err := s.store.Users().GetByID(s.ctx(), uuid.New())
s.Require().ErrorIs(err, domain.ErrNotFound)
}
func (s *RepositorySuite) TestDuplicateUsernameRejected() {
s.createUser("alice")
_, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
Username: "alice",
DisplayName: "Другая Алиса",
})
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
}
func (s *RepositorySuite) TestUsernameUniqueUnderConcurrency() {
const attempts = 50
var (
wg sync.WaitGroup
mu sync.Mutex
succeeded int
)
for range attempts {
wg.Go(func() {
_, err := s.store.Users().Create(s.ctx(), domain.UserDraft{
Username: "alice",
DisplayName: "Алиса",
})
mu.Lock()
defer mu.Unlock()
if err == nil {
succeeded++
}
})
}
wg.Wait()
s.Equal(1, succeeded, "username уникален даже при гонке")
}
func (s *RepositorySuite) TestChatRejectsUnknownMember() {
caller := s.createUser("alice")
_, err := s.store.Chats().Create(s.ctx(), domain.ChatDraft{
Title: "Проект",
MemberIDs: []uuid.UUID{caller.ID, uuid.New()},
CallerID: caller.ID,
})
s.Require().ErrorIs(err, domain.ErrUnknownMember,
"ссылочная целостность проверяется там же, где вставка")
}
func (s *RepositorySuite) TestChatVisibleOnlyToMembers() {
member := s.createUser("alice")
outsider := s.createUser("bob")
created := s.createChat("Проект", member.ID)
got, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
s.Require().NoError(err)
s.Equal(created.ID, got.ID)
_, err = s.store.Chats().GetVisible(s.ctx(), created.ID, outsider.ID)
s.Require().ErrorIs(err, domain.ErrNotFound, "чужой чат неотличим от отсутствующего")
page, err := s.store.Chats().ListVisible(s.ctx(), outsider.ID, nil, domain.DefaultPageLimit)
s.Require().NoError(err)
s.Empty(page.Items, "чужой чат не попадает в список")
}
func (s *RepositorySuite) TestStoredChatIsIsolated() {
member := s.createUser("alice")
members := []uuid.UUID{member.ID}
created := s.createChat("Проект", members...)
members[0] = uuid.New()
got, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
s.Require().NoError(err)
s.Equal([]uuid.UUID{member.ID}, got.MemberIDs, "хранилище не делит срез с вызывающим")
got.MemberIDs[0] = uuid.New()
again, err := s.store.Chats().GetVisible(s.ctx(), created.ID, member.ID)
s.Require().NoError(err)
s.Equal([]uuid.UUID{member.ID}, again.MemberIDs)
}
func (s *RepositorySuite) TestChatsSortedByKeyset() {
member := s.createUser("alice")
for range 3 {
s.createChat("Чат", member.ID)
}
page, err := s.store.Chats().ListVisible(s.ctx(), member.ID, nil, domain.DefaultPageLimit)
s.Require().NoError(err)
s.Require().Len(page.Items, 3)
for i := 1; i < len(page.Items); i++ {
s.True(
page.Items[i-1].CreatedAt.Before(page.Items[i].CreatedAt),
"порядок (created_at, id) по возрастанию",
)
}
}
func (s *RepositorySuite) TestMessageRejectsOutsider() {
member := s.createUser("alice")
outsider := s.createUser("bob")
created := s.createChat("Проект", member.ID)
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
ChatID: created.ID,
SenderID: outsider.ID,
Text: "привет",
})
s.Require().ErrorIs(err, domain.ErrNotFound)
_, err = s.store.Messages().ListVisible(s.ctx(), created.ID, outsider.ID, nil, domain.DefaultPageLimit)
s.Require().ErrorIs(err, domain.ErrNotFound)
}
func (s *RepositorySuite) TestMessageHistoryIsolatedPerChat() {
member := s.createUser("alice")
first := s.createChat("Первый", member.ID)
second := s.createChat("Второй", member.ID)
for _, tt := range []struct {
chatID uuid.UUID
text string
}{
{chatID: first.ID, text: "в первом"},
{chatID: second.ID, text: "во втором"},
} {
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
ChatID: tt.chatID,
SenderID: member.ID,
Text: tt.text,
})
s.Require().NoError(err)
}
page, err := s.store.Messages().ListVisible(s.ctx(), first.ID, member.ID, nil, domain.DefaultPageLimit)
s.Require().NoError(err)
s.Require().Len(page.Items, 1)
s.Equal("в первом", page.Items[0].Text)
}
func (s *RepositorySuite) TestEmptyHistoryReturnsEmptyPage() {
member := s.createUser("alice")
created := s.createChat("Проект", member.ID)
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, nil, domain.DefaultPageLimit)
s.Require().NoError(err)
s.NotNil(page.Items, `контракт требует "items": [], а не null`)
s.Empty(page.Items)
s.Nil(page.Next)
}
func (s *RepositorySuite) TestConcurrentMessagesAllStored() {
const (
clients = 10
perClient = 10
total = clients * perClient
readerIterations = 20
)
member := s.createUser("alice")
created := s.createChat("Проект", member.ID)
var wg sync.WaitGroup
failures := make(chan error, total+readerIterations)
for range clients {
wg.Go(func() {
for range perClient {
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
ChatID: created.ID,
SenderID: member.ID,
Text: "сообщение",
})
if err != nil {
failures <- err
}
}
})
}
wg.Go(func() {
for range readerIterations {
_, err := s.store.Messages().ListVisible(
s.ctx(), created.ID, member.ID, nil, domain.DefaultPageLimit,
)
if err != nil {
failures <- err
}
}
})
wg.Wait()
close(failures)
for err := range failures {
s.Require().NoError(err)
}
seen := make(map[uuid.UUID]struct{}, total)
var cursor *domain.Cursor
for {
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, cursor, 7)
s.Require().NoError(err)
for _, msg := range page.Items {
_, duplicate := seen[msg.ID]
s.Require().False(duplicate, "обход истории не должен повторять сообщения")
seen[msg.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, total, "все подтверждённые сообщения должны быть видны следующему чтению")
}
func (s *RepositorySuite) TestPageWalkIsStable() {
const total = 25
member := s.createUser("alice")
created := s.createChat("Проект", member.ID)
for range total {
_, err := s.store.Messages().Create(s.ctx(), domain.MessageDraft{
ChatID: created.ID,
SenderID: member.ID,
Text: "сообщение",
})
s.Require().NoError(err)
}
whole, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, nil, 100)
s.Require().NoError(err)
s.Require().Len(whole.Items, total)
var (
walked []domain.Message
cursor *domain.Cursor
)
for {
page, err := s.store.Messages().ListVisible(s.ctx(), created.ID, member.ID, cursor, 4)
s.Require().NoError(err)
walked = append(walked, page.Items...)
if page.Next == nil {
break
}
cursor = page.Next
}
s.Equal(whole.Items, walked)
}
func TestRepositoriesImplementContracts(t *testing.T) {
t.Parallel()
store := memory.NewStore()
require.Implements(t, (*user.Repository)(nil), store.Users())
require.Implements(t, (*chat.Repository)(nil), store.Chats())
require.Implements(t, (*message.Repository)(nil), store.Messages())
}
-144
View File
@@ -1,144 +0,0 @@
package memory
import (
"cmp"
"slices"
"sync"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type Clock interface {
Now() time.Time
}
type IDGenerator interface {
NewID() uuid.UUID
}
type systemClock struct{}
func (systemClock) Now() time.Time {
return time.Now().UTC()
}
type randomIDGenerator struct{}
func (randomIDGenerator) NewID() uuid.UUID {
return uuid.New()
}
type options struct {
clock Clock
ids IDGenerator
}
type Option func(*options)
func WithClock(clock Clock) Option {
return func(o *options) {
if clock != nil {
o.clock = clock
}
}
}
func WithIDGenerator(ids IDGenerator) Option {
return func(o *options) {
if ids != nil {
o.ids = ids
}
}
}
type Store struct {
clock Clock
ids IDGenerator
mu sync.RWMutex
usersByID map[uuid.UUID]domain.User
usersByUsername map[string]uuid.UUID
chatsByID map[uuid.UUID]domain.Chat
chatsOrdered []domain.Chat
messagesByChat map[uuid.UUID][]domain.Message
users *UserRepository
chats *ChatRepository
messages *MessageRepository
}
func NewStore(opts ...Option) *Store {
cfg := options{clock: systemClock{}, ids: randomIDGenerator{}}
for _, opt := range opts {
opt(&cfg)
}
store := &Store{
clock: cfg.clock,
ids: cfg.ids,
usersByID: make(map[uuid.UUID]domain.User),
usersByUsername: make(map[string]uuid.UUID),
chatsByID: make(map[uuid.UUID]domain.Chat),
messagesByChat: make(map[uuid.UUID][]domain.Message),
}
store.users = &UserRepository{store: store}
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
return store
}
func (s *Store) Users() *UserRepository { return s.users }
func (s *Store) Chats() *ChatRepository { return s.chats }
func (s *Store) Messages() *MessageRepository { return s.messages }
func compareKeyset(aCreatedAt time.Time, aID uuid.UUID, bCreatedAt time.Time, bID uuid.UUID) int {
if c := aCreatedAt.Compare(bCreatedAt); c != 0 {
return c
}
return cmp.Compare(aID.String(), bID.String())
}
func paginate[T any](
items []T,
scope uuid.UUID,
key func(T) (time.Time, uuid.UUID),
after *domain.Cursor,
limit int,
) domain.Page[T] {
start := 0
if after != nil {
start, _ = slices.BinarySearchFunc(items, *after, func(item T, target domain.Cursor) int {
createdAt, id := key(item)
if compareKeyset(createdAt, id, target.CreatedAt, target.ID) > 0 {
return 1
}
return -1
})
}
rest := items[start:]
page := domain.Page[T]{Items: make([]T, 0, min(len(rest), limit))}
if len(rest) <= limit {
page.Items = append(page.Items, rest...)
return page
}
page.Items = append(page.Items, rest[:limit]...)
createdAt, id := key(page.Items[limit-1])
page.Next = &domain.Cursor{Scope: scope, CreatedAt: createdAt, ID: id}
return page
}
-175
View File
@@ -1,175 +0,0 @@
package memory
import (
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
)
type entry struct {
createdAt time.Time
id uuid.UUID
}
func entryKey(e entry) (time.Time, uuid.UUID) {
return e.createdAt, e.id
}
func TestCompareKeyset(t *testing.T) {
t.Parallel()
earlier := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
later := earlier.Add(time.Second)
lowID := uuid.MustParse("11111111-1111-4111-8111-111111111111")
highID := uuid.MustParse("22222222-2222-4222-8222-222222222222")
tests := map[string]struct {
a entry
b entry
want int
}{
"время решает": {
a: entry{createdAt: earlier, id: highID},
b: entry{createdAt: later, id: lowID},
want: -1,
},
"при равном времени решает id": {
a: entry{createdAt: earlier, id: lowID},
b: entry{createdAt: earlier, id: highID},
want: -1,
},
"полное совпадение": {
a: entry{createdAt: earlier, id: lowID},
b: entry{createdAt: earlier, id: lowID},
want: 0,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, compareKeyset(tt.a.createdAt, tt.a.id, tt.b.createdAt, tt.b.id))
assert.Equal(t, -tt.want, compareKeyset(tt.b.createdAt, tt.b.id, tt.a.createdAt, tt.a.id),
"сравнение должно быть антисимметричным")
})
}
}
func makeEntries(n int) []entry {
base := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
items := make([]entry, 0, n)
for i := range n {
items = append(items, entry{
createdAt: base.Add(time.Duration(i) * time.Second),
id: uuid.New(),
})
}
return items
}
func TestPaginateFirstPage(t *testing.T) {
t.Parallel()
scope := uuid.New()
items := makeEntries(5)
page := paginate(items, scope, entryKey, nil, 2)
require.Len(t, page.Items, 2)
assert.Equal(t, items[:2], page.Items)
require.NotNil(t, page.Next)
assert.Equal(t, items[1].id, page.Next.ID)
assert.Equal(t, scope, page.Next.Scope, "курсор должен нести привязку к последовательности")
}
func TestPaginateLastPageHasNoCursor(t *testing.T) {
t.Parallel()
items := makeEntries(3)
page := paginate(items, uuid.New(), entryKey, nil, 3)
assert.Equal(t, items, page.Items)
assert.Nil(t, page.Next, "на последней странице next_cursor равен null")
}
func TestPaginateEmptyResultIsNotNil(t *testing.T) {
t.Parallel()
page := paginate([]entry{}, uuid.New(), entryKey, nil, 10)
assert.NotNil(t, page.Items, `контракт требует "items": [], а не null`)
assert.Empty(t, page.Items)
assert.Nil(t, page.Next)
}
func TestPaginateWalkWithoutDuplicates(t *testing.T) {
t.Parallel()
const (
total = 10
limit = 3
)
scope := uuid.New()
items := makeEntries(total)
var (
seen []entry
cursor *domain.Cursor
)
for range total {
page := paginate(items, scope, entryKey, cursor, limit)
seen = append(seen, page.Items...)
if page.Next == nil {
break
}
cursor = page.Next
}
assert.Equal(t, items, seen)
}
func TestPaginateCursorBeyondEnd(t *testing.T) {
t.Parallel()
scope := uuid.New()
items := makeEntries(3)
last := items[len(items)-1]
page := paginate(items, scope, entryKey, &domain.Cursor{
Scope: scope,
CreatedAt: last.createdAt,
ID: last.id,
}, 10)
assert.Empty(t, page.Items)
assert.Nil(t, page.Next)
}
func TestPaginateChangedLimitOnContinuation(t *testing.T) {
t.Parallel()
scope := uuid.New()
items := makeEntries(6)
first := paginate(items, scope, entryKey, nil, 2)
require.NotNil(t, first.Next)
second := paginate(items, scope, entryKey, first.Next, 4)
assert.Equal(t, items[2:], second.Items)
assert.Nil(t, second.Next, "изменение limit при продолжении допустимо")
}
@@ -1,50 +0,0 @@
package memory
import (
"context"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
)
type UserRepository struct {
store *Store
}
func (r *UserRepository) Create(_ context.Context, draft domain.UserDraft) (domain.User, error) {
s := r.store
s.mu.Lock()
defer s.mu.Unlock()
if _, taken := s.usersByUsername[draft.Username]; taken {
return domain.User{}, domain.ErrUsernameTaken
}
user := domain.User{
ID: s.ids.NewID(),
Username: draft.Username,
DisplayName: draft.DisplayName,
CreatedAt: s.clock.Now(),
}
s.usersByID[user.ID] = user
s.usersByUsername[user.Username] = user.ID
return user, nil
}
func (r *UserRepository) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
s := r.store
s.mu.RLock()
defer s.mu.RUnlock()
user, ok := s.usersByID[id]
if !ok {
return domain.User{}, domain.ErrNotFound
}
return user, nil
}
@@ -0,0 +1,159 @@
//go:build integration
package postgres_test
import (
"context"
"fmt"
"sort"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/storage/redis/mocks"
)
func TestCacheLatencyExperiment(t *testing.T) {
suite := new(BaseSuite)
suite.SetT(t)
suite.SetupTest()
defer suite.TearDownTest()
ctx := context.Background()
redisConfig := cache.RedisConfig{
Host: envOr("TEST_REDIS_HOST", "localhost"),
Port: envInt("TEST_REDIS_PORT", 6379),
Password: envOr("TEST_REDIS_PASSWORD", ""),
DB: envInt("TEST_REDIS_DB", 2),
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
redisCache, err := cache.NewRedis(redisConfig)
require.NoError(t, err)
defer func() { _ = redisCache.Close() }()
alice := suite.createUser("latency_alice")
for range 20 {
suite.createChat(alice)
}
realChats := suite.store.Chats()
var loads atomic.Int32
source := mocks.NewMockChatSource(t)
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, userID uuid.UUID) (int64, error) {
return realChats.ListVersion(ctx, userID)
}).Maybe()
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
loads.Add(1)
return realChats.ListVisible(ctx, callerID, after, limit)
}).Maybe()
for range 50 {
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
require.NoError(t, err)
}
loads.Store(0)
baseline := measureLatency(ctx, t, source.ListVisible, &loads, alice.ID, 1000)
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
require.NoError(t, err)
cached := storageredis.NewChatRepository(
source,
distributed,
time.Minute,
nil,
)
loads.Store(0)
cachedStats := measureCachedLatency(ctx, t, cached, alice.ID, 1000)
cachedStats.Loads = int(loads.Load())
require.Equal(t, 1000, baseline.Loads)
require.Equal(t, 1, cachedStats.Loads)
t.Logf("baseline: %s", formatLatency(baseline))
t.Logf("redis cache: %s", formatLatency(cachedStats))
}
func measureLatency(
ctx context.Context,
t *testing.T,
list func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error),
loads *atomic.Int32,
callerID uuid.UUID,
requests int,
) latencyStats {
t.Helper()
values := make([]time.Duration, 0, requests)
for range requests {
started := time.Now()
_, err := list(ctx, callerID, nil, 50)
require.NoError(t, err)
values = append(values, time.Since(started))
}
return makeLatencyStats(values, int(loads.Load()))
}
func measureCachedLatency(
ctx context.Context,
t *testing.T,
repository *storageredis.ChatRepository,
callerID uuid.UUID,
requests int,
) latencyStats {
t.Helper()
values := make([]time.Duration, 0, requests)
for range requests {
started := time.Now()
_, err := repository.ListVisible(ctx, callerID, nil, 50)
require.NoError(t, err)
values = append(values, time.Since(started))
}
return makeLatencyStats(values, 0)
}
type latencyStats struct {
Requests int
Loads int
P50 time.Duration
P95 time.Duration
P99 time.Duration
}
func makeLatencyStats(values []time.Duration, loads int) latencyStats {
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
percentile := func(percent int) time.Duration {
index := (len(values)*percent + 99) / 100
if index > 0 {
index--
}
return values[index]
}
return latencyStats{
Requests: len(values), Loads: loads,
P50: percentile(50), P95: percentile(95), P99: percentile(99),
}
}
func formatLatency(value latencyStats) string {
return fmt.Sprintf(
"requests=%d source_loads=%d p50=%s p95=%s p99=%s",
value.Requests, value.Loads, value.P50, value.P95, value.P99,
)
}
@@ -0,0 +1,192 @@
//go:build integration
package postgres_test
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/storage/redis/mocks"
)
func TestCachePerformanceExperiment(t *testing.T) {
suite := new(BaseSuite)
suite.SetT(t)
suite.SetupTest()
defer suite.TearDownTest()
ctx := context.Background()
redisConfig := cache.RedisConfig{
Host: envOr("TEST_REDIS_HOST", "localhost"),
Port: envInt("TEST_REDIS_PORT", 6379),
Password: envOr("TEST_REDIS_PASSWORD", ""),
DB: envInt("TEST_REDIS_DB", 2),
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 10,
}
redisCache, err := cache.NewRedis(redisConfig)
require.NoError(t, err)
defer func() { _ = redisCache.Close() }()
alice := suite.createUser("perf_alice")
bob := suite.createUser("perf_bob")
carol := suite.createUser("perf_carol")
for i := range 150 {
title := fmt.Sprintf("Chat %d with Alice", i+1)
members := []uuid.UUID{alice.ID}
if i%3 == 0 {
members = append(members, bob.ID)
}
if i%5 == 0 {
members = append(members, carol.ID)
}
_, err := suite.store.Chats().Create(ctx, domain.ChatDraft{
Title: title,
MemberIDs: members,
})
require.NoError(t, err)
}
realChats := suite.store.Chats()
var loads atomic.Int32
source := mocks.NewMockChatSource(t)
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, userID uuid.UUID) (int64, error) {
return realChats.ListVersion(ctx, userID)
}).Maybe()
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
loads.Add(1)
return realChats.ListVisible(ctx, callerID, after, limit)
}).Maybe()
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
require.NoError(t, err)
cached := storageredis.NewChatRepository(
source,
distributed,
time.Minute,
nil,
)
baselineStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
baselineStats.SQLQueries = int(loads.Load())
loads.Store(0)
cachedStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
cachedStats.SQLQueries = int(loads.Load())
loads.Store(0)
_, err = cached.ListVisible(ctx, alice.ID, nil, 50)
require.NoError(t, err)
cachedHotStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
return err
}, 50, 200)
cachedHotStats.SQLQueries = int(loads.Load())
t.Logf("baseline (no cache): %s", formatPerfStats(baselineStats))
t.Logf("redis cache (cold): %s", formatPerfStats(cachedStats))
t.Logf("redis cache (hot): %s", formatPerfStats(cachedHotStats))
}
type perfStats struct {
TotalRequests int
Concurrency int
SQLQueries int
Duration time.Duration
RPS float64
P50 time.Duration
P95 time.Duration
P99 time.Duration
}
func benchmarkConcurrent(
ctx context.Context,
t *testing.T,
operation func(context.Context) error,
concurrency int,
requestsPerWorker int,
) perfStats {
t.Helper()
totalRequests := concurrency * requestsPerWorker
latencies := make([]time.Duration, totalRequests)
var wg sync.WaitGroup
var failures atomic.Int32
started := time.Now()
for worker := range concurrency {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
offset := workerID * requestsPerWorker
for i := range requestsPerWorker {
reqStart := time.Now()
err := operation(ctx)
if err != nil {
failures.Add(1)
}
latencies[offset+i] = time.Since(reqStart)
}
}(worker)
}
wg.Wait()
require.Zero(t, failures.Load(), "some requests failed")
duration := time.Since(started)
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
percentile := func(p int) time.Duration {
index := (len(latencies)*p + 99) / 100
if index > 0 {
index--
}
return latencies[index]
}
return perfStats{
TotalRequests: totalRequests,
Concurrency: concurrency,
Duration: duration,
RPS: float64(totalRequests) / duration.Seconds(),
P50: percentile(50),
P95: percentile(95),
P99: percentile(99),
}
}
func formatPerfStats(s perfStats) string {
return fmt.Sprintf(
"requests=%d concurrency=%d sql=%d duration=%s rps=%.0f p50=%s p95=%s p99=%s",
s.TotalRequests, s.Concurrency, s.SQLQueries, s.Duration.Round(time.Millisecond),
s.RPS, s.P50, s.P95, s.P99,
)
}
@@ -0,0 +1,162 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type ChatRepository struct {
store *Store
}
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var created domain.Chat
if err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
missing, err := queries.ListMissingUserIDs(ctx, draft.MemberIDs)
if err != nil {
return fmt.Errorf("check chat members: %w", mapError(err))
}
if len(missing) > 0 {
return domain.ErrUnknownMember
}
row, err := queries.CreateChat(ctx, draft.Title)
if err != nil {
return fmt.Errorf("create chat: %w", mapError(err))
}
if err := queries.AddChatMembers(ctx, sqlcgen.AddChatMembersParams{
ChatID: row.ID,
UserIds: draft.MemberIDs,
}); err != nil {
return fmt.Errorf("add chat members: %w", mapError(err))
}
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
return fmt.Errorf("bump chat list versions: %w", mapError(err))
}
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
return nil
}); err != nil {
return domain.Chat{}, err
}
return created, nil
}
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
version, err := r.store.queries.GetChatListVersion(ctx, userID)
if err != nil {
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
}
return version, nil
}
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
sorted := slices.Clone(ids)
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
return bytes.Compare(a[:], b[:])
})
return slices.Compact(sorted)
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetChatForMember(ctx, sqlcgen.GetChatForMemberParams{
UserID: callerID,
ID: chatID,
})
if err != nil {
mapped := mapError(err)
if errors.Is(mapped, domain.ErrNotFound) {
return domain.Chat{}, fmt.Errorf("%w: chat %s for user %s", domain.ErrNotFound, chatID, callerID)
}
return domain.Chat{}, fmt.Errorf("get chat: %w", mapped)
}
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds), nil
}
func (r *ChatRepository) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
limit = clampLimit(limit)
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
var rows []domain.Chat
if after == nil {
pageRows, err := r.store.queries.ListChatsForMember(ctx, sqlcgen.ListChatsForMemberParams{
UserID: callerID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRow)
} else {
pageRows, err := r.store.queries.ListChatsForMemberAfter(ctx, sqlcgen.ListChatsForMemberAfterParams{
UserID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
}
rows = mapAll(pageRows, mapChatRowAfter)
}
return buildPage(rows, limit, func(chat domain.Chat) domain.Cursor {
return domain.Cursor{Scope: callerID, CreatedAt: chat.CreatedAt, ID: chat.ID}
}), nil
}
func mapChatRow(row sqlcgen.ListChatsForMemberRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChatRowAfter(row sqlcgen.ListChatsForMemberAfterRow) domain.Chat {
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
}
func mapChat(id uuid.UUID, title string, createdAt time.Time, memberIDs []uuid.UUID) domain.Chat {
return domain.Chat{
ID: id,
Title: title,
MemberIDs: memberIDs,
CreatedAt: toUTCTime(createdAt),
}
}
@@ -0,0 +1,239 @@
//go:build integration
package postgres_test
import (
"fmt"
"slices"
"sync"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type ChatRepositorySuite struct {
BaseSuite
}
func TestChatRepositorySuite(t *testing.T) {
suite.Run(t, new(ChatRepositorySuite))
}
func (s *ChatRepositorySuite) TestCreateRejectsUnknownMemberAtomically() {
alice := s.createUser("alice")
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "С неизвестным участником",
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
CallerID: alice.ID,
})
s.Require().ErrorIs(err, domain.ErrUnknownMember)
var chats int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chats").Scan(&chats))
s.Zero(chats, "неуспешное создание чата не оставляет строк")
var members int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chat_members").Scan(&members))
s.Zero(members)
}
func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
alice := s.createUser("alice")
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "Дубликаты",
MemberIDs: []uuid.UUID{alice.ID, alice.ID},
CallerID: alice.ID,
})
s.Require().ErrorIs(err, domain.ErrConflict)
}
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
ctx := s.T().Context()
alice := s.createUser("alice")
bob := s.createUser("bob")
carol := s.createUser("carol")
s.createChat(alice, bob)
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
s.Require().NoError(err)
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
s.Require().NoError(err)
s.Equal(int64(1), bobVersion, "member version must be bumped")
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
s.Require().NoError(err)
s.Zero(carolVersion, "non-member version must stay unchanged")
s.createChat(alice, carol)
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
s.Require().NoError(err)
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
s.Require().NoError(err)
s.Equal(int64(1), carolVersion)
}
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
ctx := s.T().Context()
users := make([]domain.User, 0, 8)
for i := range 8 {
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
}
const workers = 16
var wg sync.WaitGroup
errs := make(chan error, workers)
wg.Add(workers)
for w := range workers {
go func(w int) {
defer wg.Done()
ids := []uuid.UUID{
users[w%len(users)].ID,
users[(w+1)%len(users)].ID,
users[(w+2)%len(users)].ID,
}
if w%2 == 1 {
slices.Reverse(ids)
}
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
Title: fmt.Sprintf("chat-%d", w),
MemberIDs: ids,
CallerID: ids[0],
})
if err != nil {
errs <- err
}
}(w)
}
wg.Wait()
close(errs)
for err := range errs {
s.Require().NoError(err)
}
}
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob, eve)
s.Equal(uuid.Version(7), chat.ID.Version())
s.False(chat.CreatedAt.IsZero())
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
s.Require().NoError(err)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID, eve.ID}, visible.MemberIDs)
}
func (s *ChatRepositorySuite) TestVisibility() {
alice := s.createUser("alice")
bob := s.createUser("bob")
eve := s.createUser("eve")
chat := s.createChat(alice, bob)
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
s.Require().NoError(err)
s.Equal(chat.ID, visible.ID)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, visible.MemberIDs)
_, err = s.store.Chats().GetVisible(s.T().Context(), chat.ID, eve.ID)
s.Require().ErrorIs(err, domain.ErrNotFound)
page, err := s.store.Chats().ListVisible(s.T().Context(), eve.ID, nil, 50)
s.Require().NoError(err)
s.Empty(page.Items)
page, err = s.store.Chats().ListVisible(s.T().Context(), alice.ID, nil, 50)
s.Require().NoError(err)
s.Require().Len(page.Items, 1)
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, page.Items[0].MemberIDs)
s.Nil(page.Next)
}
func (s *ChatRepositorySuite) TestListPagination() {
alice := s.createUser("alice")
const total = 5
for range total {
s.createChat(alice)
}
seen := make(map[uuid.UUID]struct{}, total)
var cursor *domain.Cursor
for {
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
s.Require().NoError(err)
s.Require().NotEmpty(page.Items)
for _, chat := range page.Items {
_, duplicate := seen[chat.ID]
s.Require().False(duplicate)
seen[chat.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, total)
}
func (s *ChatRepositorySuite) TestListPaginationWithSharedTimestamp() {
alice := s.createUser("alice")
for range 5 {
s.createChat(alice)
}
_, err := s.pool.Exec(s.T().Context(), "UPDATE chats SET created_at = '2026-01-01 00:00:00+00'")
s.Require().NoError(err)
seen := make(map[uuid.UUID]struct{}, 5)
var cursor *domain.Cursor
for {
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
s.Require().NoError(err)
for _, chat := range page.Items {
_, duplicate := seen[chat.ID]
s.Require().False(duplicate)
seen[chat.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, 5)
}
+74
View File
@@ -0,0 +1,74 @@
package postgres
import (
"errors"
"time"
"mtusi-messenger/internal/config"
)
const (
defaultHost = "localhost"
defaultPort = 5432
defaultDatabase = "messenger"
defaultUser = "messenger"
defaultSSLMode = "disable"
defaultMaxConns = int32(10)
defaultMinConns = int32(1)
defaultMaxConnLifetime = time.Hour
defaultMaxConnIdleTime = 30 * time.Minute
defaultConnectTimeout = 5 * time.Second
defaultQueryTimeout = 5 * time.Second
)
func normalize(cfg config.Postgres) (config.Postgres, error) {
if cfg.Host == "" {
cfg.Host = defaultHost
}
if cfg.Port == 0 {
cfg.Port = defaultPort
}
if cfg.Database == "" {
cfg.Database = defaultDatabase
}
if cfg.User == "" {
cfg.User = defaultUser
}
if cfg.SSLMode == "" {
cfg.SSLMode = defaultSSLMode
}
if cfg.MaxConns == 0 {
cfg.MaxConns = defaultMaxConns
}
if cfg.MinConns == 0 {
cfg.MinConns = defaultMinConns
}
if cfg.MaxConnLifetime == 0 {
cfg.MaxConnLifetime = defaultMaxConnLifetime
}
if cfg.MaxConnIdleTime == 0 {
cfg.MaxConnIdleTime = defaultMaxConnIdleTime
}
if cfg.ConnectTimeout == 0 {
cfg.ConnectTimeout = defaultConnectTimeout
}
if cfg.QueryTimeout == 0 {
cfg.QueryTimeout = defaultQueryTimeout
}
if cfg.MinConns > cfg.MaxConns {
return cfg, errors.New("postgres: min_conns must not exceed max_conns")
}
return cfg, nil
}
+49
View File
@@ -0,0 +1,49 @@
package postgres
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/config"
)
func TestNormalizeAppliesDefaults(t *testing.T) {
cfg, err := normalize(config.Postgres{})
require.NoError(t, err)
require.Equal(t, "localhost", cfg.Host)
require.Equal(t, 5432, cfg.Port)
require.Equal(t, "messenger", cfg.Database)
require.Equal(t, "messenger", cfg.User)
require.Equal(t, "disable", cfg.SSLMode)
require.Equal(t, int32(10), cfg.MaxConns)
require.Equal(t, int32(1), cfg.MinConns)
require.Equal(t, time.Hour, cfg.MaxConnLifetime)
require.Equal(t, 5*time.Second, cfg.ConnectTimeout)
}
func TestNormalizeKeepsProvidedValues(t *testing.T) {
cfg, err := normalize(config.Postgres{
Host: "db",
Port: 6543,
Database: "app",
User: "app",
SSLMode: "require",
MaxConns: 7,
MinConns: 2,
})
require.NoError(t, err)
require.Equal(t, "db", cfg.Host)
require.Equal(t, 6543, cfg.Port)
require.Equal(t, "app", cfg.Database)
require.Equal(t, "require", cfg.SSLMode)
require.Equal(t, int32(7), cfg.MaxConns)
}
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
_, err := normalize(config.Postgres{MinConns: 5, MaxConns: 2})
require.Error(t, err)
}
+76
View File
@@ -0,0 +1,76 @@
package postgres
import (
"context"
"errors"
"fmt"
"io"
"net"
"syscall"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"mtusi-messenger/internal/domain"
)
const (
pgUniqueViolation = "23505"
pgCheckViolation = "23514"
)
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation
}
// isUnavailable reports whether err is a transport-level failure — the server is
// down, the connection dropped, or the pool/query deadline expired — rather than
// a statement-level error. Such failures are dependency outages, not caller errors.
func isUnavailable(err error) bool {
if err == nil {
return false
}
var (
connectErr *pgconn.ConnectError
netErr net.Error
)
return errors.As(err, &connectErr) ||
errors.As(err, &netErr) ||
errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, syscall.ECONNREFUSED) ||
errors.Is(err, syscall.ECONNRESET) ||
errors.Is(err, syscall.EPIPE) ||
errors.Is(err, io.EOF) ||
errors.Is(err, io.ErrUnexpectedEOF) ||
errors.Is(err, pgx.ErrTxClosed) ||
errors.Is(err, pgx.ErrTxCommitRollback)
}
func mapError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrNotFound
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
switch pgErr.Code {
case pgUniqueViolation:
return domain.ErrConflict
case pgCheckViolation:
return domain.ErrValidation
}
}
if isUnavailable(err) {
return fmt.Errorf("%w: %w", domain.ErrUnavailable, err)
}
return err
}
@@ -0,0 +1,251 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: chats.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const addChatMembers = `-- name: AddChatMembers :exec
INSERT INTO chat_members (chat_id, user_id)
SELECT $1, members.member_id
FROM unnest($2::uuid[]) AS members(member_id)
`
type AddChatMembersParams struct {
ChatID uuid.UUID
UserIds []uuid.UUID
}
func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error {
_, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds)
return err
}
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
INSERT INTO user_chat_versions (user_id, version)
SELECT DISTINCT m, 1
FROM unnest($1::uuid[]) AS m
ORDER BY m
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
`
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
return err
}
const createChat = `-- name: CreateChat :one
INSERT INTO chats (title)
VALUES ($1)
RETURNING id, title, created_at
`
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
row := q.db.QueryRow(ctx, createChat, title)
var i Chat
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
return i, err
}
const getChatForMember = `-- name: GetChatForMember :one
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible
ON visible.chat_id = c.id AND visible.user_id = $1
WHERE c.id = $2
`
type GetChatForMemberParams struct {
UserID uuid.UUID
ID uuid.UUID
}
type GetChatForMemberRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberParams) (GetChatForMemberRow, error) {
row := q.db.QueryRow(ctx, getChatForMember, arg.UserID, arg.ID)
var i GetChatForMemberRow
err := row.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
)
return i, err
}
const getChatListVersion = `-- name: GetChatListVersion :one
SELECT COALESCE(MAX(version), 0)::bigint AS version
FROM user_chat_versions
WHERE user_id = $1
`
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, getChatListVersion, userID)
var version int64
err := row.Scan(&version)
return version, err
}
const listChatsForMember = `-- name: ListChatsForMember :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = $1
ORDER BY c.created_at, c.id
LIMIT $2
`
type ListChatsForMemberParams struct {
UserID uuid.UUID
RowLimit int32
}
type ListChatsForMemberRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsForMember(ctx context.Context, arg ListChatsForMemberParams) ([]ListChatsForMemberRow, error) {
rows, err := q.db.Query(ctx, listChatsForMember, arg.UserID, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsForMemberRow{}
for rows.Next() {
var i ListChatsForMemberRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listChatsForMemberAfter = `-- name: ListChatsForMemberAfter :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = $1
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
ORDER BY c.created_at, c.id
LIMIT $4
`
type ListChatsForMemberAfterParams struct {
UserID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
RowLimit int32
}
type ListChatsForMemberAfterRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
MemberIds []uuid.UUID
}
func (q *Queries) ListChatsForMemberAfter(ctx context.Context, arg ListChatsForMemberAfterParams) ([]ListChatsForMemberAfterRow, error) {
rows, err := q.db.Query(ctx, listChatsForMemberAfter,
arg.UserID,
arg.AfterCreatedAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsForMemberAfterRow{}
for rows.Next() {
var i ListChatsForMemberAfterRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.MemberIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMissingUserIDs = `-- name: ListMissingUserIDs :many
SELECT input.id::uuid AS missing_id
FROM unnest($1::uuid[]) AS input(id)
LEFT JOIN users u ON u.id = input.id
WHERE u.id IS NULL
`
func (q *Queries) ListMissingUserIDs(ctx context.Context, userIds []uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, listMissingUserIDs, userIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var missing_id uuid.UUID
if err := rows.Scan(&missing_id); err != nil {
return nil, err
}
items = append(items, missing_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlcgen
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,160 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: messages.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createMessage = `-- name: CreateMessage :one
INSERT INTO messages (chat_id, sender_id, text)
SELECT $1, $2, $3
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
RETURNING id, chat_id, sender_id, text, created_at
`
type CreateMessageParams struct {
ChatID uuid.UUID
SenderID uuid.UUID
Text string
}
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
row := q.db.QueryRow(ctx, createMessage, arg.ChatID, arg.SenderID, arg.Text)
var i Message
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
const isChatMember = `-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
) AS is_member
`
type IsChatMemberParams struct {
ChatID uuid.UUID
UserID uuid.UUID
}
func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) {
row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID)
var is_member bool
err := row.Scan(&is_member)
return is_member, err
}
const listMessagesForChat = `-- name: ListMessagesForChat :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = $1
WHERE m.chat_id = $2
ORDER BY m.created_at, m.id
LIMIT $3
`
type ListMessagesForChatParams struct {
CallerID uuid.UUID
ChatID uuid.UUID
RowLimit int32
}
func (q *Queries) ListMessagesForChat(ctx context.Context, arg ListMessagesForChatParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesForChat, arg.CallerID, arg.ChatID, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessagesForChatAfter = `-- name: ListMessagesForChatAfter :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = $1
WHERE m.chat_id = $2
AND (m.created_at, m.id) > ($3::timestamptz, $4::uuid)
ORDER BY m.created_at, m.id
LIMIT $5
`
type ListMessagesForChatAfterParams struct {
CallerID uuid.UUID
ChatID uuid.UUID
AfterCreatedAt time.Time
AfterID uuid.UUID
RowLimit int32
}
func (q *Queries) ListMessagesForChatAfter(ctx context.Context, arg ListMessagesForChatAfterParams) ([]Message, error) {
rows, err := q.db.Query(ctx, listMessagesForChatAfter,
arg.CallerID,
arg.ChatID,
arg.AfterCreatedAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var i Message
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,51 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package sqlcgen
import (
"time"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
CreatedAt time.Time
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type Session struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
CreatedAt time.Time
}
type User struct {
ID uuid.UUID
Username string
PasswordHash string
DisplayName string
CreatedAt time.Time
}
type UserChatVersion struct {
UserID uuid.UUID
Version int64
}
@@ -0,0 +1,83 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: sessions.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createSession = `-- name: CreateSession :one
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, $3)
RETURNING token_hash, user_id, expires_at
`
type CreateSessionParams struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
type CreateSessionRow struct {
TokenHash []byte
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (CreateSessionRow, error) {
row := q.db.QueryRow(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
var i CreateSessionRow
err := row.Scan(&i.TokenHash, &i.UserID, &i.ExpiresAt)
return i, err
}
const deleteSession = `-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = $1
AND user_id = $2
`
type DeleteSessionParams struct {
TokenHash []byte
UserID uuid.UUID
}
func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) error {
_, err := q.db.Exec(ctx, deleteSession, arg.TokenHash, arg.UserID)
return err
}
const getSessionUser = `-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1
AND s.expires_at > now()
`
type GetSessionUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
ExpiresAt time.Time
}
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
row := q.db.QueryRow(ctx, getSessionUser, tokenHash)
var i GetSessionUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
@@ -0,0 +1,100 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: users.sql
package sqlcgen
import (
"context"
"time"
"github.com/google/uuid"
)
const createUser = `-- name: CreateUser :one
INSERT INTO users (username, display_name, password_hash)
VALUES ($1, $2, $3)
RETURNING id, username, display_name, created_at, password_hash
`
type CreateUserParams struct {
Username string
DisplayName string
PasswordHash string
}
type CreateUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
var i CreateUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
const getUserByID = `-- name: GetUserByID :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE id = $1
`
type GetUserByIDRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (GetUserByIDRow, error) {
row := q.db.QueryRow(ctx, getUserByID, id)
var i GetUserByIDRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
const getUserByUsername = `-- name: GetUserByUsername :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE username = $1
`
type GetUserByUsernameRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
}
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (GetUserByUsernameRow, error) {
row := q.db.QueryRow(ctx, getUserByUsername, username)
var i GetUserByUsernameRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
)
return i, err
}
+278
View File
@@ -0,0 +1,278 @@
//go:build integration
package postgres_test
import (
"context"
"database/sql"
"fmt"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/pressly/goose/v3"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/storage/postgres"
"mtusi-messenger/internal/storage/postgres/migrations"
_ "github.com/jackc/pgx/v5/stdlib"
)
const templateDB = "messenger_template"
var adminPool *pgxpool.Pool
func envOr(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testConfig() config.Postgres {
return config.Postgres{
Host: envOr("TEST_POSTGRES_HOST", "localhost"),
Port: envInt("TEST_POSTGRES_PORT", 5432),
Database: envOr("TEST_POSTGRES_DATABASE", "messenger"),
User: envOr("TEST_POSTGRES_USER", "messenger"),
Password: envOr("TEST_POSTGRES_PASSWORD", "messenger"),
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "disable"),
MaxConns: 5,
MinConns: 1,
MaxConnLifetime: time.Hour,
MaxConnIdleTime: 30 * time.Minute,
ConnectTimeout: 5 * time.Second,
QueryTimeout: 5 * time.Second,
}
}
func dsnFor(database string) string {
cfg := testConfig()
cfg.Database = database
return cfg.DSN()
}
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
adminPool, err = pgxpool.New(ctx, dsnFor(testConfig().Database))
if err != nil {
fmt.Fprintln(os.Stderr, "admin pool:", err)
os.Exit(1)
}
if err := waitForDatabase(ctx, adminPool); err != nil {
fmt.Fprintln(os.Stderr, "database is not ready:", err)
os.Exit(1)
}
if err := recreateTemplate(ctx); err != nil {
fmt.Fprintln(os.Stderr, "create template:", err)
os.Exit(1)
}
code := m.Run()
adminPool.Close()
os.Exit(code)
}
func waitForDatabase(ctx context.Context, pool *pgxpool.Pool) error {
var lastErr error
for range 60 {
err := pool.Ping(ctx)
if err == nil {
return nil
}
lastErr = err
time.Sleep(500 * time.Millisecond)
}
return lastErr
}
func adminExec(ctx context.Context, query string) error {
conn, err := adminPool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
_, err = conn.Conn().PgConn().Exec(ctx, query).ReadAll()
return err
}
const templateLockKey int64 = 0x6d657373656e6765
func withAdvisoryLock(ctx context.Context, shared bool, fn func() error) error {
conn, err := adminPool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
lock, unlock := "pg_advisory_lock", "pg_advisory_unlock"
if shared {
lock, unlock = "pg_advisory_lock_shared", "pg_advisory_unlock_shared"
}
if _, err := conn.Exec(ctx, "SELECT "+lock+"($1)", templateLockKey); err != nil {
return err
}
defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), "SELECT "+unlock+"($1)", templateLockKey) }()
return fn()
}
func recreateTemplate(ctx context.Context) error {
return withAdvisoryLock(ctx, false, func() error {
if err := adminExec(ctx, "DROP DATABASE IF EXISTS "+templateDB+" WITH (FORCE)"); err != nil {
return err
}
if err := adminExec(ctx, "CREATE DATABASE "+templateDB); err != nil {
return err
}
db, err := sql.Open("pgx", dsnFor(templateDB))
if err != nil {
return err
}
defer func() { _ = db.Close() }()
if err := db.PingContext(ctx); err != nil {
return err
}
goose.SetBaseFS(migrations.FS)
if err := goose.SetDialect("postgres"); err != nil {
return err
}
return goose.Up(db, ".")
})
}
type BaseSuite struct {
suite.Suite
store *postgres.Store
pool *pgxpool.Pool
db string
}
func (s *BaseSuite) SetupTest() {
ctx := s.T().Context()
s.db = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
s.Require().NoError(withAdvisoryLock(ctx, true, func() error {
return adminExec(ctx, "CREATE DATABASE "+s.db+" TEMPLATE "+templateDB)
}))
var err error
s.pool, err = pgxpool.New(ctx, dsnFor(s.db))
s.Require().NoError(err)
s.store = openStore(s.T(), s.db, nil)
}
func (s *BaseSuite) TearDownTest() {
if s.store != nil {
s.store.Close()
}
if s.pool != nil {
s.pool.Close()
}
if s.db != "" {
s.Require().NoError(adminExec(s.T().Context(), "DROP DATABASE "+s.db+" WITH (FORCE)"))
}
}
func openStore(t *testing.T, database string, override func(*config.Postgres)) *postgres.Store {
t.Helper()
cfg := testConfig()
cfg.Database = database
if override != nil {
override(&cfg)
}
store, err := postgres.New(t.Context(), cfg)
require.NoError(t, err)
return store
}
func (s *BaseSuite) createUser(username string) domain.User {
s.T().Helper()
hash, err := password.Hash("strong-test-password")
s.Require().NoError(err)
user, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
Username: username,
DisplayName: "Пользователь " + username,
PasswordHash: hash,
})
s.Require().NoError(err)
return user
}
func (s *BaseSuite) createChat(owner domain.User, members ...domain.User) domain.Chat {
s.T().Helper()
ids := []uuid.UUID{owner.ID}
for _, member := range members {
ids = append(ids, member.ID)
}
chat, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
Title: "Чат",
MemberIDs: ids,
CallerID: owner.ID,
})
s.Require().NoError(err)
return chat
}
+21
View File
@@ -0,0 +1,21 @@
package postgres
import "time"
func toUTCTime(t time.Time) time.Time {
if t.Location() == time.UTC {
return t
}
return t.UTC()
}
func mapAll[S, D any](rows []S, mapRow func(S) D) []D {
mapped := make([]D, 0, len(rows))
for _, row := range rows {
mapped = append(mapped, mapRow(row))
}
return mapped
}
@@ -0,0 +1,118 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type MessageRepository struct {
store *Store
}
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
ChatID: draft.ChatID,
SenderID: draft.SenderID,
Text: draft.Text,
})
if err != nil {
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
}
func (r *MessageRepository) ListVisible(
ctx context.Context,
chatID, callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Message], error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
limit = clampLimit(limit)
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
if err != nil {
return domain.Page[domain.Message]{}, err
}
if len(messages) == 0 {
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
ChatID: chatID,
UserID: callerID,
})
if err != nil {
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
}
if !member {
return domain.Page[domain.Message]{}, fmt.Errorf(
"%w: chat %s for user %s",
domain.ErrNotFound, chatID, callerID,
)
}
}
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
}), nil
}
func (r *MessageRepository) fetch(
ctx context.Context,
chatID, callerID uuid.UUID,
after *domain.Cursor,
fetch int32,
) ([]domain.Message, error) {
if after == nil {
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
ChatID: chatID,
CallerID: callerID,
RowLimit: fetch,
})
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
}
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
ChatID: chatID,
CallerID: callerID,
AfterCreatedAt: after.CreatedAt,
AfterID: after.ID,
RowLimit: fetch,
})
if err != nil {
return nil, fmt.Errorf("list messages: %w", mapError(err))
}
return mapAll(rows, mapMessageRow), nil
}
func mapMessageRow(row sqlcgen.Message) domain.Message {
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
}
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
return domain.Message{
ID: id,
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: toUTCTime(createdAt),
}
}
@@ -0,0 +1,157 @@
//go:build integration
package postgres_test
import (
"fmt"
"sync"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
)
type MessageRepositorySuite struct {
BaseSuite
}
func TestMessageRepositorySuite(t *testing.T) {
suite.Run(t, new(MessageRepositorySuite))
}
func (s *MessageRepositorySuite) TestCreateAndPagination() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice, bob)
const total = 5
for i := range total {
message, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("сообщение %d", i),
})
s.Require().NoError(err)
s.Equal(uuid.Version(7), message.ID.Version())
s.False(message.CreatedAt.IsZero())
}
seen := make(map[uuid.UUID]struct{}, total)
var cursor *domain.Cursor
for {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
s.Require().NoError(err)
s.Require().NotEmpty(page.Items)
for _, message := range page.Items {
_, duplicate := seen[message.ID]
s.Require().False(duplicate, "keyset-пагинация не повторяет сообщения")
seen[message.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, total)
}
func (s *MessageRepositorySuite) TestPaginationWithSharedTimestamp() {
alice := s.createUser("alice")
chat := s.createChat(alice)
for range 5 {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID, SenderID: alice.ID, Text: "same timestamp",
})
s.Require().NoError(err)
}
_, err := s.pool.Exec(s.T().Context(), "UPDATE messages SET created_at = '2026-01-01 00:00:00+00'")
s.Require().NoError(err)
seen := make(map[uuid.UUID]struct{}, 5)
var cursor *domain.Cursor
for {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
s.Require().NoError(err)
for _, message := range page.Items {
_, duplicate := seen[message.ID]
s.Require().False(duplicate)
seen[message.ID] = struct{}{}
}
if page.Next == nil {
break
}
cursor = page.Next
}
s.Len(seen, 5)
}
func (s *MessageRepositorySuite) TestAccessIsRestricted() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice)
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: bob.ID,
Text: "чужое",
})
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может писать в чат")
_, err = s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может читать историю")
}
func (s *MessageRepositorySuite) TestListingForMissingChatReturnsNotFound() {
alice := s.createUser("alice")
_, err := s.store.Messages().ListVisible(s.T().Context(), uuid.New(), alice.ID, nil, 50)
s.Require().ErrorIs(err, domain.ErrNotFound)
}
func (s *MessageRepositorySuite) TestFinishedMessageSurvivesConcurrentReads() {
alice := s.createUser("alice")
chat := s.createChat(alice)
const total = 20
var wg sync.WaitGroup
wg.Go(func() {
for i := range total {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("message %d", i),
})
if err != nil {
return
}
}
})
for range total {
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, nil, 100)
s.Require().NoError(err)
s.LessOrEqual(len(page.Items), total)
}
wg.Wait()
}
@@ -0,0 +1,71 @@
-- +goose Up
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT uuidv7(),
username text NOT NULL,
password_hash text NOT NULL,
display_name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_not_blank CHECK (btrim(display_name) <> ''),
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE chats (
id uuid PRIMARY KEY DEFAULT uuidv7(),
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT chats_title_not_blank CHECK (btrim(title) <> '')
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE messages (
id uuid PRIMARY KEY DEFAULT uuidv7(),
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> ''),
CONSTRAINT messages_text_length CHECK (char_length(text) <= 4000)
);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE user_chat_versions (
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
version bigint NOT NULL DEFAULT 0
);
CREATE INDEX messages_chat_id_created_at_id_idx
ON messages (chat_id, created_at, id);
CREATE INDEX chat_members_user_id_chat_id_idx
ON chat_members (user_id, chat_id);
CREATE INDEX chats_created_at_id_idx
ON chats (created_at, id);
CREATE INDEX sessions_user_id_idx
ON sessions (user_id);
-- +goose Down
DROP TABLE sessions;
DROP TABLE messages;
DROP TABLE chat_members;
DROP TABLE chats;
DROP TABLE users;
DROP TABLE user_chat_versions;
@@ -0,0 +1,6 @@
package migrations
import "embed"
//go:embed *.sql
var FS embed.FS
+25
View File
@@ -0,0 +1,25 @@
package postgres
import "mtusi-messenger/internal/domain"
const (
minPageSize = 1
maxPageSize = 100
)
func clampLimit(limit int) int {
return min(max(limit, minPageSize), maxPageSize)
}
func buildPage[T any](items []T, limit int, cursor func(item T) domain.Cursor) domain.Page[T] {
if len(items) > limit {
next := cursor(items[limit-1])
return domain.Page[T]{
Items: append([]T(nil), items[:limit]...),
Next: &next,
}
}
return domain.Page[T]{Items: append([]T(nil), items...)}
}
@@ -0,0 +1,75 @@
-- name: CreateChat :one
INSERT INTO chats (title)
VALUES (sqlc.arg(title))
RETURNING id, title, created_at;
-- name: AddChatMembers :exec
INSERT INTO chat_members (chat_id, user_id)
SELECT sqlc.arg(chat_id), members.member_id
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS members(member_id);
-- name: ListMissingUserIDs :many
SELECT input.id::uuid AS missing_id
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
LEFT JOIN users u ON u.id = input.id
WHERE u.id IS NULL;
-- name: BumpChatListVersions :exec
INSERT INTO user_chat_versions (user_id, version)
SELECT DISTINCT m, 1
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
ORDER BY m
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
-- name: GetChatListVersion :one
SELECT COALESCE(MAX(version), 0)::bigint AS version
FROM user_chat_versions
WHERE user_id = sqlc.arg(user_id);
-- name: GetChatForMember :one
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible
ON visible.chat_id = c.id AND visible.user_id = sqlc.arg(user_id)
WHERE c.id = sqlc.arg(id);
-- name: ListChatsForMember :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = sqlc.arg(user_id)
ORDER BY c.created_at, c.id
LIMIT sqlc.arg(row_limit);
-- name: ListChatsForMemberAfter :many
SELECT
c.id,
c.title,
c.created_at,
(
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
FROM chat_members m
WHERE m.chat_id = c.id
)::uuid[] AS member_ids
FROM chats c
JOIN chat_members visible ON visible.chat_id = c.id
WHERE visible.user_id = sqlc.arg(user_id)
AND (c.created_at, c.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
ORDER BY c.created_at, c.id
LIMIT sqlc.arg(row_limit);
@@ -0,0 +1,39 @@
-- name: CreateMessage :one
INSERT INTO messages (chat_id, sender_id, text)
SELECT sqlc.arg(chat_id), sqlc.arg(sender_id), sqlc.arg(text)
WHERE EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(sender_id)
)
RETURNING id, chat_id, sender_id, text, created_at;
-- name: IsChatMember :one
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = sqlc.arg(chat_id)
AND user_id = sqlc.arg(user_id)
) AS is_member;
-- name: ListMessagesForChat :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = sqlc.arg(caller_id)
WHERE m.chat_id = sqlc.arg(chat_id)
ORDER BY m.created_at, m.id
LIMIT sqlc.arg(row_limit);
-- name: ListMessagesForChatAfter :many
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM messages m
JOIN chat_members cm
ON cm.chat_id = m.chat_id
AND cm.user_id = sqlc.arg(caller_id)
WHERE m.chat_id = sqlc.arg(chat_id)
AND (m.created_at, m.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
ORDER BY m.created_at, m.id
LIMIT sqlc.arg(row_limit);
@@ -0,0 +1,16 @@
-- name: CreateSession :one
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
RETURNING token_hash, user_id, expires_at;
-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = sqlc.arg(token_hash)
AND s.expires_at > now();
-- name: DeleteSession :exec
DELETE FROM sessions
WHERE token_hash = sqlc.arg(token_hash)
AND user_id = sqlc.arg(user_id);
@@ -0,0 +1,14 @@
-- name: CreateUser :one
INSERT INTO users (username, display_name, password_hash)
VALUES (sqlc.arg(username), sqlc.arg(display_name), sqlc.arg(password_hash))
RETURNING id, username, display_name, created_at, password_hash;
-- name: GetUserByID :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE id = sqlc.arg(id);
-- name: GetUserByUsername :one
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE username = sqlc.arg(username);
@@ -0,0 +1,94 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type SessionRepository struct {
store *Store
}
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetUserByUsername(ctx, username)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.UserCredentials{}, fmt.Errorf("%w: username %q", domain.ErrUnauthenticated, username)
}
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
}
return domain.UserCredentials{
User: domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
},
PasswordHash: row.PasswordHash,
}, nil
}
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateSession(ctx, sqlcgen.CreateSessionParams{
TokenHash: session.TokenHash,
UserID: session.UserID,
ExpiresAt: session.ExpiresAt,
})
if err != nil {
return domain.Session{}, fmt.Errorf("create session: %w", mapError(err))
}
return domain.Session{ExpiresAt: toUTCTime(row.ExpiresAt)}, nil
}
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetSessionUser(ctx, tokenHash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.Session{}, fmt.Errorf("%w: session not found or expired", domain.ErrUnauthenticated)
}
return domain.Session{}, fmt.Errorf("resolve session: %w", mapError(err))
}
return domain.Session{
ExpiresAt: toUTCTime(row.ExpiresAt),
User: domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
},
}, nil
}
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
if err := r.store.queries.DeleteSession(
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
); err != nil {
return fmt.Errorf("revoke session: %w", mapError(err))
}
return nil
}
@@ -0,0 +1,81 @@
//go:build integration
package postgres_test
import (
"testing"
"time"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
"mtusi-messenger/internal/platform/token"
)
type SessionRepositorySuite struct {
BaseSuite
}
func TestSessionRepositorySuite(t *testing.T) {
suite.Run(t, new(SessionRepositorySuite))
}
func (s *SessionRepositorySuite) TestCredentials() {
alice := s.createUser("alice")
credentials, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
s.Require().NoError(err)
s.Equal(alice.ID, credentials.User.ID)
s.True(password.Verify("strong-test-password", credentials.PasswordHash))
s.False(password.Verify("wrong-password-value", credentials.PasswordHash))
}
func (s *SessionRepositorySuite) TestCredentialsUnknownUser() {
_, err := s.store.Sessions().Credentials(s.T().Context(), "nobody")
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestCreateResolveRevoke() {
alice := s.createUser("alice")
_, hash, err := token.New().Generate()
s.Require().NoError(err)
expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)
created, err := s.store.Sessions().Create(s.T().Context(), domain.NewSession{
TokenHash: hash,
UserID: alice.ID,
ExpiresAt: expiresAt,
})
s.Require().NoError(err)
s.Equal(expiresAt, created.ExpiresAt)
resolved, err := s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().NoError(err)
s.Equal(alice.ID, resolved.User.ID)
s.Equal(created.ExpiresAt, resolved.ExpiresAt)
s.Require().NoError(s.store.Sessions().Revoke(s.T().Context(), alice.ID, hash))
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestResolveRejectsExpiredToken() {
alice := s.createUser("alice")
_, hash, err := token.New().Generate()
s.Require().NoError(err)
_, err = s.store.Sessions().Create(s.T().Context(), domain.NewSession{
TokenHash: hash,
UserID: alice.ID,
ExpiresAt: time.Now().UTC().Add(-time.Minute),
})
s.Require().NoError(err)
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
+94
View File
@@ -0,0 +1,94 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type Store struct {
pool *pgxpool.Pool
queries *sqlcgen.Queries
queryTimeout time.Duration
users *UserRepository
chats *ChatRepository
messages *MessageRepository
sessions *SessionRepository
}
func New(ctx context.Context, cfg config.Postgres) (*Store, error) {
cfg, err := normalize(cfg)
if err != nil {
return nil, fmt.Errorf("normalize database config: %w", err)
}
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
if err != nil {
return nil, fmt.Errorf("parse database dsn: %w", err)
}
poolCfg.MaxConns = cfg.MaxConns
poolCfg.MinConns = cfg.MinConns
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
store := &Store{
pool: pool,
queries: sqlcgen.New(pool),
queryTimeout: cfg.QueryTimeout,
}
store.users = &UserRepository{store: store}
store.chats = &ChatRepository{store: store}
store.messages = &MessageRepository{store: store}
store.sessions = &SessionRepository{store: store}
return store, nil
}
func (s *Store) Users() *UserRepository { return s.users }
func (s *Store) Chats() *ChatRepository { return s.chats }
func (s *Store) Messages() *MessageRepository { return s.messages }
func (s *Store) Sessions() *SessionRepository { return s.sessions }
func (s *Store) Ping(ctx context.Context) error {
if err := s.pool.Ping(ctx); err != nil {
return fmt.Errorf("ping database: %w", err)
}
return nil
}
func (s *Store) Close() { s.pool.Close() }
func (s *Store) timeout(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return context.WithCancel(ctx)
}
return context.WithTimeout(ctx, s.queryTimeout)
}
+32
View File
@@ -0,0 +1,32 @@
package postgres
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
func (s *Store) RunInTx(ctx context.Context, fn func(queries *sqlcgen.Queries) error) error {
ctx, cancel := s.timeout(ctx)
defer cancel()
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return fmt.Errorf("begin transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(s.queries.WithTx(tx)); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit transaction: %w", err)
}
return nil
}
@@ -0,0 +1,63 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
)
type UserRepository struct {
store *Store
}
func (r *UserRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.CreateUser(ctx, sqlcgen.CreateUserParams{
Username: draft.Username,
DisplayName: draft.DisplayName,
PasswordHash: draft.PasswordHash,
})
if err != nil {
if isUniqueViolation(err) {
return domain.User{}, fmt.Errorf("%w: username %q", domain.ErrUsernameTaken, draft.Username)
}
return domain.User{}, fmt.Errorf("create user: %w", mapError(err))
}
return domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
}, nil
}
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
row, err := r.store.queries.GetUserByID(ctx, id)
if err != nil {
mapped := mapError(err)
if errors.Is(mapped, domain.ErrNotFound) {
return domain.User{}, fmt.Errorf("%w: user %s", domain.ErrNotFound, id)
}
return domain.User{}, fmt.Errorf("get user: %w", mapped)
}
return domain.User{
ID: row.ID,
Username: row.Username,
DisplayName: row.DisplayName,
CreatedAt: toUTCTime(row.CreatedAt),
}, nil
}
@@ -0,0 +1,114 @@
//go:build integration
package postgres_test
import (
"errors"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/password"
)
type UserRepositorySuite struct {
BaseSuite
}
func TestUserRepositorySuite(t *testing.T) {
suite.Run(t, new(UserRepositorySuite))
}
func (s *UserRepositorySuite) TestCreateAndLookup() {
created := s.createUser("alice")
s.NotEqual(uuid.Nil, created.ID)
s.Equal(uuid.Version(7), created.ID.Version())
s.Equal("alice", created.Username)
s.False(created.CreatedAt.IsZero())
found, err := s.store.Users().GetByID(s.T().Context(), created.ID)
s.Require().NoError(err)
s.Equal(created, found)
_, err = s.store.Users().GetByID(s.T().Context(), uuid.New())
s.Require().ErrorIs(err, domain.ErrNotFound)
}
func (s *UserRepositorySuite) TestDuplicateUsernameConflicts() {
s.createUser("alice")
hash, err := password.Hash("strong-test-password")
s.Require().NoError(err)
_, err = s.store.Users().Create(s.T().Context(), domain.NewUser{
Username: "alice",
DisplayName: "Другая Алиса",
PasswordHash: hash,
})
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
}
func (s *UserRepositorySuite) TestConcurrentRegistrationCreatesSingleUser() {
hash, err := password.Hash("strong-test-password")
s.Require().NoError(err)
const attempts = 8
var (
wg sync.WaitGroup
mu sync.Mutex
successes int
failures []error
)
for range attempts {
wg.Go(func() {
_, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
Username: "racer",
DisplayName: "Racer",
PasswordHash: hash,
})
mu.Lock()
defer mu.Unlock()
if err == nil {
successes++
return
}
failures = append(failures, err)
})
}
wg.Wait()
s.Equal(1, successes, "ровно одна регистрация выигрывает гонку")
s.Len(failures, attempts-1)
for _, failure := range failures {
ok := errors.Is(failure, domain.ErrUsernameTaken) || errors.Is(failure, domain.ErrConflict)
s.True(ok, "проигравшая регистрация должна давать конфликт, получено: %v", failure)
}
var count int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM users WHERE username = 'racer'").Scan(&count))
s.Equal(1, count)
}
func (s *UserRepositorySuite) TestQueryTimeoutReturnsError() {
store := openStore(s.T(), s.db, func(cfg *config.Postgres) {
cfg.QueryTimeout = time.Nanosecond
})
defer store.Close()
_, err := store.Users().GetByID(s.T().Context(), uuid.New())
s.Require().Error(err)
s.NotErrorIs(err, domain.ErrNotFound)
}
+183
View File
@@ -0,0 +1,183 @@
package redis
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
)
type ChatSource interface {
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
ListVersion(ctx context.Context, userID uuid.UUID) (int64, error)
ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error)
}
type ChatRepository struct {
source ChatSource
cache *cache.DistributedCache
ttl time.Duration
log *slog.Logger
}
func NewChatRepository(
source ChatSource,
cache *cache.DistributedCache,
ttl time.Duration,
log *slog.Logger,
) *ChatRepository {
return &ChatRepository{source: source, cache: cache, ttl: ttl, log: log}
}
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
return r.source.Create(ctx, draft)
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
return r.source.GetVisible(ctx, chatID, callerID)
}
type sourceError struct{ err error }
func (e sourceError) Error() string { return e.err.Error() }
func (e sourceError) Unwrap() error { return e.err }
const cacheOperationTimeout = 500 * time.Millisecond
func (r *ChatRepository) ListVisible(
ctx context.Context,
callerID uuid.UUID,
after *domain.Cursor,
limit int,
) (domain.Page[domain.Chat], error) {
if after != nil {
return r.source.ListVisible(ctx, callerID, after, limit)
}
version, err := r.source.ListVersion(ctx, callerID)
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("chat list version: %w", err)
}
key := chatListKey(callerID, version, limit)
loader := func(ctx context.Context) ([]byte, error) {
page, err := r.source.ListVisible(ctx, callerID, nil, limit)
if err != nil {
return nil, sourceError{err}
}
return json.Marshal(newChatPageDTO(page))
}
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
defer cancel()
encoded, err := r.cache.GetOrLoad(cctx, key, r.ttl, loader)
if err != nil {
var sourceErr sourceError
switch {
case errors.As(err, &sourceErr):
return domain.Page[domain.Chat]{}, sourceErr.err
case ctx.Err() != nil:
return domain.Page[domain.Chat]{}, ctx.Err()
}
} else {
var dto chatPageDTO
unmarshalErr := json.Unmarshal(encoded, &dto)
if unmarshalErr == nil {
return dto.toDomain(), nil
}
err = unmarshalErr
_ = r.cache.Delete(ctx, key)
}
if r.log != nil {
r.log.WarnContext(ctx, "chat list cache unavailable, falling back to source", slog.Any("error", err))
}
return r.source.ListVisible(ctx, callerID, nil, limit)
}
func chatListKey(userID uuid.UUID, version int64, limit int) string {
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, limit)
}
type chatPageDTO struct {
Items []chatDTO `json:"items"`
Next *cursorDTO `json:"next,omitempty"`
}
type chatDTO struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
type cursorDTO struct {
Scope uuid.UUID `json:"scope"`
CreatedAt time.Time `json:"created_at"`
ID uuid.UUID `json:"id"`
}
func newChatPageDTO(page domain.Page[domain.Chat]) chatPageDTO {
items := make([]chatDTO, 0, len(page.Items))
for _, chat := range page.Items {
items = append(items, chatDTO{
ID: chat.ID,
Title: chat.Title,
MemberIDs: chat.MemberIDs,
CreatedAt: chat.CreatedAt,
})
}
var next *cursorDTO
if page.Next != nil {
next = &cursorDTO{
Scope: page.Next.Scope,
CreatedAt: page.Next.CreatedAt,
ID: page.Next.ID,
}
}
return chatPageDTO{Items: items, Next: next}
}
func (d chatPageDTO) toDomain() domain.Page[domain.Chat] {
items := make([]domain.Chat, 0, len(d.Items))
for _, chat := range d.Items {
items = append(items, domain.Chat{
ID: chat.ID,
Title: chat.Title,
MemberIDs: chat.MemberIDs,
CreatedAt: chat.CreatedAt,
})
}
var next *domain.Cursor
if d.Next != nil {
next = &domain.Cursor{
Scope: d.Next.Scope,
CreatedAt: d.Next.CreatedAt,
ID: d.Next.ID,
}
}
return domain.Page[domain.Chat]{Items: items, Next: next}
}
@@ -0,0 +1,428 @@
//go:build integration
package redis_test
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
cachemocks "mtusi-messenger/internal/platform/cache/mocks"
storageredis "mtusi-messenger/internal/storage/redis"
storagemocks "mtusi-messenger/internal/storage/redis/mocks"
)
type ChatRepositorySuite struct {
suite.Suite
cache *cache.RedisCache
}
func TestChatRepositorySuite(t *testing.T) {
suite.Run(t, new(ChatRepositorySuite))
}
func (s *ChatRepositorySuite) SetupSuite() {
var err error
s.cache, err = cache.NewRedis(testRedisConfig())
s.Require().NoError(err)
s.Require().NoError(s.cache.Ping(s.T().Context()))
s.Require().NoError(flushRedisDB(s.T().Context()))
}
func (s *ChatRepositorySuite) TearDownSuite() {
if s.cache != nil {
s.Require().NoError(s.cache.Close())
}
}
func (s *ChatRepositorySuite) newDistributed() *cache.DistributedCache {
s.T().Helper()
dc, err := cache.NewDistributed(s.cache, cache.DistributedConfig{}, nil)
s.Require().NoError(err)
return dc
}
func (s *ChatRepositorySuite) newRepo(source storageredis.ChatSource) *storageredis.ChatRepository {
s.T().Helper()
return storageredis.NewChatRepository(source, s.newDistributed(), time.Minute, nil)
}
func (s *ChatRepositorySuite) TestFirstPageIsCached() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
repo := s.newRepo(source)
first, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
s.Empty(first.Items)
second, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
s.Empty(second.Items)
}
func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
ctx := s.T().Context()
alice := uuid.New()
bob := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
chat := domain.Chat{
ID: uuid.New(),
Title: "Чат",
MemberIDs: []uuid.UUID{alice, bob},
CreatedAt: time.Now().UTC(),
}
page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
source.EXPECT().Create(mock.Anything, mock.AnythingOfType("domain.ChatDraft")).Return(chat, nil).Once()
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(1), nil).Once()
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(1), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
_, err = repo.ListVisible(ctx, bob, nil, 50)
s.Require().NoError(err)
_, err = repo.Create(ctx, domain.ChatDraft{
Title: "Чат",
MemberIDs: []uuid.UUID{alice, bob},
CallerID: alice,
})
s.Require().NoError(err)
alicePage, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
s.Len(alicePage.Items, 1, "creator must observe the new chat immediately")
bobPage, err := repo.ListVisible(ctx, bob, nil, 50)
s.Require().NoError(err)
s.Len(bobPage.Items, 1, "other member must observe the new chat immediately")
}
func (s *ChatRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
ctx := s.T().Context()
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Twice()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
// Simulate a Redis flush/restart by dropping all cache entries.
s.Require().NoError(flushRedisDB(ctx))
_, err = repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
}
func (s *ChatRepositorySuite) TestDeeperPagesBypassCache() {
ctx := s.T().Context()
alice := uuid.New()
cursor := &domain.Cursor{Scope: alice, CreatedAt: time.Now().UTC(), ID: uuid.New()}
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, cursor, 50)
s.Require().NoError(err)
_, err = repo.ListVisible(ctx, alice, cursor, 50)
s.Require().NoError(err)
}
func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
ctx := s.T().Context()
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 10).Return(empty, nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 10)
s.Require().NoError(err)
_, err = repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
}
func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
ctx := s.T().Context()
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
time.Sleep(25 * time.Millisecond)
return empty, nil
}).Once()
repo := s.newRepo(source)
const workers = 100
var (
wg sync.WaitGroup
failures atomic.Int32
)
wg.Add(workers)
for range workers {
go func() {
defer wg.Done()
if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil {
failures.Add(1)
}
}()
}
wg.Wait()
s.Require().Zero(failures.Load())
s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers)
}
func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
ctx := s.T().Context()
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
time.Sleep(25 * time.Millisecond)
return empty, nil
}).Once()
const (
instances = 3
workersPerInstance = 30
)
repos := make([]*storageredis.ChatRepository, instances)
for i := range repos {
repos[i] = s.newRepo(source)
}
var (
wg sync.WaitGroup
failures atomic.Int32
)
wg.Add(instances * workersPerInstance)
for i := range repos {
repo := repos[i]
for range workersPerInstance {
go func() {
defer wg.Done()
if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil {
failures.Add(1)
}
}()
}
}
wg.Wait()
s.Require().Zero(failures.Load())
s.T().Logf("multi-instance distributed lock: %d instances x %d reads -> 1 source load",
instances, workersPerInstance)
}
func (s *ChatRepositorySuite) TestCacheUnavailableFallsBackToSource() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
lockStore := cachemocks.NewMockLockStore(s.T())
lockStore.EXPECT().Get(mock.Anything, mock.Anything).Return(nil, errors.New("redis down")).Maybe()
distributed, err := cache.NewDistributed(lockStore, cache.DistributedConfig{}, nil)
s.Require().NoError(err)
repo := storageredis.NewChatRepository(source, distributed, time.Minute, nil)
got, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "cache failure must not fail the read")
s.Empty(got.Items)
}
func (s *ChatRepositorySuite) TestBrokenCacheEntryIsDroppedAndRepopulated() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Times(3)
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Twice()
repo := s.newRepo(source)
key := "chat_list:" + alice.String() + ":0:50"
s.Require().NoError(s.cache.Set(ctx, key, []byte("{not json"), time.Minute))
// 1st: garbage -> dropped -> source.
first, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "a corrupted cache entry must not fail the read")
// 2nd: miss -> source -> repopulate.
second, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
// 3rd: served from cache, no source call.
third, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
s.Equal(first, second)
s.Equal(second, third)
}
func (s *ChatRepositorySuite) TestSlowLoaderBeyondCacheBudgetReturnsData() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
release := make(chan struct{})
var calls atomic.Int32
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
if calls.Add(1) == 1 {
<-release // the loader outlives the caller's cache budget
}
return page, nil
}).Maybe()
repo := s.newRepo(source)
started := time.Now()
got, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "budget expiry must fall back to the source, not fail")
s.Empty(got.Items)
s.GreaterOrEqual(time.Since(started), 450*time.Millisecond, "the caller must be bounded by the cache budget")
// Let the background loader finish before the test (and its mock) is torn down.
close(release)
time.Sleep(200 * time.Millisecond)
}
func (s *ChatRepositorySuite) TestSourceErrorIsNotRetried() {
ctx := s.T().Context()
alice := uuid.New()
sentinel := errors.New("postgres down")
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
Return(domain.Page[domain.Chat]{}, sentinel).Once()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().ErrorIs(err, sentinel, "source error must propagate")
}
func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede() {
ctx := s.T().Context()
alice := uuid.New()
key := "naive:" + alice.String()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
var loads atomic.Int32
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
loads.Add(1)
time.Sleep(2 * time.Millisecond)
return empty, nil
}).Maybe()
const workers = 100
var (
wg sync.WaitGroup
failures atomic.Int32
)
wg.Add(workers)
for range workers {
go func() {
defer wg.Done()
// Naive cache-aside without distributed coordination: every concurrent miss loads.
if _, err := s.cache.Get(ctx, key); err != nil {
if _, loadErr := source.ListVisible(ctx, alice, nil, 50); loadErr != nil {
failures.Add(1)
return
}
_ = s.cache.Set(ctx, key, []byte("page"), time.Minute)
}
}()
}
wg.Wait()
s.Require().Zero(failures.Load())
s.Greater(loads.Load(), int32(1), "without distributed coordination concurrent misses stampede the source")
s.T().Logf("stampede demonstration: %d concurrent reads -> %d source loads", workers, loads.Load())
}
+66
View File
@@ -0,0 +1,66 @@
//go:build integration
package redis_test
import (
"context"
"os"
"strconv"
"time"
goredis "github.com/redis/go-redis/v9"
"mtusi-messenger/internal/platform/cache"
)
const testRedisDB = 1
func redisEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func redisEnvInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testRedisConfig() cache.RedisConfig {
return cache.RedisConfig{
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
Password: os.Getenv("TEST_REDIS_PASSWORD"),
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
}
func flushRedisDB(ctx context.Context) error {
cfg := testRedisConfig()
client := goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
defer func() { _ = client.Close() }()
return client.FlushDB(ctx).Err()
}
+331
View File
@@ -0,0 +1,331 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
)
// NewMockChatSource creates a new instance of MockChatSource. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewMockChatSource(t interface {
mock.TestingT
Cleanup(func())
}) *MockChatSource {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockChatSource{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockChatSource is an autogenerated mock type for the ChatSource type
type MockChatSource struct {
mock.Mock
}
type MockChatSource_Expecter struct {
mock *mock.Mock
}
func (_m *MockChatSource) EXPECT() *MockChatSource_Expecter {
return &MockChatSource_Expecter{mock: &_m.Mock}
}
// Create provides a mock function for the type MockChatSource
func (_mock *MockChatSource) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
ret := _mock.Called(ctx, draft)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Chat
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
return returnFunc(ctx, draft)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
r0 = returnFunc(ctx, draft)
} else {
r0 = ret.Get(0).(domain.Chat)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
r1 = returnFunc(ctx, draft)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockChatSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
type MockChatSource_Create_Call struct {
*mock.Call
}
// Create is a helper method to define mock.On call
// - ctx context.Context
// - draft domain.ChatDraft
func (_e *MockChatSource_Expecter) Create(ctx any, draft any) *MockChatSource_Create_Call {
return &MockChatSource_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
}
func (_c *MockChatSource_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockChatSource_Create_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.ChatDraft
if args[1] != nil {
arg1 = args[1].(domain.ChatDraft)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockChatSource_Create_Call) Return(chat domain.Chat, err error) *MockChatSource_Create_Call {
_c.Call.Return(chat, err)
return _c
}
func (_c *MockChatSource_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockChatSource_Create_Call {
_c.Call.Return(run)
return _c
}
// GetVisible provides a mock function for the type MockChatSource
func (_mock *MockChatSource) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
ret := _mock.Called(ctx, chatID, callerID)
if len(ret) == 0 {
panic("no return value specified for GetVisible")
}
var r0 domain.Chat
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
return returnFunc(ctx, chatID, callerID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
r0 = returnFunc(ctx, chatID, callerID)
} else {
r0 = ret.Get(0).(domain.Chat)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
r1 = returnFunc(ctx, chatID, callerID)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockChatSource_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
type MockChatSource_GetVisible_Call struct {
*mock.Call
}
// GetVisible is a helper method to define mock.On call
// - ctx context.Context
// - chatID uuid.UUID
// - callerID uuid.UUID
func (_e *MockChatSource_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockChatSource_GetVisible_Call {
return &MockChatSource_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
}
func (_c *MockChatSource_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockChatSource_GetVisible_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 uuid.UUID
if args[2] != nil {
arg2 = args[2].(uuid.UUID)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockChatSource_GetVisible_Call) Return(chat domain.Chat, err error) *MockChatSource_GetVisible_Call {
_c.Call.Return(chat, err)
return _c
}
func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockChatSource_GetVisible_Call {
_c.Call.Return(run)
return _c
}
// ListVersion provides a mock function for the type MockChatSource
func (_mock *MockChatSource) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
ret := _mock.Called(ctx, userID)
if len(ret) == 0 {
panic("no return value specified for ListVersion")
}
var r0 int64
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int64, error)); ok {
return returnFunc(ctx, userID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int64); ok {
r0 = returnFunc(ctx, userID)
} else {
r0 = ret.Get(0).(int64)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
r1 = returnFunc(ctx, userID)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockChatSource_ListVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVersion'
type MockChatSource_ListVersion_Call struct {
*mock.Call
}
// ListVersion is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
func (_e *MockChatSource_Expecter) ListVersion(ctx any, userID any) *MockChatSource_ListVersion_Call {
return &MockChatSource_ListVersion_Call{Call: _e.mock.On("ListVersion", ctx, userID)}
}
func (_c *MockChatSource_ListVersion_Call) Run(run func(ctx context.Context, userID uuid.UUID)) *MockChatSource_ListVersion_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockChatSource_ListVersion_Call) Return(n int64, err error) *MockChatSource_ListVersion_Call {
_c.Call.Return(n, err)
return _c
}
func (_c *MockChatSource_ListVersion_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID) (int64, error)) *MockChatSource_ListVersion_Call {
_c.Call.Return(run)
return _c
}
// ListVisible provides a mock function for the type MockChatSource
func (_mock *MockChatSource) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
ret := _mock.Called(ctx, callerID, after, limit)
if len(ret) == 0 {
panic("no return value specified for ListVisible")
}
var r0 domain.Page[domain.Chat]
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
return returnFunc(ctx, callerID, after, limit)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
r0 = returnFunc(ctx, callerID, after, limit)
} else {
r0 = ret.Get(0).(domain.Page[domain.Chat])
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
r1 = returnFunc(ctx, callerID, after, limit)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockChatSource_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
type MockChatSource_ListVisible_Call struct {
*mock.Call
}
// ListVisible is a helper method to define mock.On call
// - ctx context.Context
// - callerID uuid.UUID
// - after *domain.Cursor
// - limit int
func (_e *MockChatSource_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockChatSource_ListVisible_Call {
return &MockChatSource_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
}
func (_c *MockChatSource_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockChatSource_ListVisible_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 *domain.Cursor
if args[2] != nil {
arg2 = args[2].(*domain.Cursor)
}
var arg3 int
if args[3] != nil {
arg3 = args[3].(int)
}
run(
arg0,
arg1,
arg2,
arg3,
)
})
return _c
}
func (_c *MockChatSource_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockChatSource_ListVisible_Call {
_c.Call.Return(page, err)
return _c
}
func (_c *MockChatSource_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockChatSource_ListVisible_Call {
_c.Call.Return(run)
return _c
}
+27 -3
View File
@@ -10,7 +10,7 @@ import (
"github.com/ogen-go/ogen/ogenerrors"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/transport/rest/oas"
"mtusi-messenger/internal/transport/rest/internal/oas"
)
var fallbackErrorBody = []byte(`{"error":{"code":"internal_error","message":"Internal error","request_id":""}}`)
@@ -28,21 +28,38 @@ func newErrorHandler(log *slog.Logger) oas.ErrorHandler {
}
func statusForError(err error) int {
var securityErr *ogenerrors.SecurityError
if errors.As(err, &securityErr) {
if status := statusForDomainError(securityErr.Err); status != http.StatusInternalServerError {
return status
}
return http.StatusUnauthorized
}
if status := ogenerrors.ErrorCode(err); status != http.StatusInternalServerError {
return status
}
return statusForDomainError(err)
}
func statusForDomainError(err error) int {
switch {
case errors.Is(err, ErrUnauthenticated):
case errors.Is(err, ErrUnauthenticated), errors.Is(err, domain.ErrUnauthenticated):
return http.StatusUnauthorized
case errors.Is(err, domain.ErrNotFound):
return http.StatusNotFound
case errors.Is(err, domain.ErrUsernameTaken):
case errors.Is(err, domain.ErrUsernameTaken),
errors.Is(err, domain.ErrConflict):
return http.StatusConflict
case errors.Is(err, domain.ErrValidation),
errors.Is(err, domain.ErrUnknownMember),
errors.Is(err, domain.ErrInvalidCursor):
return http.StatusBadRequest
case errors.Is(err, domain.ErrUnavailable):
return http.StatusServiceUnavailable
default:
return http.StatusInternalServerError
}
@@ -85,6 +102,13 @@ func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set(requestIDHeader, requestID)
if status == http.StatusUnauthorized {
challenge := `Bearer realm="messenger"`
if r.URL.Path == "/api/v1/auth/sessions" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
w.Header().Set("WWW-Authenticate", challenge)
}
w.WriteHeader(status)
if _, err := w.Write(payload); err != nil && log != nil {
+69 -5
View File
@@ -6,12 +6,13 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/transport/rest/oas"
"mtusi-messenger/internal/transport/rest/internal/oas"
)
type UserService interface {
@@ -40,24 +41,73 @@ type MessageService interface {
) (domain.Page[domain.Message], error)
}
type HealthChecker interface {
Ping(ctx context.Context) error
}
type SessionService interface {
Create(ctx context.Context, user domain.User) (domain.Session, error)
Revoke(ctx context.Context, userID uuid.UUID, token string) error
}
type Handler struct {
oas.UnimplementedHandler
users UserService
chats ChatService
messages MessageService
health HealthChecker
sessions SessionService
}
var noCursor *domain.Cursor
func NewHandler(users UserService, chats ChatService, messages MessageService) *Handler {
func NewHandler(
users UserService,
chats ChatService,
messages MessageService,
health HealthChecker,
sessions SessionService,
) *Handler {
return &Handler{
users: users,
chats: chats,
messages: messages,
health: health,
sessions: sessions,
}
}
func (h *Handler) CreateSession(ctx context.Context) (oas.CreateSessionRes, error) {
user, ok := ctx.Value(credentialsKey{}).(domain.User)
if !ok {
return nil, domain.ErrUnauthenticated
}
created, err := h.sessions.Create(ctx, user)
if err != nil {
return nil, err
}
return &oas.SessionHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
Response: oas.Session{
Token: created.Token, TokenType: "Bearer", ExpiresAt: created.ExpiresAt, User: userResponse(created.User),
},
}, nil
}
func (h *Handler) RevokeSession(ctx context.Context) (oas.RevokeSessionRes, error) {
token, ok := ctx.Value(tokenKey{}).(string)
if !ok {
return nil, domain.ErrUnauthenticated
}
if err := h.sessions.Revoke(ctx, caller(ctx), token); err != nil {
return nil, err
}
return &oas.RevokeSessionNoContent{XRequestID: oas.NewOptString(requestIDFromContext(ctx))}, nil
}
func (h *Handler) Liveness(ctx context.Context) (oas.LivenessRes, error) {
return &oas.HealthHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
@@ -66,9 +116,22 @@ func (h *Handler) Liveness(ctx context.Context) (oas.LivenessRes, error) {
}
func (h *Handler) Readiness(ctx context.Context) (oas.ReadinessRes, error) {
return &oas.HealthHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
Response: oas.Health{Status: oas.HealthStatusOk},
if h.health == nil || h.health.Ping(ctx) == nil {
return &oas.HealthHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
Response: oas.Health{Status: oas.HealthStatusOk},
}, nil
}
requestID := requestIDFromContext(ctx)
return &oas.ReadinessServiceUnavailable{
XRequestID: oas.NewOptString(requestID),
Response: oas.Error{Error: oas.ErrorError{
Code: oas.ErrorErrorCodeUnavailable,
Message: http.StatusText(http.StatusServiceUnavailable),
RequestID: requestID,
}},
}, nil
}
@@ -76,6 +139,7 @@ func (h *Handler) RegisterUser(ctx context.Context, req *oas.CreateUser) (oas.Re
user, err := h.users.Register(ctx, domain.UserDraft{
Username: req.Username,
DisplayName: req.DisplayName,
Password: req.Password,
})
if err != nil {
return nil, err
@@ -49,14 +49,14 @@ func (s *Server) handleCreateChatRequest(args [0]string, argsEscaped bool, w htt
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, CreateChatOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, CreateChatOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -177,14 +177,14 @@ func (s *Server) handleCreateMessageRequest(args [1]string, argsEscaped bool, w
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, CreateMessageOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, CreateMessageOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -299,6 +299,119 @@ func (s *Server) handleCreateMessageRequest(args [1]string, argsEscaped bool, w
}
}
// handleCreateSessionRequest handles createSession operation.
//
// Вход: Basic username:password; выдаёт сессию.
//
// POST /api/v1/auth/sessions
func (s *Server) handleCreateSessionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
ctx := r.Context()
var (
err error
opErrContext = ogenerrors.OperationContext{
Name: CreateSessionOperation,
ID: "createSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityBasicAuth(ctx, CreateSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "BasicAuth",
Err: err,
}
defer recordError("Security:BasicAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
defer recordError("Security", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
}
var rawBody []byte
var response CreateSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateSessionOperation,
OperationSummary: "Вход: Basic username:password; выдаёт сессию",
OperationID: "createSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = CreateSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateSession(ctx)
return response, err
},
)
} else {
response, err = s.h.CreateSession(ctx)
}
if err != nil {
defer recordError("Internal", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeCreateSessionResponse(response, w); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCurrentUserRequest handles currentUser operation.
//
// Текущий пользователь.
@@ -320,14 +433,14 @@ func (s *Server) handleCurrentUserRequest(args [0]string, argsEscaped bool, w ht
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, CurrentUserOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, CurrentUserOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -433,14 +546,14 @@ func (s *Server) handleGetChatRequest(args [1]string, argsEscaped bool, w http.R
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, GetChatOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, GetChatOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -561,14 +674,14 @@ func (s *Server) handleListChatsRequest(args [0]string, argsEscaped bool, w http
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, ListChatsOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, ListChatsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -693,14 +806,14 @@ func (s *Server) handleListMessagesRequest(args [1]string, argsEscaped bool, w h
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityDevUser(ctx, ListMessagesOperation, r)
sctx, ok, err := s.securityBearerAuth(ctx, ListMessagesOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "DevUser",
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:DevUser", err)
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
@@ -1021,3 +1134,116 @@ func (s *Server) handleRegisterUserRequest(args [0]string, argsEscaped bool, w h
return
}
}
// handleRevokeSessionRequest handles revokeSession operation.
//
// Отозвать текущую сессию.
//
// DELETE /api/v1/auth/sessions/current
func (s *Server) handleRevokeSessionRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
ctx := r.Context()
var (
err error
opErrContext = ogenerrors.OperationContext{
Name: RevokeSessionOperation,
ID: "revokeSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securityBearerAuth(ctx, RevokeSessionOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "BearerAuth",
Err: err,
}
defer recordError("Security:BearerAuth", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
defer recordError("Security", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
}
var rawBody []byte
var response RevokeSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: RevokeSessionOperation,
OperationSummary: "Отозвать текущую сессию",
OperationID: "revokeSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = RevokeSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.RevokeSession(ctx)
return response, err
},
)
} else {
response, err = s.h.RevokeSession(ctx)
}
if err != nil {
defer recordError("Internal", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeRevokeSessionResponse(response, w); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
@@ -9,6 +9,10 @@ type CreateMessageRes interface {
createMessageRes()
}
type CreateSessionRes interface {
createSessionRes()
}
type CurrentUserRes interface {
currentUserRes()
}
@@ -36,3 +40,7 @@ type ReadinessRes interface {
type RegisterUserRes interface {
registerUserRes()
}
type RevokeSessionRes interface {
revokeSessionRes()
}
@@ -531,11 +531,16 @@ func (s *CreateUser) encodeFields(e *jx.Encoder) {
e.FieldStart("display_name")
e.Str(s.DisplayName)
}
{
e.FieldStart("password")
e.Str(s.Password)
}
}
var jsonFieldsNameOfCreateUser = [2]string{
var jsonFieldsNameOfCreateUser = [3]string{
0: "username",
1: "display_name",
2: "password",
}
// Decode decodes CreateUser from json.
@@ -571,6 +576,18 @@ func (s *CreateUser) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"display_name\"")
}
case "password":
requiredBitSet[0] |= 1 << 2
if err := func() error {
v, err := d.Str()
s.Password = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"password\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
@@ -581,7 +598,7 @@ func (s *CreateUser) Decode(d *jx.Decoder) error {
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000011,
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
@@ -1366,6 +1383,151 @@ func (s *NilString) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *Session) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *Session) encodeFields(e *jx.Encoder) {
{
e.FieldStart("token")
e.Str(s.Token)
}
{
e.FieldStart("token_type")
e.Str("Bearer")
}
{
e.FieldStart("expires_at")
json.EncodeDateTime(e, s.ExpiresAt)
}
{
e.FieldStart("user")
s.User.Encode(e)
}
}
var jsonFieldsNameOfSession = [4]string{
0: "token",
1: "token_type",
2: "expires_at",
3: "user",
}
// Decode decodes Session from json.
func (s *Session) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode Session to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "token":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Str()
s.Token = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"token\"")
}
case "token_type":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Str()
s.TokenType = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"token_type\"")
}
case "expires_at":
requiredBitSet[0] |= 1 << 2
if err := func() error {
v, err := json.DecodeDateTime(d)
s.ExpiresAt = v
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"expires_at\"")
}
case "user":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.User.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"user\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode Session")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00001111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfSession) {
name = jsonFieldsNameOfSession[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *Session) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *Session) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *User) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -8,6 +8,7 @@ type OperationName = string
const (
CreateChatOperation OperationName = "CreateChat"
CreateMessageOperation OperationName = "CreateMessage"
CreateSessionOperation OperationName = "CreateSession"
CurrentUserOperation OperationName = "CurrentUser"
GetChatOperation OperationName = "GetChat"
ListChatsOperation OperationName = "ListChats"
@@ -15,4 +16,5 @@ const (
LivenessOperation OperationName = "Liveness"
ReadinessOperation OperationName = "Readiness"
RegisterUserOperation OperationName = "RegisterUser"
RevokeSessionOperation OperationName = "RevokeSession"
)
@@ -77,7 +77,7 @@ func encodeCreateChatResponse(response CreateChatRes, w http.ResponseWriter) err
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -188,7 +188,7 @@ func encodeCreateChatResponse(response CreateChatRes, w http.ResponseWriter) err
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -370,7 +370,7 @@ func encodeCreateMessageResponse(response CreateMessageRes, w http.ResponseWrite
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -481,7 +481,7 @@ func encodeCreateMessageResponse(response CreateMessageRes, w http.ResponseWrite
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -597,6 +597,235 @@ func encodeCreateMessageResponse(response CreateMessageRes, w http.ResponseWrite
}
}
func encodeCreateSessionResponse(response CreateSessionRes, w http.ResponseWriter) error {
switch response := response.(type) {
case *SessionHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionBadRequest:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(400)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "WWW-Authenticate" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "WWW-Authenticate",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.WWWAuthenticate.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode WWW-Authenticate header")
}
}
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(401)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.IntToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionInternalServerError:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(500)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionServiceUnavailable:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(503)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCurrentUserResponse(response CurrentUserRes, w http.ResponseWriter) error {
switch response := response.(type) {
case *UserHeaders:
@@ -663,7 +892,7 @@ func encodeCurrentUserResponse(response CurrentUserRes, w http.ResponseWriter) e
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -774,7 +1003,7 @@ func encodeCurrentUserResponse(response CurrentUserRes, w http.ResponseWriter) e
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -956,7 +1185,7 @@ func encodeGetChatResponse(response GetChatRes, w http.ResponseWriter) error {
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -1067,7 +1296,7 @@ func encodeGetChatResponse(response GetChatRes, w http.ResponseWriter) error {
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -1249,7 +1478,7 @@ func encodeListChatsResponse(response ListChatsRes, w http.ResponseWriter) error
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -1360,7 +1589,7 @@ func encodeListChatsResponse(response ListChatsRes, w http.ResponseWriter) error
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -1542,7 +1771,7 @@ func encodeListMessagesResponse(response ListMessagesRes, w http.ResponseWriter)
return nil
case *ListChatsUnauthorizedHeaders:
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
@@ -1653,7 +1882,7 @@ func encodeListMessagesResponse(response ListMessagesRes, w http.ResponseWriter)
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -2041,7 +2270,7 @@ func encodeRegisterUserResponse(response RegisterUserRes, w http.ResponseWriter)
return nil
case *ListChatsTooManyRequestsHeaders:
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
@@ -2156,3 +2385,193 @@ func encodeRegisterUserResponse(response RegisterUserRes, w http.ResponseWriter)
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeRevokeSessionResponse(response RevokeSessionRes, w http.ResponseWriter) error {
switch response := response.(type) {
case *RevokeSessionNoContent:
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(204)
return nil
case *CreateSessionUnauthorizedHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Www-Authenticate,X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "WWW-Authenticate" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "WWW-Authenticate",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.WWWAuthenticate.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode WWW-Authenticate header")
}
}
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(401)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateSessionTooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After,X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.IntToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RevokeSessionInternalServerError:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(500)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *RevokeSessionServiceUnavailable:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "X-Request-Id" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "X-Request-Id",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.XRequestID.Get(); ok {
return e.EncodeValue(conv.StringToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode X-Request-Id header")
}
}
}
w.WriteHeader(503)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
@@ -11,22 +11,28 @@ import (
)
var (
rn6AllowedHeaders = map[string]string{
"POST": "Authorization",
}
rn13AllowedHeaders = map[string]string{
"DELETE": "Authorization",
}
rn1AllowedHeaders = map[string]string{
"GET": "X-User-Id",
"POST": "Content-Type,X-User-Id",
"GET": "Authorization",
"POST": "Authorization,Content-Type",
}
rn3AllowedHeaders = map[string]string{
"GET": "X-User-Id",
"GET": "Authorization",
}
rn4AllowedHeaders = map[string]string{
"GET": "X-User-Id",
"POST": "Content-Type,X-User-Id",
"GET": "Authorization",
"POST": "Authorization,Content-Type",
}
rn11AllowedHeaders = map[string]string{
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn6AllowedHeaders = map[string]string{
"GET": "X-User-Id",
rn7AllowedHeaders = map[string]string{
"GET": "Authorization",
}
)
@@ -93,6 +99,57 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
break
}
switch elem[0] {
case 'a': // Prefix: "auth/sessions"
if l := len("auth/sessions"); len(elem) >= l && elem[0:l] == "auth/sessions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "POST":
s.handleCreateSessionRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn6AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/current"
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "DELETE":
s.handleRevokeSessionRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn13AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
case 'c': // Prefix: "chats"
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
@@ -204,7 +261,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn11AllowedHeaders,
allowedHeaders: rn12AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -229,7 +286,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: rn6AllowedHeaders,
allowedHeaders: rn7AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -418,6 +475,57 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
break
}
switch elem[0] {
case 'a': // Prefix: "auth/sessions"
if l := len("auth/sessions"); len(elem) >= l && elem[0:l] == "auth/sessions" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "POST":
r.name = CreateSessionOperation
r.summary = "Вход: Basic username:password; выдаёт сессию"
r.operationID = "createSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/auth/sessions"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/current"
if l := len("/current"); len(elem) >= l && elem[0:l] == "/current" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "DELETE":
r.name = RevokeSessionOperation
r.summary = "Отозвать текущую сессию"
r.operationID = "revokeSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/auth/sessions/current"
r.args = args
r.count = 0
return r, true
default:
return
}
}
}
case 'c': // Prefix: "chats"
if l := len("chats"); len(elem) >= l && elem[0:l] == "chats" {
@@ -9,6 +9,67 @@ import (
"github.com/google/uuid"
)
type BasicAuth struct {
Username string
Password string
Roles []string
}
// GetUsername returns the value of Username.
func (s *BasicAuth) GetUsername() string {
return s.Username
}
// GetPassword returns the value of Password.
func (s *BasicAuth) GetPassword() string {
return s.Password
}
// GetRoles returns the value of Roles.
func (s *BasicAuth) GetRoles() []string {
return s.Roles
}
// SetUsername sets the value of Username.
func (s *BasicAuth) SetUsername(val string) {
s.Username = val
}
// SetPassword sets the value of Password.
func (s *BasicAuth) SetPassword(val string) {
s.Password = val
}
// SetRoles sets the value of Roles.
func (s *BasicAuth) SetRoles(val []string) {
s.Roles = val
}
type BearerAuth struct {
Token string
Roles []string
}
// GetToken returns the value of Token.
func (s *BearerAuth) GetToken() string {
return s.Token
}
// GetRoles returns the value of Roles.
func (s *BearerAuth) GetRoles() []string {
return s.Roles
}
// SetToken sets the value of Token.
func (s *BearerAuth) SetToken(val string) {
s.Token = val
}
// SetRoles sets the value of Roles.
func (s *BearerAuth) SetRoles(val []string) {
s.Roles = val
}
// Ref: #/components/schemas/Chat
type Chat struct {
ID uuid.UUID `json:"id"`
@@ -221,10 +282,116 @@ type CreateMessageServiceUnavailable ErrorHeaders
func (*CreateMessageServiceUnavailable) createMessageRes() {}
type CreateSessionBadRequest ErrorHeaders
func (*CreateSessionBadRequest) createSessionRes() {}
type CreateSessionInternalServerError ErrorHeaders
func (*CreateSessionInternalServerError) createSessionRes() {}
type CreateSessionServiceUnavailable ErrorHeaders
func (*CreateSessionServiceUnavailable) createSessionRes() {}
// CreateSessionTooManyRequestsHeaders wraps Error with response headers.
type CreateSessionTooManyRequestsHeaders struct {
RetryAfter OptInt
XRequestID OptString
Response Error
}
// GetRetryAfter returns the value of RetryAfter.
func (s *CreateSessionTooManyRequestsHeaders) GetRetryAfter() OptInt {
return s.RetryAfter
}
// GetXRequestID returns the value of XRequestID.
func (s *CreateSessionTooManyRequestsHeaders) GetXRequestID() OptString {
return s.XRequestID
}
// GetResponse returns the value of Response.
func (s *CreateSessionTooManyRequestsHeaders) GetResponse() Error {
return s.Response
}
// SetRetryAfter sets the value of RetryAfter.
func (s *CreateSessionTooManyRequestsHeaders) SetRetryAfter(val OptInt) {
s.RetryAfter = val
}
// SetXRequestID sets the value of XRequestID.
func (s *CreateSessionTooManyRequestsHeaders) SetXRequestID(val OptString) {
s.XRequestID = val
}
// SetResponse sets the value of Response.
func (s *CreateSessionTooManyRequestsHeaders) SetResponse(val Error) {
s.Response = val
}
func (*CreateSessionTooManyRequestsHeaders) createChatRes() {}
func (*CreateSessionTooManyRequestsHeaders) createMessageRes() {}
func (*CreateSessionTooManyRequestsHeaders) createSessionRes() {}
func (*CreateSessionTooManyRequestsHeaders) currentUserRes() {}
func (*CreateSessionTooManyRequestsHeaders) getChatRes() {}
func (*CreateSessionTooManyRequestsHeaders) listChatsRes() {}
func (*CreateSessionTooManyRequestsHeaders) listMessagesRes() {}
func (*CreateSessionTooManyRequestsHeaders) registerUserRes() {}
func (*CreateSessionTooManyRequestsHeaders) revokeSessionRes() {}
// CreateSessionUnauthorizedHeaders wraps Error with response headers.
type CreateSessionUnauthorizedHeaders struct {
WWWAuthenticate OptString
XRequestID OptString
Response Error
}
// GetWWWAuthenticate returns the value of WWWAuthenticate.
func (s *CreateSessionUnauthorizedHeaders) GetWWWAuthenticate() OptString {
return s.WWWAuthenticate
}
// GetXRequestID returns the value of XRequestID.
func (s *CreateSessionUnauthorizedHeaders) GetXRequestID() OptString {
return s.XRequestID
}
// GetResponse returns the value of Response.
func (s *CreateSessionUnauthorizedHeaders) GetResponse() Error {
return s.Response
}
// SetWWWAuthenticate sets the value of WWWAuthenticate.
func (s *CreateSessionUnauthorizedHeaders) SetWWWAuthenticate(val OptString) {
s.WWWAuthenticate = val
}
// SetXRequestID sets the value of XRequestID.
func (s *CreateSessionUnauthorizedHeaders) SetXRequestID(val OptString) {
s.XRequestID = val
}
// SetResponse sets the value of Response.
func (s *CreateSessionUnauthorizedHeaders) SetResponse(val Error) {
s.Response = val
}
func (*CreateSessionUnauthorizedHeaders) createChatRes() {}
func (*CreateSessionUnauthorizedHeaders) createMessageRes() {}
func (*CreateSessionUnauthorizedHeaders) createSessionRes() {}
func (*CreateSessionUnauthorizedHeaders) currentUserRes() {}
func (*CreateSessionUnauthorizedHeaders) getChatRes() {}
func (*CreateSessionUnauthorizedHeaders) listChatsRes() {}
func (*CreateSessionUnauthorizedHeaders) listMessagesRes() {}
func (*CreateSessionUnauthorizedHeaders) revokeSessionRes() {}
// Ref: #/components/schemas/CreateUser
type CreateUser struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
// GetUsername returns the value of Username.
@@ -237,6 +404,11 @@ func (s *CreateUser) GetDisplayName() string {
return s.DisplayName
}
// GetPassword returns the value of Password.
func (s *CreateUser) GetPassword() string {
return s.Password
}
// SetUsername sets the value of Username.
func (s *CreateUser) SetUsername(val string) {
s.Username = val
@@ -247,6 +419,11 @@ func (s *CreateUser) SetDisplayName(val string) {
s.DisplayName = val
}
// SetPassword sets the value of Password.
func (s *CreateUser) SetPassword(val string) {
s.Password = val
}
type CurrentUserBadRequest ErrorHeaders
func (*CurrentUserBadRequest) currentUserRes() {}
@@ -267,31 +444,6 @@ type CurrentUserServiceUnavailable ErrorHeaders
func (*CurrentUserServiceUnavailable) currentUserRes() {}
type DevUser struct {
APIKey string
Roles []string
}
// GetAPIKey returns the value of APIKey.
func (s *DevUser) GetAPIKey() string {
return s.APIKey
}
// GetRoles returns the value of Roles.
func (s *DevUser) GetRoles() []string {
return s.Roles
}
// SetAPIKey sets the value of APIKey.
func (s *DevUser) SetAPIKey(val string) {
s.APIKey = val
}
// SetRoles sets the value of Roles.
func (s *DevUser) SetRoles(val []string) {
s.Roles = val
}
// Ref: #/components/schemas/Error
type Error struct {
Error ErrorError `json:"error"`
@@ -579,95 +731,6 @@ type ListChatsServiceUnavailable ErrorHeaders
func (*ListChatsServiceUnavailable) listChatsRes() {}
// ListChatsTooManyRequestsHeaders wraps Error with response headers.
type ListChatsTooManyRequestsHeaders struct {
RetryAfter OptInt
XRequestID OptString
Response Error
}
// GetRetryAfter returns the value of RetryAfter.
func (s *ListChatsTooManyRequestsHeaders) GetRetryAfter() OptInt {
return s.RetryAfter
}
// GetXRequestID returns the value of XRequestID.
func (s *ListChatsTooManyRequestsHeaders) GetXRequestID() OptString {
return s.XRequestID
}
// GetResponse returns the value of Response.
func (s *ListChatsTooManyRequestsHeaders) GetResponse() Error {
return s.Response
}
// SetRetryAfter sets the value of RetryAfter.
func (s *ListChatsTooManyRequestsHeaders) SetRetryAfter(val OptInt) {
s.RetryAfter = val
}
// SetXRequestID sets the value of XRequestID.
func (s *ListChatsTooManyRequestsHeaders) SetXRequestID(val OptString) {
s.XRequestID = val
}
// SetResponse sets the value of Response.
func (s *ListChatsTooManyRequestsHeaders) SetResponse(val Error) {
s.Response = val
}
func (*ListChatsTooManyRequestsHeaders) createChatRes() {}
func (*ListChatsTooManyRequestsHeaders) createMessageRes() {}
func (*ListChatsTooManyRequestsHeaders) currentUserRes() {}
func (*ListChatsTooManyRequestsHeaders) getChatRes() {}
func (*ListChatsTooManyRequestsHeaders) listChatsRes() {}
func (*ListChatsTooManyRequestsHeaders) listMessagesRes() {}
func (*ListChatsTooManyRequestsHeaders) registerUserRes() {}
// ListChatsUnauthorizedHeaders wraps Error with response headers.
type ListChatsUnauthorizedHeaders struct {
WWWAuthenticate OptString
XRequestID OptString
Response Error
}
// GetWWWAuthenticate returns the value of WWWAuthenticate.
func (s *ListChatsUnauthorizedHeaders) GetWWWAuthenticate() OptString {
return s.WWWAuthenticate
}
// GetXRequestID returns the value of XRequestID.
func (s *ListChatsUnauthorizedHeaders) GetXRequestID() OptString {
return s.XRequestID
}
// GetResponse returns the value of Response.
func (s *ListChatsUnauthorizedHeaders) GetResponse() Error {
return s.Response
}
// SetWWWAuthenticate sets the value of WWWAuthenticate.
func (s *ListChatsUnauthorizedHeaders) SetWWWAuthenticate(val OptString) {
s.WWWAuthenticate = val
}
// SetXRequestID sets the value of XRequestID.
func (s *ListChatsUnauthorizedHeaders) SetXRequestID(val OptString) {
s.XRequestID = val
}
// SetResponse sets the value of Response.
func (s *ListChatsUnauthorizedHeaders) SetResponse(val Error) {
s.Response = val
}
func (*ListChatsUnauthorizedHeaders) createChatRes() {}
func (*ListChatsUnauthorizedHeaders) createMessageRes() {}
func (*ListChatsUnauthorizedHeaders) currentUserRes() {}
func (*ListChatsUnauthorizedHeaders) getChatRes() {}
func (*ListChatsUnauthorizedHeaders) listChatsRes() {}
func (*ListChatsUnauthorizedHeaders) listMessagesRes() {}
type ListMessagesBadRequest ErrorHeaders
func (*ListMessagesBadRequest) listMessagesRes() {}
@@ -990,6 +1053,107 @@ type RegisterUserServiceUnavailable ErrorHeaders
func (*RegisterUserServiceUnavailable) registerUserRes() {}
type RevokeSessionInternalServerError ErrorHeaders
func (*RevokeSessionInternalServerError) revokeSessionRes() {}
// RevokeSessionNoContent is response for RevokeSession operation.
type RevokeSessionNoContent struct {
XRequestID OptString
}
// GetXRequestID returns the value of XRequestID.
func (s *RevokeSessionNoContent) GetXRequestID() OptString {
return s.XRequestID
}
// SetXRequestID sets the value of XRequestID.
func (s *RevokeSessionNoContent) SetXRequestID(val OptString) {
s.XRequestID = val
}
func (*RevokeSessionNoContent) revokeSessionRes() {}
type RevokeSessionServiceUnavailable ErrorHeaders
func (*RevokeSessionServiceUnavailable) revokeSessionRes() {}
// Ref: #/components/schemas/Session
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
User User `json:"user"`
}
// GetToken returns the value of Token.
func (s *Session) GetToken() string {
return s.Token
}
// GetTokenType returns the value of TokenType.
func (s *Session) GetTokenType() string {
return s.TokenType
}
// GetExpiresAt returns the value of ExpiresAt.
func (s *Session) GetExpiresAt() time.Time {
return s.ExpiresAt
}
// GetUser returns the value of User.
func (s *Session) GetUser() User {
return s.User
}
// SetToken sets the value of Token.
func (s *Session) SetToken(val string) {
s.Token = val
}
// SetTokenType sets the value of TokenType.
func (s *Session) SetTokenType(val string) {
s.TokenType = val
}
// SetExpiresAt sets the value of ExpiresAt.
func (s *Session) SetExpiresAt(val time.Time) {
s.ExpiresAt = val
}
// SetUser sets the value of User.
func (s *Session) SetUser(val User) {
s.User = val
}
// SessionHeaders wraps Session with response headers.
type SessionHeaders struct {
XRequestID OptString
Response Session
}
// GetXRequestID returns the value of XRequestID.
func (s *SessionHeaders) GetXRequestID() OptString {
return s.XRequestID
}
// GetResponse returns the value of Response.
func (s *SessionHeaders) GetResponse() Session {
return s.Response
}
// SetXRequestID sets the value of XRequestID.
func (s *SessionHeaders) SetXRequestID(val OptString) {
s.XRequestID = val
}
// SetResponse sets the value of Response.
func (s *SessionHeaders) SetResponse(val Session) {
s.Response = val
}
func (*SessionHeaders) createSessionRes() {}
// Ref: #/components/schemas/User
type User struct {
ID uuid.UUID `json:"id"`
@@ -0,0 +1,131 @@
// Code generated by ogen, DO NOT EDIT.
package oas
import (
"context"
"net/http"
"strings"
"github.com/go-faster/errors"
"github.com/ogen-go/ogen/ogenerrors"
)
// SecurityHandler is handler for security parameters.
type SecurityHandler interface {
// HandleBasicAuth handles basicAuth security.
HandleBasicAuth(ctx context.Context, operationName OperationName, t BasicAuth) (context.Context, error)
// HandleBearerAuth handles bearerAuth security.
HandleBearerAuth(ctx context.Context, operationName OperationName, t BearerAuth) (context.Context, error)
}
func findAuthorization(h http.Header, prefix string) (string, bool) {
v, ok := h["Authorization"]
if !ok {
return "", false
}
for _, vv := range v {
scheme, value, ok := strings.Cut(vv, " ")
if !ok || !strings.EqualFold(scheme, prefix) {
continue
}
return value, true
}
return "", false
}
// operationRolesBasicAuth is a private map storing roles per operation.
var operationRolesBasicAuth = map[string][]string{
CreateSessionOperation: []string{},
}
// GetRolesForBasicAuth returns the required roles for the given operation.
//
// This is useful for authorization scenarios where you need to know which roles
// are required for an operation.
//
// Example:
//
// requiredRoles := GetRolesForBasicAuth(AddPetOperation)
//
// Returns nil if the operation has no role requirements or if the operation is unknown.
func GetRolesForBasicAuth(operation string) []string {
roles, ok := operationRolesBasicAuth[operation]
if !ok {
return nil
}
// Return a copy to prevent external modification
result := make([]string, len(roles))
copy(result, roles)
return result
}
// operationRolesBearerAuth is a private map storing roles per operation.
var operationRolesBearerAuth = map[string][]string{
CreateChatOperation: []string{},
CreateMessageOperation: []string{},
CurrentUserOperation: []string{},
GetChatOperation: []string{},
ListChatsOperation: []string{},
ListMessagesOperation: []string{},
RevokeSessionOperation: []string{},
}
// GetRolesForBearerAuth returns the required roles for the given operation.
//
// This is useful for authorization scenarios where you need to know which roles
// are required for an operation.
//
// Example:
//
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
//
// Returns nil if the operation has no role requirements or if the operation is unknown.
func GetRolesForBearerAuth(operation string) []string {
roles, ok := operationRolesBearerAuth[operation]
if !ok {
return nil
}
// Return a copy to prevent external modification
result := make([]string, len(roles))
copy(result, roles)
return result
}
func (s *Server) securityBasicAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
var t BasicAuth
if _, ok := findAuthorization(req.Header, "Basic"); !ok {
return ctx, false, nil
}
username, password, ok := req.BasicAuth()
if !ok {
return nil, false, errors.New("invalid basic auth")
}
t.Username = username
t.Password = password
t.Roles = operationRolesBasicAuth[operationName]
rctx, err := s.sec.HandleBasicAuth(ctx, operationName, t)
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return rctx, true, err
}
func (s *Server) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
var t BearerAuth
token, ok := findAuthorization(req.Header, "Bearer")
if !ok {
return ctx, false, nil
}
t.Token = token
t.Roles = operationRolesBearerAuth[operationName]
rctx, err := s.sec.HandleBearerAuth(ctx, operationName, t)
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return rctx, true, err
}

Some files were not shown because too many files have changed in this diff Show More