Добавить сессии в Valkey и вход через Basic с Bearer-токеном

This commit is contained in:
2026-10-06 15:08:39 +03:00
parent 3c1b63ed98
commit 9890482747
23 changed files with 1047 additions and 274 deletions
+23 -7
View File
@@ -20,7 +20,7 @@ func newClient(baseURL string) *client {
return &client{base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
}
func (c *client) post(path, actor string, body, out any) error {
func (c *client) post(path, token string, body, out any) error {
raw, err := json.Marshal(body)
if err != nil {
return err
@@ -30,12 +30,28 @@ func (c *client) post(path, actor string, body, out any) error {
return err
}
req.Header.Set("Content-Type", "application/json")
return c.do(req, actor, http.StatusCreated, out)
return c.do(req, token, http.StatusCreated, out)
}
// login opens a session with Basic credentials and returns its bearer token.
func (c *client) login(username, password string) (string, error) {
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
if err != nil {
return "", err
}
req.SetBasicAuth(username, password)
var session struct {
Token string `json:"token"`
}
if err := c.do(req, "", http.StatusCreated, &session); err != nil {
return "", err
}
return session.Token, nil
}
// get requests the largest page the contract allows, continuing from cursor
// when it is set.
func (c *client) get(path, actor, cursor string, out any) error {
func (c *client) get(path, token, cursor string, out any) error {
query := url.Values{"limit": {"100"}}
if cursor != "" {
query.Set("cursor", cursor)
@@ -44,12 +60,12 @@ func (c *client) get(path, actor, cursor string, out any) error {
if err != nil {
return err
}
return c.do(req, actor, http.StatusOK, out)
return c.do(req, token, http.StatusOK, out)
}
func (c *client) do(req *http.Request, actor string, want int, out any) error {
if actor != "" {
req.Header.Set("X-User-Id", actor)
func (c *client) do(req *http.Request, token string, want int, out any) error {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := c.http.Do(req)
if err != nil {
+26 -19
View File
@@ -89,22 +89,22 @@ func run(baseURL string, clients, perClient int) (Report, error) {
api := newClient(baseURL)
runID := uuid.NewString()[:8]
members, err := registerClients(api, runID, clients)
members, tokens, err := registerClients(api, runID, clients)
if err != nil {
return report, err
}
room, err := createChat(api, runID, members)
room, err := createChat(api, runID, members, tokens[0])
if err != nil {
return report, err
}
started := time.Now()
created, failed := sendConcurrently(baseURL, room.ID, members, perClient)
created, failed := sendConcurrently(baseURL, room.ID, tokens, perClient)
report.ElapsedSeconds = time.Since(started).Seconds()
report.Created = len(created)
report.Failed = failed
listed, pages, err := readHistory(api, room.ID, members[0])
listed, pages, err := readHistory(api, room.ID, tokens[0])
if err != nil {
return report, err
}
@@ -124,27 +124,34 @@ func run(baseURL string, clients, perClient int) (Report, error) {
// clientPassword is shared by the synthetic clients of one run.
const clientPassword = "concurrency-check-password"
func registerClients(api *client, runID string, n int) ([]string, error) {
ids := make([]string, 0, n)
// registerClients registers and logs in n clients, returning their ids and
// bearer tokens in the same order.
func registerClients(api *client, runID string, n int) (ids, tokens []string, err error) {
for i := range n {
var created user.Response
username := fmt.Sprintf("load_%s_%d", runID, i)
body := map[string]string{
"username": fmt.Sprintf("load_%s_%d", runID, i),
"username": username,
"display_name": fmt.Sprintf("Load client %d", i),
"password": clientPassword,
}
if err := api.post("/api/v1/users", "", body, &created); err != nil {
return nil, fmt.Errorf("register client %d: %w", i, err)
return nil, nil, fmt.Errorf("register client %d: %w", i, err)
}
token, err := api.login(username, clientPassword)
if err != nil {
return nil, nil, fmt.Errorf("log in client %d: %w", i, err)
}
ids = append(ids, created.ID)
tokens = append(tokens, token)
}
return ids, nil
return ids, tokens, nil
}
func createChat(api *client, runID string, members []string) (chat.ChatResponse, error) {
func createChat(api *client, runID string, members []string, creatorToken string) (chat.ChatResponse, error) {
var created chat.ChatResponse
body := map[string]any{"title": "Concurrency check " + runID, "member_ids": members}
if err := api.post("/api/v1/chats", members[0], body, &created); err != nil {
if err := api.post("/api/v1/chats", creatorToken, body, &created); err != nil {
return chat.ChatResponse{}, fmt.Errorf("create chat: %w", err)
}
return created, nil
@@ -152,23 +159,23 @@ func createChat(api *client, runID string, members []string) (chat.ChatResponse,
// sendConcurrently gives every member its own HTTP client and releases them
// together, so the server sees genuinely parallel writes to one chat.
func sendConcurrently(baseURL, chatID string, members []string, perClient int) (map[string]struct{}, int) {
func sendConcurrently(baseURL, chatID string, tokens []string, perClient int) (map[string]struct{}, int) {
var mu sync.Mutex
created := make(map[string]struct{}, len(members)*perClient)
created := make(map[string]struct{}, len(tokens)*perClient)
failed := 0
var wg sync.WaitGroup
start := make(chan struct{})
for i, actor := range members {
for i, token := range tokens {
wg.Add(1)
go func(n int, actor string) {
go func(n int, token string) {
defer wg.Done()
own := newClient(baseURL)
<-start
for m := range perClient {
var msg chat.MessageResponse
body := map[string]string{"text": fmt.Sprintf("client %d message %d", n, m)}
err := own.post("/api/v1/chats/"+chatID+"/messages", actor, body, &msg)
err := own.post("/api/v1/chats/"+chatID+"/messages", token, body, &msg)
mu.Lock()
if err != nil {
failed++
@@ -177,20 +184,20 @@ func sendConcurrently(baseURL, chatID string, members []string, perClient int) (
}
mu.Unlock()
}
}(i, actor)
}(i, token)
}
close(start)
wg.Wait()
return created, failed
}
func readHistory(api *client, chatID, actor string) ([]string, int, error) {
func readHistory(api *client, chatID, token string) ([]string, int, error) {
var ids []string
pages := 0
cursor := ""
for {
var page pagination.PageResponse[chat.MessageResponse]
if err := api.get("/api/v1/chats/"+chatID+"/messages", actor, cursor, &page); err != nil {
if err := api.get("/api/v1/chats/"+chatID+"/messages", token, cursor, &page); err != nil {
return nil, pages, fmt.Errorf("read history: %w", err)
}
pages++
+15 -4
View File
@@ -8,28 +8,39 @@ import (
"net/http/httptest"
"os"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/testenv"
)
var db *testenv.DB
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
func TestRunAgainstLiveServer(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := httptest.NewServer(app.New(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024}).Engine)
a := app.New(app.Deps{Log: log, DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 64 * 1024})
srv := httptest.NewServer(a.Engine)
defer srv.Close()
report, err := run(srv.URL, 10, 10)