233 lines
7.8 KiB
Go
233 lines
7.8 KiB
Go
//go:build e2e
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/notification"
|
|
)
|
|
|
|
// The notification endpoints share the process, the bearer token, and the
|
|
// isolated database of the membership fixture. They let the browser suite
|
|
// put a synthetic event into the real outbox, so the relay, the event bus,
|
|
// and the inbox consumer deliver it, and then replay it the way an
|
|
// at-least-once bus does.
|
|
const (
|
|
noticeEndpoint = "/notifications/synthetic"
|
|
noticeReplayEndpoint = "/notifications/synthetic/replay"
|
|
noticeHideEndpoint = "/notifications/synthetic/hide-organization"
|
|
renamedInboxConsumer = "notification_inbox_replayed"
|
|
noticeConsumerTimeout = requestTimeout
|
|
)
|
|
|
|
// noticeFixture is the data access of the notification endpoints.
|
|
type noticeFixture struct {
|
|
// publish appends one synthetic event to the outbox and returns its ID.
|
|
publish func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error)
|
|
// replay delivers the event again to the inbox consumer and to a consumer
|
|
// of another name. It reports whether each delivery stored a new row
|
|
// claim, which is false for a duplicate.
|
|
replay func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error)
|
|
// hide records that the recipient hides the organization.
|
|
hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error
|
|
}
|
|
|
|
type noticeReplayResult struct {
|
|
// PrimaryApplied is true when the inbox consumer had not processed the
|
|
// event yet. The browser suite waits for the real consumer first, so it
|
|
// expects false.
|
|
PrimaryApplied bool `json:"primary_applied"`
|
|
// RenamedApplied is true for a consumer without a marker for the event;
|
|
// the inbox key must still keep one row.
|
|
RenamedApplied bool `json:"renamed_applied"`
|
|
}
|
|
|
|
type noticeRequest struct {
|
|
RecipientUserID string `json:"recipient_user_id"`
|
|
OrganizationID string `json:"organization_id"`
|
|
EventID string `json:"event_id"`
|
|
}
|
|
|
|
func newNoticeFixture(
|
|
transactor outbound.Transactor,
|
|
store outbound.EventConsumerStore,
|
|
check func(ctx context.Context, recipientID, organizationID uuid.UUID) error,
|
|
readEvent func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error),
|
|
hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error,
|
|
logger *slog.Logger,
|
|
) *noticeFixture {
|
|
inbox := notification.NewInboxHandler(logger, true)
|
|
return ¬iceFixture{
|
|
publish: func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error) {
|
|
if err := check(ctx, recipientID, organizationID); err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID)
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
|
EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1,
|
|
AggregateType: notification.SyntheticNoticeAggregateType, AggregateID: uuid.New(),
|
|
AggregateVersion: notification.SyntheticNoticeAggregateVersion, Payload: payload,
|
|
})
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return unit.Outbox().Append(ctx, event)
|
|
})
|
|
return event.EventID(), err
|
|
},
|
|
replay: func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error) {
|
|
event, err := readEvent(ctx, eventID)
|
|
if err != nil {
|
|
return noticeReplayResult{}, err
|
|
}
|
|
apply := func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return inbox.Handle(ctx, unit, event)
|
|
}
|
|
var result noticeReplayResult
|
|
if result.PrimaryApplied, err = store.ApplyOnce(ctx, notification.InboxConsumerName, event.EventID, apply); err != nil {
|
|
return noticeReplayResult{}, err
|
|
}
|
|
if result.RenamedApplied, err = store.ApplyOnce(ctx, renamedInboxConsumer, event.EventID, apply); err != nil {
|
|
return noticeReplayResult{}, err
|
|
}
|
|
return result, nil
|
|
},
|
|
hide: hide,
|
|
}
|
|
}
|
|
|
|
func (handler *fixtureHandler) serveNotice(w http.ResponseWriter, r *http.Request) {
|
|
if handler.notices == nil {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
if !handler.admit(w, r) {
|
|
return
|
|
}
|
|
request, status := decodeNoticeRequest(w, r)
|
|
if status != 0 {
|
|
w.WriteHeader(status)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), noticeConsumerTimeout)
|
|
defer cancel()
|
|
switch r.URL.Path {
|
|
case noticeEndpoint:
|
|
recipientID, organizationID, ok := noticeIdentities(request)
|
|
if !ok {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
eventID, err := handler.notices.publish(ctx, recipientID, organizationID)
|
|
if err != nil {
|
|
w.WriteHeader(statusForNoticeError(err))
|
|
return
|
|
}
|
|
writeNoticeJSON(w, http.StatusCreated, map[string]string{"event_id": eventID.String()})
|
|
case noticeReplayEndpoint:
|
|
eventID, err := uuid.Parse(request.EventID)
|
|
if err != nil || eventID == uuid.Nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
result, err := handler.notices.replay(ctx, eventID)
|
|
if err != nil {
|
|
w.WriteHeader(statusForNoticeError(err))
|
|
return
|
|
}
|
|
writeNoticeJSON(w, http.StatusOK, result)
|
|
case noticeHideEndpoint:
|
|
recipientID, organizationID, ok := noticeIdentities(request)
|
|
if !ok {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := handler.notices.hide(ctx, recipientID, organizationID); err != nil {
|
|
w.WriteHeader(statusForNoticeError(err))
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
default:
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}
|
|
|
|
// admit applies the checks that every mutating fixture request passes: the
|
|
// method, the request budget, the bearer token, and the JSON media type.
|
|
func (handler *fixtureHandler) admit(w http.ResponseWriter, r *http.Request) bool {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return false
|
|
}
|
|
if handler.requests.Add(1) > maxFixtureRequests {
|
|
w.WriteHeader(http.StatusTooManyRequests)
|
|
return false
|
|
}
|
|
if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return false
|
|
}
|
|
if !isJSONRequest(r) {
|
|
w.WriteHeader(http.StatusUnsupportedMediaType)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func decodeNoticeRequest(w http.ResponseWriter, r *http.Request) (noticeRequest, int) {
|
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody))
|
|
decoder.DisallowUnknownFields()
|
|
var request noticeRequest
|
|
if err := decoder.Decode(&request); err != nil {
|
|
return noticeRequest{}, statusForDecodeError(err)
|
|
}
|
|
var trailing any
|
|
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
|
return noticeRequest{}, statusForDecodeError(err)
|
|
}
|
|
return request, 0
|
|
}
|
|
|
|
func noticeIdentities(request noticeRequest) (recipientID, organizationID uuid.UUID, ok bool) {
|
|
recipientID, recipientErr := uuid.Parse(request.RecipientUserID)
|
|
organizationID, organizationErr := uuid.Parse(request.OrganizationID)
|
|
return recipientID, organizationID, recipientErr == nil && organizationErr == nil &&
|
|
recipientID != uuid.Nil && organizationID != uuid.Nil
|
|
}
|
|
|
|
func statusForNoticeError(err error) int {
|
|
switch {
|
|
case errors.Is(err, postgres.ErrCompanyFixtureScope),
|
|
errors.Is(err, outbound.ErrUserNotFound),
|
|
errors.Is(err, outbound.ErrOrganizationNotFound),
|
|
errors.Is(err, outbound.ErrNotificationInboxEntryNotFound):
|
|
return http.StatusNotFound
|
|
case errors.Is(err, outbound.ErrTransactionConflict):
|
|
return http.StatusConflict
|
|
default:
|
|
return http.StatusInternalServerError
|
|
}
|
|
}
|
|
|
|
func writeNoticeJSON(w http.ResponseWriter, status int, body any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|