Files

299 lines
9.1 KiB
Go

package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"image"
_ "image/jpeg"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
)
type apiState struct {
BaseURL string `json:"base_url"`
Token string `json:"token"`
AttachmentID string `json:"attachment_id"`
}
type apiUser struct {
ID string `json:"id"`
}
type apiSession struct {
Token string `json:"token"`
}
type apiChat struct {
ID string `json:"id"`
}
func runAPIProduce(arguments []string, output io.Writer) error {
flags := flag.NewFlagSet("api-produce", flag.ContinueOnError)
flags.SetOutput(io.Discard)
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL")
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
return errors.New("usage: lab5experiment api-produce [-base-url URL]")
}
client := &http.Client{Timeout: 10 * time.Second}
suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
password := "Lab5-" + uuid.NewString()
owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password)
if err != nil {
return err
}
member, err := registerAPIUser(client, *baseURL, "qb_"+suffix, password)
if err != nil {
return err
}
token, err := createAPISession(client, *baseURL, "qa_"+suffix, password)
if err != nil {
return err
}
chat, err := createAPIChat(client, *baseURL, token, owner.ID, member.ID)
if err != nil {
return err
}
fixture, err := pngFixture(320, 200)
if err != nil {
return err
}
var attachment model.Attachment
response, err := apiRequest(
client, http.MethodPost,
*baseURL+"/api/v1/chats/"+chat.ID+"/attachments?filename=queued.png",
token, "image/png", fixture, &attachment,
)
if err != nil {
return err
}
if response.StatusCode != http.StatusAccepted || attachment.Status != model.AttachmentQueued {
return fmt.Errorf("upload returned status=%d attachment_status=%s", response.StatusCode, attachment.Status)
}
messageBody, err := json.Marshal(map[string]any{"text": "", "attachment_ids": []string{attachment.ID}})
if err != nil {
return err
}
response, err = apiRequestWithHeaders(
client, http.MethodPost, *baseURL+"/api/v1/chats/"+chat.ID+"/messages",
token, "application/json", messageBody, nil,
map[string]string{"Idempotency-Key": uuid.NewString()},
)
if err != nil {
return err
}
if response.StatusCode != http.StatusCreated {
return fmt.Errorf("link queued attachment returned %d", response.StatusCode)
}
response, err = apiRequest(client, http.MethodGet, *baseURL+"/api/v1/attachments/"+attachment.ID+"/content", token, "", nil, nil)
if err != nil {
return err
}
if response.StatusCode != http.StatusConflict {
return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode)
}
return json.NewEncoder(output).Encode(apiState{BaseURL: *baseURL, Token: token, AttachmentID: attachment.ID})
}
func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
flags := flag.NewFlagSet("api-verify", flag.ContinueOnError)
flags.SetOutput(io.Discard)
waitTimeout := flags.Duration("wait-timeout", time.Minute, "ready wait timeout")
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
return errors.New("usage: lab5experiment api-verify [-wait-timeout 1m]")
}
var state apiState
if err := json.NewDecoder(input).Decode(&state); err != nil {
return fmt.Errorf("decode API scenario state: %w", err)
}
client := &http.Client{Timeout: 10 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout)
defer cancel()
var attachment model.Attachment
for {
response, err := apiRequest(client, http.MethodGet, state.BaseURL+"/api/v1/attachments/"+state.AttachmentID, state.Token, "", nil, &attachment)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return fmt.Errorf("attachment metadata returned %d", response.StatusCode)
}
if attachment.Status == model.AttachmentReady {
break
}
if attachment.Status == model.AttachmentFailed {
return fmt.Errorf("attachment failed with %v", attachment.ErrorCode)
}
if err := wait(ctx, 250*time.Millisecond); err != nil {
return err
}
}
if len(attachment.Variants) != 3 {
return fmt.Errorf("public variants = %d, expected 3", len(attachment.Variants))
}
response, original, err := apiBytes(client, state.BaseURL+"/api/v1/attachments/"+state.AttachmentID+"/content", state.Token)
if err != nil {
return err
}
fixture, err := pngFixture(320, 200)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK || !bytes.Equal(original, fixture) {
return errors.New("original changed after worker and broker restart")
}
response, thumbnail, err := apiBytes(
client, state.BaseURL+"/api/v1/attachments/"+state.AttachmentID+"/content?variant=thumbnail", state.Token,
)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK || response.Header.Get("Content-Type") != "image/jpeg" {
return errors.New("thumbnail response is invalid")
}
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(thumbnail))
if err != nil || format != "jpeg" || imageConfig.Width != 256 || imageConfig.Height != 160 {
return errors.New("thumbnail dimensions are invalid")
}
return json.NewEncoder(output).Encode(map[string]any{
"accepted_while_worker_stopped": true,
"accepted_before_outbox_publish": true,
"linked_while_queued": true,
"content_conflict_while_queued": true,
"ready_after_api_broker_restart": true,
"original_preserved": true,
"thumbnail_dimensions": "256x160",
})
}
func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) {
body, err := json.Marshal(map[string]string{
"username": username, "display_name": username, "password": password,
})
if err != nil {
return apiUser{}, err
}
var user apiUser
response, err := apiRequest(client, http.MethodPost, baseURL+"/api/v1/users", "", "application/json", body, &user)
if err != nil {
return apiUser{}, err
}
if response.StatusCode != http.StatusCreated {
return apiUser{}, fmt.Errorf("register user returned %d", response.StatusCode)
}
return user, nil
}
func createAPISession(client *http.Client, baseURL, username, password string) (string, error) {
credentials := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
request, err := http.NewRequest(http.MethodPost, baseURL+"/api/v1/auth/sessions", nil)
if err != nil {
return "", err
}
request.Header.Set("Authorization", "Basic "+credentials)
response, err := client.Do(request)
if err != nil {
return "", err
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusCreated {
return "", fmt.Errorf("create session returned %d", response.StatusCode)
}
var session apiSession
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&session); err != nil {
return "", err
}
return session.Token, nil
}
func createAPIChat(client *http.Client, baseURL, token, ownerID, memberID string) (apiChat, error) {
body, err := json.Marshal(map[string]any{
"title": "Lab 5 resilience", "member_ids": []string{ownerID, memberID},
})
if err != nil {
return apiChat{}, err
}
var chat apiChat
response, err := apiRequest(client, http.MethodPost, baseURL+"/api/v1/chats", token, "application/json", body, &chat)
if err != nil {
return apiChat{}, err
}
if response.StatusCode != http.StatusCreated {
return apiChat{}, fmt.Errorf("create chat returned %d", response.StatusCode)
}
return chat, nil
}
func apiRequest(
client *http.Client,
method string,
requestURL string,
token string,
contentType string,
body []byte,
result any,
) (*http.Response, error) {
return apiRequestWithHeaders(client, method, requestURL, token, contentType, body, result, nil)
}
func apiRequestWithHeaders(
client *http.Client,
method string,
requestURL string,
token string,
contentType string,
body []byte,
result any,
headers map[string]string,
) (*http.Response, error) {
request, err := http.NewRequest(method, requestURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
for name, value := range headers {
request.Header.Set(name, value)
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer func() { _ = response.Body.Close() }()
if result != nil && response.StatusCode < http.StatusBadRequest {
if err := json.NewDecoder(io.LimitReader(response.Body, 16<<20)).Decode(result); err != nil {
return nil, err
}
}
return response, nil
}
func apiBytes(client *http.Client, requestURL, token string) (*http.Response, []byte, error) {
request, err := http.NewRequest(http.MethodGet, requestURL, nil)
if err != nil {
return nil, nil, err
}
request.Header.Set("Authorization", "Bearer "+token)
response, err := client.Do(request)
if err != nil {
return nil, nil, err
}
defer func() { _ = response.Body.Close() }()
body, err := io.ReadAll(io.LimitReader(response.Body, 16<<20))
return response, body, err
}