forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
package controller
|
||||
|
||||
import "go.uber.org/fx"
|
||||
|
||||
// RunControllerFx lets Fx own startup, signal handling and graceful shutdown.
|
||||
func RunControllerFx(lc fx.Lifecycle, ctrl Controller) {
|
||||
lc.Append(fx.Hook{OnStart: ctrl.Start, OnStop: ctrl.Stop})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// Attachments defines file operations required by the HTTP boundary.
|
||||
type Attachments interface {
|
||||
// Upload validates and publishes an original.
|
||||
Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error)
|
||||
// Get authorizes access to attachment metadata.
|
||||
Get(context.Context, string, string) (dto.Attachment, error)
|
||||
// Download returns an authorized original stream.
|
||||
Download(context.Context, string, string, string) (dto.Attachment, io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// WithAttachments binds the file service during composition before server startup.
|
||||
func (ctrl *Controller) WithAttachments(attachments Attachments) *Controller {
|
||||
ctrl.attachments = attachments
|
||||
return ctrl
|
||||
}
|
||||
|
||||
type attachmentResponse struct {
|
||||
// ID identifies the uploaded file.
|
||||
ID string `json:"id"`
|
||||
// ChatID defines the chat authorization scope.
|
||||
ChatID string `json:"chat_id"`
|
||||
// OwnerID identifies the original uploader.
|
||||
OwnerID string `json:"owner_id"`
|
||||
// Filename is the validated display name.
|
||||
Filename string `json:"filename"`
|
||||
// ContentType describes the verified original format.
|
||||
ContentType string `json:"content_type"`
|
||||
// SizeBytes is the encoded original length.
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
// SHA256 is the original lowercase checksum.
|
||||
SHA256 string `json:"sha256"`
|
||||
// Status is the durable publication state.
|
||||
Status string `json:"status"`
|
||||
// Variants lists generated variants, empty in lab4.
|
||||
Variants []dto.Variant `json:"variants"`
|
||||
// ErrorCode is null for a ready original.
|
||||
ErrorCode *string `json:"error_code"`
|
||||
// CreatedAt is the reservation time.
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// UpdatedAt is the publication time.
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// attachmentResponseOf deliberately omits private S3 coordinates.
|
||||
func attachmentResponseOf(a dto.Attachment) attachmentResponse {
|
||||
return attachmentResponse{
|
||||
ID: a.ID.String(),
|
||||
ChatID: a.ChatID.String(),
|
||||
OwnerID: a.OwnerID.String(),
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: a.SHA256,
|
||||
Status: a.Status,
|
||||
Variants: publicVariants(a.Variants),
|
||||
ErrorCode: a.ErrorCode,
|
||||
CreatedAt: a.CreatedAt,
|
||||
UpdatedAt: a.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpload passes raw bounded bytes to application validation.
|
||||
func (ctrl *Controller) handleUpload(ctx *fiber.Ctx) error {
|
||||
if ctrl.attachments == nil {
|
||||
return service.ErrUnavailable
|
||||
}
|
||||
a, err := ctrl.attachments.Upload(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"), ctx.Query("filename"), ctx.Get("Content-Type"), ctx.Body())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusAccepted).JSON(attachmentResponseOf(a))
|
||||
}
|
||||
|
||||
// handleAttachment returns only the public metadata of an accessible file.
|
||||
func (ctrl *Controller) handleAttachment(ctx *fiber.Ctx) error {
|
||||
if ctrl.attachments == nil {
|
||||
return service.ErrUnavailable
|
||||
}
|
||||
a, err := ctrl.attachments.Get(ctx.UserContext(), identity(ctx), ctx.Params("id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.JSON(attachmentResponseOf(a))
|
||||
}
|
||||
|
||||
// handleContent streams original bytes without redirecting around authorization.
|
||||
func (ctrl *Controller) handleContent(ctx *fiber.Ctx) error {
|
||||
if ctrl.attachments == nil {
|
||||
return service.ErrUnavailable
|
||||
}
|
||||
a, reader, err := ctrl.attachments.Download(ctx.UserContext(), identity(ctx), ctx.Params("id"), ctx.Query("variant"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx.Set("Content-Type", a.ContentType)
|
||||
ctx.Set("X-Content-Type-Options", "nosniff")
|
||||
return ctx.SendStream(&responseStream{Reader: reader, cleanup: func() {
|
||||
}}, int(a.SizeBytes))
|
||||
}
|
||||
|
||||
// publicVariants copies generated metadata without exposing storage keys.
|
||||
func publicVariants(variants []dto.Variant) []dto.Variant {
|
||||
result := make([]dto.Variant, 0, len(variants))
|
||||
for _, variant := range variants {
|
||||
variant.ObjectKey = ""
|
||||
result = append(result, variant)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
type attachmentFixture struct {
|
||||
attachment dto.Attachment
|
||||
body []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// Upload returns the configured application outcome for an HTTP mapping scenario.
|
||||
func (f attachmentFixture) Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error) {
|
||||
return f.attachment, f.err
|
||||
}
|
||||
|
||||
// Get returns the configured metadata outcome for an HTTP mapping scenario.
|
||||
func (f attachmentFixture) Get(context.Context, string, string) (dto.Attachment, error) {
|
||||
return f.attachment, f.err
|
||||
}
|
||||
|
||||
// Download returns a stream that fails if the request context is canceled before transmission.
|
||||
func (f attachmentFixture) Download(ctx context.Context, _, _, _ string) (dto.Attachment, io.ReadCloser, error) {
|
||||
return f.attachment, &contextReader{Reader: bytes.NewReader(f.body), ctx: ctx}, f.err
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
*bytes.Reader
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
// Read verifies the admission context survives until the response is actually read.
|
||||
func (r *contextReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.Reader.Read(p)
|
||||
}
|
||||
|
||||
// Close makes the synthetic response stream an owned closer.
|
||||
func (r *contextReader) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestAttachmentHTTPMapping exercises early errors, successful metadata and byte-exact streaming.
|
||||
func TestAttachmentHTTPMapping(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
fixture *attachmentFixture
|
||||
status int
|
||||
}{
|
||||
{"upload unavailable", "POST", "/api/v1/chats/test/attachments", nil, http.StatusServiceUnavailable},
|
||||
{"metadata unavailable", "GET", "/api/v1/attachments/test", nil, http.StatusServiceUnavailable},
|
||||
{"download unavailable", "GET", "/api/v1/attachments/test/content", nil, http.StatusServiceUnavailable},
|
||||
{"upload too large", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrTooLarge}, http.StatusRequestEntityTooLarge},
|
||||
{"upload unsupported", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrMedia}, http.StatusUnsupportedMediaType},
|
||||
{"metadata missing", "GET", "/api/v1/attachments/test", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
|
||||
{"download missing", "GET", "/api/v1/attachments/test/content", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
|
||||
{"upload queued", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "queued"}}, http.StatusAccepted},
|
||||
{"metadata ready", "GET", "/api/v1/attachments/test", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "ready"}}, http.StatusOK},
|
||||
{"download stream", "GET", "/api/v1/attachments/test/content", &attachmentFixture{attachment: dto.Attachment{SizeBytes: 4, ContentType: "image/png"}, body: []byte{0, 1, 2, 3}}, http.StatusOK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
user := call(t, ctrl, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "test_user", "display_name": "Test", "password": "synthetic-password"}, http.StatusCreated)
|
||||
if tc.fixture != nil {
|
||||
ctrl.WithAttachments(*tc.fixture)
|
||||
}
|
||||
req := httptest.NewRequest(tc.method, tc.path, bytes.NewReader([]byte("fixture")))
|
||||
req.Header.Set("Authorization", "Bearer "+user["id"].(string))
|
||||
req.Header.Set("Content-Type", "image/png")
|
||||
response, err := ctrl.server.Test(req, 10000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if closeErr := response.Body.Close(); closeErr != nil {
|
||||
t.Fatal(closeErr)
|
||||
}
|
||||
if err != nil || response.StatusCode != tc.status {
|
||||
t.Fatalf("response status=%d err=%v", response.StatusCode, err)
|
||||
}
|
||||
if tc.fixture != nil && tc.fixture.body != nil && !bytes.Equal(body, tc.fixture.body) {
|
||||
t.Fatalf("stream changed: %v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
const identityKey = "authenticated-user"
|
||||
|
||||
// HandleLogin structurally decodes Basic credentials and delegates authentication.
|
||||
func (ctrl *Controller) HandleLogin(ctx *fiber.Ctx) error {
|
||||
scheme, encoded, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok {
|
||||
return service.ErrUnauthorized
|
||||
}
|
||||
if len(ctx.Body()) != 0 {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
session, err := ctrl.auth.Login(ctx.UserContext(), username, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(fiber.Map{
|
||||
"token": session.Token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session.ExpiresAt,
|
||||
"user": userResponse(session.User),
|
||||
})
|
||||
}
|
||||
|
||||
// HandleLogout revokes the current authenticated token before returning no content.
|
||||
func (ctrl *Controller) HandleLogout(ctx *fiber.Ctx) error {
|
||||
if err := ctrl.auth.Logout(ctx.UserContext(), bearer(ctx)); err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.SendStatus(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// bearer extracts a Bearer token without interpreting its identity or validity.
|
||||
func bearer(ctx *fiber.Ctx) string {
|
||||
scheme, token, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return ""
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// identity reads only the identity produced by successful session authentication.
|
||||
func identity(ctx *fiber.Ctx) string {
|
||||
value, _ := ctx.Locals(identityKey).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// requestGroup selects a bounded policy group from the HTTP operation.
|
||||
func requestGroup(ctx *fiber.Ctx) string {
|
||||
if ctx.Path() == "/api/v1/users" || strings.HasPrefix(ctx.Path(), "/api/v1/auth/") {
|
||||
return "auth"
|
||||
}
|
||||
if ctx.Method() == http.MethodGet {
|
||||
return "read"
|
||||
}
|
||||
return "write"
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
type sessionFixture struct {
|
||||
fixtureAuthentication
|
||||
login func(string, string) (dto.SessionDTO, error)
|
||||
logoutError error
|
||||
}
|
||||
|
||||
// Login delegates the credentials decoded by the controller to the arranged scenario.
|
||||
func (f sessionFixture) Login(_ context.Context, username, password string) (dto.SessionDTO, error) {
|
||||
return f.login(username, password)
|
||||
}
|
||||
|
||||
// Logout returns the prescribed revocation outcome.
|
||||
func (f sessionFixture) Logout(context.Context, string) error {
|
||||
return f.logoutError
|
||||
}
|
||||
|
||||
// TestLoginHTTPChecksBasicEncoding verifies independent wire-level login scenarios.
|
||||
func TestLoginHTTPChecksBasicEncoding(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
header string
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{"missing header", "", "", http.StatusUnauthorized},
|
||||
{"wrong scheme", "Bearer abc", "", http.StatusUnauthorized},
|
||||
{"bad base64", "Basic %%%", "", http.StatusUnauthorized},
|
||||
{"no delimiter", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice")), "", http.StatusUnauthorized},
|
||||
{"unexpected body", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "{}", http.StatusBadRequest},
|
||||
{"valid colon in password", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "", http.StatusCreated},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.auth = sessionFixture{login: func(username, password string) (dto.SessionDTO, error) {
|
||||
if username != "alice" || password != "long-password:ok" {
|
||||
t.Fatal("credentials altered")
|
||||
}
|
||||
return dto.SessionDTO{Token: "opaque", ExpiresAt: time.Now().UTC().Add(time.Hour), User: dto.UserDTO{ID: uuid.New(), Username: "alice"}}, nil
|
||||
}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader(tc.body))
|
||||
req.Header.Set("Authorization", tc.header)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != tc.status {
|
||||
t.Fatalf("got %d want %d", response.StatusCode, tc.status)
|
||||
}
|
||||
if tc.status == http.StatusUnauthorized && response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("missing Basic challenge")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginInvalidCredentialsUsesBasicChallenge checks the service rejection mapping.
|
||||
func TestLoginInvalidCredentialsUsesBasicChallenge(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.auth = sessionFixture{login: func(string, string) (dto.SessionDTO, error) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth("alice", "invalid-password")
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatal("incorrect login rejection")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutHTTPReturnsNoContent checks the authenticated revocation response.
|
||||
func TestLogoutHTTPReturnsNoContent(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+actor)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil || response.StatusCode != http.StatusNoContent || len(body) != 0 {
|
||||
t.Fatalf("invalid logout response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutHTTPPreservesFailure ensures an unsuccessful revoke does not claim success.
|
||||
func TestLogoutHTTPPreservesFailure(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
ctrl.auth = sessionFixture{fixtureAuthentication: fixtureAuthentication{ctrl.service}, logoutError: context.DeadlineExceeded}
|
||||
status, _, err := request(ctrl, http.MethodDelete, "/api/v1/auth/sessions/current", actor, nil)
|
||||
if err != nil || status != http.StatusInternalServerError {
|
||||
t.Fatalf("revocation failure hidden: %d %v", status, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyIdentityDoesNotAuthenticate verifies the lab1 header cannot grant access.
|
||||
func TestLegacyIdentityDoesNotAuthenticate(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
req.Header.Set("X-User-Id", actor)
|
||||
response, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = response.Body.Close()
|
||||
}()
|
||||
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatal("legacy identity granted access or missing challenge")
|
||||
}
|
||||
}
|
||||
|
||||
type unavailableReadiness struct{}
|
||||
|
||||
// Ping simulates an unavailable mandatory dependency for readiness mapping.
|
||||
func (unavailableReadiness) Ping(context.Context) error {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
|
||||
// TestReadinessRejectsDependencyFailure verifies readiness reflects mandatory infrastructure.
|
||||
func TestReadinessRejectsDependencyFailure(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.readiness = unavailableReadiness{}
|
||||
status, _, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
|
||||
if err != nil || status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("incorrect readiness: %d %v", status, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
||||
)
|
||||
|
||||
// TestBodyLimitInstanceHeader verifies parser-generated 413 responses over a real TCP listener.
|
||||
func TestBodyLimitInstanceHeader(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.MaxBodyBytes = 64 << 10
|
||||
cfg.HTTP.InstanceID = "body-limit-test-instance"
|
||||
})
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
address := make(chan string, 1)
|
||||
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
|
||||
address <- net.JoinHostPort(data.Host, data.Port)
|
||||
return nil
|
||||
})
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := ctrl.Stop(ctx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
client := &http.Client{Timeout: 3 * time.Second}
|
||||
|
||||
// Act.
|
||||
response, err := client.Post("http://"+<-address+"/api/v1/users", "application/json", strings.NewReader(strings.Repeat("x", ctrl.cfg.MaxBodyBytes+1)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := response.Body.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Assert.
|
||||
if response.StatusCode != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status=%d", response.StatusCode)
|
||||
}
|
||||
if instance := response.Header.Get("X-Instance-Id"); instance != ctrl.instanceID {
|
||||
t.Fatalf("instance=%q, want %q", instance, ctrl.instanceID)
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Error.Code != "payload_too_large" || body.Error.RequestID == "" || body.Error.RequestID != response.Header.Get(headerRequestID) {
|
||||
t.Fatalf("invalid error envelope: %+v", body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestController_ChatsCreate checks membership and request validation in isolated chats.
|
||||
func TestController_ChatsCreate(t *testing.T) {
|
||||
t.Run("Positive: caller included", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusCreated, body)
|
||||
if body["title"] != "Team" || !reflect.DeepEqual(body["member_ids"], []any{actor}) {
|
||||
t.Fatalf("chat fields changed: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: empty members", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: duplicate members", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: caller omitted", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
outsider := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{outsider}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown member", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, uuid.NewString()}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed member ID", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, "invalid"}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: blank title", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]any{"title": " ", "member_ids": []string{actor}})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed JSON", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
payload := []byte(`{`)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_ChatsGetByID checks access and the returned chat identity.
|
||||
func TestController_ChatsGetByID(t *testing.T) {
|
||||
t.Run("Positive: member reads chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor, target := owner, id
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if body["id"] != id || body["title"] != "Чат" {
|
||||
t.Fatalf("wrong chat: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor, target := user(t, ctrl), id
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
actor, target := owner, uuid.NewString()
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed chat ID", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
actor, target := owner, "invalid"
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: authentication precedes ID parsing", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor, target := "", "invalid"
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_ChatsGetPage checks that foreign memberships remain absent from lists.
|
||||
func TestController_ChatsGetPage(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
chat(t, ctrl, owner)
|
||||
outsider := user(t, ctrl)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats", outsider, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if len(body["items"].([]any)) != 0 || body["next_cursor"] != nil {
|
||||
t.Fatalf("foreign chat leaked: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_ChatPagination recovers every chat exactly once across page boundaries.
|
||||
func TestController_ChatPagination(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
expected := make(map[string]bool)
|
||||
for range 15 {
|
||||
expected[chat(t, ctrl, actor)] = true
|
||||
}
|
||||
|
||||
// Act.
|
||||
items := history(t, ctrl, actor, "/api/v1/chats")
|
||||
|
||||
// Assert.
|
||||
if len(items) != len(expected) {
|
||||
t.Fatalf("got %d chats, want %d", len(items), len(expected))
|
||||
}
|
||||
for _, item := range items {
|
||||
id := item.(map[string]any)["id"].(string)
|
||||
if !expected[id] {
|
||||
t.Fatalf("duplicate or unexpected chat %s", id)
|
||||
}
|
||||
delete(expected, id)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_ChatCursorScope rejects a continuation issued for another user's list.
|
||||
func TestController_ChatCursorScope(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
outsider := user(t, ctrl)
|
||||
chat(t, ctrl, owner)
|
||||
chat(t, ctrl, owner)
|
||||
page := call(t, ctrl, http.MethodGet, "/api/v1/chats?limit=1", owner, nil, http.StatusOK)
|
||||
token := page["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(token), outsider, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
)
|
||||
|
||||
// configure initializes the HTTP server, middleware and routes.
|
||||
func (ctrl *Controller) configure() {
|
||||
ctrl.createServer()
|
||||
ctrl.initMiddlewares()
|
||||
ctrl.initRoutes()
|
||||
}
|
||||
|
||||
// createServer creates Fiber with the configured transport limits and error handler.
|
||||
func (ctrl *Controller) createServer() {
|
||||
timeout := ctrl.cfg.Timeout()
|
||||
ctrl.server = fiber.New(fiber.Config{
|
||||
AppName: "messenger-lab1",
|
||||
DisableStartupMessage: true,
|
||||
Immutable: true,
|
||||
CaseSensitive: true,
|
||||
StrictRouting: true,
|
||||
BodyLimit: ctrl.cfg.MaxBodyBytes,
|
||||
Concurrency: ctrl.cfg.MaxConnections,
|
||||
ReadTimeout: timeout,
|
||||
WriteTimeout: timeout,
|
||||
IdleTimeout: timeout,
|
||||
ErrorHandler: ctrl.handleErr,
|
||||
})
|
||||
}
|
||||
|
||||
// initMiddlewares registers request logging and panic recovery middleware.
|
||||
func (ctrl *Controller) initMiddlewares() {
|
||||
ctrl.server.Use(ctrl.request)
|
||||
ctrl.server.Use(recover.New())
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Package fiber implements the messenger HTTP transport using Fiber.
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.lab260.ru/fielderr"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/controller"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// Controller owns the HTTP server and delegates business operations to Service.
|
||||
// Its configuration is copied at construction and must not change during serving.
|
||||
// Fx manages its listener through Start and Stop.
|
||||
type Controller struct {
|
||||
observer HTTPObserver
|
||||
attachments Attachments
|
||||
metrics *httpMetrics
|
||||
log *zap.Logger
|
||||
cfg config.Controller
|
||||
service service.Service
|
||||
server *fiber.App
|
||||
errorRegistry *fielderr.Registry
|
||||
admission admission.Distributed
|
||||
auth service.Authentication
|
||||
readiness Readiness
|
||||
stopping atomic.Bool
|
||||
instanceID string
|
||||
serveDone chan error
|
||||
}
|
||||
|
||||
var _ controller.Controller = (*Controller)(nil)
|
||||
|
||||
// New validates dependencies and prepares the server without opening a listener.
|
||||
// Routing, middleware and Fiber configuration are installed by configure.
|
||||
func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry *fielderr.Registry, limiter admission.Distributed, auth service.Authentication, readiness Readiness) (*Controller, error) {
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if log == nil || svc == nil || registry == nil || limiter == nil || auth == nil || readiness == nil {
|
||||
return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required")
|
||||
}
|
||||
ctrl := &Controller{
|
||||
metrics: newHTTPMetrics(),
|
||||
log: log.Named("controller.http.fiber"),
|
||||
cfg: *cfg,
|
||||
service: svc,
|
||||
errorRegistry: registry,
|
||||
admission: limiter,
|
||||
auth: auth,
|
||||
readiness: readiness,
|
||||
serveDone: make(chan error, 1),
|
||||
}
|
||||
ctrl.instanceID = cfg.InstanceID
|
||||
if ctrl.instanceID == "" {
|
||||
ctrl.instanceID = uuid.NewString()
|
||||
}
|
||||
ctrl.configure()
|
||||
return ctrl, nil
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service/production"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store/memory"
|
||||
)
|
||||
|
||||
// testController creates an integration fixture with the real controller, service and store.
|
||||
func testController(t *testing.T, change func(*config.Config)) *Controller {
|
||||
t.Helper()
|
||||
cfg := config.Default()
|
||||
cfg.HTTP.MaxConnections = 256
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 100000
|
||||
cfg.HTTP.Admission.Burst = 100000
|
||||
if change != nil {
|
||||
change(cfg)
|
||||
}
|
||||
repo, err := memory.New(cfg.Memory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := production.New(repo, codec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry, err := NewErrorRegistry()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limiter, err := admission.New(admission.Options{
|
||||
MaxInFlight: cfg.HTTP.Admission.MaxInFlight,
|
||||
RequestsPerSecond: cfg.HTTP.Admission.RequestsPerSecond,
|
||||
Burst: cfg.HTTP.Admission.Burst,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctrl, err := New(zap.NewNop(), cfg.HTTP, svc, registry, &fixtureAdmission{limiter}, fixtureAuthentication{svc}, fixtureReadiness{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ctrl
|
||||
}
|
||||
|
||||
// request sends a raw test request and decodes its response.
|
||||
func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) {
|
||||
req := httptest.NewRequest(method, path, bytes.NewReader(body))
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actor != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+actor)
|
||||
}
|
||||
resp, err := ctrl.server.Test(req, 10000)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
var data map[string]any
|
||||
if err = json.Unmarshal(b, &data); err != nil {
|
||||
return resp.StatusCode, nil, fmt.Errorf("invalid JSON response: %w", err)
|
||||
}
|
||||
if resp.Header.Get("X-Request-Id") == "" {
|
||||
return resp.StatusCode, data, fmt.Errorf("missing request ID")
|
||||
}
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
envelope, ok := data["error"].(map[string]any)
|
||||
if !ok || envelope["request_id"] != resp.Header.Get("X-Request-Id") {
|
||||
return resp.StatusCode, data, fmt.Errorf("invalid error envelope")
|
||||
}
|
||||
}
|
||||
return resp.StatusCode, data, nil
|
||||
}
|
||||
|
||||
// call sends a JSON test request and checks its expected HTTP status.
|
||||
func call(t *testing.T, ctrl *Controller, method, path, actor string, body any, want int) map[string]any {
|
||||
t.Helper()
|
||||
var b []byte
|
||||
var err error
|
||||
if raw, ok := body.([]byte); ok {
|
||||
b = raw
|
||||
} else if body != nil {
|
||||
b, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
status, data, err := request(ctrl, method, path, actor, b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != want {
|
||||
t.Fatalf("%s %s: got %d want %d: %v", method, path, status, want, data)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// user creates a test user and returns its identifier.
|
||||
func user(t *testing.T, c *Controller) string {
|
||||
t.Helper()
|
||||
r := call(t, c, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "u_" + uuid.New().String()[:8], "display_name": "Алиса 👋", "password": "fixture-password-123"}, http.StatusCreated)
|
||||
return r["id"].(string)
|
||||
}
|
||||
|
||||
// chat creates a test chat containing the supplied user.
|
||||
func chat(t *testing.T, c *Controller, u string) string {
|
||||
t.Helper()
|
||||
r := call(t, c, http.MethodPost, "/api/v1/chats", u, map[string]any{"title": "Чат", "member_ids": []string{u}}, http.StatusCreated)
|
||||
return r["id"].(string)
|
||||
}
|
||||
|
||||
// TestDuplicateUsernameRace checks username uniqueness under concurrent requests.
|
||||
func TestDuplicateUsernameRace(t *testing.T) {
|
||||
// Arrange.
|
||||
c := testController(t, nil)
|
||||
results := make(chan int, 10)
|
||||
failures := make(chan error, 10)
|
||||
var wg sync.WaitGroup
|
||||
// Act.
|
||||
for range 10 {
|
||||
wg.Go(func() {
|
||||
status, _, err := request(c, http.MethodPost, "/api/v1/users", "", []byte(`{"username":"same","display_name":"User","password":"fixture-password-123"}`))
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
results <- status
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
close(failures)
|
||||
// Assert.
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
created, conflicts := 0, 0
|
||||
for s := range results {
|
||||
switch s {
|
||||
case http.StatusCreated:
|
||||
created++
|
||||
case http.StatusConflict:
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected %d", s)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != 9 {
|
||||
t.Fatalf("created=%d conflicts=%d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
// history collects all test messages by following pagination cursors.
|
||||
func history(t *testing.T, c *Controller, u, path string) []any {
|
||||
t.Helper()
|
||||
var items []any
|
||||
next := path + "?limit=7"
|
||||
for range 100 {
|
||||
r := call(t, c, http.MethodGet, next, u, nil, http.StatusOK)
|
||||
items = append(items, r["items"].([]any)...)
|
||||
if r["next_cursor"] == nil {
|
||||
return items
|
||||
}
|
||||
next = path + "?limit=7&cursor=" + url.QueryEscape(r["next_cursor"].(string))
|
||||
}
|
||||
t.Fatal("pagination never finished")
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestConcurrent100Messages10Clients recovers the exact acknowledged records after concurrent writes.
|
||||
func TestConcurrent100Messages10Clients(t *testing.T) {
|
||||
// Arrange.
|
||||
const clients = 10
|
||||
const messagesPerClient = 10
|
||||
const total = clients * messagesPerClient
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
chatID := chat(t, ctrl, actor)
|
||||
path := "/api/v1/chats/" + chatID + "/messages"
|
||||
acknowledgements := make(chan map[string]any, total)
|
||||
failures := make(chan error, total)
|
||||
var writers sync.WaitGroup
|
||||
|
||||
// Act.
|
||||
for client := range clients {
|
||||
writers.Go(func() {
|
||||
for index := range messagesPerClient {
|
||||
text := fmt.Sprintf("client %d message %d", client, index)
|
||||
payload, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
failures <- err
|
||||
continue
|
||||
}
|
||||
status, body, err := request(ctrl, http.MethodPost, path, actor, payload)
|
||||
if err != nil {
|
||||
failures <- err
|
||||
continue
|
||||
}
|
||||
if status != http.StatusCreated || body["text"] != text || body["sender_id"] != actor || body["chat_id"] != chatID {
|
||||
failures <- fmt.Errorf("incorrect acknowledgement: status=%d, body=%v", status, body)
|
||||
continue
|
||||
}
|
||||
acknowledgements <- body
|
||||
}
|
||||
})
|
||||
}
|
||||
writers.Wait()
|
||||
close(failures)
|
||||
close(acknowledgements)
|
||||
|
||||
// Assert.
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
if t.Failed() {
|
||||
t.FailNow()
|
||||
}
|
||||
expected := make(map[string]map[string]any, total)
|
||||
for message := range acknowledgements {
|
||||
id, ok := message["id"].(string)
|
||||
if !ok || id == "" {
|
||||
t.Fatalf("invalid message ID: %v", message)
|
||||
}
|
||||
if _, duplicate := expected[id]; duplicate {
|
||||
t.Fatalf("duplicate acknowledgement ID %s", id)
|
||||
}
|
||||
expected[id] = message
|
||||
}
|
||||
if len(expected) != total {
|
||||
t.Fatalf("acknowledged=%d, want=%d", len(expected), total)
|
||||
}
|
||||
items := history(t, ctrl, actor, path)
|
||||
if len(items) != total {
|
||||
t.Fatalf("recovered=%d, want=%d", len(items), total)
|
||||
}
|
||||
for _, item := range items {
|
||||
message := item.(map[string]any)
|
||||
id := message["id"].(string)
|
||||
if !reflect.DeepEqual(message, expected[id]) {
|
||||
t.Fatalf("stored record differs from acknowledgement: got=%v, want=%v", message, expected[id])
|
||||
}
|
||||
delete(expected, id)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnsupportedMediaType checks rejection of unsupported request content types.
|
||||
func TestUnsupportedMediaType(t *testing.T) {
|
||||
// Arrange.
|
||||
c := testController(t, nil)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{}`))
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
// Act.
|
||||
r, e := c.server.Test(req)
|
||||
|
||||
// Assert.
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if r.StatusCode != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("status %d", r.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfigIndependentState prevents one application instance from accepting another's identity.
|
||||
func TestConfigIndependentState(t *testing.T) {
|
||||
// Arrange.
|
||||
first := testController(t, nil)
|
||||
actor := user(t, first)
|
||||
second := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(second, http.MethodGet, "/api/v1/users/me", actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
}
|
||||
|
||||
// mustJSON encodes fixture payloads and reports preparation failures at the caller.
|
||||
func mustJSON(t *testing.T, value any) []byte {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"mime"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/strictjson"
|
||||
)
|
||||
|
||||
// decode checks HTTP media type and maps strict JSON decoding errors to API input errors.
|
||||
func decode(ctx *fiber.Ctx, target any, requiredFields ...string) error {
|
||||
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
|
||||
if err != nil || mediaType != fiber.MIMEApplicationJSON {
|
||||
return errMedia
|
||||
}
|
||||
if err := strictjson.DecodeObject(ctx.Body(), target, requiredFields...); err != nil {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeMessage accepts the optional attachment list without weakening strict JSON validation.
|
||||
func decodeMessage(ctx *fiber.Ctx, target any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
|
||||
if err != nil || mediaType != fiber.MIMEApplicationJSON {
|
||||
return errMedia
|
||||
}
|
||||
if err := strictjson.DecodeOptional(ctx.Body(), target, []string{"text"}, []string{"attachment_ids"}); err != nil {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package fiber
|
||||
|
||||
import "context"
|
||||
|
||||
// Readiness checks the dependencies required by the synchronous request path.
|
||||
type Readiness interface {
|
||||
// Ping reports whether requests can be safely served.
|
||||
Ping(context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package fiber
|
||||
|
||||
const (
|
||||
// codeInvalid identifies malformed or invalid request input.
|
||||
codeInvalid = "invalid_request"
|
||||
// codeUnauthorized identifies an unresolved user identity.
|
||||
codeUnauthorized = "unauthorized"
|
||||
// codeNotFound deliberately covers both absent and inaccessible resources.
|
||||
codeNotFound = "not_found"
|
||||
// codeConflict identifies a violated uniqueness constraint.
|
||||
codeConflict = "conflict"
|
||||
// codeUnavailable identifies temporary admission or persistent capacity exhaustion.
|
||||
codeUnavailable = "unavailable"
|
||||
// codeRateLimited identifies exhaustion of the request token bucket.
|
||||
codeRateLimited = "rate_limited"
|
||||
// codeTooLarge identifies a request exceeding the transport byte budget.
|
||||
codeTooLarge = "payload_too_large"
|
||||
// codeMedia identifies an unsupported request media type.
|
||||
codeMedia = "unsupported_media_type"
|
||||
// codeInternal identifies a hidden unexpected failure.
|
||||
codeInternal = "internal_error"
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
)
|
||||
|
||||
// NewErrorRegistry returns an immutable mapping of application statuses to HTTP codes.
|
||||
// The registry is injected rather than installed in process-global state, allowing
|
||||
// independent application instances in integration tests.
|
||||
func NewErrorRegistry() (*fielderr.Registry, error) {
|
||||
return fielderr.NewRegistry(
|
||||
statusDefinition(codeInvalid, http.StatusBadRequest),
|
||||
statusDefinition(codeUnauthorized, http.StatusUnauthorized),
|
||||
statusDefinition(codeNotFound, http.StatusNotFound),
|
||||
statusDefinition(codeConflict, http.StatusConflict),
|
||||
statusDefinition(codeTooLarge, http.StatusRequestEntityTooLarge),
|
||||
statusDefinition(codeMedia, http.StatusUnsupportedMediaType),
|
||||
statusDefinition(codeRateLimited, http.StatusTooManyRequests),
|
||||
statusDefinition(codeUnavailable, http.StatusServiceUnavailable),
|
||||
statusDefinition(codeInternal, http.StatusInternalServerError),
|
||||
)
|
||||
}
|
||||
|
||||
// statusDefinition associates an application error code with its HTTP status.
|
||||
func statusDefinition(name string, httpStatus int) fielderr.StatusDefinition {
|
||||
return fielderr.StatusDefinition{
|
||||
Code: fielderr.NewStatusCode(name),
|
||||
Name: name,
|
||||
HTTPStatus: httpStatus,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.lab260.ru/fielderr"
|
||||
"go.uber.org/zap"
|
||||
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// handleErr normalizes a failure and writes the public error envelope.
|
||||
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
|
||||
// Parser failures such as BodyLimit rejection bypass request middleware.
|
||||
ctx.Set("X-Instance-Id", ctrl.instanceID)
|
||||
requestID := ctx.GetRespHeader(headerRequestID)
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewString()
|
||||
ctx.Set(headerRequestID, requestID)
|
||||
}
|
||||
err = publicError(normalizeTransportError(err))
|
||||
status, ok := fielderr.HTTPStatusFrom(ctrl.errorRegistry, err)
|
||||
if !ok {
|
||||
err = errInternal
|
||||
status = http.StatusInternalServerError
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if ctx.Path() == "/api/v1/auth/sessions" && ctx.Method() == http.MethodPost {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
ctx.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
}
|
||||
if status == http.StatusInternalServerError {
|
||||
ctrl.log.Error("unexpected request failure", zap.String("request_id", requestID))
|
||||
}
|
||||
return ctx.Status(status).JSON(errorResponse(err, requestID))
|
||||
}
|
||||
|
||||
// normalizeTransportError maps Fiber failures to transport-independent application errors.
|
||||
func normalizeTransportError(err error) error {
|
||||
transportError, ok := errors.AsType[*fiber.Error](err)
|
||||
if !ok {
|
||||
return err
|
||||
}
|
||||
switch transportError.Code {
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return errTooLarge
|
||||
case http.StatusNotFound, http.StatusMethodNotAllowed:
|
||||
return service.ErrNotFound
|
||||
case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestHeaderFieldsTooLarge:
|
||||
return service.ErrInvalid
|
||||
default:
|
||||
return errInternal
|
||||
}
|
||||
}
|
||||
|
||||
// errorResponse builds the public error envelope with its request identifier.
|
||||
func errorResponse(err error, requestID string) httpmodel.ErrorResponse {
|
||||
status, _ := fielderr.Status(err)
|
||||
message, _ := fielderr.PublicMessage(err)
|
||||
return httpmodel.ErrorResponse{
|
||||
Error: httpmodel.ErrorDetail{
|
||||
Code: status.String(),
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/valyala/fasthttp"
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// TestTransportErrorMapping checks safe API errors for framework-generated failures.
|
||||
func TestTransportErrorMapping(t *testing.T) {
|
||||
t.Run("large body", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrRequestEntityTooLarge) != errTooLarge {
|
||||
t.Fatal("incorrect body-limit error")
|
||||
}
|
||||
})
|
||||
t.Run("method not allowed", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrMethodNotAllowed) != service.ErrNotFound {
|
||||
t.Fatal("unexpected method error")
|
||||
}
|
||||
})
|
||||
t.Run("invalid request", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrBadRequest) != service.ErrInvalid {
|
||||
t.Fatal("unexpected input error")
|
||||
}
|
||||
})
|
||||
t.Run("unexpected framework failure", func(t *testing.T) {
|
||||
if normalizeTransportError(fiber.ErrInternalServerError) != errInternal {
|
||||
t.Fatal("unexpected failure escaped normalization")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_handleErr writes a safe, correlated fallback response.
|
||||
func TestController_handleErr(t *testing.T) {
|
||||
t.Run("Negative: unknown internal error", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
raw := &fasthttp.RequestCtx{}
|
||||
ctx := ctrl.server.AcquireCtx(raw)
|
||||
defer ctrl.server.ReleaseCtx(ctx)
|
||||
|
||||
// Act.
|
||||
err := ctrl.handleErr(ctx, errors.New("private storage secret"))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw.Response.StatusCode() != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d", raw.Response.StatusCode())
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestID := string(raw.Response.Header.Peek(headerRequestID))
|
||||
if requestID == "" || body.Error.RequestID != requestID {
|
||||
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
|
||||
}
|
||||
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
|
||||
t.Fatalf("unsafe fallback: %+v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing status mapping", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
registry, err := fielderr.NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctrl.errorRegistry = registry
|
||||
raw := &fasthttp.RequestCtx{}
|
||||
ctx := ctrl.server.AcquireCtx(raw)
|
||||
defer ctrl.server.ReleaseCtx(ctx)
|
||||
|
||||
// Act.
|
||||
err = ctrl.handleErr(ctx, service.ErrInvalid)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw.Response.StatusCode() != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d", raw.Response.StatusCode())
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requestID := string(raw.Response.Header.Peek(headerRequestID))
|
||||
if requestID == "" || body.Error.RequestID != requestID {
|
||||
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
|
||||
}
|
||||
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
|
||||
t.Fatalf("unsafe fallback: %+v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/admission"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// fixtureAuthentication isolates HTTP decoding and business authorization from session persistence.
|
||||
type fixtureAuthentication struct {
|
||||
service service.Service
|
||||
}
|
||||
|
||||
// Register delegates profile validation to the real business service.
|
||||
func (f fixtureAuthentication) Register(ctx context.Context, request dto.UsersCreateRequestDTO, _ string) (dto.UserDTO, error) {
|
||||
return f.service.UsersCreate(ctx, request)
|
||||
}
|
||||
|
||||
// Authenticate uses fixture tokens equal to user IDs exclusively in controller tests.
|
||||
func (f fixtureAuthentication) Authenticate(ctx context.Context, token string) (string, error) {
|
||||
return token, f.service.UsersCheckIdentity(ctx, token)
|
||||
}
|
||||
|
||||
// Login is deliberately unsupported by this fixture; real login has separate integration coverage.
|
||||
func (f fixtureAuthentication) Login(context.Context, string, string) (dto.SessionDTO, error) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
|
||||
// Logout accepts the fixture session without persistent side effects.
|
||||
func (f fixtureAuthentication) Logout(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixtureReadiness struct{}
|
||||
|
||||
// Ping marks isolated controller fixtures ready without external resources.
|
||||
func (fixtureReadiness) Ping(context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixtureAdmission struct {
|
||||
*admission.Limiter
|
||||
}
|
||||
|
||||
// Enter adapts the deterministic local policy fixture to the distributed boundary.
|
||||
func (f *fixtureAdmission) Enter(_ context.Context, _, user string) (func(), error) {
|
||||
if user != "" {
|
||||
return func() {
|
||||
}, nil
|
||||
}
|
||||
if !f.Allow(time.Now()) {
|
||||
return nil, admission.ErrRate
|
||||
}
|
||||
if !f.Acquire() {
|
||||
return nil, admission.ErrSlots
|
||||
}
|
||||
return f.Release, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
||||
)
|
||||
|
||||
// HandleUsersCreate decodes registration input and returns the created user.
|
||||
func (ctrl *Controller) HandleUsersCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.UsersCreateRequest
|
||||
if err := decode(ctx, &request, "username", "display_name", "password"); err != nil {
|
||||
return err
|
||||
}
|
||||
user, err := ctrl.auth.Register(ctx.UserContext(), dto.UsersCreateRequestDTO{
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}, request.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(userResponse(user))
|
||||
}
|
||||
|
||||
// HandleUsersGetMe returns the account selected by the validated session.
|
||||
func (ctrl *Controller) HandleUsersGetMe(ctx *fiber.Ctx) error {
|
||||
user, err := ctrl.service.UsersGetMe(ctx.UserContext(), identity(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(userResponse(user))
|
||||
}
|
||||
|
||||
// HandleChatsCreate decodes the chat payload and returns the new chat.
|
||||
func (ctrl *Controller) HandleChatsCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.ChatsCreateRequest
|
||||
if err := decode(ctx, &request, "title", "member_ids"); err != nil {
|
||||
return err
|
||||
}
|
||||
chat, err := ctrl.service.ChatsCreate(ctx.UserContext(), dto.ChatsCreateRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
Title: request.Title,
|
||||
MemberIDs: request.MemberIDs,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(chatResponse(chat))
|
||||
}
|
||||
|
||||
// HandleChatsGetByID delegates chat authorization and maps the accessible chat.
|
||||
func (ctrl *Controller) HandleChatsGetByID(ctx *fiber.Ctx) error {
|
||||
chat, err := ctrl.service.ChatsGetByID(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(chatResponse(chat))
|
||||
}
|
||||
|
||||
// HandleChatsGetPage returns the service's page of visible chats.
|
||||
func (ctrl *Controller) HandleChatsGetPage(ctx *fiber.Ctx) error {
|
||||
page, err := ctrl.service.ChatsGetPage(ctx.UserContext(), pageRequest(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(chatPageResponse(page))
|
||||
}
|
||||
|
||||
// HandleMessagesCreate decodes text; the service derives and authorizes the sender.
|
||||
func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error {
|
||||
var request httpmodel.MessagesCreateRequest
|
||||
if err := decodeMessage(ctx, &request); err != nil {
|
||||
return err
|
||||
}
|
||||
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
|
||||
AttachmentIDs: request.AttachmentIDs,
|
||||
IdempotencyKey: ctx.Get("Idempotency-Key"),
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Text: request.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusCreated).JSON(messageResponse(message))
|
||||
}
|
||||
|
||||
// HandleMessagesGetPage returns the service's ordered history page.
|
||||
func (ctrl *Controller) HandleMessagesGetPage(ctx *fiber.Ctx) error {
|
||||
page, err := ctrl.service.MessagesGetPage(ctx.UserContext(), pageRequest(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Status(http.StatusOK).JSON(messagePageResponse(page))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package fiber
|
||||
|
||||
const (
|
||||
headerUserID = "X-User-Id"
|
||||
headerRequestID = "X-Request-Id"
|
||||
retryAfterSeconds = 1
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// handleLive reports that the server process is running.
|
||||
func (ctrl *Controller) handleLive(ctx *fiber.Ctx) error {
|
||||
return ctx.JSON(fiber.Map{"status": "ok"})
|
||||
}
|
||||
|
||||
// handleReady reports readiness unless shutdown has started.
|
||||
func (ctrl *Controller) handleReady(ctx *fiber.Ctx) error {
|
||||
if ctrl.stopping.Load() {
|
||||
return errBusy
|
||||
}
|
||||
if err := ctrl.readiness.Ping(ctx.UserContext()); err != nil {
|
||||
return errBusy
|
||||
}
|
||||
return ctrl.handleLive(ctx)
|
||||
}
|
||||
|
||||
// handleNotFound returns the application error for an unmatched route.
|
||||
func (ctrl *Controller) handleNotFound(_ *fiber.Ctx) error {
|
||||
return service.ErrNotFound
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Start opens the listener synchronously so Fx observes bind errors immediately.
|
||||
// It must be called once per Controller; Stop terminates the serving goroutine.
|
||||
func (ctrl *Controller) Start(ctx context.Context) error {
|
||||
listener, err := net.Listen("tcp", ctrl.cfg.Bind())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ready := make(chan struct{})
|
||||
go ctrl.serve(&acceptingListener{Listener: listener, ready: ready})
|
||||
select {
|
||||
case <-ready:
|
||||
ctrl.log.Info("http listener started", zap.String("address", listener.Addr().String()))
|
||||
return nil
|
||||
case err := <-ctrl.serveDone:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
_ = listener.Close()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// acceptingListener signals after fasthttp registers the listener and enters its
|
||||
// accept loop. An OnListen hook runs earlier and cannot guarantee safe immediate Stop.
|
||||
type acceptingListener struct {
|
||||
// Listener is the bound socket owned by the HTTP lifecycle.
|
||||
net.Listener
|
||||
ready chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// Accept marks the server as started before waiting for the next connection.
|
||||
func (listener *acceptingListener) Accept() (net.Conn, error) {
|
||||
listener.once.Do(func() {
|
||||
close(listener.ready)
|
||||
})
|
||||
return listener.Listener.Accept()
|
||||
}
|
||||
|
||||
// serve serves the listener and publishes its terminal result to the lifecycle.
|
||||
func (ctrl *Controller) serve(listener net.Listener) {
|
||||
ctrl.serveDone <- ctrl.server.Listener(listener)
|
||||
}
|
||||
|
||||
// Stop disables admission, closes the listener and drains active requests.
|
||||
// The configured timeout is bounded by the caller's Fx shutdown context.
|
||||
func (ctrl *Controller) Stop(ctx context.Context) error {
|
||||
ctrl.stopping.Store(true)
|
||||
ctx, cancel := context.WithTimeout(ctx, ctrl.cfg.ShutdownTimeout())
|
||||
defer cancel()
|
||||
if err := ctrl.server.ShutdownWithContext(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case err := <-ctrl.serveDone:
|
||||
ctrl.log.Info("http listener stopped")
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// TestImmediateShutdown checks the startup/stop race without waiting for a first request.
|
||||
func TestImmediateShutdown(t *testing.T) {
|
||||
const repetitions = 10
|
||||
const stopDeadline = time.Second
|
||||
for range repetitions {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
// Select an ephemeral test port after validating the normal application config.
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), stopDeadline)
|
||||
// Act.
|
||||
err := ctrl.Stop(ctx)
|
||||
cancel()
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatalf("immediate shutdown leaked the listener or serve goroutine: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_Stop_ActiveRequestDeadline bounds draining while a real handler is still running.
|
||||
func TestController_Stop_ActiveRequestDeadline(t *testing.T) {
|
||||
// Arrange.
|
||||
const deadline = 3 * time.Second
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
// Install one controlled handler to test lifecycle independently of business routes.
|
||||
ctrl.createServer()
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
address := make(chan string, 1)
|
||||
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
|
||||
address <- net.JoinHostPort(data.Host, data.Port)
|
||||
return nil
|
||||
})
|
||||
ctrl.server.Get("/blocked", func(ctx *fiber.Ctx) error {
|
||||
close(entered)
|
||||
<-release
|
||||
return ctx.SendStatus(http.StatusOK)
|
||||
})
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Timeout: deadline}
|
||||
completed := make(chan error, 1)
|
||||
go func() {
|
||||
response, err := client.Get("http://" + <-address + "/blocked")
|
||||
if err == nil {
|
||||
err = response.Body.Close()
|
||||
}
|
||||
completed <- err
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
close(release)
|
||||
select {
|
||||
case err := <-completed:
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
case <-time.After(deadline):
|
||||
t.Error("blocked request did not terminate after release")
|
||||
}
|
||||
stopCtx, cancel := context.WithTimeout(context.Background(), deadline)
|
||||
defer cancel()
|
||||
if err := ctrl.Stop(stopCtx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(deadline):
|
||||
t.Fatal("request did not reach handler")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
|
||||
// Act.
|
||||
err := ctrl.Stop(ctx)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected canceled drain, got %v", err)
|
||||
}
|
||||
if !ctrl.stopping.Load() {
|
||||
t.Fatal("shutdown did not disable admission")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCanceledStartup closes its socket while server initialization is still blocked.
|
||||
func TestCanceledStartup(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
release := make(chan struct{})
|
||||
ctrl.server.Hooks().OnListen(func(_ fiber.ListenData) error {
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
// Act.
|
||||
err := ctrl.Start(ctx)
|
||||
close(release)
|
||||
// Assert.
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected canceled startup, got %v", err)
|
||||
}
|
||||
select {
|
||||
case <-ctrl.serveDone:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("serving goroutine leaked after canceled startup")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/http"
|
||||
)
|
||||
|
||||
// userResponse converts a user DTO into its HTTP representation.
|
||||
func userResponse(user dto.UserDTO) httpmodel.UserResponse {
|
||||
return httpmodel.UserResponse{
|
||||
ID: user.ID.String(),
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// chatResponse converts a chat DTO and its member identifiers into an HTTP response.
|
||||
func chatResponse(chat dto.ChatDTO) httpmodel.ChatResponse {
|
||||
members := make([]string, len(chat.MemberIDs))
|
||||
for index, id := range chat.MemberIDs {
|
||||
members[index] = id.String()
|
||||
}
|
||||
return httpmodel.ChatResponse{
|
||||
ID: chat.ID.String(),
|
||||
Title: chat.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// messageResponse converts a message DTO into its HTTP representation.
|
||||
func messageResponse(message dto.MessageDTO) httpmodel.MessageResponse {
|
||||
ids := append([]string{}, message.AttachmentIDs...)
|
||||
return httpmodel.MessageResponse{
|
||||
AttachmentIDs: ids,
|
||||
ID: message.ID.String(),
|
||||
ChatID: message.ChatID.String(),
|
||||
SenderID: message.SenderID.String(),
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// pageRequest extracts identity, resource and pagination parameters from the request.
|
||||
func pageRequest(ctx *fiber.Ctx) dto.PageRequestDTO {
|
||||
return dto.PageRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Limit: ctx.Query("limit"),
|
||||
Cursor: ctx.Query("cursor"),
|
||||
}
|
||||
}
|
||||
|
||||
// chatPageResponse converts a page of chat DTOs into an HTTP response.
|
||||
func chatPageResponse(page dto.ChatPageDTO) httpmodel.ChatPageResponse {
|
||||
response := httpmodel.ChatPageResponse{
|
||||
Items: make([]httpmodel.ChatResponse, len(page.Items)),
|
||||
NextCursor: page.NextCursor,
|
||||
}
|
||||
for index, chat := range page.Items {
|
||||
response.Items[index] = chatResponse(chat)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
// messagePageResponse converts a page of message DTOs into an HTTP response.
|
||||
func messagePageResponse(page dto.MessagePageDTO) httpmodel.MessagePageResponse {
|
||||
response := httpmodel.MessagePageResponse{
|
||||
Items: make([]httpmodel.MessageResponse, len(page.Items)),
|
||||
NextCursor: page.NextCursor,
|
||||
}
|
||||
for index, message := range page.Items {
|
||||
response.Items[index] = messageResponse(message)
|
||||
}
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
)
|
||||
|
||||
// TestController_MessagesCreate checks message validation and identity-derived sender fields.
|
||||
func TestController_MessagesCreate(t *testing.T) {
|
||||
t.Run("Positive: Unicode at rune limit", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
text := strings.Repeat("界", 4000)
|
||||
payload := mustJSON(t, map[string]string{"text": text})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusCreated, body)
|
||||
if body["sender_id"] != owner || body["chat_id"] != id || body["text"] != text {
|
||||
t.Fatalf("message fields changed: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: empty text", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": ""})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: whitespace text", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": " \n\t"})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: text exceeds rune limit", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
payload := mustJSON(t, map[string]string{"text": strings.Repeat("界", 4001)})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: sender spoof", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := owner
|
||||
outsider := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]string{"text": "hello", "sender_id": outsider})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := user(t, ctrl)
|
||||
payload := mustJSON(t, map[string]string{"text": "hello"})
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
})
|
||||
|
||||
t.Run("Negative: authentication precedes JSON decoding", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
owner := user(t, ctrl)
|
||||
id := chat(t, ctrl, owner)
|
||||
actor := ""
|
||||
payload := []byte(`{`)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_MessagesGetPage rejects invalid pagination separately from access failures.
|
||||
func TestController_MessagesGetPage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
query string
|
||||
outsider bool
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{"Negative: zero limit", "limit=0", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: limit above maximum", "limit=101", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: negative limit", "limit=-1", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: nonnumeric limit", "limit=x", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: fractional limit", "limit=1.0", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: malformed cursor", "cursor=invalid", false, http.StatusBadRequest, "invalid_request"},
|
||||
{"Negative: outsider", "", true, http.StatusNotFound, "not_found"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
id := chat(t, ctrl, actor)
|
||||
if tc.outsider {
|
||||
actor = user(t, ctrl)
|
||||
}
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+id+"/messages?"+tc.query, actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
assertErrorCode(t, body, tc.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_MessageCursorScope rejects a continuation from another chat's history.
|
||||
func TestController_MessageCursorScope(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
first := chat(t, ctrl, actor)
|
||||
second := chat(t, ctrl, actor)
|
||||
path := "/api/v1/chats/" + first + "/messages"
|
||||
for _, text := range []string{"first", "second"} {
|
||||
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
|
||||
}
|
||||
page := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
|
||||
token := page["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+second+"/messages?cursor="+url.QueryEscape(token), actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusBadRequest, body)
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
}
|
||||
|
||||
// TestController_MessagePageLimitChange preserves continuation when the client changes page size.
|
||||
func TestController_MessagePageLimitChange(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
|
||||
for _, text := range []string{"first", "second", "third"} {
|
||||
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
|
||||
}
|
||||
first := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
|
||||
token := first["next_cursor"].(string)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, path+"?limit=100&cursor="+url.QueryEscape(token), actor, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
items := body["items"].([]any)
|
||||
if len(items) != 2 || body["next_cursor"] != nil {
|
||||
t.Fatalf("unexpected final page: %v", body)
|
||||
}
|
||||
if items[0].(map[string]any)["text"] != "second" || items[1].(map[string]any)["text"] != "third" {
|
||||
t.Fatalf("lost order or skipped messages: %v", items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_MessageCapacity preserves acknowledged data after rejecting an overflow write.
|
||||
func TestController_MessageCapacity(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.Memory.MaxMessages = 2
|
||||
})
|
||||
actor := user(t, ctrl)
|
||||
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
|
||||
first := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "first"}, http.StatusCreated)
|
||||
second := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "second"}, http.StatusCreated)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, path, actor, []byte(`{"text":"rejected"}`))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusServiceUnavailable, body)
|
||||
assertErrorCode(t, body, "unavailable")
|
||||
items := history(t, ctrl, actor, path)
|
||||
if len(items) != 2 || items[0].(map[string]any)["id"] != first["id"] || items[1].(map[string]any)["id"] != second["id"] {
|
||||
t.Fatalf("overflow changed acknowledged messages: %v", items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/adaptor"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
// httpMetrics owns a per-server registry with bounded labels and no user identifiers.
|
||||
type httpMetrics struct {
|
||||
registry *prometheus.Registry
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
active prometheus.Gauge
|
||||
}
|
||||
|
||||
// newHTTPMetrics creates independent collectors so multiple test servers do not share state.
|
||||
func newHTTPMetrics() *httpMetrics {
|
||||
metrics := &httpMetrics{
|
||||
registry: prometheus.NewRegistry(),
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "messenger_http_requests_total", Help: "Completed requests by route, method and status class."}, []string{"route", "method", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "messenger_http_duration_seconds", Help: "Completed request latency.", Buckets: prometheus.DefBuckets}, []string{"route", "method"}),
|
||||
active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "messenger_http_in_flight", Help: "Currently executing HTTP requests."}),
|
||||
}
|
||||
metrics.registry.MustRegister(metrics.requests, metrics.duration, metrics.active)
|
||||
return metrics
|
||||
}
|
||||
|
||||
// observe records bounded route patterns, methods and status classes after error handling.
|
||||
func (m *httpMetrics) observe(ctx *fiber.Ctx, elapsed time.Duration) {
|
||||
route := "unmatched"
|
||||
if ctx.Route() != nil && ctx.Route().Path != "/" {
|
||||
route = ctx.Route().Path
|
||||
}
|
||||
method := ctx.Method()
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
||||
default:
|
||||
method = "other"
|
||||
}
|
||||
status := "5xx"
|
||||
switch ctx.Response().StatusCode() / 100 {
|
||||
case 2:
|
||||
status = "2xx"
|
||||
case 3:
|
||||
status = "3xx"
|
||||
case 4:
|
||||
status = "4xx"
|
||||
}
|
||||
m.requests.WithLabelValues(route, method, status).Inc()
|
||||
m.duration.WithLabelValues(route, method).Observe(elapsed.Seconds())
|
||||
}
|
||||
|
||||
// handleMetrics exposes this process's Prometheus registry without external backend calls.
|
||||
func (ctrl *Controller) handleMetrics(ctx *fiber.Ctx) error {
|
||||
return adaptor.HTTPHandler(promhttp.HandlerFor(ctrl.metrics.registry, promhttp.HandlerOpts{}))(ctx)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// TestMetricsBoundUnknownMethods keeps arbitrary client methods out of metric labels.
|
||||
func TestMetricsBoundUnknownMethods(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
raw := &fasthttp.RequestCtx{}
|
||||
raw.Request.Header.SetMethod("CUSTOM_RANDOM_METHOD")
|
||||
raw.Response.SetStatusCode(http.StatusTemporaryRedirect)
|
||||
ctx := ctrl.server.AcquireCtx(raw)
|
||||
defer ctrl.server.ReleaseCtx(ctx)
|
||||
ctrl.metrics.observe(ctx, time.Millisecond)
|
||||
families, err := ctrl.metrics.registry.Gather()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, family := range families {
|
||||
for _, metric := range family.Metric {
|
||||
for _, label := range metric.Label {
|
||||
if label.GetValue() == "CUSTOM_RANDOM_METHOD" {
|
||||
t.Fatal("unbounded method label")
|
||||
}
|
||||
found = found || label.GetValue() == "other"
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("unknown method was not grouped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMetricsEndpoint exposes completed requests without token or user labels.
|
||||
func TestMetricsEndpoint(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
call(t, ctrl, http.MethodGet, "/health/live", "", nil, http.StatusOK)
|
||||
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "messenger_http_requests_total") || !strings.Contains(string(body), "messenger_http_duration_seconds_bucket") {
|
||||
t.Fatalf("invalid metrics response: status %d", resp.StatusCode)
|
||||
}
|
||||
if resp.Header.Get("X-Instance-Id") == "" {
|
||||
t.Fatal("metrics response lacks instance ID")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstanceIdentityRemainsStable verifies errors and successes identify the same process.
|
||||
func TestInstanceIdentityRemainsStable(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
var instance string
|
||||
for _, path := range []string{"/health/live", "/unknown"} {
|
||||
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instance == "" {
|
||||
instance = resp.Header.Get("X-Instance-Id")
|
||||
}
|
||||
if instance == "" || resp.Header.Get("X-Instance-Id") != instance {
|
||||
t.Fatal("unstable instance identity")
|
||||
}
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingIdempotencyHeader rejects an otherwise valid authenticated write.
|
||||
func TestMissingIdempotencyHeader(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
caller := user(t, ctrl)
|
||||
room := chat(t, ctrl, caller)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room+"/messages", strings.NewReader(`{"text":"valid"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+caller)
|
||||
resp, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("missing key accepted: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/admission"
|
||||
)
|
||||
|
||||
// request assigns a request identifier, handles errors and logs the completed request.
|
||||
func (ctrl *Controller) request(ctx *fiber.Ctx) error {
|
||||
ctx.Set(headerRequestID, uuid.NewString())
|
||||
ctx.Set("X-Instance-Id", ctrl.instanceID)
|
||||
started := time.Now()
|
||||
var finish func(error)
|
||||
if ctrl.observer != nil {
|
||||
parent := ctrl.observer.Extract(ctx.UserContext(), ctx.Get("traceparent"), ctx.Get("tracestate"))
|
||||
observed, end := ctrl.observer.Start(parent, "http.request", "server")
|
||||
ctx.SetUserContext(observed)
|
||||
finish = end
|
||||
}
|
||||
ctrl.metrics.active.Inc()
|
||||
defer ctrl.metrics.active.Dec()
|
||||
err := ctx.Next()
|
||||
if err != nil {
|
||||
err = ctrl.handleErr(ctx, err)
|
||||
}
|
||||
ctrl.logRequest(ctx, time.Since(started))
|
||||
if ctrl.observer != nil {
|
||||
route := "unmatched"
|
||||
if ctx.Route() != nil {
|
||||
route = ctx.Route().Path
|
||||
}
|
||||
ctrl.observer.HTTP(ctx.UserContext(), ctx.Method(), route, ctx.Response().StatusCode(), time.Since(started), ctx.GetRespHeader(headerRequestID))
|
||||
finish(err)
|
||||
} else if ctx.Path() != "/metrics" {
|
||||
ctrl.metrics.observe(ctx, time.Since(started))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// logRequest logs request metadata without including message contents.
|
||||
func (ctrl *Controller) logRequest(ctx *fiber.Ctx, elapsed time.Duration) {
|
||||
route := "unmatched"
|
||||
if ctx.Route() != nil {
|
||||
route = ctx.Route().Path
|
||||
}
|
||||
ctrl.log.Info("http request",
|
||||
zap.String("method", ctx.Method()),
|
||||
zap.String("route", route),
|
||||
zap.Int("status", ctx.Response().StatusCode()),
|
||||
zap.String("request_id", ctx.GetRespHeader(headerRequestID)),
|
||||
zap.Duration("duration", elapsed),
|
||||
)
|
||||
}
|
||||
|
||||
// admit reserves global budgets and bounds downstream request work.
|
||||
func (ctrl *Controller) admit(ctx *fiber.Ctx) error {
|
||||
if ctrl.stopping.Load() {
|
||||
return errBusy
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(ctx.UserContext(), ctrl.cfg.Timeout())
|
||||
ctx.SetUserContext(requestCtx)
|
||||
release, err := ctrl.admission.Enter(requestCtx, requestGroup(ctx), "")
|
||||
if err != nil {
|
||||
cancel()
|
||||
return admissionError(ctx, err)
|
||||
}
|
||||
defer finishRequest(ctx, func() {
|
||||
release()
|
||||
cancel()
|
||||
})
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
// requireIdentity resolves the session before reserving per-user budgets.
|
||||
func (ctrl *Controller) requireIdentity(ctx *fiber.Ctx) error {
|
||||
user, err := ctrl.auth.Authenticate(ctx.UserContext(), bearer(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx.Locals(identityKey, user)
|
||||
release, err := ctrl.admission.Enter(ctx.UserContext(), requestGroup(ctx), user)
|
||||
if err != nil {
|
||||
return admissionError(ctx, err)
|
||||
}
|
||||
defer finishRequest(ctx, release)
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
// admissionError maps policy rejection and backend failure into HTTP-owned errors.
|
||||
func admissionError(ctx *fiber.Ctx, err error) error {
|
||||
ctx.Set(fiber.HeaderRetryAfter, strconv.Itoa(retryAfterSeconds))
|
||||
if errors.Is(err, admission.ErrRate) {
|
||||
return errRateLimited
|
||||
}
|
||||
return errBusy
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
)
|
||||
|
||||
// TestController_InFlightAdmission checks rejection, recovery and health exemption independently.
|
||||
func TestController_InFlightAdmission(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
release bool
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{"Negative: occupied execution slot", false, "/api/v1/users/me", http.StatusServiceUnavailable},
|
||||
{"Positive: released execution slot", true, "/api/v1/users/me", http.StatusUnauthorized},
|
||||
{"Positive: health bypasses occupied slot", false, "/health/live", http.StatusOK},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.MaxInFlight = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Acquire() {
|
||||
t.Fatal("fixture could not reserve slot")
|
||||
}
|
||||
if tc.release {
|
||||
ctrl.admission.(*fixtureAdmission).Release()
|
||||
} else {
|
||||
t.Cleanup(ctrl.admission.(*fixtureAdmission).Release)
|
||||
}
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_RateAdmission checks exhausted tokens without timing-dependent HTTP setup.
|
||||
func TestController_RateAdmission(t *testing.T) {
|
||||
t.Run("/api/v1/users/me", func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 1
|
||||
cfg.HTTP.Admission.Burst = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
|
||||
t.Fatal("fixture token missing")
|
||||
}
|
||||
expected := http.StatusTooManyRequests
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, expected, body)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("/health/ready", func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.Admission.RequestsPerSecond = 1
|
||||
cfg.HTTP.Admission.Burst = 1
|
||||
})
|
||||
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
|
||||
t.Fatal("fixture token missing")
|
||||
}
|
||||
expected := http.StatusOK
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, expected, body)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// TestController_Draining checks each endpoint's admission policy during shutdown.
|
||||
func TestController_Draining(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
status int
|
||||
}{
|
||||
{"Negative: readiness disabled", "/health/ready", http.StatusServiceUnavailable},
|
||||
{"Positive: liveness remains available", "/health/live", http.StatusOK},
|
||||
{"Negative: business requests rejected", "/api/v1/users/me", http.StatusServiceUnavailable},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
ctrl.stopping.Store(true)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_UnknownRoute checks the public fallback for an unmatched path.
|
||||
func TestController_UnknownRoute(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/missing", "", nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusNotFound, body)
|
||||
assertErrorCode(t, body, "not_found")
|
||||
}
|
||||
|
||||
// TestController_New rejects each missing dependency independently.
|
||||
func TestController_New(t *testing.T) {
|
||||
t.Run("Negative: missing configuration", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, nil, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing logger", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(nil, &fixture.cfg, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing service", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, nil, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing registry", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, nil, fixture.admission, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing limiter", func(t *testing.T) {
|
||||
// Arrange.
|
||||
fixture := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, fixture.errorRegistry, nil, fixture.auth, fixture.readiness)
|
||||
|
||||
// Assert.
|
||||
if err == nil || ctrl != nil {
|
||||
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HTTPObserver consumes only safe transport metadata and W3C context.
|
||||
type HTTPObserver interface {
|
||||
// Start begins a server operation and returns its completion callback.
|
||||
Start(context.Context, string, string) (context.Context, func(error))
|
||||
// Extract restores the upstream W3C parent without baggage.
|
||||
Extract(context.Context, string, string) context.Context
|
||||
// HTTP observes the completed response using a route template.
|
||||
HTTP(context.Context, string, string, int, time.Duration, string)
|
||||
}
|
||||
|
||||
// WithObserver installs optional instrumentation before the HTTP listener starts.
|
||||
func (ctrl *Controller) WithObserver(observer HTTPObserver) *Controller {
|
||||
ctrl.observer = observer
|
||||
return ctrl
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
var (
|
||||
errBusy = publicFailure(codeUnavailable, "server is busy")
|
||||
errRateLimited = publicFailure(codeRateLimited, "request rate exceeded")
|
||||
errTooLarge = publicFailure(codeTooLarge, "request body is too large")
|
||||
errMedia = publicFailure(codeMedia, "expected application/json")
|
||||
errInternal = publicFailure(codeInternal, "internal server error")
|
||||
)
|
||||
|
||||
// publicFailure creates a transport-owned error with a safe API message.
|
||||
func publicFailure(code, message string) error {
|
||||
return fielderr.WithStatus(errors.New(message), fielderr.NewStatusCode(code), message)
|
||||
}
|
||||
|
||||
// publicError maps application failures into the public API envelope.
|
||||
// Unknown errors receive a fixed response without exposing their details.
|
||||
func publicError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrTooLarge):
|
||||
return errTooLarge
|
||||
case errors.Is(err, service.ErrMedia):
|
||||
return errMedia
|
||||
case errors.Is(err, service.ErrUnavailable):
|
||||
return publicFailure(codeUnavailable, "dependency unavailable")
|
||||
case errors.Is(err, service.ErrInvalid):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeInvalid), "invalid request")
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnauthorized), "unknown user identity")
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeNotFound), "resource not found")
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeConflict), "username already exists")
|
||||
case errors.Is(err, service.ErrCapacity):
|
||||
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnavailable), "in-memory storage capacity reached")
|
||||
case errors.Is(err, errBusy):
|
||||
return errBusy
|
||||
case errors.Is(err, errRateLimited):
|
||||
return errRateLimited
|
||||
case errors.Is(err, errTooLarge):
|
||||
return errTooLarge
|
||||
case errors.Is(err, errMedia):
|
||||
return errMedia
|
||||
default:
|
||||
return errInternal
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"go.lab260.ru/fielderr"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// TestPublicErrorSafety maps wrapped application failures without exposing internal details.
|
||||
func TestPublicErrorSafety(t *testing.T) {
|
||||
t.Run("wrapped application error", func(t *testing.T) {
|
||||
err := publicError(fmt.Errorf("private database detail: %w", service.ErrConflict))
|
||||
response := errorResponse(err, "request")
|
||||
if response.Error.Code != codeConflict || response.Error.Message != "username already exists" {
|
||||
t.Fatalf("unexpected response: %+v", response)
|
||||
}
|
||||
})
|
||||
t.Run("unknown error", func(t *testing.T) {
|
||||
err := publicError(errors.New("private database detail"))
|
||||
if err != errInternal {
|
||||
t.Fatalf("unexpected public error: %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("foreign public status", func(t *testing.T) {
|
||||
err := fielderr.WithStatus(errors.New("private detail"), fielderr.NewStatusCode(codeInvalid), "private detail")
|
||||
if publicError(err) != errInternal {
|
||||
t.Fatal("untrusted error metadata reached the public response")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestPublicErrorUnavailable keeps dependency details out of the public envelope.
|
||||
func TestPublicErrorUnavailable(t *testing.T) {
|
||||
err := publicError(fmt.Errorf("private database detail: %w", service.ErrUnavailable))
|
||||
response := errorResponse(err, "request")
|
||||
if response.Error.Code != codeUnavailable || response.Error.Message != "dependency unavailable" {
|
||||
t.Fatalf("unexpected response: %+v", response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package fiber
|
||||
|
||||
// initRoutes registers health endpoints and authenticated application routes.
|
||||
func (ctrl *Controller) initRoutes() {
|
||||
ctrl.server.Get("/metrics", ctrl.handleMetrics)
|
||||
ctrl.server.Get("/health/live", ctrl.handleLive)
|
||||
ctrl.server.Get("/health/ready", ctrl.handleReady)
|
||||
ctrl.server.Use(ctrl.admit)
|
||||
ctrl.server.Post("/api/v1/users", ctrl.HandleUsersCreate)
|
||||
|
||||
ctrl.server.Post("/api/v1/auth/sessions", ctrl.HandleLogin)
|
||||
|
||||
api := ctrl.server.Group("/api/v1", ctrl.requireIdentity)
|
||||
api.Delete("/auth/sessions/current", ctrl.HandleLogout)
|
||||
api.Get("/users/me", ctrl.HandleUsersGetMe)
|
||||
api.Post("/chats", ctrl.HandleChatsCreate)
|
||||
api.Get("/chats", ctrl.HandleChatsGetPage)
|
||||
api.Get("/chats/:chat_id", ctrl.HandleChatsGetByID)
|
||||
api.Post("/chats/:chat_id/attachments", ctrl.handleUpload)
|
||||
api.Get("/attachments/:id", ctrl.handleAttachment)
|
||||
api.Get("/attachments/:id/content", ctrl.handleContent)
|
||||
api.Post("/chats/:chat_id/messages", ctrl.HandleMessagesCreate)
|
||||
api.Get("/chats/:chat_id/messages", ctrl.HandleMessagesGetPage)
|
||||
|
||||
ctrl.server.Use(ctrl.handleNotFound)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type responseStream struct {
|
||||
io.Reader
|
||||
cleanup func()
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// Close releases request budgets after fasthttp finishes transmitting the stream.
|
||||
func (s *responseStream) Close() error {
|
||||
var err error
|
||||
s.once.Do(func() {
|
||||
if closer, ok := s.Reader.(io.Closer); ok {
|
||||
err = closer.Close()
|
||||
}
|
||||
s.cleanup()
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// finishRequest keeps deadlines and admission leases alive until streamed responses close.
|
||||
func finishRequest(ctx *fiber.Ctx, cleanup func()) {
|
||||
stream, ok := ctx.Response().BodyStream().(*responseStream)
|
||||
if !ok {
|
||||
cleanup()
|
||||
return
|
||||
}
|
||||
previous := stream.cleanup
|
||||
stream.cleanup = func() {
|
||||
previous()
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestController_UsersCreate checks one registration contract scenario per subtest.
|
||||
func TestController_UsersCreate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{"Positive: valid Unicode display name", `{"password":"fixture-password-123","username":"alice","display_name":"Алиса 👋"}`, http.StatusCreated},
|
||||
{"Positive: display name at rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 100) + `"}`, http.StatusCreated},
|
||||
{"Negative: display name exceeds rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 101) + `"}`, http.StatusBadRequest},
|
||||
{"Negative: uppercase username", `{"password":"fixture-password-123","username":"Alice","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: malformed JSON", `{`, http.StatusBadRequest},
|
||||
{"Negative: null root", `null`, http.StatusBadRequest},
|
||||
{"Negative: array root", `[]`, http.StatusBadRequest},
|
||||
{"Negative: missing fields", `{}`, http.StatusBadRequest},
|
||||
{"Negative: null field", `{"password":"fixture-password-123","username":"alice","display_name":null}`, http.StatusBadRequest},
|
||||
{"Negative: wrong field type", `{"password":"fixture-password-123","username":5,"display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: unknown field", `{"password":"fixture-password-123","username":"alice","display_name":"Alice","unknown":"secret"}`, http.StatusBadRequest},
|
||||
{"Negative: field name case", `{"password":"fixture-password-123","Username":"alice","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: duplicate field", `{"password":"fixture-password-123","username":"alice","username":"bob","display_name":"Alice"}`, http.StatusBadRequest},
|
||||
{"Negative: trailing object", `{"password":"fixture-password-123","username":"alice","display_name":"Alice"} {}`, http.StatusBadRequest},
|
||||
{"Negative: invalid UTF-8", "{\"username\":\"alice\",\"display_name\":\"\xff\"}", http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodPost, "/api/v1/users", "", []byte(tc.body))
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, tc.status, body)
|
||||
if tc.status == http.StatusBadRequest {
|
||||
assertErrorCode(t, body, "invalid_request")
|
||||
return
|
||||
}
|
||||
if body["username"] != "alice" || body["display_name"] == "" {
|
||||
t.Fatalf("registration fields changed: %v", body)
|
||||
}
|
||||
if _, err := uuid.Parse(body["id"].(string)); err != nil {
|
||||
t.Fatalf("invalid assigned ID: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestController_UsersGetMe verifies profile selection and authentication failures.
|
||||
func TestController_UsersGetMe(t *testing.T) {
|
||||
t.Run("Positive: own profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
actor := user(t, ctrl)
|
||||
identity := actor
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusOK, body)
|
||||
if body["id"] != actor || body["display_name"] != "Алиса 👋" {
|
||||
t.Fatalf("wrong profile: %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
identity := ""
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, nil)
|
||||
identity := uuid.NewString()
|
||||
|
||||
// Act.
|
||||
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
|
||||
assertErrorCode(t, body, "unauthorized")
|
||||
})
|
||||
}
|
||||
|
||||
// assertHTTPStatus reports the response body alongside a mismatched status.
|
||||
func assertHTTPStatus(t *testing.T, got, want int, body map[string]any) {
|
||||
t.Helper()
|
||||
if got != want {
|
||||
t.Fatalf("status=%d, want=%d, body=%v", got, want, body)
|
||||
}
|
||||
}
|
||||
|
||||
// assertErrorCode checks the documented error classification independently of status.
|
||||
func assertErrorCode(t *testing.T, body map[string]any, want string) {
|
||||
t.Helper()
|
||||
envelope, ok := body["error"].(map[string]any)
|
||||
if !ok || envelope["code"] != want {
|
||||
t.Fatalf("error=%v, want code %q", body, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Package controller connects transport lifecycles to Fx.
|
||||
package controller
|
||||
|
||||
import "context"
|
||||
|
||||
// Controller is a process-owned transport server.
|
||||
type Controller interface {
|
||||
// Start acquires the listener and reports startup errors to the lifecycle owner.
|
||||
Start(context.Context) error
|
||||
// Stop stops accepting work and drains active requests within the supplied deadline.
|
||||
Stop(context.Context) error
|
||||
}
|
||||
Reference in New Issue
Block a user