feat(platform): add the notification inbox and deterministic match search
This commit is contained in:
1 parent
5edff21d2d
commit
0b11021b16
169 files changed
+17083
-443
No files matched your search
+65
-19
@@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff
|
||||
|
||||
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
|
||||
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. Other product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). Other product workflows are not implemented: roles, profiles, assessments, grades, invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
|
||||
|
||||
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
|
||||
|
||||
@@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal
|
||||
|
||||
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
|
||||
|
||||
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; one product consumer is registered, `notification_delivery` for mail deliveries. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
|
||||
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; two product consumers are registered, `notification_delivery` for mail deliveries and `notification_inbox` for the [internal notifications](#internal-notifications). Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
|
||||
|
||||
### HTTP perimeter and client address
|
||||
|
||||
@@ -134,7 +134,7 @@ The metric `lincodex_outbox_relay_events_total{outcome}` counts published and fa
|
||||
|
||||
### Event consumers
|
||||
|
||||
Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `<CONSUMER_GROUP_PREFIX>.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers).
|
||||
Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. Two product handlers are registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries) and the inbox handler `notification_inbox` described in [Internal notifications](#internal-notifications), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in each of the groups `<CONSUMER_GROUP_PREFIX>.notification_delivery` and `<CONSUMER_GROUP_PREFIX>.notification_inbox`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers).
|
||||
|
||||
A handler implements three methods:
|
||||
|
||||
@@ -410,6 +410,25 @@ Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`rese
|
||||
|
||||
Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
||||
|
||||
### Internal notifications
|
||||
|
||||
Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. No product module produces a notification yet. Invitations, the first planned producer, are not implemented, so the only event that reaches the inbox today is a synthetic one and a real recipient sees an empty list.
|
||||
|
||||
Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications).
|
||||
|
||||
- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. When invitations arrive, the delivered state of an invitation is the existence of its inbox row.
|
||||
- A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists.
|
||||
- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module therefore needs no change in the table, the consumer, or the API: it appends `invitation.delivered` and registers a content resolver for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. Until a resolver exists, an item of that source is listed without content.
|
||||
- Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation.
|
||||
- Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `<CONSUMER_GROUP_PREFIX>.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored.
|
||||
- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The one resolver today belongs to the synthetic notice: its fixed Russian text names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. A candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet.
|
||||
- Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction.
|
||||
- Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added.
|
||||
- Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds.
|
||||
- Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event.
|
||||
- Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)).
|
||||
- Not implemented: the invitation producer and its content resolver, an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
Implemented as storage, a publisher, and a startup seed: migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
|
||||
@@ -430,7 +449,7 @@ Typed policy, `domain.ProductPolicy`: every value is a named field whose type ca
|
||||
|
||||
The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization.
|
||||
|
||||
Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
|
||||
Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, `support`, and `matching`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
|
||||
|
||||
The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage.
|
||||
|
||||
@@ -455,6 +474,26 @@ Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initi
|
||||
|
||||
The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values.
|
||||
|
||||
Matching coefficients (`matching`, schema 2, `domain.MatchingPolicy` in `policy_matching.go`, demo version `domain.DemoProductPolicyV4()`): every field is required once the section is present, and the units are basis points except the two skill weights and the cohort size. The demo values are the design values of PRD 4.9 for checking the flow, not measured results; they are published explicitly (the isolated browser fixture publishes V4; startup still seeds V1 only), and a policy version without the section makes the search fail closed instead of ranking with defaults.
|
||||
|
||||
| Field | Demo value | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; the three add up to 1 |
|
||||
| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * freshness * responsiveness`; the two add up to 1 |
|
||||
| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | the multiplier `0.9 + 0.1 * x` of Fr and Rsp; a floor of zero is refused |
|
||||
| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` |
|
||||
| `neutral_unknown_bp` | 5000 | the neutral 0.5 for an unknown component (Dom, Sem, T, Fr, Rsp, and Cov of an empty request) |
|
||||
| `near_skill_threshold_bp` | 2500 | a required skill that contributes less moves a confirmed profile to the near group |
|
||||
| `required_skill_weight`, `desired_skill_weight` | 2, 1 | weights of the skills in Cov |
|
||||
| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | coefficients of the evidence trust levels 0 to 3 |
|
||||
| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | personal result, team role, team result without a role |
|
||||
| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | evidence for the same skill, a narrower one, a broader one |
|
||||
| `percentile_min_cohort` | 30 | the smallest comparable real cohort that allows a percentile; the search compares the real cohort of each returned category with it |
|
||||
| `max_results_per_group` | 10 | entries of each group that one search may return; the whole bank is ranked and only the output is cut |
|
||||
| `skill_taxonomy` | backend over docker, go, kafka, postgresql; devops_sre over docker | the technologies inside each specialization, which decide whether evidence is broader or narrower than a requested skill |
|
||||
|
||||
The validation keeps each share in 0..1, the fit and rank weights at a sum of 1, the trust and relation coefficients ordered, and the floors above zero. Not in the policy yet: the competition half-life of 24 months and the embedding-only relation 0.3, because no competition data and no embeddings exist.
|
||||
|
||||
Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently.
|
||||
|
||||
Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions.
|
||||
@@ -540,7 +579,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
|
||||
|
||||
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
|
||||
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
||||
|
||||
@@ -625,7 +664,7 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql
|
||||
|
||||
### Skill evidence
|
||||
|
||||
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. It feeds nothing yet: no ranking, matching, or percentile reads it.
|
||||
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
|
||||
|
||||
Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)).
|
||||
|
||||
@@ -639,25 +678,32 @@ Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries
|
||||
- Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts.
|
||||
- Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate.
|
||||
- Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property.
|
||||
- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in ranking or in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
|
||||
- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent.
|
||||
Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule.
|
||||
|
||||
Initial baseline after filtering:
|
||||
- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns.
|
||||
- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership.
|
||||
- Charged like card reads. A search returns card content (the confirmed category with its strength, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card.
|
||||
- One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately.
|
||||
- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed.
|
||||
- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged.
|
||||
- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing.
|
||||
- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for every entry (no ML), both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere.
|
||||
- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale.
|
||||
- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`.
|
||||
- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored.
|
||||
- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate.
|
||||
- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions.
|
||||
- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations 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 batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section.
|
||||
|
||||
score = 0.50 * skill_fit
|
||||
+ 0.40 * assessment_score
|
||||
+ 0.10 * fsp_evidence
|
||||
Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. The invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here.
|
||||
|
||||
Each component ranges from 0 to 1. skill_fit is weighted coverage of verified requested skills. assessment_score is the result for relevant assessment sections. fsp_evidence is a small bonus for relevant verified achievements. An empty skill set uses a predefined neutral value and avoids division by zero. Use a stable ID tie-break, never personal characteristics.
|
||||
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success.
|
||||
|
||||
No FSP history gives a zero bonus without excluding the candidate. Synthetic achievements are marked and affect demo data only. Results include score_components, reason_codes, evidence, and gaps. A candidate with a verified Middle grade and 4 of 5 covered skills still fails a filter that requires confirmation of all five.
|
||||
|
||||
This is an initial baseline, not an optimized or measured ranking model. The plan compares keyword search, the verified-skill baseline, and an ML variant. Add a semantic signal only after an experiment; never treat its score as a probability of hiring success.
|
||||
|
||||
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded.
|
||||
Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing.
|
||||
|
||||
## ML, documents, and background jobs
|
||||
|
||||
@@ -953,7 +999,7 @@ Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailabl
|
||||
| Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Not implemented |
|
||||
| Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned |
|
||||
| No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned |
|
||||
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Not implemented |
|
||||
| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not |
|
||||
| Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned |
|
||||
| Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented |
|
||||
| RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Not implemented |
|
||||
|
||||
+15
-1
@@ -120,11 +120,12 @@ The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending
|
||||
|
||||
### Event consumers
|
||||
|
||||
The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `<CONSUMER_GROUP_PREFIX>.<consumer name>`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: one product handler is registered, `notification_delivery` (mail deliveries), so the backend runs one consumer in the group `<CONSUMER_GROUP_PREFIX>.notification_delivery` (`lincodex.notification_delivery` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled.
|
||||
The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `<CONSUMER_GROUP_PREFIX>.<consumer name>`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: two product handlers are registered, `notification_delivery` (mail deliveries) and `notification_inbox` (internal notifications), so the backend runs one consumer in each of the groups `<CONSUMER_GROUP_PREFIX>.notification_delivery` and `<CONSUMER_GROUP_PREFIX>.notification_inbox` (`lincodex.notification_delivery` and `lincodex.notification_inbox` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. A new group starts at the earliest retained event of the topic, so the first start of `notification_inbox` after a deployment reads the retained events and ignores those of other types. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled.
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `CONSUMER_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no consumer runs, and events wait in Kafka for as long as the topic retains them. |
|
||||
| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` or `false`. Turns on the synthetic inbox event `notification.synthetic_delivered`: the `notification_inbox` consumer stores it and the inbox renders its fixed text. Leave it off in production; the browser E2E stand sets it. With `false` such an event is acknowledged and ignored, and a stored synthetic row is listed without content. The database CHECK allows the type either way. |
|
||||
| `CONSUMER_GROUP_PREFIX` | `lincodex` | Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. |
|
||||
| `CONSUMER_MAX_ATTEMPTS` | `5` | Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. |
|
||||
| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Wait after the first failed attempt; it doubles with each consecutive failure. |
|
||||
@@ -345,6 +346,19 @@ make -C backend assessment-category-attest ARGS='attest --specialization backend
|
||||
- The attestation trigger accepts a policy of kind `demo` with `real_mode = demo_basic`. When a category is assigned, the database compares the threshold of the result with `basic_pass_mark_bp` of the policy version pinned to the attempt, so a 9000 threshold in an accepted policy works like 8000. A result decided before the attestation gets no category; only a result decided after it can assign one.
|
||||
- Without either step a result that reached the threshold is stored as `not_eligible`: the candidate sees the score and no category. `demo_express` never creates a category under any setting. `make -C backend assessment-category-attest-build` builds `backend/bin/assessment-category-attest`.
|
||||
|
||||
## Match search policy on a stand
|
||||
|
||||
The match search ranks with the `matching` section of the effective `product` policy and fails closed without it: a search answers 500 `internal`, the log holds an error line that says the effective product policy has no matching section and names the command below, and no default is used. The startup seed publishes only the first demonstration version, which has no such section, so at startup the backend logs the warning `the effective product policy has no matching section` while the section is missing. Publish it once per stand as an operator:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- The command takes the latest product policy version, which must be a demonstration version (kind `demo`), and publishes the next version as a copy of it with the demo matching section added. No other value changes. A latest version that already has the section changes nothing and prints `already present`; if another publication takes the next version number meanwhile, the command stores nothing and asks to run it again; a calibrated latest version, or a family without a version, is refused. `make -C backend policy-publish-build` builds `backend/bin/policy-publish`.
|
||||
- It needs only `DATABASE_URL`, reads no dotenv file, validates its arguments first, and prints the version number only. The author of the version is the `operator:<handle>` label, an audit label and not authentication: local database access is the operator boundary.
|
||||
- The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards.
|
||||
- The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself.
|
||||
|
||||
## Separate ML Compose project
|
||||
|
||||
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
||||
|
||||
@@ -53,7 +53,7 @@ What exists now:
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers).
|
||||
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
|
||||
|
||||
@@ -195,7 +195,7 @@ A directly launched backend with `DATABASE_URL` set runs the relay against `KAFK
|
||||
|
||||
The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`.
|
||||
|
||||
One product handler is registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does.
|
||||
Two product handlers are registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)) and `notification.InboxHandler` stores inbox references (see [Internal notifications](#internal-notifications)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does.
|
||||
|
||||
A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests).
|
||||
|
||||
@@ -205,6 +205,10 @@ To send a notification from a usecase, call `notification.MailRequester.RequestN
|
||||
|
||||
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
|
||||
### Internal notifications
|
||||
|
||||
To put a notification into a recipient's inbox, append an event with `unit.Outbox().Append` in the usecase's own transaction. The type must be allowlisted (`domain.NotificationInboxSourceFor`), the payload must be exactly `recipient_user_id` and `organization_id`, and the aggregate must be the one the type names (`invitation` for `invitation.delivered`). Never put text or contacts in the payload. The `notification_inbox` consumer stores a reference. The text is produced when the recipient reads the list, by a resolver that you register for your source type in `notification.DefaultInboxSourceResolvers()`: an `InboxSourceResolver` that reads the current state through the `UnitOfWork`, applies the recipient's current visibility, and returns `ErrInboxContentUnavailable` when the content must not be shown. For a new event type add the pair to `domain.NotificationInboxSourceFor`, the entry to `inboxProjections` in `usecase/notification/inbox_handler.go`, a migration that widens the CHECK constraint of `notification_inbox_events` (never edit a deployed migration), a `NotificationKind` value to the contract, and the mapping in `adapter/primary/http/v1/notifications.go`. A producer needs no email: mail is requested separately with `MailRequester`, and the inbox state does not depend on it. The path can be tried end to end with the synthetic event `notification.synthetic_delivered` (`notification.SyntheticNoticeEventPayload` builds its payload); it has no product meaning and is handled only when `NOTIFICATION_SYNTHETIC_ENABLED=true`. See [Internal notifications](ARCHITECTURE.md#internal-notifications).
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
|
||||
|
||||
+17
-1
@@ -174,7 +174,7 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa
|
||||
- `internal/usecase/notification/`: a request stores its text under the event's aggregate ID and the event payload carries only `mail_request_id` and `kind`; invalid requests write nothing; the handler stores one delivery under the request ID with the source event, the account address, the rendered content, the configured provider account, and the clock time, and deletes the request; the same event again finds no request; an existing delivery under the request ID is accepted for the same recipient and kind and rejected otherwise; broken events (another schema version or aggregate, a malformed payload, trailing data, a request ID that is not the aggregate ID, a token mail kind) and text the template refuses are rejected without quoting the payload; a request that is gone, an account that is gone, and an unverified address are skipped with a log line that names only the delivery and event IDs; storage failures, including an account deleted between its read and the insert, stay retryable and keep the request; and no error or log line holds the address, subject, or body.
|
||||
- `internal/adapter/secondary/postgres/`: delivery and mail request constraint errors map to their sentinels (`deliveries_content_immutable` and `delivery_attempts_immutable` to `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` to `ErrDeliveryProviderPinned`, the user foreign keys to `ErrUserNotFound`), and any other PostgreSQL error, such as a check violation, keeps only its SQLSTATE and constraint without the message or detail.
|
||||
- `internal/usecase/notification/mailtemplate/`: a rendering converts to the stored content with the same kind, version, parts, and hash.
|
||||
- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` handler and refuses an invalid account label.
|
||||
- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` and `notification_inbox` handlers and refuses an invalid account label.
|
||||
|
||||
`TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are:
|
||||
|
||||
@@ -463,6 +463,22 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
|
||||
The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation.
|
||||
|
||||
## Internal notification tests
|
||||
|
||||
Unit tests (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
- `domain/notification_inbox_test.go`: an entry accepts only the allowlisted pairs of event type and source type (the synthetic event with the organization, `invitation.delivered` with the invitation), a new entry starts unread, and `MarkRead` keeps the first time.
|
||||
- `usecase/notification/inbox_test.go` with an in-memory repository and a fake unit of work: the list resolves each item against its current source and falls back to no content; a candidate cabinet refuses an employer, the organization cabinet refuses a candidate, an unknown or unverified account, and a revoked membership (which answers like an unknown organization, for the list and for the mark); a repository row outside the recipient scope is an internal error; an owner and a recruiter (and the other roles) read and mark only their own items of the organization, with the membership locked for the read; an unverified employer gets `ErrInboxEmailNotVerified`; a mark keeps the first time and cannot touch another recipient's item; content links reject an external URL, a protocol-relative URL, a query, a fragment, a backslash, an escape, a dot segment, and a long path; the synthetic resolver follows the recipient's standing and an unregistered source type is unavailable.
|
||||
- `usecase/notification/inbox_handler_test.go`: a repeated event stores one row; a broken schema version, aggregate, unknown field, missing organization, non-object payload, trailing data, and an event ID reused with other metadata are rejected for good; a deleted recipient is skipped; a store failure stays retryable; an unverified address still gets its row (the inbox reads no mail state); a recipient that vanished between the check and the insert is retried and then skipped, not rejected; the synthetic event is ignored while its switch is off; an `invitation.delivered` event with the same payload contract stores the invitation as its source.
|
||||
- `adapter/primary/http/v1/notifications_test.go` and `adapter/primary/http/notification_contract_test.go`: the mapping of content and fallback, the cursor bound to the account and the cabinet (a foreign or crossed cursor is a 400), the refusals, the conventions of the four operations, and closed schemas. `bootstrap/consumers_test.go` pins the two registered consumers.
|
||||
- Frontend: `features/notifications/` tests the link check, the retry of a mark once after a 403 (and no retry of a 401, 404, or 500), the labels, the wording of an item without content, the query keys and their removal by account, and the rendered list (read state as a word, a mark button only for unread items, no unsafe link, the empty state, the refusal of the other cabinet).
|
||||
|
||||
Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka): `TestNotificationInboxOverHTTP` writes a synthetic event through the real outbox writer and delivers it through the consumer store with the real handler. One event delivered twice and once more by a renamed consumer stores one row. The same router then checks the candidate list, a foreign candidate, the wrong cabinet, a missing CSRF token and a foreign Origin, the mark and its repeat (the first time is kept), the persistence of the read state, the loss of content when the candidate hides the organization, paging with a cursor bound to the account, the employer cabinet with only its own items of the organization, a recruiter with its own items, a non-member, an item of another organization, and the 404 for the list and the mark after the membership is revoked. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` and `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` check the allowlist of migration 00036, the refused rollback with a synthetic row, and the restored constraint. `TestNotificationInboxStoreNamesTheMissingReference` checks that a missing recipient and a missing organization are told apart. `TestPostgresMigrations` covers up and down to zero.
|
||||
|
||||
Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content.
|
||||
|
||||
What these tests do not show: a real invitation (none produces an event yet), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check).
|
||||
|
||||
## Future software validation
|
||||
|
||||
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
|
||||
|
||||
+65
-19
@@ -6,7 +6,7 @@
|
||||
|
||||
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
|
||||
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
|
||||
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
|
||||
|
||||
@@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через
|
||||
|
||||
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Общий файловый слой и контроль доступа в контейнере SeaweedFS описаны в разделе [Закрытое файловое хранилище](#закрытое-файловое-хранилище). Загрузка резюме, проверка прав, продуктовые правила содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
|
||||
|
||||
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрирован один продуктовый обработчик - `notification_delivery` для доставок писем. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
|
||||
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрированы два продуктовых обработчика - `notification_delivery` для доставок писем и `notification_inbox` для [внутренних уведомлений](#внутренние-уведомления). Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
|
||||
|
||||
### HTTP-периметр и адрес клиента
|
||||
|
||||
@@ -134,7 +134,7 @@ Producer требует подтверждения от всех in-sync реп
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `<CONSUMER_GROUP_PREFIX>.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий).
|
||||
Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрированы два продуктовых обработчика: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), и обработчик inbox `notification_inbox`, описанный в разделе [Внутренние уведомления](#внутренние-уведомления), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает по одному обработчику в группах `<CONSUMER_GROUP_PREFIX>.notification_delivery` и `<CONSUMER_GROUP_PREFIX>.notification_inbox`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий).
|
||||
|
||||
Обработчик реализует три метода:
|
||||
|
||||
@@ -410,6 +410,25 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Открытые вопросы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
|
||||
### Внутренние уведомления
|
||||
|
||||
Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Ни один продуктовый модуль пока не создает уведомления. Приглашения, первый запланированный источник, не реализованы, поэтому единственное событие, которое сегодня попадает в inbox, синтетическое, и у настоящего получателя список пуст.
|
||||
|
||||
Код: миграции `backend/db/migrations/00032_create_notification_inbox.sql` и `00036_allow_synthetic_notification_event.sql`, запросы `backend/db/queries/notification_inbox.sql`, модель `backend/internal/domain/notification_inbox.go`, порт `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), адаптер `adapter/secondary/postgres/notification_inbox.go`, файлы usecase `usecase/notification/inbox.go`, `inbox_handler.go` и `inbox_content.go`, HTTP-обработчик `adapter/primary/http/v1/notifications.go` с курсором `notification_cursor.go`, подключение в `bootstrap/notification.go` и `eventHandlers()` и frontend-функция `frontend/src/features/notifications/` со страницей `frontend/src/pages/notifications/`. Операции описаны в [api/README.md](../../api/README.md#уведомления).
|
||||
|
||||
- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Когда появятся приглашения, состояние "доставлено" у приглашения - это существование его строки в inbox.
|
||||
- Строка хранит ссылки, а не текст. В `notification_inbox_events` ключ `(recipient_user_id, event_id)` и столбцы `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at` и `read_at`. Заголовка, текста, названия, контакта и оценки там нет. Триггеры делают ссылку неизменяемой (можно только один раз задать `read_at`) и запрещают прямое удаление; удаление аккаунта получателя удаляет строки каскадом, а внешний ключ организации - `RESTRICT`. CHECK пропускает только пары типа события и типа источника из `domain.NotificationInboxSourceFor`, обе в версии схемы 1: `invitation.delivered` с `invitation` и синтетическое `notification.synthetic_delivered` с `organization`. Миграция 00032 уже развернута и не менялась; 00036 только расширила CHECK, а ее откат отказывает, пока есть синтетическая строка.
|
||||
- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Поэтому модулю приглашений не нужны изменения в таблице, обработчике и API: он добавляет `invitation.delivered` и регистрирует преобразователь содержимого для источника `invitation` в `notification.DefaultInboxSourceResolvers()`. Пока преобразователя нет, элемент такого источника показывается без содержимого.
|
||||
- Синтетический тип события. `notification.synthetic_delivered` не имеет продуктового смысла. Он нужен, чтобы пройти весь путь (outbox, relay, Kafka, обработчик, проверка при чтении, список, прочтение) до появления настоящего источника и в браузерных тестах. По умолчанию он выключен: обработчик обрабатывает его, а inbox показывает, только при `NOTIFICATION_SYNTHETIC_ENABLED=true` (стенд разработки или браузерных тестов; overlay e2e включает его). При выключенном флаге событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого; CHECK в базе разрешает тип в любом случае, поэтому для включения миграция не нужна. Создать событие может только код, который умеет писать в outbox, а содержимое - фиксированный текст с названием отправляющей организации. Браузерный набор добавляет его через `company-fixture` (тег сборки Go `e2e`), а не через операцию пользователя.
|
||||
- Обработчик `notification_inbox`. `InboxHandler` обрабатывает разрешенные типы. В транзакции dedup-маркера он проверяет конверт и payload и окончательно отклоняет сломанное событие (`ErrEventRejected`), пропускает получателя, чей аккаунт удален, и пишет строку с `ON CONFLICT DO NOTHING` по ключу. Получатель, удаленный между проверкой и вставкой, прерывает вставку внешним ключом получателя; обработчик возвращает это как повторяемую ошибку, и повтор видит, что аккаунта нет, и пропускает событие, а ошибка внешнего ключа организации отклоняет событие окончательно. Одну строку на получателя и ID события держат три слоя: маркер обработчика, ключ и сравнение дубликата с сохраненными метаданными; ID события, который пришел снова с другими метаданными, отклоняется, а не перезаписывается. Поэтому повтор под переименованным обработчиком второй строки не создает. `occurred_at` - информационное время вставки строки outbox; вместе с ID события оно упорядочивает список. Группа `<CONSUMER_GROUP_PREFIX>.notification_inbox` новая, поэтому читает с самого раннего сохраненного события; события других типов считаются пропущенными.
|
||||
- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Единственный преобразователь сегодня - у синтетического уведомления: его фиксированный русский текст называет организацию-отправителя по ее текущему названию, которое `OrganizationNameForRecipient` читает с учетом текущего положения получателя. Кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета.
|
||||
- Область доступа. Кабинет кандидата требует подтвержденный аккаунт кандидата и показывает все организации, которые писали вызывающему. Кабинет одной организации требует аккаунт работодателя с подтвержденной почтой (иначе 403 `email_not_verified`, как у других операций организации) и активное членство любой роли в организации из пути. Членство блокируется `FOR SHARE` через `LockActiveMembership` в транзакции списка или отметки, как в чтениях карточки, поэтому отзыв не может зафиксироваться между проверкой и чтением и останавливает следующий же запрос. Получатель всегда берется из сессии; организация из пути только сужает строки, а один идентификатор в пути ничего не дает. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403. Нет членства, неизвестная организация, элемент другого аккаунта, элемент другой организации и неизвестный ID дают один и тот же 404 `not_found`. Маршруты организации не входят в список только для владельца в `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` называет их проверяемыми в собственной транзакции.
|
||||
- Чтение и отметка. `GET /api/v1/me/notifications` и `GET /api/v1/organizations/{org_id}/notifications` возвращают страницу от новых к старым с курсором, привязанным к аккаунту и кабинету; курсор другого аккаунта или кабинета - 400. `POST .../{notification_id}/read` сохраняет первое время прочтения и возвращает его при каждом повторе. Он не читает источник и не возвращает содержимое, поэтому элемент без содержимого тоже можно отметить. Все четыре - `Cache-Control: no-store`; отметка требует сессию, CSRF-токен и разрешенный Origin, а Idempotency-Key не нужен, потому что операция идемпотентна по эффекту. Новых кодов problem нет.
|
||||
- Frontend. `features/notifications` экспортирует `NotificationInbox` (кандидат или одна организация) и `OrganizationNotificationInbox` (выбор организации в параметре `organization_id` и сам inbox). Их используют страницы `/candidate/notifications` и `/employer/notifications` и пункт "Уведомления" в каждой оболочке. Список читается при каждом заходе и не сохраняется (`gcTime: 0`), ключ зависит от аккаунта и кабинета, а кэш сбрасывается при смене аккаунта или сессии и при отказе в доступе. Состояния: загрузка, пусто, ошибка с повтором, нет доступа, элемент без содержимого и "Показать еще". Состояние прочтения выражено словом, а не только стилем, отметка - нативная кнопка, и после успеха фокус переходит на заголовок элемента.
|
||||
- Компромисс: согласованность в конечном счете. Строку пишет обработчик после relay и Kafka, поэтому уведомление появляется через секунды после фиксации у источника, а не внутри его транзакции. Альтернатива - писать строку в транзакции источника через `UnitOfWork.NotificationInbox()` - дала бы мгновенность, но привязала бы каждый источник к inbox и лишила бы повторов и dead-letter, которые дает обработчик. Поэтому браузерный набор ждет появления элемента и затем повторяет доставку.
|
||||
- Тесты. Модульные: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` и `inbox_handler_test.go` (проверки кабинета, отзыв членства, запасной вариант преобразователя, идемпотентный обработчик, отклоненные события, событие `invitation.delivered` по тому же контракту), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go` и тесты функции в `frontend/src/features/notifications/`. Интеграционные: `TestNotificationInboxOverHTTP` и `TestSyntheticNotificationMigration*`. Браузерный: `frontend/e2e/notifications.spec.ts` в режиме регистрации ([TESTING.md](TESTING.md#браузерный-e2e-набор)).
|
||||
- Не реализовано: источник приглашений и его преобразователь содержимого, счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет.
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
Реализованы хранение, публикация и начальное заполнение при старте: миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
|
||||
@@ -430,7 +449,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Решение для учета попыток MVP: `MaxAttemptsPerWindow` считает корневые попытки кандидата по всем специализациям в скользящем окне `AttemptWindow`. Корректирующая попытка использует место своего корня, учебная его не расходует. Таймеры пересдачи и повышения остаются независимыми по специализациям.
|
||||
|
||||
Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются.
|
||||
Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals`, `support` и `matching` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются.
|
||||
|
||||
Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу.
|
||||
|
||||
@@ -455,6 +474,26 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Сроки identity в этой таблице - значения контракта identity ([api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Они берутся из версионированной продуктовой политики, а не из конфигурации: usecase регистрации, подтверждения и сессий будут читать их из действующей версии политики. Правила грейда в разделе [Оценивание и подтверждение грейда](#оценивание-и-подтверждение-грейда) используют те же значения оценивания.
|
||||
|
||||
Коэффициенты подбора (`matching`, схема 2, `domain.MatchingPolicy` в `policy_matching.go`, демонстрационная версия `domain.DemoProductPolicyV4()`): при наличии раздела все поля обязательны, единицы - базисные пункты, кроме двух весов навыков и размера когорты. Демонстрационные значения - проектные значения PRD 4.9 для проверки сценария, а не измеренные результаты; они публикуются явно (изолированный браузерный стенд публикует V4, а при старте по-прежнему создается только V1), и версия политики без раздела приводит к закрытому отказу поиска вместо ранжирования по умолчаниям.
|
||||
|
||||
| Поле | Демо-значение | Смысл |
|
||||
| --- | --- | --- |
|
||||
| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; сумма равна 1 |
|
||||
| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * свежесть * своевременность`; сумма равна 1 |
|
||||
| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | множитель `0.9 + 0.1 * x` для Fr и Rsp; нулевая нижняя граница отклоняется |
|
||||
| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` |
|
||||
| `neutral_unknown_bp` | 5000 | нейтральное 0.5 для неизвестного компонента (Dom, Sem, T, Fr, Rsp и Cov пустого запроса) |
|
||||
| `near_skill_threshold_bp` | 2500 | обязательный навык с меньшим вкладом переводит подтвержденный профиль в группу близких |
|
||||
| `required_skill_weight`, `desired_skill_weight` | 2, 1 | веса навыков в Cov |
|
||||
| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | коэффициенты уровней доверия доказательства 0-3 |
|
||||
| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | личный результат, роль в команде, командный результат без роли |
|
||||
| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | доказательство того же навыка, более узкого, более широкого |
|
||||
| `percentile_min_cohort` | 30 | наименьшая сопоставимая реальная когорта, при которой допустим перцентиль; поиск сравнивает с ним реальную когорту каждой возвращаемой категории |
|
||||
| `max_results_per_group` | 10 | записей каждой группы, которые может вернуть один поиск; ранжируется весь банк, обрезается только вывод |
|
||||
| `skill_taxonomy` | backend над docker, go, kafka, postgresql; devops_sre над docker | технологии внутри каждой специализации, определяющие, шире или уже доказательство запрошенного навыка |
|
||||
|
||||
Проверка держит каждую долю в пределах 0..1, суммы весов Fit и ранга равными 1, коэффициенты доверия и связи упорядоченными, а нижние границы выше нуля. В политику пока не вошли полураспад соревнований в 24 месяца и связь «только embedding» 0.3, так как данных о соревнованиях и embeddings нет.
|
||||
|
||||
Начальное заполнение: при старте, после миграций и при том же условии (`DATABASE_MIGRATE_ON_START` равен true и задан `DATABASE_URL`), bootstrap вызывает `Publisher.EnsureDemoProductPolicy`. Он проверяет только, есть ли у `product` хотя бы одна версия, и никогда не разбирает ее, поэтому сохраненная версия более новой или неизвестной структуры не может остановить запуск. Если семейство пусто, он публикует демонстрационную версию 1, действующую с момента публикации; иначе ничего не меняет и пишет в лог, что заполнение пропущено. Экземпляры, стартующие одновременно, состязаются за версию 1, и проигравший пропускает заполнение. Строка лога содержит только ключ, номер, вид и ID. Ошибка базы данных останавливает запуск. Заполнение не является вставкой данных в миграции, поэтому схема и значения политики меняются независимо.
|
||||
|
||||
Ссылка на версию (запланировано): таблицы, которые фиксируют решение по политике, например решения о грейде, снимки подбора и приглашения, получают `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` и хранят версию, использованную в момент решения. Существующее решение читает эту версию через `GetByID` и никогда не пересчитывается через `GetEffective`, ответ которого для заданного момента меняется, когда запланированную версию заменяет более новая. Удалить версию, на которую есть ссылка, нельзя ни через внешний ключ, ни через триггер, и новая версия не переписывает прошлые решения.
|
||||
@@ -540,7 +579,7 @@ backend/
|
||||
|
||||
За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
|
||||
|
||||
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
|
||||
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиками `notification_delivery` и `notification_inbox`, внутренний inbox уведомлений с операциями списка и прочтения, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
|
||||
|
||||
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
|
||||
|
||||
@@ -625,7 +664,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию пока никто не использует: ни ранжирование, ни подбор, ни перцентиль ее не читают.
|
||||
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
|
||||
|
||||
Код: миграция `backend/db/migrations/00035_create_skill_evidence.sql`, запросы `backend/db/queries/evidence.sql`, модель `backend/internal/domain/evidence.go`, порт `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), адаптер `adapter/secondary/postgres/evidence.go`, usecase `backend/internal/usecase/evidence/read.go`, обработчик `adapter/primary/http/v1/evidence.go` и операции `ListMyEvidence` и `GetOrganizationCandidateEvidence` ([api/README.md](../../api/README.md#доказательства-навыков)).
|
||||
|
||||
@@ -639,25 +678,32 @@ contact_grant относится к паре кандидат-компания
|
||||
- Область согласия C2. Публикация поля `categories` теперь отправляет организации подтвержденную категорию и один подтверждающий ее факт оценки (навык, грейд, уровень доверия, год и метки демонстрации). Кандидат видит тот же раздел в `GetMyCardPreview` (`evidence`); предпросмотр не применяет организацию и когорту, поэтому организация может получить меньше. Текст согласия C2 написан до появления этого раздела, и нужна ли для него новая версия, решают владелец продукта и юрист; это изменение тексты согласий не трогает.
|
||||
- Экспресс и провал. Чтение доказательств до и после экспресс-прогона дает один и тот же список, база отказывает факту, чей результат - экспресс-прогон или проваленная попытка, а экспресс не входит в категорию и потому в когорту карточки. Перцентиля и ранжирования в этом выпуске нет; когда они появятся, они обязаны читать тот же предикат.
|
||||
- Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом.
|
||||
- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в ранжировании и в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом.
|
||||
- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
|
||||
Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре.
|
||||
|
||||
Начальная baseline формула после фильтров:
|
||||
- Доступ до ранжирования. Поиск выполняется в одной транзакции. Роль владельца проверяется под блокировкой членства до чтения любых карточек. Затем `ListVisibleCards` проводит проверки чтения карточки: подтвержденный работодатель, затем `ListVisibleCandidateViewSources`, который выбирает из `candidate_effective_publications` (опубликовано и подкреплено неотозванным C2) и исключает кандидатов, скрывших читающую организацию, через `NOT EXISTS` по `candidate_hidden_organizations`; затем блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти. Поэтому список - это ровно те handle, которые в этот момент открывает `GetOrganizationCandidateCard`: карточка, скрытая правилами когорты, не ищется, отзыв C2, закрытая публикация или скрытая организация действуют со следующего запроса, ничего не кешируется и не хранится. Разрешенные доказательства читаются только организационно безопасным пакетным запросом `ListOrganizationVisibleEvidenceBatch` (один запрос на весь набор кандидатов с барьерами одиночного чтения: представление действующих публикаций, `NOT EXISTS` по скрытию, поле `categories`, видимые измерения) и только если запрос называет навыки. Блокировки - те же, что у чтения карточки, ничего больше не блокируется; записи поиска ограничены кандидатами, которых он возвращает.
|
||||
- Только владелец. Для MVP ищет действующий владелец организации. HTTP-граница отклоняет любую другую роль (`ownerCompanyOperations`), а usecase повторяет проверку роли под блокировкой членства, поэтому само членство ничего не дает. Полная матрица ролей и назначений - более поздняя работа и не должна расширять права по одному членству.
|
||||
- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением.
|
||||
- Одна запись на специализацию кандидата, из карточки, которую организации разрешено видеть. Специализация подтверждена, только когда карточка показывает ее категорию (`categories` опубликованы и не обобщены до пустоты); роль, помеченная в самооценке как неподтвержденная, - неподтвержденная запись; роль, помеченная подтвержденной, чью категорию карточка не показывает, записи не дает, потому что результат не может заявлять подтверждение, которое кандидат не опубликовал. Один и тот же handle может быть подтвержден по Backend и не подтвержден по сетям, и подтверждение Backend никогда не меняет запись по сетям. Статус записи следует специализации запроса: подтвержденная специализация потребности и фильтр `specialization` оба ограничивают поиск, а два разных значения не оставляют ничего. Потребность без подтвержденной специализации ищет по всем и возвращает каждую специализацию отдельно.
|
||||
- Фильтры, все до расчета. `confirmed_grade`, `confirmed_category` и `confirmation_status: confirmed` оставляют только подтвержденные записи; заявленный грейд их не удовлетворяет. `declared_grade` - отдельное заявление. `stack` требует каждый названный тег в карточке и одновременно считается обязательным навыком запроса. `conditions.work_formats` требует один общий формат, `conditions.salary_compatibility` - то же значение; неизвестное значение карточки условие не удовлетворяет. Одна неподтвержденная категория ничего не скрывает: без подтвержденного фильтра заявленные специализации выводятся.
|
||||
- Запрошенные навыки. Навыки для Cov берутся из подтвержденных обязательных (вес 2) и желательных (вес 1) навыков снимка потребности, теги фильтра `stack` считаются обязательными. Код считается один раз, сколько бы раз он ни повторялся. Навык без таксономического кода не имеет проверенного соответствия, ничему не соответствует и остается пробелом. Пустой запрос использует нейтральное Cov 0.5 вместо деления на ноль. Потребность читается по `requirements_version` (`GetVersion`); общая версия, изменившая только название, не является снимком требований и дает 404, а снимок прежней версии требований остается доступным и неизменным.
|
||||
- Доказательство навыка. Для каждого запрошенного навыка берется лучшее произведение коэффициентов доверия, атрибуции и связи среди разрешенных доказательств, а не их сумма. Доказательства - заявленные теги стека карточки (доверие 0, заявление) и для подтвержденной записи единственный факт оценки, подтверждающий ее категорию (доверие 1, личный). Связь точная для того же кода, широкая для специализации над технологией и узкая в обратную сторону, по `skill_taxonomy` версии политики (демо: `backend` над `docker`, `go`, `kafka`, `postgresql`; `devops_sre` над `docker`); версия без таксономии связывает только равные коды, так что версия политики полностью определяет результат. Таксономия - демонстрационное соответствие, а не измеренное. Онлайн-результат Backend стоит 0.6 * 1.0 * 0.4 = 0.24 для запрошенного Go, заявленный тег Go - 0.25; порог близости 0.25, поэтому кандидат, у которого единственное доказательство обязательной технологии - оценка Backend, для нее всегда в `near`, а одного заявленного тега достаточно для `main`. Это следствие значений PRD - вопрос владельцу продукта. Повтор тега или навыка ничего не добавляет.
|
||||
- Компоненты и группы. `Cov` - взвешенное среднее вкладов; `Dom = 0.5` (анонимная карточка не несет домен) и `Sem = 0.5` для каждой записи (ML нет), оба названы в `unknown_flags`; `T = 0.5` с null-перцентилем и признаком `cohort_below_30`, который поиск доказывает, а не декларирует: он считает кандидатов, имеющих каждую возвращаемую категорию из источника, отличного от синтетической демонстрации (`CountRealComparableCategories`, только числа), и сравнивает число с `percentile_min_cohort`; сегодня оно равно 0, так как каждая сохраненная категория - синтетическая демонстрация, которая никогда не смешивается с реальными результатами. Реальной когорте на уровне минимума понадобилась бы theta ее участников, которой нет в организационно безопасной проекции, поэтому поиск из-за этого никогда не падает: T остается нейтральным 0.5, перцентиль остается null, причина становится `percentile_not_computed` вместо `cohort_below_30`, и поиск пишет одно предупреждение на каждую такую категорию. Считаются только категории записей, прошедших фильтры; `V = 0`, так как данных о соревнованиях нет, - это ни штраф, ни неизвестность; `Fr = Rsp = 0.5` с признаками `no_freshness_history` и `no_response_history`. Подтвержденная запись с обязательным навыком ниже порога близости (0.25) попадает в `near`, иначе в `main`; неподтвержденная запись попадает в `unconfirmed` только с Fit и Coverage, считается отдельным путем и никогда не вычисляет theta, T, P, перцентиль или S. Отсутствие ФСП нигде не оценивается.
|
||||
- Порядок и округление. Баллы - целые числа в микроединицах (шесть знаков), доли - базисные пункты, произведения точные целые, поэтому одни и те же данные и политика дают один порядок на любой платформе. `main` и `near` сортируются по S, затем Cov (оба по убыванию), затем по внутреннему идентификатору кандидата по возрастанию (затем по коду специализации, который лишь разделяет две записи одного кандидата); `unconfirmed` - по Fit, затем Cov, затем по идентификатору. Идентификатор не покидает сервер, группы не объединяются общей шкалой.
|
||||
- Объяснение. Сводка и признаки строятся из тех же рассчитанных вкладов: для каждой группы навыков `supports` (каждый навык подкреплен измерением не ниже порога), `declared_only` (только заявленные теги), `partial` (смесь или измерения ниже порога) или `gap` (ничего), а также подтвержденная категория, заявленный грейд, совпадение форматов работы с потребностью или фильтром и совместимость зарплаты. Только ограниченные коды, никогда свободный текст, контакт, локация кандидата, значение или минимум зарплаты, проваленная попытка или причина скрытых данных. Неизвестный компонент виден только в `unknown_flags`.
|
||||
- Политика. Поиск читает действующую политику `product` на время приложения и ее раздел `matching`. Политика без раздела дает закрытый отказ с внутренней ошибкой (в перечислении ProblemCode нет кода для временно недоступной зависимости, и новый не добавляется); в логе ошибка говорит, что в действующей политике нет раздела подбора, и называет команду оператора `policy-publish`, при старте backend пишет предупреждение, пока раздела нет, а [DEPLOY.md](DEPLOY.md#политика-подбора-на-стенде) описывает команду. Ответ не называет версию политики, поиск не сохраняется.
|
||||
- Параллельность. Резервирования берут исключительную блокировку организации порта квоты компании. Проверка членства до них держит на той же строке только разделяемую блокировку, и два поиска одной организации взаимно блокировались бы при ее повышении, поэтому поиск сначала берет блокировку организации (`CompanyQuotaRepository.LockOrganization`, документированный порядок; это FOR NO KEY UPDATE, поэтому читатели встают в очередь друг за другом, но блокировка внешнего ключа при собственном скрытии кандидата, которое держит строку кандидата и затем требует строку организации, не блокируется, а само резервирование по-прежнему берет FOR UPDATE в той же транзакции), а оплата одной организации сериализуется. Изменение видимой когорты во время ее блокировки (`ErrConcurrentVisibilityChange`) повторяет весь поиск до трех раз, а записи неудачной попытки откатываются вместе с ней. Чтение карточки (`GetOrganizationCard`) и раздел доказательств (`AuthorizeCategoriesSection`) по той же причине берут эту исключительную блокировку первой, до любой разделяемой: до такого порядка два одновременных чтения карточек одной организации взаимно блокировались (SQLSTATE 40P01). `TestMatchSearchOverHTTP` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата.
|
||||
- Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу.
|
||||
- Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела.
|
||||
|
||||
score = 0.50 * skill_fit
|
||||
+ 0.40 * assessment_score
|
||||
+ 0.10 * fsp_evidence
|
||||
Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; семантическая близость и признак недоступности ML сверх нейтрального значения; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Приглашение из результата поиска тоже не реализовано, поэтому отзыв C2 после приглашения здесь не проверяется.
|
||||
|
||||
Все компоненты лежат в диапазоне 0..1. skill_fit - взвешенное покрытие подтвержденных навыков. assessment_score - результат по соответствующим разделам теста. fsp_evidence - небольшой бонус за релевантные проверенные достижения. При пустом наборе навыков применяется заранее определенное нейтральное значение, без деления на ноль. Равные значения сортируются стабильным tie-break по ID, а не по персональным признакам.
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. Это первая модель, а не оптимальное или измеренное ранжирование: планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант, семантический сигнал добавлять только после эксперимента и не считать его балл вероятностью успешного найма.
|
||||
|
||||
Нет истории ФСП - нулевой бонус, но кандидат остается в выдаче. Синтетические достижения помечаются и влияют только на демонстрационный набор. Результат включает score_components, reason_codes, подтверждающие факты и пробелы. Например, кандидат может иметь подтвержденный Middle и покрыть 4 из 5 навыков, но не пройдет фильтр, требующий все пять подтверждений.
|
||||
|
||||
Формула - исходная baseline, не оптимальная или измеренная модель. До финала планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант. Семантический сигнал добавляется только после эксперимента и не становится вероятностью успешного найма.
|
||||
|
||||
Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен.
|
||||
Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен. Это запланировано; реализованный поиск ничего не сохраняет.
|
||||
|
||||
## ML, документы и фоновые задания
|
||||
|
||||
@@ -953,7 +999,7 @@ Go экспортирует стандартные Go/process метрики и
|
||||
| Опрос, грейд, тест и категория, с. 1-3 | assessment, варианты задач, grade history | Не реализовано |
|
||||
| Сопоставимость тестов и защита от утечек, с. 1-2 | Семейства, blueprint, рубрики, ротация и пилот | Только план |
|
||||
| Не понижать грейд при провале, частота изменений, с. 2-3 | verified/claimed, retry правила, cooldown и eligibility | Только план |
|
||||
| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Не реализовано |
|
||||
| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Реализован базовый детерминированный поиск; ML, данных соревнований и снимков нет |
|
||||
| Уточнение поиска без потери старой выдачи, с. 4 | Версионные search_run и серверные снимки | Только план |
|
||||
| Приглашение без вакансии, с. 3 | Необязательный vacancy_id | Не реализовано |
|
||||
| Зарплата от-до в RUB, компания и связь, с. 4 | Обязательные границы зарплаты и явный формат периода/налогов | Не реализовано |
|
||||
|
||||
+15
-1
@@ -122,11 +122,12 @@ Relay создает отсутствующий топик и никогда н
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `<CONSUMER_GROUP_PREFIX>.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: зарегистрирован один продуктовый обработчик, `notification_delivery` (доставки писем), поэтому при `CONSUMER_ENABLED` и заданном `DATABASE_URL` backend запускает один обработчик в группе `<CONSUMER_GROUP_PREFIX>.notification_delivery` (по умолчанию `lincodex.notification_delivery`). Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены.
|
||||
Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `<CONSUMER_GROUP_PREFIX>.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: зарегистрированы два продуктовых обработчика, `notification_delivery` (доставки писем) и `notification_inbox` (внутренние уведомления), поэтому при `CONSUMER_ENABLED` и заданном `DATABASE_URL` backend запускает по одному обработчику в группах `<CONSUMER_GROUP_PREFIX>.notification_delivery` и `<CONSUMER_GROUP_PREFIX>.notification_inbox` (по умолчанию `lincodex.notification_delivery` и `lincodex.notification_inbox`). Новая группа начинает с самого раннего сохраненного события топика, поэтому первый запуск `notification_inbox` после развертывания читает сохраненные события и пропускает события других типов. Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены.
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
| --- | --- | --- |
|
||||
| `CONSUMER_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` обработчики не работают, и события ждут в Kafka, пока их хранит топик. |
|
||||
| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` или `false`. Включает синтетическое событие inbox `notification.synthetic_delivered`: обработчик `notification_inbox` его сохраняет, а inbox показывает его фиксированный текст. В боевой среде держите выключенным; браузерный стенд E2E включает его. При `false` такое событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого. CHECK в базе разрешает этот тип в любом случае. |
|
||||
| `CONSUMER_GROUP_PREFIX` | `lincodex` | Префикс ID каждой consumer group, до 128 латинских букв, цифр, точек, подчеркиваний или дефисов. Смена префикса создает новые группы, которые читают топик с самой ранней хранимой записи; маркеры дедупликации превращают уже примененные события в дубликаты. |
|
||||
| `CONSUMER_MAX_ATTEMPTS` | `5` | Попытки обработчика для одного события до перевода в dead letters, от 1 до 20. Сбои базы вне обработчика не считаются. Должно укладываться в бюджет ребалансировки ниже. |
|
||||
| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Пауза после первой неудачной попытки; удваивается после каждой следующей неудачи. |
|
||||
@@ -347,6 +348,19 @@ make -C backend assessment-category-attest ARGS='attest --specialization backend
|
||||
- Триггер аттестации принимает политику вида `demo` с `real_mode = demo_basic`. При присвоении категории база сверяет порог результата с `basic_pass_mark_bp` версии политики, закрепленной за попыткой, поэтому порог 9000 в принятой политике работает так же, как 8000. Попытки, по которым решение принято до аттестации, категории не получают; категорию присваивает только результат, принятый после нее.
|
||||
- Без любого из шагов результат с пройденным порогом сохраняется как `not_eligible`: кандидат видит оценку, категории нет. `demo_express` категорию не создает ни при каких настройках. `make -C backend assessment-category-attest-build` собирает `backend/bin/assessment-category-attest`.
|
||||
|
||||
## Политика подбора на стенде
|
||||
|
||||
Подбор ранжирует по разделу `matching` действующей политики `product` и без него отказывает закрыто: поиск отвечает 500 `internal`, в логе строка уровня error сообщает, что в действующей политике нет раздела подбора, и называет команду ниже, значения по умолчанию не используются. Стартовое заполнение публикует только первую демонстрационную версию, в которой такого раздела нет, поэтому при старте backend пишет предупреждение `the effective product policy has no matching section`, пока раздела нет. Опубликуйте его один раз на стенде как оператор:
|
||||
|
||||
```sh
|
||||
make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- Команда берет последнюю версию политики product, которая должна быть демонстрационной (kind `demo`), и публикует следующую версию как ее копию с добавленным демонстрационным разделом подбора. Остальные значения не меняются. Если в последней версии раздел уже есть, ничего не меняется и печатается `already present`; если за это время другая публикация заняла следующий номер версии, команда ничего не сохраняет и просит запустить ее снова; последняя калиброванная версия или семейство без версий отклоняются. `make -C backend policy-publish-build` собирает `backend/bin/policy-publish`.
|
||||
- Нужен только `DATABASE_URL`, dotenv-файл не читается, аргументы проверяются до подключения, печатается только номер версии. Автор версии - метка `operator:<handle>`: это метка аудита, а не аутентификация, границей оператора служит локальный доступ к базе.
|
||||
- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после.
|
||||
- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам.
|
||||
|
||||
## Отдельный ML Compose
|
||||
|
||||
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
||||
|
||||
@@ -53,7 +53,7 @@ Frontend зависимости выбираются из актуальных s
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий).
|
||||
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
|
||||
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
|
||||
|
||||
@@ -195,7 +195,7 @@ Backend, запущенный напрямую с `DATABASE_URL`, запуска
|
||||
|
||||
Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`.
|
||||
|
||||
Зарегистрирован один продуктовый обработчик: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`.
|
||||
Зарегистрированы два продуктовых обработчика: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)), а `notification.InboxHandler` сохраняет ссылки inbox (см. [Внутренние уведомления](#внутренние-уведомления)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`.
|
||||
|
||||
Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий).
|
||||
|
||||
@@ -205,6 +205,10 @@ Backend, запущенный напрямую с зарегистрирован
|
||||
|
||||
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
|
||||
### Внутренние уведомления
|
||||
|
||||
Чтобы положить уведомление в inbox получателя, добавьте событие через `unit.Outbox().Append` в собственной транзакции usecase. Тип должен быть разрешен (`domain.NotificationInboxSourceFor`), payload должен состоять ровно из `recipient_user_id` и `organization_id`, а агрегат - тот, который назван для типа (`invitation` для `invitation.delivered`). Никогда не кладите в payload текст или контакты. Обработчик `notification_inbox` сохраняет ссылку. Текст создается, когда получатель читает список, преобразователем, который вы регистрируете для своего типа источника в `notification.DefaultInboxSourceResolvers()`: `InboxSourceResolver` читает текущее состояние через `UnitOfWork`, применяет текущую видимость получателя и возвращает `ErrInboxContentUnavailable`, когда содержимое показывать нельзя. Для нового типа события добавьте пару в `domain.NotificationInboxSourceFor`, запись в `inboxProjections` в `usecase/notification/inbox_handler.go`, миграцию, расширяющую CHECK у `notification_inbox_events` (развернутую миграцию не правят), значение `NotificationKind` в контракт и отображение в `adapter/primary/http/v1/notifications.go`. Источнику письмо не нужно: почта запрашивается отдельно через `MailRequester`, а состояние inbox от нее не зависит. Путь можно проверить целиком синтетическим событием `notification.synthetic_delivered` (payload строит `notification.SyntheticNoticeEventPayload`); продуктового смысла у него нет, и обрабатывается он только при `NOTIFICATION_SYNTHETIC_ENABLED=true`. См. [Внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления).
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `<id>:<version>`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик.
|
||||
|
||||
+17
-1
@@ -174,7 +174,7 @@ Unit-тесты (`make -C backend test`) покрывают модель дос
|
||||
- `internal/usecase/notification/`: запрос сохраняет текст под ID агрегата события, а payload события содержит только `mail_request_id` и `kind`; некорректные запросы ничего не записывают; обработчик сохраняет одну доставку под ID запроса с исходным событием, адресом аккаунта, сформированным содержимым, настроенным аккаунтом провайдера и временем часов и удаляет запрос; то же событие повторно не находит запрос; существующая доставка под ID запроса принимается для того же получателя и вида и отклоняется в остальных случаях; сломанные события (другая версия схемы или агрегат, некорректный payload, данные после объекта, ID запроса, не равный ID агрегата, вид письма с токеном) и текст, который отклоняет шаблон, отклоняются без цитирования payload; исчезнувший запрос, исчезнувший аккаунт и неподтвержденный адрес пропускаются со строкой лога, которая называет только ID доставки и события; ошибки хранилища, включая аккаунт, удаленный между чтением и вставкой, остаются повторяемыми и сохраняют запрос; ни одна ошибка и строка лога не содержит адрес, тему или тело.
|
||||
- `internal/adapter/secondary/postgres/`: ошибки ограничений доставок и запросов писем переводятся в свои sentinel (`deliveries_content_immutable` и `delivery_attempts_immutable` - в `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` - в `ErrDeliveryProviderPinned`, внешние ключи на пользователей - в `ErrUserNotFound`), а любая другая ошибка PostgreSQL, например нарушение CHECK, сохраняет только SQLSTATE и имя ограничения без message и detail.
|
||||
- `internal/usecase/notification/mailtemplate/`: результат рендеринга переводится в сохраняемое содержимое с тем же видом, версией, частями и hash.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчик `notification_delivery` и отклоняет некорректную метку аккаунта.
|
||||
- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчики `notification_delivery` и `notification_inbox` и отклоняет некорректную метку аккаунта.
|
||||
|
||||
`TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи:
|
||||
|
||||
@@ -463,6 +463,22 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции.
|
||||
|
||||
## Тесты внутренних уведомлений
|
||||
|
||||
Модульные тесты (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
- `domain/notification_inbox_test.go`: запись принимает только разрешенные пары типа события и типа источника (синтетическое событие с организацией, `invitation.delivered` с приглашением), новая запись непрочитана, а `MarkRead` сохраняет первое время.
|
||||
- `usecase/notification/inbox_test.go` с памятью вместо репозитория и фальшивым unit of work: список вычисляет каждый элемент по текущему источнику и при отказе показывает его без содержимого; кабинет кандидата отказывает работодателю, кабинет организации отказывает кандидату, неизвестному или неподтвержденному аккаунту и отозванному членству (оно отвечает как неизвестная организация, и для списка, и для отметки); строка репозитория вне области получателя - внутренняя ошибка; владелец и рекрутер (и остальные роли) читают и отмечают только свои элементы организации, а членство блокируется на время чтения; работодатель с неподтвержденной почтой получает `ErrInboxEmailNotVerified`; отметка сохраняет первое время и не может задеть элемент другого получателя; ссылки содержимого отклоняют внешний URL, URL без схемы, query, fragment, обратную косую черту, escape, сегмент с точками и длинный путь; синтетический преобразователь следует положению получателя, а тип источника без преобразователя недоступен.
|
||||
- `usecase/notification/inbox_handler_test.go`: повторное событие дает одну строку; неверная версия схемы, агрегат, неизвестное поле, отсутствие организации, payload не объектом, лишние данные и ID события, повторенный с другими метаданными, отклоняются окончательно; удаленный получатель пропускается; сбой хранилища остается повторяемым; неподтвержденный адрес все равно получает строку (inbox не читает состояние почты); получатель, исчезнувший между проверкой и вставкой, повторяется и затем пропускается, а не отклоняется; синтетическое событие игнорируется при выключенном флаге; событие `invitation.delivered` с тем же контрактом payload сохраняет приглашение как источник.
|
||||
- `adapter/primary/http/v1/notifications_test.go` и `adapter/primary/http/notification_contract_test.go`: отображение содержимого и запасного варианта, курсор, привязанный к аккаунту и кабинету (чужой или перепутанный курсор дает 400), отказы, соглашения четырех операций и закрытые схемы. `bootstrap/consumers_test.go` фиксирует два зарегистрированных обработчика.
|
||||
- Frontend: `features/notifications/` проверяет проверку ссылки, один повтор отметки после 403 (и отсутствие повтора после 401, 404 и 500), подписи, формулировку элемента без содержимого, ключи запросов и их удаление по аккаунту и отрисованный список (состояние прочтения словом, кнопка отметки только у непрочитанных, нет небезопасной ссылки, пустое состояние, отказ для чужого кабинета).
|
||||
|
||||
Интеграционные тесты (`make -C backend test-int`; PostgreSQL и Redis, без Kafka): `TestNotificationInboxOverHTTP` пишет синтетическое событие через настоящий писатель outbox и доставляет его через хранилище обработчика с настоящим обработчиком. Одно событие, доставленное дважды и еще раз переименованным обработчиком, дает одну строку. Затем на том же роутере проверяются список кандидата, чужой кандидат, чужой кабинет, отсутствие CSRF-токена и чужой Origin, отметка и ее повтор (первое время сохраняется), сохранение состояния прочтения, потеря содержимого, когда кандидат скрывает организацию, страницы с курсором, привязанным к аккаунту, кабинет работодателя только с его элементами организации, рекрутер со своими элементами, не участник, элемент другой организации и 404 для списка и отметки после отзыва членства. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` и `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` проверяют список разрешенных значений миграции 00036, отказ отката при синтетической строке и восстановленное ограничение. `TestNotificationInboxStoreNamesTheMissingReference` проверяет, что отсутствующий получатель и отсутствующая организация различаются. `TestPostgresMigrations` покрывает подъем и откат до нуля.
|
||||
|
||||
Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое.
|
||||
|
||||
Чего эти тесты не показывают: настоящее приглашение (пока ни одно не создает событие), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет).
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
Reference in new issue
Block a user