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

+41
View File
@@ -718,6 +718,47 @@ Each operation also declares the problem response `default`. No new problem code
Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list.
### Match search
The tag `organization` has one search operation for the organization-visible candidate bank (PRD FR09). It is implemented as a deterministic search without ML; the model, the groups, and the data it reads are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | session, CSRF, `Origin`, active owner | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` |
The operation changes nothing and needs no Idempotency-Key; `POST` carries the body. The 200 response also declares no 429.
- Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment.
- Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted).
- Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another.
- Neutral and unknown values. The semantics component is 0.5 for every entry with `ml_unavailable`; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`.
- A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required.
- No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults.
Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock.
Open questions: the demo value 10 of `max_results_per_group` and whether the output needs paging beyond it; whether a search should charge a candidate for a summary entry at the price of a full card view; whether the grade of a need should be an implicit filter or only an explanation; whether the PRD values should keep an online Backend result (trust 0.6 times the broad relation 0.4 gives 0.24) below the near threshold 0.25 while a stated tag (0.25) reaches it, so that a candidate whose only evidence for a required technology is an assessment of the specialization is always in `near` for it; whether the `stack` filter should require every tag (as implemented) or any; and whether the demonstration relation between specializations and technologies (Backend over Go, PostgreSQL, Kafka, and Docker; DevOps over Docker) is the taxonomy the owner wants.
### Notifications
The tag `notification` describes the in-platform inbox of the current account, in the candidate cabinet and in the cabinet of one organization. It has four operations; the logic behind them is implemented, and no product module produces a real notification yet (see [architecture](../docs/en/ARCHITECTURE.md#internal-notifications)).
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/notifications` | `ListMyNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (an employer account) |
| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (a candidate account) or `email_not_verified`, 404 `not_found` |
| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
Each operation also declares the problem response `default`. No new problem code is added.
- The inbox is the delivery state inside the platform. An item exists once the event reached the platform, whether or not an email was sent, and a failed or missing email never blocks it. A repeated delivery of the same event is the same item (`id` is the event identifier).
- The inbox stores references, not text. `content` is resolved from the current source for the recipient on every read and is `null` 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, can be marked, and a client shows a generic line, never an earlier copy. `content.link_path` is a same-origin absolute path (`^/[A-Za-z0-9/_-]{0,255}$`) or `null`.
- The recipient is the session account. The organization route also needs an active membership of any role in `org_id` and lists only the caller's items of that organization. A candidate on the organization route and an employer on the candidate route get 403 `forbidden`, and an employer with an unconfirmed email gets 403 `email_not_verified` on the organization route. A missing membership, an unknown organization, an item of another account or of another organization, and an unknown identifier get the same 404 `not_found`, so identifiers cannot be enumerated.
- Pagination follows the shared `limit` (1-100, default 20) and `cursor`, newest delivery first with the identifier as the tie-breaker. The cursor is bound to the account and the cabinet; a cursor of another account or cabinet gets 400.
- A mark is idempotent by its effect and needs no Idempotency-Key: the first read time is stored and every repeat returns it. It reads no source and returns no content. `kind` is `invitation_delivered` (no module produces it yet) or `synthetic` (a notice with no product meaning that exercises the path).
- Closed schemas and checks. Every notification object has `additionalProperties: false` and all properties required. `TestNotificationOperationsFollowTheConventions` and `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) check the tag, the security of reads and marks, the statuses, no-store, the parameters, and that an item carries no text, name, or contact outside `content`.
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
+41
View File
@@ -718,6 +718,47 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Открытые вопросы: нужна ли новая версия текста согласия C2, раз публикация `categories` теперь отправляет организации еще один подтверждающий факт оценки (навык, грейд, уровень доверия, год) - решение владельца продукта и юриста, тексты согласий здесь не меняются; нужно ли доказательствам собственное поле карточки вместо поля `categories`; подходит ли работодателю точность в один год; операция скрыть или показать факт для кандидата (сохраненная видимость есть, операции для ее изменения нет); когда в список добавятся заявления профиля и факты из других источников.
### Подбор
В теге `organization` одна операция поиска по банку кандидатов, видимому организации (PRD FR09). Она реализована как детерминированный поиск без ML; модель, группы и читаемые данные описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
| --- | --- | --- | --- | --- |
| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | сессия, CSRF, `Origin`, действующий владелец | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` |
Операция ничего не меняет и не требует Idempotency-Key; `POST` нужен для тела. Ответ 200 также не объявляет 429.
- Доступ. Организация берется из пути и действующего членства владельца аккаунта сессии. Отсутствие сессии дает 401; аккаунт кандидата, участник не владелец, отсутствие CSRF-токена и чужой `Origin` дают 403; неизвестная организация, организация без действующего членства, потребность другой организации, неизвестная потребность и `requirements_version`, которую не создавало изменение подтвержденных требований, дают 404. Скрытые профили, отозванная или отсутствующая публикация C2, скрытие именно этой организации и минимальная когорта карточки применяются до появления любой записи: handle в результате - это handle, который `GetOrganizationCandidateCard` открывает в тот же момент.
- Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован).
- Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой.
- Нейтральные и неизвестные значения. Семантика равна 0.5 для каждой записи с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`.
- Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен.
- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`. Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям.
Принятые остаточные риски: `truncated` - один бит о размере видимого банка, и время ответа растет вместе с ним; оба ограничены пределом группы и не несут числа. Когда реальная сопоставимая когорта категории достигает минимума политики, перцентиль все равно null с причиной `percentile_not_computed`, и поиск не падает. Изменение видимой когорты во время поиска повторяет его до трех раз; два одновременных поиска одной организации сериализуются ее блокировкой квоты.
Открытые вопросы: демонстрационное значение 10 для `max_results_per_group` и нужна ли постраничная выдача сверх него; должен ли поиск списывать кандидата за краткую запись по цене полного просмотра карточки; должен ли грейд потребности быть неявным фильтром или только объяснением; должны ли значения PRD оставлять онлайн-результат Backend (доверие 0.6 на широкую связь 0.4 дает 0.24) ниже порога близости 0.25, тогда как заявленный тег (0.25) его достигает, так что кандидат, у которого единственное доказательство нужной технологии - оценка специализации, всегда попадает для нее в `near`; должен ли фильтр `stack` требовать каждый тег (как реализовано) или любой; и является ли демонстрационная связь специализаций с технологиями (Backend над Go, PostgreSQL, Kafka и Docker; DevOps над Docker) таксономией, которую хочет владелец продукта.
### Уведомления
Тег `notification` описывает внутренний inbox текущего аккаунта в кабинете кандидата и в кабинете одной организации. В нем четыре операции; логика за ними реализована, но настоящие уведомления пока не создает ни один продуктовый модуль (см. [архитектуру](../docs/ru/ARCHITECTURE.md#внутренние-уведомления)).
| Метод и путь | operationId | Защита | Успех | Специфичные ошибки |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/notifications` | `ListMyNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт работодателя) |
| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт кандидата) или `email_not_verified`, 404 `not_found` |
| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 |
Каждая операция также объявляет проблемный ответ `default`. Новый код problem не добавляется.
- Inbox - состояние доставки внутри платформы. Элемент существует, как только событие дошло до платформы, независимо от того, отправлено ли письмо, и неудачное или отсутствующее письмо его не блокирует. Повторная доставка того же события - тот же элемент (`id` - идентификатор события).
- Inbox хранит ссылки, а не текст. `content` вычисляется из текущего источника для получателя при каждом чтении и равен `null`, когда источника нет или получатель сейчас не вправе его видеть (например, кандидат скрыл организацию); элемент остается в списке, его можно отметить, а клиент показывает общую строку и никогда не показывает прежнюю копию. `content.link_path` - абсолютный путь того же origin (`^/[A-Za-z0-9/_-]{0,255}$`) или `null`.
- Получатель - аккаунт сессии. Маршрут организации дополнительно требует активное членство любой роли в `org_id` и показывает только элементы вызывающего в этой организации. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403 `forbidden`, а работодатель с неподтвержденной почтой на маршруте организации - 403 `email_not_verified`. Нет членства, неизвестная организация, элемент другого аккаунта или другой организации и неизвестный идентификатор дают один и тот же 404 `not_found`, поэтому идентификаторы нельзя перебирать.
- Пагинация использует общие `limit` (1-100, по умолчанию 20) и `cursor`, новые доставки первыми, идентификатор разрешает равенство. Курсор привязан к аккаунту и кабинету; курсор другого аккаунта или кабинета дает 400.
- Отметка идемпотентна по эффекту и не требует Idempotency-Key: первое время прочтения сохраняется, и каждый повтор возвращает его. Она не читает источник и не возвращает содержимое. `kind` равен `invitation_delivered` (пока его не создает ни один модуль) или `synthetic` (уведомление без продуктового смысла, которое проверяет путь).
- Закрытые схемы и проверки. У каждого объекта уведомлений `additionalProperties: false`, и все свойства обязательны. `TestNotificationOperationsFollowTheConventions` и `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) проверяют тег, защиту чтений и отметок, статусы, no-store, параметры и то, что у элемента нет текста, названия и контакта вне `content`.
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
+27
View File
@@ -4536,3 +4536,30 @@ HiddenOrganizationLimitReached:
pointer: /org_id
code: limit_reached
message: The candidate already hides the maximum number of organizations.
NotificationListPage:
summary: An unread notice and a read one whose source is no longer visible
value:
items:
- id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
kind: synthetic
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
delivered_at: "2026-10-09T08:30:00Z"
read_at: null
content:
title: Тестовое уведомление
summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий.
link_path: null
- id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f
kind: synthetic
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
delivered_at: "2026-10-08T17:05:00Z"
read_at: "2026-10-08T17:10:00Z"
content: null
page:
has_more: false
next_cursor: null
NotificationReadReceipt:
summary: The first read time of an item
value:
id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
read_at: "2026-10-09T08:45:00Z"
+57
View File
@@ -139,6 +139,7 @@ ThreeGroups:
unknown_flags:
- component: assessment
reason: no_confirmation_for_specialization
truncated: false
Empty:
summary: A valid search with no eligible visible candidates.
@@ -157,6 +158,7 @@ Empty:
main: []
near: []
unconfirmed: []
truncated: false
MLUnavailable:
summary: Semantic similarity uses the documented neutral value while ML is unavailable.
@@ -207,6 +209,7 @@ MLUnavailable:
reason: ml_unavailable
near: []
unconfirmed: []
truncated: false
CohortBelow30:
summary: A small comparison cohort has no published percentile.
@@ -257,3 +260,57 @@ CohortBelow30:
reason: cohort_below_30
near: []
unconfirmed: []
truncated: false
Truncated:
summary: The group limit or the card-view allowance cut the output.
description: >-
Synthetic example. The entries returned are in rank order and already
counted as card views; the flag carries no total.
value:
source:
kind: bank
filters:
specialization: backend
confirmed_grade: null
confirmed_category: null
confirmation_status: null
declared_grade: null
stack: null
conditions: null
groups:
main:
- candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
specialization: backend
confirmation_status: confirmed
declared_grade: null
category:
specialization: backend
grade: junior
strength: standard
public_context:
stack: null
experience_band: null
work_formats: null
salary_compatibility: null
evidence_summary:
- code: confirmed_category
state: supports
components:
fit: 0.5
coverage: 0.5
domain: 0.5
semantics: 0.5
percentile: null
competition: 0.0
freshness: 0.5
responsiveness: 0.5
rank_score: 0.45125
unknown_flags:
- component: semantics
reason: ml_unavailable
- component: percentile
reason: cohort_below_30
near: []
unconfirmed: []
truncated: true
+13
View File
@@ -158,3 +158,16 @@ HiddenOrganizationId:
type: string
format: uuid
example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
NotificationId:
name: notification_id
in: path
required: true
description: >-
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.
schema:
type: string
format: uuid
example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
+112 -1
View File
@@ -4847,7 +4847,7 @@ MatchUnknownComponent:
- domain
MatchUnknownReason:
type: string
description: Bounded explanation for an unknown component, not a hiding reason.
description: 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.
enum:
- ml_unavailable
- cohort_below_30
@@ -4856,6 +4856,7 @@ MatchUnknownReason:
- need_field_unconfirmed
- no_freshness_history
- no_response_history
- percentile_not_computed
MatchUnknownFlag:
type: object
description: A safe, bounded explanation for one unavailable component.
@@ -5110,11 +5111,15 @@ MatchSearchResponse:
required:
- source
- groups
- truncated
properties:
source:
$ref: '#/MatchSearchSource'
groups:
$ref: '#/MatchSearchGroups'
truncated:
type: boolean
description: '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.'
NeedVersion:
type: integer
format: int64
@@ -6027,6 +6032,112 @@ NeedUpdate:
oneOf:
- $ref: '#/NeedSalaryInput'
- type: 'null'
NotificationKind:
type: string
description: '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.'
enum:
- invitation_delivered
- synthetic
NotificationContent:
type: object
description: 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.
additionalProperties: false
required:
- title
- summary
- link_path
properties:
title:
type: string
minLength: 1
maxLength: 120
description: Short heading in Russian.
summary:
type: string
minLength: 1
maxLength: 500
description: One or two sentences in Russian. Plain text, never markup.
link_path:
type:
- string
- 'null'
maxLength: 256
pattern: ^/[A-Za-z0-9/_-]{0,255}$
description: 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.
examples:
- /candidate/invitations
Notification:
type: object
description: 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.
additionalProperties: false
required:
- id
- kind
- organization_id
- delivered_at
- read_at
- content
properties:
id:
type: string
format: uuid
description: 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.
kind:
$ref: '#/NotificationKind'
organization_id:
type: string
format: uuid
description: '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.'
delivered_at:
$ref: '#/Timestamp'
read_at:
description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.
oneOf:
- $ref: '#/Timestamp'
- type: 'null'
content:
description: 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.
oneOf:
- $ref: '#/NotificationContent'
- type: 'null'
NotificationList:
type: object
description: One page of the inbox, newest delivery first.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Items of the page.
items:
$ref: '#/Notification'
page:
$ref: '#/PageInfo'
NotificationReadReceipt:
type: object
description: The read state of one item after a mark. It carries no content, so marking never reads the source.
additionalProperties: false
required:
- id
- read_at
properties:
id:
type: string
format: uuid
description: Identifier of the marked item.
read_at:
$ref: '#/Timestamp'
OrganizationVersion:
type: integer
format: int64
+16 -1
View File
@@ -278,7 +278,12 @@ schemas:
- domain
MatchUnknownReason:
type: string
description: Bounded explanation for an unknown component, not a hiding reason.
description: >-
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.
enum:
- ml_unavailable
- cohort_below_30
@@ -287,6 +292,7 @@ schemas:
- need_field_unconfirmed
- no_freshness_history
- no_response_history
- percentile_not_computed
MatchUnknownFlag:
type: object
description: A safe, bounded explanation for one unavailable component.
@@ -567,8 +573,17 @@ schemas:
required:
- source
- groups
- truncated
properties:
source:
$ref: "#/schemas/MatchSearchSource"
groups:
$ref: "#/schemas/MatchSearchGroups"
truncated:
type: boolean
description: >-
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.
@@ -0,0 +1,131 @@
schemas:
NotificationKind:
type: string
description: |-
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.
enum:
- invitation_delivered
- synthetic
NotificationContent:
type: object
description: >-
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.
additionalProperties: false
required:
- title
- summary
- link_path
properties:
title:
type: string
minLength: 1
maxLength: 120
description: Short heading in Russian.
summary:
type: string
minLength: 1
maxLength: 500
description: One or two sentences in Russian. Plain text, never markup.
link_path:
type:
- string
- "null"
maxLength: 256
pattern: "^/[A-Za-z0-9/_-]{0,255}$"
description: >-
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.
examples:
- /candidate/invitations
Notification:
type: object
description: >-
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.
additionalProperties: false
required:
- id
- kind
- organization_id
- delivered_at
- read_at
- content
properties:
id:
type: string
format: uuid
description: >-
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.
kind:
$ref: "#/schemas/NotificationKind"
organization_id:
type: string
format: uuid
description: >-
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.
delivered_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
read_at:
description: >-
When the recipient first marked the item read, or null while it is
unread. A repeated mark keeps the first time.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
content:
description: >-
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.
oneOf:
- $ref: "#/schemas/NotificationContent"
- type: "null"
NotificationList:
type: object
description: One page of the inbox, newest delivery first.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Items of the page.
items:
$ref: "#/schemas/Notification"
page:
$ref: "./common_schemas.yml#/schemas/PageInfo"
NotificationReadReceipt:
type: object
description: >-
The read state of one item after a mark. It carries no content, so
marking never reads the source.
additionalProperties: false
required:
- id
- read_at
properties:
id:
type: string
format: uuid
description: Identifier of the marked item.
read_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
+375 -2
View File
@@ -27,6 +27,8 @@ tags:
description: 'Visibility of the current candidate: the publication of the anonymous card (a setting that refers to the C2 consent of the ledger and never replaces it), the search status that is not a consent, the organizations that the candidate hides the profile from, the preview of the card, and the history of the settings and of the accesses. Everything is closed by default, and no change makes a candidate more visible than they chose. No schema here reaches a contact, a name, or the lowest salary.'
- name: evidence
description: 'Skill evidence derived from confirmed assessment results: one fact per source event with its skills, trust level, attribution, date, and visibility. The candidate reads their own facts; an organization reads only the permitted projection of a currently visible card. Raw answers, failures, and anti-cheat data are never part of it.'
- name: notification
description: 'The in-platform inbox of the current account: references to delivered events with a read state, in the candidate cabinet and in the cabinet of one organization. The inbox is the source of the delivery state inside the platform and never depends on email. It stores no text: the content of every item is resolved from the current source for the recipient on each read, and an item whose source is gone or no longer visible stays in the list without content.'
- name: consent
description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.'
- name: support
@@ -1647,9 +1649,11 @@ paths:
The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An 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 entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. 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`.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. 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`. 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 not_found. The response is `Cache-Control: no-store`.
security:
@@ -1689,6 +1693,8 @@ paths:
$ref: '#/components/examples/MLUnavailable'
cohort_below_30:
$ref: '#/components/examples/CohortBelow30'
truncated:
$ref: '#/components/examples/Truncated'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
@@ -2556,6 +2562,174 @@ paths:
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/notifications:
get:
operationId: ListMyNotifications
summary: List the inbox of the current candidate.
description: |-
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.
security:
- sessionCookie: []
tags:
- notification
parameters:
- $ref: '#/components/parameters/PageLimit'
- $ref: '#/components/parameters/PageCursor'
responses:
'200':
description: A page of the inbox of the current candidate.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/NotificationList'
examples:
page:
$ref: '#/components/examples/NotificationListPage'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/notifications/{notification_id}/read:
post:
operationId: MarkMyNotificationRead
summary: Mark an item of the inbox of the current candidate as read.
description: |-
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.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- notification
parameters:
- $ref: '#/components/parameters/NotificationId'
responses:
'200':
description: The read state of the item, newly set or repeated.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/NotificationReadReceipt'
examples:
read:
$ref: '#/components/examples/NotificationReadReceipt'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'404':
$ref: '#/components/responses/NotFound'
'429':
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/organizations/{org_id}/notifications:
get:
operationId: ListOrganizationNotifications
summary: List the inbox of the current employer in one organization.
description: |-
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.
security:
- sessionCookie: []
tags:
- notification
parameters:
- $ref: '#/components/parameters/OrganizationId'
- $ref: '#/components/parameters/PageLimit'
- $ref: '#/components/parameters/PageCursor'
responses:
'200':
description: A page of the inbox of the current employer in the organization.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/NotificationList'
examples:
page:
$ref: '#/components/examples/NotificationListPage'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/Forbidden'
'404':
$ref: '#/components/responses/NotFound'
default:
$ref: '#/components/responses/Problem'
/api/v1/organizations/{org_id}/notifications/{notification_id}/read:
post:
operationId: MarkOrganizationNotificationRead
summary: Mark an item of the inbox of the current employer in one organization as read.
description: |-
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.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- notification
parameters:
- $ref: '#/components/parameters/OrganizationId'
- $ref: '#/components/parameters/NotificationId'
responses:
'200':
description: The read state of the item, newly set or repeated.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/NotificationReadReceipt'
examples:
read:
$ref: '#/components/examples/NotificationReadReceipt'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'404':
$ref: '#/components/responses/NotFound'
'429':
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/consents:
get:
operationId: ListMyConsents
@@ -9719,6 +9893,110 @@ components:
description: Permitted facts, one for each supported category.
items:
$ref: '#/components/schemas/OrganizationEvidenceFact'
NotificationKind:
type: string
description: |-
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.
enum:
- invitation_delivered
- synthetic
NotificationContent:
type: object
description: 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.
additionalProperties: false
required:
- title
- summary
- link_path
properties:
title:
type: string
minLength: 1
maxLength: 120
description: Short heading in Russian.
summary:
type: string
minLength: 1
maxLength: 500
description: One or two sentences in Russian. Plain text, never markup.
link_path:
type:
- string
- 'null'
maxLength: 256
pattern: ^/[A-Za-z0-9/_-]{0,255}$
description: 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.
examples:
- /candidate/invitations
Notification:
type: object
description: 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.
additionalProperties: false
required:
- id
- kind
- organization_id
- delivered_at
- read_at
- content
properties:
id:
type: string
format: uuid
description: 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.
kind:
$ref: '#/components/schemas/NotificationKind'
organization_id:
type: string
format: uuid
description: '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.'
delivered_at:
$ref: '#/components/schemas/Timestamp'
read_at:
description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.
oneOf:
- $ref: '#/components/schemas/Timestamp'
- type: 'null'
content:
description: 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.
oneOf:
- $ref: '#/components/schemas/NotificationContent'
- type: 'null'
NotificationList:
type: object
description: One page of the inbox, newest delivery first.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Items of the page.
items:
$ref: '#/components/schemas/Notification'
page:
$ref: '#/components/schemas/PageInfo'
NotificationReadReceipt:
type: object
description: The read state of one item after a mark. It carries no content, so marking never reads the source.
additionalProperties: false
required:
- id
- read_at
properties:
id:
type: string
format: uuid
description: Identifier of the marked item.
read_at:
$ref: '#/components/schemas/Timestamp'
HealthResponse:
type: object
additionalProperties: false
@@ -10717,7 +10995,7 @@ components:
- domain
MatchUnknownReason:
type: string
description: Bounded explanation for an unknown component, not a hiding reason.
description: 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.
enum:
- ml_unavailable
- cohort_below_30
@@ -10726,6 +11004,7 @@ components:
- need_field_unconfirmed
- no_freshness_history
- no_response_history
- percentile_not_computed
MatchUnknownFlag:
type: object
description: A safe, bounded explanation for one unavailable component.
@@ -10875,11 +11154,15 @@ components:
required:
- source
- groups
- truncated
properties:
source:
$ref: '#/components/schemas/MatchSearchSource'
groups:
$ref: '#/components/schemas/MatchSearchGroups'
truncated:
type: boolean
description: '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.'
CardSelfAssessment:
type: object
description: Candidate-declared specialization and optional grade. This is never an assessment result.
@@ -11022,6 +11305,15 @@ components:
type: string
format: uuid
example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
NotificationId:
name: notification_id
in: path
required: true
description: 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.
schema:
type: string
format: uuid
example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
CandidateHandle:
name: candidate_handle
in: path
@@ -14347,6 +14639,7 @@ components:
unknown_flags:
- component: assessment
reason: no_confirmation_for_specialization
truncated: false
Empty:
summary: A valid search with no eligible visible candidates.
value:
@@ -14364,6 +14657,7 @@ components:
main: []
near: []
unconfirmed: []
truncated: false
MLUnavailable:
summary: Semantic similarity uses the documented neutral value while ML is unavailable.
description: Synthetic example; 0.5 is the FR09 neutral value, not an inference.
@@ -14413,6 +14707,7 @@ components:
reason: ml_unavailable
near: []
unconfirmed: []
truncated: false
CohortBelow30:
summary: A small comparison cohort has no published percentile.
description: Synthetic example; the exact cohort size is not disclosed.
@@ -14462,6 +14757,57 @@ components:
reason: cohort_below_30
near: []
unconfirmed: []
truncated: false
Truncated:
summary: The group limit or the card-view allowance cut the output.
description: Synthetic example. The entries returned are in rank order and already counted as card views; the flag carries no total.
value:
source:
kind: bank
filters:
specialization: backend
confirmed_grade: null
confirmed_category: null
confirmation_status: null
declared_grade: null
stack: null
conditions: null
groups:
main:
- candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
specialization: backend
confirmation_status: confirmed
declared_grade: null
category:
specialization: backend
grade: junior
strength: standard
public_context:
stack: null
experience_band: null
work_formats: null
salary_compatibility: null
evidence_summary:
- code: confirmed_category
state: supports
components:
fit: 0.5
coverage: 0.5
domain: 0.5
semantics: 0.5
percentile: null
competition: 0
freshness: 0.5
responsiveness: 0.5
rank_score: 0.45125
unknown_flags:
- component: semantics
reason: ml_unavailable
- component: percentile
reason: cohort_below_30
near: []
unconfirmed: []
truncated: true
OrganizationAnonymousCandidateCard:
summary: An anonymous card currently visible to one organization
description: The alias is scoped to the reading organization; no contact values are included.
@@ -15719,6 +16065,33 @@ components:
granted_at: '2026-10-06T15:00:00Z'
revoked_at: '2026-10-07T10:00:00Z'
revocation_reason: participation_cancelled
NotificationListPage:
summary: An unread notice and a read one whose source is no longer visible
value:
items:
- id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
kind: synthetic
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
delivered_at: '2026-10-09T08:30:00Z'
read_at: null
content:
title: Тестовое уведомление
summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий.
link_path: null
- id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f
kind: synthetic
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
delivered_at: '2026-10-08T17:05:00Z'
read_at: '2026-10-08T17:10:00Z'
content: null
page:
has_more: false
next_cursor: null
NotificationReadReceipt:
summary: The first read time of an item
value:
id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
read_at: '2026-10-09T08:45:00Z'
ConsentRecordListPage:
summary: The whole consent history of a candidate on one page
description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed.
+29
View File
@@ -67,6 +67,15 @@ tags:
visibility. The candidate reads their own facts; an organization reads
only the permitted projection of a currently visible card. Raw
answers, failures, and anti-cheat data are never part of it.
- name: notification
description: >-
The in-platform inbox of the current account: references to delivered
events with a read state, in the candidate cabinet and in the cabinet of
one organization. The inbox is the source of the delivery state inside
the platform and never depends on email. It stores no text: the content
of every item is resolved from the current source for the recipient on
each read, and an item whose source is gone or no longer visible stays
in the list without content.
- name: consent
description: >-
The consent ledger of the current account: the independent consents
@@ -168,6 +177,14 @@ paths:
$ref: ./routes/candidate_invitation_decline.yml
/api/v1/me/invitations/{invitation_id}/cancel:
$ref: ./routes/candidate_invitation_cancel.yml
/api/v1/me/notifications:
$ref: ./routes/candidate_notifications.yml
/api/v1/me/notifications/{notification_id}/read:
$ref: ./routes/candidate_notification_read.yml
/api/v1/organizations/{org_id}/notifications:
$ref: ./routes/organization_notifications.yml
/api/v1/organizations/{org_id}/notifications/{notification_id}/read:
$ref: ./routes/organization_notification_read.yml
/api/v1/me/consents:
$ref: ./routes/consents.yml
/api/v1/me/consents/{purpose}:
@@ -910,6 +927,16 @@ components:
$ref: ./components/schemas.yml#/OrganizationEvidenceFact
OrganizationEvidence:
$ref: ./components/schemas.yml#/OrganizationEvidence
NotificationKind:
$ref: ./components/schemas.yml#/NotificationKind
NotificationContent:
$ref: ./components/schemas.yml#/NotificationContent
Notification:
$ref: ./components/schemas.yml#/Notification
NotificationList:
$ref: ./components/schemas.yml#/NotificationList
NotificationReadReceipt:
$ref: ./components/schemas.yml#/NotificationReadReceipt
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
@@ -933,6 +960,8 @@ components:
$ref: ./components/parameters.yml#/MyInvitationId
HiddenOrganizationId:
$ref: ./components/parameters.yml#/HiddenOrganizationId
NotificationId:
$ref: ./components/parameters.yml#/NotificationId
headers:
ETag:
$ref: ./components/headers.yml#/ETag
@@ -0,0 +1,43 @@
post:
operationId: MarkMyNotificationRead
summary: Mark an item of the inbox of the current candidate as read.
description: |-
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.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- notification
parameters:
- $ref: ../components/parameters.yml#/NotificationId
responses:
"200":
description: The read state of the item, newly set or repeated.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/NotificationReadReceipt
examples:
read:
$ref: ../components/examples.yml#/NotificationReadReceipt
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,37 @@
get:
operationId: ListMyNotifications
summary: List the inbox of the current candidate.
description: |-
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.
security:
- sessionCookie: []
tags:
- notification
parameters:
- $ref: ../components/parameters.yml#/PageLimit
- $ref: ../components/parameters.yml#/PageCursor
responses:
"200":
description: A page of the inbox of the current candidate.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/NotificationList
examples:
page:
$ref: ../components/examples.yml#/NotificationListPage
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem
+5 -1
View File
@@ -6,9 +6,11 @@ post:
The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An 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 entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. 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`.
The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. 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`. 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 not_found. The response is `Cache-Control: no-store`.
security:
@@ -48,6 +50,8 @@ post:
$ref: ../components/examples/matches.yml#/MLUnavailable
cohort_below_30:
$ref: ../components/examples/matches.yml#/CohortBelow30
truncated:
$ref: ../components/examples/matches.yml#/Truncated
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
@@ -0,0 +1,44 @@
post:
operationId: MarkOrganizationNotificationRead
summary: Mark an item of the inbox of the current employer in one organization as read.
description: |-
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.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- notification
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/NotificationId
responses:
"200":
description: The read state of the item, newly set or repeated.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/NotificationReadReceipt
examples:
read:
$ref: ../components/examples.yml#/NotificationReadReceipt
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,40 @@
get:
operationId: ListOrganizationNotifications
summary: List the inbox of the current employer in one organization.
description: |-
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.
security:
- sessionCookie: []
tags:
- notification
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/PageLimit
- $ref: ../components/parameters.yml#/PageCursor
responses:
"200":
description: A page of the inbox of the current employer in the organization.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/NotificationList
examples:
page:
$ref: ../components/examples.yml#/NotificationListPage
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
+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)
}
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more