feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

+18
View File
@@ -12,6 +12,7 @@ import (
"errors"
"io"
"log"
"log/slog"
"mime"
"net/http"
"os"
@@ -45,6 +46,7 @@ type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) er
type fixtureHandler struct {
token string
revoke membershipRevoker
notices *noticeFixture
requests atomic.Uint32
}
@@ -98,6 +100,20 @@ func serve() error {
revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error {
return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID)
},
notices: newNoticeFixture(
postgres.NewTransactor(pool),
postgres.NewEventConsumerStore(pool, requestTimeout),
func(ctx context.Context, recipientID, organizationID uuid.UUID) error {
return postgres.CheckNotificationFixtureScope(ctx, pool, recipientID, organizationID)
},
func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error) {
return postgres.NotificationFixtureEvent(ctx, pool, eventID)
},
func(ctx context.Context, recipientID, organizationID uuid.UUID) error {
return postgres.HideNotificationFixtureOrganization(ctx, pool, recipientID, organizationID)
},
slog.New(slog.DiscardHandler),
),
},
ReadHeaderTimeout: readHeaderTimeout,
ReadTimeout: readTimeout,
@@ -142,6 +158,8 @@ func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
handler.serveHealthcheck(w, r)
case fixtureEndpoint:
handler.serveMembershipRevocation(w, r)
case noticeEndpoint, noticeReplayEndpoint, noticeHideEndpoint:
handler.serveNotice(w, r)
default:
w.WriteHeader(http.StatusNotFound)
}
@@ -0,0 +1,232 @@
//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 &noticeFixture{
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)
}
@@ -0,0 +1,86 @@
//go:build e2e
package main
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/port/outbound"
)
func TestNoticeEndpointsNeedTheBearerAndDecodeStrictly(t *testing.T) {
recipientID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New()
var published, hidden int
handler := &fixtureHandler{
token: strings.Repeat("ab", 32),
notices: &noticeFixture{
publish: func(_ context.Context, gotRecipient, gotOrganization uuid.UUID) (uuid.UUID, error) {
published++
if gotRecipient != recipientID || gotOrganization != organizationID {
t.Fatalf("publish IDs = %s/%s, want %s/%s", gotRecipient, gotOrganization, recipientID, organizationID)
}
return eventID, nil
},
replay: func(_ context.Context, got uuid.UUID) (noticeReplayResult, error) {
if got != eventID {
t.Fatalf("replay event = %s, want %s", got, eventID)
}
return noticeReplayResult{RenamedApplied: true}, nil
},
hide: func(context.Context, uuid.UUID, uuid.UUID) error {
hidden++
return postgres.ErrCompanyFixtureScope
},
},
}
bearer := "Bearer " + handler.token
body := `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `"}`
if response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json"); response.Code != http.StatusUnauthorized || published != 0 {
t.Fatalf("unauthorized publish = %d, published %d", response.Code, published)
}
response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, bearer, "application/json")
var created struct {
EventID uuid.UUID `json:"event_id"`
}
if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &created) != nil || created.EventID != eventID {
t.Fatalf("publish = %d %s, want 201 with the event ID", response.Code, response.Body.String())
}
replay := fixtureRequest(handler, http.MethodPost, noticeReplayEndpoint, `{"event_id":"`+eventID.String()+`"}`, bearer, "application/json")
var result noticeReplayResult
if replay.Code != http.StatusOK || json.Unmarshal(replay.Body.Bytes(), &result) != nil || result.PrimaryApplied || !result.RenamedApplied {
t.Fatalf("replay = %d %s, want 200 with a duplicate for the primary consumer", replay.Code, replay.Body.String())
}
if hide := fixtureRequest(handler, http.MethodPost, noticeHideEndpoint, body, bearer, "application/json"); hide.Code != http.StatusNotFound || hidden != 1 {
t.Fatalf("hide outside the fixture scope = %d, want 404", hide.Code)
}
for name, test := range map[string]struct {
path, body string
want int
}{
"unknown field": {noticeEndpoint, `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `","email":"x"}`, http.StatusBadRequest},
"bad recipient": {noticeEndpoint, `{"recipient_user_id":"x","organization_id":"` + organizationID.String() + `"}`, http.StatusBadRequest},
"nil event": {noticeReplayEndpoint, `{"event_id":"` + uuid.Nil.String() + `"}`, http.StatusBadRequest},
"trailing content": {noticeEndpoint, body + " {}", http.StatusBadRequest},
} {
if got := fixtureRequest(handler, http.MethodPost, test.path, test.body, bearer, "application/json"); got.Code != test.want {
t.Errorf("%s = %d, want %d", name, got.Code, test.want)
}
}
if got := fixtureRequest(handler, http.MethodGet, noticeEndpoint, "", bearer, ""); got.Code != http.StatusMethodNotAllowed {
t.Errorf("GET = %d, want 405", got.Code)
}
if statusForNoticeError(outbound.ErrOrganizationNotFound) != http.StatusNotFound {
t.Error("an unknown organization must answer 404")
}
if got := fixtureRequest(&fixtureHandler{token: handler.token}, http.MethodPost, noticeEndpoint, body, bearer, "application/json"); got.Code != http.StatusNotFound {
t.Errorf("a handler without notices = %d, want 404", got.Code)
}
}
+29
View File
@@ -0,0 +1,29 @@
// Command policy-publish adds the demo matching section to the product
// policy of a stand. It publishes a new immutable version and changes nothing
// else.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"lincodex/backend/internal/adapter/primary/cli/policypublish"
)
func main() {
os.Exit(run())
}
func run() int {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := policypublish.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "policy-publish: %v\n", err)
return 2
}
return 0
}
+4 -3
View File
@@ -315,8 +315,9 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (
}
// The isolated browser fixture opts into the extended demo policy explicitly,
// including the manual-review band thresholds. Normal startup still seeds V1,
// and an operator's policy must never be replaced.
// including the manual-review band thresholds and the matching coefficients.
// Normal startup still seeds V1, and an operator's policy must never be
// replaced.
func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
@@ -345,7 +346,7 @@ func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (
}
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV3(),
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV4(),
})
return err
})