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

+8
View File
@@ -57,6 +57,14 @@ assessment-category-attest-build: ## Build the local category attestation operat
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest
.PHONY: policy-publish policy-publish-build
policy-publish: ## Add the demo matching section to the product policy (set ARGS)
$(GO) run ./cmd/policy-publish $(ARGS)
policy-publish-build: ## Build the local policy publication operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish
.PHONY: deps install install-tools
deps: ## Download pinned Go module dependencies
$(GO) mod download
+17
View File
@@ -118,4 +118,21 @@ A confirmed real assessment result leaves one fact of skill evidence per attempt
The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, query `ListCandidateEvidenceFacts`); an employer reads the permitted projection at `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, which runs the checks of the card read (`candidateview.Service.AuthorizeCategoriesSection`: membership, effective C2 publication, hiding, minimum cohort, quota, access audit) and then the statement `ListOrganizationVisibleEvidence` (effective publication view, `NOT EXISTS` over the hidden organizations, the `categories` field, visible measurements, one fact for each category of the card that supports its confirmed grade, an allowlist of six columns: skill, grade, trust, basis, calibration, year). The preview of the candidate (`GetMyCardPreview`) shows the same section through `ListCandidatePreviewEvidence`. The reads touch only the two evidence tables; `backend/db/evidence_queries_test.go` fails when an evidence query names a result, attempt, answer, signal, or review table. The facts, the tags, and the rules are described in [architecture](../docs/en/ARCHITECTURE.md#skill-evidence). The integration test `TestSkillEvidenceOverHTTP` runs against a real PostgreSQL and covers the fact tied to its result with trust 1, two more tags on one event, an express run and a failed attempt, paging, the organization projection with C2 granted and revoked, a hidden organization, a hidden fact, a card without categories, tags that can join a fact only in its creating transaction, the erasure of an account with facts through both cascade paths, the refusal to roll the migration back while a fact is hidden, and the rebuild after the migration is rolled back and applied again.
## Match search
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand).
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
The integration test `TestMatchSearchOverHTTP` runs against a real PostgreSQL through the real router, the profile, consent, publication, need, organization, and assessment operations: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, one handle confirmed in Backend and unconfirmed in Networks, a profile published without a grade and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the access denials, and the policy without the section. The browser fixture `questionnaire-fixture` publishes `DemoProductPolicyV4`, so a local stand has the matching section.
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
## Internal notifications
The inbox stores a reference to a delivered event for one recipient (`notification_inbox_events`, migrations 32 and 36), never its text. The consumer `notification_inbox` (`usecase/notification/inbox_handler.go`) writes the row in the transaction of its dedup marker; the key `(recipient_user_id, event_id)` keeps one row per recipient and event, and an event ID that returns with other metadata is rejected. The row exists whether or not an email was sent, and nothing in the handler reads mail state.
The text is resolved when the list is read (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` authorizes the cabinet in the read transaction (a verified candidate for `GET /api/v1/me/notifications`; a verified employer with an active membership for `GET /api/v1/organizations/{org_id}/notifications`), then asks the resolver of each item's source type for the content that the recipient may see now. A source that is gone or hidden leaves the item in the list without content. The mark (`POST .../{notification_id}/read`) keeps the first read time and reads no source. A foreign, cross-organization, or unknown item answers 404.
A producer appends an `invitation.delivered` event with the payload `recipient_user_id` and `organization_id` and registers a resolver for its source; the synthetic `notification.synthetic_delivered` event exercises the path and has no product meaning. The contract is in [docs/en/ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#internal-notifications) and [api/README.en.md](../api/README.en.md#notifications); no invitation produces an event yet.
+16
View File
@@ -118,4 +118,20 @@
Кандидат читает факты через `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, запрос `ListCandidateEvidenceFacts`); работодатель читает разрешенную проекцию через `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, которая выполняет проверки чтения карточки (`candidateview.Service.AuthorizeCategoriesSection`: членство, действующая публикация с C2, скрытие, минимальная когорта, квота, аудит доступа), а затем запрос `ListOrganizationVisibleEvidence` (представление действующих публикаций, `NOT EXISTS` по скрытым организациям, поле `categories`, видимые измерения, по одному факту на каждую категорию карточки, подтверждающему ее грейд, белый список из шести колонок: навык, грейд, доверие, основание, калибровка, год). Предпросмотр кандидата (`GetMyCardPreview`) показывает тот же раздел через `ListCandidatePreviewEvidence`. Чтения трогают только две таблицы доказательств; `backend/db/evidence_queries_test.go` падает, если запрос доказательств называет таблицу результатов, попыток, ответов, сигналов или проверок. Факты, теги и правила описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#доказательства-навыков). Интеграционный тест `TestSkillEvidenceOverHTTP` выполняется на настоящем PostgreSQL и проверяет: факт, связанный с результатом, с доверием 1, два дополнительных тега одного события, экспресс-прогон и проваленная попытка, постраничное чтение, проекция организации при выданном и отозванном C2, скрытая организация, скрытый факт, карточка без категорий теги, которые могут присоединиться к факту только в создавшей его транзакции, удаление аккаунта с фактами по обоим каскадным путям, отказ откатывать миграцию, пока есть скрытый факт, и перестроение после отката и повторного применения миграции.
## Подбор
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде).
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
Интеграционный тест `TestMatchSearchOverHTTP` работает на настоящем PostgreSQL через настоящий маршрутизатор и операции профиля, согласий, публикации, потребностей, организаций и оценки: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, один handle подтвержден по Backend и не подтвержден по сетям, профиль без грейда, опубликованный и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, отказы доступа и политика без раздела. Браузерный стенд `questionnaire-fixture` публикует `DemoProductPolicyV4`, поэтому локальный стенд имеет раздел подбора.
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
## Внутренние уведомления
Inbox хранит ссылку на доставленное событие для одного получателя (`notification_inbox_events`, миграции 32 и 36), но не его текст. Обработчик `notification_inbox` (`usecase/notification/inbox_handler.go`) пишет строку в транзакции своего dedup-маркера; ключ `(recipient_user_id, event_id)` держит одну строку на получателя и событие, а ID события, пришедший снова с другими метаданными, отклоняется. Строка существует независимо от того, отправлено ли письмо, и обработчик не читает состояние почты.
Текст вычисляется при чтении списка (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` проверяет кабинет в транзакции чтения (подтвержденный кандидат для `GET /api/v1/me/notifications`; подтвержденный работодатель с активным членством для `GET /api/v1/organizations/{org_id}/notifications`), затем просит преобразователь типа источника каждого элемента дать содержимое, которое получатель вправе видеть сейчас. Исчезнувший или скрытый источник оставляет элемент в списке без содержимого. Отметка (`POST .../{notification_id}/read`) сохраняет первое время прочтения и не читает источник. Чужой элемент, элемент другой организации и неизвестный элемент дают 404.
Источник добавляет событие `invitation.delivered` с payload `recipient_user_id` и `organization_id` и регистрирует преобразователь для своего источника; синтетическое событие `notification.synthetic_delivered` проверяет путь и продуктового смысла не имеет. Контракт описан в [docs/ru/ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#внутренние-уведомления) и [api/README.md](../api/README.md#уведомления); пока ни одно приглашение не создает событие.
+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
})
+7
View File
@@ -63,6 +63,10 @@ type Config struct {
// ConsumerEnabled runs the registered event consumers next to the HTTP
// servers.
ConsumerEnabled bool
// NotificationSyntheticEnabled lets the inbox consume and render the
// synthetic notification event. Off by default; a development or browser
// test stand turns it on.
NotificationSyntheticEnabled bool
// ConsumerGroupPrefix and a consumer name form the consumer group ID.
ConsumerGroupPrefix string
ConsumerMaxAttempts int
@@ -191,6 +195,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadConsumer(lookup); err != nil {
return Config{}, err
}
if err := config.loadNotification(lookup); err != nil {
return Config{}, err
}
if err := config.loadJobs(lookup); err != nil {
return Config{}, err
}
+12
View File
@@ -0,0 +1,12 @@
package config
// defaultNotificationSyntheticEnabled keeps the synthetic inbox event off:
// a production deployment neither consumes nor renders it. A development or
// browser-test stand turns it on.
const defaultNotificationSyntheticEnabled = false
func (config *Config) loadNotification(lookup LookupEnv) error {
var err error
config.NotificationSyntheticEnabled, err = boolOrDefault(lookup, "NOTIFICATION_SYNTHETIC_ENABLED", defaultNotificationSyntheticEnabled)
return err
}
+17
View File
@@ -0,0 +1,17 @@
package config
import "testing"
func TestLoadFromEnvReadsTheSyntheticNotificationSwitch(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(nil))
if err != nil || settings.NotificationSyntheticEnabled {
t.Fatalf("default = %t, %v, want off", settings.NotificationSyntheticEnabled, err)
}
settings, err = LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": " True "}))
if err != nil || !settings.NotificationSyntheticEnabled {
t.Fatalf("enabled = %t, %v, want on", settings.NotificationSyntheticEnabled, err)
}
if _, err := LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": "yes"})); err == nil {
t.Fatal("LoadFromEnv() accepted a value that is not true or false")
}
}
+41 -1
View File
@@ -12,7 +12,9 @@ import (
var (
evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`)
// evidenceReaders are the only queries that may name the evidence tables.
evidenceReaders = []string{"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence"}
evidenceReaders = []string{
"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence", "ListOrganizationVisibleEvidenceBatch",
}
// evidenceForbiddenSources are tables whose content must never reach the
// evidence reads: raw answers and items, results with their scores,
// attempts, signals, and the anti-cheat review band.
@@ -123,3 +125,41 @@ func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) {
t.Errorf("organization evidence query reads the publication table directly: %s", statement)
}
}
// The batch read repeats every barrier of the single organization read, and
// the match-search queries name no evidence table.
func TestOrganizationEvidenceBatchReadRepeatsTheVisibilityBarrier(t *testing.T) {
statements := evidenceStatements(t)
statement := statements["ListOrganizationVisibleEvidenceBatch"]
if statement == "" {
t.Fatal("the batch organization evidence query is missing")
}
for _, required := range []string{
"inner join candidate_effective_publications as effective",
"from candidate_hidden_organizations as hidden",
"not exists",
"hidden.organization_id = sqlc.arg(organization_id)",
"'categories' = any(effective.fields)",
"fact.visibility = 'visible'",
"fact.kind = 'measurement'",
"(skill.skill_code || '/' || fact.grade) = wanted.category",
} {
if !strings.Contains(statement, required) {
t.Errorf("batch organization evidence query lacks %q: %s", required, statement)
}
}
if strings.Contains(statement, "candidate_publications") && !strings.Contains(statement, "candidate_effective_publications") {
t.Errorf("batch organization evidence query reads the publication table directly: %s", statement)
}
for _, private := range []string{"fact.id,", "event_id", "result_id", "fact.visibility,", "occurred_at,"} {
selected := statement[len("select"):strings.Index(statement, " from (")]
if strings.Contains(selected, private) {
t.Errorf("batch organization evidence query selects %q: %s", private, selected)
}
}
for name, search := range statements {
if strings.HasPrefix(name, "CountReal") && evidenceTableName.MatchString(search) {
t.Errorf("%s names an evidence table: %s", name, search)
}
}
}
@@ -0,0 +1,48 @@
-- The inbox allowlist gains a synthetic event type. It carries no product
-- meaning: it lets the consumer, the read-time visibility check, the list,
-- and the read state run end to end before real producers exist. Each event
-- type is bound to the one source type its content is resolved from.
-- +goose Up
ALTER TABLE notification_inbox_events
DROP CONSTRAINT notification_inbox_events_type_known;
ALTER TABLE notification_inbox_events
ADD CONSTRAINT notification_inbox_events_type_known CHECK (
schema_version = 1
AND (
(event_type = 'invitation.delivered' AND source_type = 'invitation')
OR (
event_type = 'notification.synthetic_delivered'
AND source_type = 'organization'
)
)
);
-- A rollback must not silently lose or orphan recipient-visible history.
-- +goose Down
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM notification_inbox_events
WHERE event_type <> 'invitation.delivered'
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'notification_inbox_events_type_known',
TABLE = 'notification_inbox_events',
MESSAGE = 'synthetic notification inbox records must be resolved before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
ALTER TABLE notification_inbox_events
DROP CONSTRAINT notification_inbox_events_type_known;
ALTER TABLE notification_inbox_events
ADD CONSTRAINT notification_inbox_events_type_known CHECK (
event_type = 'invitation.delivered'
AND schema_version = 1
AND source_type = 'invitation'
);
+18
View File
@@ -0,0 +1,18 @@
-- Reads that only the match search needs. The visibility of the candidates and
-- their permitted evidence come from the card and evidence queries, which are
-- the single copy of those barriers; this file adds no candidate-facing read.
-- The number of candidates who hold each given category from a source that is
-- not a synthetic demonstration, which is the size of the comparable real
-- cohort that a percentile needs. It returns counts only, for the pairs the
-- caller passes as "specialization/grade", and no row for a pair nobody holds.
-- name: CountRealComparableCategories :many
SELECT
category.specialization,
category.grade,
count(*)::bigint AS candidates
FROM candidate_assessment_categories AS category
WHERE
category.source <> 'synthetic_demo'
AND (category.specialization || '/' || category.grade) = any(sqlc.arg(categories)::text [])
GROUP BY category.specialization, category.grade;
+14
View File
@@ -2,6 +2,20 @@
-- finally usage rows. The organization lock serializes quota decisions for
-- the tenant and makes the subsequent count and insert atomic.
-- Takes the organization lock ahead of every share lock of a reader that will
-- reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
-- SHARE, so readers of one organization queue up instead of deadlocking on a
-- share lock that each then tries to raise, but it does not conflict with the
-- FOR KEY SHARE that a foreign key takes, such as the hidden-organization
-- insert of a candidate, which holds the candidate's row and then needs this
-- one. The reservation itself still takes FOR UPDATE inside the same
-- transaction.
-- name: LockCompanyQuotaOrganizationFirst :one
SELECT id
FROM organizations
WHERE id = sqlc.arg(organization_id)
FOR NO KEY UPDATE;
-- name: LockCompanyQuotaOrganization :one
SELECT
id,
+45
View File
@@ -103,3 +103,48 @@ WHERE
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
-- The same organization read for a whole candidate set, so a search reads the
-- evidence of every listed candidate in one statement. The pairs come from the
-- caller as two parallel arrays, one row per candidate and category of the card
-- that was just projected. The statement repeats every barrier of the single
-- read: the effective publication view, NOT EXISTS over the candidates that
-- hide the organization, the categories field, and only visible measurements.
-- The candidate identifier is returned for the caller to group by and never
-- leaves the server; the other columns are the same allowlist.
-- name: ListOrganizationVisibleEvidenceBatch :many
SELECT DISTINCT ON (wanted.candidate_id, skill.skill_code)
wanted.candidate_id::uuid AS candidate_id,
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM (
SELECT
candidate_ids.candidate_id,
wanted_categories.category
FROM unnest(sqlc.arg(candidate_ids)::uuid []) WITH ORDINALITY AS candidate_ids (candidate_id, position)
INNER JOIN unnest(sqlc.arg(categories)::text []) WITH ORDINALITY AS wanted_categories (category, position)
ON candidate_ids.position = wanted_categories.position
) AS wanted
INNER JOIN candidate_effective_publications AS effective
ON wanted.candidate_id = effective.user_id
INNER JOIN skill_evidence_facts AS fact
ON effective.user_id = fact.candidate_id
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
'categories' = any(effective.fields)
AND (skill.skill_code || '/' || fact.grade) = wanted.category
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = effective.user_id
AND hidden.organization_id = sqlc.arg(organization_id)
)
ORDER BY wanted.candidate_id, skill.skill_code, fact.occurred_at, fact.id;
+39 -3
View File
@@ -69,13 +69,19 @@ WHERE recipient_user_id = sqlc.arg(recipient_user_id)
ORDER BY occurred_at DESC, event_id DESC
LIMIT sqlc.arg(page_limit);
-- Persist the first read time under exact recipient and organization scope.
-- Repeated calls preserve the original read timestamp.
-- Persist the first read time for the recipient, optionally under one exact
-- organization context. A missing organization is the candidate cabinet,
-- which spans the organizations that sent to it; the employer cabinet always
-- names its organization. Repeated calls preserve the original read
-- timestamp.
-- name: MarkNotificationInboxEventRead :one
UPDATE notification_inbox_events
SET read_at = COALESCE(read_at, sqlc.arg(read_at)::timestamptz)
WHERE recipient_user_id = sqlc.arg(recipient_user_id)
AND organization_id = sqlc.arg(organization_id)
AND (
sqlc.narg(organization_id)::uuid IS NULL
OR organization_id = sqlc.narg(organization_id)::uuid
)
AND event_id = sqlc.arg(event_id)
RETURNING
recipient_user_id,
@@ -87,3 +93,33 @@ RETURNING
source_id,
occurred_at,
read_at;
-- Resolve the sender organization of a synthetic notice under the recipient's
-- current standing, so the notice never outlives that standing. A candidate
-- sees the name only while the organization is not hidden from them; an
-- employer sees it only while they are an active member. No row means the
-- content is no longer visible to this recipient.
-- name: GetNotificationOrganizationNameForRecipient :one
SELECT organizations.name
FROM organizations
INNER JOIN users ON users.id = sqlc.arg(recipient_user_id)
WHERE organizations.id = sqlc.arg(organization_id)
AND (
(
users.scenario = 'candidate'
AND NOT EXISTS (
SELECT 1 FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = users.id
AND candidate_hidden_organizations.organization_id = organizations.id
)
)
OR (
users.scenario = 'employer'
AND EXISTS (
SELECT 1 FROM memberships
WHERE memberships.user_id = users.id
AND memberships.organization_id = organizations.id
AND memberships.state = 'active'
)
)
);
@@ -23,6 +23,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
@@ -524,6 +525,21 @@ func newAssessmentAttemptHTTPHarnessWithOptions(
env *testEnvironment,
categories assessment.AssessmentCategoryDecisionSettings,
extra func(assessmentHarnessParts) []v1.HandlerOption,
) *assessmentAttemptHTTPHarness {
t.Helper()
return newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, categories, extra, nil)
}
// newAssessmentAttemptHTTPHarnessWithMiddleware also mounts the operation
// middleware that middleware returns, after extra has built its handlers, so a
// scenario can add the owner company context to the same router.
func newAssessmentAttemptHTTPHarnessWithMiddleware(
ctx context.Context,
t *testing.T,
env *testEnvironment,
categories assessment.AssessmentCategoryDecisionSettings,
extra func(assessmentHarnessParts) []v1.HandlerOption,
middleware func() []apiadapter.Middleware,
) *assessmentAttemptHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
@@ -585,7 +601,11 @@ func newAssessmentAttemptHTTPHarnessWithOptions(
options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...)
}
handler := v1.NewHandler(healthHandler, responder, options...)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
var operationMiddleware []apiadapter.Middleware
if middleware != nil {
operationMiddleware = middleware()
}
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, operationMiddleware...)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,135 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
)
const (
// syntheticNotificationMigrationVersion adds the synthetic event type to
// the inbox allowlist.
syntheticNotificationMigrationVersion = 36
checkViolation = "23514"
notificationTypeConstraint = "notification_inbox_events_type_known"
)
func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
candidate := identity.createUser(t, "inbox-migration@example.com", domain.ScenarioCandidate, now.Add(-time.Hour))
organizations := organizationFixture{
ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now,
}
owner := organizations.employer(t, "inbox-migration-owner@example.com")
organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now)
insert := func(eventType, sourceType string, schemaVersion int) error {
_, err := pool.Exec(ctx, `INSERT INTO notification_inbox_events (
recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
candidate.ID, uuid.New(), organization.ID(), eventType, schemaVersion, sourceType, organization.ID(), now)
return err
}
if err := insert("invitation.delivered", "invitation", 1); err != nil {
t.Fatalf("insert invitation event: %v", err)
}
if err := insert("notification.synthetic_delivered", "organization", 1); err != nil {
t.Fatalf("insert synthetic event: %v", err)
}
for name, args := range map[string][3]any{
"synthetic event with the invitation source": {"notification.synthetic_delivered", "invitation", 1},
"invitation event with the organization": {"invitation.delivered", "organization", 1},
"unknown event type": {"notification.mail_requested", "organization", 1},
"unsupported schema version": {"notification.synthetic_delivered", "organization", 2},
} {
err := insert(args[0].(string), args[1].(string), args[2].(int))
assertPgError(t, name, err, checkViolation, notificationTypeConstraint)
}
// A rollback refuses to orphan a synthetic row and leaves the migration
// applied.
_, err := migrator.DownOne(ctx)
assertPgError(t, "DownOne() with a synthetic inbox event", err, privacyIntegrityViolation, notificationTypeConstraint)
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() error = %v", err)
}
for _, status := range statuses {
if status.Version == syntheticNotificationMigrationVersion && !status.Applied {
t.Fatal("the migration was rolled back despite a synthetic inbox event")
}
}
}
func TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion)
result, err := migrator.DownOne(ctx)
if err != nil || result.Version != syntheticNotificationMigrationVersion {
t.Fatalf("DownOne() = %+v, %v, want version %d rolled back", result, err, syntheticNotificationMigrationVersion)
}
var constraint string
if err := pool.QueryRow(ctx, `SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = $1`, notificationTypeConstraint).Scan(&constraint); err != nil {
t.Fatalf("read the restored constraint: %v", err)
}
if constraint != "CHECK (((event_type = 'invitation.delivered'::text) AND (schema_version = 1) AND (source_type = 'invitation'::text)))" {
t.Fatalf("restored constraint = %s, want the invitation-only allowlist", constraint)
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}
// rollBackAboveVersion rolls back every migration newer than version, so a
// test of one migration keeps working when later migrations exist.
func rollBackAboveVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, version int64) {
t.Helper()
for {
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() while preparing migration %d: %v", version, err)
}
latest := int64(0)
for _, status := range statuses {
if status.Applied && status.Version > latest {
latest = status.Version
}
}
if latest < version {
t.Fatalf("migration %d is not applied", version)
}
if latest == version {
return
}
if _, err := migrator.DownOne(ctx); err != nil {
t.Fatalf("DownOne() while preparing migration %d: %v", version, err)
}
}
}
@@ -0,0 +1,431 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/organization"
)
const (
notificationHTTPTimeout = 5 * time.Minute
notificationConsumerTTL = 10 * time.Second
// inboxRenamedConsumer stands for a consumer renamed after a deployment:
// its markers are empty, so only the inbox key can absorb the replay.
inboxRenamedConsumer = "notification_inbox_renamed"
)
type notificationBody struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
OrganizationID uuid.UUID `json:"organization_id"`
DeliveredAt time.Time `json:"delivered_at"`
ReadAt *time.Time `json:"read_at"`
Content *struct {
Title string `json:"title"`
Summary string `json:"summary"`
LinkPath *string `json:"link_path"`
} `json:"content"`
}
type notificationPageBody struct {
Items []notificationBody `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
func newNotificationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
store := postgresadapter.NewIdentityStore(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
credentials := identity.NewCredentials(hasher)
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
transactor := postgresadapter.NewTransactor(pool)
sessionService, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials,
Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
}, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: env.Config.IdentitySessionIdleTimeout,
AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
})
if err != nil {
t.Fatalf("NewSessionService() error = %v", err)
}
organizationService, err := organization.NewService(organization.Dependencies{
Transactor: transactor, Keyring: keyring, Clock: clock.Now,
})
if err != nil {
t.Fatalf("organization.NewService() error = %v", err)
}
inbox, err := notification.NewInboxService(transactor,
notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(true)), clock.Now)
if err != nil {
t.Fatalf("notification.NewInboxService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.DiscardHandler)
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil,
v1.WithSessionService(sessionService),
v1.WithPublicOrigin(env.Config.AppPublicURL),
)
organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler),
v1.WithNotifications(v1.NewNotificationHandler(inbox)),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
}
// appendSyntheticNotice records a synthetic inbox event through the real
// outbox writer, as a producer does in its own transaction, and returns the
// envelope a consumer would receive for it.
func appendSyntheticNotice(
ctx context.Context,
t *testing.T,
transactor outbound.Transactor,
recipientID, organizationID uuid.UUID,
occurredAt time.Time,
) outbound.ConsumedEvent {
t.Helper()
payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID)
if err != nil {
t.Fatalf("SyntheticNoticeEventPayload() error = %v", 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 {
t.Fatalf("NewDomainEvent() error = %v", err)
}
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Outbox().Append(ctx, event)
})
if err != nil {
t.Fatalf("Append(synthetic notice) error = %v", err)
}
return outbound.ConsumedEvent{
EventID: event.EventID(), EventType: event.EventType(), SchemaVersion: event.SchemaVersion(),
AggregateType: event.AggregateType(), AggregateID: event.AggregateID(), AggregateVersion: event.AggregateVersion(),
OccurredAt: occurredAt, Payload: event.Payload(),
}
}
func deliverToInbox(
ctx context.Context,
t *testing.T,
store *postgresadapter.EventConsumerStore,
consumer string,
event outbound.ConsumedEvent,
) bool {
t.Helper()
handler := notification.NewInboxHandler(slog.New(slog.DiscardHandler), true)
applied, err := store.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, event)
})
if err != nil {
t.Fatalf("ApplyOnce(%s, %s) error = %v", consumer, event.EventID, err)
}
return applied
}
func notificationRequest(
t *testing.T,
harness *sessionHTTPHarness,
method, path, origin string,
session organizationHTTPSession,
) *httptest.ResponseRecorder {
t.Helper()
return organizationHTTPRequest(t, harness, method, path, "", origin, session, "")
}
func decodeNotificationPage(t *testing.T, response *httptest.ResponseRecorder) notificationPageBody {
t.Helper()
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("notification list = %d %q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String())
}
var page notificationPageBody
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
t.Fatalf("decode notification page: %v", err)
}
return page
}
func requireNotificationProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) {
t.Helper()
requireSessionProblem(t, response, status, code)
}
func TestNotificationInboxOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout)
defer cancel()
harness := newNotificationHTTPHarness(ctx, t, env)
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
truncateTables(ctx, t, harness.pool, resetTables...)
transactor := postgresadapter.NewTransactor(harness.pool)
consumerStore := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
otherCandidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-other-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreign := createOrganizationHTTPUser(ctx, t, harness, "inbox-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "inbox-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
otherCandidateSession := loginOrganizationHTTP(t, harness, otherCandidate.Email.Address())
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
origin := env.Config.AppPublicURL
organizationID := createCompanyForContextTest(t, harness, origin, ownerSession, "inbox-company")
foreignOrganizationID := createCompanyForContextTest(t, harness, origin, foreignSession, "inbox-foreign-company")
var organizationName string
if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, organizationID).Scan(&organizationName); err != nil {
t.Fatalf("read organization name: %v", err)
}
// One synthetic event delivered twice, and once more by a renamed
// consumer, stores exactly one row.
deliveredAt := now.Add(-time.Hour)
event := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, deliveredAt)
if !deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) {
t.Fatal("the first delivery was reported as a duplicate")
}
if deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) {
t.Fatal("the second delivery of the same event ID was applied again")
}
deliverToInbox(ctx, t, consumerStore, inboxRenamedConsumer, event)
var rows int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE event_id = $1`, event.EventID).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("inbox rows for the repeated event = %d, %v, want 1", rows, err)
}
list := func(session organizationHTTPSession) notificationPageBody {
t.Helper()
return decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", session))
}
page := list(candidateSession)
if len(page.Items) != 1 || page.Page.HasMore || page.Page.NextCursor != nil {
t.Fatalf("candidate inbox = %+v, want one item on the last page", page)
}
item := page.Items[0]
if item.ID != event.EventID || item.Kind != "synthetic" || item.OrganizationID != organizationID ||
item.ReadAt != nil || !item.DeliveredAt.Equal(deliveredAt.Truncate(time.Second)) {
t.Fatalf("candidate item = %+v, want the unread synthetic event", item)
}
if item.Content == nil || item.Content.Title != "Тестовое уведомление" || !strings.Contains(item.Content.Summary, organizationName) ||
item.Content.LinkPath != nil {
t.Fatalf("candidate item content = %+v, want the current organization name", item.Content)
}
if got := list(otherCandidateSession); len(got.Items) != 0 {
t.Fatalf("another candidate's inbox = %+v, want empty", got)
}
// Account and cabinet boundaries.
markPath := "/api/v1/me/notifications/" + event.EventID.String() + "/read"
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", ownerSession), http.StatusForbidden, "forbidden")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, ownerSession), http.StatusForbidden, "forbidden")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, otherCandidateSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/"+uuid.NewString()+"/read", origin, candidateSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/not-a-uuid/read", origin, candidateSession), http.StatusBadRequest, "validation_failed")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, "https://evil.example", candidateSession), http.StatusForbidden, "csrf_check_failed")
noCSRFSession := candidateSession
noCSRFSession.csrf = ""
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, noCSRFSession), http.StatusForbidden, "csrf_check_failed")
if got := list(candidateSession); got.Items[0].ReadAt != nil {
t.Fatal("a refused request marked the item read")
}
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationID.String()+"/notifications", "", candidateSession), http.StatusForbidden, "forbidden")
// Mark read twice: the first time stays, and the list persists it.
first := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession)
var receipt struct {
ID uuid.UUID `json:"id"`
ReadAt time.Time `json:"read_at"`
}
if first.Code != http.StatusOK || first.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("mark read = %d %s, want a no-store 200", first.Code, first.Body.String())
}
if err := json.Unmarshal(first.Body.Bytes(), &receipt); err != nil || receipt.ID != event.EventID || receipt.ReadAt.IsZero() {
t.Fatalf("mark read receipt = %s, %v", first.Body.String(), err)
}
harness.clock.Advance(time.Hour)
again := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession)
var repeated struct {
ReadAt time.Time `json:"read_at"`
}
if err := json.Unmarshal(again.Body.Bytes(), &repeated); err != nil || !repeated.ReadAt.Equal(receipt.ReadAt) {
t.Fatalf("repeated mark = %s, %v, want the first read time %s", again.Body.String(), err, receipt.ReadAt)
}
if got := list(candidateSession); got.Items[0].ReadAt == nil || !got.Items[0].ReadAt.Equal(receipt.ReadAt) {
t.Fatalf("list after mark = %+v, want the persisted read time", got.Items)
}
// Hiding the organization removes the content from the next read; the
// item and its read state stay.
if _, err := harness.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`,
candidate.ID, organizationID, now); err != nil {
t.Fatalf("hide organization: %v", err)
}
hidden := list(candidateSession)
if len(hidden.Items) != 1 || hidden.Items[0].Content != nil || hidden.Items[0].ReadAt == nil {
t.Fatalf("list after hiding = %+v, want the item without content and still read", hidden.Items)
}
if strings.Contains(notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", candidateSession).Body.String(), organizationName) {
t.Fatal("the organization name still reaches a candidate who hid the organization")
}
// Pagination: newest first, a cursor bound to the account.
for offset := 1; offset <= 3; offset++ {
extra := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, now.Add(-time.Duration(offset)*time.Minute))
deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, extra)
}
firstPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2", "", candidateSession))
if len(firstPage.Items) != 2 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil ||
!firstPage.Items[0].DeliveredAt.After(firstPage.Items[1].DeliveredAt) {
t.Fatalf("first page = %+v, want two newest-first items and a cursor", firstPage)
}
cursor := url.QueryEscape(*firstPage.Page.NextCursor)
secondPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2&cursor="+cursor, "", candidateSession))
if len(secondPage.Items) != 2 || secondPage.Page.HasMore || secondPage.Items[0].ID == firstPage.Items[1].ID ||
!secondPage.Items[0].DeliveredAt.Before(firstPage.Items[1].DeliveredAt) {
t.Fatalf("second page = %+v, want the remaining two items after the first page", secondPage)
}
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?cursor="+cursor, "", otherCandidateSession), http.StatusBadRequest, "validation_failed")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=101", "", candidateSession), http.StatusBadRequest, "validation_failed")
// The employer cabinet: only the caller's items of this organization, and
// no access after the membership ends.
employerEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, organizationID, now.Add(-time.Minute))
deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, employerEvent)
foreignOrganizationEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, foreignOrganizationID, now.Add(-time.Minute))
// An owner of another organization is not a member of it: the row exists
// but stays out of the cabinet of the first organization.
deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, foreignOrganizationEvent)
organizationPath := "/api/v1/organizations/" + organizationID.String() + "/notifications"
organizationPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession))
if len(organizationPage.Items) != 1 || organizationPage.Items[0].ID != employerEvent.EventID || organizationPage.Items[0].Content == nil {
t.Fatalf("employer inbox = %+v, want only the item of this organization with content", organizationPage.Items)
}
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", foreignSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+uuid.NewString()+"/notifications", "", ownerSession), http.StatusNotFound, "not_found")
employerMark := organizationPath + "/" + employerEvent.EventID.String() + "/read"
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, foreignSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost,
organizationPath+"/"+foreignOrganizationEvent.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost,
organizationPath+"/"+event.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found")
if marked := notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession); marked.Code != http.StatusOK {
t.Fatalf("employer mark read = %d %s, want 200", marked.Code, marked.Body.String())
}
// A member of another role reads and marks its own items only, although the
// owner-only operations refuse it.
insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now)
recruiterEvent := appendSyntheticNotice(ctx, t, transactor, recruiter.ID, organizationID, now.Add(-time.Minute))
deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, recruiterEvent)
recruiterPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", recruiterSession))
if len(recruiterPage.Items) != 1 || recruiterPage.Items[0].ID != recruiterEvent.EventID || recruiterPage.Items[0].Content == nil {
t.Fatalf("recruiter inbox = %+v, want only its own item with content", recruiterPage.Items)
}
if marked := notificationRequest(t, harness, http.MethodPost, organizationPath+"/"+recruiterEvent.EventID.String()+"/read", origin, recruiterSession); marked.Code != http.StatusOK {
t.Fatalf("recruiter mark read = %d %s, want 200", marked.Code, marked.Body.String())
}
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, recruiterSession), http.StatusNotFound, "not_found")
if _, err := harness.pool.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organizationID, owner.ID); err != nil {
t.Fatalf("revoke membership: %v", err)
}
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession), http.StatusNotFound, "not_found")
requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession), http.StatusNotFound, "not_found")
}
// A recipient or an organization that does not exist is told apart, so a
// handler can retry and skip a deleted account but reject a broken reference.
func TestNotificationInboxStoreNamesTheMissingReference(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout)
defer cancel()
harness := newNotificationHTTPHarness(ctx, t, env)
truncateTables(ctx, t, harness.pool, append([]pgx.Identifier{}, usersDependentTables...)...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "inbox-ref-company")
repository := postgresadapter.NewNotificationInboxRepository(harness.pool)
entry := func(recipientID, orgID uuid.UUID) domain.NotificationInboxEntry {
built, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: orgID,
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceOrganization, SourceID: orgID, OccurredAt: now,
})
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return built
}
if _, err := repository.Store(ctx, entry(uuid.New(), organizationID)); !errors.Is(err, outbound.ErrNotificationInboxRecipientMissing) {
t.Fatalf("Store(unknown recipient) error = %v, want ErrNotificationInboxRecipientMissing", err)
}
if _, err := repository.Store(ctx, entry(candidate.ID, uuid.New())); !errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) {
t.Fatalf("Store(unknown organization) error = %v, want ErrNotificationInboxReferenceMissing", err)
}
if created, err := repository.Store(ctx, entry(candidate.ID, organizationID)); err != nil || !created {
t.Fatalf("Store(valid) = %t, %v, want true, nil", created, err)
}
}
@@ -807,6 +807,8 @@ func TestSkillEvidenceOverHTTP(t *testing.T) {
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil {
t.Fatalf("hide the fact: %v", err)
}
// Later migrations may exist; the rollback under test is the evidence one.
rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion)
_, err = migrator.DownOne(ctx)
assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained")
assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills")
@@ -0,0 +1,113 @@
// Package policypublish implements the local operator command that adds the
// demo matching section to the product policy. Until an administrative policy
// editor exists, this is how a stand gets the coefficients that the match
// search needs: startup seeds only the first demo version.
package policypublish
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/policy"
)
const usage = "usage: policy-publish matching --actor operator:<handle>"
// Command is a parsed, validated request.
type Command struct {
Author domain.PolicyAuthor
}
// Extender publishes the demo matching section.
type Extender interface {
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "matching" {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError)
flags.SetOutput(io.Discard)
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
value := strings.TrimSpace(*actor)
author, err := domain.ParsePolicyAuthor(value)
if err != nil || !strings.HasPrefix(value, "operator:") {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{Author: author}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
// environment, and publishes. It does not load dotenv files.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil || clock == nil {
return errors.New("policy publication command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
return Execute(ctx, command, policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), clock), output)
}
// Execute publishes the section and prints the version number only.
func Execute(ctx context.Context, command Command, extender Extender, output io.Writer) error {
if extender == nil || output == nil {
return errors.New("policy publication command dependencies are required")
}
result, err := extender.EnsureDemoMatchingSection(ctx, command.Author)
if err != nil {
return safeOperationError(err)
}
status := "already present"
if result.Created {
status = "published"
}
if _, err := fmt.Fprintf(output,
"%s: product policy version %d carries the demo matching section\n"+
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n",
status, result.Version.Version(),
); err != nil {
return errors.New("could not write the result")
}
return nil
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, policy.ErrNotDemoPolicy):
return errors.New("the latest product policy is not a demonstration version; publish the matching section with the calibrated policy instead")
case errors.Is(err, policy.ErrPolicyChanged):
return errors.New("the product policy changed while publishing; run the command again")
case errors.Is(err, outbound.ErrPolicyVersionNotFound):
return errors.New("the product policy has no version yet; start the service once so that it seeds the demo policy")
default:
return errors.New("policy publication failed")
}
}
@@ -0,0 +1,64 @@
package policypublish
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/policy"
)
type extenderFake struct {
result policy.MatchingResult
err error
author domain.PolicyAuthor
}
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
extender.author = author
return extender.result, extender.err
}
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
command, err := Parse([]string{"matching", "--actor", "operator:night"})
if err != nil || command.Author != "operator:night" {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
{"matching", "--actor", "operator:night", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T) {
var output bytes.Buffer
extender := &extenderFake{}
if err := Execute(context.Background(), Command{Author: "operator:night"}, extender, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !strings.HasPrefix(output.String(), "already present: product policy version 0") || extender.author != "operator:night" {
t.Fatalf("output = %q, author %q", output.String(), extender.author)
}
for _, test := range []struct {
err error
want string
}{
{policy.ErrNotDemoPolicy, "not a demonstration version"},
{outbound.ErrPolicyVersionNotFound, "no version yet"},
{policy.ErrPolicyChanged, "run the command again"},
{errors.New("pq: password authentication failed for user x"), "policy publication failed"},
} {
err := Execute(context.Background(), Command{Author: "operator:night"}, &extenderFake{err: test.err}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "password") {
t.Errorf("Execute(%v) error = %v, want a safe message containing %q", test.err, err, test.want)
}
}
}
@@ -19,6 +19,7 @@ import (
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
@@ -9263,6 +9263,225 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyNotificationsRequest handles ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
func (s *Server) handleListMyNotificationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyNotifications"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/notifications"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyNotificationsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyNotificationsOperation,
ID: "ListMyNotifications",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyNotificationsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyNotificationsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyNotificationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyNotificationsOperation,
OperationSummary: "List the inbox of the current candidate.",
OperationID: "ListMyNotifications",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyNotificationsParams
Response = ListMyNotificationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyNotificationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyNotifications(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyNotifications(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyNotificationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
@@ -10366,6 +10585,229 @@ func (s *Server) handleListOrganizationNeedsRequest(args [1]string, argsEscaped
}
}
// handleListOrganizationNotificationsRequest handles ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
func (s *Server) handleListOrganizationNotificationsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListOrganizationNotifications"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationNotificationsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListOrganizationNotificationsOperation,
ID: "ListOrganizationNotifications",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationNotificationsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListOrganizationNotificationsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListOrganizationNotificationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListOrganizationNotificationsOperation,
OperationSummary: "List the inbox of the current employer in one organization.",
OperationID: "ListOrganizationNotifications",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListOrganizationNotificationsParams
Response = ListOrganizationNotificationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListOrganizationNotificationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListOrganizationNotifications(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListOrganizationNotifications(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListOrganizationNotificationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleLoginRequest handles Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -10745,6 +11187,477 @@ func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.Re
}
}
// handleMarkMyNotificationReadRequest handles MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
func (s *Server) handleMarkMyNotificationReadRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("MarkMyNotificationRead"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/notifications/{notification_id}/read"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), MarkMyNotificationReadOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: MarkMyNotificationReadOperation,
ID: "MarkMyNotificationRead",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, MarkMyNotificationReadOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, MarkMyNotificationReadOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeMarkMyNotificationReadParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response MarkMyNotificationReadRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: MarkMyNotificationReadOperation,
OperationSummary: "Mark an item of the inbox of the current candidate as read.",
OperationID: "MarkMyNotificationRead",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "notification_id",
In: "path",
}: params.NotificationID,
},
Raw: r,
}
type (
Request = struct{}
Params = MarkMyNotificationReadParams
Response = MarkMyNotificationReadRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackMarkMyNotificationReadParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.MarkMyNotificationRead(ctx, params)
return response, err
},
)
} else {
response, err = s.h.MarkMyNotificationRead(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeMarkMyNotificationReadResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleMarkOrganizationNotificationReadRequest handles MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
func (s *Server) handleMarkOrganizationNotificationReadRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("MarkOrganizationNotificationRead"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications/{notification_id}/read"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), MarkOrganizationNotificationReadOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: MarkOrganizationNotificationReadOperation,
ID: "MarkOrganizationNotificationRead",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, MarkOrganizationNotificationReadOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, MarkOrganizationNotificationReadOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeMarkOrganizationNotificationReadParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response MarkOrganizationNotificationReadRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: MarkOrganizationNotificationReadOperation,
OperationSummary: "Mark an item of the inbox of the current employer in one organization as read.",
OperationID: "MarkOrganizationNotificationRead",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "notification_id",
In: "path",
}: params.NotificationID,
},
Raw: r,
}
type (
Request = struct{}
Params = MarkOrganizationNotificationReadParams
Response = MarkOrganizationNotificationReadRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackMarkOrganizationNotificationReadParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.MarkOrganizationNotificationRead(ctx, params)
return response, err
},
)
} else {
response, err = s.h.MarkOrganizationNotificationRead(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeMarkOrganizationNotificationReadResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRaiseOrganizationInvitationSalaryRequest handles RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -12840,6 +13753,15 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -12855,7 +13777,10 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -157,6 +157,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyNotificationsRes interface {
listMyNotificationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
@@ -177,6 +181,10 @@ type ListOrganizationNeedsRes interface {
listOrganizationNeedsRes()
}
type ListOrganizationNotificationsRes interface {
listOrganizationNotificationsRes()
}
type LoginRes interface {
loginRes()
}
@@ -185,6 +193,14 @@ type LogoutRes interface {
logoutRes()
}
type MarkMyNotificationReadRes interface {
markMyNotificationReadRes()
}
type MarkOrganizationNotificationReadRes interface {
markOrganizationNotificationReadRes()
}
type RaiseOrganizationInvitationSalaryRes interface {
raiseOrganizationInvitationSalaryRes()
}
File diff suppressed because it is too large. Load diff
@@ -47,13 +47,17 @@ const (
ListMyEvidenceOperation OperationName = "ListMyEvidence"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyNotificationsOperation OperationName = "ListMyNotifications"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
ListOrganizationNotificationsOperation OperationName = "ListOrganizationNotifications"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
MarkMyNotificationReadOperation OperationName = "MarkMyNotificationRead"
MarkOrganizationNotificationReadOperation OperationName = "MarkOrganizationNotificationRead"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
@@ -3696,6 +3696,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyNotificationsParams is parameters of ListMyNotifications operation.
type ListMyNotificationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyNotificationsParams(packed middleware.Parameters) (params ListMyNotificationsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyNotificationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyNotificationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
type ListMyOrganizationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -4690,6 +4866,432 @@ func decodeListOrganizationNeedsParams(args [1]string, argsEscaped bool, r *http
return params, nil
}
// ListOrganizationNotificationsParams is parameters of ListOrganizationNotifications operation.
type ListOrganizationNotificationsParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListOrganizationNotificationsParams(packed middleware.Parameters) (params ListOrganizationNotificationsParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListOrganizationNotificationsParams(args [1]string, argsEscaped bool, r *http.Request) (params ListOrganizationNotificationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// MarkMyNotificationReadParams is parameters of MarkMyNotificationRead operation.
type MarkMyNotificationReadParams struct {
// Identifier of an item of the inbox of the current account in the cabinet that the path names. An
// item of another account, an item of another organization context, and an unknown identifier all
// answer 404 not_found, so identifiers cannot be enumerated.
NotificationID uuid.UUID
}
func unpackMarkMyNotificationReadParams(packed middleware.Parameters) (params MarkMyNotificationReadParams) {
{
key := middleware.ParameterKey{
Name: "notification_id",
In: "path",
}
params.NotificationID = packed[key].(uuid.UUID)
}
return params
}
func decodeMarkMyNotificationReadParams(args [1]string, argsEscaped bool, r *http.Request) (params MarkMyNotificationReadParams, _ error) {
// Decode path: notification_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "notification_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.NotificationID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "notification_id",
In: "path",
Err: err,
}
}
return params, nil
}
// MarkOrganizationNotificationReadParams is parameters of MarkOrganizationNotificationRead operation.
type MarkOrganizationNotificationReadParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
// Identifier of an item of the inbox of the current account in the cabinet that the path names. An
// item of another account, an item of another organization context, and an unknown identifier all
// answer 404 not_found, so identifiers cannot be enumerated.
NotificationID uuid.UUID
}
func unpackMarkOrganizationNotificationReadParams(packed middleware.Parameters) (params MarkOrganizationNotificationReadParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "notification_id",
In: "path",
}
params.NotificationID = packed[key].(uuid.UUID)
}
return params
}
func decodeMarkOrganizationNotificationReadParams(args [2]string, argsEscaped bool, r *http.Request) (params MarkOrganizationNotificationReadParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
// Decode path: notification_id.
if err := func() error {
param := args[1]
if argsEscaped {
unescaped, err := url.PathUnescape(args[1])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "notification_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.NotificationID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "notification_id",
In: "path",
Err: err,
}
}
return params, nil
}
// RaiseOrganizationInvitationSalaryParams is parameters of RaiseOrganizationInvitationSalary operation.
type RaiseOrganizationInvitationSalaryParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -3461,6 +3461,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyNotificationsResponse(response ListMyNotificationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyNotificationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyNotificationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyNotificationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
@@ -3828,6 +3899,89 @@ func encodeListOrganizationNeedsResponse(response ListOrganizationNeedsRes, w ht
}
}
func encodeListOrganizationNotificationsResponse(response ListOrganizationNotificationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListOrganizationNotificationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListOrganizationNotificationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListOrganizationNotificationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListOrganizationNotificationsNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SessionHeaders:
@@ -4014,6 +4168,236 @@ func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace.
}
}
func encodeMarkMyNotificationReadResponse(response MarkMyNotificationReadRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationReadReceiptHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkMyNotificationReadBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkMyNotificationReadUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkMyNotificationReadForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkMyNotificationReadNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeMarkOrganizationNotificationReadResponse(response MarkOrganizationNotificationReadRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationReadReceiptHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkOrganizationNotificationReadBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkOrganizationNotificationReadUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkOrganizationNotificationReadForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *MarkOrganizationNotificationReadNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationInvitationSalaryRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -11,43 +11,43 @@ import (
)
var (
rn74AllowedHeaders = map[string]string{
rn83AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn70AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn66AllowedHeaders = map[string]string{
rn69AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn27AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
rn81AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn11AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn85AllowedHeaders = map[string]string{
rn94AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn22AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn84AllowedHeaders = map[string]string{
rn93AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn69AllowedHeaders = map[string]string{
rn78AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn76AllowedHeaders = map[string]string{
rn85AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
@@ -63,17 +63,20 @@ var (
rn19AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
rn95AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn56AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn81AllowedHeaders = map[string]string{
rn90AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn82AllowedHeaders = map[string]string{
rn91AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn38AllowedHeaders = map[string]string{
@@ -97,16 +100,16 @@ var (
rn46AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn68AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn77AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn18AllowedHeaders = map[string]string{
@@ -115,6 +118,9 @@ var (
rn49AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn75AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
func (s *Server) cutPrefix(path string) (string, bool) {
@@ -269,7 +275,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn74AllowedHeaders,
allowedHeaders: rn83AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -346,7 +352,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn70AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -370,7 +376,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn66AllowedHeaders,
allowedHeaders: rn69AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -450,7 +456,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn72AllowedHeaders,
allowedHeaders: rn81AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -572,7 +578,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn85AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -665,7 +671,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn84AllowedHeaders,
allowedHeaders: rn93AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -692,7 +698,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn69AllowedHeaders,
allowedHeaders: rn78AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -903,7 +909,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn76AllowedHeaders,
allowedHeaders: rn85AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1145,7 +1151,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn86AllowedHeaders,
allowedHeaders: rn95AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1160,6 +1166,82 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'n': // Prefix: "notifications"
if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListMyNotificationsRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleMarkMyNotificationReadRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn72AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
case 'o': // Prefix: "organizations"
if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" {
@@ -1416,7 +1498,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn81AllowedHeaders,
allowedHeaders: rn90AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1443,7 +1525,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn82AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1861,7 +1943,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn68AllowedHeaders,
allowedHeaders: rn77AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1889,7 +1971,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn88AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1919,7 +2001,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn87AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1952,7 +2034,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn77AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1961,77 +2043,170 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 'n': // Prefix: "needs"
case 'n': // Prefix: "n"
if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" {
if l := len("n"); len(elem) >= l && elem[0:l] == "n" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListOrganizationNeedsRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
case "POST":
s.handleCreateOrganizationNeedRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn18AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
break
}
switch elem[0] {
case '/': // Prefix: "/"
case 'e': // Prefix: "eeds"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetOrganizationNeedRequest([2]string{
s.handleListOrganizationNeedsRequest([1]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
case "PATCH":
s.handleUpdateOrganizationNeedRequest([2]string{
case "POST":
s.handleCreateOrganizationNeedRequest([1]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn49AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
allowedMethods: "GET,POST",
allowedHeaders: rn18AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetOrganizationNeedRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
case "PATCH":
s.handleUpdateOrganizationNeedRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn49AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
}
return
}
}
case 'o': // Prefix: "otifications"
if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListOrganizationNotificationsRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[1] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleMarkOrganizationNotificationReadRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn75AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
}
@@ -3147,6 +3322,80 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'n': // Prefix: "notifications"
if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListMyNotificationsOperation
r.summary = "List the inbox of the current candidate."
r.operationID = "ListMyNotifications"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/notifications"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = MarkMyNotificationReadOperation
r.summary = "Mark an item of the inbox of the current candidate as read."
r.operationID = "MarkMyNotificationRead"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/notifications/{notification_id}/read"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
case 'o': // Prefix: "organizations"
if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" {
@@ -3957,81 +4206,169 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 'n': // Prefix: "needs"
case 'n': // Prefix: "n"
if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" {
if l := len("n"); len(elem) >= l && elem[0:l] == "n" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListOrganizationNeedsOperation
r.summary = "List the needs of an organization."
r.operationID = "ListOrganizationNeeds"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 1
return r, true
case "POST":
r.name = CreateOrganizationNeedOperation
r.summary = "Create a need of an organization from a form, a text, or both."
r.operationID = "CreateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 1
return r, true
default:
return
}
break
}
switch elem[0] {
case '/': // Prefix: "/"
case 'e': // Prefix: "eeds"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetOrganizationNeedOperation
r.summary = "Read the current version of a need of an organization."
r.operationID = "GetOrganizationNeed"
r.name = ListOrganizationNeedsOperation
r.summary = "List the needs of an organization."
r.operationID = "ListOrganizationNeeds"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 2
r.count = 1
return r, true
case "PATCH":
r.name = UpdateOrganizationNeedOperation
r.summary = "Confirm, change, or delete requirements of a need."
r.operationID = "UpdateOrganizationNeed"
case "POST":
r.name = CreateOrganizationNeedOperation
r.summary = "Create a need of an organization from a form, a text, or both."
r.operationID = "CreateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 2
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetOrganizationNeedOperation
r.summary = "Read the current version of a need of an organization."
r.operationID = "GetOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.args = args
r.count = 2
return r, true
case "PATCH":
r.name = UpdateOrganizationNeedOperation
r.summary = "Confirm, change, or delete requirements of a need."
r.operationID = "UpdateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.args = args
r.count = 2
return r, true
default:
return
}
}
}
case 'o': // Prefix: "otifications"
if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListOrganizationNotificationsOperation
r.summary = "List the inbox of the current employer in one organization."
r.operationID = "ListOrganizationNotifications"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/notifications"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[1] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = MarkOrganizationNotificationReadOperation
r.summary = "Mark an item of the inbox of the current employer in one organization as read."
r.operationID = "MarkOrganizationNotificationRead"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/notifications/{notification_id}/read"
r.args = args
r.count = 2
return r, true
default:
return
}
}
}
}
}
@@ -12625,6 +12625,18 @@ type ListMyInvitationsUnauthorized Problem
func (*ListMyInvitationsUnauthorized) listMyInvitationsRes() {}
type ListMyNotificationsBadRequest Problem
func (*ListMyNotificationsBadRequest) listMyNotificationsRes() {}
type ListMyNotificationsForbidden Problem
func (*ListMyNotificationsForbidden) listMyNotificationsRes() {}
type ListMyNotificationsUnauthorized Problem
func (*ListMyNotificationsUnauthorized) listMyNotificationsRes() {}
type ListMyOrganizationsBadRequest Problem
func (*ListMyOrganizationsBadRequest) listMyOrganizationsRes() {}
@@ -12689,6 +12701,22 @@ type ListOrganizationNeedsUnauthorized Problem
func (*ListOrganizationNeedsUnauthorized) listOrganizationNeedsRes() {}
type ListOrganizationNotificationsBadRequest Problem
func (*ListOrganizationNotificationsBadRequest) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsForbidden Problem
func (*ListOrganizationNotificationsForbidden) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsNotFound Problem
func (*ListOrganizationNotificationsNotFound) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsUnauthorized Problem
func (*ListOrganizationNotificationsUnauthorized) listOrganizationNotificationsRes() {}
type LoginBadRequest Problem
func (*LoginBadRequest) loginRes() {}
@@ -12747,6 +12775,38 @@ func (s *LogoutNoContent) SetSetCookie(val string) {
func (*LogoutNoContent) logoutRes() {}
type MarkMyNotificationReadBadRequest Problem
func (*MarkMyNotificationReadBadRequest) markMyNotificationReadRes() {}
type MarkMyNotificationReadForbidden Problem
func (*MarkMyNotificationReadForbidden) markMyNotificationReadRes() {}
type MarkMyNotificationReadNotFound Problem
func (*MarkMyNotificationReadNotFound) markMyNotificationReadRes() {}
type MarkMyNotificationReadUnauthorized Problem
func (*MarkMyNotificationReadUnauthorized) markMyNotificationReadRes() {}
type MarkOrganizationNotificationReadBadRequest Problem
func (*MarkOrganizationNotificationReadBadRequest) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadForbidden Problem
func (*MarkOrganizationNotificationReadForbidden) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadNotFound Problem
func (*MarkOrganizationNotificationReadNotFound) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadUnauthorized Problem
func (*MarkOrganizationNotificationReadUnauthorized) markOrganizationNotificationReadRes() {}
// Conditions echoed as a complete snapshot; null means no filter.
// Ref: #/components/schemas/MatchAppliedConditions
type MatchAppliedConditions struct {
@@ -13864,6 +13924,11 @@ func NewMatchSearchByBankMatchSearchRequest(v MatchSearchByBank) MatchSearchRequ
type MatchSearchResponse struct {
Source MatchSearchSource `json:"source"`
Groups MatchSearchGroups `json:"groups"`
// True when the groups are not the whole ranked result: a group exceeded the versioned per-group
// limit, or the organization's card-view allowance ended while the entries were being revealed. The
// entries returned are in rank order and already counted as card views. It carries no total, so it
// does not reveal how many candidates match.
Truncated bool `json:"truncated"`
}
// GetSource returns the value of Source.
@@ -13876,6 +13941,11 @@ func (s *MatchSearchResponse) GetGroups() MatchSearchGroups {
return s.Groups
}
// GetTruncated returns the value of Truncated.
func (s *MatchSearchResponse) GetTruncated() bool {
return s.Truncated
}
// SetSource sets the value of Source.
func (s *MatchSearchResponse) SetSource(val MatchSearchSource) {
s.Source = val
@@ -13886,6 +13956,11 @@ func (s *MatchSearchResponse) SetGroups(val MatchSearchGroups) {
s.Groups = val
}
// SetTruncated sets the value of Truncated.
func (s *MatchSearchResponse) SetTruncated(val bool) {
s.Truncated = val
}
// MatchSearchResponseHeaders wraps MatchSearchResponse with response headers.
type MatchSearchResponseHeaders struct {
CacheControl CacheControlNoStore
@@ -14392,7 +14467,10 @@ func (s *MatchUnknownFlag) SetReason(val MatchUnknownReason) {
type MatchUnknownFlags []MatchUnknownFlag
// Bounded explanation for an unknown component, not a hiding reason.
// Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported
// only while the comparable real cohort of the category is smaller than the versioned minimum; once
// the cohort reaches the minimum but the percentile is still not computed, the reason is
// `percentile_not_computed`. In both cases T is the neutral 0.5.
// Ref: #/components/schemas/MatchUnknownReason
type MatchUnknownReason string
@@ -14404,6 +14482,7 @@ const (
MatchUnknownReasonNeedFieldUnconfirmed MatchUnknownReason = "need_field_unconfirmed"
MatchUnknownReasonNoFreshnessHistory MatchUnknownReason = "no_freshness_history"
MatchUnknownReasonNoResponseHistory MatchUnknownReason = "no_response_history"
MatchUnknownReasonPercentileNotComputed MatchUnknownReason = "percentile_not_computed"
)
// AllValues returns all MatchUnknownReason values.
@@ -14416,6 +14495,7 @@ func (MatchUnknownReason) AllValues() []MatchUnknownReason {
MatchUnknownReasonNeedFieldUnconfirmed,
MatchUnknownReasonNoFreshnessHistory,
MatchUnknownReasonNoResponseHistory,
MatchUnknownReasonPercentileNotComputed,
}
}
@@ -14436,6 +14516,8 @@ func (s MatchUnknownReason) MarshalText() ([]byte, error) {
return []byte(s), nil
case MatchUnknownReasonNoResponseHistory:
return []byte(s), nil
case MatchUnknownReasonPercentileNotComputed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
@@ -14465,6 +14547,9 @@ func (s *MatchUnknownReason) UnmarshalText(data []byte) error {
case MatchUnknownReasonNoResponseHistory:
*s = MatchUnknownReasonNoResponseHistory
return nil
case MatchUnknownReasonPercentileNotComputed:
*s = MatchUnknownReasonPercentileNotComputed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
@@ -18830,6 +18915,51 @@ func (o NilNeedVersionLabel) Or(d NeedVersionLabel) NeedVersionLabel {
return d
}
// NewNilNotificationContent returns new NilNotificationContent with value set to v.
func NewNilNotificationContent(v NotificationContent) NilNotificationContent {
return NilNotificationContent{
Value: v,
}
}
// NilNotificationContent is nullable NotificationContent.
type NilNotificationContent struct {
Value NotificationContent
Null bool
}
// SetTo sets value to v.
func (o *NilNotificationContent) SetTo(v NotificationContent) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilNotificationContent) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilNotificationContent) SetToNull() {
o.Null = true
var v NotificationContent
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilNotificationContent) Get() (v NotificationContent, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilNotificationContent) Or(d NotificationContent) NotificationContent {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilOrganizationDescription returns new NilOrganizationDescription with value set to v.
func NewNilOrganizationDescription(v OrganizationDescription) NilOrganizationDescription {
return NilOrganizationDescription{
@@ -20495,6 +20625,301 @@ func (o NilWorkContext) Or(d WorkContext) WorkContext {
return d
}
// One item of the inbox of the current account. Its identity, kind, organization, delivery time, and
// read state are stored; its content is resolved from the current source on every read.
// Ref: #/components/schemas/Notification
type Notification struct {
// Identifier of the item. It equals the identifier of the event that produced it, so a repeated
// delivery of the same event is the same item.
ID uuid.UUID `json:"id"`
Kind NotificationKind `json:"kind"`
// The organization context of the item: the organization that sent it to a candidate, or the
// organization whose cabinet holds it for an employer. The identifier is not a right to read the
// organization.
OrganizationID uuid.UUID `json:"organization_id"`
DeliveredAt Timestamp `json:"delivered_at"`
// When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the
// first time.
ReadAt NilTimestamp `json:"read_at"`
// The current content, or null when the source is gone or the recipient may not see it now. A client
// then shows a generic line such as "The content is no longer available" and never an old copy. The
// item stays in the list and can be marked read.
Content NilNotificationContent `json:"content"`
}
// GetID returns the value of ID.
func (s *Notification) GetID() uuid.UUID {
return s.ID
}
// GetKind returns the value of Kind.
func (s *Notification) GetKind() NotificationKind {
return s.Kind
}
// GetOrganizationID returns the value of OrganizationID.
func (s *Notification) GetOrganizationID() uuid.UUID {
return s.OrganizationID
}
// GetDeliveredAt returns the value of DeliveredAt.
func (s *Notification) GetDeliveredAt() Timestamp {
return s.DeliveredAt
}
// GetReadAt returns the value of ReadAt.
func (s *Notification) GetReadAt() NilTimestamp {
return s.ReadAt
}
// GetContent returns the value of Content.
func (s *Notification) GetContent() NilNotificationContent {
return s.Content
}
// SetID sets the value of ID.
func (s *Notification) SetID(val uuid.UUID) {
s.ID = val
}
// SetKind sets the value of Kind.
func (s *Notification) SetKind(val NotificationKind) {
s.Kind = val
}
// SetOrganizationID sets the value of OrganizationID.
func (s *Notification) SetOrganizationID(val uuid.UUID) {
s.OrganizationID = val
}
// SetDeliveredAt sets the value of DeliveredAt.
func (s *Notification) SetDeliveredAt(val Timestamp) {
s.DeliveredAt = val
}
// SetReadAt sets the value of ReadAt.
func (s *Notification) SetReadAt(val NilTimestamp) {
s.ReadAt = val
}
// SetContent sets the value of Content.
func (s *Notification) SetContent(val NilNotificationContent) {
s.Content = val
}
// The text of a notification as the current source shows it to the recipient now. It is computed on
// every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it
// from the next read. It holds no contact, no score, and no result of an assessment.
// Ref: #/components/schemas/NotificationContent
type NotificationContent struct {
// Short heading in Russian.
Title string `json:"title"`
// One or two sentences in Russian. Plain text, never markup.
Summary string `json:"summary"`
// Same-origin absolute path of the screen that the notification opens, or null when there is none. It
// has no origin, query, fragment, or escape; a client opens it only as a path of its own router.
LinkPath NilString `json:"link_path"`
}
// GetTitle returns the value of Title.
func (s *NotificationContent) GetTitle() string {
return s.Title
}
// GetSummary returns the value of Summary.
func (s *NotificationContent) GetSummary() string {
return s.Summary
}
// GetLinkPath returns the value of LinkPath.
func (s *NotificationContent) GetLinkPath() NilString {
return s.LinkPath
}
// SetTitle sets the value of Title.
func (s *NotificationContent) SetTitle(val string) {
s.Title = val
}
// SetSummary sets the value of Summary.
func (s *NotificationContent) SetSummary(val string) {
s.Summary = val
}
// SetLinkPath sets the value of LinkPath.
func (s *NotificationContent) SetLinkPath(val NilString) {
s.LinkPath = val
}
// Which event put the notification into the inbox. The inbox stores a reference to the event, never
// its text.
//
// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform
// delivery state of the invitation: it does not depend on any email, and a failed or missing email
// never blocks it. The invitation operations are planned; no invitation produces a notification
// yet.
// - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility
// check, the list, and the read state). It has no product meaning, needs no action, and is never
// produced by a user action.
//
// Adding a value is a contract change; a client shows an unknown kind with the generic text of an item
// without content.
// Ref: #/components/schemas/NotificationKind
type NotificationKind string
const (
NotificationKindInvitationDelivered NotificationKind = "invitation_delivered"
NotificationKindSynthetic NotificationKind = "synthetic"
)
// AllValues returns all NotificationKind values.
func (NotificationKind) AllValues() []NotificationKind {
return []NotificationKind{
NotificationKindInvitationDelivered,
NotificationKindSynthetic,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s NotificationKind) MarshalText() ([]byte, error) {
switch s {
case NotificationKindInvitationDelivered:
return []byte(s), nil
case NotificationKindSynthetic:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *NotificationKind) UnmarshalText(data []byte) error {
switch NotificationKind(data) {
case NotificationKindInvitationDelivered:
*s = NotificationKindInvitationDelivered
return nil
case NotificationKindSynthetic:
*s = NotificationKindSynthetic
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// One page of the inbox, newest delivery first.
// Ref: #/components/schemas/NotificationList
type NotificationList struct {
// Items of the page.
Items []Notification `json:"items"`
Page PageInfo `json:"page"`
}
// GetItems returns the value of Items.
func (s *NotificationList) GetItems() []Notification {
return s.Items
}
// GetPage returns the value of Page.
func (s *NotificationList) GetPage() PageInfo {
return s.Page
}
// SetItems sets the value of Items.
func (s *NotificationList) SetItems(val []Notification) {
s.Items = val
}
// SetPage sets the value of Page.
func (s *NotificationList) SetPage(val PageInfo) {
s.Page = val
}
// NotificationListHeaders wraps NotificationList with response headers.
type NotificationListHeaders struct {
CacheControl CacheControlNoStore
Response NotificationList
}
// GetCacheControl returns the value of CacheControl.
func (s *NotificationListHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *NotificationListHeaders) GetResponse() NotificationList {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *NotificationListHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *NotificationListHeaders) SetResponse(val NotificationList) {
s.Response = val
}
func (*NotificationListHeaders) listMyNotificationsRes() {}
func (*NotificationListHeaders) listOrganizationNotificationsRes() {}
// The read state of one item after a mark. It carries no content, so marking never reads the source.
// Ref: #/components/schemas/NotificationReadReceipt
type NotificationReadReceipt struct {
// Identifier of the marked item.
ID uuid.UUID `json:"id"`
ReadAt Timestamp `json:"read_at"`
}
// GetID returns the value of ID.
func (s *NotificationReadReceipt) GetID() uuid.UUID {
return s.ID
}
// GetReadAt returns the value of ReadAt.
func (s *NotificationReadReceipt) GetReadAt() Timestamp {
return s.ReadAt
}
// SetID sets the value of ID.
func (s *NotificationReadReceipt) SetID(val uuid.UUID) {
s.ID = val
}
// SetReadAt sets the value of ReadAt.
func (s *NotificationReadReceipt) SetReadAt(val Timestamp) {
s.ReadAt = val
}
// NotificationReadReceiptHeaders wraps NotificationReadReceipt with response headers.
type NotificationReadReceiptHeaders struct {
CacheControl CacheControlNoStore
Response NotificationReadReceipt
}
// GetCacheControl returns the value of CacheControl.
func (s *NotificationReadReceiptHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *NotificationReadReceiptHeaders) GetResponse() NotificationReadReceipt {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *NotificationReadReceiptHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *NotificationReadReceiptHeaders) SetResponse(val NotificationReadReceipt) {
s.Response = val
}
func (*NotificationReadReceiptHeaders) markMyNotificationReadRes() {}
func (*NotificationReadReceiptHeaders) markOrganizationNotificationReadRes() {}
// Numeric answer in the unit of the item. Two answers are equal when their decoded values are
// numerically equal, so 254 and 254.0 are the same answer.
// Ref: #/components/schemas/NumberAnswer
@@ -30507,6 +30932,8 @@ func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {}
func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {}
func (*TooManyRequestsHeaders) hideOrganizationRes() {}
func (*TooManyRequestsHeaders) loginRes() {}
func (*TooManyRequestsHeaders) markMyNotificationReadRes() {}
func (*TooManyRequestsHeaders) markOrganizationNotificationReadRes() {}
func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {}
func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {}
func (*TooManyRequestsHeaders) registerAccountRes() {}
@@ -93,12 +93,16 @@ var operationRolesSessionCookie = map[string][]string{
ListMyEvidenceOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyNotificationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
ListOrganizationNotificationsOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
@@ -156,6 +160,8 @@ var operationRolesSessionCsrf = map[string][]string{
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
@@ -1173,6 +1173,27 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyNotifications implements ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (ListMyNotificationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
@@ -1278,6 +1299,27 @@ type Handler interface {
//
// GET /api/v1/organizations/{org_id}/needs
ListOrganizationNeeds(ctx context.Context, params ListOrganizationNeedsParams) (ListOrganizationNeedsRes, error)
// ListOrganizationNotifications implements ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (ListOrganizationNotificationsRes, error)
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -1312,6 +1354,49 @@ type Handler interface {
//
// DELETE /api/v1/identity/sessions/current
Logout(ctx context.Context) (LogoutRes, error)
// MarkMyNotificationRead implements MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (MarkMyNotificationReadRes, error)
// MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (MarkOrganizationNotificationReadRes, error)
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -1585,6 +1670,15 @@ type Handler interface {
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -1600,7 +1694,10 @@ type Handler interface {
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -1301,6 +1301,30 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyNotifications implements ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
func (UnimplementedHandler) ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (r ListMyNotificationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
@@ -1421,6 +1445,30 @@ func (UnimplementedHandler) ListOrganizationNeeds(ctx context.Context, params Li
return r, ht.ErrNotImplemented
}
// ListOrganizationNotifications implements ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
func (UnimplementedHandler) ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (r ListOrganizationNotificationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -1461,6 +1509,55 @@ func (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) {
return r, ht.ErrNotImplemented
}
// MarkMyNotificationRead implements MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
func (UnimplementedHandler) MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (r MarkMyNotificationReadRes, _ error) {
return r, ht.ErrNotImplemented
}
// MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
func (UnimplementedHandler) MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (r MarkOrganizationNotificationReadRes, _ error) {
return r, ht.ErrNotImplemented
}
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -1761,6 +1858,15 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -1776,7 +1882,10 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -11427,6 +11427,30 @@ func (s *ListMyInvitationsUnauthorized) Validate() error {
return nil
}
func (s *ListMyNotificationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyNotificationsForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyNotificationsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyOrganizationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -11555,6 +11579,38 @@ func (s *ListOrganizationNeedsUnauthorized) Validate() error {
return nil
}
func (s *ListOrganizationNotificationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *LoginBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -11668,6 +11724,70 @@ func (s *LogoutNoContent) Validate() error {
return nil
}
func (s *MarkMyNotificationReadBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MatchAppliedConditions) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -13378,6 +13498,8 @@ func (s MatchUnknownReason) Validate() error {
return nil
case "no_response_history":
return nil
case "percentile_not_computed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -16179,6 +16301,262 @@ func (s NewPassword) Validate() error {
return nil
}
func (s *Notification) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if err := func() error {
if value, ok := s.Content.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "content",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationContent) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 120,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Title)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "title",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 500,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Summary)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "summary",
Error: err,
})
}
if err := func() error {
if value, ok := s.LinkPath.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 256,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^/[A-Za-z0-9/_-]{0,255}$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "link_path",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s NotificationKind) Validate() error {
switch s {
case "invitation_delivered":
return nil
case "synthetic":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *NotificationList) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if s.Items == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 100,
MaxLengthSet: true,
}).ValidateLength(len(s.Items)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Items {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "items",
Error: err,
})
}
if err := func() error {
if err := s.Page.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "page",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationListHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationReadReceiptHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NumberAnswer) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -36,9 +36,9 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
apiadapter.GetOrganizationInvitationContactsOperation: {},
apiadapter.WithdrawOrganizationInvitationOperation: {},
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
// The match search contract requires an active owner membership. The
// operation has no handler yet; classifying it here keeps it closed to
// every other role when the handler arrives.
// The match search requires an active owner membership: the minimal
// milestone grants a membership by itself no tenant right, and the usecase
// repeats the owner check inside its transaction.
apiadapter.SearchOrganizationMatchesOperation: {},
}
@@ -53,6 +53,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T)
// the owner-only capability does not apply to that operation.
apiadapter.GetOrganizationCandidateCardOperation,
apiadapter.GetOrganizationCandidateEvidenceOperation,
// The inbox runs the membership check in the read transaction for any role.
apiadapter.ListOrganizationNotificationsOperation,
apiadapter.MarkOrganizationNotificationReadOperation,
apiadapter.HideOrganizationOperation,
apiadapter.UnhideOrganizationOperation,
apiadapter.RevokeMyOrganizationContactConsentOperation,
@@ -111,6 +114,13 @@ func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testi
}
}
// organizationNotificationPaths are the inbox operations of one organization,
// which check the membership inside their own transaction.
var organizationNotificationPaths = map[string]string{
"ListOrganizationNotifications": "/api/v1/organizations/{org_id}/notifications",
"MarkOrganizationNotificationRead": "/api/v1/organizations/{org_id}/notifications/{notification_id}/read",
}
func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
const bundlePath = "../../../../../api/core/openapi.bundle.yml"
data, err := os.ReadFile(bundlePath)
@@ -137,6 +147,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
seenExceptions := make(map[string]bool, len(candidateExceptions))
seenCardRead := false
seenEvidenceRead := false
seenNotifications := map[string]bool{}
for path, methods := range document.Paths {
for _, operation := range methods {
if operation.OperationID == "" {
@@ -170,6 +181,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
seenEvidenceRead = true
continue
}
// The inbox of one organization authorizes any active membership and
// the recipient together with the read, inside the read transaction;
// the owner-only capability does not apply.
if notificationPath, ok := organizationNotificationPaths[operation.OperationID]; ok && notificationPath == path {
seenNotifications[operation.OperationID] = true
continue
}
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
seenExceptions[operation.OperationID] = true
@@ -194,6 +212,11 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
if !seenEvidenceRead {
t.Error("transaction-authorized candidate evidence read is absent or moved")
}
for operation := range organizationNotificationPaths {
if !seenNotifications[operation] {
t.Errorf("transaction-authorized inbox operation %s is absent or moved", operation)
}
}
}
type companyContextAuthenticator struct {
@@ -0,0 +1,127 @@
package httpadapter
import (
"slices"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
)
// The four inbox operations follow the project conventions: the session
// cookie for a read, the session and the CSRF token for a mark, no-store on
// every success, the shared cursor parameters, the anti-enumeration 404 on
// everything keyed by an identifier, and no new problem code.
func TestNotificationOperationsFollowTheConventions(t *testing.T) {
spec := parsePublicContract(t)
for _, test := range []struct {
id string
path string
reads bool
parameters []string
statuses []string
absent []string
}{
{id: "ListMyNotifications", path: "/api/v1/me/notifications", reads: true,
parameters: []string{"PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403"}, absent: []string{"404"}},
{id: "ListOrganizationNotifications", path: "/api/v1/organizations/{org_id}/notifications", reads: true,
parameters: []string{"OrganizationId", "PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403", "404"}},
{id: "MarkMyNotificationRead", path: "/api/v1/me/notifications/{notification_id}/read",
parameters: []string{"NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}},
{id: "MarkOrganizationNotificationRead", path: "/api/v1/organizations/{org_id}/notifications/{notification_id}/read",
parameters: []string{"OrganizationId", "NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}},
} {
t.Run(test.id, func(t *testing.T) {
operation := operationByID(t, spec, test.id)
if spec.Paths[test.path] == nil {
t.Fatalf("the contract has no path %s", test.path)
}
if !slices.Contains(operation.Tags, "notification") {
t.Errorf("%s is not in the notification tag", test.id)
}
if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") == test.reads {
t.Errorf("%s security = %v, want the session cookie and a CSRF token only for a mark", test.id, operation.Security)
}
for _, status := range append(test.statuses, "default") {
if operation.Responses[status] == nil {
t.Errorf("%s does not declare %s", test.id, status)
}
}
for _, status := range test.absent {
if operation.Responses[status] != nil {
t.Errorf("%s declares %s", test.id, status)
}
}
if success := operation.Responses["200"]; success == nil || success.Headers["Cache-Control"] == nil {
t.Errorf("%s does not mark its 200 response no-store", test.id)
}
if operation.RequestBody != nil {
t.Errorf("%s takes a body: the item and the recipient come from the path and the session", test.id)
}
names := make([]string, 0, len(operation.Parameters))
for _, parameter := range operation.Parameters {
names = append(names, parameterName(parameter))
}
if !slices.Equal(names, test.parameters) {
t.Errorf("%s parameters = %v, want %v", test.id, names, test.parameters)
}
})
}
// An idempotent command by its effect needs no key.
for _, id := range []string{"MarkMyNotificationRead", "MarkOrganizationNotificationRead"} {
for _, parameter := range operationByID(t, spec, id).Parameters {
if parameterName(parameter) == "IdempotencyKey" || parameterName(parameter) == "IfMatch" {
t.Errorf("%s declares %s", id, parameterName(parameter))
}
}
}
codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"}))
for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "csrf_check_failed", "not_found", "rate_limited"} {
if !slices.Contains(codes, code) {
t.Errorf("ProblemCode has no %s", code)
}
}
}
// Every inbox object is closed and fully required, an item carries a
// reference and a state but no text of its own, and the text sits in the one
// nullable content object.
func TestNotificationSchemasAreClosedAndKeepTextInTheContent(t *testing.T) {
spec := parsePublicContract(t)
for _, pair := range []struct {
name string
want []string
}{
{"Notification", []string{"content", "delivered_at", "id", "kind", "organization_id", "read_at"}},
{"NotificationContent", []string{"link_path", "summary", "title"}},
{"NotificationList", []string{"items", "page"}},
{"NotificationReadReceipt", []string{"id", "read_at"}},
} {
schema := spec.Components.Schemas[pair.name]
if schema == nil {
t.Fatalf("the contract has no schema %s", pair.name)
}
if got := propertyNames(schema); !slices.Equal(got, pair.want) {
t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want)
}
if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
t.Errorf("%s accepts unknown properties", pair.name)
}
if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) {
t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want)
}
}
if got := enumValues(t, spec.Components.Schemas["NotificationKind"]); !slices.Equal(got, []string{"invitation_delivered", "synthetic"}) {
t.Errorf("NotificationKind = %v", got)
}
assertNoJSONFields(t, api.Notification{}, []string{
"title", "summary", "body", "text", "email", "name", "contact", "contacts", "recipient_user_id", "user_id", "candidate_id",
})
assertNoJSONFields(t, api.NotificationReadReceipt{}, []string{"content", "title", "summary", "kind", "organization_id"})
for _, property := range spec.Components.Schemas["NotificationList"].Properties {
if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 100) {
t.Errorf("NotificationList.items maxItems = %v, want the page limit 100", property.Schema.MaxItems)
}
}
}
@@ -30,6 +30,8 @@ type Handler struct {
assessmentSignals *AssessmentSignalHandler
privacy *PrivacyHandler
evidence *EvidenceHandler
matches *MatchHandler
notifications *NotificationHandler
problems *problem.Responder
}
@@ -99,6 +101,17 @@ func WithEvidence(evidence *EvidenceHandler) HandlerOption {
return func(handler *Handler) { handler.evidence = evidence }
}
// WithNotifications serves the inbox of the candidate cabinet and of one
// organization cabinet.
func WithNotifications(notifications *NotificationHandler) HandlerOption {
return func(handler *Handler) { handler.notifications = notifications }
}
// WithMatches serves the deterministic match search of the visible bank.
func WithMatches(matches *MatchHandler) HandlerOption {
return func(handler *Handler) { handler.matches = matches }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
@@ -0,0 +1,310 @@
package v1
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/matching"
)
// MatchOperations searches and ranks the organization-visible candidate bank.
type MatchOperations interface {
Search(ctx context.Context, request matching.Request) (matching.Result, error)
}
// MatchHandler binds the match search use case to the v1 API.
type MatchHandler struct {
operations MatchOperations
}
func NewMatchHandler(operations MatchOperations) *MatchHandler {
if operations == nil {
panic("v1.NewMatchHandler - operations must not be nil")
}
return &MatchHandler{operations: operations}
}
func (handler *Handler) SearchOrganizationMatches(
ctx context.Context,
request api.MatchSearchRequest,
params api.SearchOrganizationMatchesParams,
) (api.SearchOrganizationMatchesRes, error) {
if handler.matches == nil {
return handler.UnimplementedHandler.SearchOrganizationMatches(ctx, request, params)
}
return handler.matches.SearchOrganizationMatches(ctx, request, params)
}
func (handler *MatchHandler) SearchOrganizationMatches(
ctx context.Context,
request api.MatchSearchRequest,
params api.SearchOrganizationMatchesParams,
) (api.SearchOrganizationMatchesRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SearchOrganizationMatchesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, err := matchSearchCommand(principal.UserID, params.OrgID, request)
if err != nil {
return nil, err
}
result, err := handler.operations.Search(ctx, command)
if err != nil {
switch {
case errors.Is(err, matching.ErrForbidden), errors.Is(err, candidateview.ErrForbidden),
errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.SearchOrganizationMatchesForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, matching.ErrNeedNotFound):
return (*api.SearchOrganizationMatchesNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
}
return nil, err
}
return &api.MatchSearchResponseHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: matchSearchResponse(result),
}, nil
}
func matchSearchCommand(actorID, organizationID uuid.UUID, request api.MatchSearchRequest) (matching.Request, error) {
command := matching.Request{ActorID: actorID, OrganizationID: organizationID}
switch {
case request.IsMatchSearchByNeed():
byNeed := request.MatchSearchByNeed
command.Need = &matching.NeedReference{NeedID: byNeed.NeedID, RequirementsVersion: int64(byNeed.RequirementsVersion)}
if byNeed.Filters.Set {
command.Filters = matchFilters(byNeed.Filters.Value)
}
case request.IsMatchSearchByBank():
command.Filters = matchFilters(request.MatchSearchByBank.Filters)
default:
return matching.Request{}, errors.New("v1.matchSearchCommand - request variant is not known")
}
return command, nil
}
func matchFilters(filters api.MatchSearchFilters) matching.Filters {
result := matching.Filters{}
if filters.Specialization.Set {
value := domain.SpecializationCode(filters.Specialization.Value)
result.Specialization = &value
}
if filters.ConfirmedGrade.Set {
value := domain.GradeCode(filters.ConfirmedGrade.Value)
result.ConfirmedGrade = &value
}
if filters.ConfirmedCategory.Set {
category := filters.ConfirmedCategory.Value
result.ConfirmedCategory = &matching.GradeFilter{
Specialization: domain.SpecializationCode(category.Specialization), Grade: domain.GradeCode(category.Grade),
}
}
if filters.ConfirmationStatus.Set {
value := domain.CandidateViewConfirmationStatus(filters.ConfirmationStatus.Value)
result.ConfirmationStatus = &value
}
if filters.DeclaredGrade.Set {
value := domain.GradeCode(filters.DeclaredGrade.Value)
result.DeclaredGrade = &value
}
for _, tag := range filters.Stack {
result.Stack = append(result.Stack, domain.CandidateViewSkillCode(tag))
}
if filters.Conditions.Set {
conditions := &matching.Conditions{}
for _, format := range filters.Conditions.Value.WorkFormats {
conditions.WorkFormats = append(conditions.WorkFormats, domain.QuestionnaireWorkFormat(format))
}
if filters.Conditions.Value.SalaryCompatibility.Set {
value := domain.CandidateViewSalaryCompatibility(filters.Conditions.Value.SalaryCompatibility.Value)
conditions.SalaryCompatibility = &value
}
result.Conditions = conditions
}
return result
}
func matchSearchResponse(result matching.Result) api.MatchSearchResponse {
response := api.MatchSearchResponse{
Source: matchSearchSource(result.Source),
Truncated: result.Truncated,
Groups: api.MatchSearchGroups{
Main: make([]api.MatchConfirmedCandidate, 0, len(result.Main)),
Near: make([]api.MatchConfirmedCandidate, 0, len(result.Near)),
Unconfirmed: make([]api.MatchUnconfirmedCandidate, 0, len(result.Unconfirmed)),
},
}
for _, entry := range result.Main {
response.Groups.Main = append(response.Groups.Main, matchConfirmedCandidate(entry))
}
for _, entry := range result.Near {
response.Groups.Near = append(response.Groups.Near, matchConfirmedCandidate(entry))
}
for _, entry := range result.Unconfirmed {
response.Groups.Unconfirmed = append(response.Groups.Unconfirmed, matchUnconfirmedCandidate(entry))
}
return response
}
func matchSearchSource(source matching.Source) api.MatchSearchSource {
var response api.MatchSearchSource
if source.Need != nil {
response.SetMatchSearchNeedSource(api.MatchSearchNeedSource{
Kind: api.MatchSearchNeedSourceKindNeed, NeedID: source.Need.NeedID,
RequirementsVersion: api.NeedVersion(source.Need.RequirementsVersion),
})
return response
}
response.SetMatchSearchBankSource(api.MatchSearchBankSource{
Kind: api.MatchSearchBankSourceKindBank, Filters: matchAppliedFilters(source.Filters),
})
return response
}
// matchAppliedFilters writes every key, with null for a filter that was not
// asked for, so the result stays tied to its exact basis.
func matchAppliedFilters(filters matching.Filters) api.MatchAppliedFilters {
var applied api.MatchAppliedFilters
applied.Specialization.SetToNull()
applied.ConfirmedGrade.SetToNull()
applied.ConfirmedCategory.SetToNull()
applied.ConfirmationStatus.SetToNull()
applied.DeclaredGrade.SetToNull()
applied.Conditions.SetToNull()
if filters.Specialization != nil {
applied.Specialization.SetTo(api.SpecializationCode(*filters.Specialization))
}
if filters.ConfirmedGrade != nil {
applied.ConfirmedGrade.SetTo(api.GradeCode(*filters.ConfirmedGrade))
}
if filters.ConfirmedCategory != nil {
applied.ConfirmedCategory.SetTo(api.MatchGradeFilter{
Specialization: api.SpecializationCode(filters.ConfirmedCategory.Specialization),
Grade: api.GradeCode(filters.ConfirmedCategory.Grade),
})
}
if filters.ConfirmationStatus != nil {
applied.ConfirmationStatus.SetTo(api.MatchConfirmationStatus(*filters.ConfirmationStatus))
}
if filters.DeclaredGrade != nil {
applied.DeclaredGrade.SetTo(api.GradeCode(*filters.DeclaredGrade))
}
for _, tag := range filters.Stack {
applied.Stack = append(applied.Stack, api.MatchSearchStackTag(tag))
}
if filters.Conditions != nil {
conditions := api.MatchAppliedConditions{}
conditions.SalaryCompatibility.SetToNull()
for _, format := range filters.Conditions.WorkFormats {
conditions.WorkFormats = append(conditions.WorkFormats, api.WorkFormat(format))
}
if filters.Conditions.SalaryCompatibility != nil {
conditions.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*filters.Conditions.SalaryCompatibility))
}
applied.Conditions.SetTo(conditions)
}
return applied
}
func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate {
candidate := api.MatchConfirmedCandidate{
CandidateHandle: api.CandidateHandle(entry.CandidateHandle),
Specialization: api.SpecializationCode(entry.Specialization),
ConfirmationStatus: api.MatchConfirmedCandidateConfirmationStatusConfirmed,
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
candidate.DeclaredGrade = matchDeclaredGrade(entry.DeclaredGrade)
if entry.Category != nil {
candidate.Category = api.MatchCategory{
Specialization: api.SpecializationCode(entry.Category.Specialization), Grade: api.GradeCode(entry.Category.Grade),
}
candidate.Strength = api.MatchStrength(entry.Category.Strength)
}
components := api.MatchConfirmedComponents{
Fit: api.MatchScore(entry.Components.Fit), Coverage: api.MatchScore(entry.Components.Coverage),
Domain: api.MatchScore(entry.Components.Domain), Semantics: api.MatchScore(entry.Components.Semantics),
Competition: api.MatchScore(entry.Components.Competition), Freshness: api.MatchScore(entry.Components.Freshness),
Responsiveness: api.MatchScore(entry.Components.Responsiveness), RankScore: api.MatchScore(entry.Components.RankScore),
}
components.Percentile.SetToNull()
if entry.Components.Percentile != nil {
components.Percentile.SetTo(*entry.Components.Percentile)
}
candidate.Components = components
return candidate
}
func matchUnconfirmedCandidate(entry matching.Entry) api.MatchUnconfirmedCandidate {
return api.MatchUnconfirmedCandidate{
CandidateHandle: api.CandidateHandle(entry.CandidateHandle),
Specialization: api.SpecializationCode(entry.Specialization),
ConfirmationStatus: api.MatchUnconfirmedCandidateConfirmationStatusUnconfirmed,
DeclaredGrade: matchDeclaredGrade(entry.DeclaredGrade),
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
Components: api.MatchUnconfirmedComponents{Fit: entry.Components.Fit, Coverage: entry.Components.Coverage},
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
}
func matchDeclaredGrade(grade *domain.GradeCode) api.NilGradeCode {
var declared api.NilGradeCode
declared.SetToNull()
if grade != nil {
declared.SetTo(api.GradeCode(*grade))
}
return declared
}
func matchPublicContext(context matching.PublicContext) api.MatchPublicContext {
var response api.MatchPublicContext
response.ExperienceBand.SetToNull()
response.SalaryCompatibility.SetToNull()
if len(context.Stack) > 0 {
response.Stack = make(api.MatchPublicStack, 0, len(context.Stack))
for _, tag := range context.Stack {
response.Stack = append(response.Stack, api.MatchSearchStackTag(tag))
}
}
if context.ExperienceBand != nil {
response.ExperienceBand.SetTo(api.CandidateExperienceBand(*context.ExperienceBand))
}
if len(context.WorkFormats) > 0 {
response.WorkFormats = make([]api.WorkFormat, 0, len(context.WorkFormats))
for _, format := range context.WorkFormats {
response.WorkFormats = append(response.WorkFormats, api.WorkFormat(format))
}
}
if context.SalaryCompatibility != nil {
response.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*context.SalaryCompatibility))
}
return response
}
func matchEvidenceSummary(items []matching.EvidenceItem) api.MatchEvidenceSummary {
summary := make(api.MatchEvidenceSummary, 0, len(items))
for _, item := range items {
summary = append(summary, api.MatchEvidenceSummaryItem{
Code: api.MatchEvidenceCode(item.Code), State: api.MatchEvidenceState(item.State),
})
}
return summary
}
func matchUnknownFlags(flags []matching.UnknownFlag) api.MatchUnknownFlags {
response := make(api.MatchUnknownFlags, 0, len(flags))
for _, flag := range flags {
response = append(response, api.MatchUnknownFlag{
Component: api.MatchUnknownComponent(flag.Component), Reason: api.MatchUnknownReason(flag.Reason),
})
}
return response
}
@@ -0,0 +1,221 @@
package v1
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/matching"
)
type matchOperationsStub struct {
result matching.Result
err error
request matching.Request
}
func (stub *matchOperationsStub) Search(_ context.Context, request matching.Request) (matching.Result, error) {
stub.request = request
return stub.result, stub.err
}
func TestSearchOrganizationMatchesMapsABankRequestAndEchoesTheNormalizedFilters(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
stub := &matchOperationsStub{}
handler := NewMatchHandler(stub)
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{Filters: api.MatchSearchFilters{
Specialization: api.NewOptSpecializationCode(api.SpecializationCodeBackend),
ConfirmedCategory: api.NewOptMatchGradeFilter(api.MatchGradeFilter{Specialization: api.SpecializationCodeBackend, Grade: api.GradeCodeMiddle}),
Stack: []api.MatchSearchStackTag{api.MatchSearchStackTagPostgresql, api.MatchSearchStackTagGo},
Conditions: api.NewOptMatchSearchConditions(api.MatchSearchConditions{
WorkFormats: []api.WorkFormat{api.WorkFormatRemote},
SalaryCompatibility: api.NewOptCandidateSalaryCompatibility(api.CandidateSalaryCompatibilityCompatible),
}),
}})
stub.result.Truncated = false
stub.result.Source = matching.Source{Filters: matching.Filters{
Specialization: new(domain.SpecializationCode), Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo},
}}
*stub.result.Source.Filters.Specialization = domain.SpecializationBackend
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
if stub.request.ActorID != userID || stub.request.OrganizationID != organizationID || stub.request.Need != nil {
t.Fatalf("command scope = %+v, want the session actor and the path organization", stub.request)
}
filters := stub.request.Filters
if filters.Specialization == nil || *filters.Specialization != domain.SpecializationBackend ||
filters.ConfirmedCategory == nil || filters.ConfirmedCategory.Grade != domain.GradeMiddle || filters.ConfirmedGrade != nil ||
filters.ConfirmationStatus != nil || filters.DeclaredGrade != nil || len(filters.Stack) != 2 ||
filters.Conditions == nil || len(filters.Conditions.WorkFormats) != 1 || filters.Conditions.SalaryCompatibility == nil {
t.Fatalf("mapped filters = %+v", filters)
}
body, ok := response.(*api.MatchSearchResponseHeaders)
if !ok || body.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("response = %#v, want a no-store result", response)
}
encoded, err := json.Marshal(body.Response)
if err != nil {
t.Fatalf("encode response: %v", err)
}
want := `{"source":{"kind":"bank","filters":{"specialization":"backend","confirmed_grade":null,"confirmed_category":null,` +
`"confirmation_status":null,"declared_grade":null,"stack":["go"],"conditions":null}},"groups":{"main":[],"near":[],"unconfirmed":[]},"truncated":false}`
if string(encoded) != want {
t.Fatalf("response = %s, want %s", encoded, want)
}
}
func TestSearchOrganizationMatchesMapsANeedRequestAndKeepsUnconfirmedEntriesStrict(t *testing.T) {
userID, organizationID, needID := uuid.New(), uuid.New(), uuid.New()
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
junior := domain.GradeJunior
stub := &matchOperationsStub{result: matching.Result{
Source: matching.Source{Need: &matching.NeedReference{NeedID: needID, RequirementsVersion: 3}},
Unconfirmed: []matching.Entry{{
CandidateHandle: handle, Specialization: domain.SpecializationNetworkEngineer, DeclaredGrade: &junior,
Components: matching.Components{Fit: 0.3125, Coverage: 0.25},
UnknownFlags: []matching.UnknownFlag{
{Component: matching.UnknownAssessment, Reason: matching.ReasonNoConfirmationForSpecialization},
},
EvidenceSummary: []matching.EvidenceItem{{Code: matching.EvidenceDeclaredGrade, State: matching.EvidenceStateDeclaredOnly}},
}},
}}
handler := NewMatchHandler(stub)
var request api.MatchSearchRequest
request.SetMatchSearchByNeed(api.MatchSearchByNeed{NeedID: needID, RequirementsVersion: 3})
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
if stub.request.Need == nil || stub.request.Need.NeedID != needID || stub.request.Need.RequirementsVersion != 3 {
t.Fatalf("need reference = %+v", stub.request.Need)
}
body, ok := response.(*api.MatchSearchResponseHeaders)
if !ok {
t.Fatalf("response = %#v", response)
}
encoded, err := json.Marshal(body.Response.Groups.Unconfirmed)
if err != nil {
t.Fatalf("encode response: %v", err)
}
want := `[{"candidate_handle":"` + handle + `","specialization":"network_engineer","confirmation_status":"unconfirmed","declared_grade":"junior",` +
`"category":null,"strength":null,"public_context":{"stack":null,"experience_band":null,"work_formats":null,"salary_compatibility":null},` +
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"components":{"fit":0.3125,"coverage":0.25},` +
`"unknown_flags":[{"component":"assessment","reason":"no_confirmation_for_specialization"}]}]`
if string(encoded) != want {
t.Fatalf("unconfirmed entries = %s\nwant %s", encoded, want)
}
for _, forbidden := range []string{"percentile", "rank_score", "theta", "freshness"} {
if strings.Contains(string(encoded), forbidden) {
t.Fatalf("an unconfirmed entry exposes %q", forbidden)
}
}
}
func TestSearchOrganizationMatchesMapsAConfirmedEntryWithANullPercentile(t *testing.T) {
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stub := &matchOperationsStub{result: matching.Result{Main: []matching.Entry{{
CandidateHandle: handle, Specialization: domain.SpecializationBackend,
Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, Strength: domain.CandidateViewStrengthStrong},
Components: matching.Components{
Fit: 0.5, Coverage: 0.5, Domain: 0.5, Semantics: 0.5, Freshness: 0.5, Responsiveness: 0.5, RankScore: 0.45125,
},
}}}}
response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""),
func() api.MatchSearchRequest {
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
return request
}(), api.SearchOrganizationMatchesParams{OrgID: uuid.New()})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response.Groups.Main)
if err != nil {
t.Fatalf("encode response: %v", err)
}
for _, want := range []string{
`"confirmation_status":"confirmed"`, `"declared_grade":null`, `"category":{"specialization":"backend","grade":"middle"}`, `"strength":"strong"`,
`"percentile":null`, `"competition":0`, `"rank_score":0.45125`,
} {
if !strings.Contains(string(encoded), want) {
t.Errorf("confirmed entry %s lacks %s", encoded, want)
}
}
}
func TestSearchOrganizationMatchesMapsFailuresToTheContractProblems(t *testing.T) {
userID := uuid.New()
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
params := api.SearchOrganizationMatchesParams{OrgID: uuid.New()}
stub := &matchOperationsStub{}
handler := NewMatchHandler(stub)
unauthenticated, err := handler.SearchOrganizationMatches(context.Background(), request, params)
if _, ok := unauthenticated.(*api.SearchOrganizationMatchesUnauthorized); err != nil || !ok {
t.Fatalf("no principal = %#v, %v, want 401", unauthenticated, err)
}
for name, test := range map[string]struct {
err error
want string
}{
"not an owner": {matching.ErrForbidden, "forbidden"},
"candidate account": {candidateview.ErrForbidden, "forbidden"},
"membership is not an owner": {outbound.ErrOrganizationManagerRequired, "forbidden"},
"no membership": {outbound.ErrOrganizationNotFound, "not_found"},
"unknown need": {matching.ErrNeedNotFound, "not_found"},
} {
stub.err = test.err
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params)
if err != nil {
t.Errorf("%s: error = %v", name, err)
continue
}
var got string
switch response.(type) {
case *api.SearchOrganizationMatchesForbidden:
got = "forbidden"
case *api.SearchOrganizationMatchesNotFound:
got = "not_found"
}
if got != test.want {
t.Errorf("%s = %T, want %s", name, response, test.want)
}
}
for _, unexpected := range []error{errors.New("storage failed"), matching.ErrPolicyUnavailable} {
stub.err = unexpected
if _, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params); err == nil {
t.Fatalf("an unexpected failure %v was answered as a client problem", unexpected)
}
}
}
func TestSearchOrganizationMatchesReportsATruncatedResultWithoutACount(t *testing.T) {
stub := &matchOperationsStub{result: matching.Result{Truncated: true}}
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""), request, api.SearchOrganizationMatchesParams{OrgID: uuid.New()})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response)
if err != nil {
t.Fatalf("encode response: %v", err)
}
if !strings.Contains(string(encoded), `"truncated":true`) || strings.Contains(string(encoded), "total") || strings.Contains(string(encoded), "count") {
t.Fatalf("response = %s, want the flag and no count", encoded)
}
}
@@ -0,0 +1,78 @@
package v1
import (
"encoding/base64"
"encoding/binary"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
const (
notificationCursorVersion = 1
notificationCursorBytes = 61
// maxNotificationCursorYear keeps the decoded time inside the range that
// PostgreSQL stores and that the contract's RFC 3339 timestamps print.
maxNotificationCursorYear = 9999
)
// encodeNotificationCursor binds a page position to the account and the
// organization context of the listing, so a cursor of another account or
// another cabinet fails as malformed instead of continuing a foreign list.
// A nil organization is the candidate cabinet.
func encodeNotificationCursor(recipientID uuid.UUID, organizationID *uuid.UUID, position outbound.NotificationInboxPosition) (string, error) {
at := position.OccurredAt.UTC()
if recipientID == uuid.Nil || position.EventID == uuid.Nil || at.IsZero() || at.Year() > maxNotificationCursorYear {
return "", errors.New("v1.encodeNotificationCursor - a recipient and a valid page position are required")
}
seconds, nanos := at.Unix(), at.Nanosecond()
if seconds < 0 {
return "", errors.New("v1.encodeNotificationCursor - the page position predates the epoch")
}
if nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
return "", errors.New("v1.encodeNotificationCursor - the page position has no microsecond precision")
}
var value [notificationCursorBytes]byte
value[0] = notificationCursorVersion
copy(value[1:17], recipientID[:])
if organizationID != nil {
copy(value[17:33], organizationID[:])
}
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], position.EventID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
// decodeNotificationCursor reads a cursor made for the same account and
// cabinet by encodeNotificationCursor.
func decodeNotificationCursor(cursor string, recipientID uuid.UUID, organizationID *uuid.UUID) (outbound.NotificationInboxPosition, error) {
const location = "v1.decodeNotificationCursor"
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != notificationCursorBytes || recipientID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != notificationCursorVersion ||
uuid.UUID(value[1:17]) != recipientID {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor is invalid")
}
var scope uuid.UUID
if organizationID != nil {
scope = *organizationID
}
if uuid.UUID(value[17:33]) != scope {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor belongs to another cabinet")
}
seconds := binary.BigEndian.Uint64(value[33:41])
nanos := binary.BigEndian.Uint32(value[41:45])
eventID := uuid.UUID(value[45:61])
if seconds > uint64(1<<62) || nanos >= 1_000_000_000 || nanos%1_000 != 0 || eventID == uuid.Nil {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor position is invalid")
}
at := time.Unix(int64(seconds), int64(nanos)).UTC()
if at.IsZero() || at.Year() > maxNotificationCursorYear {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor timestamp is invalid")
}
return outbound.NotificationInboxPosition{OccurredAt: at, EventID: eventID}, nil
}
@@ -0,0 +1,277 @@
package v1
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const defaultNotificationLimit = 20
// NotificationOperations lists and marks the inbox of the authenticated
// account. The candidate cabinet and the cabinet of one organization share
// the operations; the request names which one.
type NotificationOperations interface {
List(ctx context.Context, request notification.InboxListRequest) (notification.InboxPage, error)
MarkRead(ctx context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error)
}
// NotificationHandler binds the inbox use cases to the v1 API.
type NotificationHandler struct {
operations NotificationOperations
}
func NewNotificationHandler(operations NotificationOperations) *NotificationHandler {
if operations == nil {
panic("v1.NewNotificationHandler - operations must not be nil")
}
return &NotificationHandler{operations: operations}
}
func (handler *Handler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.ListMyNotifications(ctx, params)
}
return handler.notifications.ListMyNotifications(ctx, params)
}
func (handler *Handler) MarkMyNotificationRead(ctx context.Context, params api.MarkMyNotificationReadParams) (api.MarkMyNotificationReadRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.MarkMyNotificationRead(ctx, params)
}
return handler.notifications.MarkMyNotificationRead(ctx, params)
}
func (handler *Handler) ListOrganizationNotifications(
ctx context.Context,
params api.ListOrganizationNotificationsParams,
) (api.ListOrganizationNotificationsRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.ListOrganizationNotifications(ctx, params)
}
return handler.notifications.ListOrganizationNotifications(ctx, params)
}
func (handler *Handler) MarkOrganizationNotificationRead(
ctx context.Context,
params api.MarkOrganizationNotificationReadParams,
) (api.MarkOrganizationNotificationReadRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.MarkOrganizationNotificationRead(ctx, params)
}
return handler.notifications.MarkOrganizationNotificationRead(ctx, params)
}
func (handler *NotificationHandler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
list, pointer := handler.list(ctx, principal.UserID, nil, params.Limit, params.Cursor)
if pointer != "" {
return (*api.ListMyNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := list()
switch {
case err == nil:
return page, nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.ListMyNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) ListOrganizationNotifications(
ctx context.Context,
params api.ListOrganizationNotificationsParams,
) (api.ListOrganizationNotificationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListOrganizationNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
organizationID := params.OrgID
list, pointer := handler.list(ctx, principal.UserID, &organizationID, params.Limit, params.Cursor)
if pointer != "" {
return (*api.ListOrganizationNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := list()
switch {
case err == nil:
return page, nil
case errors.Is(err, notification.ErrInboxEmailNotVerified):
return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.ListOrganizationNotificationsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) MarkMyNotificationRead(
ctx context.Context,
params api.MarkMyNotificationReadParams,
) (api.MarkMyNotificationReadRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.MarkMyNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
receipt, err := handler.mark(ctx, principal.UserID, nil, params.NotificationID)
switch {
case err == nil:
return receipt, nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.MarkMyNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrNotificationInboxEntryNotFound):
return (*api.MarkMyNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) MarkOrganizationNotificationRead(
ctx context.Context,
params api.MarkOrganizationNotificationReadParams,
) (api.MarkOrganizationNotificationReadRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.MarkOrganizationNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
organizationID := params.OrgID
receipt, err := handler.mark(ctx, principal.UserID, &organizationID, params.NotificationID)
switch {
case err == nil:
return receipt, nil
case errors.Is(err, notification.ErrInboxEmailNotVerified):
return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNotificationInboxEntryNotFound):
// A missing membership, an unknown organization, and an item that is
// not the caller's in this organization are one answer.
return (*api.MarkOrganizationNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
// list validates the page parameters and returns the deferred read, so the
// two list operations share the mapping of a page to the public type. A
// non-empty pointer names the invalid query parameter.
func (handler *NotificationHandler) list(
ctx context.Context,
recipientID uuid.UUID,
organizationID *uuid.UUID,
limitParam api.OptInt32,
cursorParam api.OptString,
) (func() (*api.NotificationListHeaders, error), string) {
limit, set := limitParam.Get()
if !set {
limit = defaultNotificationLimit
}
if limit < 1 || limit > outbound.MaxNotificationInboxPageSize {
return nil, "limit"
}
request := notification.InboxListRequest{RecipientUserID: recipientID, OrganizationID: organizationID, Limit: limit}
if cursor, set := cursorParam.Get(); set {
position, err := decodeNotificationCursor(cursor, recipientID, organizationID)
if err != nil {
return nil, "cursor"
}
request.After = &position
}
return func() (*api.NotificationListHeaders, error) {
const location = "NotificationHandler.list"
page, err := handler.operations.List(ctx, request)
if err != nil {
return nil, err
}
items := make([]api.Notification, 0, len(page.Items))
for _, item := range page.Items {
mapped, err := notificationResponse(item)
if err != nil {
return nil, fmt.Errorf("%s - map item: %w", location, err)
}
items = append(items, mapped)
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := outbound.NotificationInboxPositionOf(page.Items[len(page.Items)-1].Entry)
return encodeNotificationCursor(recipientID, organizationID, last)
})
if err != nil {
return nil, fmt.Errorf("%s - encode cursor: %w", location, err)
}
return &api.NotificationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.NotificationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}, ""
}
func (handler *NotificationHandler) mark(
ctx context.Context,
recipientID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
) (*api.NotificationReadReceiptHeaders, error) {
entry, err := handler.operations.MarkRead(ctx, notification.InboxMarkReadRequest{
RecipientUserID: recipientID, OrganizationID: organizationID, EventID: eventID,
})
if err != nil {
return nil, err
}
readAt, isRead := entry.ReadAt()
if !isRead {
return nil, errors.New("NotificationHandler.mark - a marked item has no read time")
}
return &api.NotificationReadReceiptHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.NotificationReadReceipt{ID: entry.EventID(), ReadAt: api.Timestamp(readAt)},
}, nil
}
func notificationResponse(item notification.InboxItem) (api.Notification, error) {
kind, ok := notificationKind(item.Entry.EventType())
if !ok {
return api.Notification{}, errors.New("v1.notificationResponse - the stored event type has no public kind")
}
response := api.Notification{
ID: item.Entry.EventID(), Kind: kind, OrganizationID: item.Entry.OrganizationID(),
DeliveredAt: api.Timestamp(item.Entry.OccurredAt()),
}
response.ReadAt.SetToNull()
if readAt, isRead := item.Entry.ReadAt(); isRead {
response.ReadAt.SetTo(api.Timestamp(readAt))
}
response.Content.SetToNull()
if item.Content != nil {
content := api.NotificationContent{Title: item.Content.Title(), Summary: item.Content.Summary()}
content.LinkPath.SetToNull()
if path := item.Content.LinkPath(); path != "" {
content.LinkPath.SetTo(path)
}
response.Content.SetTo(content)
}
return response, nil
}
func notificationKind(eventType domain.NotificationInboxEventType) (api.NotificationKind, bool) {
switch eventType {
case domain.NotificationInboxInvitationDelivered:
return api.NotificationKindInvitationDelivered, true
case domain.NotificationInboxSyntheticDelivered:
return api.NotificationKindSynthetic, true
default:
return "", false
}
}
@@ -0,0 +1,263 @@
package v1
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
type notificationOperationsStub struct {
page notification.InboxPage
entry domain.NotificationInboxEntry
err error
listRequest notification.InboxListRequest
markRequest notification.InboxMarkReadRequest
}
func (stub *notificationOperationsStub) List(_ context.Context, request notification.InboxListRequest) (notification.InboxPage, error) {
stub.listRequest = request
return stub.page, stub.err
}
func (stub *notificationOperationsStub) MarkRead(_ context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error) {
stub.markRequest = request
return stub.entry, stub.err
}
func notificationTestEntry(t *testing.T, recipientID, organizationID uuid.UUID, at time.Time) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID,
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID, OccurredAt: at,
})
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return entry
}
func TestListMyNotificationsMapsContentAndFallbackAndBindsTheCursor(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
at := time.Date(2026, 10, 9, 8, 30, 0, 123000, time.UTC)
withContent := notificationTestEntry(t, userID, organizationID, at)
content, err := notification.NewInboxContent("Тестовое уведомление", "Проверка доставки.", "/candidate/invitations")
if err != nil {
t.Fatalf("NewInboxContent() error = %v", err)
}
withoutContent := notificationTestEntry(t, userID, organizationID, at.Add(-time.Hour))
read, err := withoutContent.MarkRead(at)
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
stub := &notificationOperationsStub{page: notification.InboxPage{
Items: []notification.InboxItem{
{Entry: withContent, Content: &content},
{Entry: read, ContentUnavailable: true},
},
HasMore: true,
}}
handler := NewNotificationHandler(stub)
ctx := privacyHTTPContext(userID, "")
response, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(2)})
if err != nil {
t.Fatalf("ListMyNotifications() error = %v", err)
}
page, ok := response.(*api.NotificationListHeaders)
if !ok || page.CacheControl != api.CacheControlNoStoreNoStore || len(page.Response.Items) != 2 {
t.Fatalf("ListMyNotifications() = %#v, want a no-store page of two items", response)
}
if stub.listRequest.RecipientUserID != userID || stub.listRequest.OrganizationID != nil || stub.listRequest.Limit != 2 {
t.Fatalf("list request = %+v, want the session account in the candidate cabinet", stub.listRequest)
}
first, second := page.Response.Items[0], page.Response.Items[1]
if first.ID != withContent.EventID() || first.Kind != api.NotificationKindSynthetic || !first.ReadAt.Null {
t.Fatalf("first item = %+v, want an unread synthetic item", first)
}
if first.Content.Null || first.Content.Value.Title != "Тестовое уведомление" || first.Content.Value.LinkPath.Null ||
first.Content.Value.LinkPath.Value != "/candidate/invitations" {
t.Fatalf("first content = %+v, want the resolved text and link", first.Content)
}
if !second.Content.Null || second.ReadAt.Null {
t.Fatalf("second item = %+v, want no content and a read time", second)
}
if !page.Response.Page.HasMore || page.Response.Page.NextCursor.Null {
t.Fatalf("page info = %+v, want a next cursor", page.Response.Page)
}
// The cursor continues only the same account in the same cabinet.
next := page.Response.Page.NextCursor.Value
if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Cursor: api.NewOptString(next)}); err != nil {
t.Fatalf("ListMyNotifications(cursor) error = %v", err)
}
if stub.listRequest.After == nil || stub.listRequest.After.EventID != read.EventID() {
t.Fatalf("continuation = %+v, want the position of the last item", stub.listRequest.After)
}
foreign, err := handler.ListMyNotifications(privacyHTTPContext(uuid.New(), ""), api.ListMyNotificationsParams{Cursor: api.NewOptString(next)})
if err != nil {
t.Fatalf("ListMyNotifications(foreign cursor) error = %v", err)
}
if _, ok := foreign.(*api.ListMyNotificationsBadRequest); !ok {
t.Fatalf("ListMyNotifications(foreign cursor) = %#v, want 400", foreign)
}
// A cursor of the candidate cabinet cannot continue an organization cabinet.
crossed, err := handler.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{
OrgID: organizationID, Cursor: api.NewOptString(next),
})
if err != nil {
t.Fatalf("ListOrganizationNotifications(candidate cursor) error = %v", err)
}
if _, ok := crossed.(*api.ListOrganizationNotificationsBadRequest); !ok {
t.Fatalf("ListOrganizationNotifications(candidate cursor) = %#v, want 400", crossed)
}
for _, limit := range []int32{0, 101} {
bad, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(limit)})
if err != nil {
t.Fatalf("ListMyNotifications(limit %d) error = %v", limit, err)
}
if _, ok := bad.(*api.ListMyNotificationsBadRequest); !ok {
t.Fatalf("ListMyNotifications(limit %d) = %#v, want 400", limit, bad)
}
}
}
func TestNotificationOperationsMapAccessFailuresWithoutRevealingObjects(t *testing.T) {
userID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New()
ctx := privacyHTTPContext(userID, "")
for _, test := range []struct {
name string
err error
list func(*NotificationHandler) (any, error)
mark func(*NotificationHandler) (any, error)
want []any
code api.ProblemCode
}{
{
name: "an account of the other scenario",
err: notification.ErrInboxForbidden,
list: func(h *NotificationHandler) (any, error) {
return h.ListMyNotifications(ctx, api.ListMyNotificationsParams{})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID})
},
want: []any{(*api.ListMyNotificationsForbidden)(nil), (*api.MarkMyNotificationReadForbidden)(nil)},
},
{
name: "no active membership",
err: outbound.ErrOrganizationNotFound,
list: func(h *NotificationHandler) (any, error) {
return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID})
},
want: []any{(*api.ListOrganizationNotificationsNotFound)(nil), (*api.MarkOrganizationNotificationReadNotFound)(nil)},
},
{
name: "an employer whose email is not confirmed",
err: notification.ErrInboxEmailNotVerified,
list: func(h *NotificationHandler) (any, error) {
return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID})
},
want: []any{(*api.ListOrganizationNotificationsForbidden)(nil), (*api.MarkOrganizationNotificationReadForbidden)(nil)},
code: api.ProblemCodeEmailNotVerified,
},
{
name: "an item of another account",
err: outbound.ErrNotificationInboxEntryNotFound,
mark: func(h *NotificationHandler) (any, error) {
return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID})
},
want: []any{nil, (*api.MarkMyNotificationReadNotFound)(nil)},
},
} {
t.Run(test.name, func(t *testing.T) {
handler := NewNotificationHandler(&notificationOperationsStub{err: test.err})
if test.list != nil {
got, err := test.list(handler)
if err != nil || !sameResponseType(got, test.want[0]) {
t.Fatalf("list = %#v, %v, want %T", got, err, test.want[0])
}
requireProblemCode(t, got, test.code)
}
got, err := test.mark(handler)
if err != nil || !sameResponseType(got, test.want[1]) {
t.Fatalf("mark = %#v, %v, want %T", got, err, test.want[1])
}
requireProblemCode(t, got, test.code)
})
}
handler := NewNotificationHandler(&notificationOperationsStub{err: errors.New("database is down")})
if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{}); err == nil {
t.Fatal("ListMyNotifications() hid an unexpected failure")
}
response, err := handler.ListMyNotifications(context.Background(), api.ListMyNotificationsParams{})
if err != nil {
t.Fatalf("ListMyNotifications(no session) error = %v", err)
}
if _, ok := response.(*api.ListMyNotificationsUnauthorized); !ok {
t.Fatalf("ListMyNotifications(no session) = %#v, want 401", response)
}
}
func sameResponseType(got, want any) bool {
return want != nil && reflect.TypeOf(got) == reflect.TypeOf(want)
}
func TestMarkNotificationReadReturnsTheFirstReadTimeOnly(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
readAt := time.Date(2026, 10, 9, 8, 45, 0, 0, time.UTC)
entry, err := notificationTestEntry(t, userID, organizationID, readAt.Add(-time.Hour)).MarkRead(readAt)
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
stub := &notificationOperationsStub{entry: entry}
handler := NewNotificationHandler(stub)
response, err := handler.MarkOrganizationNotificationRead(privacyHTTPContext(userID, ""),
api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: entry.EventID()})
if err != nil {
t.Fatalf("MarkOrganizationNotificationRead() error = %v", err)
}
receipt, ok := response.(*api.NotificationReadReceiptHeaders)
if !ok || receipt.CacheControl != api.CacheControlNoStoreNoStore || receipt.Response.ID != entry.EventID() ||
!time.Time(receipt.Response.ReadAt).Equal(readAt) {
t.Fatalf("MarkOrganizationNotificationRead() = %#v, want the receipt of the first read", response)
}
if stub.markRequest.RecipientUserID != userID || stub.markRequest.OrganizationID == nil || *stub.markRequest.OrganizationID != organizationID {
t.Fatalf("mark request = %+v, want the session account in the path organization", stub.markRequest)
}
}
func requireProblemCode(t *testing.T, response any, want api.ProblemCode) {
t.Helper()
if want == "" {
return
}
var got api.ProblemCode
switch typed := response.(type) {
case *api.ListOrganizationNotificationsForbidden:
got = typed.Code
case *api.MarkOrganizationNotificationReadForbidden:
got = typed.Code
default:
t.Fatalf("response %T carries no problem code", response)
}
if got != want {
t.Fatalf("problem code = %s, want %s", got, want)
}
}
@@ -194,6 +194,17 @@ func (repository companyQuotaRepository) reserveNewCardView(
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error {
const location = "companyQuotaRepository.LockOrganization"
if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - organization was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
}
return nil
}
func (repository companyQuotaRepository) lockAndCheckSnapshot(
ctx context.Context,
location string,
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
@@ -117,6 +118,80 @@ func (repository evidenceRepository) ListOrganizationFacts(
return facts, nil
}
func (repository evidenceRepository) ListOrganizationFactsBatch(
ctx context.Context,
organizationID uuid.UUID,
requests []outbound.EvidenceCandidateCategories,
) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) {
const location = "evidenceRepository.ListOrganizationFactsBatch"
if organizationID == uuid.Nil {
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidEvidence)
}
var candidateIDs []pgtype.UUID
var pairs []string
for _, request := range requests {
if request.CandidateID == uuid.Nil {
return nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidEvidence)
}
requested, err := evidenceCategoryPairs(request.Categories)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
for _, pair := range requested {
candidateIDs = append(candidateIDs, pgUUID(request.CandidateID))
pairs = append(pairs, pair)
}
}
facts := make(map[uuid.UUID][]domain.EvidenceOrganizationFact, len(requests))
if len(pairs) == 0 {
return facts, nil
}
rows, err := repository.queries.ListOrganizationVisibleEvidenceBatch(ctx, sqlc.ListOrganizationVisibleEvidenceBatchParams{
CandidateIds: candidateIDs, Categories: pairs, OrganizationID: pgUUID(organizationID),
})
if err != nil {
return nil, fmt.Errorf("%s - select permitted facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, row := range rows {
candidateID, err := optionalUUIDValue(row.CandidateID)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
if err != nil {
return nil, fmt.Errorf("%s - %w", location, err)
}
facts[candidateID] = append(facts[candidateID], fact)
}
return facts, nil
}
func (repository evidenceRepository) CountComparableRealCategories(
ctx context.Context,
categories []outbound.CategoryKey,
) (map[outbound.CategoryKey]int64, error) {
const location = "evidenceRepository.CountComparableRealCategories"
counts := make(map[outbound.CategoryKey]int64, len(categories))
if len(categories) == 0 {
return counts, nil
}
pairs := make([]string, 0, len(categories))
for _, category := range categories {
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() {
return nil, fmt.Errorf("%s - category is not known: %w", location, domain.ErrInvalidEvidence)
}
pairs = append(pairs, string(category.Specialization)+"/"+string(category.Grade))
}
rows, err := repository.queries.CountRealComparableCategories(ctx, pairs)
if err != nil {
return nil, fmt.Errorf("%s - count cohorts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
for _, row := range rows {
counts[outbound.CategoryKey{Specialization: domain.SpecializationCode(row.Specialization), Grade: domain.GradeCode(row.Grade)}] = row.Candidates
}
return counts, nil
}
func (repository evidenceRepository) ListPreviewFacts(
ctx context.Context,
candidateID uuid.UUID,
@@ -187,3 +262,10 @@ func evidenceTrust(value int16) (domain.EvidenceTrust, error) {
}
return domain.EvidenceTrust(value), nil
}
func optionalUUIDValue(value pgtype.UUID) (uuid.UUID, error) {
if !value.Valid || value.Bytes == uuid.Nil {
return uuid.Nil, fmt.Errorf("candidate identity is invalid: %w", domain.ErrInvalidEvidence)
}
return uuid.UUID(value.Bytes), nil
}
@@ -0,0 +1,94 @@
//go:build e2e
package postgres
import (
"context"
"errors"
"fmt"
"regexp"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/port/outbound"
)
// notificationFixtureEmail limits the notification fixture to the synthetic
// accounts of the isolated browser suite.
var notificationFixtureEmail = regexp.MustCompile(`@example\.test$`)
// syntheticNoticeEventType is the synthetic inbox event the fixture replays.
const syntheticNoticeEventType = "notification.synthetic_delivered"
// CheckNotificationFixtureScope accepts only a synthetic account and an
// existing organization. It is available only in e2e-tagged builds.
func CheckNotificationFixtureScope(ctx context.Context, pool *pgxpool.Pool, recipientID, organizationID uuid.UUID) error {
const location = "postgres.CheckNotificationFixtureScope"
if pool == nil || recipientID == uuid.Nil || organizationID == uuid.Nil {
return fmt.Errorf("%s - invalid fixture identity: %w", location, ErrCompanyFixtureScope)
}
var email string
err := pool.QueryRow(ctx, `SELECT email FROM users WHERE id = $1`, recipientID).Scan(&email)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - recipient: %w", location, outbound.ErrUserNotFound)
}
if err != nil {
return fmt.Errorf("%s - read recipient: %w", location, sanitizedDatabaseError(err))
}
if !notificationFixtureEmail.MatchString(email) {
return fmt.Errorf("%s - recipient is outside the fixture scope: %w", location, ErrCompanyFixtureScope)
}
var exists bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM organizations WHERE id = $1)`, organizationID).Scan(&exists); err != nil {
return fmt.Errorf("%s - read organization: %w", location, sanitizedDatabaseError(err))
}
if !exists {
return fmt.Errorf("%s - organization: %w", location, outbound.ErrOrganizationNotFound)
}
return nil
}
// NotificationFixtureEvent reads a synthetic inbox event from the outbox as
// the envelope a consumer receives for it, so the fixture can deliver it
// again the way an at-least-once bus does.
func NotificationFixtureEvent(ctx context.Context, pool *pgxpool.Pool, eventID uuid.UUID) (outbound.ConsumedEvent, error) {
const location = "postgres.NotificationFixtureEvent"
var event outbound.ConsumedEvent
var payload []byte
err := pool.QueryRow(ctx, `
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
FROM outbox_events
WHERE event_id = $1 AND event_type = $2`, eventID, syntheticNoticeEventType).Scan(
&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID,
&event.AggregateVersion, &payload, &event.OccurredAt)
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ConsumedEvent{}, fmt.Errorf("%s - synthetic event: %w", location, outbound.ErrNotificationInboxEntryNotFound)
}
if err != nil {
return outbound.ConsumedEvent{}, fmt.Errorf("%s - read outbox event: %w", location, sanitizedDatabaseError(err))
}
event.Payload = payload
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
return event, nil
}
// HideNotificationFixtureOrganization records that a synthetic candidate
// hides an organization, the visibility change that removes the content of a
// synthetic notice. The browser suite cannot use the public operation for an
// organization the candidate has not seen yet.
func HideNotificationFixtureOrganization(ctx context.Context, pool *pgxpool.Pool, recipientID, organizationID uuid.UUID) error {
const location = "postgres.HideNotificationFixtureOrganization"
if err := CheckNotificationFixtureScope(ctx, pool, recipientID, organizationID); err != nil {
return err
}
if _, err := pool.Exec(ctx, `
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at)
VALUES ($1, $2, now())
ON CONFLICT DO NOTHING`, recipientID, organizationID); err != nil {
return fmt.Errorf("%s - hide organization: %w", location, sanitizedDatabaseError(err))
}
return nil
}
@@ -18,9 +18,13 @@ import (
var _ outbound.NotificationInboxRepository = notificationInboxRepository{}
// notificationInboxRecipientConstraint is the foreign key of the recipient in
// migration 00032; the organization key has its own name.
const notificationInboxRecipientConstraint = "notification_inbox_events_recipient_fkey"
// NewNotificationInboxRepository creates a direct store for inbox operations.
// Transaction-bound callers can construct the same repository around the
// queries of their current UnitOfWork.
// Transaction-bound callers use UnitOfWork.NotificationInbox, which builds
// the same repository around the queries of the current transaction.
func NewNotificationInboxRepository(pool *pgxpool.Pool) outbound.NotificationInboxRepository {
return notificationInboxRepository{queries: sqlc.New(pool)}
}
@@ -29,6 +33,11 @@ type notificationInboxRepository struct {
queries *sqlc.Queries
}
// NotificationInbox binds the inbox repository to this transaction.
func (unit *UnitOfWork) NotificationInbox() outbound.NotificationInboxRepository {
return notificationInboxRepository{queries: unit.queries}
}
func (repository notificationInboxRepository) Store(
ctx context.Context,
entry domain.NotificationInboxEntry,
@@ -52,7 +61,18 @@ func (repository notificationInboxRepository) Store(
OccurredAt: pgTime(entry.OccurredAt()),
})
if err != nil {
return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitizedDatabaseError(err))
sanitized := sanitizedDatabaseError(err)
var failure *databaseError
if errors.As(sanitized, &failure) && failure.code == foreignKeyViolationCode {
// The statement failed on the recipient or the organization row, so
// the surrounding transaction is aborted.
reference := outbound.ErrNotificationInboxReferenceMissing
if failure.constraint == notificationInboxRecipientConstraint {
reference = outbound.ErrNotificationInboxRecipientMissing
}
return false, fmt.Errorf("%s - insert recipient event: %w: %w", location, reference, sanitized)
}
return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitized)
}
if rows == 1 {
return true, nil
@@ -116,16 +136,16 @@ func (repository notificationInboxRepository) List(
func (repository notificationInboxRepository) MarkRead(
ctx context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error) {
const location = "notificationInboxRepository.MarkRead"
if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil || at.IsZero() {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry)
if recipientUserID == uuid.Nil || (organizationID != nil && *organizationID == uuid.Nil) || eventID == uuid.Nil || at.IsZero() {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry)
}
row, err := repository.queries.MarkNotificationInboxEventRead(ctx, sqlc.MarkNotificationInboxEventReadParams{
RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID),
RecipientUserID: pgUUID(recipientUserID), OrganizationID: notificationInboxOptionalUUID(organizationID),
EventID: pgUUID(eventID), ReadAt: pgTime(at),
})
if errors.Is(err, pgx.ErrNoRows) {
@@ -141,6 +161,26 @@ func (repository notificationInboxRepository) MarkRead(
return entry, nil
}
func (repository notificationInboxRepository) OrganizationNameForRecipient(
ctx context.Context,
recipientUserID, organizationID uuid.UUID,
) (string, error) {
const location = "notificationInboxRepository.OrganizationNameForRecipient"
if recipientUserID == uuid.Nil || organizationID == uuid.Nil {
return "", fmt.Errorf("%s - recipient and organization are required: %w", location, domain.ErrInvalidNotificationInboxEntry)
}
name, err := repository.queries.GetNotificationOrganizationNameForRecipient(ctx, sqlc.GetNotificationOrganizationNameForRecipientParams{
RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID),
})
if errors.Is(err, pgx.ErrNoRows) {
return "", fmt.Errorf("%s - read organization: %w", location, outbound.ErrNotificationInboxSourceNotVisible)
}
if err != nil {
return "", fmt.Errorf("%s - read organization: %w", location, sanitizedDatabaseError(err))
}
return name, nil
}
func validateInboxEntryForStore(entry domain.NotificationInboxEntry) error {
_, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: entry.EventID(), RecipientUserID: entry.RecipientUserID(), OrganizationID: entry.OrganizationID(),
@@ -0,0 +1,56 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: candidate_search.sql
package sqlc
import (
"context"
)
const countRealComparableCategories = `-- name: CountRealComparableCategories :many
SELECT
category.specialization,
category.grade,
count(*)::bigint AS candidates
FROM candidate_assessment_categories AS category
WHERE
category.source <> 'synthetic_demo'
AND (category.specialization || '/' || category.grade) = any($1::text [])
GROUP BY category.specialization, category.grade
`
type CountRealComparableCategoriesRow struct {
Specialization string
Grade string
Candidates int64
}
// Reads that only the match search needs. The visibility of the candidates and
// their permitted evidence come from the card and evidence queries, which are
// the single copy of those barriers; this file adds no candidate-facing read.
// The number of candidates who hold each given category from a source that is
// not a synthetic demonstration, which is the size of the comparable real
// cohort that a percentile needs. It returns counts only, for the pairs the
// caller passes as "specialization/grade", and no row for a pair nobody holds.
func (q *Queries) CountRealComparableCategories(ctx context.Context, categories []string) ([]CountRealComparableCategoriesRow, error) {
rows, err := q.db.Query(ctx, countRealComparableCategories, categories)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CountRealComparableCategoriesRow
for rows.Next() {
var i CountRealComparableCategoriesRow
if err := rows.Scan(&i.Specialization, &i.Grade, &i.Candidates); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -186,7 +186,6 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins
}
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
SELECT
id,
verification_level,
@@ -204,9 +203,6 @@ type LockCompanyQuotaOrganizationRow struct {
VerificationChangedAt pgtype.Timestamptz
}
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID)
var i LockCompanyQuotaOrganizationRow
@@ -219,6 +215,32 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization
return i, err
}
const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one
SELECT id
FROM organizations
WHERE id = $1
FOR NO KEY UPDATE
`
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
// Takes the organization lock ahead of every share lock of a reader that will
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
// SHARE, so readers of one organization queue up instead of deadlocking on a
// share lock that each then tries to raise, but it does not conflict with the
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
// insert of a candidate, which holds the candidate's row and then needs this
// one. The reservation itself still takes FOR UPDATE inside the same
// transaction.
func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
UPDATE company_card_view_quota_usage
SET
@@ -264,3 +264,93 @@ func (q *Queries) ListOrganizationVisibleEvidence(ctx context.Context, arg ListO
}
return items, nil
}
const listOrganizationVisibleEvidenceBatch = `-- name: ListOrganizationVisibleEvidenceBatch :many
SELECT DISTINCT ON (wanted.candidate_id, skill.skill_code)
wanted.candidate_id::uuid AS candidate_id,
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM (
SELECT
candidate_ids.candidate_id,
wanted_categories.category
FROM unnest($1::uuid []) WITH ORDINALITY AS candidate_ids (candidate_id, position)
INNER JOIN unnest($2::text []) WITH ORDINALITY AS wanted_categories (category, position)
ON candidate_ids.position = wanted_categories.position
) AS wanted
INNER JOIN candidate_effective_publications AS effective
ON wanted.candidate_id = effective.user_id
INNER JOIN skill_evidence_facts AS fact
ON effective.user_id = fact.candidate_id
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
'categories' = any(effective.fields)
AND (skill.skill_code || '/' || fact.grade) = wanted.category
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = effective.user_id
AND hidden.organization_id = $3
)
ORDER BY wanted.candidate_id, skill.skill_code, fact.occurred_at, fact.id
`
type ListOrganizationVisibleEvidenceBatchParams struct {
CandidateIds []pgtype.UUID
Categories []string
OrganizationID pgtype.UUID
}
type ListOrganizationVisibleEvidenceBatchRow struct {
CandidateID pgtype.UUID
Skill string
Grade string
Trust int16
Basis string
CalibrationStatus string
ObservedYear int32
}
// The same organization read for a whole candidate set, so a search reads the
// evidence of every listed candidate in one statement. The pairs come from the
// caller as two parallel arrays, one row per candidate and category of the card
// that was just projected. The statement repeats every barrier of the single
// read: the effective publication view, NOT EXISTS over the candidates that
// hide the organization, the categories field, and only visible measurements.
// The candidate identifier is returned for the caller to group by and never
// leaves the server; the other columns are the same allowlist.
func (q *Queries) ListOrganizationVisibleEvidenceBatch(ctx context.Context, arg ListOrganizationVisibleEvidenceBatchParams) ([]ListOrganizationVisibleEvidenceBatchRow, error) {
rows, err := q.db.Query(ctx, listOrganizationVisibleEvidenceBatch, arg.CandidateIds, arg.Categories, arg.OrganizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationVisibleEvidenceBatchRow
for rows.Next() {
var i ListOrganizationVisibleEvidenceBatchRow
if err := rows.Scan(
&i.CandidateID,
&i.Skill,
&i.Grade,
&i.Trust,
&i.Basis,
&i.CalibrationStatus,
&i.ObservedYear,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -51,6 +51,49 @@ func (q *Queries) GetNotificationInboxEvent(ctx context.Context, arg GetNotifica
return i, err
}
const getNotificationOrganizationNameForRecipient = `-- name: GetNotificationOrganizationNameForRecipient :one
SELECT organizations.name
FROM organizations
INNER JOIN users ON users.id = $1
WHERE organizations.id = $2
AND (
(
users.scenario = 'candidate'
AND NOT EXISTS (
SELECT 1 FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = users.id
AND candidate_hidden_organizations.organization_id = organizations.id
)
)
OR (
users.scenario = 'employer'
AND EXISTS (
SELECT 1 FROM memberships
WHERE memberships.user_id = users.id
AND memberships.organization_id = organizations.id
AND memberships.state = 'active'
)
)
)
`
type GetNotificationOrganizationNameForRecipientParams struct {
RecipientUserID pgtype.UUID
OrganizationID pgtype.UUID
}
// Resolve the sender organization of a synthetic notice under the recipient's
// current standing, so the notice never outlives that standing. A candidate
// sees the name only while the organization is not hidden from them; an
// employer sees it only while they are an active member. No row means the
// content is no longer visible to this recipient.
func (q *Queries) GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error) {
row := q.db.QueryRow(ctx, getNotificationOrganizationNameForRecipient, arg.RecipientUserID, arg.OrganizationID)
var name string
err := row.Scan(&name)
return name, err
}
const insertNotificationInboxEvent = `-- name: InsertNotificationInboxEvent :execrows
INSERT INTO notification_inbox_events (
recipient_user_id,
@@ -183,7 +226,10 @@ const markNotificationInboxEventRead = `-- name: MarkNotificationInboxEventRead
UPDATE notification_inbox_events
SET read_at = COALESCE(read_at, $1::timestamptz)
WHERE recipient_user_id = $2
AND organization_id = $3
AND (
$3::uuid IS NULL
OR organization_id = $3::uuid
)
AND event_id = $4
RETURNING
recipient_user_id,
@@ -204,8 +250,11 @@ type MarkNotificationInboxEventReadParams struct {
EventID pgtype.UUID
}
// Persist the first read time under exact recipient and organization scope.
// Repeated calls preserve the original read timestamp.
// Persist the first read time for the recipient, optionally under one exact
// organization context. A missing organization is the candidate cabinet,
// which spans the organizations that sent to it; the employer cabinet always
// names its organization. Repeated calls preserve the original read
// timestamp.
func (q *Queries) MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) {
row := q.db.QueryRow(ctx, markNotificationInboxEventRead,
arg.ReadAt,
@@ -131,6 +131,14 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// Reads that only the match search needs. The visibility of the candidates and
// their permitted evidence come from the card and evidence queries, which are
// the single copy of those barriers; this file adds no candidate-facing read.
// The number of candidates who hold each given category from a source that is
// not a synthetic demonstration, which is the size of the comparable real
// cohort that a percentile needs. It returns counts only, for the pairs the
// caller passes as "specialization/grade", and no row for a pair nobody holds.
CountRealComparableCategories(ctx context.Context, categories []string) ([]CountRealComparableCategoriesRow, error)
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error)
@@ -304,6 +312,12 @@ type Querier interface {
// Read the existing row after a duplicate insert so the repository can reject
// an event ID whose immutable metadata changed on redelivery.
GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error)
// Resolve the sender organization of a synthetic notice under the recipient's
// current standing, so the notice never outlives that standing. A candidate
// sees the name only while the organization is not hidden from them; an
// employer sees it only while they are an active member. No row means the
// content is no longer visible to this recipient.
GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error)
// Reads only the historical result. It intentionally does not join the live
// organization or membership, whose profile and state may have since changed.
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
@@ -615,6 +629,15 @@ type Querier interface {
// calibration (the same for every candidate) say that the fact is a synthetic
// demonstration.
ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error)
// The same organization read for a whole candidate set, so a search reads the
// evidence of every listed candidate in one statement. The pairs come from the
// caller as two parallel arrays, one row per candidate and category of the card
// that was just projected. The statement repeats every barrier of the single
// read: the effective publication view, NOT EXISTS over the candidates that
// hide the organization, the categories field, and only visible measurements.
// The candidate identifier is returned for the caller to group by and never
// leaves the server; the other columns are the same allowlist.
ListOrganizationVisibleEvidenceBatch(ctx context.Context, arg ListOrganizationVisibleEvidenceBatchParams) ([]ListOrganizationVisibleEvidenceBatchRow, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
@@ -678,10 +701,19 @@ type Querier interface {
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Takes the organization lock ahead of every share lock of a reader that will
// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR
// SHARE, so readers of one organization queue up instead of deadlocking on a
// share lock that each then tries to raise, but it does not conflict with the
// FOR KEY SHARE that a foreign key takes, such as the hidden-organization
// insert of a candidate, which holds the candidate's row and then needs this
// one. The reservation itself still takes FOR UPDATE inside the same
// transaction.
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error)
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
@@ -743,8 +775,11 @@ type Querier interface {
// gate stops admitting sends until the window resets or an operator raises
// the limit. The caller holds the row lock.
MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error)
// Persist the first read time under exact recipient and organization scope.
// Repeated calls preserve the original read timestamp.
// Persist the first read time for the recipient, optionally under one exact
// organization context. A missing organization is the candidate cabinet,
// which spans the organizations that sent to it; the employer cabinet always
// names its organization. Repeated calls preserve the original read
// timestamp.
MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error)
// Marks the events that the broker acknowledged. The relay passes only IDs
// whose rows its own transaction locked, so the statement never waits and the
+4 -1
View File
@@ -48,7 +48,10 @@ func eventHandlers(settings config.Config, logger *slog.Logger) ([]inbound.Event
time.Now,
logger.With(slog.String("component", "notification_delivery")),
)
return []inbound.EventHandler{deliveries}, nil
// The inbox handler stores references only and reads no mail state, so it
// needs no renderer, provider account, or clock.
inbox := notification.NewInboxHandler(logger.With(slog.String("component", "notification_inbox")), settings.NotificationSyntheticEnabled)
return []inbound.EventHandler{deliveries, inbox}, nil
}
func newEventConsumers(
+17 -2
View File
@@ -14,6 +14,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
@@ -77,17 +78,31 @@ func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) {
}
}
func TestBootstrapRegistersTheDeliveryHandler(t *testing.T) {
func TestBootstrapRegistersTheDeliveryAndInboxHandlers(t *testing.T) {
handlers, err := eventHandlers(consumerTestConfig(t), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("eventHandlers() error = %v", err)
}
if len(handlers) != 1 || handlers[0].ConsumerName() != notification.DeliveryConsumerName {
if len(handlers) != 2 || handlers[0].ConsumerName() != notification.DeliveryConsumerName ||
handlers[1].ConsumerName() != notification.InboxConsumerName {
t.Fatalf("eventHandlers() = %v; update the documentation when the registered consumers change", handlers)
}
if !handlers[0].Handles(notification.MailRequestedEventType) {
t.Fatalf("the delivery handler does not handle %s", notification.MailRequestedEventType)
}
if !handlers[1].Handles(string(domain.NotificationInboxInvitationDelivered)) ||
handlers[1].Handles(notification.MailRequestedEventType) {
t.Fatal("the inbox handler must handle the invitation event and no mail request")
}
if handlers[1].Handles(string(domain.NotificationInboxSyntheticDelivered)) {
t.Fatal("the synthetic inbox event is handled although its switch is off by default")
}
settings := consumerTestConfig(t)
settings.NotificationSyntheticEnabled = true
enabled, err := eventHandlers(settings, slog.New(slog.DiscardHandler))
if err != nil || !enabled[1].Handles(string(domain.NotificationInboxSyntheticDelivered)) {
t.Fatalf("the synthetic inbox event is not handled with its switch on: %v", err)
}
}
func TestBootstrapRefusesAnInvalidMailAccountForDeliveries(t *testing.T) {
+4
View File
@@ -46,6 +46,8 @@ func newAPIHandler(
assessmentSignalHandler *v1.AssessmentSignalHandler,
privacyHandler *v1.PrivacyHandler,
evidenceHandler *v1.EvidenceHandler,
notificationHandler *v1.NotificationHandler,
matchHandler *v1.MatchHandler,
) *v1.Handler {
return v1.NewHandler(health, problems,
v1.WithIdentity(identityHandler),
@@ -60,6 +62,8 @@ func newAPIHandler(
v1.WithAssessmentSignals(assessmentSignalHandler),
v1.WithPrivacy(privacyHandler),
v1.WithEvidence(evidenceHandler),
v1.WithNotifications(notificationHandler),
v1.WithMatches(matchHandler),
)
}
+66
View File
@@ -0,0 +1,66 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/matching"
)
const matchesPoolMaxConns = 4
func newMatchHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
keyring *identity.Keyring,
) (*v1.MatchHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("match search is not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - derive projection key: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, matchesPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create pool: %w", err)
}
transactor := postgres.NewTransactor(pool)
views, err := newCandidateViewService(pool, transactor, key)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create view service: %w", err)
}
service, err := matching.NewService(matching.Dependencies{
Transactor: transactor, Cards: views.ListVisibleCards, Views: searchViews(views), Clock: time.Now, Logger: logger,
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create service: %w", err)
}
return v1.NewMatchHandler(service), pool.Close, nil
}
// searchViews adapts the card view service to the search, which charges and
// records the candidates it reveals like card reads.
func searchViews(views *candidateview.Service) matching.BeginViews {
return func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) {
session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID)
if err != nil {
return nil, err
}
return session, nil
}
}
@@ -0,0 +1,44 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/notification"
)
const notificationPoolMaxConns = 4
// newNotificationHandler builds the inbox operations and the PostgreSQL pool
// they own. Nothing connects here, so an unavailable database never blocks
// startup. It returns no handler when DATABASE_URL is unset, and the
// operations then answer 501.
func newNotificationHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
) (*v1.NotificationHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("notification inbox operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, notificationPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationHandler - create pool: %w", err)
}
service, err := notification.NewInboxService(
postgres.NewTransactor(pool),
notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(settings.NotificationSyntheticEnabled)),
time.Now,
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationHandler - create service: %w", err)
}
return v1.NewNotificationHandler(service), pool.Close, nil
}
+29 -7
View File
@@ -9,6 +9,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/policy"
)
@@ -45,13 +46,34 @@ func seedDemoPolicy(ctx context.Context, settings config.Config, logger *slog.Lo
logger.Info("product policy already present; demo seed skipped",
slog.String("policy_key", string(domain.ProductPolicyKey)),
)
return nil
} else {
logger.Info("demo product policy published",
slog.String("policy_key", string(result.Version.Key())),
slog.Int("policy_version", int(result.Version.Version())),
slog.String("policy_kind", string(result.Version.Kind())),
slog.String("policy_version_id", result.Version.ID().String()),
)
}
logger.Info("demo product policy published",
slog.String("policy_key", string(result.Version.Key())),
slog.Int("policy_version", int(result.Version.Version())),
slog.String("policy_kind", string(result.Version.Kind())),
slog.String("policy_version_id", result.Version.ID().String()),
)
warnWithoutMatchingSection(ctx, postgres.NewPolicyStore(pool).Policies(), logger)
return nil
}
// warnWithoutMatchingSection tells the operator at startup that the match
// search fails closed: the effective product policy has no matching section, and
// the demo seed publishes only the first version. It only warns; a policy the
// service cannot read must not stop startup either.
func warnWithoutMatchingSection(ctx context.Context, policies outbound.PolicyRepository, logger *slog.Logger) {
version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, time.Now())
if err != nil {
logger.Warn("the effective product policy could not be checked for the matching section",
slog.String("policy_key", string(domain.ProductPolicyKey)),
)
return
}
if version.Policy().Matching == nil {
logger.Warn("the effective product policy has no matching section; match search answers with an internal error until an operator publishes it (make -C backend policy-publish ARGS='matching --actor operator:<handle>')",
slog.String("policy_key", string(version.Key())),
slog.Int("policy_version", int(version.Version())),
)
}
}
+2
View File
@@ -58,6 +58,8 @@ func initialize(
newAssessmentSignalHandler,
newPrivacyHandler,
newEvidenceHandler,
newNotificationHandler,
newMatchHandler,
newSessionSecurity,
newRouter,
newOutboxRelay,
+80 -27
View File
@@ -202,10 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
notificationHandler, cleanup16, err := newNotificationHandler(ctx, config2, logger)
if err != nil {
cleanup15()
cleanup14()
@@ -224,26 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
relay, cleanup16, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup17, err := newEventConsumers(ctx, config2, logger, metrics)
matchHandler, cleanup17, err := newMatchHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup16()
cleanup15()
@@ -263,7 +241,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup18, err := newJobWorker(ctx, config2, logger, metrics)
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup17()
cleanup16()
@@ -284,7 +265,28 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup19, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
relay, cleanup18, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup19, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup18()
cleanup17()
@@ -306,7 +308,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup20, err := newDeliveryMetrics(ctx, config2, logger, metrics)
worker, cleanup20, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup19()
cleanup18()
@@ -329,8 +331,59 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup21, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
sampler, cleanup22, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
@@ -0,0 +1,22 @@
package domain
import (
"log/slog"
"github.com/google/uuid"
)
// VisibleCandidateCard pairs the organization-scoped anonymous card with the
// internal candidate identifier of the same read. The identifier is a join and
// ordering key for server-side work such as matching; it must never be
// serialized, logged, or returned to an organization.
type VisibleCandidateCard struct {
CandidateID uuid.UUID
Card AnonymousCandidateViewDTO
}
func (VisibleCandidateCard) String() string { return "[visible candidate card]" }
func (VisibleCandidateCard) GoString() string { return "[visible candidate card]" }
func (VisibleCandidateCard) LogValue() slog.Value {
return slog.StringValue("[visible candidate card]")
}
@@ -0,0 +1,19 @@
package domain
// EvidenceSkillRelation says how the skill of a piece of evidence relates to
// a skill that a need asks for.
type EvidenceSkillRelation uint8
const (
// EvidenceSkillRelationNone means the evidence says nothing about the
// requested skill.
EvidenceSkillRelationNone EvidenceSkillRelation = iota
// EvidenceSkillRelationExact means the same skill.
EvidenceSkillRelationExact
// EvidenceSkillRelationNarrower means the evidence names a part of the
// requested skill (a technology under a requested specialization).
EvidenceSkillRelationNarrower
// EvidenceSkillRelationBroader means the evidence names a field that
// contains the requested skill (a specialization over a technology).
EvidenceSkillRelationBroader
)
+32 -3
View File
@@ -14,13 +14,41 @@ var ErrInvalidNotificationInboxEntry = errors.New("invalid notification inbox en
// in the internal inbox.
type NotificationInboxEventType string
const NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered"
const (
// NotificationInboxInvitationDelivered records that an invitation reached
// the candidate's inbox. Its source is the invitation.
NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered"
// NotificationInboxSyntheticDelivered is a synthetic event type. It
// carries no product meaning: it exists to exercise the whole inbox path
// (outbox, consumer, read-time visibility check, listing, read state)
// before real producers exist and in browser tests. Its source is the
// sending organization, and its content is a fixed notice that names that
// organization.
NotificationInboxSyntheticDelivered NotificationInboxEventType = "notification.synthetic_delivered"
)
// NotificationInboxSourceType identifies the current source-of-truth record
// used to resolve an inbox item's content.
type NotificationInboxSourceType string
const NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation"
const (
NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation"
NotificationInboxSourceOrganization NotificationInboxSourceType = "organization"
)
// NotificationInboxSourceFor returns the only source type that an event type
// may refer to, and false for an event type that is not allowlisted. The
// database repeats the same pairs in a CHECK constraint.
func NotificationInboxSourceFor(eventType NotificationInboxEventType) (NotificationInboxSourceType, bool) {
switch eventType {
case NotificationInboxInvitationDelivered:
return NotificationInboxSourceInvitation, true
case NotificationInboxSyntheticDelivered:
return NotificationInboxSourceOrganization, true
default:
return "", false
}
}
// NotificationInboxEntryInput contains identifiers and event metadata only.
// It deliberately has no content snapshot: presentation is resolved from the
@@ -78,7 +106,8 @@ func restoreNotificationInboxEntryWithLocation(
if input.EventID == uuid.Nil || input.RecipientUserID == uuid.Nil || input.OrganizationID == uuid.Nil || input.SourceID == uuid.Nil {
return NotificationInboxEntry{}, fmt.Errorf("%s - event, recipient, organization, and source IDs are required: %w", location, ErrInvalidNotificationInboxEntry)
}
if input.EventType != NotificationInboxInvitationDelivered || input.SchemaVersion != 1 || input.SourceType != NotificationInboxSourceInvitation {
sourceType, known := NotificationInboxSourceFor(input.EventType)
if !known || input.SchemaVersion != 1 || input.SourceType != sourceType {
return NotificationInboxEntry{}, fmt.Errorf("%s - event type, schema version, and source type are unsupported: %w", location, ErrInvalidNotificationInboxEntry)
}
if input.OccurredAt.IsZero() {
@@ -57,6 +57,7 @@ func TestRestoreNotificationInboxEntryRejectsInvalidMetadata(t *testing.T) {
{name: "unknown event type", mutate: func(input *NotificationInboxEntryInput) { input.EventType = "notification.mail_requested" }},
{name: "unsupported schema version", mutate: func(input *NotificationInboxEntryInput) { input.SchemaVersion = 2 }},
{name: "unknown source type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = "mail_request" }},
{name: "source type of another event type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = NotificationInboxSourceOrganization }},
{name: "missing occurrence time", mutate: func(input *NotificationInboxEntryInput) { input.OccurredAt = time.Time{} }},
{name: "zero read time", mutate: func(input *NotificationInboxEntryInput) { input.ReadAt = &zeroTime }},
}
@@ -118,3 +119,21 @@ func TestNotificationInboxEntryMarkReadPreservesFirstTimestamp(t *testing.T) {
t.Fatal("MarkRead changed immutable source identity")
}
}
func TestNotificationInboxEntryAcceptsTheSyntheticEventOnlyWithItsSource(t *testing.T) {
t.Parallel()
input := NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: NotificationInboxSourceOrganization, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC),
}
if _, err := NewNotificationInboxEntry(input); err != nil {
t.Fatalf("NewNotificationInboxEntry(synthetic) error = %v", err)
}
input.SourceType = NotificationInboxSourceInvitation
if _, err := NewNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) {
t.Fatalf("NewNotificationInboxEntry(synthetic with invitation source) error = %v, want ErrInvalidNotificationInboxEntry", err)
}
}
+13
View File
@@ -93,6 +93,10 @@ type ProductPolicy struct {
// Support is absent only in immutable policy documents that predate the
// support section. New demo policies should set it explicitly.
Support *SupportPolicy
// Matching holds the coefficients of the deterministic basic matching. It
// is nil in policy versions that predate it; such a version cannot rank
// and never inherits another version's coefficients.
Matching *MatchingPolicy
}
// Validate checks every section. A zero value is never valid, so a section
@@ -114,6 +118,11 @@ func (policy ProductPolicy) Validate() error {
return fmt.Errorf("ProductPolicy.Validate - support section: %w: %w", ErrInvalidPolicy, err)
}
}
if policy.Matching != nil {
if err := policy.Matching.Validate(); err != nil {
return err
}
}
return nil
}
@@ -138,6 +147,10 @@ func (policy ProductPolicy) clone() ProductPolicy {
supportCopy := *support
copied.Support = &supportCopy
}
if matching := policy.Matching; matching != nil {
matchingCopy := matching.Clone()
copied.Matching = &matchingCopy
}
return copied
}
+10
View File
@@ -96,3 +96,13 @@ func DemoProductPolicyV3() ProductPolicy {
policy.Assessment.Signals = &signals
return policy
}
// DemoProductPolicyV4 returns the demo policy with the matching coefficients
// on top of DemoProductPolicyV3. It is published explicitly; a stored version
// is never rewritten, and startup seeding publishes V1 only.
func DemoProductPolicyV4() ProductPolicy {
policy := DemoProductPolicyV3()
matching := DemoMatchingPolicy()
policy.Matching = &matching
return policy
}
+127 -4
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"slices"
)
const (
@@ -36,6 +37,7 @@ type productPolicyDocument struct {
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
Support *supportPolicyDocument `json:"support,omitempty"`
Matching *matchingPolicyDocument `json:"matching,omitempty"`
}
// productPolicyV1Document deliberately excludes extension keys. Its strict
@@ -157,6 +159,39 @@ type identityPolicyDocument struct {
SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"`
}
type matchingPolicyDocument struct {
FitCoverageWeightBP *BasisPoints `json:"fit_coverage_weight_bp"`
FitDomainWeightBP *BasisPoints `json:"fit_domain_weight_bp"`
FitSemanticsWeightBP *BasisPoints `json:"fit_semantics_weight_bp"`
RankFitWeightBP *BasisPoints `json:"rank_fit_weight_bp"`
RankStrengthWeightBP *BasisPoints `json:"rank_strength_weight_bp"`
FreshnessFloorBP *BasisPoints `json:"freshness_floor_bp"`
ResponsivenessFloorBP *BasisPoints `json:"responsiveness_floor_bp"`
CompetitionBoostBP *BasisPoints `json:"competition_boost_bp"`
NeutralUnknownBP *BasisPoints `json:"neutral_unknown_bp"`
NearSkillThresholdBP *BasisPoints `json:"near_skill_threshold_bp"`
RequiredSkillWeight *int32 `json:"required_skill_weight"`
DesiredSkillWeight *int32 `json:"desired_skill_weight"`
TrustStatedBP *BasisPoints `json:"trust_stated_bp"`
TrustOnlineBP *BasisPoints `json:"trust_online_bp"`
TrustIdentityBP *BasisPoints `json:"trust_identity_bp"`
TrustInPersonBP *BasisPoints `json:"trust_in_person_bp"`
AttributionPersonalBP *BasisPoints `json:"attribution_personal_bp"`
AttributionTeamRoleBP *BasisPoints `json:"attribution_team_role_bp"`
AttributionTeamUnattributed *BasisPoints `json:"attribution_team_unattributed_bp"`
RelationExactBP *BasisPoints `json:"relation_exact_bp"`
RelationNarrowerBP *BasisPoints `json:"relation_narrower_bp"`
RelationBroaderBP *BasisPoints `json:"relation_broader_bp"`
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
}
type matchingSkillGroupDocument struct {
Specialization *SpecializationCode `json:"specialization"`
Skills *[]CandidateViewSkillCode `json:"skills"`
}
type searchStatusDocument struct {
SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"`
}
@@ -178,7 +213,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil {
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil ||
policy.Support != nil || policy.Matching != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
@@ -230,7 +266,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
Support: support,
Support: support,
Matching: encodeMatchingPolicy(policy.Matching),
}
encoded, err := json.Marshal(document)
if err != nil {
@@ -292,6 +329,49 @@ func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSig
}
}
func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
if policy == nil {
return nil
}
return &matchingPolicyDocument{
FitCoverageWeightBP: pointer(policy.FitCoverageWeight),
FitDomainWeightBP: pointer(policy.FitDomainWeight),
FitSemanticsWeightBP: pointer(policy.FitSemanticsWeight),
RankFitWeightBP: pointer(policy.RankFitWeight),
RankStrengthWeightBP: pointer(policy.RankStrengthWeight),
FreshnessFloorBP: pointer(policy.FreshnessFloor),
ResponsivenessFloorBP: pointer(policy.ResponsivenessFloor),
CompetitionBoostBP: pointer(policy.CompetitionBoost),
NeutralUnknownBP: pointer(policy.NeutralUnknown),
NearSkillThresholdBP: pointer(policy.NearSkillThreshold),
RequiredSkillWeight: pointer(policy.RequiredSkillWeight),
DesiredSkillWeight: pointer(policy.DesiredSkillWeight),
TrustStatedBP: pointer(policy.TrustStated),
TrustOnlineBP: pointer(policy.TrustOnline),
TrustIdentityBP: pointer(policy.TrustIdentity),
TrustInPersonBP: pointer(policy.TrustInPerson),
AttributionPersonalBP: pointer(policy.AttributionSelf),
AttributionTeamRoleBP: pointer(policy.AttributionTeamRole),
AttributionTeamUnattributed: pointer(policy.AttributionTeamUnattributed),
RelationExactBP: pointer(policy.RelationExact),
RelationNarrowerBP: pointer(policy.RelationNarrower),
RelationBroaderBP: pointer(policy.RelationBroader),
PercentileMinCohort: pointer(policy.PercentileMinCohort),
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
}
}
func encodeMatchingSkillGroups(groups []MatchingSkillGroup) []matchingSkillGroupDocument {
documents := make([]matchingSkillGroupDocument, 0, len(groups))
for _, group := range groups {
documents = append(documents, matchingSkillGroupDocument{
Specialization: pointer(group.Specialization), Skills: pointer(slices.Clone(group.Skills)),
})
}
return documents
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
@@ -347,7 +427,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil)
if !hasAssessmentExtension && parsed.Support == nil {
if !hasAssessmentExtension && parsed.Support == nil && parsed.Matching == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
default:
@@ -493,7 +573,8 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
Matching: decodeOptionalMatchingPolicy(&reader, parsed.Matching),
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
@@ -501,6 +582,48 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
return policy, nil
}
// decodeOptionalMatchingPolicy keeps documents that predate the matching
// section without it and never fills an omitted section with demo values.
func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPolicyDocument) *MatchingPolicy {
if document == nil {
return nil
}
taxonomy := make([]MatchingSkillGroup, 0)
for _, group := range require(reader, "matching.skill_taxonomy", document.SkillTaxonomy) {
taxonomy = append(taxonomy, MatchingSkillGroup{
Specialization: require(reader, "matching.skill_taxonomy.specialization", group.Specialization),
Skills: require(reader, "matching.skill_taxonomy.skills", group.Skills),
})
}
return &MatchingPolicy{
FitCoverageWeight: require(reader, "matching.fit_coverage_weight_bp", document.FitCoverageWeightBP),
FitDomainWeight: require(reader, "matching.fit_domain_weight_bp", document.FitDomainWeightBP),
FitSemanticsWeight: require(reader, "matching.fit_semantics_weight_bp", document.FitSemanticsWeightBP),
RankFitWeight: require(reader, "matching.rank_fit_weight_bp", document.RankFitWeightBP),
RankStrengthWeight: require(reader, "matching.rank_strength_weight_bp", document.RankStrengthWeightBP),
FreshnessFloor: require(reader, "matching.freshness_floor_bp", document.FreshnessFloorBP),
ResponsivenessFloor: require(reader, "matching.responsiveness_floor_bp", document.ResponsivenessFloorBP),
CompetitionBoost: require(reader, "matching.competition_boost_bp", document.CompetitionBoostBP),
NeutralUnknown: require(reader, "matching.neutral_unknown_bp", document.NeutralUnknownBP),
NearSkillThreshold: require(reader, "matching.near_skill_threshold_bp", document.NearSkillThresholdBP),
RequiredSkillWeight: require(reader, "matching.required_skill_weight", document.RequiredSkillWeight),
DesiredSkillWeight: require(reader, "matching.desired_skill_weight", document.DesiredSkillWeight),
TrustStated: require(reader, "matching.trust_stated_bp", document.TrustStatedBP),
TrustOnline: require(reader, "matching.trust_online_bp", document.TrustOnlineBP),
TrustIdentity: require(reader, "matching.trust_identity_bp", document.TrustIdentityBP),
TrustInPerson: require(reader, "matching.trust_in_person_bp", document.TrustInPersonBP),
AttributionSelf: require(reader, "matching.attribution_personal_bp", document.AttributionPersonalBP),
AttributionTeamRole: require(reader, "matching.attribution_team_role_bp", document.AttributionTeamRoleBP),
AttributionTeamUnattributed: require(reader, "matching.attribution_team_unattributed_bp", document.AttributionTeamUnattributed),
RelationExact: require(reader, "matching.relation_exact_bp", document.RelationExactBP),
RelationNarrower: require(reader, "matching.relation_narrower_bp", document.RelationNarrowerBP),
RelationBroader: require(reader, "matching.relation_broader_bp", document.RelationBroaderBP),
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
SkillTaxonomy: taxonomy,
}
}
func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota {
tier := require(reader, field, document)
return OrganizationTierQuota{
+336
View File
@@ -0,0 +1,336 @@
package domain
import "slices"
// MatchingPolicy holds the versioned coefficients of the deterministic basic
// matching (FR09). Every share is a BasisPoints value, so a comparison and a
// stored document carry an exact integer instead of a binary fraction. The
// section is optional: a policy version without it cannot rank, and an absent
// section never acquires defaults.
//
// Fit = FitCoverageWeight*Cov + FitDomainWeight*Dom + FitSemanticsWeight*Sem
// P = T + CompetitionBoost*(1-T)*V
// S = (RankFitWeight*Fit + RankStrengthWeight*P) *
//
// (FreshnessFloor + (1-FreshnessFloor)*Fr) *
// (ResponsivenessFloor + (1-ResponsivenessFloor)*Rsp)
//
// A skill contributes the best product of the trust, attribution, and
// relation coefficients over the permitted evidence; Cov is the weighted mean
// of the contributions of the requested skills.
type MatchingPolicy struct {
FitCoverageWeight BasisPoints
FitDomainWeight BasisPoints
FitSemanticsWeight BasisPoints
RankFitWeight BasisPoints
RankStrengthWeight BasisPoints
// FreshnessFloor and ResponsivenessFloor are the multipliers of a
// component equal to zero; a component equal to one multiplies by 1.
FreshnessFloor BasisPoints
ResponsivenessFloor BasisPoints
// CompetitionBoost is the share of the remaining distance (1-T) that a
// competition contribution of one adds to the strength of the profile.
CompetitionBoost BasisPoints
// NeutralUnknown replaces a component whose value is unknown. The
// unknown state is reported next to it and is never read as zero ability.
NeutralUnknown BasisPoints
// NearSkillThreshold is the contribution below which a requested
// required skill moves a confirmed profile to the near group.
NearSkillThreshold BasisPoints
RequiredSkillWeight int32
DesiredSkillWeight int32
// The trust coefficients are indexed by the evidence trust level 0..3.
TrustStated BasisPoints
TrustOnline BasisPoints
TrustIdentity BasisPoints
TrustInPerson BasisPoints
AttributionSelf BasisPoints
// AttributionTeamRole is a relevant role in a team result and
// AttributionTeamUnattributed a team result without a role.
AttributionTeamRole BasisPoints
AttributionTeamUnattributed BasisPoints
// The relation coefficients apply when the evidence skill equals the
// requested one (or a synonym), is narrower than it, or is broader.
RelationExact BasisPoints
RelationNarrower BasisPoints
RelationBroader BasisPoints
// PercentileMinCohort is the smallest number of comparable real
// candidates that allows a percentile; below it T is neutral.
PercentileMinCohort int32
// MaxResultsPerGroup bounds how many entries of each group one search may
// return. The whole visible bank is ranked and only the output is cut, so
// a search cannot read the whole bank at once. It is a demonstration value
// that stays below the daily card-view allowance of the first tier.
MaxResultsPerGroup int32
// SkillTaxonomy lists, for each specialization, the technologies that fall
// inside it. Evidence for a specialization is broader evidence for each of
// them, and evidence for one of them is narrower evidence for the
// specialization. It is part of the version, so the policy version fully
// determines a result.
SkillTaxonomy []MatchingSkillGroup
}
// MatchingSkillGroup is the technologies that one specialization contains.
type MatchingSkillGroup struct {
Specialization SpecializationCode
Skills []CandidateViewSkillCode
}
// Clone copies the slices, so a caller cannot change a stored version.
func (policy MatchingPolicy) Clone() MatchingPolicy {
policy.SkillTaxonomy = slices.Clone(policy.SkillTaxonomy)
for index := range policy.SkillTaxonomy {
policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills)
}
return policy
}
// RelateSkill classifies the skill of a piece of evidence against a requested
// skill by the taxonomy of this policy version. Both are taxonomy codes; an
// unmapped code has no relation.
func (policy MatchingPolicy) RelateSkill(requested, evidence string) EvidenceSkillRelation {
switch {
case requested == "" || evidence == "":
return EvidenceSkillRelationNone
case requested == evidence:
return EvidenceSkillRelationExact
case policy.contains(evidence, requested):
return EvidenceSkillRelationBroader
case policy.contains(requested, evidence):
return EvidenceSkillRelationNarrower
default:
return EvidenceSkillRelationNone
}
}
func (policy MatchingPolicy) contains(specialization, skill string) bool {
for _, group := range policy.SkillTaxonomy {
if string(group.Specialization) != specialization {
continue
}
for _, contained := range group.Skills {
if string(contained) == skill {
return true
}
}
}
return false
}
// Sanity bounds of the matching section. They reject a value in the wrong
// unit; the demo values themselves are recorded in DemoMatchingPolicy.
const (
maxMatchingSkillWeight = 100
maxMatchingCohortMinimum = 100000
maxMatchingResults = 1000
)
// DemoMatchingPolicy returns the initial matching coefficients. They are the
// design values of PRD 4.9 for verifying the flow, not measured results: no
// labelled set supports them, and a calibrated policy must replace them.
func DemoMatchingPolicy() MatchingPolicy {
return MatchingPolicy{
FitCoverageWeight: 7500, FitDomainWeight: 1500, FitSemanticsWeight: 1000,
RankFitWeight: 5000, RankStrengthWeight: 5000,
FreshnessFloor: 9000, ResponsivenessFloor: 9000,
CompetitionBoost: 3000,
NeutralUnknown: 5000, NearSkillThreshold: 2500,
RequiredSkillWeight: 2, DesiredSkillWeight: 1,
TrustStated: 2500, TrustOnline: 6000, TrustIdentity: 8500, TrustInPerson: 10000,
AttributionSelf: 10000, AttributionTeamRole: 8000, AttributionTeamUnattributed: 5000,
RelationExact: 10000, RelationNarrower: 8000, RelationBroader: 4000,
PercentileMinCohort: 30,
// 10 per group is at most 30 reveals for one search, below the 50
// distinct card views per day of the first tier, so one search cannot
// spend a whole allowance.
MaxResultsPerGroup: 10,
SkillTaxonomy: []MatchingSkillGroup{
{
Specialization: SpecializationBackend,
Skills: []CandidateViewSkillCode{
CandidateViewSkillDocker, CandidateViewSkillGo, CandidateViewSkillKafka, CandidateViewSkillPostgreSQL,
},
},
{Specialization: SpecializationDevopsSRE, Skills: []CandidateViewSkillCode{CandidateViewSkillDocker}},
},
}
}
// TrustCoefficient returns the coefficient of an evidence trust level. An
// unknown level has none.
func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) {
switch trust {
case EvidenceTrustStated:
return policy.TrustStated, true
case EvidenceTrustOnlineUnconfirmed:
return policy.TrustOnline, true
case EvidenceTrustIdentityTied:
return policy.TrustIdentity, true
case EvidenceTrustInPerson:
return policy.TrustInPerson, true
default:
return 0, false
}
}
// AttributionCoefficient returns the coefficient of an evidence attribution.
func (policy MatchingPolicy) AttributionCoefficient(attribution EvidenceAttribution) (BasisPoints, bool) {
switch attribution {
case EvidenceAttributionPersonal:
return policy.AttributionSelf, true
case EvidenceAttributionTeamRole:
return policy.AttributionTeamRole, true
case EvidenceAttributionTeamUnattributed:
return policy.AttributionTeamUnattributed, true
default:
return 0, false
}
}
// RelationCoefficient returns the coefficient of a skill relation. A skill
// that is unrelated to the requested one earns nothing.
func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation) BasisPoints {
switch relation {
case EvidenceSkillRelationExact:
return policy.RelationExact
case EvidenceSkillRelationNarrower:
return policy.RelationNarrower
case EvidenceSkillRelationBroader:
return policy.RelationBroader
case EvidenceSkillRelationNone:
return 0
default:
return 0
}
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy MatchingPolicy) Validate() error {
return firstError(
policy.validateShares(),
policy.validateWeights(),
policy.validateOrdering(),
)
}
func (policy MatchingPolicy) validateShares() error {
const location = "MatchingPolicy.Validate"
shares := []struct {
field string
value BasisPoints
}{
{"matching.competition_boost_bp", policy.CompetitionBoost},
{"matching.neutral_unknown_bp", policy.NeutralUnknown},
{"matching.near_skill_threshold_bp", policy.NearSkillThreshold},
{"matching.trust_stated_bp", policy.TrustStated},
{"matching.trust_online_bp", policy.TrustOnline},
{"matching.trust_identity_bp", policy.TrustIdentity},
{"matching.trust_in_person_bp", policy.TrustInPerson},
{"matching.attribution_personal_bp", policy.AttributionSelf},
{"matching.attribution_team_role_bp", policy.AttributionTeamRole},
{"matching.attribution_team_unattributed_bp", policy.AttributionTeamUnattributed},
{"matching.relation_exact_bp", policy.RelationExact},
{"matching.relation_narrower_bp", policy.RelationNarrower},
{"matching.relation_broader_bp", policy.RelationBroader},
}
for _, share := range shares {
if err := checkRange(location, share.field, share.value, 0, basisPointsPerUnit); err != nil {
return err
}
}
// A floor of zero would let one unknown multiplier erase the score, and a
// floor of one would switch the multiplier off.
return firstError(
checkRange(location, "matching.freshness_floor_bp", policy.FreshnessFloor, 1, basisPointsPerUnit),
checkRange(location, "matching.responsiveness_floor_bp", policy.ResponsivenessFloor, 1, basisPointsPerUnit),
)
}
func (policy MatchingPolicy) validateWeights() error {
const location = "MatchingPolicy.Validate"
if err := firstError(
checkRange(location, "matching.required_skill_weight", policy.RequiredSkillWeight, 1, maxMatchingSkillWeight),
checkRange(location, "matching.desired_skill_weight", policy.DesiredSkillWeight, 1, maxMatchingSkillWeight),
checkRange(location, "matching.percentile_min_cohort", policy.PercentileMinCohort, 1, maxMatchingCohortMinimum),
checkRange(location, "matching.max_results_per_group", policy.MaxResultsPerGroup, 1, maxMatchingResults),
policy.validateTaxonomy(),
); err != nil {
return err
}
for _, sum := range []struct {
field string
values []BasisPoints
}{
{"matching.fit_*_weight_bp", []BasisPoints{policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight}},
{"matching.rank_*_weight_bp", []BasisPoints{policy.RankFitWeight, policy.RankStrengthWeight}},
} {
var total BasisPoints
for _, value := range sum.values {
if err := checkRange(location, sum.field, value, 0, basisPointsPerUnit); err != nil {
return err
}
total += value
}
if total != basisPointsPerUnit {
return invalidPolicy(location, sum.field+" must add up to 1.0000")
}
}
return nil
}
// validateOrdering keeps a stronger confirmation from counting for less than
// a weaker one, and a closer relation from counting for less than a looser one.
func (policy MatchingPolicy) validateOrdering() error {
const location = "MatchingPolicy.Validate"
if policy.TrustStated > policy.TrustOnline || policy.TrustOnline > policy.TrustIdentity || policy.TrustIdentity > policy.TrustInPerson {
return invalidPolicy(location, "matching trust coefficients must not decrease with the trust level")
}
if policy.AttributionTeamUnattributed > policy.AttributionTeamRole || policy.AttributionTeamRole > policy.AttributionSelf {
return invalidPolicy(location, "matching attribution coefficients must not increase from personal to team results")
}
if policy.RelationBroader > policy.RelationNarrower || policy.RelationNarrower > policy.RelationExact {
return invalidPolicy(location, "matching relation coefficients must not increase from broader to exact")
}
return nil
}
// validateTaxonomy keeps each specialization and technology known and listed
// once, so a relation never depends on the order or a repeat.
func (policy MatchingPolicy) validateTaxonomy() error {
const location = "MatchingPolicy.Validate"
seen := make(map[SpecializationCode]struct{}, len(policy.SkillTaxonomy))
if len(policy.SkillTaxonomy) > len(specializationCodes) {
return invalidPolicy(location, "matching.skill_taxonomy has more groups than specializations")
}
for _, group := range policy.SkillTaxonomy {
if !group.Specialization.IsKnown() {
return invalidPolicy(location, "matching.skill_taxonomy names an unknown specialization")
}
if _, repeated := seen[group.Specialization]; repeated {
return invalidPolicy(location, "matching.skill_taxonomy repeats a specialization")
}
seen[group.Specialization] = struct{}{}
if len(group.Skills) == 0 || len(group.Skills) > len(candidateViewSkillCodes) {
return invalidPolicy(location, "matching.skill_taxonomy needs between one and every known technology for a specialization")
}
skills := make(map[CandidateViewSkillCode]struct{}, len(group.Skills))
for _, skill := range group.Skills {
if !skill.IsKnown() {
return invalidPolicy(location, "matching.skill_taxonomy names an unknown technology")
}
if _, repeated := skills[skill]; repeated {
return invalidPolicy(location, "matching.skill_taxonomy repeats a technology")
}
skills[skill] = struct{}{}
}
}
return nil
}
@@ -0,0 +1,187 @@
package domain
import (
"bytes"
"errors"
"reflect"
"testing"
)
func TestDemoProductPolicyV4CarriesTheMatchingSection(t *testing.T) {
policy := DemoProductPolicyV4()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV4().Validate() error = %v", err)
}
if policy.Matching == nil || policy.Assessment.Signals == nil || policy.Support == nil {
t.Fatalf("DemoProductPolicyV4() sections = matching:%v signals:%v support:%v, want all", policy.Matching != nil, policy.Assessment.Signals != nil, policy.Support != nil)
}
if DemoProductPolicyV3().Matching != nil {
t.Fatal("DemoProductPolicyV3() gained a matching section: a stored version must not change")
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Matching == nil || !reflect.DeepEqual(*decoded.Matching, *policy.Matching) {
t.Fatalf("decoded matching policy = %+v, want %+v", decoded.Matching, policy.Matching)
}
}
func TestMatchingPolicyIsAnIndependentSchemaTwoExtension(t *testing.T) {
policy := DemoProductPolicyV1()
matching := DemoMatchingPolicy()
policy.Matching = &matching
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Matching == nil || decoded.Assessment.Attempt != nil || decoded.Assessment.Training != nil ||
decoded.Assessment.Signals != nil || decoded.Support != nil {
t.Fatalf("decoded extensions = matching:%v attempt:%v training:%v signals:%v support:%v, want only matching",
decoded.Matching != nil, decoded.Assessment.Attempt != nil, decoded.Assessment.Training != nil,
decoded.Assessment.Signals != nil, decoded.Support != nil)
}
legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
document["matching"] = nil
})
if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 1 with a matching key) error = %v, want ErrInvalidPolicy", err)
}
}
func TestMatchingPolicyDocumentRequiresEveryFieldAndRejectsUnknownOnes(t *testing.T) {
encoded, _, err := encodeProductPolicy(DemoProductPolicyV4())
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
missing := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000,`), nil, 1)
if bytes.Equal(missing, encoded) {
t.Fatal("encoded matching section did not contain neutral_unknown_bp")
}
if _, err := decodeProductPolicy(missing); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(missing neutral_unknown_bp) error = %v, want ErrInvalidPolicy", err)
}
unknown := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000`), []byte(`"neutral_unknown_bp":5000,"unknown":1`), 1)
if _, err := decodeProductPolicy(unknown); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(unknown matching field) error = %v, want ErrInvalidPolicy", err)
}
}
func TestMatchingPolicyRejectsInconsistentValues(t *testing.T) {
tests := []struct {
name string
change func(*MatchingPolicy)
}{
{name: "fit weights do not add up", change: func(policy *MatchingPolicy) { policy.FitCoverageWeight = 7000 }},
{name: "rank weights do not add up", change: func(policy *MatchingPolicy) { policy.RankFitWeight = 6000 }},
{name: "share above one", change: func(policy *MatchingPolicy) { policy.NeutralUnknown = 10001 }},
{name: "zero freshness floor", change: func(policy *MatchingPolicy) { policy.FreshnessFloor = 0 }},
{name: "zero responsiveness floor", change: func(policy *MatchingPolicy) { policy.ResponsivenessFloor = 0 }},
{name: "trust falls with the level", change: func(policy *MatchingPolicy) { policy.TrustOnline = 2000 }},
{name: "team result above a personal one", change: func(policy *MatchingPolicy) { policy.AttributionTeamRole = 10001 }},
{name: "broader relation above exact", change: func(policy *MatchingPolicy) {
policy.RelationBroader = 10000
policy.RelationNarrower = 9000
policy.RelationExact = 8000
}},
{name: "zero required weight", change: func(policy *MatchingPolicy) { policy.RequiredSkillWeight = 0 }},
{name: "zero cohort minimum", change: func(policy *MatchingPolicy) { policy.PercentileMinCohort = 0 }},
{name: "no results allowed", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 0 }},
{name: "unbounded results", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 1001 }},
{name: "unknown specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Specialization = "chef" }},
{name: "unknown technology in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills[0] = "cobol" }},
{name: "repeated technology in a group", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills = []CandidateViewSkillCode{"go", "go"} }},
{name: "repeated specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Specialization = SpecializationBackend }},
{name: "empty group in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Skills = nil }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := DemoProductPolicyV4()
test.change(policy.Matching)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("ProductPolicy.Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
func TestMatchingPolicyDemoValuesAreTheDesignValuesOfThePRD(t *testing.T) {
policy := DemoMatchingPolicy()
for level, want := range map[EvidenceTrust]BasisPoints{
EvidenceTrustStated: 2500, EvidenceTrustOnlineUnconfirmed: 6000, EvidenceTrustIdentityTied: 8500, EvidenceTrustInPerson: 10000,
} {
if got, ok := policy.TrustCoefficient(level); !ok || got != want {
t.Errorf("TrustCoefficient(%d) = %d, %v, want %d", level, got, ok, want)
}
}
if _, ok := policy.TrustCoefficient(EvidenceTrust(4)); ok {
t.Error("TrustCoefficient(4) reported a coefficient for an unknown level")
}
for attribution, want := range map[EvidenceAttribution]BasisPoints{
EvidenceAttributionPersonal: 10000, EvidenceAttributionTeamRole: 8000, EvidenceAttributionTeamUnattributed: 5000,
} {
if got, ok := policy.AttributionCoefficient(attribution); !ok || got != want {
t.Errorf("AttributionCoefficient(%s) = %d, %v, want %d", attribution, got, ok, want)
}
}
for relation, want := range map[EvidenceSkillRelation]BasisPoints{
EvidenceSkillRelationExact: 10000, EvidenceSkillRelationNarrower: 8000, EvidenceSkillRelationBroader: 4000, EvidenceSkillRelationNone: 0,
} {
if got := policy.RelationCoefficient(relation); got != want {
t.Errorf("RelationCoefficient(%d) = %d, want %d", relation, got, want)
}
}
}
func TestMatchingPolicyRelatesSkillsByItsOwnTaxonomy(t *testing.T) {
policy := DemoMatchingPolicy()
tests := []struct {
name string
requested, offered string
want EvidenceSkillRelation
}{
{"same technology", "go", "go", EvidenceSkillRelationExact},
{"specialization evidence for a technology", "go", "backend", EvidenceSkillRelationBroader},
{"technology evidence for a specialization", "backend", "go", EvidenceSkillRelationNarrower},
{"another technology", "go", "kafka", EvidenceSkillRelationNone},
{"unrelated specialization", "go", "frontend", EvidenceSkillRelationNone},
{"devops covers docker only", "go", "devops_sre", EvidenceSkillRelationNone},
{"devops covers docker", "docker", "devops_sre", EvidenceSkillRelationBroader},
{"unmapped requested skill", "", "backend", EvidenceSkillRelationNone},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := policy.RelateSkill(test.requested, test.offered); got != test.want {
t.Fatalf("RelateSkill(%q, %q) = %d, want %d", test.requested, test.offered, got, test.want)
}
})
}
// A version without a taxonomy relates nothing but equal codes, and a
// changed version changes the relation: the version decides the result.
policy.SkillTaxonomy = nil
if got := policy.RelateSkill("go", "backend"); got != EvidenceSkillRelationNone {
t.Fatalf("RelateSkill without a taxonomy = %d, want none", got)
}
policy.SkillTaxonomy = []MatchingSkillGroup{{Specialization: SpecializationFrontend, Skills: []CandidateViewSkillCode{"docker"}}}
if got := policy.RelateSkill("docker", "frontend"); got != EvidenceSkillRelationBroader {
t.Fatalf("RelateSkill with a changed taxonomy = %d, want broader", got)
}
}
func TestMatchingPolicyCloneDoesNotShareTheTaxonomy(t *testing.T) {
original := DemoMatchingPolicy()
copied := original.Clone()
copied.SkillTaxonomy[0].Skills[0] = "kafka"
copied.SkillTaxonomy[1].Specialization = SpecializationQA
if original.SkillTaxonomy[0].Skills[0] == "kafka" || original.SkillTaxonomy[1].Specialization == SpecializationQA {
t.Fatal("a clone of the matching policy shares its taxonomy with the original")
}
}
@@ -46,6 +46,17 @@ type CompanyQuotaDecision struct {
// Repeated views update last_seen monotonically with the greater of the
// stored and current times.
type CompanyQuotaRepository interface {
// LockOrganization takes the organization lock that serializes the
// reservations of one organization (FOR NO KEY UPDATE, which does not block
// the foreign-key lock of a candidate's own hide), ahead of the share locks
// of a membership check. A
// caller that checks the membership first and reserves later would hold a
// share lock and then ask for the exclusive one, and two such callers of one
// organization deadlock. A caller that reserves after a share lock takes
// this lock first, in the documented order. It returns
// ErrCompanyQuotaSnapshotChanged for a removed organization.
LockOrganization(ctx context.Context, organizationID uuid.UUID) error
// ReserveInvitation counts a new invitation against the current policy
// limit. An existing invitation ID is returned as allowed and reused
// without a second charge, regardless of its age or the request key. A
@@ -37,6 +37,20 @@ func EvidencePositionOf(fact domain.EvidenceFact) EvidencePosition {
return EvidencePosition{OccurredAt: snapshot.OccurredAt, ID: snapshot.ID}
}
// EvidenceCandidateCategories names the categories that the card of one
// candidate shows, which are the categories whose supporting facts a batch
// read may return.
type EvidenceCandidateCategories struct {
CandidateID uuid.UUID
Categories []domain.CandidateViewCategory
}
// CategoryKey is a specialization and a grade.
type CategoryKey struct {
Specialization domain.SpecializationCode
Grade domain.GradeCode
}
// EvidenceRepository reads the skill evidence projection. It never reads an
// assessment result, answer, attempt, or review: the projection is the only
// source, so no answer, failure, or anti-cheat datum can reach a caller.
@@ -59,6 +73,24 @@ type EvidenceRepository interface {
categories []domain.CandidateViewCategory,
) ([]domain.EvidenceOrganizationFact, error)
// ListOrganizationFactsBatch is ListOrganizationFacts for many candidates in
// one statement, with the same barriers: the effective publication view,
// the exclusion of the candidates that hide the organization, the
// categories field, and only visible measurements. A candidate with no
// permitted fact has no entry in the result. The result is for the caller's
// grouping and is never returned as it is.
ListOrganizationFactsBatch(
ctx context.Context,
organizationID uuid.UUID,
requests []EvidenceCandidateCategories,
) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error)
// CountComparableRealCategories returns, for each given category, how many
// candidates hold it from a source that is not a synthetic demonstration:
// the size of the comparable real cohort. A category nobody holds from a
// real source is absent. It returns counts only.
CountComparableRealCategories(ctx context.Context, categories []CategoryKey) (map[CategoryKey]int64, error)
// ListPreviewFacts returns the same selection for the candidate's own card
// preview. It applies no organization and no cohort, and the caller has
// locked the effective C2 and publication.
@@ -17,6 +17,17 @@ var (
// ErrNotificationInboxEventConflict reports an event ID reused with
// different immutable recipient or source metadata.
ErrNotificationInboxEventConflict = errors.New("notification inbox event metadata conflicts")
// ErrNotificationInboxReferenceMissing reports an event that names an
// organization that does not exist. A retry cannot fix it.
ErrNotificationInboxReferenceMissing = errors.New("notification inbox event references a missing record")
// ErrNotificationInboxRecipientMissing reports a recipient account that
// does not exist now. The recipient may have been deleted a moment ago,
// so a handler retries and then skips instead of rejecting the event.
ErrNotificationInboxRecipientMissing = errors.New("notification inbox recipient does not exist")
// ErrNotificationInboxSourceNotVisible reports a source that does not
// exist or is not visible to the recipient now. The two cases are one on
// purpose.
ErrNotificationInboxSourceNotVisible = errors.New("notification source is not visible to the recipient")
)
const MaxNotificationInboxPageSize = 100
@@ -33,15 +44,25 @@ type NotificationInboxRepository interface {
// OrganizationID means all organization contexts of that recipient.
List(ctx context.Context, query NotificationInboxListQuery) (NotificationInboxPage, error)
// MarkRead records the first read time in exact recipient and organization
// context. Missing and unauthorized identities share one not-found result.
// MarkRead records the first read time for the recipient. A non-nil
// organizationID narrows the match to that organization context; nil
// matches any context of the recipient, which is the candidate cabinet.
// Missing and unauthorized identities share one not-found result.
MarkRead(
ctx context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error)
// OrganizationNameForRecipient returns the current name of an
// organization under the recipient's current standing: a candidate who has
// not hidden it, or an employer with an active membership in it. It
// returns ErrNotificationInboxSourceNotVisible otherwise. Content that
// names an organization is resolved through it at read time, so a hiding
// or a revoked membership removes the name from every later read.
OrganizationNameForRecipient(ctx context.Context, recipientUserID, organizationID uuid.UUID) (string, error)
}
// NotificationInboxListQuery selects a bounded recipient-owned page.
@@ -14,6 +14,9 @@ var (
ErrCandidateCardAccessNotFound = errors.New("candidate card access not found")
ErrCandidateC2Unavailable = errors.New("candidate C2 publication is unavailable")
ErrContactAccessClosed = errors.New("contact access is closed")
// ErrConcurrentVisibilityChange reports that the visible cohort changed
// while a read was locking it. The read can be repeated.
ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read")
)
const MaxCandidateCardAccessPageSize = 100
@@ -63,6 +63,7 @@ type UnitOfWork interface {
PrivacyView() PrivacyViewRepository
PrivacySettings() PrivacySettingsRepository
Evidence() EvidenceRepository
NotificationInbox() NotificationInboxRepository
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
@@ -174,6 +174,16 @@ func (unit contactAccessUnit) Organizations() outbound.OrganizationRepository {
return unit.organizations
}
func (unit contactAccessUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view }
func (unit contactAccessUnit) CompanyQuotas() outbound.CompanyQuotaRepository {
return organizationLockStub{}
}
// organizationLockStub accepts the organization lock and is not used for more.
type organizationLockStub struct {
outbound.CompanyQuotaRepository
}
func (organizationLockStub) LockOrganization(context.Context, uuid.UUID) error { return nil }
type contactAccessUsers struct {
outbound.UserRepository
@@ -19,7 +19,7 @@ var (
ErrForbidden = errors.New("candidate view is forbidden")
ErrCandidateCardNotFound = errors.New("candidate card not found")
ErrInvalidCandidateHandle = errors.New("candidate handle is invalid")
ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read")
ErrConcurrentVisibilityChange = outbound.ErrConcurrentVisibilityChange
ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable")
ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted")
)
@@ -92,6 +92,9 @@ func (service *Service) GetOrganizationCard(
}
var result domain.AnonymousCandidateViewDTO
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
return err
}
view, err := service.getOrganizationCardInTransaction(ctx, unit, actorID, organizationID, handle, location)
if err != nil {
return err
@@ -153,6 +156,114 @@ func (service *Service) reserveCardView(
return nil
}
// ListVisibleCards returns the cards of the current, locked,
// organization-visible cohort, built by the same projection as a card read, so
// a handle in the list is a handle that GetOrganizationCard opens. It runs the
// membership, effective C2 publication, hiding, and minimum-cohort checks of a
// card read under the same locks, inside the caller's transaction. A candidate
// whose card is suppressed by the cohort rules is not in the list.
//
// Listing itself consumes nothing. The caller charges and records each
// candidate that it reveals through BeginSearchViews, because an entry holds
// card content.
func (service *Service) ListVisibleCards(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
) ([]domain.VisibleCandidateCard, error) {
const location = "candidateview.Service.ListVisibleCards"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return nil, ErrForbidden
}
_, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location)
if err != nil {
return nil, err
}
candidateByAlias := make(map[string]uuid.UUID, len(sources))
for _, source := range sources {
alias, err := service.sourceAlias(organizationID, source)
if err != nil {
return nil, fmt.Errorf("%s - derive current alias: %w", location, err)
}
candidateByAlias[alias] = source.CandidateID()
}
views, err := service.projector.ProjectSources(organizationID, sources)
if err != nil {
return nil, fmt.Errorf("%s - build current candidate views: %w", location, err)
}
cards := make([]domain.VisibleCandidateCard, 0, len(views))
for _, view := range views {
candidateID, exists := candidateByAlias[view.Pseudonym]
if !exists {
return nil, fmt.Errorf("%s - projected view has no source: %w", location, domain.ErrInvalidAnonymousCandidateView)
}
cards = append(cards, domain.VisibleCandidateCard{CandidateID: candidateID, Card: view})
}
return cards, nil
}
// SearchViews charges and records the candidates that one search reveals. It is
// bound to the caller's transaction and to the organization that was already
// authorized, so a failure of the search leaves neither a charge nor a record.
type SearchViews struct {
service *Service
unit outbound.UnitOfWork
organization domain.Organization
repository outbound.PrivacyViewRepository
actorID uuid.UUID
}
// BeginSearchViews prepares the charging of a search inside the caller's
// transaction. The actor must have an active membership of the organization.
func (service *Service) BeginSearchViews(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
) (*SearchViews, error) {
const location = "candidateview.Service.BeginSearchViews"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return nil, ErrForbidden
}
organization, err := authorizeEmployer(ctx, unit, actorID, organizationID)
if err != nil {
return nil, err
}
repository, err := privacyViewRepository(unit)
if err != nil {
return nil, fmt.Errorf("%s - open the access repository: %w", location, err)
}
return &SearchViews{service: service, unit: unit, organization: organization, repository: repository, actorID: actorID}, nil
}
// Reserve counts the candidate as a distinct card view of the organization. A
// candidate that the organization already viewed inside the window is allowed
// again without another charge. It reports false, writing nothing, when the
// allowance is used up.
func (views *SearchViews) Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error) {
decision, err := views.service.quota(ctx, views.unit, views.organization, candidateID)
if err != nil {
return false, fmt.Errorf("candidateview.SearchViews.Reserve - reserve card view: %w", err)
}
return decision.Allowed, nil
}
// Record appends the access history entry for the fields that a search
// actually returned about the candidate, so the candidate sees the read.
func (views *SearchViews) Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error {
const location = "candidateview.SearchViews.Record"
event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
CandidateID: candidateID, OrganizationID: views.organization.ID(), ActorID: views.actorID,
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: views.service.clock(),
})
if err != nil {
return fmt.Errorf("%s - build access audit: %w", location, err)
}
if err := views.repository.RecordCandidateCardAccess(ctx, event); err != nil {
return fmt.Errorf("%s - record access audit: %w", location, err)
}
return nil
}
// AuthorizeCategoriesSection runs the checks of an organization card read
// inside the caller's transaction and reports which candidate, and which
// categories (specialization and grade), the card shows. It exists for the sections
@@ -180,6 +291,10 @@ func (service *Service) AuthorizeCategoriesSection(
if !domain.IsCandidateViewPseudonym(handle) {
return uuid.Nil, nil, ErrInvalidCandidateHandle
}
// The caller's transaction has taken no share lock of the organization yet.
if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil {
return uuid.Nil, nil, err
}
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
if err != nil {
return uuid.Nil, nil, err
@@ -429,6 +544,26 @@ func (service *Service) CurrentContactFields(
return fields, nil
}
// lockOrganizationFirst takes the exclusive organization lock that the card-view
// reservation takes later. The membership check holds only a share lock on the
// same row, and two readers of one organization that each hold a share lock
// and then ask for the exclusive one deadlock. Taking the exclusive lock before
// any share lock follows the documented lock order and serializes the charges
// of one organization.
func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID) error {
repository := unit.CompanyQuotas()
if repository == nil {
return fmt.Errorf("candidateview.lockOrganizationFirst - quota repository is missing: %w", ErrCandidateViewServiceMissing)
}
if err := repository.LockOrganization(ctx, organizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return outbound.ErrOrganizationNotFound
}
return fmt.Errorf("candidateview.lockOrganizationFirst - lock organization: %w", err)
}
return nil
}
func authorizeEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (domain.Organization, error) {
user, err := unit.Users().GetByID(ctx, actorID)
if errors.Is(err, outbound.ErrUserNotFound) {
@@ -0,0 +1,108 @@
package candidateview
import (
"context"
"errors"
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (fixture *categoriesSectionFixture) listVisible(t *testing.T) ([]domain.VisibleCandidateCard, error) {
t.Helper()
var cards []domain.VisibleCandidateCard
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
cards, err = fixture.service.ListVisibleCards(ctx, unit, fixture.actorID, fixture.organizationID)
return err
})
return cards, err
}
func TestListVisibleCardsReturnsTheCardsOfTheCurrentCohortWithoutAViewTrace(t *testing.T) {
t.Parallel()
shown := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}}
fixture := newCategoriesSectionFixture(t, shown, true, domain.ScenarioEmployer)
cards, err := fixture.listVisible(t)
if err != nil {
t.Fatalf("ListVisibleCards() error = %v", err)
}
if len(cards) != 1 || cards[0].CandidateID == uuid.Nil || cards[0].Card.Pseudonym != fixture.handle ||
!slices.Equal(cards[0].Card.Categories, shown) {
t.Fatalf("cards = %v, want the one visible card under the organization handle", cards)
}
if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 {
t.Fatalf("quota calls = %d, audits = %v, want a listing that is not a card view", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestListVisibleCardsRefusesAnActorWithoutAnEmployerRole(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate)
if _, err := fixture.listVisible(t); !errors.Is(err, ErrForbidden) {
t.Fatalf("ListVisibleCards() error = %v, want ErrForbidden", err)
}
if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 {
t.Fatalf("quota calls = %d, audits = %v, want no trace", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestSearchViewsChargeAndRecordWhatTheSearchReveals(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioEmployer)
candidateID := uuid.New()
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID)
if err != nil {
return err
}
allowed, err := views.Reserve(ctx, candidateID)
if err != nil || !allowed {
t.Fatalf("Reserve() = %v, %v, want allowed", allowed, err)
}
return views.Record(ctx, candidateID, []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack})
})
if err != nil {
t.Fatalf("search views error = %v", err)
}
if fixture.quotaCalls != 1 || len(fixture.contact.audits) != 1 || fixture.contact.audits[0].Kind() != domain.CandidateCardAccessCardViewed ||
!slices.Equal(fixture.contact.audits[0].FieldCodes(), []string{"categories", "stack"}) {
t.Fatalf("quota calls = %d, audits = %v, want one charge and one view of the returned fields", fixture.quotaCalls, fixture.contact.audits)
}
}
func TestSearchViewsReportAnExhaustedAllowanceWithoutAWrite(t *testing.T) {
t.Parallel()
fixture := newCategoriesSectionFixture(t, nil, false, domain.ScenarioEmployer)
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID)
if err != nil {
return err
}
allowed, err := views.Reserve(ctx, uuid.New())
if err != nil || allowed {
t.Fatalf("Reserve() = %v, %v, want a refusal without an error", allowed, err)
}
return nil
})
if err != nil || len(fixture.contact.audits) != 0 {
t.Fatalf("error = %v, audits = %v, want no record for a refused view", err, fixture.contact.audits)
}
candidate := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate)
err = candidate.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := candidate.service.BeginSearchViews(ctx, unit, candidate.actorID, candidate.organizationID)
return err
})
if !errors.Is(err, ErrForbidden) {
t.Fatalf("BeginSearchViews(candidate) error = %v, want ErrForbidden", err)
}
}
@@ -47,6 +47,8 @@ func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quot
return repository.decision, repository.err
}
func (repository *quotaTestRepository) LockOrganization(context.Context, uuid.UUID) error { return nil }
func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
repository.cardViewCalls++
repository.cardViewQuota = quota
@@ -67,6 +67,18 @@ func (repository *evidenceTestRepository) ListOrganizationFacts(
return nil, nil
}
func (repository *evidenceTestRepository) ListOrganizationFactsBatch(
context.Context, uuid.UUID, []outbound.EvidenceCandidateCategories,
) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) {
return nil, errors.New("the single organization read must not use the batch read")
}
func (repository *evidenceTestRepository) CountComparableRealCategories(
context.Context, []outbound.CategoryKey,
) (map[outbound.CategoryKey]int64, error) {
return nil, errors.New("the evidence read must not count cohorts")
}
func (repository *evidenceTestRepository) ListPreviewFacts(context.Context, uuid.UUID, []domain.CandidateViewCategory) ([]domain.EvidenceOrganizationFact, error) {
return nil, errors.New("the organization read must not read the preview")
}
@@ -0,0 +1,150 @@
package matching
import (
"slices"
"lincodex/backend/internal/domain"
)
// explanationInput is what the explanation reads: the computed scores of the
// entry and the facts of the card. It builds nothing that the scores did not
// compute, so a change of the requirements moves the numbers and the
// explanation together.
type explanationInput struct {
confirmed bool
declaredGrade *domain.GradeCode
policy domain.MatchingPolicy
scores scores
context PublicContext
// requestedFormats are the work formats that the search asks for; it is
// empty when neither the need nor a filter names any.
requestedFormats []domain.QuestionnaireWorkFormat
// needDomainConfirmed tells why the domain is unknown: the card has no
// domain, and the need may not have confirmed one either.
needDomainConfirmed bool
// percentileReason is the reason that the percentile is null; the zero
// value means the cohort is below the minimum.
percentileReason UnknownReason
}
// explain builds the bounded, templated explanation and the unknown flags.
// An unknown component appears only in the flags and is never shown as a
// verdict about the person, and the absence of FSP data is neither a gap nor
// an unknown here: the competition component is zero by definition.
func explain(input explanationInput) ([]EvidenceItem, []UnknownFlag) {
return evidenceSummary(input), unknownFlags(input)
}
func evidenceSummary(input explanationInput) []EvidenceItem {
items := make([]EvidenceItem, 0, 6)
if input.confirmed {
items = append(items, EvidenceItem{Code: EvidenceConfirmedCategory, State: EvidenceStateSupports})
}
if input.declaredGrade != nil {
items = append(items, EvidenceItem{Code: EvidenceDeclaredGrade, State: EvidenceStateDeclaredOnly})
}
if state, ok := skillGroupState(input, true); ok {
items = append(items, EvidenceItem{Code: EvidenceRequiredSkill, State: state})
}
if state, ok := skillGroupState(input, false); ok {
items = append(items, EvidenceItem{Code: EvidenceDesiredSkill, State: state})
}
if len(input.requestedFormats) > 0 && len(input.context.WorkFormats) > 0 {
state := EvidenceStateGap
for _, format := range input.context.WorkFormats {
if slices.Contains(input.requestedFormats, format) {
state = EvidenceStateSupports
break
}
}
items = append(items, EvidenceItem{Code: EvidenceWorkConditionsMatch, State: state})
}
if compatibility := input.context.SalaryCompatibility; compatibility != nil {
state := EvidenceStateGap
if *compatibility == domain.CandidateViewSalaryCompatible {
state = EvidenceStateSupports
}
items = append(items, EvidenceItem{Code: EvidenceSalaryCompatibility, State: state})
}
return items
}
// skillGroupState summarizes the skills of one weight class from their
// computed contributions. A skill is supported by a measurement that reaches
// the policy threshold, declared when only a stated claim carries it, partial
// when a measurement exists but stays below the threshold, and a gap when
// nothing counts. The group is supported or a gap only when every skill is.
func skillGroupState(input explanationInput, required bool) (EvidenceState, bool) {
threshold := int64(input.policy.NearSkillThreshold) * picoPerBasisPoint
var total, supported, declared, gaps int
for _, skill := range input.scores.skills {
if skill.required != required {
continue
}
total++
switch {
case skill.pico == 0:
gaps++
case skill.measured && skill.pico >= threshold:
supported++
case !skill.measured:
declared++
}
}
switch {
case total == 0:
return "", false
case supported == total:
return EvidenceStateSupports, true
case gaps == total:
return EvidenceStateGap, true
case declared == total:
return EvidenceStateDeclaredOnly, true
default:
return EvidenceStatePartial, true
}
}
// unknownFlags lists, in the order of the contract's component list, every
// value that is neutral or absent. A confirmed entry shows the neutral T and
// the neutral freshness and responsiveness; an unconfirmed entry shows that
// the specialization has no confirmation instead.
func unknownFlags(input explanationInput) []UnknownFlag {
flags := make([]UnknownFlag, 0, 9)
flags = append(flags, UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable})
if input.confirmed {
reason := input.percentileReason
if reason == "" {
reason = ReasonCohortBelow30
}
flags = append(flags, UnknownFlag{Component: UnknownPercentile, Reason: reason})
} else {
flags = append(flags, UnknownFlag{Component: UnknownAssessment, Reason: ReasonNoConfirmationForSpecialization})
}
if input.confirmed {
flags = append(flags,
UnknownFlag{Component: UnknownFreshness, Reason: ReasonNoFreshnessHistory},
UnknownFlag{Component: UnknownResponsiveness, Reason: ReasonNoResponseHistory},
)
}
if input.context.ExperienceBand == nil {
flags = append(flags, UnknownFlag{Component: UnknownExperienceBand, Reason: ReasonNotInPublicCard})
}
if len(input.context.WorkFormats) == 0 {
flags = append(flags, UnknownFlag{Component: UnknownWorkFormats, Reason: ReasonNotInPublicCard})
}
if input.context.SalaryCompatibility == nil {
flags = append(flags, UnknownFlag{Component: UnknownSalaryCompatibility, Reason: ReasonNotInPublicCard})
}
flags = append(flags, domainFlag(input))
return flags
}
// domainFlag says why Dom is the neutral value. The anonymous card never
// carries a domain, so a confirmed need domain cannot be compared with it.
func domainFlag(input explanationInput) UnknownFlag {
if input.needDomainConfirmed {
return UnknownFlag{Component: UnknownDomain, Reason: ReasonNotInPublicCard}
}
return UnknownFlag{Component: UnknownDomain, Reason: ReasonNeedFieldUnconfirmed}
}
@@ -0,0 +1,67 @@
package matching
import (
"slices"
"lincodex/backend/internal/domain"
)
// accepts reports whether one candidate specialization passes every explicit
// filter and the effective specialization. A filter that names a confirmed
// grade or category excludes every unconfirmed specialization, and a
// declaration never satisfies a confirmed filter. An unknown card value never
// satisfies a condition.
func (filters Filters) accepts(entry candidateEntry, specialization *domain.SpecializationCode) bool {
if specialization != nil && entry.specialization != *specialization {
return false
}
return filters.acceptsConfirmation(entry) && filters.acceptsCard(entry)
}
func (filters Filters) acceptsConfirmation(entry candidateEntry) bool {
confirmed := entry.category != nil
if filters.ConfirmedGrade != nil && (!confirmed || entry.category.Grade != *filters.ConfirmedGrade) {
return false
}
if category := filters.ConfirmedCategory; category != nil {
if !confirmed || entry.category.Specialization != category.Specialization || entry.category.Grade != category.Grade {
return false
}
}
if status := filters.ConfirmationStatus; status != nil && (*status == domain.CandidateViewConfirmationConfirmed) != confirmed {
return false
}
return filters.DeclaredGrade == nil || (entry.declaredGrade != nil && *entry.declaredGrade == *filters.DeclaredGrade)
}
func (filters Filters) acceptsCard(entry candidateEntry) bool {
for _, tag := range filters.Stack {
if !slices.Contains(entry.card.Skills, tag) {
return false
}
}
return filters.Conditions.accepts(entry.card)
}
func (conditions *Conditions) accepts(card domain.AnonymousCandidateViewDTO) bool {
if conditions == nil {
return true
}
if len(conditions.WorkFormats) > 0 {
offered := false
for _, format := range card.WorkFormats {
if slices.Contains(conditions.WorkFormats, format) {
offered = true
break
}
}
if !offered {
return false
}
}
if conditions.SalaryCompatibility != nil &&
(card.SalaryCompatibility == nil || *card.SalaryCompatibility != *conditions.SalaryCompatibility) {
return false
}
return true
}
@@ -0,0 +1,119 @@
package matching
import (
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func gradePointer(grade domain.GradeCode) *domain.GradeCode { return &grade }
func TestEntriesOfKeepsEverySpecializationSeparate(t *testing.T) {
middle, junior := domain.GradeMiddle, domain.GradeJunior
card := domain.AnonymousCandidateViewDTO{
Pseudonym: "handle",
Categories: []domain.CandidateViewCategory{
{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard},
},
SelfAssessment: []domain.CandidateViewSelfAssessment{
{Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed, DeclaredGrade: &junior},
{Specialization: domain.SpecializationNetworkEngineer, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed, DeclaredGrade: &middle},
// Confirmed in the self-assessment but not shown as a category:
// the card does not publish that confirmation, so no entry claims it.
{Specialization: domain.SpecializationQA, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed},
},
}
entries := entriesOf(domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: card})
got := make([]string, 0, len(entries))
for _, entry := range entries {
state := "unconfirmed"
if entry.category != nil {
state = "confirmed"
}
got = append(got, string(entry.specialization)+":"+state)
}
if want := []string{"backend:confirmed", "network_engineer:unconfirmed"}; !slices.Equal(got, want) {
t.Fatalf("entries = %v, want %v", got, want)
}
if entries[0].declaredGrade == nil || *entries[0].declaredGrade != domain.GradeJunior ||
entries[1].declaredGrade == nil || *entries[1].declaredGrade != domain.GradeMiddle {
t.Fatalf("declared grades = %v and %v, want each specialization's own", entries[0].declaredGrade, entries[1].declaredGrade)
}
}
func TestFiltersKeepTheConfirmedAndDeclaredClaimsApart(t *testing.T) {
remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}
compatible := domain.CandidateViewSalaryCompatible
confirmed := candidateEntry{
specialization: domain.SpecializationBackend,
category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle},
declaredGrade: gradePointer(domain.GradeJunior),
card: domain.AnonymousCandidateViewDTO{Skills: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}, WorkFormats: remote, SalaryCompatibility: &compatible},
}
unconfirmed := candidateEntry{
specialization: domain.SpecializationBackend, declaredGrade: gradePointer(domain.GradeMiddle),
card: domain.AnonymousCandidateViewDTO{WorkFormats: remote},
}
backend := domain.SpecializationBackend
frontend := domain.SpecializationFrontend
status := func(value domain.CandidateViewConfirmationStatus) *domain.CandidateViewConfirmationStatus {
return &value
}
tests := []struct {
name string
filters Filters
specialization *domain.SpecializationCode
wantConfirmed, wantUnconf bool
}{
{name: "no filter", filters: Filters{}, wantConfirmed: true, wantUnconf: true},
{name: "specialization", filters: Filters{}, specialization: &backend, wantConfirmed: true, wantUnconf: true},
{name: "another specialization", filters: Filters{}, specialization: &frontend},
{name: "confirmed grade excludes the unconfirmed", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeMiddle)}, wantConfirmed: true},
{name: "a declared grade never satisfies a confirmed grade", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeJunior)}},
{
name: "confirmed category",
filters: Filters{ConfirmedCategory: &GradeFilter{Specialization: backend, Grade: domain.GradeMiddle}},
wantConfirmed: true,
},
{name: "confirmation status confirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationConfirmed)}, wantConfirmed: true},
{name: "confirmation status unconfirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationUnconfirmed)}, wantUnconf: true},
{name: "declared grade", filters: Filters{DeclaredGrade: gradePointer(domain.GradeMiddle)}, wantUnconf: true},
{
name: "every stack tag is required",
filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}},
wantConfirmed: true,
},
{name: "a stack tag the card lacks", filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillDocker}}},
{name: "work format", filters: Filters{Conditions: &Conditions{WorkFormats: remote}}, wantConfirmed: true, wantUnconf: true},
{
name: "an unknown salary compatibility never satisfies the condition",
filters: Filters{Conditions: &Conditions{SalaryCompatibility: &compatible}}, wantConfirmed: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := test.filters.accepts(confirmed, test.specialization); got != test.wantConfirmed {
t.Errorf("accepts(confirmed) = %v, want %v", got, test.wantConfirmed)
}
if got := test.filters.accepts(unconfirmed, test.specialization); got != test.wantUnconf {
t.Errorf("accepts(unconfirmed) = %v, want %v", got, test.wantUnconf)
}
})
}
}
func TestEffectiveSpecializationNeverMergesTwoDifferentOnes(t *testing.T) {
backend, frontend := domain.SpecializationBackend, domain.SpecializationFrontend
if got, ok := effectiveSpecialization(&backend, &frontend); ok || got != nil {
t.Fatalf("effectiveSpecialization(backend, frontend) = %v, %v, want an empty search", got, ok)
}
if got, ok := effectiveSpecialization(nil, &frontend); !ok || got == nil || *got != frontend {
t.Fatalf("effectiveSpecialization(nil, frontend) = %v, %v, want the need specialization", got, ok)
}
if got, ok := effectiveSpecialization(nil, nil); !ok || got != nil {
t.Fatalf("effectiveSpecialization(nil, nil) = %v, %v, want no restriction", got, ok)
}
}
@@ -0,0 +1,126 @@
package matching
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// cohortEvidence answers the cohort count and no fact.
type cohortEvidence struct {
outbound.EvidenceRepository
counts map[outbound.CategoryKey]int64
asked [][]outbound.CategoryKey
}
func (evidence *cohortEvidence) CountComparableRealCategories(
_ context.Context, categories []outbound.CategoryKey,
) (map[outbound.CategoryKey]int64, error) {
evidence.asked = append(evidence.asked, categories)
return evidence.counts, nil
}
type cohortUnit struct {
outbound.UnitOfWork
evidence *cohortEvidence
}
func (unit cohortUnit) Evidence() outbound.EvidenceRepository { return unit.evidence }
func confirmedCard(specialization domain.SpecializationCode, grade domain.GradeCode) domain.VisibleCandidateCard {
return domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: domain.AnonymousCandidateViewDTO{
Pseudonym: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
Categories: []domain.CandidateViewCategory{{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard}},
}}
}
func TestRankKeepsTheNeutralTWhenTheRealCohortReachesTheMinimum(t *testing.T) {
policy := domain.DemoMatchingPolicy()
backendIntern := outbound.CategoryKey{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}
frontendJunior := outbound.CategoryKey{Specialization: domain.SpecializationFrontend, Grade: domain.GradeJunior}
evidence := &cohortEvidence{counts: map[outbound.CategoryKey]int64{
backendIntern: int64(policy.PercentileMinCohort),
frontendJunior: int64(policy.PercentileMinCohort) - 1,
}}
var logs bytes.Buffer
service := &Service{logger: slog.New(slog.NewTextHandler(&logs, nil))}
cards := []domain.VisibleCandidateCard{
confirmedCard(domain.SpecializationBackend, domain.GradeIntern),
confirmedCard(domain.SpecializationBackend, domain.GradeIntern),
confirmedCard(domain.SpecializationFrontend, domain.GradeJunior),
}
ranked, err := service.rank(context.Background(), cohortUnit{evidence: evidence}, Request{}, searchBasis{}, policy, cards)
if err != nil {
t.Fatalf("rank() error = %v, want a result whatever the real cohort size", err)
}
if len(ranked.main) != 3 {
t.Fatalf("main = %d entries, want 3", len(ranked.main))
}
// Only the categories of the accepted entries are counted, each once.
if len(evidence.asked) != 1 || len(evidence.asked[0]) != 2 {
t.Fatalf("cohort questions = %v, want one question for the two categories of the entries", evidence.asked)
}
reasons := map[domain.SpecializationCode]UnknownReason{}
for _, item := range ranked.main {
for _, flag := range item.entry.UnknownFlags {
if flag.Component == UnknownPercentile {
reasons[item.entry.Specialization] = flag.Reason
}
}
if item.entry.Components.Percentile != nil || microToFloat(item.rank) != item.entry.Components.RankScore {
t.Fatalf("entry %+v has a percentile or a rank that is not the neutral-T rank", item.entry.Components)
}
// T is the neutral 0.5 in every case: Cov, Dom, Sem 0.5 give S = 0.45125.
if item.entry.Components.RankScore != 0.45125 {
t.Fatalf("rank score = %v, want 0.45125 with the neutral T", item.entry.Components.RankScore)
}
}
if reasons[domain.SpecializationBackend] != ReasonPercentileNotComputed || reasons[domain.SpecializationFrontend] != ReasonCohortBelow30 {
t.Fatalf("percentile reasons = %v, want not computed at the minimum and below 30 under it", reasons)
}
if strings.Count(logs.String(), "reached the percentile minimum") != 1 || !strings.Contains(logs.String(), "specialization=backend") {
t.Fatalf("log = %q, want one warning for the one category that reached the minimum", logs.String())
}
}
// repeatingTransactor fails with a visibility change a number of times and then
// succeeds without running the work.
type repeatingTransactor struct {
failures int
calls int
}
func (transactor *repeatingTransactor) WithinTransaction(context.Context, func(context.Context, outbound.UnitOfWork) error) error {
transactor.calls++
if transactor.calls <= transactor.failures {
return fmt.Errorf("lock the cohort: %w", outbound.ErrConcurrentVisibilityChange)
}
return nil
}
func TestSearchRepeatsAfterAConcurrentVisibilityChangeAFewTimes(t *testing.T) {
request := Request{ActorID: uuid.New(), OrganizationID: uuid.New()}
for _, test := range []struct {
failures, calls int
wantErr bool
}{{0, 1, false}, {2, 3, false}, {3, 3, true}} {
transactor := &repeatingTransactor{failures: test.failures}
service := &Service{transactor: transactor}
_, err := service.Search(context.Background(), request)
if transactor.calls != test.calls || (err != nil) != test.wantErr ||
(err != nil && !errors.Is(err, outbound.ErrConcurrentVisibilityChange)) {
t.Errorf("%d failures: %d attempts, error %v; want %d attempts, error %v", test.failures, transactor.calls, err, test.calls, test.wantErr)
}
}
}
@@ -0,0 +1,129 @@
package matching
import (
"context"
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// viewsFake charges a fixed number of distinct candidates and records what it
// is asked to write.
type viewsFake struct {
allowance int
reserved map[uuid.UUID]bool
attempts []uuid.UUID
recorded map[uuid.UUID][]domain.CardField
order []uuid.UUID
}
func newViewsFake(allowance int) *viewsFake {
return &viewsFake{allowance: allowance, reserved: map[uuid.UUID]bool{}, recorded: map[uuid.UUID][]domain.CardField{}}
}
func (views *viewsFake) Reserve(_ context.Context, candidateID uuid.UUID) (bool, error) {
views.attempts = append(views.attempts, candidateID)
if views.reserved[candidateID] {
return true, nil
}
if len(views.reserved) >= views.allowance {
return false, nil
}
views.reserved[candidateID] = true
return true, nil
}
func (views *viewsFake) Record(_ context.Context, candidateID uuid.UUID, fields []domain.CardField) error {
views.recorded[candidateID] = fields
views.order = append(views.order, candidateID)
return nil
}
func revealService(views *viewsFake) *Service {
return &Service{views: func(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID) (ViewSession, error) {
return views, nil
}}
}
func confirmedItem(id uuid.UUID) rankedEntry {
band := domain.CandidateExperienceBandOneToThree
return rankedEntry{candidate: id, entry: Entry{
Specialization: domain.SpecializationBackend,
Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior},
PublicContext: PublicContext{ExperienceBand: &band, Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo}},
}}
}
func declaredItem(id uuid.UUID, specialization domain.SpecializationCode) rankedEntry {
return rankedEntry{candidate: id, entry: Entry{Specialization: specialization}}
}
func TestRevealCutsEachGroupAndRecordsTheFieldsReturned(t *testing.T) {
first, second := uuid.New(), uuid.New()
policy := domain.DemoMatchingPolicy()
policy.MaxResultsPerGroup = 2
views := newViewsFake(10)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, policy, groups{
main: []rankedEntry{confirmedItem(first), confirmedItem(second), confirmedItem(uuid.New())},
unconfirmed: []rankedEntry{declaredItem(first, domain.SpecializationNetworkEngineer)},
})
if err != nil {
t.Fatalf("reveal() error = %v", err)
}
if len(result.Main) != 2 || len(result.Unconfirmed) != 1 || !result.Truncated {
t.Fatalf("result = %d main, %d unconfirmed, truncated %v, want the group cut at 2 and flagged", len(result.Main), len(result.Unconfirmed), result.Truncated)
}
// The first candidate appears twice and is charged once; the dropped third
// entry is never charged.
if len(views.reserved) != 2 || !views.reserved[first] || !views.reserved[second] {
t.Fatalf("reserved = %v, want the two returned candidates", views.reserved)
}
// The fields are those that the returned entries show: the category, the
// stack, and the experience of the Backend entry plus the self-assessment of
// the Networks entry.
want := []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, domain.CardFieldSelfAssessment}
if !slices.Equal(views.recorded[first], want) {
t.Fatalf("recorded fields of the first candidate = %v, want %v", views.recorded[first], want)
}
if got := views.recorded[second]; !slices.Equal(got, want[:3]) {
t.Fatalf("recorded fields of the second candidate = %v, want %v", got, want[:3])
}
}
func TestRevealReturnsThePrefixThatIsPaidForWhenTheAllowanceEnds(t *testing.T) {
ids := []uuid.UUID{uuid.New(), uuid.New(), uuid.New(), uuid.New()}
views := newViewsFake(2)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
main: []rankedEntry{confirmedItem(ids[0])},
near: []rankedEntry{confirmedItem(ids[1]), confirmedItem(ids[2])},
unconfirmed: []rankedEntry{declaredItem(ids[0], domain.SpecializationNetworkEngineer), declaredItem(ids[3], domain.SpecializationQA)},
})
if err != nil {
t.Fatalf("reveal() error = %v", err)
}
if len(result.Main) != 1 || len(result.Near) != 1 || len(result.Unconfirmed) != 0 || !result.Truncated {
t.Fatalf("result = %d/%d/%d truncated %v, want the entries before the refusal and nothing after it",
len(result.Main), len(result.Near), len(result.Unconfirmed), result.Truncated)
}
if len(views.reserved) != 2 || len(views.recorded) != 2 || views.reserved[ids[2]] || views.reserved[ids[3]] {
t.Fatalf("reserved %v, recorded %v, want only the two paid candidates", views.reserved, views.recorded)
}
}
func TestRevealDoesNotFlagACompleteResult(t *testing.T) {
views := newViewsFake(5)
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
main: []rankedEntry{confirmedItem(uuid.New())},
})
if err != nil || result.Truncated || len(result.Main) != 1 {
t.Fatalf("reveal() = %+v, %v, want one entry that is not truncated", result, err)
}
empty, err := revealService(newViewsFake(0)).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{})
if err != nil || empty.Truncated || len(empty.Main)+len(empty.Near)+len(empty.Unconfirmed) != 0 {
t.Fatalf("an empty search = %+v, %v, want an empty result that is not truncated", empty, err)
}
}
+171
View File
@@ -0,0 +1,171 @@
package matching
import (
"lincodex/backend/internal/domain"
)
// Scores are computed in integers so that the same data and policy always give
// the same order on every platform. A policy share is BasisPoints (1e-4); a
// component is stored in micro units (1e-6), the precision at which results
// are rounded and compared; a skill contribution keeps the exact product of
// three shares in pico units (1e-12).
const (
microPerUnit int64 = 1_000_000
bpPerUnit int64 = 10_000
picoPerBasisPoint int64 = 100_000_000
microPerBasisPoint int64 = 100
)
// requestedSkill is one skill that a need or a stack filter asks for. A skill
// without a taxonomy code cannot match any evidence: the platform has no
// reviewed mapping for it, so it stays a gap and never an invented match.
type requestedSkill struct {
code string
required bool
}
// evidenceSource is one permitted piece of evidence of a candidate: either a
// stated stack tag of the card (trust 0, a claim) or the one assessment fact
// that supports the confirmed category.
type evidenceSource struct {
code string
trust domain.EvidenceTrust
attribution domain.EvidenceAttribution
measured bool
}
// skillOutcome is the contribution of one requested skill and what it rests
// on. The explanation reads these exact values.
type skillOutcome struct {
required bool
pico int64
// measured is true when the best evidence is a measurement and false when
// it is a stated claim or when there is none.
measured bool
}
// scores are the computed components of one entry, in micro units.
type scores struct {
skills []skillOutcome
coverage int64
domain int64
semantics int64
fit int64
t int64
competition int64
strength int64
freshness int64
responsive int64
rank int64
}
// scoreInput is everything a score depends on.
type scoreInput struct {
// confirmed selects the confirmed-profile model. An unconfirmed profile
// gets only coverage and fit: it has no theta, T, P, or rank score, so
// those values are never computed for it.
confirmed bool
policy domain.MatchingPolicy
skills []requestedSkill
evidence []evidenceSource
}
// computeScores applies the FR09 model. Unknown components are neutral: Dom,
// Sem, Fr, and Rsp use the neutral value, T is neutral because there is no
// comparable real cohort, and V is zero because no competition evidence
// exists, which is not a penalty.
func computeScores(input scoreInput) scores {
policy := input.policy
neutral := int64(policy.NeutralUnknown) * microPerBasisPoint
result := scores{
domain: neutral, semantics: neutral, t: neutral, freshness: neutral, responsive: neutral,
}
result.skills = make([]skillOutcome, 0, len(input.skills))
var weighted, weights int64
for _, skill := range input.skills {
pico, measured := skillContribution(policy, skill, input.evidence)
weight := int64(policy.DesiredSkillWeight)
if skill.required {
weight = int64(policy.RequiredSkillWeight)
}
weighted += weight * pico
weights += weight
result.skills = append(result.skills, skillOutcome{required: skill.required, pico: pico, measured: measured})
}
// An empty request has nothing to cover; it uses the neutral value instead
// of dividing by zero.
result.coverage = neutral
if weights > 0 {
result.coverage = roundedQuotient(weighted, weights*microPerUnit)
}
result.fit = roundedQuotient(
int64(policy.FitCoverageWeight)*result.coverage+
int64(policy.FitDomainWeight)*result.domain+
int64(policy.FitSemanticsWeight)*result.semantics,
bpPerUnit)
if !input.confirmed {
result.t, result.freshness, result.responsive = 0, 0, 0
return result
}
// P = T + boost * (1 - T) * V, with V = 0 without competition evidence.
result.strength = result.t + roundedQuotient(
int64(policy.CompetitionBoost)*(microPerUnit-result.t)*result.competition, bpPerUnit*microPerUnit)
rank := roundedQuotient(
int64(policy.RankFitWeight)*result.fit+int64(policy.RankStrengthWeight)*result.strength, bpPerUnit)
rank = multiplyMicro(rank, blendedMultiplier(policy.FreshnessFloor, result.freshness))
result.rank = multiplyMicro(rank, blendedMultiplier(policy.ResponsivenessFloor, result.responsive))
return result
}
// skillContribution is the best product of the trust, attribution, and
// relation coefficients over the evidence, not their sum, so a repeated tag or
// a second piece of the same kind never raises the contribution. A tie goes to
// the measurement, so the explanation names the stronger basis.
func skillContribution(policy domain.MatchingPolicy, skill requestedSkill, evidence []evidenceSource) (int64, bool) {
if skill.code == "" {
return 0, false
}
var best int64
var measured bool
for _, source := range evidence {
trust, trustOK := policy.TrustCoefficient(source.trust)
attribution, attributionOK := policy.AttributionCoefficient(source.attribution)
if !trustOK || !attributionOK {
continue
}
relation := policy.RelationCoefficient(policy.RelateSkill(skill.code, source.code))
value := int64(trust) * int64(attribution) * int64(relation)
if value > best || (value == best && value > 0 && source.measured && !measured) {
best, measured = value, source.measured
}
}
return best, measured
}
// belongsToNearGroup reports whether a requested required skill earns less
// than the policy threshold, which moves a confirmed profile to "near".
func (result scores) belongsToNearGroup(policy domain.MatchingPolicy) bool {
threshold := int64(policy.NearSkillThreshold) * picoPerBasisPoint
for _, skill := range result.skills {
if skill.required && skill.pico < threshold {
return true
}
}
return false
}
// blendedMultiplier is floor + (1 - floor) * x, in micro units.
func blendedMultiplier(floor domain.BasisPoints, x int64) int64 {
return int64(floor)*microPerBasisPoint + roundedQuotient((bpPerUnit-int64(floor))*x, bpPerUnit)
}
func multiplyMicro(left, right int64) int64 {
return roundedQuotient(left*right, microPerUnit)
}
// roundedQuotient divides non-negative integers and rounds half up.
func roundedQuotient(numerator, denominator int64) int64 {
return (numerator + denominator/2) / denominator
}
func microToFloat(value int64) float64 { return float64(value) / float64(microPerUnit) }
@@ -0,0 +1,283 @@
package matching
import (
"slices"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
onlineBackendFact = evidenceSource{code: "backend", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true}
statedGo = evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
statedKafka = evidenceSource{code: "kafka", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
)
func required(code string) requestedSkill { return requestedSkill{code: code, required: true} }
func desired(code string) requestedSkill { return requestedSkill{code: code} }
func TestComputeScoresFollowsTheFR09Formulas(t *testing.T) {
policy := domain.DemoMatchingPolicy()
tests := []struct {
name string
confirmed bool
skills []requestedSkill
evidence []evidenceSource
coverage int64
fit int64
rank int64
near bool
}{
{
// 0.6 online trust * 1.0 personal * 0.4 broader relation = 0.24:
// Cov 0.24, Fit 0.75*0.24+0.15*0.5+0.10*0.5 = 0.305, P = T = 0.5,
// S = (0.5*0.305+0.5*0.5) * 0.95 * 0.95 = 0.363256.
name: "a broad measurement under a requested technology is below the near threshold", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{onlineBackendFact},
coverage: 240000, fit: 305000, rank: 363256, near: true,
},
{
// A stated tag is a claim with trust 0.25.
name: "a stated tag reaches the threshold exactly", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo},
coverage: 250000, fit: 312500, rank: 366641, near: false,
},
{
name: "the best evidence counts once, not the sum of duplicates", confirmed: true,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo, statedGo, onlineBackendFact, onlineBackendFact},
coverage: 250000, fit: 312500, rank: 366641, near: false,
},
{
name: "weights are 2 for required and 1 for desired", confirmed: true,
skills: []requestedSkill{required("go"), desired("kafka")},
evidence: []evidenceSource{onlineBackendFact, statedKafka},
coverage: 243333, fit: 307500, rank: 364385, near: true,
},
{
name: "an empty request is neutral and never divides by zero", confirmed: true,
skills: nil, evidence: []evidenceSource{onlineBackendFact},
coverage: 500000, fit: 500000, rank: 451250, near: false,
},
{
// Cov 0: Fit 0.125, S = (0.5*0.125+0.25) * 0.9025 = 0.282031.
name: "a skill without a taxonomy mapping is a gap", confirmed: true,
skills: []requestedSkill{required("")}, evidence: []evidenceSource{onlineBackendFact, statedGo},
coverage: 0, fit: 125000, rank: 282031, near: true,
},
{
name: "an unconfirmed profile has fit and coverage only", confirmed: false,
skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo},
coverage: 250000, fit: 312500, rank: 0, near: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := computeScores(scoreInput{confirmed: test.confirmed, policy: policy, skills: test.skills, evidence: test.evidence})
if got.coverage != test.coverage || got.fit != test.fit {
t.Fatalf("coverage/fit = %d/%d, want %d/%d", got.coverage, got.fit, test.coverage, test.fit)
}
if test.confirmed && got.rank != test.rank {
t.Fatalf("rank = %d, want %d", got.rank, test.rank)
}
if got.belongsToNearGroup(policy) != test.near {
t.Fatalf("near = %v, want %v", got.belongsToNearGroup(policy), test.near)
}
})
}
}
func TestComputeScoresNeverGivesAnUnconfirmedProfileStrength(t *testing.T) {
got := computeScores(scoreInput{
confirmed: false, policy: domain.DemoMatchingPolicy(), skills: []requestedSkill{required("go")},
evidence: []evidenceSource{statedGo},
})
if got.t != 0 || got.strength != 0 || got.rank != 0 || got.freshness != 0 || got.responsive != 0 {
t.Fatalf("unconfirmed scores = %+v, want no T, P, S, or rank multipliers", got)
}
}
func TestComputeScoresIsRepeatable(t *testing.T) {
input := scoreInput{
confirmed: true, policy: domain.DemoMatchingPolicy(),
skills: []requestedSkill{required("go"), required("postgresql"), desired("kafka"), desired("docker")},
evidence: []evidenceSource{onlineBackendFact, statedGo, statedKafka},
}
first := computeScores(input)
for range 20 {
if again := computeScores(input); !slices.Equal(again.skills, first.skills) || again.rank != first.rank || again.fit != first.fit {
t.Fatalf("computeScores() changed between runs: %+v then %+v", first, again)
}
}
}
func TestSkillContributionPrefersAMeasurementOnATie(t *testing.T) {
policy := domain.DemoMatchingPolicy()
policy.TrustStated = policy.TrustOnline
measured := evidenceSource{code: "go", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true}
stated := evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}
for _, evidence := range [][]evidenceSource{{stated, measured}, {measured, stated}} {
if _, isMeasured := skillContribution(policy, required("go"), evidence); !isMeasured {
t.Fatalf("skillContribution(%v) reported a claim although an equal measurement exists", evidence)
}
}
}
func TestRequestedSkillsCountEachCodeOnce(t *testing.T) {
goCode, kafkaCode := "go", "kafka"
confirmedSkill := func(name string, code *string) domain.NeedSkill {
return domain.NeedSkill{Name: name, TaxonomyCode: code, Status: domain.NeedItemConfirmed}
}
skills := requestedSkills(
[]domain.NeedSkill{
confirmedSkill("Go", &goCode), confirmedSkill("Golang", &goCode), confirmedSkill("Temporal", nil), confirmedSkill(" temporal ", nil),
{Name: "Rust", Status: domain.NeedItemExtracted},
},
[]domain.NeedSkill{confirmedSkill("Kafka", &kafkaCode), confirmedSkill("Go again", &goCode)},
[]domain.CandidateViewSkillCode{domain.CandidateViewSkillKafka, domain.CandidateViewSkillDocker},
)
want := []requestedSkill{
{code: "go", required: true}, {required: true}, {code: "kafka", required: true}, {code: "docker", required: true},
}
if !slices.Equal(skills, want) {
t.Fatalf("requestedSkills() = %+v, want %+v", skills, want)
}
}
func TestExplanationReadsTheComputedContributions(t *testing.T) {
policy := domain.DemoMatchingPolicy()
explainWith := func(confirmed bool, skills []requestedSkill, evidence []evidenceSource, context PublicContext, formats []domain.QuestionnaireWorkFormat) []EvidenceItem {
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: skills, evidence: evidence})
items, _ := explain(explanationInput{confirmed: confirmed, policy: policy, scores: computed, context: context, requestedFormats: formats})
return items
}
remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}
office := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatOffice}
tests := []struct {
name string
got []EvidenceItem
want []EvidenceItem
}{
{
name: "all required skills carried by measurements",
got: explainWith(true, []requestedSkill{required("backend")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStateSupports}},
},
{
name: "a measurement below the threshold is partial",
got: explainWith(true, []requestedSkill{required("go")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStatePartial}},
},
{
name: "only stated tags are declared",
got: explainWith(false, []requestedSkill{required("go")}, []evidenceSource{statedGo}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateDeclaredOnly}},
},
{
name: "nothing carries the skills",
got: explainWith(false, []requestedSkill{required("go"), desired("kafka")}, nil, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateGap}, {EvidenceDesiredSkill, EvidenceStateGap}},
},
{
name: "a mix of covered and missing skills is partial",
got: explainWith(false, []requestedSkill{required("go"), required("kafka")}, []evidenceSource{statedGo}, PublicContext{}, nil),
want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStatePartial}},
},
{
name: "work formats are compared with the request",
got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, office),
want: []EvidenceItem{{EvidenceWorkConditionsMatch, EvidenceStateGap}},
},
{
name: "no request for skills or formats gives no item",
got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, nil),
want: []EvidenceItem{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if len(test.got) == 0 && len(test.want) == 0 {
return
}
if !slices.Equal(test.got, test.want) {
t.Fatalf("evidence summary = %+v, want %+v", test.got, test.want)
}
})
}
}
func TestUnknownFlagsNameNeutralValuesAndNeverFSP(t *testing.T) {
policy := domain.DemoMatchingPolicy()
computed := computeScores(scoreInput{confirmed: true, policy: policy})
_, confirmedFlags := explain(explanationInput{confirmed: true, policy: policy, scores: computed})
wantConfirmed := []UnknownFlag{
{UnknownSemantics, ReasonMLUnavailable}, {UnknownPercentile, ReasonCohortBelow30},
{UnknownFreshness, ReasonNoFreshnessHistory}, {UnknownResponsiveness, ReasonNoResponseHistory},
{UnknownExperienceBand, ReasonNotInPublicCard}, {UnknownWorkFormats, ReasonNotInPublicCard},
{UnknownSalaryCompatibility, ReasonNotInPublicCard}, {UnknownDomain, ReasonNeedFieldUnconfirmed},
}
if !slices.Equal(confirmedFlags, wantConfirmed) {
t.Fatalf("confirmed unknown flags = %+v, want %+v", confirmedFlags, wantConfirmed)
}
band := domain.CandidateExperienceBandOneToThree
compatible := domain.CandidateViewSalaryCompatible
_, unconfirmedFlags := explain(explanationInput{
policy: policy, needDomainConfirmed: true,
context: PublicContext{ExperienceBand: &band, SalaryCompatibility: &compatible, WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}},
})
wantUnconfirmed := []UnknownFlag{
{UnknownSemantics, ReasonMLUnavailable}, {UnknownAssessment, ReasonNoConfirmationForSpecialization},
{UnknownDomain, ReasonNotInPublicCard},
}
if !slices.Equal(unconfirmedFlags, wantUnconfirmed) {
t.Fatalf("unconfirmed unknown flags = %+v, want %+v", unconfirmedFlags, wantUnconfirmed)
}
}
func TestOrderingIsStableAndSeparateForEachGroup(t *testing.T) {
lowID := uuid.MustParse("00000000-0000-0000-0000-000000000001")
highID := uuid.MustParse("00000000-0000-0000-0000-000000000002")
entry := func(id uuid.UUID, specialization domain.SpecializationCode, fit, coverage, rank int64) rankedEntry {
return rankedEntry{
entry: Entry{Specialization: specialization},
candidate: id, fit: fit, coverage: coverage, rank: rank,
}
}
ids := func(items []rankedEntry) []uuid.UUID {
result := make([]uuid.UUID, len(items))
for index, item := range items {
result[index] = item.candidate
}
return result
}
t.Run("equal rank is resolved by coverage and then by the internal identifier", func(t *testing.T) {
items := []rankedEntry{
entry(highID, "backend", 0, 400000, 500000),
entry(lowID, "backend", 0, 400000, 500000),
entry(highID, "devops_sre", 0, 450000, 500000),
}
slices.SortStableFunc(items, compareByRank)
if got := ids(items); !slices.Equal(got, []uuid.UUID{highID, lowID, highID}) || items[0].entry.Specialization != "devops_sre" {
t.Fatalf("order = %v, want higher coverage first, then ascending identifiers", got)
}
})
t.Run("the unconfirmed group uses fit, then coverage, then the identifier", func(t *testing.T) {
items := []rankedEntry{
entry(highID, "qa", 300000, 100000, 999999),
entry(lowID, "qa", 300000, 100000, 1),
entry(highID, "frontend", 400000, 0, 0),
}
slices.SortStableFunc(items, compareByFit)
if items[0].entry.Specialization != "frontend" || items[1].candidate != lowID || items[2].candidate != highID {
t.Fatalf("order = %+v, want fit first and the rank score ignored", items)
}
})
t.Run("two entries of one candidate keep a stable order", func(t *testing.T) {
items := []rankedEntry{entry(lowID, "qa", 0, 0, 0), entry(lowID, "backend", 0, 0, 0)}
slices.SortStableFunc(items, compareByRank)
if items[0].entry.Specialization != "backend" {
t.Fatalf("order = %+v, want the specialization to separate equal entries", items)
}
})
}
+697
View File
@@ -0,0 +1,697 @@
// Package matching ranks the organization-visible candidate bank
// deterministically. It filters by the current visibility rules first, scores
// each candidate specialization with the versioned matching policy, and builds
// the explanation from the same computed components. It reads no contact, no
// raw assessment data, and no hidden minimum, and it consumes no ML result.
package matching
import (
"cmp"
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// VisibleCards returns the current organization-visible cards inside the
// caller's transaction. candidateview.Service.ListVisibleCards provides it;
// bootstrap passes it in so this package depends on no other usecase.
type VisibleCards func(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
) ([]domain.VisibleCandidateCard, error)
// ViewSession charges and records the candidates that one search reveals,
// inside the caller's transaction.
type ViewSession interface {
// Reserve counts the candidate as a distinct card view of the organization.
// A candidate already viewed inside the window is allowed without another
// charge. It reports false and writes nothing once the allowance is used up.
Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error)
// Record appends the access history entry for the fields that were returned.
Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error
}
// BeginViews opens a ViewSession for an authorized actor and organization.
// candidateview.Service.BeginSearchViews provides it through bootstrap.
type BeginViews func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (ViewSession, error)
// Dependencies configure the search service.
type Dependencies struct {
Transactor outbound.Transactor
Cards VisibleCards
Views BeginViews
Clock func() time.Time
// Logger receives the warnings of a search. A nil logger discards them.
Logger *slog.Logger
}
// Service searches and ranks the visible bank.
type Service struct {
transactor outbound.Transactor
cards VisibleCards
views BeginViews
clock func() time.Time
logger *slog.Logger
}
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Cards == nil || deps.Views == nil || deps.Clock == nil {
return nil, fmt.Errorf("matching.NewService - dependencies are missing: %w", ErrServiceMissing)
}
logger := deps.Logger
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return &Service{transactor: deps.Transactor, cards: deps.Cards, views: deps.Views, clock: deps.Clock, logger: logger}, nil
}
// Search returns the groups for one request. Everything runs in one
// transaction: the owner role, the membership, and the candidate visibility are
// checked and locked before any card is read, the need snapshot and the policy
// are read from storage, and the permitted evidence is read through the
// organization-safe projection queries, so no later read can widen what the
// first one allowed.
//
// A search reveals card content, so it is charged like card reads. The whole
// visible bank is ranked, but each group is cut to the policy's
// MaxResultsPerGroup, and no total is returned. Walking the output in the
// order main, near, unconfirmed, each newly revealed candidate is reserved as a
// distinct card view of the organization (a candidate already viewed inside the
// window costs nothing again) and recorded in the candidate's access history
// with the fields actually returned, in the same transaction. When the
// allowance runs out the entries already paid for are returned with Truncated
// set, and nothing is written for the rest.
func (service *Service) Search(ctx context.Context, request Request) (Result, error) {
const location = "matching.Service.Search"
if request.ActorID == uuid.Nil || request.OrganizationID == uuid.Nil {
return Result{}, ErrForbidden
}
var result Result
var err error
// The visible cohort can change while it is locked. The whole search is
// then repeated, a bounded number of times, and the writes of a failed
// attempt roll back with it.
for range maxSearchAttempts {
result, err = service.searchOnce(ctx, request)
if !errors.Is(err, outbound.ErrConcurrentVisibilityChange) {
break
}
}
if err != nil {
return Result{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// maxSearchAttempts bounds the repeats after a concurrent visibility change.
const maxSearchAttempts = 3
func (service *Service) searchOnce(ctx context.Context, request Request) (Result, error) {
const location = "matching.Service.searchOnce"
var result Result
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
// The MVP milestone allows only the active owner; a membership alone
// grants nothing here. The HTTP boundary checks the same rule, and the
// repeat keeps the usecase closed when it is called another way. The
// role is settled before the cohort is read and locked.
// The reservations below take the exclusive organization lock. Taking it
// first, before the share lock of the membership check, keeps two
// searches of one organization from deadlocking on the upgrade, and it
// serializes their charges.
if err := unit.CompanyQuotas().LockOrganization(ctx, request.OrganizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return outbound.ErrOrganizationNotFound
}
return fmt.Errorf("%s - lock organization: %w", location, err)
}
membership, err := unit.Organizations().LockActiveMembership(ctx, request.OrganizationID, request.ActorID)
if err != nil {
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner {
return ErrForbidden
}
cards, err := service.cards(ctx, unit, request.ActorID, request.OrganizationID)
if err != nil {
return err
}
policy, err := service.matchingPolicy(ctx, unit)
if err != nil {
return err
}
basis, err := loadBasis(ctx, unit, request)
if err != nil {
return err
}
ranked, err := service.rank(ctx, unit, request, basis, policy, cards)
if err != nil {
return err
}
result, err = service.reveal(ctx, unit, request, policy, ranked)
return err
})
if err != nil {
return Result{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func (service *Service) matchingPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.MatchingPolicy, error) {
const location = "matching.Service.matchingPolicy"
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, service.clock().UTC())
if err != nil {
return domain.MatchingPolicy{}, fmt.Errorf("%s - read effective product policy: %w", location, err)
}
policy := version.Policy().Matching
if policy == nil {
return domain.MatchingPolicy{}, fmt.Errorf("%s - the effective product policy has no matching section, publish it with the policy-publish command: %w", location, ErrPolicyUnavailable)
}
return *policy, nil
}
// searchBasis is what a need snapshot contributes to the search. A bank search
// has an empty basis.
type searchBasis struct {
specialization *domain.SpecializationCode
skills []requestedSkill
requestedFormats []domain.QuestionnaireWorkFormat
needDomainConfirmed bool
}
func loadBasis(ctx context.Context, unit outbound.UnitOfWork, request Request) (searchBasis, error) {
const location = "matching.loadBasis"
var needSkills, needDesired []domain.NeedSkill
basis := searchBasis{}
if request.Need != nil {
need, err := unit.Needs().GetVersion(ctx, request.OrganizationID, request.Need.NeedID, request.Need.RequirementsVersion)
if err != nil {
if errors.Is(err, outbound.ErrNeedNotFound) {
return searchBasis{}, ErrNeedNotFound
}
return searchBasis{}, fmt.Errorf("%s - read need snapshot: %w", location, err)
}
// A version that only edited a title or a suggestion is not a
// requirements snapshot of its own.
if need.RequirementsVersion() != request.Need.RequirementsVersion {
return searchBasis{}, ErrNeedNotFound
}
requirements := need.Snapshot().Requirements
if requirements.Specialization.Status == domain.NeedValueConfirmed && requirements.Specialization.Value != nil {
specialization := *requirements.Specialization.Value
basis.specialization = &specialization
}
if requirements.WorkFormats.Status == domain.NeedValueConfirmed && requirements.WorkFormats.Value != nil {
for _, format := range *requirements.WorkFormats.Value {
basis.requestedFormats = append(basis.requestedFormats, domain.QuestionnaireWorkFormat(format))
}
}
basis.needDomainConfirmed = requirements.Domain.Status == domain.NeedValueConfirmed
needSkills, needDesired = requirements.RequiredSkills, requirements.DesiredSkills
}
basis.skills = requestedSkills(needSkills, needDesired, request.Filters.Stack)
return basis, nil
}
// requestedSkills lists each distinct requested skill once. A confirmed
// required skill weighs more than a desired one, a stack filter tag counts as
// required, and a repeated code never counts twice, so repeating a skill in a
// need cannot raise or lower a score.
func requestedSkills(required, desired []domain.NeedSkill, stack []domain.CandidateViewSkillCode) []requestedSkill {
var skills []requestedSkill
byCode := make(map[string]int)
seenUnmapped := make(map[string]struct{})
add := func(code, name string, isRequired bool) {
if code == "" {
key := strings.ToLower(strings.TrimSpace(name))
if _, repeated := seenUnmapped[key]; repeated {
return
}
seenUnmapped[key] = struct{}{}
skills = append(skills, requestedSkill{required: isRequired})
return
}
if index, repeated := byCode[code]; repeated {
skills[index].required = skills[index].required || isRequired
return
}
byCode[code] = len(skills)
skills = append(skills, requestedSkill{code: code, required: isRequired})
}
for _, group := range []struct {
skills []domain.NeedSkill
isRequired bool
}{{required, true}, {desired, false}} {
for _, skill := range group.skills {
if skill.Status != domain.NeedItemConfirmed {
continue
}
code := ""
if skill.TaxonomyCode != nil {
code = *skill.TaxonomyCode
}
add(code, skill.Name, group.isRequired)
}
}
for _, tag := range stack {
add(string(tag), "", true)
}
return skills
}
// candidateEntry is one candidate specialization before scoring.
type candidateEntry struct {
candidateID uuid.UUID
card domain.AnonymousCandidateViewDTO
specialization domain.SpecializationCode
category *domain.CandidateViewCategory
declaredGrade *domain.GradeCode
}
// entriesOf derives the specializations that a card shows. A specialization is
// confirmed only when the card shows its category; one specialization never
// confirms another. A specialization that the self-assessment marks confirmed
// but whose category the card does not show is left out: a result cannot
// claim a confirmation that the candidate did not publish.
func entriesOf(visible domain.VisibleCandidateCard) []candidateEntry {
card := visible.Card
declared := make(map[domain.SpecializationCode]*domain.GradeCode, len(card.SelfAssessment))
for _, assessment := range card.SelfAssessment {
declared[assessment.Specialization] = assessment.DeclaredGrade
}
entries := make([]candidateEntry, 0, len(card.Categories)+len(card.SelfAssessment))
confirmed := make(map[domain.SpecializationCode]struct{}, len(card.Categories))
for index := range card.Categories {
category := card.Categories[index]
confirmed[category.Specialization] = struct{}{}
entries = append(entries, candidateEntry{
candidateID: visible.CandidateID, card: card, specialization: category.Specialization,
category: &category, declaredGrade: declared[category.Specialization],
})
}
for _, assessment := range card.SelfAssessment {
if _, isConfirmed := confirmed[assessment.Specialization]; isConfirmed ||
assessment.ConfirmationStatus != domain.CandidateViewConfirmationUnconfirmed {
continue
}
entries = append(entries, candidateEntry{
candidateID: visible.CandidateID, card: card, specialization: assessment.Specialization,
declaredGrade: assessment.DeclaredGrade,
})
}
return entries
}
// rankedEntry carries the sort keys next to the entry that leaves.
type rankedEntry struct {
entry Entry
candidate uuid.UUID
fit int64
coverage int64
rank int64
near bool
}
// groups holds the ranked entries of the three groups before the output is cut.
type groups struct {
main, near, unconfirmed []rankedEntry
}
func (service *Service) rank(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
basis searchBasis,
policy domain.MatchingPolicy,
cards []domain.VisibleCandidateCard,
) (groups, error) {
specialization, compatible := effectiveSpecialization(request.Filters.Specialization, basis.specialization)
if !compatible {
return groups{}, nil
}
requestedFormats := basis.requestedFormats
if conditions := request.Filters.Conditions; conditions != nil && len(conditions.WorkFormats) > 0 {
requestedFormats = conditions.WorkFormats
}
var accepted []candidateEntry
for _, visible := range cards {
for _, entry := range entriesOf(visible) {
if request.Filters.accepts(entry, specialization) {
accepted = append(accepted, entry)
}
}
}
reachedCohorts, err := service.reachedPercentileCohorts(ctx, unit, policy, accepted)
if err != nil {
return groups{}, err
}
facts, err := service.permittedFacts(ctx, unit, request, basis, accepted)
if err != nil {
return groups{}, err
}
var result groups
for _, entry := range accepted {
ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts)
switch {
case entry.category == nil:
result.unconfirmed = append(result.unconfirmed, ranked)
case ranked.near:
result.near = append(result.near, ranked)
default:
result.main = append(result.main, ranked)
}
}
slices.SortStableFunc(result.main, compareByRank)
slices.SortStableFunc(result.near, compareByRank)
slices.SortStableFunc(result.unconfirmed, compareByFit)
return result, nil
}
// reachedPercentileCohorts returns the categories among the accepted entries
// whose comparable real cohort has reached the policy minimum. The cohort of a
// category is the number of candidates who hold it from a source that is not a
// synthetic demonstration; only the categories of the accepted entries are
// counted. A percentile would need the theta of those members, which the
// organization-safe projection does not carry, so T stays the neutral value and
// the percentile stays null, but the reason is then "not computed" instead of
// "cohort below the minimum". The search never fails for it and logs one
// warning for each such category.
func (service *Service) reachedPercentileCohorts(
ctx context.Context,
unit outbound.UnitOfWork,
policy domain.MatchingPolicy,
accepted []candidateEntry,
) (map[outbound.CategoryKey]bool, error) {
seen := make(map[outbound.CategoryKey]struct{})
var categories []outbound.CategoryKey
for _, entry := range accepted {
if entry.category == nil {
continue
}
key := outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}
if _, repeated := seen[key]; !repeated {
seen[key] = struct{}{}
categories = append(categories, key)
}
}
counts, err := unit.Evidence().CountComparableRealCategories(ctx, categories)
if err != nil {
return nil, fmt.Errorf("matching.Service.reachedPercentileCohorts - count real cohorts: %w", err)
}
reached := make(map[outbound.CategoryKey]bool)
for _, key := range categories {
if counts[key] >= int64(policy.PercentileMinCohort) {
reached[key] = true
service.logger.WarnContext(ctx, "the real cohort of a category reached the percentile minimum, but the percentile is not computed",
slog.String("specialization", string(key.Specialization)),
slog.String("grade", string(key.Grade)),
slog.Int64("cohort_size", counts[key]),
slog.Int("minimum", int(policy.PercentileMinCohort)),
)
}
}
return reached, nil
}
// permittedFacts reads the permitted evidence of every candidate with a
// confirmed entry in one statement, and only when the request names skills.
func (service *Service) permittedFacts(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
basis searchBasis,
accepted []candidateEntry,
) (map[uuid.UUID][]evidenceSource, error) {
sources := make(map[uuid.UUID][]evidenceSource)
if len(basis.skills) == 0 {
return sources, nil
}
seen := make(map[uuid.UUID]struct{})
var requests []outbound.EvidenceCandidateCategories
for _, entry := range accepted {
if _, repeated := seen[entry.candidateID]; repeated || entry.category == nil {
continue
}
seen[entry.candidateID] = struct{}{}
requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: entry.candidateID, Categories: entry.card.Categories})
}
facts, err := unit.Evidence().ListOrganizationFactsBatch(ctx, request.OrganizationID, requests)
if err != nil {
return nil, fmt.Errorf("matching.Service.permittedFacts - read permitted evidence: %w", err)
}
for candidateID, candidateFacts := range facts {
sources[candidateID] = factSources(candidateFacts)
}
return sources, nil
}
// reveal cuts each group to the policy bound and charges the output in order.
func (service *Service) reveal(
ctx context.Context,
unit outbound.UnitOfWork,
request Request,
policy domain.MatchingPolicy,
ranked groups,
) (Result, error) {
result := Result{Source: sourceOf(request), Main: []Entry{}, Near: []Entry{}, Unconfirmed: []Entry{}}
limit := int(policy.MaxResultsPerGroup)
for _, group := range []*[]rankedEntry{&ranked.main, &ranked.near, &ranked.unconfirmed} {
if len(*group) > limit {
*group = (*group)[:limit]
result.Truncated = true
}
}
views, err := service.views(ctx, unit, request.ActorID, request.OrganizationID)
if err != nil {
return Result{}, fmt.Errorf("matching.Service.reveal - open card views: %w", err)
}
revealed := make(map[uuid.UUID]map[domain.CardField]struct{})
var order []uuid.UUID
charge := func(entries []rankedEntry) ([]Entry, bool, error) {
kept := make([]Entry, 0, len(entries))
for _, item := range entries {
if _, paid := revealed[item.candidate]; !paid {
allowed, err := views.Reserve(ctx, item.candidate)
if err != nil {
return nil, false, fmt.Errorf("matching.Service.reveal - reserve card view: %w", err)
}
if !allowed {
return kept, false, nil
}
revealed[item.candidate] = make(map[domain.CardField]struct{})
order = append(order, item.candidate)
}
for _, field := range entryFields(item.entry) {
revealed[item.candidate][field] = struct{}{}
}
kept = append(kept, item.entry)
}
return kept, true, nil
}
complete := true
for _, step := range []struct {
entries []rankedEntry
target *[]Entry
}{{ranked.main, &result.Main}, {ranked.near, &result.Near}, {ranked.unconfirmed, &result.Unconfirmed}} {
if !complete {
break
}
kept, ok, err := charge(step.entries)
if err != nil {
return Result{}, err
}
*step.target, complete = kept, ok
}
if !complete {
result.Truncated = true
}
for _, candidateID := range order {
if err := views.Record(ctx, candidateID, orderedFields(revealed[candidateID])); err != nil {
return Result{}, fmt.Errorf("matching.Service.reveal - record card view: %w", err)
}
}
return result, nil
}
// entryFields lists the card fields that an entry actually shows, so the
// candidate's history names what the search returned about them.
func entryFields(entry Entry) []domain.CardField {
var fields []domain.CardField
if entry.Category != nil {
fields = append(fields, domain.CardFieldCategories)
}
if len(entry.PublicContext.Stack) > 0 {
fields = append(fields, domain.CardFieldStack)
}
if entry.PublicContext.ExperienceBand != nil {
fields = append(fields, domain.CardFieldExperience)
}
// An unconfirmed entry exists only because the self-assessment is published.
if entry.Category == nil || entry.DeclaredGrade != nil {
fields = append(fields, domain.CardFieldSelfAssessment)
}
if len(entry.PublicContext.WorkFormats) > 0 {
fields = append(fields, domain.CardFieldWorkFormats)
}
if entry.PublicContext.SalaryCompatibility != nil {
fields = append(fields, domain.CardFieldSalaryCompatibility)
}
return fields
}
func orderedFields(set map[domain.CardField]struct{}) []domain.CardField {
fields := make([]domain.CardField, 0, len(set))
for _, field := range []domain.CardField{
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility,
} {
if _, shown := set[field]; shown {
fields = append(fields, field)
}
}
return fields
}
// effectiveSpecialization combines the filter with the specialization of the
// need. Two different specializations leave nothing to show.
func effectiveSpecialization(filter, need *domain.SpecializationCode) (*domain.SpecializationCode, bool) {
switch {
case filter != nil && need != nil && *filter != *need:
return nil, false
case filter != nil:
return filter, true
default:
return need, true
}
}
// factSources turns the permitted assessment facts into evidence. Each fact is
// the one measurement that supports a confirmed category, tagged with that
// category's specialization.
func factSources(facts []domain.EvidenceOrganizationFact) []evidenceSource {
sources := make([]evidenceSource, 0, len(facts))
for _, fact := range facts {
input := fact.Input()
sources = append(sources, evidenceSource{
code: string(input.Skill), trust: input.Trust, attribution: domain.EvidenceAttributionPersonal, measured: true,
})
}
return sources
}
func scoreEntry(
entry candidateEntry,
policy domain.MatchingPolicy,
basis searchBasis,
requestedFormats []domain.QuestionnaireWorkFormat,
facts []evidenceSource,
reachedCohorts map[outbound.CategoryKey]bool,
) rankedEntry {
evidence := make([]evidenceSource, 0, len(entry.card.Skills)+len(facts))
for _, skill := range entry.card.Skills {
evidence = append(evidence, evidenceSource{code: string(skill), trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal})
}
confirmed := entry.category != nil
if confirmed {
for _, fact := range facts {
// A fact supports only its own specialization's category.
if fact.code == string(entry.specialization) {
evidence = append(evidence, fact)
}
}
}
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence})
context := PublicContext{
ExperienceBand: entry.card.ExperienceBand, SalaryCompatibility: entry.card.SalaryCompatibility,
}
if len(entry.card.Skills) > 0 {
context.Stack = slices.Clone(entry.card.Skills)
}
if len(entry.card.WorkFormats) > 0 {
context.WorkFormats = slices.Clone(entry.card.WorkFormats)
}
summary, flags := explain(explanationInput{
confirmed: confirmed, declaredGrade: entry.declaredGrade, policy: policy, scores: computed, context: context,
requestedFormats: requestedFormats, needDomainConfirmed: basis.needDomainConfirmed,
percentileReason: percentileReason(entry, reachedCohorts),
})
components := Components{Fit: microToFloat(computed.fit), Coverage: microToFloat(computed.coverage)}
if confirmed {
components.Domain = microToFloat(computed.domain)
components.Semantics = microToFloat(computed.semantics)
components.Competition = microToFloat(computed.competition)
components.Freshness = microToFloat(computed.freshness)
components.Responsiveness = microToFloat(computed.responsive)
components.RankScore = microToFloat(computed.rank)
}
return rankedEntry{
entry: Entry{
CandidateHandle: entry.card.Pseudonym, Specialization: entry.specialization,
DeclaredGrade: entry.declaredGrade, Category: entry.category,
PublicContext: context, EvidenceSummary: summary, Components: components, UnknownFlags: flags,
},
candidate: entry.candidateID, fit: computed.fit, coverage: computed.coverage, rank: computed.rank,
near: confirmed && computed.belongsToNearGroup(policy),
}
}
// compareByRank orders a confirmed group: S descending, then coverage
// descending, then the internal identifier ascending. The identifier is the
// stable tie-breaker and never leaves the server; the specialization only
// separates two entries of the same candidate.
func compareByRank(left, right rankedEntry) int {
return cmp.Or(
cmp.Compare(right.rank, left.rank),
cmp.Compare(right.coverage, left.coverage),
slices.Compare(left.candidate[:], right.candidate[:]),
strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)),
)
}
// compareByFit orders the unconfirmed group: Fit descending, then coverage
// descending, then the internal identifier ascending. It never uses a
// confirmed-profile score.
func compareByFit(left, right rankedEntry) int {
return cmp.Or(
cmp.Compare(right.fit, left.fit),
cmp.Compare(right.coverage, left.coverage),
slices.Compare(left.candidate[:], right.candidate[:]),
strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)),
)
}
// sourceOf echoes the search basis. A bank search carries its normalized
// filters, so the result stays tied to what was asked.
func sourceOf(request Request) Source {
if request.Need != nil {
need := *request.Need
return Source{Need: &need}
}
filters := request.Filters
filters.Stack = slices.Clone(filters.Stack)
slices.Sort(filters.Stack)
if conditions := filters.Conditions; conditions != nil {
normalized := *conditions
normalized.WorkFormats = slices.Clone(conditions.WorkFormats)
slices.Sort(normalized.WorkFormats)
filters.Conditions = &normalized
}
return Source{Filters: filters}
}
// percentileReason says why the percentile of a confirmed entry is null.
func percentileReason(entry candidateEntry, reachedCohorts map[outbound.CategoryKey]bool) UnknownReason {
if entry.category != nil && reachedCohorts[outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}] {
return ReasonPercentileNotComputed
}
return ReasonCohortBelow30
}
+187
View File
@@ -0,0 +1,187 @@
package matching
import (
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrForbidden reports an actor that may not search: not a verified
// employer, or not the active owner of the organization.
ErrForbidden = errors.New("match search is forbidden")
// ErrNeedNotFound reports a need of another organization, an unknown need,
// or a requirements version that no confirmed-requirements change created.
ErrNeedNotFound = errors.New("match search need snapshot not found")
// ErrPolicyUnavailable reports an effective product policy without the
// matching section. The search fails closed instead of using defaults.
ErrPolicyUnavailable = errors.New("match search policy is unavailable")
// ErrServiceMissing reports an incomplete service wiring.
ErrServiceMissing = errors.New("match search service is unavailable")
)
// NeedReference selects one immutable confirmed-requirements snapshot.
type NeedReference struct {
NeedID uuid.UUID
RequirementsVersion int64
}
// GradeFilter is a confirmed category that a filter asks for.
type GradeFilter struct {
Specialization domain.SpecializationCode
Grade domain.GradeCode
}
// Conditions filter by the safe, coarse card conditions. An unknown card value
// never satisfies a condition.
type Conditions struct {
WorkFormats []domain.QuestionnaireWorkFormat
SalaryCompatibility *domain.CandidateViewSalaryCompatibility
}
// Filters narrow the organization-visible bank. A nil field is no filter.
type Filters struct {
Specialization *domain.SpecializationCode
ConfirmedGrade *domain.GradeCode
ConfirmedCategory *GradeFilter
ConfirmationStatus *domain.CandidateViewConfirmationStatus
DeclaredGrade *domain.GradeCode
Stack []domain.CandidateViewSkillCode
Conditions *Conditions
}
// Request is one search. The actor and the organization come from the
// authenticated session and the path, never from the body.
type Request struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
// Need selects a requirements snapshot. It is nil for a search of the
// whole organization-visible bank.
Need *NeedReference
Filters Filters
}
// Source is the search basis that the result carries.
type Source struct {
Need *NeedReference
// Filters are the normalized bank filters; they are set for a bank search.
Filters Filters
}
// EvidenceCode names a templated explanation item.
type EvidenceCode string
const (
EvidenceConfirmedCategory EvidenceCode = "confirmed_category"
EvidenceRequiredSkill EvidenceCode = "required_skill_evidence"
EvidenceDesiredSkill EvidenceCode = "desired_skill_evidence"
EvidenceWorkConditionsMatch EvidenceCode = "work_conditions_match"
EvidenceSalaryCompatibility EvidenceCode = "salary_compatibility"
EvidenceDeclaredGrade EvidenceCode = "declared_grade"
)
// EvidenceState is the verdict of one explanation item.
type EvidenceState string
const (
EvidenceStateSupports EvidenceState = "supports"
EvidenceStatePartial EvidenceState = "partial"
EvidenceStateGap EvidenceState = "gap"
EvidenceStateDeclaredOnly EvidenceState = "declared_only"
)
// EvidenceItem is one bounded explanation item without free text.
type EvidenceItem struct {
Code EvidenceCode
State EvidenceState
}
// UnknownComponent names a component whose value is unknown.
type UnknownComponent string
const (
UnknownSemantics UnknownComponent = "semantics"
UnknownPercentile UnknownComponent = "percentile"
UnknownAssessment UnknownComponent = "assessment"
UnknownFreshness UnknownComponent = "freshness"
UnknownResponsiveness UnknownComponent = "responsiveness"
UnknownExperienceBand UnknownComponent = "experience_band"
UnknownWorkFormats UnknownComponent = "work_formats"
UnknownSalaryCompatibility UnknownComponent = "salary_compatibility"
UnknownDomain UnknownComponent = "domain"
)
// UnknownReason is the bounded reason of an unknown component.
type UnknownReason string
const (
ReasonMLUnavailable UnknownReason = "ml_unavailable"
ReasonCohortBelow30 UnknownReason = "cohort_below_30"
ReasonNoConfirmationForSpecialization UnknownReason = "no_confirmation_for_specialization"
ReasonNotInPublicCard UnknownReason = "not_in_public_card"
ReasonNeedFieldUnconfirmed UnknownReason = "need_field_unconfirmed"
ReasonNoFreshnessHistory UnknownReason = "no_freshness_history"
ReasonNoResponseHistory UnknownReason = "no_response_history"
ReasonPercentileNotComputed UnknownReason = "percentile_not_computed"
)
// UnknownFlag reports one unavailable component and why.
type UnknownFlag struct {
Component UnknownComponent
Reason UnknownReason
}
// PublicContext is the safe part of the anonymous card that a result shows. A
// nil or empty value means the card does not show it.
type PublicContext struct {
Stack []domain.CandidateViewSkillCode
ExperienceBand *domain.CandidateExperienceBand
WorkFormats []domain.QuestionnaireWorkFormat
SalaryCompatibility *domain.CandidateViewSalaryCompatibility
}
// Components are the computed scores of an entry, each rounded to six
// decimals. An unconfirmed entry has only Fit and Coverage: it has no theta,
// T, P, percentile, or rank score.
type Components struct {
Fit float64
Coverage float64
Domain float64
Semantics float64
Competition float64
Freshness float64
Responsiveness float64
RankScore float64
// Percentile is nil while there are fewer comparable real candidates than
// the policy needs, and then T is the neutral value.
Percentile *float64
}
// Entry is one candidate specialization of a result. The handle is the
// organization-scoped pseudonym; no account or profile identifier leaves.
type Entry struct {
CandidateHandle string
Specialization domain.SpecializationCode
DeclaredGrade *domain.GradeCode
// Category and Strength are set only for a confirmed entry.
Category *domain.CandidateViewCategory
PublicContext PublicContext
EvidenceSummary []EvidenceItem
Components Components
UnknownFlags []UnknownFlag
}
// Result holds the three separate groups. Their scores are never merged into
// one scale.
type Result struct {
Source Source
Main []Entry
Near []Entry
Unconfirmed []Entry
// Truncated is true when the output is not the whole ranked bank: a group
// exceeded the policy bound, or the card-view allowance of the organization
// ended. It carries no count.
Truncated bool
}
+142 -86
View File
@@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
@@ -17,6 +17,13 @@ import (
var (
ErrInboxUnavailable = errors.New("notification inbox is unavailable")
// ErrInboxForbidden reports an account that may not use the requested
// cabinet inbox: a missing or unverified account, or an account of the
// other scenario.
ErrInboxForbidden = errors.New("notification inbox is forbidden")
// ErrInboxEmailNotVerified reports an employer account whose email is not
// confirmed; the organization operations answer it as email_not_verified.
ErrInboxEmailNotVerified = errors.New("notification inbox requires a confirmed email")
// ErrInboxContentUnavailable means the referenced source is missing or its
// current visibility no longer permits the original presentation.
ErrInboxContentUnavailable = errors.New("notification content is unavailable")
@@ -27,6 +34,12 @@ const (
maxInboxSummaryRunes = 500
)
// inboxLinkPathPattern is the shape of a content link: a same-origin
// absolute path of at most 256 characters from a narrow alphabet, so it has
// no query, fragment, escape, dot segment, or backslash. The public contract
// states the same pattern.
var inboxLinkPathPattern = regexp.MustCompile(`^/[A-Za-z0-9/_-]{0,255}$`)
// InboxContent is resolved from the current source at read time. It is never
// written to notification_inbox_events.
type InboxContent struct {
@@ -66,26 +79,15 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
}
func validInboxLinkPath(value string) bool {
if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") {
return false
}
parsed, err := url.ParseRequestURI(value)
if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value {
return false
}
for _, segment := range strings.Split(value, "/") {
if segment == "." || segment == ".." {
return false
}
}
return true
return inboxLinkPathPattern.MatchString(value) && !strings.HasPrefix(value, "//")
}
// InboxContentResolver reads the current source under its current visibility
// rules. It must return ErrInboxContentUnavailable when that source is gone or
// no longer safe to present.
// rules, inside the read transaction that also authorized the viewer. It must
// return ErrInboxContentUnavailable when that source is gone or no longer
// safe to present to the recipient.
type InboxContentResolver interface {
Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error)
Resolve(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
}
// InboxItem pairs immutable event metadata with content resolved for this
@@ -96,9 +98,11 @@ type InboxItem struct {
ContentUnavailable bool
}
// InboxListRequest is built from the authenticated recipient and optional
// organization context. The organization ID filters items but grants no
// authorization by itself.
// InboxListRequest is built from the authenticated recipient. A nil
// OrganizationID is the candidate cabinet: every organization that sent to
// the recipient. A set OrganizationID is the employer cabinet of that
// organization and requires the recipient's current active membership. The
// organization ID filters items but is never authorization by itself.
type InboxListRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
@@ -106,111 +110,163 @@ type InboxListRequest struct {
Limit int32
}
// InboxMarkReadRequest names one inbox item in the same cabinet scope as
// InboxListRequest.
type InboxMarkReadRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
EventID uuid.UUID
}
type InboxPage struct {
Items []InboxItem
HasMore bool
}
// InboxService coordinates recipient-scoped storage and read-time content
// resolution. A caller for employer-scoped notices must authorize current
// membership before constructing the request; invitation recipients need not
// belong to the sender's organization.
// InboxService lists and marks the inbox of the authenticated recipient.
// Every operation authorizes the recipient for the requested cabinet and
// reads the inbox in one transaction, so a membership revoked a moment ago
// cannot authorize a later read. The inbox stores references only: the text
// of an item is resolved from its current source at each list, so a hiding, a
// revoked membership, or a withdrawn source removes the content from every
// later read. Mail delivery is a separate concern: an item exists whether or
// not any email was sent, and an email failure never blocks it.
type InboxService struct {
repository outbound.NotificationInboxRepository
transactor outbound.Transactor
resolver InboxContentResolver
clock func() time.Time
}
func NewInboxService(
repository outbound.NotificationInboxRepository,
transactor outbound.Transactor,
resolver InboxContentResolver,
clock func() time.Time,
) (*InboxService, error) {
if repository == nil || resolver == nil || clock == nil {
return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable)
if transactor == nil || resolver == nil || clock == nil {
return nil, fmt.Errorf("notification.NewInboxService - transactor, resolver, and clock are required: %w", ErrInboxUnavailable)
}
return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil
return &InboxService{transactor: transactor, resolver: resolver, clock: clock}, nil
}
// StoreInvitationDelivered stores the recipient-specific reference to an
// invitation-delivered event. A transaction-bound repository lets a future
// event handler commit this row with the invitation state and consumer marker.
func (service *InboxService) StoreInvitationDelivered(
ctx context.Context,
input domain.NotificationInboxEntryInput,
) (bool, error) {
const location = "InboxService.StoreInvitationDelivered"
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
return false, err
}
created, err := service.repository.Store(ctx, entry)
if err != nil {
return false, fmt.Errorf("%s - store event: %w", location, err)
}
return created, nil
}
// List resolves each stored reference against its current source. A source
// that is missing or no longer visible is returned without source content.
// List returns one newest-first page and resolves each stored reference
// against its current source. A source that is missing or no longer visible
// is returned without content.
func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) {
const location = "InboxService.List"
if err := validateInboxListRequest(request); err != nil {
return InboxPage{}, err
}
stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{
RecipientUserID: request.RecipientUserID,
OrganizationID: request.OrganizationID,
After: request.After,
Limit: request.Limit,
var page InboxPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
return err
}
stored, err := unit.NotificationInbox().List(ctx, outbound.NotificationInboxListQuery{
RecipientUserID: request.RecipientUserID,
OrganizationID: request.OrganizationID,
After: request.After,
Limit: request.Limit,
})
if err != nil {
return fmt.Errorf("%s - list recipient events: %w", location, err)
}
resolved := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
for _, entry := range stored.Items {
if !inboxEntryMatchesRequest(entry, request) {
return fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, unit, entry)
switch {
case errors.Is(resolveErr, ErrInboxContentUnavailable):
item.ContentUnavailable = true
case resolveErr != nil:
return fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
default:
item.Content = &content
}
resolved.Items = append(resolved.Items, item)
}
page = resolved
return nil
})
if err != nil {
return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err)
}
page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
for _, entry := range stored.Items {
if !inboxEntryMatchesRequest(entry, request) {
return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
}
item := InboxItem{Entry: entry}
content, resolveErr := service.resolver.Resolve(ctx, entry)
switch {
case errors.Is(resolveErr, ErrInboxContentUnavailable):
item.ContentUnavailable = true
case resolveErr != nil:
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
default:
item.Content = &content
}
page.Items = append(page.Items, item)
return InboxPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return page, nil
}
// MarkRead persists the first read timestamp for one recipient and exact
// organization context. The source is not read and no private content is
// returned by this command.
func (service *InboxService) MarkRead(
ctx context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
eventID uuid.UUID,
) (domain.NotificationInboxEntry, error) {
// MarkRead persists the first read timestamp of one item of the recipient. A
// repeat keeps the first timestamp. The source is not read and no content is
// returned. An item of another recipient, of another organization context,
// or an unknown item all return outbound.ErrNotificationInboxEntryNotFound.
func (service *InboxService) MarkRead(ctx context.Context, request InboxMarkReadRequest) (domain.NotificationInboxEntry, error) {
const location = "InboxService.MarkRead"
if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable)
if request.RecipientUserID == uuid.Nil || request.EventID == uuid.Nil ||
(request.OrganizationID != nil && *request.OrganizationID == uuid.Nil) {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient and event IDs are required: %w", location, ErrInboxUnavailable)
}
at := service.clock()
if at.IsZero() {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable)
}
entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at)
var entry domain.NotificationInboxEntry
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
return err
}
marked, err := unit.NotificationInbox().MarkRead(ctx, request.RecipientUserID, request.OrganizationID, request.EventID, at)
if err != nil {
return fmt.Errorf("%s - mark event read: %w", location, err)
}
entry = marked
return nil
})
if err != nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err)
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return entry, nil
}
// authorizeInboxViewer checks the account against the requested cabinet. The
// candidate cabinet needs a verified candidate account. The employer cabinet
// needs an employer account with a verified email (otherwise
// ErrInboxEmailNotVerified, like the other organization operations) and an
// active membership of any role in the named organization. The membership is
// locked FOR SHARE until the transaction ends, like the card reads, so a
// revocation cannot commit between this check and the read that follows. A
// missing or inactive membership returns outbound.ErrOrganizationNotFound, so
// an organization that exists cannot be told from one that does not.
func authorizeInboxViewer(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, organizationID *uuid.UUID) error {
const location = "notification.authorizeInboxViewer"
user, err := unit.Users().GetByID(ctx, userID)
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - account does not exist: %w", location, ErrInboxForbidden)
}
if err != nil {
return fmt.Errorf("%s - read account: %w", location, err)
}
if organizationID == nil {
if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() {
return fmt.Errorf("%s - the candidate inbox needs a verified candidate account: %w", location, ErrInboxForbidden)
}
return nil
}
if user.Scenario != domain.ScenarioEmployer {
return fmt.Errorf("%s - the organization inbox needs an employer account: %w", location, ErrInboxForbidden)
}
if !user.EmailVerified() {
return fmt.Errorf("%s - email is not verified: %w", location, ErrInboxEmailNotVerified)
}
if _, err := unit.Organizations().LockActiveMembership(ctx, *organizationID, userID); err != nil {
if errors.Is(err, outbound.ErrOrganizationNotFound) {
return fmt.Errorf("%s - no active membership: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
return nil
}
func validateInboxListRequest(request InboxListRequest) error {
const location = "notification.validateInboxListRequest"
if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize {
@@ -0,0 +1,82 @@
package notification
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// InboxSourceResolver resolves the content of the entries of one source
// type from the current state of that source, for the entry's recipient. It
// returns ErrInboxContentUnavailable when the source is gone or the recipient
// may not see it now.
type InboxSourceResolver func(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
// sourceContentResolver dispatches by source type. A source type without a
// resolver is unavailable, never guessed, so a new event type shows nothing
// until its resolver is registered.
type sourceContentResolver map[domain.NotificationInboxSourceType]InboxSourceResolver
var _ InboxContentResolver = sourceContentResolver(nil)
// NewInboxContentResolver combines the resolvers of the source types.
func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]InboxSourceResolver) InboxContentResolver {
return sourceContentResolver(resolvers)
}
// DefaultInboxSourceResolvers lists the source types that have a resolver
// today. The synthetic notice resolver is registered only when
// syntheticEnabled is true (development and browser-test stands); a stored
// synthetic row is then listed without content. The invitation module adds
// domain.NotificationInboxSourceInvitation with its own resolver; the
// handler, the table, and the API need no change.
func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver {
resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{}
if syntheticEnabled {
resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice
}
return resolvers
}
func (resolvers sourceContentResolver) Resolve(
ctx context.Context,
unit outbound.UnitOfWork,
entry domain.NotificationInboxEntry,
) (InboxContent, error) {
resolve, ok := resolvers[entry.SourceType()]
if !ok {
return InboxContent{}, ErrInboxContentUnavailable
}
return resolve(ctx, unit, entry)
}
const (
syntheticNoticeTitle = "Тестовое уведомление"
// syntheticNoticeSummary has one verb slot for the organization name.
syntheticNoticeSummary = "Организация «%s» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий."
)
// ResolveSyntheticNotice resolves a synthetic notice. The text is fixed and
// names the sending organization by its current name, which is read under the
// recipient's current standing: a candidate sees it until they hide the
// organization, an employer while they are an active member. Afterwards the
// entry stays in the list without content.
func ResolveSyntheticNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
const location = "notification.ResolveSyntheticNotice"
name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.SourceID())
if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) {
return InboxContent{}, ErrInboxContentUnavailable
}
if err != nil {
return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err)
}
content, err := NewInboxContent(syntheticNoticeTitle, fmt.Sprintf(syntheticNoticeSummary, name), "")
if err != nil {
// A stored name that does not fit the presentation is not shown.
return InboxContent{}, ErrInboxContentUnavailable
}
return content, nil
}
@@ -0,0 +1,213 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// InboxConsumerName names the consumer group and scopes deduplication of the
// inbox handler. Renaming it makes the consumer process every retained event
// again; the inbox key keeps the rows unique, but do not rename it lightly.
const InboxConsumerName = "notification_inbox"
// inboxPayloadSchemaVersion is the only supported schema version of the
// inbox events. Version 1 is inboxEventPayload.
const inboxPayloadSchemaVersion = 1
// inboxEventPayload is version 1 of the payload of every event the inbox
// stores. It names the recipient and the organization context and nothing
// else: the text is resolved from the source when the inbox is read, so
// neither the outbox nor the event bus keeps content that could outlive a
// revocation.
type inboxEventPayload struct {
RecipientUserID uuid.UUID `json:"recipient_user_id"`
OrganizationID uuid.UUID `json:"organization_id"`
}
// inboxProjection describes how one event type becomes an inbox row: the
// aggregate the event must come from and where the content source is.
type inboxProjection struct {
aggregateType string
// source returns the source record of the content for a decoded event.
source func(event outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID
}
// inboxProjections is the allowlist of events the inbox stores. A producer
// plugs in by appending an event of one of these types in its own
// transaction; adding a type here also needs the same pair in
// domain.NotificationInboxSourceFor, the CHECK constraint of the table, and a
// content resolver for its source type.
//
// - invitation.delivered: the aggregate is the invitation, which is also
// the source. Invitations are a later module; the projection and the
// payload contract are fixed here so that it needs no inbox change.
// - notification.synthetic_delivered: a synthetic event for tests and
// probes. Its aggregate is a one-off notice and its source is the
// organization of the payload.
var inboxProjections = map[domain.NotificationInboxEventType]inboxProjection{
domain.NotificationInboxInvitationDelivered: {
aggregateType: "invitation",
source: func(event outbound.ConsumedEvent, _ inboxEventPayload) uuid.UUID {
return event.AggregateID
},
},
domain.NotificationInboxSyntheticDelivered: {
aggregateType: SyntheticNoticeAggregateType,
source: func(_ outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID {
return payload.OrganizationID
},
},
}
// SyntheticNoticeAggregateType is the aggregate type of a synthetic inbox
// event. Every notice is its own aggregate at version 1.
const SyntheticNoticeAggregateType = "synthetic_notice"
// SyntheticNoticeAggregateVersion is the version of a synthetic notice.
const SyntheticNoticeAggregateVersion = 1
// SyntheticNoticeEventPayload builds the version 1 payload of a synthetic
// inbox event for the outbox. It is the single writer of the contract that
// the inbox handler reads.
func SyntheticNoticeEventPayload(recipientUserID, organizationID uuid.UUID) ([]byte, error) {
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: recipientUserID, OrganizationID: organizationID})
if err != nil {
return nil, fmt.Errorf("notification.SyntheticNoticeEventPayload - encode payload: %w", err)
}
return payload, nil
}
// InboxHandler stores one inbox row for each inbox event, in the consumer
// transaction that records the event as processed. The row key is the
// recipient and the event ID, so a repeated delivery, a replayed dead letter,
// or a renamed consumer still stores one row, and a redelivery that changed
// the immutable metadata is refused instead of overwritten.
//
// The inbox is the in-platform delivery state of a notification: a stored row
// means delivered. Nothing here reads mail state, so an unverified address, a
// missing mail provider, or a failed email never blocks a notification.
type InboxHandler struct {
logger *slog.Logger
syntheticEnabled bool
}
var _ inbound.EventHandler = (*InboxHandler)(nil)
// NewInboxHandler creates the handler. The synthetic event type is handled
// only when syntheticEnabled is true, which a development or browser-test
// stand sets; otherwise such an event is acknowledged and ignored.
func NewInboxHandler(logger *slog.Logger, syntheticEnabled bool) *InboxHandler {
return &InboxHandler{logger: logger, syntheticEnabled: syntheticEnabled}
}
func (*InboxHandler) ConsumerName() string { return InboxConsumerName }
func (handler *InboxHandler) Handles(eventType string) bool {
return handler.handles(domain.NotificationInboxEventType(eventType))
}
func (handler *InboxHandler) handles(eventType domain.NotificationInboxEventType) bool {
if eventType == domain.NotificationInboxSyntheticDelivered && !handler.syntheticEnabled {
return false
}
_, known := inboxProjections[eventType]
return known
}
// Handle turns the event into an inbox row:
//
// - A payload or envelope that breaks the contract, a recipient or
// organization that does not exist, or an event ID that already holds
// different metadata is rejected for good (inbound.ErrEventRejected).
// - A recipient account that was deleted is skipped: its private inbox
// went with it. An account deleted between the check and the insert
// aborts the insert; the error is returned for a retry, and the retry
// finds the account gone and skips.
// - Storage errors, including a recipient that disappeared, are returned
// for a retry.
//
// Errors and logs carry event IDs, never the payload.
func (handler *InboxHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
const location = "InboxHandler.Handle"
eventType := domain.NotificationInboxEventType(event.EventType)
projection := inboxProjections[eventType]
if !handler.handles(eventType) {
return fmt.Errorf("%s - event type is not an inbox event: %w", location, inbound.ErrEventRejected)
}
payload, err := decodeInboxPayload(event, projection)
if err != nil {
return err
}
if _, err := unit.Users().GetByID(ctx, payload.RecipientUserID); err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
handler.logger.InfoContext(ctx, "inbox event skipped because the recipient account does not exist",
slog.String("event_id", event.EventID.String()))
return nil
}
return fmt.Errorf("%s - read recipient account: %w", location, err)
}
sourceType, _ := domain.NotificationInboxSourceFor(eventType)
entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: event.EventID,
RecipientUserID: payload.RecipientUserID,
OrganizationID: payload.OrganizationID,
EventType: eventType,
SchemaVersion: event.SchemaVersion,
SourceType: sourceType,
SourceID: projection.source(event, payload),
OccurredAt: event.OccurredAt,
})
if err != nil {
return fmt.Errorf("%s - build inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
}
if _, err := unit.NotificationInbox().Store(ctx, entry); err != nil {
// A vanished recipient (ErrNotificationInboxRecipientMissing) is not
// the event's fault: it is retried and then skipped above.
if errors.Is(err, outbound.ErrNotificationInboxEventConflict) || errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) {
return fmt.Errorf("%s - store inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
}
return fmt.Errorf("%s - store inbox entry: %w", location, err)
}
return nil
}
// decodeInboxPayload checks the envelope and the version 1 payload. Errors
// name the broken rule and never quote the payload.
func decodeInboxPayload(event outbound.ConsumedEvent, projection inboxProjection) (inboxEventPayload, error) {
const location = "notification.decodeInboxPayload"
rejected := func(reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
}
if event.SchemaVersion != inboxPayloadSchemaVersion {
return inboxEventPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
}
if event.AggregateType != projection.aggregateType || event.AggregateID == uuid.Nil {
return inboxEventPayload{}, rejected("aggregate does not match the event type")
}
var payload inboxEventPayload
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
decoder.DisallowUnknownFields()
// The decoder error can quote a fragment of the payload, so it is not
// wrapped. A second value after the object is refused as well.
if err := decoder.Decode(&payload); err != nil {
return inboxEventPayload{}, rejected("payload is not a valid inbox event")
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return inboxEventPayload{}, rejected("payload has data after the inbox event")
}
if payload.RecipientUserID == uuid.Nil || payload.OrganizationID == uuid.Nil {
return inboxEventPayload{}, rejected("recipient and organization IDs are required")
}
return payload, nil
}
@@ -0,0 +1,201 @@
package notification
import (
"context"
"encoding/json"
"errors"
"log/slog"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
func newInboxHandlerFixture(t *testing.T) (*InboxHandler, *inboxFixture, outbound.ConsumedEvent) {
t.Helper()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
payload, err := SyntheticNoticeEventPayload(fixture.user.ID, fixture.organizationID)
if err != nil {
t.Fatalf("SyntheticNoticeEventPayload() error = %v", err)
}
event := outbound.ConsumedEvent{
EventID: uuid.New(), EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1,
AggregateType: SyntheticNoticeAggregateType, AggregateID: uuid.New(), AggregateVersion: SyntheticNoticeAggregateVersion,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
}
return NewInboxHandler(slog.New(slog.DiscardHandler), true), fixture, event
}
func TestInboxHandlerStoresOneRowForARepeatedEvent(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
if !handler.Handles(event.EventType) || handler.Handles("notification.mail_requested") {
t.Fatal("Handles() must accept inbox events only")
}
for range 2 {
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
}
if len(fixture.repository.entries) != 1 {
t.Fatalf("stored rows = %d, want one for a repeated event ID", len(fixture.repository.entries))
}
entry := fixture.repository.entries[0]
if entry.EventID() != event.EventID || entry.RecipientUserID() != fixture.user.ID ||
entry.OrganizationID() != fixture.organizationID || entry.SourceID() != fixture.organizationID ||
entry.SourceType() != domain.NotificationInboxSourceOrganization {
t.Fatalf("stored entry = %+v, want the references of the event", entry)
}
if _, isRead := entry.ReadAt(); isRead {
t.Fatal("a delivered row starts as read")
}
}
func TestInboxHandlerRejectsEventsThatBreakTheContract(t *testing.T) {
t.Parallel()
for _, test := range []struct {
name string
mutate func(*outbound.ConsumedEvent, *inboxFixture)
}{
{name: "schema version", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.SchemaVersion = 2 }},
{name: "aggregate type", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.AggregateType = "mail_request" }},
{name: "unknown field", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `","organization_id":"` + fixture.organizationID.String() + `","email":"a@example.test"}`)
}},
{name: "missing organization", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `"}`)
}},
{name: "not an object", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.Payload = json.RawMessage(`[]`) }},
{name: "trailing data", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) {
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {}`)...)
}},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
test.mutate(&event, fixture)
err := handler.Handle(context.Background(), fixture.unit(), event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
}
if len(fixture.repository.entries) != 0 {
t.Fatal("a rejected event stored a row")
}
})
}
}
func TestInboxHandlerRejectsAnEventIDReusedWithOtherMetadata(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(first) error = %v", err)
}
event.OccurredAt = event.OccurredAt.Add(time.Hour)
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(changed replay) error = %v, want ErrEventRejected", err)
}
}
func TestInboxHandlerSkipsADeletedRecipientAndKeepsStoreErrorsRetryable(t *testing.T) {
t.Parallel()
handler, fixture, event := newInboxHandlerFixture(t)
delete(fixture.users, fixture.user.ID)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(deleted recipient) error = %v, want a skip", err)
}
if len(fixture.repository.entries) != 0 {
t.Fatal("a deleted recipient got a row")
}
handler, fixture, event = newInboxHandlerFixture(t)
fixture.repository.storeErr = errors.New("connection reset")
err := handler.Handle(context.Background(), fixture.unit(), event)
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(store failure) error = %v, want a retryable error", err)
}
fixture.repository.storeErr = outbound.ErrNotificationInboxReferenceMissing
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(missing organization) error = %v, want ErrEventRejected", err)
}
// A recipient deleted between the check and the insert is not the event's
// fault: the attempt is retried, and the retry skips the deleted account.
fixture.repository.storeErr = outbound.ErrNotificationInboxRecipientMissing
if err := handler.Handle(context.Background(), fixture.unit(), event); err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle(vanished recipient) error = %v, want a retryable error", err)
}
delete(fixture.users, fixture.user.ID)
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(retry after the recipient vanished) error = %v, want a skip", err)
}
}
func TestInboxHandlerPlugsInInvitationEventsWithTheSameContract(t *testing.T) {
t.Parallel()
handler, fixture, _ := newInboxHandlerFixture(t)
invitationID := uuid.New()
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID})
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
event := outbound.ConsumedEvent{
EventID: uuid.New(), EventType: string(domain.NotificationInboxInvitationDelivered), SchemaVersion: 1,
AggregateType: "invitation", AggregateID: invitationID, AggregateVersion: 3,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
}
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(invitation.delivered) error = %v", err)
}
entry := fixture.repository.entries[0]
if entry.SourceType() != domain.NotificationInboxSourceInvitation || entry.SourceID() != invitationID {
t.Fatalf("invitation entry source = %s %s, want the invitation aggregate", entry.SourceType(), entry.SourceID())
}
}
func TestInboxHandlerStoresARowWhateverTheStateOfTheAddress(t *testing.T) {
t.Parallel()
// A mail delivery skips an address that is not verified. The inbox is the
// delivery state inside the platform and reads no mail state.
handler, fixture, event := newInboxHandlerFixture(t)
unverified := fixture.user
unverified.EmailVerifiedAt = nil
fixture.users[unverified.ID] = unverified
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
t.Fatalf("Handle(unverified address) error = %v", err)
}
if len(fixture.repository.entries) != 1 {
t.Fatalf("stored rows = %d, want 1: an address state must not block a notification", len(fixture.repository.entries))
}
}
func TestInboxHandlerIgnoresTheSyntheticEventWhileItIsSwitchedOff(t *testing.T) {
t.Parallel()
_, fixture, event := newInboxHandlerFixture(t)
off := NewInboxHandler(slog.New(slog.DiscardHandler), false)
if off.Handles(event.EventType) {
t.Fatal("the synthetic event is handled while the switch is off")
}
if !off.Handles(string(domain.NotificationInboxInvitationDelivered)) {
t.Fatal("the invitation event must not depend on the synthetic switch")
}
if err := off.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) || len(fixture.repository.entries) != 0 {
t.Fatalf("Handle(synthetic, off) error = %v, rows = %d, want a rejection and no row", err, len(fixture.repository.entries))
}
if _, ok := DefaultInboxSourceResolvers(false)[domain.NotificationInboxSourceOrganization]; ok {
t.Fatal("the synthetic resolver is registered while the switch is off")
}
if _, ok := DefaultInboxSourceResolvers(true)[domain.NotificationInboxSourceOrganization]; !ok {
t.Fatal("the synthetic resolver is missing while the switch is on")
}
}
@@ -3,6 +3,7 @@ package notification
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -12,78 +13,168 @@ import (
"lincodex/backend/internal/port/outbound"
)
func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) {
t.Parallel()
repository := &memoryInboxRepository{}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
input := inboxTestEntryInput()
created, err := service.StoreInvitationDelivered(context.Background(), input)
if err != nil || !created {
t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err)
}
created, err = service.StoreInvitationDelivered(context.Background(), input)
if err != nil || created {
t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err)
}
if len(repository.entries) != 1 {
t.Fatalf("stored entries = %d, want one", len(repository.entries))
}
changed := input
changed.SourceID = uuid.New()
if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) {
t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err)
}
}
func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) {
t.Parallel()
first := mustInboxTestEntry(t, inboxTestEntryInput())
secondInput := inboxTestEntryInput()
secondInput.RecipientUserID = first.RecipientUserID()
secondInput.OrganizationID = first.OrganizationID()
secondInput.EventID = uuid.New()
second := mustInboxTestEntry(t, secondInput)
wrongOrganizationInput := inboxTestEntryInput()
wrongOrganizationInput.RecipientUserID = first.RecipientUserID()
wrongOrganizationInput.EventID = uuid.New()
wrongOrganizationInput.OrganizationID = uuid.New()
wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput)
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}}
resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}}
service := newInboxTestService(t, repository, resolver, time.Now)
orgID := first.OrganizationID()
page, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10,
})
fixture := newInboxFixture(t, domain.ScenarioCandidate)
first := fixture.add(t, fixture.entryInput())
second := fixture.add(t, fixture.entryInput())
fixture.resolver.unavailable[second.EventID()] = true
otherRecipient := fixtureEntryInput(uuid.New(), fixture.organizationID)
fixture.add(t, otherRecipient)
page, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if err != nil {
t.Fatalf("List() error = %v", err)
}
if len(page.Items) != 2 {
t.Fatalf("List() returned %d items, want 2", len(page.Items))
t.Fatalf("List() returned %d items, want only the recipient's 2", len(page.Items))
}
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", page.Items[0])
byID := map[uuid.UUID]InboxItem{}
for _, item := range page.Items {
byID[item.Entry.EventID()] = item
}
if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1])
if item := byID[first.EventID()]; item.Content == nil || item.ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", item)
}
if resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
if item := byID[second.EventID()]; item.Content != nil || !item.ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", item)
}
if fixture.resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", fixture.resolver.calls)
}
}
func TestInboxServiceAuthorizesTheCabinetInTheReadTransaction(t *testing.T) {
t.Parallel()
t.Run("the candidate inbox refuses an employer", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(employer in the candidate cabinet) error = %v, want ErrInboxForbidden", err)
}
if fixture.repository.listCalls != 0 {
t.Fatal("the repository was read before the account was authorized")
}
})
t.Run("the organization inbox refuses a candidate", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
_, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(candidate in the organization cabinet) error = %v, want ErrInboxForbidden", err)
}
})
t.Run("an unknown or unverified account is refused", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: uuid.New(), Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(unknown account) error = %v, want ErrInboxForbidden", err)
}
fixture.user.EmailVerifiedAt = nil
fixture.users[fixture.user.ID] = fixture.user
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
t.Fatalf("List(unverified account) error = %v, want ErrInboxForbidden", err)
}
})
t.Run("a revoked membership answers like an unknown organization", func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
entry := fixture.add(t, fixture.entryInput())
request := InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10}
page, err := fixture.service.List(context.Background(), request)
if err != nil || len(page.Items) != 1 {
t.Fatalf("List(active member) = %d items, %v, want 1 item", len(page.Items), err)
}
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateRemoved)
if _, err := fixture.service.List(context.Background(), request); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("List(revoked member) error = %v, want ErrOrganizationNotFound", err)
}
_, err = fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: entry.EventID(),
})
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("MarkRead(revoked member) error = %v, want ErrOrganizationNotFound", err)
}
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
t.Fatal("a revoked member marked an item read")
}
unknown := uuid.New()
_, err = fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &unknown, Limit: 10})
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("List(unknown organization) error = %v, want the same ErrOrganizationNotFound", err)
}
})
}
func TestInboxServiceOrganizationCabinetServesEveryRoleItsOwnItems(t *testing.T) {
t.Parallel()
for _, role := range []domain.OrganizationRole{
domain.OrganizationRoleOwner, domain.OrganizationRoleRecruiter,
domain.OrganizationRoleHiringManager, domain.OrganizationRoleTechnicalExpert,
} {
t.Run(string(role), func(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, role, domain.MembershipStateActive)
own := fixture.add(t, fixture.entryInput())
otherMember := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
otherOrganization := fixture.add(t, fixtureEntryInput(fixture.user.ID, uuid.New()))
page, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if err != nil || len(page.Items) != 1 || page.Items[0].Entry.EventID() != own.EventID() {
t.Fatalf("List(%s) = %d items, %v, want only its own item", role, len(page.Items), err)
}
if fixture.locks == 0 {
t.Fatal("the membership was not locked for the read")
}
for _, foreign := range []domain.NotificationInboxEntry{otherMember, otherOrganization} {
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: foreign.EventID(),
})
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
t.Fatalf("MarkRead(%s, foreign item) error = %v, want ErrNotificationInboxEntryNotFound", role, err)
}
}
if _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: own.EventID(),
}); err != nil {
t.Fatalf("MarkRead(%s, own item) error = %v", role, err)
}
})
}
}
func TestInboxServiceOrganizationCabinetNeedsAConfirmedEmail(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioEmployer)
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
fixture.user.EmailVerifiedAt = nil
fixture.users[fixture.user.ID] = fixture.user
_, err := fixture.service.List(context.Background(), InboxListRequest{
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
})
if !errors.Is(err, ErrInboxEmailNotVerified) {
t.Fatalf("List(unverified employer) error = %v, want ErrInboxEmailNotVerified", err)
}
}
func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
_, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10,
})
fixture := newInboxFixture(t, domain.ScenarioCandidate)
fixture.repository.ignoreListScope = true
fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
if !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
}
@@ -92,21 +183,17 @@ func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T
func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC)
secondRead := firstRead.Add(time.Hour)
clockCalls := 0
clock := func() time.Time {
fixture := newInboxFixtureWithClock(t, domain.ScenarioCandidate, func() time.Time {
clockCalls++
if clockCalls == 1 {
return firstRead
}
return secondRead
}
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
return firstRead.Add(time.Duration(clockCalls-1) * time.Hour)
})
entry := fixture.add(t, fixture.entryInput())
for range 2 {
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
read, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, EventID: entry.EventID(),
})
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
@@ -117,6 +204,22 @@ func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
}
}
func TestInboxServiceMarkReadRefusesAnotherRecipientsItem(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
foreign := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
RecipientUserID: fixture.user.ID, EventID: foreign.EventID(),
})
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
t.Fatalf("MarkRead(foreign item) error = %v, want ErrNotificationInboxEntryNotFound", err)
}
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
t.Fatal("another recipient's item was marked read")
}
}
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
t.Parallel()
@@ -129,6 +232,9 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
{name: "query string", path: "/candidate/invitations?token=secret"},
{name: "fragment", path: "/candidate/invitations#current"},
{name: "backslash", path: `/candidate\\invitations`},
{name: "escape", path: "/candidate/%2e%2e/invitations"},
{name: "dot segment", path: "/candidate/../invitations"},
{name: "too long", path: "/" + strings.Repeat("a", 300)},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -138,32 +244,112 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
}
})
}
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"); err != nil {
t.Fatalf("NewInboxContent(same-origin path) error = %v", err)
}
}
func newInboxTestService(
t *testing.T,
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) *InboxService {
func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) {
t.Parallel()
fixture := newInboxFixture(t, domain.ScenarioCandidate)
entry := fixture.add(t, fixture.entryInput())
unit := fixture.unit()
content, err := ResolveSyntheticNotice(context.Background(), unit, entry)
if err != nil {
t.Fatalf("ResolveSyntheticNotice(visible) error = %v", err)
}
if content.Title() != syntheticNoticeTitle || content.LinkPath() != "" || content.Summary() == "" {
t.Fatalf("synthetic content = %+v", content)
}
fixture.repository.organizationName = ""
if _, err := ResolveSyntheticNotice(context.Background(), unit, entry); !errors.Is(err, ErrInboxContentUnavailable) {
t.Fatalf("ResolveSyntheticNotice(not visible) error = %v, want ErrInboxContentUnavailable", err)
}
resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(true))
invitation := fixtureEntry(t, domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID,
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
})
if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) {
t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err)
}
}
type inboxFixture struct {
service *InboxService
repository *memoryInboxRepository
resolver *memoryInboxResolver
users map[uuid.UUID]domain.User
memberships map[uuid.UUID]domain.Membership
user domain.User
organizationID uuid.UUID
locks int
}
func newInboxFixture(t *testing.T, scenario domain.Scenario) *inboxFixture {
t.Helper()
service, err := NewInboxService(repository, resolver, clock)
return newInboxFixtureWithClock(t, scenario, time.Now)
}
func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func() time.Time) *inboxFixture {
t.Helper()
verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
fixture := &inboxFixture{
repository: &memoryInboxRepository{organizationName: "Север"},
resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}},
users: map[uuid.UUID]domain.User{},
memberships: map[uuid.UUID]domain.Membership{},
user: domain.User{ID: uuid.New(), Scenario: scenario, EmailVerifiedAt: &verifiedAt},
organizationID: uuid.New(),
}
fixture.users[fixture.user.ID] = fixture.user
service, err := NewInboxService(inboxTestTransactor{fixture: fixture}, fixture.resolver, clock)
if err != nil {
t.Fatalf("NewInboxService() error = %v", err)
}
return service
fixture.service = service
return fixture
}
func inboxTestEntryInput() domain.NotificationInboxEntryInput {
func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} }
func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput {
return fixtureEntryInput(fixture.user.ID, fixture.organizationID)
}
func (fixture *inboxFixture) add(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry := fixtureEntry(t, input)
fixture.repository.entries = append(fixture.repository.entries, entry)
return entry
}
func (fixture *inboxFixture) addMembership(t *testing.T, role domain.OrganizationRole, state domain.MembershipState) {
t.Helper()
now := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: uuid.New(), OrganizationID: fixture.organizationID, UserID: fixture.user.ID,
Role: string(role), State: string(state), CreatedAt: now, UpdatedAt: now,
})
if err != nil {
t.Fatalf("RestoreMembership() error = %v", err)
}
fixture.memberships[fixture.user.ID] = membership
}
func fixtureEntryInput(recipientID, organizationID uuid.UUID) domain.NotificationInboxEntryInput {
return domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID,
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID,
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
}
}
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
func fixtureEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
@@ -172,14 +358,71 @@ func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput)
return entry
}
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
type inboxTestTransactor struct{ fixture *inboxFixture }
func (transactor inboxTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
return fn(ctx, transactor.fixture.unit())
}
type inboxTestUnit struct {
outbound.UnitOfWork
fixture *inboxFixture
}
func (unit inboxTestUnit) Users() outbound.UserRepository {
return inboxTestUsers{fixture: unit.fixture}
}
func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository {
return inboxTestOrganizations{fixture: unit.fixture}
}
func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository {
return unit.fixture.repository
}
type inboxTestUsers struct {
outbound.UserRepository
fixture *inboxFixture
}
func (repository inboxTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
user, ok := repository.fixture.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type inboxTestOrganizations struct {
outbound.OrganizationRepository
fixture *inboxFixture
}
// LockActiveMembership answers like the real repository: only an active
// membership of the account in the organization is returned.
func (repository inboxTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
repository.fixture.locks++
membership, ok := repository.fixture.memberships[userID]
if !ok || membership.OrganizationID() != organizationID || !membership.GrantsAccess() {
return domain.Membership{}, outbound.ErrOrganizationNotFound
}
return membership, nil
}
type memoryInboxRepository struct {
entries []domain.NotificationInboxEntry
ignoreListScope bool
entries []domain.NotificationInboxEntry
ignoreListScope bool
listCalls int
organizationName string
storeErr error
}
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
if repository.storeErr != nil {
return false, repository.storeErr
}
for _, existing := range repository.entries {
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
continue
@@ -194,6 +437,7 @@ func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.N
}
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
repository.listCalls++
page := outbound.NotificationInboxPage{}
for _, entry := range repository.entries {
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
@@ -207,12 +451,13 @@ func (repository *memoryInboxRepository) List(_ context.Context, query outbound.
func (repository *memoryInboxRepository) MarkRead(
_ context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error) {
for index, entry := range repository.entries {
if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID {
if entry.RecipientUserID() != recipientUserID || entry.EventID() != eventID ||
(organizationID != nil && entry.OrganizationID() != *organizationID) {
continue
}
read, err := entry.MarkRead(at)
@@ -225,6 +470,13 @@ func (repository *memoryInboxRepository) MarkRead(
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
}
func (repository *memoryInboxRepository) OrganizationNameForRecipient(context.Context, uuid.UUID, uuid.UUID) (string, error) {
if repository.organizationName == "" {
return "", outbound.ErrNotificationInboxSourceNotVisible
}
return repository.organizationName, nil
}
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
@@ -236,7 +488,7 @@ type memoryInboxResolver struct {
calls int
}
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
func (resolver *memoryInboxResolver) Resolve(_ context.Context, _ outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
resolver.calls++
if resolver.unavailable[entry.EventID()] {
return InboxContent{}, ErrInboxContentUnavailable
@@ -0,0 +1,74 @@
package policy
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ErrNotDemoPolicy reports a latest product policy that is not a demonstration
// version. The operator command never builds on a calibrated version.
var ErrNotDemoPolicy = errors.New("the latest product policy is not a demonstration version")
// ErrPolicyChanged reports that another publication took the next version
// number while the section was being added. Nothing was stored; the command
// can be run again.
var ErrPolicyChanged = errors.New("the product policy changed during publication, run the command again")
// MatchingResult reports what EnsureDemoMatchingSection did. Version is the
// version that carries the matching section: the new one when Created, the
// latest one otherwise.
type MatchingResult struct {
Created bool
Version domain.PolicyVersion
}
// EnsureDemoMatchingSection makes the latest demonstration version carry the
// demo matching section. A version that already has the section is left alone.
// Otherwise it publishes the next version: a copy of the latest one with
// domain.DemoMatchingPolicy added, so no other value changes. It refuses a
// latest version that is not a demonstration version and a family without a
// version, because the section is only an addition to a policy that exists.
func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
const location = "Publisher.EnsureDemoMatchingSection"
latest, err := publisher.policies.GetLatest(ctx, domain.ProductPolicyKey)
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return MatchingResult{}, fmt.Errorf("%s - the product policy has no version to extend: %w", location, err)
}
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - read latest version: %w", location, err)
}
current := latest.Policy()
if current.Matching != nil {
return MatchingResult{Version: latest}, nil
}
if latest.Kind() != domain.PolicyKindDemo {
return MatchingResult{}, fmt.Errorf("%s - latest version %d is %s: %w", location, latest.Version(), latest.Kind(), ErrNotDemoPolicy)
}
matching := domain.DemoMatchingPolicy()
current.Matching = &matching
// The new version is built on the version that was read, so it takes the
// next number exactly once. A taken number means the base is no longer the
// latest, and the operator decides again instead of the command retrying.
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: current,
})
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - build the extended version: %w", location, err)
}
numbered, err := draft.WithVersion(latest.Version() + 1)
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - number the extended version: %w", location, err)
}
published, err := publisher.policies.Create(ctx, numbered)
if errors.Is(err, outbound.ErrPolicyVersionConflict) {
return MatchingResult{}, fmt.Errorf("%s - version %d is taken: %w", location, numbered.Version(), ErrPolicyChanged)
}
if err != nil {
return MatchingResult{}, fmt.Errorf("%s - store the extended version: %w", location, err)
}
return MatchingResult{Created: true, Version: published}, nil
}
@@ -0,0 +1,83 @@
package policy
import (
"context"
"errors"
"testing"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func seedVersion(t *testing.T, store *memoryPolicies, kind domain.PolicyKind, product domain.ProductPolicy) {
t.Helper()
publisher := NewPublisher(store, testClock)
if _, err := publisher.Publish(context.Background(), PublishInput{
Key: domain.ProductPolicyKey, Kind: kind, Author: domain.DemoPolicySeedAuthor, Policy: product,
}); err != nil {
t.Fatalf("Publish() error = %v", err)
}
}
func TestEnsureDemoMatchingSectionAddsOnlyTheSection(t *testing.T) {
store := &memoryPolicies{}
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2())
publisher := NewPublisher(store, testClock)
result, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night")
if err != nil || !result.Created || result.Version.Version() != 2 {
t.Fatalf("EnsureDemoMatchingSection() = %+v, %v, want version 2 created", result, err)
}
extended := result.Version.Policy()
want := domain.DemoProductPolicyV2()
if extended.Matching == nil || extended.Support == nil || extended.Assessment.Attempt == nil ||
extended.Invitations.MaxPendingPerNeed != want.Invitations.MaxPendingPerNeed {
t.Fatalf("extended policy = %+v, want the earlier sections kept and the matching section added", extended)
}
if result.Version.Kind() != domain.PolicyKindDemo || string(result.Version.Author()) != "operator:night" {
t.Fatalf("version kind/author = %s/%s", result.Version.Kind(), result.Version.Author())
}
again, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night")
if err != nil || again.Created || again.Version.Version() != 2 || len(store.versions) != 2 {
t.Fatalf("second call = %+v, %v with %d versions, want no new version", again, err, len(store.versions))
}
}
func TestEnsureDemoMatchingSectionRefusesWhatItCannotExtend(t *testing.T) {
empty := &memoryPolicies{}
if _, err := NewPublisher(empty, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, outbound.ErrPolicyVersionNotFound) {
t.Fatalf("empty family error = %v, want ErrPolicyVersionNotFound", err)
}
calibrated := &memoryPolicies{}
product := domain.DemoProductPolicyV2()
product.Assessment.Calibration = domain.AssessmentCalibrationCalibrated
seedVersion(t, calibrated, domain.PolicyKindCalibrated, product)
if _, err := NewPublisher(calibrated, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, ErrNotDemoPolicy) {
t.Fatalf("calibrated family error = %v, want ErrNotDemoPolicy", err)
}
if len(calibrated.versions) != 1 {
t.Fatalf("versions = %d, want the calibrated family untouched", len(calibrated.versions))
}
}
func TestEnsureDemoMatchingSectionDoesNotRetryAfterAConcurrentPublication(t *testing.T) {
store := &memoryPolicies{}
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2())
store.beforeCreate = func(domain.PolicyVersionDraft) {
store.beforeCreate = nil
// Another operator publishes version 2 first.
if _, err := NewPublisher(store, testClock).Publish(context.Background(), PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "operator:other", Policy: domain.DemoProductPolicyV2(),
}); err != nil {
t.Errorf("concurrent Publish() error = %v", err)
}
}
_, err := NewPublisher(store, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night")
if !errors.Is(err, ErrPolicyChanged) {
t.Fatalf("EnsureDemoMatchingSection() error = %v, want ErrPolicyChanged", err)
}
if len(store.versions) != 2 || store.versions[1].Policy().Matching != nil {
t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions))
}
}