160 lines
4.7 KiB
Go
160 lines
4.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
)
|
|
|
|
// result is one HTTP exchange; instance is the X-Instance-Id of the answer,
|
|
// empty when the balancer answered itself or nothing answered.
|
|
type result struct {
|
|
status int
|
|
instance string
|
|
body []byte
|
|
latency time.Duration
|
|
err error
|
|
}
|
|
|
|
type client struct {
|
|
base string
|
|
http *http.Client
|
|
timeout time.Duration
|
|
}
|
|
|
|
// newClient keeps many connections open to the balancer, as many concurrent
|
|
// users would; HAProxy balances every request, not every connection.
|
|
func newClient(base string, timeout time.Duration) *client {
|
|
transport := &http.Transport{
|
|
MaxIdleConns: 10000,
|
|
MaxIdleConnsPerHost: 10000,
|
|
IdleConnTimeout: 30 * time.Second,
|
|
DisableCompression: true,
|
|
}
|
|
return &client{base: base, http: &http.Client{Transport: transport}, timeout: timeout}
|
|
}
|
|
|
|
func (c *client) do(ctx context.Context, method, path, token, key string, body []byte, basic string) result {
|
|
ctx, cancel := context.WithTimeout(ctx, c.timeout)
|
|
defer cancel()
|
|
var reader io.Reader
|
|
if body != nil {
|
|
reader = bytes.NewReader(body)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, c.base+path, reader)
|
|
if err != nil {
|
|
return result{err: err}
|
|
}
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
switch {
|
|
case basic != "":
|
|
req.Header.Set("Authorization", "Basic "+basic)
|
|
case token != "":
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
if key != "" {
|
|
req.Header.Set("Idempotency-Key", key)
|
|
}
|
|
start := time.Now()
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return result{err: err, latency: time.Since(start)}
|
|
}
|
|
defer resp.Body.Close()
|
|
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
r := result{status: resp.StatusCode, instance: resp.Header.Get("X-Instance-Id"), body: payload, latency: time.Since(start), err: err}
|
|
return r
|
|
}
|
|
|
|
func (c *client) postJSON(ctx context.Context, path, token, key string, body any) result {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return result{err: err}
|
|
}
|
|
return c.do(ctx, http.MethodPost, path, token, key, raw, "")
|
|
}
|
|
|
|
// expect decodes the body of a result with the wanted status.
|
|
func expect(r result, want int, out any) error {
|
|
if r.err != nil {
|
|
return r.err
|
|
}
|
|
if r.status != want {
|
|
return fmt.Errorf("status %d, want %d: %s", r.status, want, r.body)
|
|
}
|
|
if out == nil {
|
|
return nil
|
|
}
|
|
return json.Unmarshal(r.body, out)
|
|
}
|
|
|
|
func (c *client) register(ctx context.Context, username, password string) (string, error) {
|
|
var created struct {
|
|
ID string `json:"id"`
|
|
}
|
|
body := map[string]string{"username": username, "display_name": username, "password": password}
|
|
err := expect(c.postJSON(ctx, "/api/v1/users", "", "", body), http.StatusCreated, &created)
|
|
return created.ID, err
|
|
}
|
|
|
|
func (c *client) login(ctx context.Context, username, password string) (string, error) {
|
|
var session struct {
|
|
Token string `json:"token"`
|
|
}
|
|
basic := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
|
err := expect(c.do(ctx, http.MethodPost, "/api/v1/auth/sessions", "", "", nil, basic), http.StatusCreated, &session)
|
|
return session.Token, err
|
|
}
|
|
|
|
func (c *client) createChat(ctx context.Context, token, title string, members []string) (string, error) {
|
|
var created struct {
|
|
ID string `json:"id"`
|
|
}
|
|
body := map[string]any{"title": title, "member_ids": members}
|
|
err := expect(c.postJSON(ctx, "/api/v1/chats", token, "", body), http.StatusCreated, &created)
|
|
return created.ID, err
|
|
}
|
|
|
|
func (c *client) send(ctx context.Context, chatID, token, key, text string) result {
|
|
return c.postJSON(ctx, "/api/v1/chats/"+chatID+"/messages", token, key, map[string]string{"text": text})
|
|
}
|
|
|
|
// firstPage reads the oldest page of a history: the read of the profile.
|
|
func (c *client) firstPage(ctx context.Context, chatID, token string) result {
|
|
return c.do(ctx, http.MethodGet, "/api/v1/chats/"+chatID+"/messages?limit=50", token, "", nil, "")
|
|
}
|
|
|
|
type message struct {
|
|
ID string `json:"id"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// history reads a whole chat, page by page.
|
|
func (c *client) history(ctx context.Context, chatID, token string) ([]message, error) {
|
|
var all []message
|
|
path := "/api/v1/chats/" + chatID + "/messages?limit=100"
|
|
for range 100000 {
|
|
var page struct {
|
|
Items []message `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
if err := expect(c.do(ctx, http.MethodGet, path, token, "", nil, ""), http.StatusOK, &page); err != nil {
|
|
return nil, err
|
|
}
|
|
all = append(all, page.Items...)
|
|
if page.NextCursor == nil {
|
|
return all, nil
|
|
}
|
|
path = "/api/v1/chats/" + chatID + "/messages?limit=100&cursor=" + url.QueryEscape(*page.NextCursor)
|
|
}
|
|
return nil, fmt.Errorf("history of %s did not end", chatID)
|
|
}
|