Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
// client is a minimal typed HTTP client for the messenger API.
|
||||
type client struct {
|
||||
base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
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 {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return c.do(req, actor, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
query := url.Values{"limit": {"100"}}
|
||||
if cursor != "" {
|
||||
query.Set("cursor", cursor)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, c.base+path+"?"+query.Encode(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.do(req, actor, 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)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode != want {
|
||||
return fmt.Errorf("%s %s: status %d, want %d: %s", req.Method, req.URL.Path, resp.StatusCode, want, payload)
|
||||
}
|
||||
return json.Unmarshal(payload, out)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
// Command concurrency is the black-box race check from the grading rubric:
|
||||
// N clients send M messages each into one chat at the same time, then the
|
||||
// history is paged and must contain exactly N*M unique messages in id order.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/pagination"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
// Report is the machine readable outcome saved as evidence.
|
||||
type Report struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
Clients int `json:"clients"`
|
||||
PerClient int `json:"per_client"`
|
||||
Expected int `json:"expected_messages"`
|
||||
Created int `json:"created_201"`
|
||||
Failed int `json:"failed_posts"`
|
||||
Listed int `json:"listed_messages"`
|
||||
Unique int `json:"unique_ids"`
|
||||
Missing int `json:"created_but_not_listed"`
|
||||
Ordered bool `json:"history_ordered_by_id"`
|
||||
Pages int `json:"pages_read"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
Passed bool `json:"passed"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL")
|
||||
clients := flag.Int("clients", 10, "number of concurrent clients")
|
||||
perClient := flag.Int("per-client", 10, "messages sent by each client")
|
||||
output := flag.String("output", "", "optional path for the JSON report")
|
||||
flag.Parse()
|
||||
|
||||
report, err := run(*baseURL, *clients, *perClient)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
}
|
||||
text, _ := json.MarshalIndent(report, "", " ")
|
||||
fmt.Println(string(text))
|
||||
if *output != "" {
|
||||
if err := writeReport(*output, text); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
}
|
||||
if !report.Passed {
|
||||
fail(fmt.Errorf("concurrency invariants violated"))
|
||||
}
|
||||
fmt.Printf("PASS: %d clients x %d messages produced exactly %d unique ordered messages\n",
|
||||
report.Clients, report.PerClient, report.Unique)
|
||||
}
|
||||
|
||||
func fail(err error) {
|
||||
fmt.Fprintln(os.Stderr, "FAIL:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func writeReport(path string, text []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(text, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func run(baseURL string, clients, perClient int) (Report, error) {
|
||||
if clients < 1 || perClient < 1 {
|
||||
return Report{}, fmt.Errorf("clients and per-client must be positive")
|
||||
}
|
||||
report := Report{
|
||||
BaseURL: baseURL,
|
||||
StartedAt: time.Now().UTC(),
|
||||
Clients: clients,
|
||||
PerClient: perClient,
|
||||
Expected: clients * perClient,
|
||||
}
|
||||
api := newClient(baseURL)
|
||||
runID := uuid.NewString()[:8]
|
||||
|
||||
members, err := registerClients(api, runID, clients)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
room, err := createChat(api, runID, members)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
created, failed := sendConcurrently(baseURL, room.ID, members, perClient)
|
||||
report.ElapsedSeconds = time.Since(started).Seconds()
|
||||
report.Created = len(created)
|
||||
report.Failed = failed
|
||||
|
||||
listed, pages, err := readHistory(api, room.ID, members[0])
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
report.Pages = pages
|
||||
report.Listed = len(listed)
|
||||
report.Unique, report.Missing = compare(created, listed)
|
||||
report.Ordered = sort.StringsAreSorted(listed)
|
||||
report.Passed = report.Failed == 0 &&
|
||||
report.Created == report.Expected &&
|
||||
report.Listed == report.Expected &&
|
||||
report.Unique == report.Expected &&
|
||||
report.Missing == 0 &&
|
||||
report.Ordered
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func registerClients(api *client, runID string, n int) ([]string, error) {
|
||||
ids := make([]string, 0, n)
|
||||
for i := range n {
|
||||
var created user.Response
|
||||
body := map[string]string{
|
||||
"username": fmt.Sprintf("load_%s_%d", runID, i),
|
||||
"display_name": fmt.Sprintf("Load client %d", i),
|
||||
}
|
||||
if err := api.post("/api/v1/users", "", body, &created); err != nil {
|
||||
return nil, fmt.Errorf("register client %d: %w", i, err)
|
||||
}
|
||||
ids = append(ids, created.ID)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func createChat(api *client, runID string, members []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 {
|
||||
return chat.ChatResponse{}, fmt.Errorf("create chat: %w", err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
var mu sync.Mutex
|
||||
created := make(map[string]struct{}, len(members)*perClient)
|
||||
failed := 0
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i, actor := range members {
|
||||
wg.Add(1)
|
||||
go func(n int, actor 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)
|
||||
mu.Lock()
|
||||
if err != nil {
|
||||
failed++
|
||||
} else {
|
||||
created[msg.ID] = struct{}{}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}(i, actor)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
return created, failed
|
||||
}
|
||||
|
||||
func readHistory(api *client, chatID, actor 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 {
|
||||
return nil, pages, fmt.Errorf("read history: %w", err)
|
||||
}
|
||||
pages++
|
||||
for _, m := range page.Items {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
return ids, pages, nil
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
}
|
||||
|
||||
// compare returns how many distinct ids the history holds and how many
|
||||
// acknowledged ids never showed up in it.
|
||||
func compare(created map[string]struct{}, listed []string) (unique, missing int) {
|
||||
seen := make(map[string]struct{}, len(listed))
|
||||
for _, id := range listed {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
for id := range created {
|
||||
if _, ok := seen[id]; !ok {
|
||||
missing++
|
||||
}
|
||||
}
|
||||
return len(seen), missing
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/app"
|
||||
)
|
||||
|
||||
func TestRunAgainstLiveServer(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
srv := httptest.NewServer(app.New(log, 64*1024).Engine)
|
||||
defer srv.Close()
|
||||
|
||||
report, err := run(srv.URL, 10, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("run error: %v", err)
|
||||
}
|
||||
if report.Clients != 10 || report.PerClient != 10 || report.Expected != 100 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
if report.Created != 100 || report.Listed != 100 || report.Unique != 100 || report.Missing != 0 {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
if !report.Ordered || !report.Passed {
|
||||
t.Fatalf("report = %+v", report)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunFailsOnUnreachableServer(t *testing.T) {
|
||||
if _, err := run("http://127.0.0.1:1", 2, 2); err == nil {
|
||||
t.Fatal("expected an error for an unreachable server")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user