feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
+4
-3
@@ -71,13 +71,14 @@ PASSWORD_HASH_CONCURRENCY=1
|
||||
APP_SUBNET=172.29.79.0/24
|
||||
APP_FRONTEND_IP=172.29.79.10
|
||||
# Registration and email confirmation. IDENTITY_KEY_SECRET is required. It
|
||||
# keys idempotency records, rate-limit counters, and session CSRF tokens across
|
||||
# restarts and instances.
|
||||
# keys idempotency records, rate-limit counters, session CSRF tokens, and
|
||||
# organization-scoped candidate aliases across restarts and instances.
|
||||
# Use at least 32 bytes. There is no usable example value: leave it empty here
|
||||
# and generate one for every deployment (Compose refuses an empty value):
|
||||
# openssl rand -base64 48
|
||||
# A value that starts with replace-this is refused. Without it the backend refuses to start, unless a development stand sets
|
||||
# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process).
|
||||
# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process; candidate
|
||||
# aliases also change after restart).
|
||||
IDENTITY_KEY_SECRET=
|
||||
# Registration and every verification resend count toward both per-address limits.
|
||||
VERIFICATION_MAIL_MIN_INTERVAL=1m
|
||||
|
||||
@@ -1488,10 +1488,7 @@ AssessmentItemNotCurrent:
|
||||
detail: The resource is in a state that does not allow this operation.
|
||||
trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f
|
||||
AssessmentFinalizeNotReady:
|
||||
summary: Premature finalize; the problem does not list the unfinished parts
|
||||
description: >-
|
||||
Problem has no extension fields. The client reads what remains from the
|
||||
attempt: `state`, `progress`, `current_item`, and `practices`.
|
||||
summary: Premature finalize; the problem lists unanswered frozen items
|
||||
value:
|
||||
type: urn:lincodex:problem:state_conflict
|
||||
title: Resource state conflict
|
||||
@@ -1499,6 +1496,9 @@ AssessmentFinalizeNotReady:
|
||||
code: state_conflict
|
||||
detail: The resource is in a state that does not allow this operation.
|
||||
trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e
|
||||
pending_item_ids:
|
||||
- 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
|
||||
- 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d
|
||||
AssessmentAttemptNotAvailable:
|
||||
summary: No attempt can start for the category now
|
||||
value:
|
||||
@@ -2484,7 +2484,7 @@ InvitationCreateFromNeed:
|
||||
summary: A draft for a candidate from the search results of a need
|
||||
description: "Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided."
|
||||
value:
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2625,7 +2625,7 @@ OrganizationInvitationDraft:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2688,7 +2688,7 @@ OrganizationInvitationDraftUpdated:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2752,7 +2752,7 @@ OrganizationInvitationDelivered:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2816,7 +2816,7 @@ OrganizationInvitationSalaryRaised:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2880,7 +2880,7 @@ OrganizationInvitationAccepted:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -2945,7 +2945,7 @@ OrganizationInvitationWithdrawn:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -3010,7 +3010,7 @@ OrganizationInvitationListPage:
|
||||
value:
|
||||
items:
|
||||
- id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -3033,7 +3033,7 @@ OrganizationInvitationListPage:
|
||||
created_at: "2026-10-06T09:00:00Z"
|
||||
updated_at: "2026-10-06T15:00:00Z"
|
||||
- id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80
|
||||
candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb
|
||||
candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
|
||||
need: null
|
||||
state: declined
|
||||
expiry_reason: null
|
||||
@@ -4373,17 +4373,35 @@ PublishedCardPreview:
|
||||
- categories
|
||||
- stack
|
||||
card:
|
||||
pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
categories:
|
||||
- specialization: backend
|
||||
grade: middle
|
||||
strength: standard
|
||||
stack:
|
||||
- PostgreSQL
|
||||
- Kafka
|
||||
experience_months: null
|
||||
soft_skills: null
|
||||
location: null
|
||||
relocation: null
|
||||
- postgresql
|
||||
- kafka
|
||||
self_assessment: null
|
||||
experience_band: "1_3"
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
generated_at: "2026-10-06T09:30:00Z"
|
||||
OrganizationAnonymousCandidateCard:
|
||||
summary: An anonymous card currently visible to one organization
|
||||
description: The alias is scoped to the reading organization; no contact values are included.
|
||||
value:
|
||||
pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
categories:
|
||||
- specialization: backend
|
||||
grade: middle
|
||||
strength: standard
|
||||
stack:
|
||||
- postgresql
|
||||
- kafka
|
||||
self_assessment: null
|
||||
experience_band: "1_3"
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
ClosedCardPreview:
|
||||
summary: The preview of a closed profile
|
||||
value:
|
||||
|
||||
@@ -82,6 +82,19 @@ OrganizationId:
|
||||
type: string
|
||||
format: uuid
|
||||
example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
CandidateHandle:
|
||||
name: candidate_handle
|
||||
in: path
|
||||
required: true
|
||||
description: >-
|
||||
Organization-scoped opaque candidate alias issued by the current visible
|
||||
card projection. The server resolves it only for the organization in the
|
||||
path and rechecks current membership, publication consent, and hiding on
|
||||
every read. Unknown, hidden, unpublished, and suppressed candidates all
|
||||
answer the same 404.
|
||||
schema:
|
||||
$ref: ./schemas.yml#/CandidateHandle
|
||||
example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
NeedId:
|
||||
name: need_id
|
||||
in: path
|
||||
|
||||
@@ -316,15 +316,14 @@ AssessmentFinalizeConflict:
|
||||
The attempt state does not allow finalize at the current version, code
|
||||
state_conflict: items or the main practice are unfinished, a practice
|
||||
verdict is pending, or the attempt ended as expired or insufficient_bank.
|
||||
The problem does not list the unfinished parts, because Problem allows
|
||||
no extension fields; the attempt shows them in `state`, `progress`,
|
||||
`current_item`, and `practices`. Or a request with the same
|
||||
Idempotency-Key is still running, code idempotency_in_progress. Nothing
|
||||
was changed in either case.
|
||||
If required questions are unfinished, the response includes their frozen
|
||||
IDs in `pending_item_ids`; other state conflicts omit that field. Or a
|
||||
request with the same Idempotency-Key is still running, code
|
||||
idempotency_in_progress. Nothing was changed in either case.
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: ./schemas.yml#/Problem
|
||||
$ref: ./schemas.yml#/AssessmentFinalizeConflictProblem
|
||||
examples:
|
||||
state_conflict:
|
||||
$ref: ./examples.yml#/AssessmentFinalizeNotReady
|
||||
|
||||
+277
-52
@@ -25,12 +25,12 @@ PageInfo:
|
||||
description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.
|
||||
CandidateHandle:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9_-]+$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: ^cv1_[A-Za-z0-9_-]{43}$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
- cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
AssessmentMode:
|
||||
type: string
|
||||
description: 'Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence.
|
||||
@@ -862,6 +862,7 @@ NumberAnswer:
|
||||
number:
|
||||
type: number
|
||||
format: double
|
||||
x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber
|
||||
StringAnswer:
|
||||
type: object
|
||||
description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.
|
||||
@@ -1213,6 +1214,58 @@ AssessmentResult:
|
||||
root: '#/AssessmentQualifiedResult'
|
||||
corrective: '#/AssessmentCorrectiveResult'
|
||||
demo_express: '#/AssessmentExpressResult'
|
||||
AssessmentFinalizeConflictProblem:
|
||||
type: object
|
||||
description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- title
|
||||
- status
|
||||
- code
|
||||
properties:
|
||||
type:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 256
|
||||
title:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 200
|
||||
status:
|
||||
type: integer
|
||||
format: int32
|
||||
const: 409
|
||||
code:
|
||||
type: string
|
||||
enum:
|
||||
- state_conflict
|
||||
- idempotency_in_progress
|
||||
detail:
|
||||
type: string
|
||||
maxLength: 1000
|
||||
instance:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 2048
|
||||
trace_id:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9._-]+$
|
||||
errors:
|
||||
type: array
|
||||
maxItems: 100
|
||||
items:
|
||||
$ref: '#/ProblemFieldError'
|
||||
pending_item_ids:
|
||||
type: array
|
||||
maxItems: 220
|
||||
uniqueItems: true
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items.
|
||||
AssessmentRealResultCommon:
|
||||
type: object
|
||||
description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.
|
||||
@@ -1594,6 +1647,120 @@ AssessmentAvailability:
|
||||
description: Questionnaire specializations in questionnaire order.
|
||||
items:
|
||||
$ref: '#/AssessmentSpecializationAvailability'
|
||||
AssessmentSignalEvent:
|
||||
description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.
|
||||
oneOf:
|
||||
- $ref: '#/AssessmentFocusLossSignal'
|
||||
- $ref: '#/AssessmentClipboardSignal'
|
||||
- $ref: '#/AssessmentFullscreenExitSignal'
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
focus_loss: '#/AssessmentFocusLossSignal'
|
||||
copy: '#/AssessmentClipboardSignal'
|
||||
paste: '#/AssessmentClipboardSignal'
|
||||
cut: '#/AssessmentClipboardSignal'
|
||||
fullscreen_exit: '#/AssessmentFullscreenExitSignal'
|
||||
AssessmentFocusLossSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- duration_ms
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- focus_loss
|
||||
item_instance_id:
|
||||
$ref: '#/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/Timestamp'
|
||||
duration_ms:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 1
|
||||
maximum: 259200000
|
||||
description: Client-measured duration away from the assessment tab or window, in milliseconds.
|
||||
AssessmentClipboardSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- size_bytes
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- copy
|
||||
- paste
|
||||
- cut
|
||||
item_instance_id:
|
||||
$ref: '#/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/Timestamp'
|
||||
size_bytes:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 2147483647
|
||||
description: Byte count only. Clipboard or selection contents are not transmitted or retained.
|
||||
AssessmentFullscreenExitSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- fullscreen_exit
|
||||
item_instance_id:
|
||||
$ref: '#/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/Timestamp'
|
||||
AssessmentSignalBatch:
|
||||
type: object
|
||||
description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- events
|
||||
properties:
|
||||
events:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 50
|
||||
items:
|
||||
$ref: '#/AssessmentSignalEvent'
|
||||
AssessmentSignalReceipt:
|
||||
type: object
|
||||
description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- status
|
||||
- accepted_events
|
||||
- received_at
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum:
|
||||
- accepted
|
||||
- saturated
|
||||
description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.'
|
||||
accepted_events:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 50
|
||||
description: Number of events stored from this batch; zero when saturated.
|
||||
received_at:
|
||||
$ref: '#/Timestamp'
|
||||
ProfileVersion:
|
||||
type: integer
|
||||
format: int64
|
||||
@@ -5413,17 +5580,19 @@ CardField:
|
||||
description: 'A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
|
||||
- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
|
||||
- stack: the technology tags of the profile.
|
||||
- self_assessment: the candidate''s declared specialization and grade, separate from confirmed categories.
|
||||
|
||||
- experience: the total months of work experience, without employers, periods, or descriptions.
|
||||
- stack: only recognized technology codes from the server''s closed taxonomy.
|
||||
|
||||
- soft_skills: the soft skills of the profile.
|
||||
- experience: a coarse total-experience band, without employers, periods, or descriptions.
|
||||
|
||||
- location: the city or region of the profile.
|
||||
- work_formats: explicitly selected work formats from the private questionnaire.
|
||||
|
||||
- relocation: whether the candidate is ready to relocate.
|
||||
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
|
||||
|
||||
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
|
||||
|
||||
|
||||
Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
||||
@@ -5432,15 +5601,18 @@ CardField:
|
||||
Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.'
|
||||
enum:
|
||||
- categories
|
||||
- salary_compatibility
|
||||
- self_assessment
|
||||
- stack
|
||||
- experience
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- work_formats
|
||||
CardFieldSet:
|
||||
type: array
|
||||
minItems: 0
|
||||
maxItems: 6
|
||||
maxItems: 9
|
||||
uniqueItems: true
|
||||
description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.
|
||||
items:
|
||||
@@ -5644,24 +5816,78 @@ CardCategory:
|
||||
required:
|
||||
- specialization
|
||||
- grade
|
||||
- strength
|
||||
properties:
|
||||
specialization:
|
||||
$ref: '#/SpecializationCode'
|
||||
grade:
|
||||
$ref: '#/GradeCode'
|
||||
AnonymousCardContent:
|
||||
strength:
|
||||
type: string
|
||||
enum:
|
||||
- standard
|
||||
- strong
|
||||
description: Coarse strength of the authoritative confirmation.
|
||||
CardSelfAssessment:
|
||||
type: object
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are
|
||||
defined by the search contract, which reuses this content.
|
||||
description: Candidate-declared specialization and optional grade. This is never an assessment result.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- specialization
|
||||
- confirmation_status
|
||||
properties:
|
||||
specialization:
|
||||
$ref: '#/SpecializationCode'
|
||||
confirmation_status:
|
||||
type: string
|
||||
enum:
|
||||
- confirmed
|
||||
- unconfirmed
|
||||
declared_grade:
|
||||
oneOf:
|
||||
- $ref: '#/GradeCode'
|
||||
- type: 'null'
|
||||
CandidateExperienceBand:
|
||||
type: string
|
||||
description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned.
|
||||
enum:
|
||||
- '0_1'
|
||||
- '1_3'
|
||||
- '3_6'
|
||||
- 6_plus
|
||||
- '0_3'
|
||||
- 3_plus
|
||||
CandidateWorkFormat:
|
||||
type: string
|
||||
enum:
|
||||
- remote
|
||||
- office
|
||||
- hybrid
|
||||
CandidateSalaryCompatibility:
|
||||
type: string
|
||||
description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card.
|
||||
enum:
|
||||
- compatible
|
||||
- not_compatible
|
||||
AnonymousCardContent:
|
||||
type: object
|
||||
description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- pseudonym
|
||||
- categories
|
||||
- stack
|
||||
- experience_months
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- self_assessment
|
||||
- experience_band
|
||||
- work_formats
|
||||
- salary_compatibility
|
||||
properties:
|
||||
pseudonym:
|
||||
type: string
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: ^cv1_[A-Za-z0-9_-]{43}$
|
||||
description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations.
|
||||
categories:
|
||||
type:
|
||||
- array
|
||||
@@ -5674,45 +5900,44 @@ AnonymousCardContent:
|
||||
type:
|
||||
- array
|
||||
- 'null'
|
||||
maxItems: 30
|
||||
description: Technology tags of the candidate, or null.
|
||||
maxItems: 4
|
||||
description: Recognized confirmed technology codes only, or null.
|
||||
items:
|
||||
$ref: '#/StackTag'
|
||||
experience_months:
|
||||
type:
|
||||
- integer
|
||||
- 'null'
|
||||
minimum: 0
|
||||
maximum: 1200
|
||||
description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null.
|
||||
soft_skills:
|
||||
type: string
|
||||
enum:
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
self_assessment:
|
||||
type:
|
||||
- array
|
||||
- 'null'
|
||||
maxItems: 10
|
||||
description: Soft skills of the candidate, or null.
|
||||
maxItems: 9
|
||||
description: Candidate-declared specialization and grade, separate from categories.
|
||||
items:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 50
|
||||
pattern: ^\S(?:.*\S)?$
|
||||
description: Plain text; clients show it as text, never as HTML.
|
||||
location:
|
||||
$ref: '#/CardSelfAssessment'
|
||||
experience_band:
|
||||
oneOf:
|
||||
- $ref: '#/CandidateExperienceBand'
|
||||
- type: 'null'
|
||||
description: Coarse total work-experience bucket, or null.
|
||||
work_formats:
|
||||
type:
|
||||
- string
|
||||
- array
|
||||
- 'null'
|
||||
minLength: 1
|
||||
maxLength: 100
|
||||
pattern: ^\S(?:.*\S)?$
|
||||
description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.
|
||||
relocation:
|
||||
type:
|
||||
- boolean
|
||||
- 'null'
|
||||
description: Whether the candidate is ready to relocate, or null.
|
||||
maxItems: 3
|
||||
description: Explicitly opted-in work formats, or null.
|
||||
items:
|
||||
$ref: '#/CandidateWorkFormat'
|
||||
salary_compatibility:
|
||||
oneOf:
|
||||
- $ref: '#/CandidateSalaryCompatibility'
|
||||
- type: 'null'
|
||||
description: Nullable compatibility result with no salary values.
|
||||
CardPreview:
|
||||
type: object
|
||||
description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.'
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
@@ -5813,7 +6038,7 @@ CardAccessKind:
|
||||
description: 'How an organization reached the candidate.
|
||||
|
||||
|
||||
- card_viewed: an organization read the anonymous card in a search result.
|
||||
- card_viewed: an organization read the permitted anonymous card.
|
||||
|
||||
- contact_read: an organization read the contacts through the contact grant of an accepted invitation.'
|
||||
enum:
|
||||
@@ -5821,7 +6046,7 @@ CardAccessKind:
|
||||
- contact_read
|
||||
CardAccess:
|
||||
type: object
|
||||
description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization.
|
||||
description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
@@ -6612,7 +6837,7 @@ SupportCase:
|
||||
- 'null'
|
||||
format: int32
|
||||
minimum: 1
|
||||
description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.'
|
||||
description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`.
|
||||
response_target:
|
||||
$ref: '#/SupportResponseTarget'
|
||||
decision:
|
||||
|
||||
@@ -947,6 +947,7 @@ schemas:
|
||||
number:
|
||||
type: number
|
||||
format: double
|
||||
x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber
|
||||
StringAnswer:
|
||||
type: object
|
||||
description: >-
|
||||
@@ -1329,6 +1330,64 @@ schemas:
|
||||
root: "#/schemas/AssessmentQualifiedResult"
|
||||
corrective: "#/schemas/AssessmentCorrectiveResult"
|
||||
demo_express: "#/schemas/AssessmentExpressResult"
|
||||
AssessmentFinalizeConflictProblem:
|
||||
type: object
|
||||
description: >-
|
||||
A finalize state conflict. `pending_item_ids` is present only when the
|
||||
attempt still has required questions without answers; it is omitted for
|
||||
other state conflicts and idempotency conflicts.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- title
|
||||
- status
|
||||
- code
|
||||
properties:
|
||||
type:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 256
|
||||
title:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 200
|
||||
status:
|
||||
type: integer
|
||||
format: int32
|
||||
const: 409
|
||||
code:
|
||||
type: string
|
||||
enum:
|
||||
- state_conflict
|
||||
- idempotency_in_progress
|
||||
detail:
|
||||
type: string
|
||||
maxLength: 1000
|
||||
instance:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 2048
|
||||
trace_id:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: "^[A-Za-z0-9._-]+$"
|
||||
errors:
|
||||
type: array
|
||||
maxItems: 100
|
||||
items:
|
||||
$ref: "./problem_schemas.yml#/schemas/ProblemFieldError"
|
||||
pending_item_ids:
|
||||
type: array
|
||||
maxItems: 220
|
||||
uniqueItems: true
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
description: >-
|
||||
Frozen item IDs still unanswered when finalize is rejected for an
|
||||
incomplete attempt. Omitted when the conflict is unrelated to
|
||||
unanswered items.
|
||||
AssessmentRealResultCommon:
|
||||
type: object
|
||||
description: >-
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
schemas:
|
||||
AssessmentSignalEvent:
|
||||
description: >-
|
||||
One client-reported event bound to an item instance of the attempt. The
|
||||
timestamp is untrusted input and is used only as event metadata; server
|
||||
receipt time is authoritative for limits and retention.
|
||||
oneOf:
|
||||
- $ref: "#/schemas/AssessmentFocusLossSignal"
|
||||
- $ref: "#/schemas/AssessmentClipboardSignal"
|
||||
- $ref: "#/schemas/AssessmentFullscreenExitSignal"
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
focus_loss: "#/schemas/AssessmentFocusLossSignal"
|
||||
copy: "#/schemas/AssessmentClipboardSignal"
|
||||
paste: "#/schemas/AssessmentClipboardSignal"
|
||||
cut: "#/schemas/AssessmentClipboardSignal"
|
||||
fullscreen_exit: "#/schemas/AssessmentFullscreenExitSignal"
|
||||
AssessmentFocusLossSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- duration_ms
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- focus_loss
|
||||
item_instance_id:
|
||||
$ref: "#/schemas/AssessmentItemId"
|
||||
occurred_at:
|
||||
$ref: "#/schemas/Timestamp"
|
||||
duration_ms:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 1
|
||||
maximum: 259200000
|
||||
description: Client-measured duration away from the assessment tab or window, in milliseconds.
|
||||
AssessmentClipboardSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- size_bytes
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- copy
|
||||
- paste
|
||||
- cut
|
||||
item_instance_id:
|
||||
$ref: "#/schemas/AssessmentItemId"
|
||||
occurred_at:
|
||||
$ref: "#/schemas/Timestamp"
|
||||
size_bytes:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 2147483647
|
||||
description: Byte count only. Clipboard or selection contents are not transmitted or retained.
|
||||
AssessmentFullscreenExitSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- fullscreen_exit
|
||||
item_instance_id:
|
||||
$ref: "#/schemas/AssessmentItemId"
|
||||
occurred_at:
|
||||
$ref: "#/schemas/Timestamp"
|
||||
AssessmentSignalBatch:
|
||||
type: object
|
||||
description: >-
|
||||
A bounded batch of client event metadata. The raw request body is limited
|
||||
to 32 KiB before decoding and the batch contains at most 50 events.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- events
|
||||
properties:
|
||||
events:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 50
|
||||
items:
|
||||
$ref: "#/schemas/AssessmentSignalEvent"
|
||||
AssessmentSignalReceipt:
|
||||
type: object
|
||||
description: >-
|
||||
Receipt for the submitted batch. It contains no signal details, score,
|
||||
review decision, threshold, or result band.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- status
|
||||
- accepted_events
|
||||
- received_at
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum:
|
||||
- accepted
|
||||
- saturated
|
||||
description: >-
|
||||
`saturated` means no event from this batch was stored because the
|
||||
attempt's bounded evidence storage is full.
|
||||
accepted_events:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 50
|
||||
description: Number of events stored from this batch; zero when saturated.
|
||||
received_at:
|
||||
$ref: "#/schemas/Timestamp"
|
||||
@@ -34,16 +34,16 @@ schemas:
|
||||
must not parse, build, or store it beyond the current listing.
|
||||
CandidateHandle:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: "^[A-Za-z0-9_-]+$"
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: '^cv1_[A-Za-z0-9_-]{43}$'
|
||||
description: >-
|
||||
Opaque reference to a candidate as one organization sees it, taken
|
||||
from a search result card of that organization. It is not the
|
||||
candidate's account or profile identifier, it never contains an email
|
||||
address or a phone number, and it means nothing to another
|
||||
organization. The server resolves it only for the organization in the
|
||||
path. Clients never parse it. It is shared by the invitations of
|
||||
FR12 and the search results of FR11, which issue it.
|
||||
from the organization-scoped anonymous card. It is a versioned HMAC
|
||||
alias, not a candidate account or profile identifier; it contains no
|
||||
contact information and is meaningless to another organization. The
|
||||
server resolves it only against the current visible cohort of the
|
||||
organization in the path. Clients never parse or construct it. It is
|
||||
shared by the candidate-card read and invitations.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
- cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
@@ -28,27 +28,31 @@ schemas:
|
||||
description: |-
|
||||
A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.
|
||||
- stack: the technology tags of the profile.
|
||||
- experience: the total months of work experience, without employers, periods, or descriptions.
|
||||
- soft_skills: the soft skills of the profile.
|
||||
- location: the city or region of the profile.
|
||||
- relocation: whether the candidate is ready to relocate.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
- self_assessment: the candidate's declared specialization and grade, separate from confirmed categories.
|
||||
- stack: only recognized technology codes from the server's closed taxonomy.
|
||||
- experience: a coarse total-experience band, without employers, periods, or descriptions.
|
||||
- work_formats: explicitly selected work formats from the private questionnaire.
|
||||
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
|
||||
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
|
||||
|
||||
Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
||||
|
||||
Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.
|
||||
enum:
|
||||
- categories
|
||||
- salary_compatibility
|
||||
- self_assessment
|
||||
- stack
|
||||
- experience
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- work_formats
|
||||
CardFieldSet:
|
||||
type: array
|
||||
minItems: 0
|
||||
maxItems: 6
|
||||
maxItems: 9
|
||||
uniqueItems: true
|
||||
description: >-
|
||||
Distinct card fields. The server stores them in ascending order of
|
||||
@@ -316,21 +320,70 @@ schemas:
|
||||
required:
|
||||
- specialization
|
||||
- grade
|
||||
- strength
|
||||
properties:
|
||||
specialization:
|
||||
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
|
||||
grade:
|
||||
$ref: "./catalog_schemas.yml#/schemas/GradeCode"
|
||||
strength:
|
||||
type: string
|
||||
enum:
|
||||
- standard
|
||||
- strong
|
||||
description: Coarse strength of the authoritative confirmation.
|
||||
CardSelfAssessment:
|
||||
type: object
|
||||
description: Candidate-declared specialization and optional grade. This is never an assessment result.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- specialization
|
||||
- confirmation_status
|
||||
properties:
|
||||
specialization:
|
||||
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
|
||||
confirmation_status:
|
||||
type: string
|
||||
enum:
|
||||
- confirmed
|
||||
- unconfirmed
|
||||
declared_grade:
|
||||
oneOf:
|
||||
- $ref: "./catalog_schemas.yml#/schemas/GradeCode"
|
||||
- type: "null"
|
||||
CandidateExperienceBand:
|
||||
type: string
|
||||
description: >-
|
||||
Coarse total experience bucket. Rare combinations may be generalized to
|
||||
0_3 or 3_plus before they are returned.
|
||||
enum:
|
||||
- "0_1"
|
||||
- "1_3"
|
||||
- "3_6"
|
||||
- "6_plus"
|
||||
- "0_3"
|
||||
- "3_plus"
|
||||
CandidateWorkFormat:
|
||||
type: string
|
||||
enum:
|
||||
- remote
|
||||
- office
|
||||
- hybrid
|
||||
CandidateSalaryCompatibility:
|
||||
type: string
|
||||
description: >-
|
||||
A coarse compatibility result only. No salary amount, minimum, range,
|
||||
or threshold is part of the anonymous card.
|
||||
enum:
|
||||
- compatible
|
||||
- not_compatible
|
||||
AnonymousCardContent:
|
||||
type: object
|
||||
description: >-
|
||||
The anonymous candidate card as an organization reads it. Only values
|
||||
that the candidate confirmed reach it; an unconfirmed suggestion and an
|
||||
unknown value never do. A free text value (a stack tag, a soft skill, the
|
||||
location) that looks like a contact (an email address, a phone number, a
|
||||
URL or domain, a Telegram link, an @handle) is dropped by the builder
|
||||
and never published. It carries
|
||||
no name, contact, resume text, employer, salary figure, account or
|
||||
The anonymous candidate card as an organization reads it. Only explicitly
|
||||
published values reach it; unconfirmed stack suggestions and unknown
|
||||
values never do. Stack output uses a closed taxonomy. It carries no name,
|
||||
contact, resume text, employer, salary figure, account or
|
||||
profile identifier, and no schema of the private profile or of a
|
||||
contact disclosure is reachable from it; a contact reaches an
|
||||
organization only through the contact grant of an accepted
|
||||
@@ -343,13 +396,22 @@ schemas:
|
||||
content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- pseudonym
|
||||
- categories
|
||||
- stack
|
||||
- experience_months
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- self_assessment
|
||||
- experience_band
|
||||
- work_formats
|
||||
- salary_compatibility
|
||||
properties:
|
||||
pseudonym:
|
||||
type: string
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: '^cv1_[A-Za-z0-9_-]{43}$'
|
||||
description: >-
|
||||
Stable opaque alias scoped to the reading organization. It is not an
|
||||
account or profile identifier and changes across organizations.
|
||||
categories:
|
||||
type:
|
||||
- array
|
||||
@@ -362,54 +424,51 @@ schemas:
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
maxItems: 30
|
||||
description: Technology tags of the candidate, or null.
|
||||
maxItems: 4
|
||||
description: Recognized confirmed technology codes only, or null.
|
||||
items:
|
||||
$ref: "./questionnaire_schemas.yml#/schemas/StackTag"
|
||||
experience_months:
|
||||
type:
|
||||
- integer
|
||||
- "null"
|
||||
minimum: 0
|
||||
maximum: 1200
|
||||
description: >-
|
||||
Total months of work experience, summed by the server without the
|
||||
employers, periods, or descriptions, or null.
|
||||
soft_skills:
|
||||
type: string
|
||||
enum:
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
self_assessment:
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
maxItems: 10
|
||||
description: Soft skills of the candidate, or null.
|
||||
maxItems: 9
|
||||
description: Candidate-declared specialization and grade, separate from categories.
|
||||
items:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 50
|
||||
pattern: '^\S(?:.*\S)?$'
|
||||
description: Plain text; clients show it as text, never as HTML.
|
||||
location:
|
||||
$ref: "#/schemas/CardSelfAssessment"
|
||||
experience_band:
|
||||
oneOf:
|
||||
- $ref: "#/schemas/CandidateExperienceBand"
|
||||
- type: "null"
|
||||
description: Coarse total work-experience bucket, or null.
|
||||
work_formats:
|
||||
type:
|
||||
- string
|
||||
- array
|
||||
- "null"
|
||||
minLength: 1
|
||||
maxLength: 100
|
||||
pattern: '^\S(?:.*\S)?$'
|
||||
description: >-
|
||||
City or region as free text, never a street address, or null.
|
||||
Plain text; clients show it as text, never as HTML.
|
||||
relocation:
|
||||
type:
|
||||
- boolean
|
||||
- "null"
|
||||
description: Whether the candidate is ready to relocate, or null.
|
||||
maxItems: 3
|
||||
description: Explicitly opted-in work formats, or null.
|
||||
items:
|
||||
$ref: "#/schemas/CandidateWorkFormat"
|
||||
salary_compatibility:
|
||||
oneOf:
|
||||
- $ref: "#/schemas/CandidateSalaryCompatibility"
|
||||
- type: "null"
|
||||
description: Nullable compatibility result with no salary values.
|
||||
CardPreview:
|
||||
type: object
|
||||
description: >-
|
||||
What an organization that the candidate does not hide the profile from
|
||||
would read now, computed from the current profile, the current
|
||||
publication, and the consent ledger. It is a read for the candidate: it
|
||||
creates no view and no history record, and it never reaches an
|
||||
organization. `card` is null while the profile is closed.
|
||||
A private candidate preview computed from the current profile,
|
||||
publication, and consent ledger. Its pseudonym uses a separate preview
|
||||
context and is not an organization's alias. Organization-specific
|
||||
visibility filters and cohort checks can further generalize or suppress
|
||||
the organization-facing card. This read creates no view or history
|
||||
record and never reaches an organization. `card` is null while the
|
||||
profile is closed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
@@ -520,7 +579,7 @@ schemas:
|
||||
description: |-
|
||||
How an organization reached the candidate.
|
||||
|
||||
- card_viewed: an organization read the anonymous card in a search result.
|
||||
- card_viewed: an organization read the permitted anonymous card.
|
||||
- contact_read: an organization read the contacts through the contact grant of an accepted invitation.
|
||||
enum:
|
||||
- card_viewed
|
||||
@@ -529,12 +588,12 @@ schemas:
|
||||
type: object
|
||||
description: >-
|
||||
One access of an organization to the card or the contacts of the
|
||||
current candidate. `organization` is null for a view by an
|
||||
organization that has no invitation relation with the candidate, so the
|
||||
history shows that the card was viewed without naming a company that
|
||||
the candidate cannot otherwise see; whether the candidate should learn
|
||||
the name is an open product question. The record carries no query,
|
||||
ranking, or search filter of the organization.
|
||||
current candidate. A retained access permits the candidate to see the
|
||||
organization's identifier and current name and to hide their profile
|
||||
from it. `organization` is null when the organization cannot be
|
||||
presented. Earlier permitted accesses remain after hiding. The record
|
||||
carries no employee identity, query, ranking, or search filter of the
|
||||
organization.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
|
||||
@@ -533,12 +533,12 @@ schemas:
|
||||
format: int32
|
||||
minimum: 1
|
||||
description: >-
|
||||
For a manual assessment, the version of the published rubric of the
|
||||
category that the server fixed on creation; the expert assesses with
|
||||
it, the same rubric as the automated assessment. Null for other
|
||||
types, and null for a manual assessment whose category has no
|
||||
published rubric yet: the case then waits in `waiting_expert` and
|
||||
the client says so instead of promising a date.
|
||||
For a manual assessment, the version of the grading policy pinned
|
||||
by the server at creation. The exact reviewed category opening and
|
||||
rubric manifest are retained privately so the expert can use the
|
||||
same rubric as automated assessment. Null for other types and for a
|
||||
manual assessment without one unique current reviewed category; the
|
||||
case still waits in `waiting_expert`.
|
||||
response_target:
|
||||
$ref: "#/schemas/SupportResponseTarget"
|
||||
decision:
|
||||
|
||||
+446
-93
@@ -854,6 +854,58 @@ paths:
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/signals:
|
||||
post:
|
||||
operationId: RecordMyAssessmentAttemptSignals
|
||||
summary: Store a bounded batch of client-reported assessment signals.
|
||||
description: |-
|
||||
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect.
|
||||
|
||||
The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
|
||||
A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
sessionCsrf: []
|
||||
tags:
|
||||
- assessment
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/AssessmentAttemptId'
|
||||
- $ref: '#/components/parameters/IdempotencyKey'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AssessmentSignalBatch'
|
||||
responses:
|
||||
'200':
|
||||
description: The stored or replayed receipt. A saturated receipt explicitly says that none of this batch's events was stored.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: '#/components/headers/CacheControlNoStore'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AssessmentSignalReceipt'
|
||||
'400':
|
||||
$ref: '#/components/responses/ValidationFailed'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'403':
|
||||
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'409':
|
||||
$ref: '#/components/responses/StateConflict'
|
||||
'413':
|
||||
$ref: '#/components/responses/PayloadTooLarge'
|
||||
'422':
|
||||
$ref: '#/components/responses/UnprocessableContent'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/answers:
|
||||
post:
|
||||
operationId: SubmitMyAssessmentAnswer
|
||||
@@ -954,7 +1006,7 @@ paths:
|
||||
|
||||
A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
|
||||
An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not.
|
||||
security:
|
||||
@@ -1470,6 +1522,52 @@ paths:
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}:
|
||||
get:
|
||||
operationId: GetOrganizationCandidateCard
|
||||
summary: Read one currently visible anonymous candidate card.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
|
||||
`candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
|
||||
The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
|
||||
Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- privacy
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/OrganizationId'
|
||||
- $ref: '#/components/parameters/CandidateHandle'
|
||||
responses:
|
||||
'200':
|
||||
description: The current anonymous card for this organization.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: '#/components/headers/CacheControlNoStore'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AnonymousCardContent'
|
||||
examples:
|
||||
published:
|
||||
$ref: '#/components/examples/OrganizationAnonymousCandidateCard'
|
||||
'400':
|
||||
$ref: '#/components/responses/ValidationFailed'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'403':
|
||||
$ref: '#/components/responses/Forbidden'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'429':
|
||||
$ref: '#/components/responses/TooManyRequests'
|
||||
default:
|
||||
$ref: '#/components/responses/Problem'
|
||||
/api/v1/organizations/{org_id}/invitations:
|
||||
get:
|
||||
operationId: ListOrganizationInvitations
|
||||
@@ -2529,9 +2627,11 @@ paths:
|
||||
operationId: GetMyCardPreview
|
||||
summary: Preview the anonymous card that organizations would read.
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`.
|
||||
|
||||
The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results.
|
||||
The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it.
|
||||
|
||||
`card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
security:
|
||||
@@ -2659,7 +2759,7 @@ paths:
|
||||
|
||||
The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization.
|
||||
|
||||
Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
|
||||
A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit.
|
||||
|
||||
@@ -2775,9 +2875,9 @@ paths:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history.
|
||||
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
security:
|
||||
@@ -5026,6 +5126,7 @@ components:
|
||||
number:
|
||||
type: number
|
||||
format: double
|
||||
x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber
|
||||
StringAnswer:
|
||||
type: object
|
||||
description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison.
|
||||
@@ -5146,6 +5247,120 @@ components:
|
||||
$ref: '#/components/schemas/AssessmentItemId'
|
||||
answer:
|
||||
$ref: '#/components/schemas/AssessmentAnswer'
|
||||
AssessmentSignalEvent:
|
||||
description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/AssessmentFocusLossSignal'
|
||||
- $ref: '#/components/schemas/AssessmentClipboardSignal'
|
||||
- $ref: '#/components/schemas/AssessmentFullscreenExitSignal'
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
focus_loss: '#/components/schemas/AssessmentFocusLossSignal'
|
||||
copy: '#/components/schemas/AssessmentClipboardSignal'
|
||||
paste: '#/components/schemas/AssessmentClipboardSignal'
|
||||
cut: '#/components/schemas/AssessmentClipboardSignal'
|
||||
fullscreen_exit: '#/components/schemas/AssessmentFullscreenExitSignal'
|
||||
AssessmentFocusLossSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- duration_ms
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- focus_loss
|
||||
item_instance_id:
|
||||
$ref: '#/components/schemas/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
duration_ms:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 1
|
||||
maximum: 259200000
|
||||
description: Client-measured duration away from the assessment tab or window, in milliseconds.
|
||||
AssessmentClipboardSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
- size_bytes
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- copy
|
||||
- paste
|
||||
- cut
|
||||
item_instance_id:
|
||||
$ref: '#/components/schemas/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
size_bytes:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 2147483647
|
||||
description: Byte count only. Clipboard or selection contents are not transmitted or retained.
|
||||
AssessmentFullscreenExitSignal:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- kind
|
||||
- item_instance_id
|
||||
- occurred_at
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- fullscreen_exit
|
||||
item_instance_id:
|
||||
$ref: '#/components/schemas/AssessmentItemId'
|
||||
occurred_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
AssessmentSignalBatch:
|
||||
type: object
|
||||
description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- events
|
||||
properties:
|
||||
events:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 50
|
||||
items:
|
||||
$ref: '#/components/schemas/AssessmentSignalEvent'
|
||||
AssessmentSignalReceipt:
|
||||
type: object
|
||||
description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- status
|
||||
- accepted_events
|
||||
- received_at
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum:
|
||||
- accepted
|
||||
- saturated
|
||||
description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.'
|
||||
accepted_events:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 0
|
||||
maximum: 50
|
||||
description: Number of events stored from this batch; zero when saturated.
|
||||
received_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
AssessmentFinalization:
|
||||
type: object
|
||||
description: Command to finalize the attempt.
|
||||
@@ -6817,7 +7032,7 @@ components:
|
||||
- 'null'
|
||||
format: int32
|
||||
minimum: 1
|
||||
description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.'
|
||||
description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`.
|
||||
response_target:
|
||||
$ref: '#/components/schemas/SupportResponseTarget'
|
||||
decision:
|
||||
@@ -6967,12 +7182,12 @@ components:
|
||||
- 7
|
||||
CandidateHandle:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9_-]+$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: ^cv1_[A-Za-z0-9_-]{43}$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
- cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
InvitationRoleTitle:
|
||||
type: string
|
||||
minLength: 1
|
||||
@@ -8495,27 +8710,31 @@ components:
|
||||
description: |-
|
||||
A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.
|
||||
|
||||
- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.
|
||||
- stack: the technology tags of the profile.
|
||||
- experience: the total months of work experience, without employers, periods, or descriptions.
|
||||
- soft_skills: the soft skills of the profile.
|
||||
- location: the city or region of the profile.
|
||||
- relocation: whether the candidate is ready to relocate.
|
||||
- categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
- self_assessment: the candidate's declared specialization and grade, separate from confirmed categories.
|
||||
- stack: only recognized technology codes from the server's closed taxonomy.
|
||||
- experience: a coarse total-experience band, without employers, periods, or descriptions.
|
||||
- work_formats: explicitly selected work formats from the private questionnaire.
|
||||
- salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds.
|
||||
- soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card.
|
||||
|
||||
Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
||||
|
||||
Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.
|
||||
enum:
|
||||
- categories
|
||||
- salary_compatibility
|
||||
- self_assessment
|
||||
- stack
|
||||
- experience
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- work_formats
|
||||
CardFieldSet:
|
||||
type: array
|
||||
minItems: 0
|
||||
maxItems: 6
|
||||
maxItems: 9
|
||||
uniqueItems: true
|
||||
description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.
|
||||
items:
|
||||
@@ -8715,23 +8934,37 @@ components:
|
||||
required:
|
||||
- specialization
|
||||
- grade
|
||||
- strength
|
||||
properties:
|
||||
specialization:
|
||||
$ref: '#/components/schemas/SpecializationCode'
|
||||
grade:
|
||||
$ref: '#/components/schemas/GradeCode'
|
||||
strength:
|
||||
type: string
|
||||
enum:
|
||||
- standard
|
||||
- strong
|
||||
description: Coarse strength of the authoritative confirmation.
|
||||
AnonymousCardContent:
|
||||
type: object
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
|
||||
description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- pseudonym
|
||||
- categories
|
||||
- stack
|
||||
- experience_months
|
||||
- soft_skills
|
||||
- location
|
||||
- relocation
|
||||
- self_assessment
|
||||
- experience_band
|
||||
- work_formats
|
||||
- salary_compatibility
|
||||
properties:
|
||||
pseudonym:
|
||||
type: string
|
||||
minLength: 47
|
||||
maxLength: 47
|
||||
pattern: ^cv1_[A-Za-z0-9_-]{43}$
|
||||
description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations.
|
||||
categories:
|
||||
type:
|
||||
- array
|
||||
@@ -8744,45 +8977,44 @@ components:
|
||||
type:
|
||||
- array
|
||||
- 'null'
|
||||
maxItems: 30
|
||||
description: Technology tags of the candidate, or null.
|
||||
maxItems: 4
|
||||
description: Recognized confirmed technology codes only, or null.
|
||||
items:
|
||||
$ref: '#/components/schemas/StackTag'
|
||||
experience_months:
|
||||
type:
|
||||
- integer
|
||||
- 'null'
|
||||
minimum: 0
|
||||
maximum: 1200
|
||||
description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null.
|
||||
soft_skills:
|
||||
type: string
|
||||
enum:
|
||||
- go
|
||||
- postgresql
|
||||
- kafka
|
||||
- docker
|
||||
self_assessment:
|
||||
type:
|
||||
- array
|
||||
- 'null'
|
||||
maxItems: 10
|
||||
description: Soft skills of the candidate, or null.
|
||||
maxItems: 9
|
||||
description: Candidate-declared specialization and grade, separate from categories.
|
||||
items:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 50
|
||||
pattern: ^\S(?:.*\S)?$
|
||||
description: Plain text; clients show it as text, never as HTML.
|
||||
location:
|
||||
$ref: '#/components/schemas/CardSelfAssessment'
|
||||
experience_band:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/CandidateExperienceBand'
|
||||
- type: 'null'
|
||||
description: Coarse total work-experience bucket, or null.
|
||||
work_formats:
|
||||
type:
|
||||
- string
|
||||
- array
|
||||
- 'null'
|
||||
minLength: 1
|
||||
maxLength: 100
|
||||
pattern: ^\S(?:.*\S)?$
|
||||
description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.
|
||||
relocation:
|
||||
type:
|
||||
- boolean
|
||||
- 'null'
|
||||
description: Whether the candidate is ready to relocate, or null.
|
||||
maxItems: 3
|
||||
description: Explicitly opted-in work formats, or null.
|
||||
items:
|
||||
$ref: '#/components/schemas/CandidateWorkFormat'
|
||||
salary_compatibility:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/CandidateSalaryCompatibility'
|
||||
- type: 'null'
|
||||
description: Nullable compatibility result with no salary values.
|
||||
CardPreview:
|
||||
type: object
|
||||
description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.'
|
||||
description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- state
|
||||
@@ -8877,14 +9109,14 @@ components:
|
||||
description: |-
|
||||
How an organization reached the candidate.
|
||||
|
||||
- card_viewed: an organization read the anonymous card in a search result.
|
||||
- card_viewed: an organization read the permitted anonymous card.
|
||||
- contact_read: an organization read the contacts through the contact grant of an accepted invitation.
|
||||
enum:
|
||||
- card_viewed
|
||||
- contact_read
|
||||
CardAccess:
|
||||
type: object
|
||||
description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization.
|
||||
description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
@@ -9194,6 +9426,58 @@ components:
|
||||
- task_language
|
||||
- root_attempt_id
|
||||
- chain_deadline
|
||||
AssessmentFinalizeConflictProblem:
|
||||
type: object
|
||||
description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- type
|
||||
- title
|
||||
- status
|
||||
- code
|
||||
properties:
|
||||
type:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 256
|
||||
title:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 200
|
||||
status:
|
||||
type: integer
|
||||
format: int32
|
||||
const: 409
|
||||
code:
|
||||
type: string
|
||||
enum:
|
||||
- state_conflict
|
||||
- idempotency_in_progress
|
||||
detail:
|
||||
type: string
|
||||
maxLength: 1000
|
||||
instance:
|
||||
type: string
|
||||
format: uri-reference
|
||||
maxLength: 2048
|
||||
trace_id:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9._-]+$
|
||||
errors:
|
||||
type: array
|
||||
maxItems: 100
|
||||
items:
|
||||
$ref: '#/components/schemas/ProblemFieldError'
|
||||
pending_item_ids:
|
||||
type: array
|
||||
maxItems: 220
|
||||
uniqueItems: true
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items.
|
||||
AssessmentRealResultCommon:
|
||||
type: object
|
||||
description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero.
|
||||
@@ -9460,6 +9744,47 @@ components:
|
||||
description: Short educational feedback about this training run.
|
||||
decided_at:
|
||||
$ref: '#/components/schemas/Timestamp'
|
||||
CardSelfAssessment:
|
||||
type: object
|
||||
description: Candidate-declared specialization and optional grade. This is never an assessment result.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- specialization
|
||||
- confirmation_status
|
||||
properties:
|
||||
specialization:
|
||||
$ref: '#/components/schemas/SpecializationCode'
|
||||
confirmation_status:
|
||||
type: string
|
||||
enum:
|
||||
- confirmed
|
||||
- unconfirmed
|
||||
declared_grade:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/GradeCode'
|
||||
- type: 'null'
|
||||
CandidateExperienceBand:
|
||||
type: string
|
||||
description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned.
|
||||
enum:
|
||||
- '0_1'
|
||||
- '1_3'
|
||||
- '3_6'
|
||||
- 6_plus
|
||||
- '0_3'
|
||||
- 3_plus
|
||||
CandidateWorkFormat:
|
||||
type: string
|
||||
enum:
|
||||
- remote
|
||||
- office
|
||||
- hybrid
|
||||
CandidateSalaryCompatibility:
|
||||
type: string
|
||||
description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card.
|
||||
enum:
|
||||
- compatible
|
||||
- not_compatible
|
||||
parameters:
|
||||
IdempotencyKey:
|
||||
name: Idempotency-Key
|
||||
@@ -9577,6 +9902,14 @@ components:
|
||||
type: string
|
||||
format: uuid
|
||||
example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
CandidateHandle:
|
||||
name: candidate_handle
|
||||
in: path
|
||||
required: true
|
||||
description: Organization-scoped opaque candidate alias issued by the current visible card projection. The server resolves it only for the organization in the path and rechecks current membership, publication consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all answer the same 404.
|
||||
schema:
|
||||
$ref: '#/components/schemas/CandidateHandle'
|
||||
example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
headers:
|
||||
ETag:
|
||||
description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version.
|
||||
@@ -9886,11 +10219,11 @@ components:
|
||||
idempotency_in_progress:
|
||||
$ref: '#/components/examples/IdempotencyInProgress'
|
||||
AssessmentFinalizeConflict:
|
||||
description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. The problem does not list the unfinished parts, because Problem allows no extension fields; the attempt shows them in `state`, `progress`, `current_item`, and `practices`. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.'
|
||||
description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. If required questions are unfinished, the response includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.'
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Problem'
|
||||
$ref: '#/components/schemas/AssessmentFinalizeConflictProblem'
|
||||
examples:
|
||||
state_conflict:
|
||||
$ref: '#/components/examples/AssessmentFinalizeNotReady'
|
||||
@@ -11411,6 +11744,24 @@ components:
|
||||
code: version_conflict
|
||||
detail: The resource changed after it was read. Read it again before retrying.
|
||||
trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c
|
||||
StateConflict:
|
||||
summary: The resource state does not allow the operation
|
||||
value:
|
||||
type: urn:lincodex:problem:state_conflict
|
||||
title: Resource state conflict
|
||||
status: 409
|
||||
code: state_conflict
|
||||
detail: The resource is in a state that does not allow this operation.
|
||||
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b
|
||||
PayloadTooLarge:
|
||||
summary: The request body exceeds the limit
|
||||
value:
|
||||
type: urn:lincodex:problem:payload_too_large
|
||||
title: Request body too large
|
||||
status: 413
|
||||
code: payload_too_large
|
||||
detail: Reduce the request body size and retry.
|
||||
trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e
|
||||
AssessmentChoiceAnswer:
|
||||
summary: Answer item 1 of version 1
|
||||
value:
|
||||
@@ -11562,8 +11913,7 @@ components:
|
||||
value:
|
||||
expected_version: 20
|
||||
AssessmentFinalizeNotReady:
|
||||
summary: Premature finalize; the problem does not list the unfinished parts
|
||||
description: 'Problem has no extension fields. The client reads what remains from the attempt: `state`, `progress`, `current_item`, and `practices`.'
|
||||
summary: Premature finalize; the problem lists unanswered frozen items
|
||||
value:
|
||||
type: urn:lincodex:problem:state_conflict
|
||||
title: Resource state conflict
|
||||
@@ -11571,6 +11921,9 @@ components:
|
||||
code: state_conflict
|
||||
detail: The resource is in a state that does not allow this operation.
|
||||
trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e
|
||||
pending_item_ids:
|
||||
- 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d
|
||||
- 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d
|
||||
AssessmentDemoBasicResult:
|
||||
summary: demo_basic result with a confirmed grade and no uncertainty
|
||||
description: demo_basic computes no ability estimate, so `uncertainty` and `strength` are null rather than zero, and no percentile is shown. The pass mark comes from basic grading policy version 1, and the limitations name the uncalibrated thresholds, the demo bank, and the missing practice. A first confirmation is not a promotion, so the higher grade can be tested at once. The result never changes; a repeated finalize returns the completed attempt, and this read returns the same result.
|
||||
@@ -12738,13 +13091,29 @@ components:
|
||||
code: version_conflict
|
||||
detail: The resource changed after it was read. Read it again before retrying.
|
||||
trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d
|
||||
OrganizationAnonymousCandidateCard:
|
||||
summary: An anonymous card currently visible to one organization
|
||||
description: The alias is scoped to the reading organization; no contact values are included.
|
||||
value:
|
||||
pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
categories:
|
||||
- specialization: backend
|
||||
grade: middle
|
||||
strength: standard
|
||||
stack:
|
||||
- postgresql
|
||||
- kafka
|
||||
self_assessment: null
|
||||
experience_band: '1_3'
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
OrganizationInvitationListPage:
|
||||
summary: The last page of the invitations of an organization
|
||||
description: The organization sees that the second invitation was declined, but not the reason or the comment.
|
||||
value:
|
||||
items:
|
||||
- id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -12767,7 +13136,7 @@ components:
|
||||
created_at: '2026-10-06T09:00:00Z'
|
||||
updated_at: '2026-10-06T15:00:00Z'
|
||||
- id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80
|
||||
candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb
|
||||
candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
|
||||
need: null
|
||||
state: declined
|
||||
expiry_reason: null
|
||||
@@ -12793,7 +13162,7 @@ components:
|
||||
summary: A draft for a candidate from the search results of a need
|
||||
description: 'Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided.'
|
||||
value:
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -12841,7 +13210,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -13007,7 +13376,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -13071,7 +13440,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -13179,7 +13548,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -13238,15 +13607,6 @@ components:
|
||||
delivered_at: null
|
||||
viewed_at: null
|
||||
responded_at: null
|
||||
StateConflict:
|
||||
summary: The resource state does not allow the operation
|
||||
value:
|
||||
type: urn:lincodex:problem:state_conflict
|
||||
title: Resource state conflict
|
||||
status: 409
|
||||
code: state_conflict
|
||||
detail: The resource is in a state that does not allow this operation.
|
||||
trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b
|
||||
InvitationStaleTerms:
|
||||
summary: The acceptance named a terms version that is no longer current
|
||||
description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision.
|
||||
@@ -13309,7 +13669,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -13377,7 +13737,7 @@ components:
|
||||
value:
|
||||
id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
|
||||
organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01
|
||||
candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt
|
||||
candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
need:
|
||||
need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12
|
||||
requirements_version: 3
|
||||
@@ -14146,16 +14506,18 @@ components:
|
||||
- categories
|
||||
- stack
|
||||
card:
|
||||
pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
categories:
|
||||
- specialization: backend
|
||||
grade: middle
|
||||
strength: standard
|
||||
stack:
|
||||
- PostgreSQL
|
||||
- Kafka
|
||||
experience_months: null
|
||||
soft_skills: null
|
||||
location: null
|
||||
relocation: null
|
||||
- postgresql
|
||||
- kafka
|
||||
self_assessment: null
|
||||
experience_band: '1_3'
|
||||
work_formats: null
|
||||
salary_compatibility: null
|
||||
generated_at: '2026-10-06T09:30:00Z'
|
||||
ClosedCardPreview:
|
||||
summary: The preview of a closed profile
|
||||
@@ -14539,15 +14901,6 @@ components:
|
||||
message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам.
|
||||
created_at: '2026-10-01T10:00:00Z'
|
||||
updated_at: '2026-10-09T14:30:00Z'
|
||||
PayloadTooLarge:
|
||||
summary: The request body exceeds the limit
|
||||
value:
|
||||
type: urn:lincodex:problem:payload_too_large
|
||||
title: Request body too large
|
||||
status: 413
|
||||
code: payload_too_large
|
||||
detail: Reduce the request body size and retry.
|
||||
trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e
|
||||
PreconditionRequired:
|
||||
summary: The operation requires If-Match
|
||||
value:
|
||||
|
||||
@@ -109,6 +109,8 @@ paths:
|
||||
$ref: ./routes/candidate_assessment_attempt.yml
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/sessions:
|
||||
$ref: ./routes/candidate_assessment_attempt_sessions.yml
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/signals:
|
||||
$ref: ./routes/candidate_assessment_signals.yml
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/answers:
|
||||
$ref: ./routes/candidate_assessment_attempt_answers.yml
|
||||
/api/v1/me/assessment-attempts/{attempt_id}/finalize:
|
||||
@@ -125,6 +127,8 @@ paths:
|
||||
$ref: ./routes/organization_needs.yml
|
||||
/api/v1/organizations/{org_id}/needs/{need_id}:
|
||||
$ref: ./routes/organization_need.yml
|
||||
/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}:
|
||||
$ref: ./routes/organization_candidate_card.yml
|
||||
/api/v1/organizations/{org_id}/invitations:
|
||||
$ref: ./routes/organization_invitations.yml
|
||||
/api/v1/organizations/{org_id}/invitations/{invitation_id}:
|
||||
@@ -439,6 +443,18 @@ components:
|
||||
$ref: ./components/schemas.yml#/AssessmentAnswer
|
||||
AssessmentAnswerSubmission:
|
||||
$ref: ./components/schemas.yml#/AssessmentAnswerSubmission
|
||||
AssessmentSignalEvent:
|
||||
$ref: ./components/schemas.yml#/AssessmentSignalEvent
|
||||
AssessmentFocusLossSignal:
|
||||
$ref: ./components/schemas.yml#/AssessmentFocusLossSignal
|
||||
AssessmentClipboardSignal:
|
||||
$ref: ./components/schemas.yml#/AssessmentClipboardSignal
|
||||
AssessmentFullscreenExitSignal:
|
||||
$ref: ./components/schemas.yml#/AssessmentFullscreenExitSignal
|
||||
AssessmentSignalBatch:
|
||||
$ref: ./components/schemas.yml#/AssessmentSignalBatch
|
||||
AssessmentSignalReceipt:
|
||||
$ref: ./components/schemas.yml#/AssessmentSignalReceipt
|
||||
AssessmentFinalization:
|
||||
$ref: ./components/schemas.yml#/AssessmentFinalization
|
||||
AssessmentOutcome:
|
||||
|
||||
@@ -13,7 +13,7 @@ post:
|
||||
|
||||
A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
|
||||
An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not.
|
||||
security:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
post:
|
||||
operationId: RecordMyAssessmentAttemptSignals
|
||||
summary: Store a bounded batch of client-reported assessment signals.
|
||||
description: |-
|
||||
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect.
|
||||
|
||||
The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
|
||||
A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
sessionCsrf: []
|
||||
tags:
|
||||
- assessment
|
||||
parameters:
|
||||
- $ref: ../components/parameters.yml#/AssessmentAttemptId
|
||||
- $ref: ../components/parameters.yml#/IdempotencyKey
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/AssessmentSignalBatch
|
||||
responses:
|
||||
"200":
|
||||
description: >-
|
||||
The stored or replayed receipt. A saturated receipt explicitly says
|
||||
that none of this batch's events was stored.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: ../components/headers.yml#/CacheControlNoStore
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/AssessmentSignalReceipt
|
||||
"400":
|
||||
$ref: ../components/responses.yml#/ValidationFailed
|
||||
"401":
|
||||
$ref: ../components/responses.yml#/Unauthenticated
|
||||
"403":
|
||||
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
|
||||
"404":
|
||||
$ref: ../components/responses.yml#/NotFound
|
||||
"409":
|
||||
$ref: ../components/responses.yml#/StateConflict
|
||||
"413":
|
||||
$ref: ../components/responses.yml#/PayloadTooLarge
|
||||
"422":
|
||||
$ref: ../components/responses.yml#/UnprocessableContent
|
||||
"429":
|
||||
$ref: ../components/responses.yml#/TooManyRequests
|
||||
default:
|
||||
$ref: ../components/responses.yml#/Problem
|
||||
@@ -4,9 +4,9 @@ get:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history.
|
||||
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
security:
|
||||
|
||||
@@ -6,7 +6,7 @@ put:
|
||||
|
||||
The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization.
|
||||
|
||||
Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
|
||||
|
||||
A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit.
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@ get:
|
||||
operationId: GetMyCardPreview
|
||||
summary: Preview the anonymous card that organizations would read.
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`.
|
||||
|
||||
The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results.
|
||||
The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it.
|
||||
|
||||
`card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
security:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
get:
|
||||
operationId: GetOrganizationCandidateCard
|
||||
summary: Read one currently visible anonymous candidate card.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
|
||||
|
||||
`candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
|
||||
The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
|
||||
Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- privacy
|
||||
parameters:
|
||||
- $ref: ../components/parameters.yml#/OrganizationId
|
||||
- $ref: ../components/parameters.yml#/CandidateHandle
|
||||
responses:
|
||||
"200":
|
||||
description: The current anonymous card for this organization.
|
||||
headers:
|
||||
Cache-Control:
|
||||
$ref: ../components/headers.yml#/CacheControlNoStore
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: ../components/schemas.yml#/AnonymousCardContent
|
||||
examples:
|
||||
published:
|
||||
$ref: ../components/examples.yml#/OrganizationAnonymousCandidateCard
|
||||
"400":
|
||||
$ref: ../components/responses.yml#/ValidationFailed
|
||||
"401":
|
||||
$ref: ../components/responses.yml#/Unauthenticated
|
||||
"403":
|
||||
$ref: ../components/responses.yml#/Forbidden
|
||||
"404":
|
||||
$ref: ../components/responses.yml#/NotFound
|
||||
"429":
|
||||
$ref: ../components/responses.yml#/TooManyRequests
|
||||
default:
|
||||
$ref: ../components/responses.yml#/Problem
|
||||
+48
-4
@@ -26,7 +26,7 @@ HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`
|
||||
|
||||
Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF.
|
||||
|
||||
Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account or profile use. A separate manual-assessment request is planned, but its endpoint is not implemented. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously.
|
||||
Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously.
|
||||
|
||||
`make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request.
|
||||
|
||||
@@ -34,20 +34,38 @@ Revoking C2 makes the publication effectively closed and hides its fields throug
|
||||
|
||||
`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved.
|
||||
|
||||
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Needs and invitations remain unimplemented, but their routes already enforce the common owner check before the 501 fallback.
|
||||
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes still enforce the common owner check before the 501 fallback; their business operations remain unimplemented.
|
||||
|
||||
`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL.
|
||||
|
||||
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
|
||||
|
||||
## Need storage
|
||||
## Organization needs
|
||||
|
||||
Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict. Need business endpoints remain unimplemented at this storage stage.
|
||||
Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict.
|
||||
|
||||
The owner-scoped create, read, list, and update operations live in `internal/adapter/primary/http/v1/need.go`. Every operation checks the current verified employer account and locks its active owner membership in the transaction. List cursors carry both account and organization scope. Creates retain the original public response for the 24-hour idempotency window, even after a later edit.
|
||||
|
||||
Source text is parsed locally by deterministic rules into unconfirmed suggestions. Unknown or ambiguous values remain unknown. Confirming a stored suggestion preserves its origin; a manual replacement records a manual origin. Editing source text preserves confirmed values, and removing a suggestion prevents later extraction from silently restoring it. Readiness is derived from confirmed requirements. Category recommendations currently report `not_available` without confirmed skills and `pending` otherwise; the category recommendation calculator is not implemented yet.
|
||||
|
||||
`requirements_version` identifies the snapshot where confirmed requirements last changed. Editing only the title, source text, or unconfirmed suggestions leaves that reference unchanged. Domain no-ops preserve both versions. Snapshots preserve provenance, reject oversized content, and use UTC microsecond timestamps. Current and historical reads require the organization ID; immutable history rejects ordinary UPDATE and DELETE. Down migration removes both tables and their history, so it is destructive after data has been written.
|
||||
|
||||
`TestOrganizationNeedsStorage` exercises actual PostgreSQL isolation, history, concurrent updates, transaction rollback, immutable snapshots, and storage bounds. The caller must perform the existing active-owner check in the same business operation; storage scope alone does not grant company access.
|
||||
|
||||
Migration `00026_create_organization_need_creation_results.sql` adds create-response storage and 8 KiB of database representation headroom for JSONB whitespace. The compact domain snapshot limit remains 256 KiB. Its down migration refuses to discard live replay results or restore the previous database bound over larger stored snapshots. Check those conditions before rollback; it does not remove need history to make a downgrade succeed.
|
||||
|
||||
## Support cases
|
||||
|
||||
Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent.
|
||||
|
||||
A manual request pins the current published rubric for its specialization and grade. The API shows the grading-policy version; private references retain the exact category opening and immutable family-version manifest. Later publications do not change an existing case's rubric. Without one unambiguous current rubric, the version remains `null` and the case waits for an expert.
|
||||
|
||||
Creation requires an explicit support section in the effective product policy. `DemoProductPolicyV2` includes it; normal startup still seeds only the immutable V1 policy. The demo targets are five business days for support, complaints, and manual assessment, and ten for appeals. The versioned calendar counts UTC weekdays without public holidays and does not pause while waiting for the user. These are operational targets, not legal deadlines.
|
||||
|
||||
The account-wide rolling request limit is checked under a database lock before idempotent replay. Valid retries consume that request budget and return the original creation response during the 24-hour window. A 429 response includes `Retry-After`. GET and list show the current status, public history, and current overdue flag. Migration `00025_create_support_cases.sql` stores immutable events and replay results; rollback removes these records and is destructive.
|
||||
|
||||
`TestSupportCasesOverHTTP` covers real sessions, owner isolation, typed-reference checks, replay, manual assessment without C3, and request limits. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` checks concurrent requests and clock ordering. Expert processing and references to not-yet-implemented invitations or anti-cheat reviews remain unavailable.
|
||||
|
||||
## Candidate questionnaire
|
||||
|
||||
Verified candidates can read and replace their own questionnaire through `GET/PUT /api/v1/me/questionnaire`. The questionnaire has a separate version and stores self-assessment, work formats, optional experience totals, and one or two specializations. It cannot assign confirmed grades. An identical retry returns the saved record without advancing its version; a stale changed body returns 412, as specified by the API contract. Concurrent identical writes also return the same winning record.
|
||||
@@ -58,4 +76,30 @@ The public specialization catalog derives readiness from the current published b
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` covers persistence, account isolation, version races, rollback, conditional onboarding, and changing bank availability. Company quota storage and its calling contract are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md).
|
||||
|
||||
## Assessment attempts
|
||||
|
||||
A candidate creates an attempt through `POST /api/v1/me/assessment-attempts`, reads it by ID, and resumes work through `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Real assessment requires current C3 consent; the owner's attempt history remains readable after revocation. GET neither consumes sessions nor changes state. A command with a stale version returns 412.
|
||||
|
||||
Creation pins the policy, bank and algorithm versions, the published family manifest, and generated question instances. The API response excludes answer keys, seeds, and private rubrics. Root-attempt quota is candidate-wide; retry and promotion intervals apply per specialization. A corrective attempt retains its root and the original chain deadline. Training `demo_express` uses a separate explicitly published bank and consumes no real-assessment quota.
|
||||
|
||||
Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records.
|
||||
|
||||
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. Category assignment remains separate work; a basic threshold is not evidence of calibration.
|
||||
|
||||
## Assessment signals
|
||||
|
||||
The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt.
|
||||
|
||||
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Browser collection and interpretation of these signals are separate work.
|
||||
|
||||
## Anonymous profile projection
|
||||
|
||||
The organization-scoped projection uses purpose-separated HMAC aliases, a closed skill taxonomy, coarse experience bands, and explicitly selected publication fields. Confirmed categories and self-assessed grades remain separate. It excludes contacts, employer names, free text, exact salary, and account identifiers. Overlapping work periods count once.
|
||||
|
||||
The repository filters current C2 publication and hidden organizations before building the cohort. Complete visible feature combinations with fewer than five candidates are generalized or suppressed. This reduces identification risk; it does not guarantee anonymity. The private owner-preview alias uses a separate purpose. Category and salary compatibility inputs remain absent until their authoritative source supplies them; missing evidence is never inferred from a claimed grade.
|
||||
|
||||
Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me/privacy/preview`, change history at `GET /api/v1/me/privacy/history`, and card views at `GET /api/v1/me/privacy/access-history`. Hidden organizations are listed at `GET /api/v1/me/privacy/hidden-organizations` and changed through `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Publication and search status use `PUT /api/v1/me/privacy/publication` and `PUT /api/v1/me/privacy/search-status`. The data is scoped to the candidate in the current session, responses use `Cache-Control: no-store`, and writes require the session CSRF token and an exact allowed Origin. C2, publication, search status, and hidden organizations are independent: changing one does not enable another. Search status is a statement by the candidate, not consent.
|
||||
|
||||
An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details.
|
||||
|
||||
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
|
||||
+48
-4
@@ -26,7 +26,7 @@
|
||||
|
||||
Публично доступен только текущий текст C1 для регистрации. Подтвержденный пользователь может прочитать текущие тексты C1/C2/C3/C5 перед выдачей в настройках и постранично получить только собственный журнал согласий. C1 можно выдать аккаунту любого сценария; C2, C3 и C5 доступны кандидату. Изменения требуют явного подтверждения, exact Origin и session-bound CSRF.
|
||||
|
||||
Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт или профиль. Отдельный запрос ручной оценки запланирован, но его endpoint пока не реализован. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно.
|
||||
Отзыв C2 закрывает публикацию в модели чтения и скрывает поля в той же транзакции; сохраненная публикация остается связанной с отозванной записью, поэтому повторная выдача C2 не открывает ее снова. Отзыв C3 не блокирует аккаунт, профиль или запрос ручной оценки через поддержку. Отзыв C5 немедленно закрывает gate будущего импорта и пишет intent в outbox; внешнего адаптера ФСП пока нет. Отзыв C4 ограничен одной организацией и использует сохраненную область контактов. Запрос C1 отзывает согласие и создает долговечную запись запроса удаления с outbox intent; повтор возвращает ту же активную запись, а сама учетная запись не удаляется синхронно.
|
||||
|
||||
Проверку полного HTTP-пути с PostgreSQL и Redis запускает `make -C backend test-int`; тест `TestConsentSettingsOverHTTP` покрывает тексты, журнал, grants, revocation effects и C1 deletion request.
|
||||
|
||||
@@ -34,20 +34,38 @@
|
||||
|
||||
Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется.
|
||||
|
||||
Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Потребности и приглашения пока не реализованы, но их пути уже защищены общей проверкой владельца до ответа 501.
|
||||
Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца до ответа 501; их бизнес-операции пока не реализованы.
|
||||
|
||||
`TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа.
|
||||
|
||||
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
|
||||
|
||||
## Хранилище потребностей
|
||||
## Потребности организаций
|
||||
|
||||
Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412. На этом этапе хранилища бизнес-операции HTTP потребностей еще не реализованы.
|
||||
Потребности организаций сохраняются в PostgreSQL через связанный с транзакцией `UnitOfWork.Needs()`. Миграция `00023_create_organization_needs.sql` добавляет указатель текущей версии и неизменяемые снимки в области организации. Создание начинается с версии 1. Измененный снимок повышает версию через compare-and-swap; проигравший конкурентный запрос получает конфликт версии. Контракт HTTP использует для него 412.
|
||||
|
||||
Операции создания, чтения, списка и изменения доступны владельцу и находятся в `internal/adapter/primary/http/v1/need.go`. Каждая операция проверяет текущую подтвержденную учетную запись работодателя и блокирует активное членство владельца в транзакции. Курсор списка содержит область учетной записи и организации. Создание сохраняет исходный публичный ответ на 24 часа для повторов с тем же ключом, даже после последующего изменения.
|
||||
|
||||
Исходный текст разбирается локально детерминированными правилами в неподтвержденные предложения. Неизвестные и неоднозначные значения остаются неизвестными. Подтверждение сохраненного предложения сохраняет его происхождение; ручная замена получает ручное происхождение. Изменение исходного текста сохраняет подтвержденные значения, а удаление предложения запрещает разбору незаметно восстановить его позднее. Готовность вычисляется по подтвержденным требованиям. Рекомендации категорий пока возвращают `not_available` без подтвержденных навыков и `pending` в остальных случаях; вычисление рекомендаций категорий еще не реализовано.
|
||||
|
||||
`requirements_version` указывает на снимок последнего изменения подтвержденных требований. Правка только названия, исходного текста или неподтвержденных предложений сохраняет эту ссылку. Доменный no-op сохраняет обе версии. Снимки сохраняют происхождение полей, отклоняют слишком большой объем данных и используют время UTC с точностью до микросекунд. Чтение текущей и исторической версии требует ID организации; обычные UPDATE и DELETE истории запрещены. Откат миграции удаляет обе таблицы вместе с историей, поэтому после записи данных он приводит к их потере.
|
||||
|
||||
`TestOrganizationNeedsStorage` проверяет на настоящем PostgreSQL изоляцию, историю, конкурентные обновления, откат транзакции, неизменяемость снимков и ограничения объема. Вызывающая бизнес-операция должна применять существующую проверку активного владельца; область организации в хранилище сама по себе не дает доступа к компании.
|
||||
|
||||
Миграция `00026_create_organization_need_creation_results.sql` добавляет хранение ответа создания и запас 8 KiB для пробелов в представлении JSONB. Ограничение компактного доменного снимка остается 256 KiB. Обратная миграция отказывается удалять действующие результаты повторов или восстанавливать прежний предел БД поверх более крупных сохраненных снимков. Перед откатом нужно проверить эти условия; история потребностей не удаляется ради успешного отката.
|
||||
|
||||
## Обращения в поддержку
|
||||
|
||||
Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие.
|
||||
|
||||
Ручной запрос фиксирует текущую опубликованную рубрику для выбранных специализации и грейда. API показывает версию политики оценивания; внутренние ссылки сохраняют точное открытие категории и неизменяемый набор версий семейств. Последующие публикации не меняют рубрику существующего обращения. При отсутствии однозначной актуальной рубрики версия остается `null`, а обращение ожидает эксперта.
|
||||
|
||||
Для создания нужен явный раздел поддержки в действующей продуктовой политике. Он есть в `DemoProductPolicyV2`; обычный запуск по-прежнему создает только неизменяемую политику V1. Демо-срок составляет пять рабочих дней для поддержки, жалоб и ручной оценки и десять для апелляций. Версионированный календарь считает будни UTC без государственных праздников и не приостанавливает срок при ожидании пользователя. Это операционные ориентиры, а не юридические сроки.
|
||||
|
||||
Скользящий лимит запросов аккаунта проверяется под блокировкой БД до идемпотентного повтора. Корректные повторы расходуют этот бюджет и возвращают исходный ответ создания в течение 24 часов. Ответ 429 содержит `Retry-After`. GET и список показывают актуальный статус, публичную историю и текущий признак просрочки. Миграция `00025_create_support_cases.sql` хранит неизменяемые события и результаты повторов; откат удаляет эти записи и является разрушительным.
|
||||
|
||||
`TestSupportCasesOverHTTP` проверяет настоящие сессии, изоляцию владельцев, типизированные ссылки, повторы, ручную оценку без C3 и лимиты запросов. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` проверяет конкурентные запросы и порядок времени. Обработка экспертом и ссылки на еще не реализованные приглашения или античит-проверки остаются недоступны.
|
||||
|
||||
## Анкета кандидата
|
||||
|
||||
Подтвержденный кандидат читает и заменяет собственную анкету через `GET/PUT /api/v1/me/questionnaire`. Анкета имеет отдельную версию и хранит самооценку, форматы работы, необязательные суммы опыта и одну или две специализации. Она не назначает подтвержденные грейды. Идентичный повтор возвращает сохраненную запись без повышения версии; измененное тело с устаревшей версией получает 412 согласно контракту API. Одновременные одинаковые записи также возвращают одну победившую запись.
|
||||
@@ -58,4 +76,30 @@
|
||||
|
||||
`TestCandidateQuestionnaireOverHTTP` проверяет сохранность, изоляцию аккаунтов, конкурентные версии, откат, условный переход шага и изменение доступности банка. Хранилище квот компании и порядок его вызова описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md).
|
||||
|
||||
## Попытки оценки
|
||||
|
||||
Кандидат создает попытку через `POST /api/v1/me/assessment-attempts`, читает ее по ID и возобновляет работу командой `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Реальная оценка требует действующего C3; история собственной попытки остается доступной после его отзыва. GET не расходует сессии и не меняет состояние. Команда с устаревшей версией возвращает 412.
|
||||
|
||||
Создание фиксирует версии политики, банка и алгоритма, опубликованный набор семейств и сгенерированные экземпляры вопросов. Ответ API не содержит ключей ответов, seed или приватных рубрик. Квота корневых попыток общая для кандидата, а ограничения повторов и повышения грейда действуют по специализации. Корректирующая попытка сохраняет корень и исходный срок цепочки. Учебный `demo_express` использует отдельный явно опубликованный банк и не расходует квоту реальной оценки.
|
||||
|
||||
Повтор команды с тем же ключом и телом возвращает сохраненный ответ в течение 24 часов. Повтор ключа с другим телом возвращает 422; недоступный банк или исчерпанная квота - 409 `state_conflict`. PostgreSQL сериализует проверку квоты и изменения сессии, а доменное время берется после ожидания блокировок. Миграция 24 добавляет попытки, экземпляры вопросов, учебные привязки и сохраненные ответы команд; ее откат удаляет эти данные.
|
||||
|
||||
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Присвоение категории остается отдельной работой; базовый порог не подтверждает калибровку.
|
||||
|
||||
## Сигналы прохождения оценки
|
||||
|
||||
Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки.
|
||||
|
||||
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Сбор событий браузером и их интерпретация относятся к отдельной работе.
|
||||
|
||||
## Анонимная проекция профиля
|
||||
|
||||
Проекция для организации использует HMAC-псевдонимы с разделением назначений ключей, закрытый справочник навыков, диапазоны стажа и явно выбранные поля публикации. Подтвержденные категории и самооценка разделены. Контакты, работодатели, свободный текст, точная зарплата и идентификаторы аккаунта исключены. Пересекающиеся периоды работы учитываются один раз.
|
||||
|
||||
Репозиторий проверяет актуальную публикацию по C2 и скрытые организации до построения группы. Полные комбинации видимых признаков, которым соответствуют меньше пяти кандидатов, обобщаются или скрываются. Это снижает риск идентификации, но не гарантирует анонимность. Приватный псевдоним предпросмотра владельца использует отдельное назначение. Категория и денежная совместимость отсутствуют до получения данных от авторитетного источника; заявленный грейд не заменяет подтверждение.
|
||||
|
||||
Кандидат читает настройки через `GET /api/v1/me/privacy`, предпросмотр - через `GET /api/v1/me/privacy/preview`, историю изменений - через `GET /api/v1/me/privacy/history`, а просмотры карточки - через `GET /api/v1/me/privacy/access-history`. Скрытые компании доступны через `GET /api/v1/me/privacy/hidden-organizations` и меняются через `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Публикация и статус поиска меняются через `PUT /api/v1/me/privacy/publication` и `PUT /api/v1/me/privacy/search-status`. Данные доступны только из текущей сессии кандидата, ответы имеют `Cache-Control: no-store`, а изменения требуют CSRF-токен сессии и точный разрешенный Origin. C2, публикация, статус поиска и скрытые компании независимы: один параметр не включает остальные. Поиск остается заявлением кандидата, а не согласием.
|
||||
|
||||
Работодатель с подтвержденной учетной записью и активным членством читает карточку по `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Каждый запрос заново проверяет членство, действующее C2, публикацию, скрытие для этой компании и минимальный размер группы; успешный просмотр и расход квоты записываются в одной транзакции. Закрытая, отозванная, скрытая или подавленная карточка не раскрывается и отвечает так же, как неизвестный псевдоним. Кандидат видит записи об успешных просмотрах карточки в своей истории доступа. Операция чтения контактов и управление грантами C4 пока недоступны; карточка контактов не содержит.
|
||||
|
||||
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
@@ -4,17 +4,23 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -22,13 +28,15 @@ const (
|
||||
fixtureTimeout = 90 * time.Second
|
||||
maxFixtureFamilies = 200
|
||||
|
||||
fixtureBundleName = "e2e-questionnaire-bank"
|
||||
fixtureAuthor = "operator:questionnaire-fixture-author"
|
||||
fixtureReviewer = "operator:questionnaire-fixture-reviewer"
|
||||
fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher")
|
||||
fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener")
|
||||
fixtureFamilyStem = "e2e-questionnaire-family-"
|
||||
fixtureCategory = domain.AssessmentCategory("backend")
|
||||
fixtureBundleName = "e2e-questionnaire-bank"
|
||||
fixtureAuthor = "operator:questionnaire-fixture-author"
|
||||
fixtureReviewer = "operator:questionnaire-fixture-reviewer"
|
||||
fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher")
|
||||
fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener")
|
||||
fixtureFamilyStem = "e2e-questionnaire-family-"
|
||||
fixtureCategory = domain.AssessmentCategory("backend")
|
||||
trainingFamilyStem = "e2e-express-family-"
|
||||
trainingCategory = "e2e-express"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -85,9 +93,16 @@ func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if occupied {
|
||||
return errors.New(location + " refuses existing backend openings or published families")
|
||||
}
|
||||
trainingOccupied, err := questionnaireTrainingBankOccupied(ctx, pool)
|
||||
if err != nil {
|
||||
return errors.New(location + " could not inspect training bank state")
|
||||
}
|
||||
if trainingOccupied {
|
||||
return errors.New(location + " refuses an existing training binding or published families")
|
||||
}
|
||||
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
currentPolicy, err := currentProductPolicy(ctx, transactor)
|
||||
currentPolicy, err := publishFixturePolicy(ctx, transactor)
|
||||
if err != nil {
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return errors.New(location + " requires a current product assessment policy")
|
||||
@@ -122,6 +137,156 @@ func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
}); err != nil {
|
||||
return errors.New(location + " could not open the reviewed catalog mapping")
|
||||
}
|
||||
if err := seedQuestionnaireTrainingBank(ctx, pool, bank, currentPolicy); err != nil {
|
||||
return errors.New(location + " could not seed the reviewed express training bank")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func questionnaireTrainingBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) {
|
||||
var occupied bool
|
||||
err := pool.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM assessment_training_bank_bindings WHERE category = $1
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM assessment_families
|
||||
WHERE category = $1 AND family_key LIKE $2
|
||||
)`, trainingCategory, trainingFamilyStem+"%").Scan(&occupied)
|
||||
return occupied, err
|
||||
}
|
||||
|
||||
func seedQuestionnaireTrainingBank(
|
||||
ctx context.Context,
|
||||
pool *pgxpool.Pool,
|
||||
bank *assessment.Bank,
|
||||
productPolicy domain.PolicyVersion,
|
||||
) error {
|
||||
trainingPolicy := productPolicy.Policy().Assessment.Training
|
||||
if trainingPolicy == nil {
|
||||
return errors.New("current product policy has no explicit training mode")
|
||||
}
|
||||
count := int(trainingPolicy.DemoExpressItemCount)
|
||||
if count < 1 || count > maxFixtureFamilies {
|
||||
return errors.New("training item count is outside the fixture limit")
|
||||
}
|
||||
bundle, err := reviewedTrainingBundle(count)
|
||||
if err != nil {
|
||||
return errors.New("reviewed training family fixture is invalid")
|
||||
}
|
||||
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
|
||||
return errors.New("could not import reviewed training families")
|
||||
}
|
||||
for _, family := range bundle.Families {
|
||||
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
||||
return errors.New("could not publish reviewed training family")
|
||||
}
|
||||
}
|
||||
return seedQuestionnaireTrainingBinding(ctx, pool, productPolicy.ID().UUID(), bundle.Category, count)
|
||||
}
|
||||
|
||||
func reviewedTrainingBundle(count int) (assessment.Bundle, error) {
|
||||
bundle, err := reviewedQuestionnaireBundle(count)
|
||||
if err != nil {
|
||||
return assessment.Bundle{}, err
|
||||
}
|
||||
bundle.Name = "e2e-express-training-bank"
|
||||
bundle.Category = trainingCategory
|
||||
for index := range bundle.Families {
|
||||
bundle.Families[index].Key = fmt.Sprintf("%s%02d", trainingFamilyStem, index+1)
|
||||
bundle.Families[index].Specialization = "rate-limiting"
|
||||
}
|
||||
if _, err := bundle.Drafts(); err != nil {
|
||||
return assessment.Bundle{}, err
|
||||
}
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func seedQuestionnaireTrainingBinding(
|
||||
ctx context.Context,
|
||||
pool *pgxpool.Pool,
|
||||
policyID uuid.UUID,
|
||||
category string,
|
||||
itemCount int,
|
||||
) error {
|
||||
type manifestEntry struct {
|
||||
FamilyKey string `json:"family_key"`
|
||||
Version int32 `json:"version"`
|
||||
ContentSHA256 string `json:"content_sha256"`
|
||||
}
|
||||
type familyRecord struct {
|
||||
ID uuid.UUID
|
||||
Entry manifestEntry
|
||||
Hash []byte
|
||||
}
|
||||
rows, err := pool.Query(ctx, `
|
||||
SELECT id, family_key, version, content_sha256
|
||||
FROM assessment_families
|
||||
WHERE category=$1 AND lifecycle='published'
|
||||
ORDER BY family_key, version`, category)
|
||||
if err != nil {
|
||||
return errors.New("could not read published training families")
|
||||
}
|
||||
var families []familyRecord
|
||||
for rows.Next() {
|
||||
var family familyRecord
|
||||
if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil {
|
||||
rows.Close()
|
||||
return errors.New("could not read a published training family")
|
||||
}
|
||||
family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash)
|
||||
families = append(families, family)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return errors.New("could not finish reading training families")
|
||||
}
|
||||
rows.Close()
|
||||
if len(families) != itemCount {
|
||||
return errors.New("published training family count does not match policy")
|
||||
}
|
||||
entries := make([]manifestEntry, len(families))
|
||||
canonical := []byte("lincodex.assessment.category-manifest.v1\x00")
|
||||
for index, family := range families {
|
||||
if len(family.Entry.FamilyKey) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size {
|
||||
return errors.New("training family manifest entry is outside the supported range")
|
||||
}
|
||||
entries[index] = family.Entry
|
||||
key := []byte(family.Entry.FamilyKey)
|
||||
canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key)))
|
||||
canonical = append(canonical, key...)
|
||||
canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version))
|
||||
canonical = append(canonical, family.Hash...)
|
||||
}
|
||||
manifest, err := json.Marshal(entries)
|
||||
if err != nil {
|
||||
return errors.New("could not encode training family manifest")
|
||||
}
|
||||
manifestHash := sha256.Sum256(canonical)
|
||||
transaction, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return errors.New("could not begin training binding transaction")
|
||||
}
|
||||
defer transaction.Rollback(ctx)
|
||||
bindingID := uuid.New()
|
||||
if _, err := transaction.Exec(ctx, `
|
||||
INSERT INTO assessment_training_bank_bindings (
|
||||
id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`,
|
||||
bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil {
|
||||
return errors.New("could not insert the training binding")
|
||||
}
|
||||
for index, family := range families {
|
||||
if _, err := transaction.Exec(ctx, `
|
||||
INSERT INTO assessment_training_bank_binding_families (
|
||||
binding_id, ordinal, family_id, family_key, family_version, content_sha256
|
||||
) VALUES ($1,$2,$3,$4,$5,$6)`,
|
||||
bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil {
|
||||
return errors.New("could not add a training binding family")
|
||||
}
|
||||
}
|
||||
if err := transaction.Commit(ctx); err != nil {
|
||||
return errors.New("could not commit the training binding")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -129,7 +294,7 @@ func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, e
|
||||
return domain.NewAssessmentCategoryCatalogMetadata(
|
||||
domain.SpecializationBackend,
|
||||
domain.GradeJunior,
|
||||
[]domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
[]domain.TaskLanguageCode{domain.TaskLanguageGo, domain.TaskLanguagePython},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -149,14 +314,38 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (
|
||||
return occupied, err
|
||||
}
|
||||
|
||||
func currentProductPolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
|
||||
// The isolated browser fixture opts into the extended demo policy explicitly.
|
||||
// Normal startup still seeds V1, and an operator's policy must never be replaced.
|
||||
func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
|
||||
initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
|
||||
Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.PolicyVersion{}, err
|
||||
}
|
||||
var version domain.PolicyVersion
|
||||
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
version, err = unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime)
|
||||
current, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Kind() != domain.PolicyKindDemo || current.DocumentHash() != initial.DocumentHash() ||
|
||||
current.Version() != 1 || current.ID() != latest.ID() {
|
||||
return errors.New("questionnaire fixture refuses an operator-owned product policy")
|
||||
}
|
||||
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
|
||||
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV2(),
|
||||
})
|
||||
return err
|
||||
})
|
||||
return version, err
|
||||
|
||||
@@ -79,8 +79,9 @@ func TestQuestionnaireCatalogMetadataUsesTheReviewedE2EProjection(t *testing.T)
|
||||
t.Fatalf("questionnaireCatalogMetadata() error = %v", err)
|
||||
}
|
||||
if metadata.Specialization() != domain.SpecializationBackend || metadata.Grade() != domain.GradeJunior ||
|
||||
len(metadata.TaskLanguages()) != 1 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo {
|
||||
t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go",
|
||||
len(metadata.TaskLanguages()) != 2 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo ||
|
||||
metadata.TaskLanguages()[1] != domain.TaskLanguagePython {
|
||||
t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go+Python",
|
||||
metadata.Specialization(), metadata.Grade(), metadata.TaskLanguages())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
-- +goose Up
|
||||
-- Assessment attempts pin their product policy, category opening or separate
|
||||
-- training source, and generated item variants. Candidate answers are stored
|
||||
-- separately from the immutable variant and never appear in idempotency rows.
|
||||
|
||||
CREATE TABLE assessment_training_bank_bindings (
|
||||
id uuid NOT NULL,
|
||||
category text NOT NULL,
|
||||
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
|
||||
item_count integer NOT NULL,
|
||||
manifest_sha256 bytea NOT NULL,
|
||||
family_manifest jsonb NOT NULL,
|
||||
reviewed_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_training_bank_bindings_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_training_bank_bindings_policy_manifest_key UNIQUE (
|
||||
category, product_policy_version_id, manifest_sha256
|
||||
),
|
||||
CONSTRAINT assessment_training_bank_bindings_category_format CHECK (
|
||||
category ~ '^[a-z][a-z0-9-]{1,47}$'
|
||||
),
|
||||
CONSTRAINT assessment_training_bank_bindings_item_count CHECK (
|
||||
item_count BETWEEN 1 AND 20
|
||||
),
|
||||
CONSTRAINT assessment_training_bank_bindings_manifest_hash CHECK (
|
||||
octet_length(manifest_sha256) = 32
|
||||
),
|
||||
CONSTRAINT assessment_training_bank_bindings_manifest_object CHECK (
|
||||
jsonb_typeof(family_manifest) = 'array'
|
||||
),
|
||||
CONSTRAINT assessment_training_bank_bindings_reviewer CHECK (
|
||||
char_length(reviewed_by) <= 128
|
||||
AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE assessment_training_bank_binding_families (
|
||||
binding_id uuid NOT NULL REFERENCES assessment_training_bank_bindings (id),
|
||||
ordinal integer NOT NULL,
|
||||
family_id uuid NOT NULL REFERENCES assessment_families (id),
|
||||
family_key text NOT NULL,
|
||||
family_version integer NOT NULL,
|
||||
content_sha256 bytea NOT NULL,
|
||||
CONSTRAINT assessment_training_bank_binding_families_pkey PRIMARY KEY (binding_id, ordinal),
|
||||
CONSTRAINT assessment_training_bank_binding_families_family_key UNIQUE (binding_id, family_key),
|
||||
CONSTRAINT assessment_training_bank_binding_families_ordinal CHECK (ordinal > 0),
|
||||
CONSTRAINT assessment_training_bank_binding_families_version CHECK (family_version > 0),
|
||||
CONSTRAINT assessment_training_bank_binding_families_hash CHECK (octet_length(content_sha256) = 32)
|
||||
);
|
||||
|
||||
-- A binding is accepted only for an explicit training policy and a category
|
||||
-- not already opened for real assessments. The category advisory lock is the
|
||||
-- same lock taken by the bank's publish, retire, and opening operations.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
policy_item_count integer;
|
||||
current_product_policy_id uuid;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.assessment.category:' || NEW.category, 0)
|
||||
);
|
||||
|
||||
SELECT (document #>> '{assessment,training,demo_express_item_count}')::integer
|
||||
INTO policy_item_count
|
||||
FROM policy_versions
|
||||
WHERE id = NEW.product_policy_version_id
|
||||
AND policy_key = 'product';
|
||||
|
||||
IF policy_item_count IS NULL OR policy_item_count <> NEW.item_count THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_policy',
|
||||
MESSAGE = 'training binding does not match explicit product policy';
|
||||
END IF;
|
||||
|
||||
SELECT id INTO current_product_policy_id
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= clock_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1;
|
||||
IF current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_current_policy',
|
||||
MESSAGE = 'training binding must pin the current product policy';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM assessment_category_openings WHERE category = NEW.category
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint',
|
||||
MESSAGE = 'training category already has a real opening';
|
||||
END IF;
|
||||
|
||||
NEW.created_at := clock_timestamp();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_training_binding_guard
|
||||
BEFORE INSERT ON assessment_training_bank_bindings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_guard();
|
||||
|
||||
-- A real opening cannot consume a category reserved for training. Taking the
|
||||
-- same lock in both directions closes the race between binding and opening.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_real_opening_rejects_training_category() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.assessment.category:' || NEW.category, 0)
|
||||
);
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM assessment_training_bank_bindings WHERE category = NEW.category
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint',
|
||||
MESSAGE = 'real opening cannot use a training category';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_real_opening_rejects_training_category
|
||||
BEFORE INSERT ON assessment_category_openings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_real_opening_rejects_training_category();
|
||||
|
||||
-- Each pinned training family must be reviewed, published, and in the
|
||||
-- category reserved by its binding. No family row can later be replaced.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_family_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
binding assessment_training_bank_bindings%ROWTYPE;
|
||||
family assessment_families%ROWTYPE;
|
||||
BEGIN
|
||||
SELECT * INTO STRICT binding
|
||||
FROM assessment_training_bank_bindings
|
||||
WHERE id = NEW.binding_id;
|
||||
|
||||
SELECT * INTO STRICT family
|
||||
FROM assessment_families
|
||||
WHERE id = NEW.family_id;
|
||||
|
||||
IF family.category <> binding.category OR family.family_key <> NEW.family_key OR
|
||||
family.version <> NEW.family_version OR family.content_sha256 <> NEW.content_sha256 OR
|
||||
family.lifecycle <> 'published' OR family.review_status <> 'approved' OR
|
||||
family.reviewer IS NULL OR family.author = family.reviewer THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_family_reviewed',
|
||||
MESSAGE = 'training family is not an approved published member of the binding';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_training_binding_family_guard
|
||||
BEFORE INSERT ON assessment_training_bank_binding_families
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_guard();
|
||||
|
||||
-- The family rows and canonical manifest must agree when the transaction
|
||||
-- commits; inserts may arrive after the binding header in the same unit.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_complete() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
binding_id_value uuid;
|
||||
BEGIN
|
||||
binding_id_value := NEW.id;
|
||||
PERFORM assessment_training_binding_assert_complete(binding_id_value);
|
||||
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_assert_complete(binding_id_value uuid) RETURNS void
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
expected_count integer;
|
||||
actual_count integer;
|
||||
actual_manifest jsonb;
|
||||
family_manifest_value jsonb;
|
||||
BEGIN
|
||||
SELECT item_count, family_manifest INTO expected_count, family_manifest_value
|
||||
FROM assessment_training_bank_bindings
|
||||
WHERE id = binding_id_value;
|
||||
|
||||
SELECT count(*)::integer INTO actual_count
|
||||
FROM assessment_training_bank_binding_families
|
||||
WHERE binding_id = binding_id_value;
|
||||
|
||||
IF actual_count <> expected_count OR jsonb_array_length(family_manifest_value) <> expected_count THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_complete',
|
||||
MESSAGE = 'training binding family count is incomplete';
|
||||
END IF;
|
||||
|
||||
SELECT COALESCE(jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family_key,
|
||||
'version', family_version,
|
||||
'content_sha256', encode(content_sha256, 'hex')
|
||||
) ORDER BY family_key, family_version
|
||||
), '[]'::jsonb) INTO actual_manifest
|
||||
FROM assessment_training_bank_binding_families
|
||||
WHERE binding_id = binding_id_value;
|
||||
|
||||
IF actual_manifest <> family_manifest_value THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_manifest',
|
||||
MESSAGE = 'training binding manifest does not match its families';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- The deferred child trigger prevents an extra family from being appended
|
||||
-- after the header's own deferred completeness check was queued.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_family_complete() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM assessment_training_binding_assert_complete(NEW.binding_id);
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE CONSTRAINT TRIGGER assessment_training_binding_complete
|
||||
AFTER INSERT ON assessment_training_bank_bindings
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_complete();
|
||||
|
||||
CREATE CONSTRAINT TRIGGER assessment_training_binding_family_complete
|
||||
AFTER INSERT ON assessment_training_bank_binding_families
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_complete();
|
||||
|
||||
-- Bindings and their family manifest are immutable once stored.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_training_binding_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_training_binding_immutable',
|
||||
MESSAGE = 'training bank bindings are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_training_binding_refuse_update_delete
|
||||
BEFORE UPDATE OR DELETE ON assessment_training_bank_bindings
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change();
|
||||
|
||||
CREATE TRIGGER assessment_training_binding_family_refuse_update_delete
|
||||
BEFORE UPDATE OR DELETE ON assessment_training_bank_binding_families
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change();
|
||||
|
||||
CREATE TABLE assessment_attempts (
|
||||
id uuid NOT NULL,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
kind text NOT NULL,
|
||||
mode text NOT NULL,
|
||||
state text NOT NULL,
|
||||
outcome text,
|
||||
bank_category text NOT NULL,
|
||||
specialization text,
|
||||
target_grade text,
|
||||
task_language text,
|
||||
root_attempt_id uuid NOT NULL,
|
||||
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
|
||||
product_policy_version integer NOT NULL,
|
||||
grading_policy_version_id uuid REFERENCES policy_versions (id),
|
||||
opening_id uuid REFERENCES assessment_category_openings (id),
|
||||
opening_manifest_sha256 bytea,
|
||||
training_binding_id uuid REFERENCES assessment_training_bank_bindings (id),
|
||||
training_manifest_sha256 bytea,
|
||||
bank_version text NOT NULL,
|
||||
algorithm_version text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
chain_deadline timestamptz,
|
||||
idle_timeout_seconds integer NOT NULL,
|
||||
max_sessions integer NOT NULL,
|
||||
sessions_used integer NOT NULL,
|
||||
session_started_at timestamptz NOT NULL,
|
||||
last_activity_at timestamptz NOT NULL,
|
||||
version bigint NOT NULL,
|
||||
ended_at timestamptz,
|
||||
CONSTRAINT assessment_attempts_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_attempts_id_owner_key UNIQUE (id, user_id),
|
||||
CONSTRAINT assessment_attempts_owner_root_fk FOREIGN KEY (root_attempt_id, user_id)
|
||||
REFERENCES assessment_attempts (id, user_id) DEFERRABLE INITIALLY DEFERRED,
|
||||
CONSTRAINT assessment_attempts_kind CHECK (kind IN ('root', 'corrective', 'demo_express')),
|
||||
CONSTRAINT assessment_attempts_mode CHECK (mode IN ('demo_basic', 'adaptive', 'demo_express')),
|
||||
CONSTRAINT assessment_attempts_state CHECK (
|
||||
state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize',
|
||||
'completed', 'expired', 'insufficient_bank')
|
||||
),
|
||||
CONSTRAINT assessment_attempts_outcome CHECK (
|
||||
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined')
|
||||
),
|
||||
CONSTRAINT assessment_attempts_track CHECK (
|
||||
(
|
||||
kind IN ('root', 'corrective')
|
||||
AND mode IN ('demo_basic', 'adaptive')
|
||||
AND specialization IS NOT NULL
|
||||
AND specialization ~ '^[a-z][a-z0-9_-]{1,47}$'
|
||||
AND target_grade IS NOT NULL
|
||||
AND target_grade IN ('intern', 'junior', 'middle', 'senior')
|
||||
AND (task_language IS NULL OR task_language IN ('go', 'python'))
|
||||
AND grading_policy_version_id IS NOT NULL
|
||||
AND opening_id IS NOT NULL
|
||||
AND opening_manifest_sha256 IS NOT NULL
|
||||
AND octet_length(opening_manifest_sha256) = 32
|
||||
AND training_binding_id IS NULL
|
||||
AND training_manifest_sha256 IS NULL
|
||||
AND chain_deadline IS NOT NULL
|
||||
AND (
|
||||
(kind = 'root' AND root_attempt_id = id)
|
||||
OR (kind = 'corrective' AND root_attempt_id <> id)
|
||||
)
|
||||
) OR (
|
||||
kind = 'demo_express'
|
||||
AND mode = 'demo_express'
|
||||
AND specialization IS NULL AND target_grade IS NULL AND task_language IS NULL
|
||||
AND root_attempt_id = id
|
||||
AND grading_policy_version_id IS NULL
|
||||
AND opening_id IS NULL AND opening_manifest_sha256 IS NULL
|
||||
AND training_binding_id IS NOT NULL
|
||||
AND training_manifest_sha256 IS NOT NULL
|
||||
AND octet_length(training_manifest_sha256) = 32
|
||||
AND chain_deadline IS NULL
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_attempts_policy_version_positive CHECK (product_policy_version > 0),
|
||||
CONSTRAINT assessment_attempts_version_positive CHECK (version > 0),
|
||||
CONSTRAINT assessment_attempts_session_limits CHECK (
|
||||
idle_timeout_seconds BETWEEN 60 AND 86400
|
||||
AND max_sessions BETWEEN 1 AND 10
|
||||
AND sessions_used BETWEEN 1 AND max_sessions
|
||||
),
|
||||
CONSTRAINT assessment_attempts_timestamps CHECK (
|
||||
created_at <= updated_at
|
||||
AND created_at <= session_started_at
|
||||
AND session_started_at <= last_activity_at
|
||||
AND last_activity_at <= updated_at
|
||||
AND expires_at > created_at
|
||||
AND (chain_deadline IS NULL OR (chain_deadline > created_at AND expires_at <= chain_deadline))
|
||||
AND (ended_at IS NULL OR (ended_at >= created_at AND ended_at >= last_activity_at AND ended_at <= updated_at))
|
||||
),
|
||||
CONSTRAINT assessment_attempts_state_stamp CHECK (
|
||||
(state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
AND outcome IS NULL AND ended_at IS NULL)
|
||||
OR (state IN ('expired', 'insufficient_bank') AND outcome IS NULL AND ended_at IS NOT NULL)
|
||||
OR (state = 'completed' AND outcome IS NOT NULL AND ended_at IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
-- A corrective attempt can only attach to an eligible terminal root owned by
|
||||
-- the same candidate and for the same specialization. The application still
|
||||
-- validates the full chain order and descending grades inside its transaction.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_root_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
root_attempt assessment_attempts%ROWTYPE;
|
||||
BEGIN
|
||||
IF NEW.kind <> 'corrective' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
SELECT * INTO root_attempt
|
||||
FROM assessment_attempts
|
||||
WHERE id = NEW.root_attempt_id
|
||||
FOR SHARE;
|
||||
|
||||
IF NOT FOUND OR root_attempt.kind <> 'root' OR root_attempt.user_id <> NEW.user_id OR
|
||||
root_attempt.specialization <> NEW.specialization OR
|
||||
root_attempt.state NOT IN ('expired', 'completed') OR
|
||||
(root_attempt.state = 'completed' AND root_attempt.outcome NOT IN ('not_confirmed', 'not_determined')) OR
|
||||
root_attempt.chain_deadline IS NULL OR root_attempt.chain_deadline <= NEW.created_at OR
|
||||
NEW.chain_deadline <> root_attempt.chain_deadline THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_root_eligibility',
|
||||
MESSAGE = 'corrective attempt does not continue an eligible root';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_root_guard
|
||||
BEFORE INSERT OR UPDATE ON assessment_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_root_guard();
|
||||
|
||||
-- Verify the row refers to the exact current, reviewed opening or separately
|
||||
-- reviewed training binding chosen by the transaction-bound bank service.
|
||||
-- The caller holds the category advisory lock while it resolves and inserts.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_bank_pin_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
pinned_category text;
|
||||
pinned_product_policy_id uuid;
|
||||
pinned_grading_policy_id uuid;
|
||||
pinned_manifest_sha256 bytea;
|
||||
current_product_policy_id uuid;
|
||||
current_product_policy_version integer;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.assessment.category:' || NEW.bank_category, 0)
|
||||
);
|
||||
|
||||
SELECT id, version INTO current_product_policy_id, current_product_policy_version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= NEW.created_at
|
||||
ORDER BY version DESC
|
||||
LIMIT 1;
|
||||
IF NOT FOUND OR current_product_policy_id <> NEW.product_policy_version_id OR
|
||||
current_product_policy_version <> NEW.product_policy_version THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_product_policy_pin',
|
||||
MESSAGE = 'attempt must pin the effective product policy';
|
||||
END IF;
|
||||
|
||||
IF NEW.kind = 'demo_express' THEN
|
||||
SELECT category, product_policy_version_id, manifest_sha256
|
||||
INTO pinned_category, pinned_product_policy_id, pinned_manifest_sha256
|
||||
FROM assessment_training_bank_bindings
|
||||
WHERE id = NEW.training_binding_id;
|
||||
|
||||
IF NOT FOUND OR pinned_category <> NEW.bank_category OR
|
||||
pinned_product_policy_id <> NEW.product_policy_version_id OR
|
||||
pinned_manifest_sha256 <> NEW.training_manifest_sha256 THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_training_binding_pin',
|
||||
MESSAGE = 'training attempt does not match its reviewed binding';
|
||||
END IF;
|
||||
ELSE
|
||||
SELECT opening.category, opening.policy_version_id, catalog.published_manifest_sha256
|
||||
INTO pinned_category, pinned_grading_policy_id, pinned_manifest_sha256
|
||||
FROM assessment_category_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS catalog ON catalog.opening_id = opening.id
|
||||
WHERE opening.id = NEW.opening_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM assessment_category_openings AS newer
|
||||
WHERE newer.category = opening.category
|
||||
AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id)
|
||||
);
|
||||
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin',
|
||||
MESSAGE = 'real attempt opening is not current and reviewed';
|
||||
END IF;
|
||||
|
||||
IF pinned_category <> NEW.bank_category OR
|
||||
pinned_grading_policy_id <> NEW.grading_policy_version_id OR
|
||||
pinned_manifest_sha256 <> NEW.opening_manifest_sha256 OR
|
||||
current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin',
|
||||
MESSAGE = 'real attempt does not match its current reviewed opening';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_bank_pin_guard
|
||||
BEFORE INSERT ON assessment_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_bank_pin_guard();
|
||||
|
||||
-- Commands may update lifecycle and session fields, but an attempt's owner,
|
||||
-- selection, policy/bank pins, and deadlines never change after creation.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_immutable_pins_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (to_jsonb(NEW) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' -
|
||||
'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') IS DISTINCT FROM
|
||||
(to_jsonb(OLD) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' -
|
||||
'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') OR
|
||||
NEW.version <> OLD.version + 1 OR NEW.updated_at < OLD.updated_at THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_pins_immutable',
|
||||
MESSAGE = 'assessment attempt pins are immutable and every transition increments version';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_immutable_pins_guard
|
||||
BEFORE UPDATE ON assessment_attempts
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_immutable_pins_guard();
|
||||
|
||||
CREATE INDEX assessment_attempts_candidate_created_idx
|
||||
ON assessment_attempts (user_id, created_at DESC, id DESC);
|
||||
|
||||
-- Corrective attempts belong to their root chain and share its specialization.
|
||||
CREATE INDEX assessment_attempts_root_chain_idx
|
||||
ON assessment_attempts (root_attempt_id, created_at, id);
|
||||
|
||||
-- Active work is unique per candidate and real specialization. All nonterminal
|
||||
-- lifecycle states stay in the index as later commands add them.
|
||||
CREATE UNIQUE INDEX assessment_attempts_one_active_real_specialization
|
||||
ON assessment_attempts (user_id, specialization)
|
||||
WHERE kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize');
|
||||
|
||||
CREATE UNIQUE INDEX assessment_attempts_one_active_training
|
||||
ON assessment_attempts (user_id)
|
||||
WHERE kind = 'demo_express'
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize');
|
||||
|
||||
CREATE TABLE assessment_attempt_items (
|
||||
id uuid NOT NULL,
|
||||
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
|
||||
ordinal integer NOT NULL,
|
||||
family_id uuid NOT NULL REFERENCES assessment_families (id),
|
||||
family_key text NOT NULL,
|
||||
family_version integer NOT NULL,
|
||||
family_content_sha256 bytea NOT NULL,
|
||||
variant jsonb NOT NULL,
|
||||
-- Keep canonical UTF-8 JSON bytes so schema-valid strings containing NUL
|
||||
-- survive PostgreSQL storage; jsonb rejects \u0000 values.
|
||||
answer bytea,
|
||||
answered_at timestamptz,
|
||||
CONSTRAINT assessment_attempt_items_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_attempt_items_ordinal_key UNIQUE (attempt_id, ordinal),
|
||||
CONSTRAINT assessment_attempt_items_family_key UNIQUE (attempt_id, family_key),
|
||||
CONSTRAINT assessment_attempt_items_ordinal CHECK (ordinal BETWEEN 1 AND 220),
|
||||
CONSTRAINT assessment_attempt_items_family_version CHECK (family_version > 0),
|
||||
CONSTRAINT assessment_attempt_items_family_hash CHECK (octet_length(family_content_sha256) = 32),
|
||||
CONSTRAINT assessment_attempt_items_variant_object CHECK (
|
||||
jsonb_typeof(variant) = 'object' AND octet_length(variant::text) <= 1048576
|
||||
),
|
||||
CONSTRAINT assessment_attempt_items_answer_bound CHECK (
|
||||
answer IS NULL OR octet_length(answer) <= 524288
|
||||
),
|
||||
CONSTRAINT assessment_attempt_items_answer_stamp CHECK (
|
||||
(answer IS NULL) = (answered_at IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_attempt_items_family_usage_idx
|
||||
ON assessment_attempt_items (family_id, attempt_id);
|
||||
|
||||
-- A variant's identity and content are fixed at creation. Answering is a
|
||||
-- one-way NULL -> value transition; replay is handled by the attempt outcome.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_item_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
attempt assessment_attempts%ROWTYPE;
|
||||
family assessment_families%ROWTYPE;
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
IF pg_trigger_depth() <= 1 THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_delete_forbidden',
|
||||
MESSAGE = 'assessment items can be removed only by account or attempt cascade';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
|
||||
SELECT * INTO STRICT attempt
|
||||
FROM assessment_attempts WHERE id = NEW.attempt_id;
|
||||
SELECT * INTO STRICT family
|
||||
FROM assessment_families WHERE id = NEW.family_id;
|
||||
|
||||
IF family.family_key <> NEW.family_key OR family.version <> NEW.family_version OR
|
||||
family.content_sha256 <> NEW.family_content_sha256 OR family.category <> attempt.bank_category THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_pin',
|
||||
MESSAGE = 'assessment item family pin is inconsistent';
|
||||
END IF;
|
||||
|
||||
IF TG_OP = 'UPDATE' THEN
|
||||
IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.ordinal <> OLD.ordinal OR
|
||||
NEW.family_id <> OLD.family_id OR NEW.family_key <> OLD.family_key OR
|
||||
NEW.family_version <> OLD.family_version OR NEW.family_content_sha256 <> OLD.family_content_sha256 OR
|
||||
NEW.variant <> OLD.variant OR OLD.answer IS NOT NULL OR NEW.answer IS NULL OR NEW.answered_at IS NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_immutable',
|
||||
MESSAGE = 'assessment item identity and variant are immutable';
|
||||
END IF;
|
||||
IF NEW.answered_at < attempt.created_at OR NEW.answered_at >= attempt.expires_at THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_time',
|
||||
MESSAGE = 'assessment answer time is outside the attempt deadline';
|
||||
END IF;
|
||||
ELSIF TG_OP = 'INSERT' THEN
|
||||
IF family.lifecycle <> 'published' OR family.review_status <> 'approved' OR
|
||||
family.reviewer IS NULL OR family.author = family.reviewer THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_reviewed',
|
||||
MESSAGE = 'assessment item family is not approved and published';
|
||||
END IF;
|
||||
IF attempt.kind = 'demo_express' AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM assessment_training_bank_binding_families AS member
|
||||
WHERE member.binding_id = attempt.training_binding_id
|
||||
AND member.family_id = NEW.family_id
|
||||
AND member.family_key = NEW.family_key
|
||||
AND member.family_version = NEW.family_version
|
||||
AND member.content_sha256 = NEW.family_content_sha256
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_training_member',
|
||||
MESSAGE = 'training attempt item is not in its pinned binding';
|
||||
END IF;
|
||||
IF NEW.answer IS NOT NULL OR NEW.answered_at IS NOT NULL THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_initial',
|
||||
MESSAGE = 'assessment items start without candidate answers';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_item_guard
|
||||
BEFORE INSERT OR UPDATE OR DELETE ON assessment_attempt_items
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_item_guard();
|
||||
|
||||
-- Every idempotent response is a typed, allowlisted public read-model snapshot.
|
||||
-- It never contains candidate answers, reference answers, seeds, family keys,
|
||||
-- or private policy and opening identifiers.
|
||||
CREATE TABLE assessment_attempt_idempotency_outcomes (
|
||||
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
|
||||
operation text NOT NULL,
|
||||
status_code smallint NOT NULL,
|
||||
problem_code text,
|
||||
response_snapshot jsonb,
|
||||
response_schema_version smallint NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_pkey PRIMARY KEY (scope_hash),
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')),
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
|
||||
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL)
|
||||
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
),
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_response CHECK (
|
||||
response_snapshot IS NULL OR (
|
||||
jsonb_typeof(response_snapshot) = 'object'
|
||||
AND octet_length(response_snapshot::text) <= 4194304
|
||||
)
|
||||
),
|
||||
CONSTRAINT assessment_attempt_idempotency_outcomes_schema CHECK (response_schema_version = 1)
|
||||
);
|
||||
|
||||
-- Keep committed command outcomes immutable; the generic 24-hour idempotency
|
||||
-- purge may still delete them by cascading from idempotency_records.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_idempotency_outcome_refuse_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_idempotency_outcome_immutable',
|
||||
MESSAGE = 'assessment idempotency outcomes are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_idempotency_outcome_refuse_update
|
||||
BEFORE UPDATE ON assessment_attempt_idempotency_outcomes
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_idempotency_outcome_refuse_update();
|
||||
|
||||
-- +goose Down
|
||||
DROP TRIGGER assessment_attempt_idempotency_outcome_refuse_update ON assessment_attempt_idempotency_outcomes;
|
||||
DROP FUNCTION assessment_attempt_idempotency_outcome_refuse_update();
|
||||
DROP TABLE assessment_attempt_idempotency_outcomes;
|
||||
|
||||
DROP TRIGGER assessment_attempt_item_guard ON assessment_attempt_items;
|
||||
DROP FUNCTION assessment_attempt_item_guard();
|
||||
DROP TABLE assessment_attempt_items;
|
||||
DROP TRIGGER assessment_attempt_root_guard ON assessment_attempts;
|
||||
DROP FUNCTION assessment_attempt_root_guard();
|
||||
DROP TRIGGER assessment_attempt_bank_pin_guard ON assessment_attempts;
|
||||
DROP FUNCTION assessment_attempt_bank_pin_guard();
|
||||
DROP TRIGGER assessment_attempt_immutable_pins_guard ON assessment_attempts;
|
||||
DROP FUNCTION assessment_attempt_immutable_pins_guard();
|
||||
DROP INDEX assessment_attempts_one_active_training;
|
||||
DROP INDEX assessment_attempts_one_active_real_specialization;
|
||||
DROP INDEX assessment_attempts_root_chain_idx;
|
||||
DROP INDEX assessment_attempts_candidate_created_idx;
|
||||
DROP TABLE assessment_attempts;
|
||||
|
||||
DROP TRIGGER assessment_training_binding_family_refuse_update_delete ON assessment_training_bank_binding_families;
|
||||
DROP TRIGGER assessment_training_binding_refuse_update_delete ON assessment_training_bank_bindings;
|
||||
DROP FUNCTION assessment_training_binding_refuse_change();
|
||||
DROP TRIGGER assessment_training_binding_complete ON assessment_training_bank_bindings;
|
||||
DROP TRIGGER assessment_training_binding_family_complete ON assessment_training_bank_binding_families;
|
||||
DROP FUNCTION assessment_training_binding_complete();
|
||||
DROP FUNCTION assessment_training_binding_family_complete();
|
||||
DROP FUNCTION assessment_training_binding_assert_complete(uuid);
|
||||
DROP TRIGGER assessment_training_binding_family_guard ON assessment_training_bank_binding_families;
|
||||
DROP FUNCTION assessment_training_binding_family_guard();
|
||||
DROP TRIGGER assessment_real_opening_rejects_training_category ON assessment_category_openings;
|
||||
DROP FUNCTION assessment_real_opening_rejects_training_category();
|
||||
DROP TRIGGER assessment_training_binding_guard ON assessment_training_bank_bindings;
|
||||
DROP FUNCTION assessment_training_binding_guard();
|
||||
DROP TABLE assessment_training_bank_binding_families;
|
||||
DROP TABLE assessment_training_bank_bindings;
|
||||
@@ -0,0 +1,385 @@
|
||||
-- +goose Up
|
||||
-- Account-owned support snapshots store only typed object references. The
|
||||
-- referenced records stay in their own bounded authorization scopes.
|
||||
CREATE SEQUENCE support_case_number_seq
|
||||
AS bigint
|
||||
MINVALUE 1
|
||||
MAXVALUE 9999999999
|
||||
NO CYCLE;
|
||||
|
||||
CREATE TABLE support_cases (
|
||||
id uuid NOT NULL,
|
||||
case_number text NOT NULL,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
case_type text NOT NULL,
|
||||
status text NOT NULL,
|
||||
description text NOT NULL,
|
||||
object_type text,
|
||||
object_id uuid,
|
||||
assessment_specialization text,
|
||||
assessment_grade text,
|
||||
complaint_reason text,
|
||||
rubric_version integer,
|
||||
rubric_opening_id uuid,
|
||||
rubric_policy_version_id uuid,
|
||||
target_business_days integer NOT NULL,
|
||||
target_due_at timestamptz NOT NULL,
|
||||
target_answered_at timestamptz,
|
||||
target_policy_version integer NOT NULL,
|
||||
target_calendar_version integer NOT NULL,
|
||||
decision_outcome text,
|
||||
decision_reason text,
|
||||
decision_at timestamptz,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT support_cases_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT support_cases_number_key UNIQUE (case_number),
|
||||
CONSTRAINT support_cases_number_format CHECK (
|
||||
case_number ~ '^SC-[0-9]{4}-[0-9]{6,10}$'
|
||||
AND substring(case_number FROM 4 FOR 4)::integer =
|
||||
EXTRACT(YEAR FROM created_at AT TIME ZONE 'UTC')::integer
|
||||
),
|
||||
CONSTRAINT support_cases_case_type CHECK (
|
||||
case_type IN ('support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment')
|
||||
),
|
||||
CONSTRAINT support_cases_status CHECK (
|
||||
status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed')
|
||||
),
|
||||
CONSTRAINT support_cases_description CHECK (
|
||||
char_length(description) BETWEEN 1 AND 4000
|
||||
),
|
||||
CONSTRAINT support_cases_object_pair CHECK (
|
||||
(object_type IS NULL) = (object_id IS NULL)
|
||||
),
|
||||
CONSTRAINT support_cases_object_type CHECK (
|
||||
object_type IS NULL OR object_type IN ('assessment_attempt', 'organization', 'invitation', 'support_case')
|
||||
),
|
||||
CONSTRAINT support_cases_assessment_target_pair CHECK (
|
||||
(assessment_specialization IS NULL) = (assessment_grade IS NULL)
|
||||
),
|
||||
CONSTRAINT support_cases_assessment_specialization CHECK (
|
||||
assessment_specialization IS NULL OR assessment_specialization IN (
|
||||
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
|
||||
'data_analyst', 'ds_ml', 'information_security', 'qa'
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_assessment_grade CHECK (
|
||||
assessment_grade IS NULL OR assessment_grade IN ('intern', 'junior', 'middle', 'senior')
|
||||
),
|
||||
CONSTRAINT support_cases_complaint_reason CHECK (
|
||||
complaint_reason IS NULL OR complaint_reason IN (
|
||||
'organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other'
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_rubric_version CHECK (rubric_version IS NULL OR rubric_version > 0),
|
||||
CONSTRAINT support_cases_rubric_opening_fkey FOREIGN KEY (rubric_opening_id)
|
||||
REFERENCES assessment_category_openings (id),
|
||||
CONSTRAINT support_cases_rubric_policy_version_fkey FOREIGN KEY (rubric_policy_version_id)
|
||||
REFERENCES policy_versions (id),
|
||||
CONSTRAINT support_cases_rubric_pin_shape CHECK (
|
||||
(rubric_version IS NULL AND rubric_opening_id IS NULL AND rubric_policy_version_id IS NULL)
|
||||
OR (
|
||||
case_type = 'manual_assessment'
|
||||
AND rubric_version IS NOT NULL
|
||||
AND rubric_opening_id IS NOT NULL
|
||||
AND rubric_policy_version_id IS NOT NULL
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_target_values CHECK (
|
||||
target_business_days BETWEEN 1 AND 60
|
||||
AND target_policy_version > 0
|
||||
AND target_calendar_version > 0
|
||||
AND target_due_at >= created_at
|
||||
AND (target_answered_at IS NULL OR target_answered_at >= created_at)
|
||||
),
|
||||
CONSTRAINT support_cases_decision_shape CHECK (
|
||||
(decision_outcome IS NULL AND decision_reason IS NULL AND decision_at IS NULL)
|
||||
OR (
|
||||
decision_outcome IS NOT NULL
|
||||
AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed')
|
||||
AND decision_reason IS NOT NULL
|
||||
AND char_length(decision_reason) BETWEEN 1 AND 4000
|
||||
AND decision_at IS NOT NULL
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_timestamps CHECK (
|
||||
updated_at >= created_at
|
||||
AND (target_answered_at IS NULL OR target_answered_at <= updated_at)
|
||||
AND (decision_at IS NULL OR (decision_at >= created_at AND decision_at <= updated_at))
|
||||
),
|
||||
CONSTRAINT support_cases_fields_match_type CHECK (
|
||||
(
|
||||
case_type = 'support'
|
||||
AND (complaint_reason IS NULL)
|
||||
AND rubric_version IS NULL
|
||||
AND assessment_specialization IS NULL
|
||||
)
|
||||
OR (
|
||||
case_type = 'complaint'
|
||||
AND object_type IS NOT NULL
|
||||
AND object_type IN ('organization', 'invitation')
|
||||
AND complaint_reason IS NOT NULL
|
||||
AND assessment_specialization IS NULL
|
||||
AND rubric_version IS NULL
|
||||
AND (complaint_reason NOT IN ('offer_content', 'salary_terms_violation') OR object_type = 'invitation')
|
||||
)
|
||||
OR (
|
||||
case_type = 'grade_appeal'
|
||||
AND object_type IS NOT NULL
|
||||
AND object_type IN ('assessment_attempt', 'support_case')
|
||||
AND complaint_reason IS NULL
|
||||
AND assessment_specialization IS NULL
|
||||
AND rubric_version IS NULL
|
||||
)
|
||||
OR (
|
||||
case_type = 'anticheat_appeal'
|
||||
AND object_type IS NOT NULL
|
||||
AND object_type = 'assessment_attempt'
|
||||
AND complaint_reason IS NULL
|
||||
AND assessment_specialization IS NULL
|
||||
AND rubric_version IS NULL
|
||||
)
|
||||
OR (
|
||||
case_type = 'manual_assessment'
|
||||
AND assessment_specialization IS NOT NULL
|
||||
AND complaint_reason IS NULL
|
||||
AND (object_type IS NULL OR object_type = 'assessment_attempt')
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_decision_matches_type CHECK (
|
||||
decision_outcome IS NULL
|
||||
OR (case_type = 'support' AND decision_outcome = 'answered')
|
||||
OR (case_type = 'manual_assessment' AND decision_outcome = 'assessed')
|
||||
OR (
|
||||
case_type IN ('complaint', 'grade_appeal', 'anticheat_appeal')
|
||||
AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld')
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_cases_status_decision CHECK (
|
||||
(status = 'resolved') = (decision_outcome IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
-- A stored rubric pin must name the immutable current opening for the exact
|
||||
-- target and the grading-policy version used by automated assessment.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION support_cases_rubric_pin_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
opening_policy_version_id uuid;
|
||||
pinned_version integer;
|
||||
BEGIN
|
||||
IF NEW.rubric_version IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
SELECT opening.policy_version_id, policy.version
|
||||
INTO opening_policy_version_id, pinned_version
|
||||
FROM assessment_category_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
JOIN policy_versions AS policy
|
||||
ON policy.id = opening.policy_version_id
|
||||
WHERE opening.id = NEW.rubric_opening_id
|
||||
AND opening.policy_version_id = NEW.rubric_policy_version_id
|
||||
AND binding.specialization = NEW.assessment_specialization
|
||||
AND binding.grade = NEW.assessment_grade
|
||||
AND policy.policy_key = 'product'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM assessment_category_openings AS newer
|
||||
WHERE newer.category = opening.category
|
||||
AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id)
|
||||
)
|
||||
AND opening.policy_version_id = (
|
||||
SELECT current_policy.id
|
||||
FROM policy_versions AS current_policy
|
||||
WHERE current_policy.policy_key = 'product'
|
||||
AND current_policy.effective_at <= statement_timestamp()
|
||||
ORDER BY current_policy.version DESC
|
||||
LIMIT 1
|
||||
);
|
||||
|
||||
IF NOT FOUND OR opening_policy_version_id IS DISTINCT FROM NEW.rubric_policy_version_id
|
||||
OR pinned_version IS DISTINCT FROM NEW.rubric_version THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation', CONSTRAINT = 'support_cases_rubric_pin_consistency',
|
||||
MESSAGE = 'support case rubric pin does not match its current reviewed opening';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER support_cases_rubric_pin_guard
|
||||
BEFORE INSERT OR UPDATE OF rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
assessment_specialization, assessment_grade, created_at
|
||||
ON support_cases
|
||||
FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_guard();
|
||||
|
||||
-- Rubric evidence is fixed at creation even when case status and history later
|
||||
-- change.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION support_cases_rubric_pin_immutable() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (NEW.rubric_version, NEW.rubric_opening_id, NEW.rubric_policy_version_id)
|
||||
IS DISTINCT FROM (OLD.rubric_version, OLD.rubric_opening_id, OLD.rubric_policy_version_id) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'support_cases_rubric_pin_immutable',
|
||||
MESSAGE = 'support case rubric pin is immutable';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER support_cases_rubric_pin_immutable
|
||||
BEFORE UPDATE ON support_cases
|
||||
FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_immutable();
|
||||
|
||||
CREATE INDEX support_cases_owner_created_idx
|
||||
ON support_cases (owner_id, created_at DESC, id DESC);
|
||||
|
||||
-- An appeal is once per owner, appeal type, and target regardless of outcome.
|
||||
CREATE UNIQUE INDEX support_cases_one_appeal_per_target
|
||||
ON support_cases (owner_id, case_type, object_type, object_id)
|
||||
WHERE case_type IN ('grade_appeal', 'anticheat_appeal');
|
||||
|
||||
CREATE UNIQUE INDEX support_cases_one_open_manual_assessment
|
||||
ON support_cases (owner_id, assessment_specialization)
|
||||
WHERE case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed');
|
||||
|
||||
CREATE UNIQUE INDEX support_cases_one_open_complaint_per_object
|
||||
ON support_cases (owner_id, object_type, object_id)
|
||||
WHERE case_type = 'complaint' AND status NOT IN ('resolved', 'closed');
|
||||
|
||||
-- Events are the append-only public history. No staff identity, private note,
|
||||
-- evidence blob, or copied object data is present in this table.
|
||||
CREATE TABLE support_case_events (
|
||||
case_id uuid NOT NULL REFERENCES support_cases (id) ON DELETE CASCADE,
|
||||
sequence integer NOT NULL,
|
||||
event_kind text NOT NULL,
|
||||
actor_kind text NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
status text,
|
||||
message text,
|
||||
CONSTRAINT support_case_events_pkey PRIMARY KEY (case_id, sequence),
|
||||
CONSTRAINT support_case_events_sequence CHECK (sequence BETWEEN 1 AND 200),
|
||||
CONSTRAINT support_case_events_kind CHECK (
|
||||
event_kind IN ('created', 'status_changed', 'reply', 'decision')
|
||||
),
|
||||
CONSTRAINT support_case_events_actor CHECK (actor_kind IN ('user', 'support', 'system')),
|
||||
CONSTRAINT support_case_events_status CHECK (
|
||||
status IS NULL OR status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed')
|
||||
),
|
||||
CONSTRAINT support_case_events_message CHECK (
|
||||
message IS NULL OR (
|
||||
char_length(message) BETWEEN 1 AND 4000
|
||||
)
|
||||
),
|
||||
CONSTRAINT support_case_events_shape CHECK (
|
||||
(event_kind = 'created' AND actor_kind = 'user' AND status = 'submitted' AND message IS NULL)
|
||||
OR (event_kind = 'status_changed' AND actor_kind IN ('support', 'system') AND status IS NOT NULL)
|
||||
OR (event_kind = 'reply' AND actor_kind IN ('user', 'support') AND status IS NULL AND message IS NOT NULL)
|
||||
OR (event_kind = 'decision' AND actor_kind = 'support' AND status = 'resolved' AND message IS NOT NULL)
|
||||
),
|
||||
CONSTRAINT support_case_events_close_reason CHECK (
|
||||
status <> 'closed' OR (event_kind = 'status_changed' AND message IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
-- Prevent rewriting event history while allowing account deletion cascades.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION support_case_events_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'support_case_events_immutable',
|
||||
MESSAGE = 'support case events are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER support_case_events_refuse_update_delete
|
||||
BEFORE UPDATE OR DELETE ON support_case_events
|
||||
FOR EACH ROW EXECUTE FUNCTION support_case_events_refuse_change();
|
||||
|
||||
-- The create result lives exactly as long as its generic scoped idempotency
|
||||
-- record. Its original snapshot and late flag cannot be rewritten on replay.
|
||||
CREATE TABLE support_case_create_outcomes (
|
||||
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
|
||||
outcome_kind text NOT NULL,
|
||||
case_snapshot jsonb,
|
||||
target_was_late boolean,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT support_case_create_outcomes_pkey PRIMARY KEY (scope_hash),
|
||||
CONSTRAINT support_case_create_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
|
||||
CONSTRAINT support_case_create_outcomes_kind CHECK (
|
||||
outcome_kind IN ('created', 'not_found', 'state_conflict')
|
||||
),
|
||||
CONSTRAINT support_case_create_outcomes_snapshot CHECK (
|
||||
(
|
||||
outcome_kind = 'created'
|
||||
AND case_snapshot IS NOT NULL
|
||||
AND jsonb_typeof(case_snapshot) = 'object'
|
||||
AND octet_length(case_snapshot::text) <= 1048576
|
||||
AND target_was_late IS NOT NULL
|
||||
) OR (
|
||||
outcome_kind IN ('not_found', 'state_conflict')
|
||||
AND case_snapshot IS NULL
|
||||
AND target_was_late IS NULL
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- A live idempotent result cannot change between the original response and a
|
||||
-- replay. Expiry cleanup may still delete it through its parent record.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION support_case_create_outcomes_refuse_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'support_case_create_outcomes_immutable',
|
||||
MESSAGE = 'support case create outcomes are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER support_case_create_outcomes_refuse_update
|
||||
BEFORE UPDATE ON support_case_create_outcomes
|
||||
FOR EACH ROW EXECUTE FUNCTION support_case_create_outcomes_refuse_update();
|
||||
|
||||
-- Request events retain the maximum supported 24-hour window, not merely the
|
||||
-- current policy's window. Rows are pruned in small batches by each request.
|
||||
CREATE TABLE support_case_request_events (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
requested_at timestamptz NOT NULL,
|
||||
CONSTRAINT support_case_request_events_pkey PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
CREATE INDEX support_case_request_events_owner_time_idx
|
||||
ON support_case_request_events (owner_id, requested_at, id);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE support_case_request_events;
|
||||
DROP TRIGGER support_cases_rubric_pin_immutable ON support_cases;
|
||||
DROP FUNCTION support_cases_rubric_pin_immutable();
|
||||
DROP TRIGGER support_cases_rubric_pin_guard ON support_cases;
|
||||
DROP FUNCTION support_cases_rubric_pin_guard();
|
||||
DROP TRIGGER support_case_create_outcomes_refuse_update ON support_case_create_outcomes;
|
||||
DROP FUNCTION support_case_create_outcomes_refuse_update();
|
||||
DROP TABLE support_case_create_outcomes;
|
||||
DROP TRIGGER support_case_events_refuse_update_delete ON support_case_events;
|
||||
DROP FUNCTION support_case_events_refuse_change();
|
||||
DROP TABLE support_case_events;
|
||||
DROP INDEX support_cases_one_open_complaint_per_object;
|
||||
DROP INDEX support_cases_one_open_manual_assessment;
|
||||
DROP INDEX support_cases_one_appeal_per_target;
|
||||
DROP INDEX support_cases_owner_created_idx;
|
||||
DROP TABLE support_cases;
|
||||
DROP SEQUENCE support_case_number_seq;
|
||||
@@ -0,0 +1,97 @@
|
||||
-- +goose Up
|
||||
-- Store the original public create response alongside the generic
|
||||
-- idempotency record. A new reservation may replace this snapshot only after
|
||||
-- the 24-hour logical replay window expires; bounded purge removes it with
|
||||
-- the idempotency row. The live need is intentionally not a foreign key.
|
||||
-- jsonb::text adds structural whitespace, so these checks allow a bounded
|
||||
-- 8 KiB representation margin after the compact application-level limits.
|
||||
ALTER TABLE organization_need_versions
|
||||
DROP CONSTRAINT organization_need_versions_snapshot_shape,
|
||||
ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK (
|
||||
jsonb_typeof(snapshot) = 'object'
|
||||
AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version']
|
||||
AND jsonb_typeof(snapshot -> 'id') = 'string'
|
||||
AND snapshot ->> 'id' = need_id::text
|
||||
AND jsonb_typeof(snapshot -> 'organization_id') = 'string'
|
||||
AND snapshot ->> 'organization_id' = organization_id::text
|
||||
AND jsonb_typeof(snapshot -> 'version') = 'number'
|
||||
AND snapshot ->> 'version' = version::text
|
||||
AND jsonb_typeof(snapshot -> 'requirements_version') = 'number'
|
||||
AND CASE
|
||||
WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$'
|
||||
THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version
|
||||
ELSE FALSE
|
||||
END
|
||||
AND octet_length(snapshot::text) <= 270336
|
||||
);
|
||||
|
||||
CREATE TABLE organization_need_creation_results (
|
||||
scope_hash bytea NOT NULL,
|
||||
snapshot jsonb NOT NULL,
|
||||
CONSTRAINT organization_need_creation_results_pkey PRIMARY KEY (scope_hash),
|
||||
CONSTRAINT organization_need_creation_results_idempotency_fkey FOREIGN KEY (
|
||||
scope_hash
|
||||
) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
|
||||
CONSTRAINT organization_need_creation_results_scope_hash_sha256 CHECK (
|
||||
octet_length(scope_hash) = 32
|
||||
),
|
||||
CONSTRAINT organization_need_creation_results_snapshot_bounded CHECK (
|
||||
jsonb_typeof(snapshot) = 'object'
|
||||
AND snapshot ?& ARRAY['need', 'readiness', 'recommendations']
|
||||
AND octet_length(snapshot::text) <= 532480
|
||||
)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
-- Rolling back must not invalidate a response replay that is still within its
|
||||
-- logical window, or remove historical need snapshots that the old bound
|
||||
-- cannot represent. Expired replay rows may remain until bounded purge runs.
|
||||
-- The idempotency lock blocks writes across the shared table, so operators
|
||||
-- run this rollback with writing processes stopped.
|
||||
LOCK TABLE idempotency_records IN ACCESS EXCLUSIVE MODE;
|
||||
LOCK TABLE organization_need_versions IN ACCESS EXCLUSIVE MODE;
|
||||
LOCK TABLE organization_need_creation_results IN ACCESS EXCLUSIVE MODE;
|
||||
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM organization_need_creation_results AS result
|
||||
INNER JOIN idempotency_records AS record USING (scope_hash)
|
||||
WHERE record.expires_at > clock_timestamp()
|
||||
) THEN
|
||||
RAISE EXCEPTION 'cannot roll back migration 00026 while live need creation replays remain';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM organization_need_versions
|
||||
WHERE octet_length(snapshot::text) > 262144
|
||||
) THEN
|
||||
RAISE EXCEPTION 'cannot roll back migration 00026 while need snapshots exceed the prior storage bound';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TABLE organization_need_creation_results;
|
||||
ALTER TABLE organization_need_versions
|
||||
DROP CONSTRAINT organization_need_versions_snapshot_shape,
|
||||
ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK (
|
||||
jsonb_typeof(snapshot) = 'object'
|
||||
AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version']
|
||||
AND jsonb_typeof(snapshot -> 'id') = 'string'
|
||||
AND snapshot ->> 'id' = need_id::text
|
||||
AND jsonb_typeof(snapshot -> 'organization_id') = 'string'
|
||||
AND snapshot ->> 'organization_id' = organization_id::text
|
||||
AND jsonb_typeof(snapshot -> 'version') = 'number'
|
||||
AND snapshot ->> 'version' = version::text
|
||||
AND jsonb_typeof(snapshot -> 'requirements_version') = 'number'
|
||||
AND CASE
|
||||
WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$'
|
||||
THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version
|
||||
ELSE FALSE
|
||||
END
|
||||
AND octet_length(snapshot::text) <= 262144
|
||||
);
|
||||
@@ -0,0 +1,64 @@
|
||||
-- +goose Up
|
||||
-- TASK-089 adds separately chosen opt-in groups to the anonymous card. The
|
||||
-- publication and event constraints call this function, so replacing it
|
||||
-- changes the accepted contract without rewriting any saved field set.
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
|
||||
SELECT
|
||||
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
|
||||
AND cardinality(fields) BETWEEN 0 AND 9
|
||||
AND array_position(fields, NULL) IS NULL
|
||||
AND fields <@ ARRAY[
|
||||
'categories', 'experience', 'location', 'relocation',
|
||||
'salary_compatibility', 'self_assessment', 'soft_skills',
|
||||
'stack', 'work_formats'
|
||||
]::text []
|
||||
AND fields = ARRAY(
|
||||
SELECT DISTINCT field COLLATE "C"
|
||||
FROM unnest(fields) AS field
|
||||
ORDER BY field COLLATE "C"
|
||||
);
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- Do not strand stored publication or immutable history rows outside the old
|
||||
-- contract. An operator must close/remove the newer publications through the
|
||||
-- normal product workflow before this migration can be rolled back.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_publications
|
||||
WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text []
|
||||
) OR EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_privacy_events
|
||||
WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text []
|
||||
) THEN
|
||||
RAISE EXCEPTION 'candidate card opt-in fields are still referenced by publication history';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
|
||||
SELECT
|
||||
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
|
||||
AND cardinality(fields) BETWEEN 0 AND 6
|
||||
AND array_position(fields, NULL) IS NULL
|
||||
AND fields <@ ARRAY[
|
||||
'categories', 'experience', 'location', 'relocation',
|
||||
'soft_skills', 'stack'
|
||||
]::text []
|
||||
AND fields = ARRAY(
|
||||
SELECT DISTINCT field COLLATE "C"
|
||||
FROM unnest(fields) AS field
|
||||
ORDER BY field COLLATE "C"
|
||||
);
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
@@ -0,0 +1,186 @@
|
||||
-- +goose Up
|
||||
-- Signal storage is a separate, bounded side channel. It contains only
|
||||
-- client-reported timing and byte counts, never answer or clipboard content.
|
||||
-- Writes take the generic idempotency scope, C3 consent row, then attempt row;
|
||||
-- the event trigger's parent lock is reentrant inside that same transaction.
|
||||
|
||||
ALTER TABLE assessment_attempt_items
|
||||
ADD CONSTRAINT assessment_attempt_items_attempt_id_id_key UNIQUE (attempt_id, id);
|
||||
|
||||
CREATE TABLE assessment_signal_batches (
|
||||
id uuid NOT NULL,
|
||||
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
|
||||
received_at timestamptz NOT NULL,
|
||||
event_count integer NOT NULL,
|
||||
CONSTRAINT assessment_signal_batches_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_signal_batches_attempt_id_id_key UNIQUE (attempt_id, id),
|
||||
CONSTRAINT assessment_signal_batches_event_count CHECK (event_count BETWEEN 1 AND 50)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_signal_batches_attempt_received_idx
|
||||
ON assessment_signal_batches (attempt_id, received_at, id);
|
||||
|
||||
-- Direct edits and deletes would invalidate accepted receipt counts. The
|
||||
-- nested delete issued by the attempt foreign-key cascade is the only delete
|
||||
-- path while a batch exists.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_signal_batch_immutable() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_signal_batches_immutable',
|
||||
MESSAGE = 'assessment signal batches are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_signal_batch_immutable
|
||||
BEFORE UPDATE OR DELETE ON assessment_signal_batches
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_signal_batch_immutable();
|
||||
|
||||
CREATE TABLE assessment_signal_events (
|
||||
batch_id uuid NOT NULL,
|
||||
attempt_id uuid NOT NULL,
|
||||
ordinal integer NOT NULL,
|
||||
item_instance_id uuid NOT NULL,
|
||||
kind text NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
duration_ms integer,
|
||||
size_bytes integer,
|
||||
CONSTRAINT assessment_signal_events_pkey PRIMARY KEY (batch_id, ordinal),
|
||||
CONSTRAINT assessment_signal_events_batch_attempt_fk FOREIGN KEY (attempt_id, batch_id)
|
||||
REFERENCES assessment_signal_batches (attempt_id, id) ON DELETE CASCADE,
|
||||
CONSTRAINT assessment_signal_events_item_attempt_fk FOREIGN KEY (attempt_id, item_instance_id)
|
||||
REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE,
|
||||
CONSTRAINT assessment_signal_events_ordinal CHECK (ordinal BETWEEN 1 AND 50),
|
||||
CONSTRAINT assessment_signal_events_kind CHECK (
|
||||
kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit')
|
||||
),
|
||||
CONSTRAINT assessment_signal_events_measurement CHECK (
|
||||
(kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL)
|
||||
OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647)
|
||||
OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_signal_events_attempt_idx
|
||||
ON assessment_signal_events (attempt_id, batch_id, ordinal);
|
||||
|
||||
-- Serialize capacity and lifecycle checks on the same attempt row used by the
|
||||
-- usecase. The application stores a whole-batch saturated receipt before this
|
||||
-- trigger is reached; the trigger is a backstop for other database writers.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_signal_event_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
attempt_kind text;
|
||||
attempt_state text;
|
||||
attempt_expires_at timestamptz;
|
||||
existing_count bigint;
|
||||
BEGIN
|
||||
SELECT kind, state, expires_at
|
||||
INTO attempt_kind, attempt_state, attempt_expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = NEW.attempt_id
|
||||
FOR UPDATE;
|
||||
|
||||
IF attempt_kind NOT IN ('root', 'corrective')
|
||||
OR attempt_state NOT IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
OR attempt_expires_at <= clock_timestamp() THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_active',
|
||||
MESSAGE = 'assessment attempt cannot accept signal events';
|
||||
END IF;
|
||||
|
||||
SELECT count(*) INTO existing_count
|
||||
FROM assessment_signal_events
|
||||
WHERE attempt_id = NEW.attempt_id;
|
||||
|
||||
IF existing_count >= 10000 THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_capacity',
|
||||
MESSAGE = 'assessment attempt signal capacity is full';
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_signal_event_guard
|
||||
BEFORE INSERT ON assessment_signal_events
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_guard();
|
||||
|
||||
-- Events are immutable. Only nested foreign-key cascades may delete them.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_signal_event_immutable() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_signal_events_immutable',
|
||||
MESSAGE = 'assessment signal events are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_signal_event_immutable
|
||||
BEFORE UPDATE OR DELETE ON assessment_signal_events
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_immutable();
|
||||
|
||||
CREATE TABLE assessment_signal_idempotency_outcomes (
|
||||
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
|
||||
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
|
||||
status text NOT NULL,
|
||||
accepted_events integer NOT NULL,
|
||||
received_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_signal_idempotency_outcomes_pkey PRIMARY KEY (scope_hash),
|
||||
CONSTRAINT assessment_signal_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
|
||||
CONSTRAINT assessment_signal_idempotency_outcomes_status CHECK (
|
||||
(status = 'accepted' AND accepted_events BETWEEN 1 AND 50)
|
||||
OR (status = 'saturated' AND accepted_events = 0)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_signal_idempotency_outcomes_attempt_received_idx
|
||||
ON assessment_signal_idempotency_outcomes (attempt_id, received_at, scope_hash);
|
||||
|
||||
-- Expired scope replacement and idempotency cleanup may delete an outcome,
|
||||
-- but a live response snapshot cannot be rewritten.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_signal_idempotency_outcome_immutable() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_signal_idempotency_outcomes_immutable',
|
||||
MESSAGE = 'assessment signal outcomes are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_signal_idempotency_outcome_immutable
|
||||
BEFORE UPDATE ON assessment_signal_idempotency_outcomes
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_signal_idempotency_outcome_immutable();
|
||||
|
||||
-- +goose Down
|
||||
DROP TRIGGER assessment_signal_idempotency_outcome_immutable ON assessment_signal_idempotency_outcomes;
|
||||
DROP FUNCTION assessment_signal_idempotency_outcome_immutable();
|
||||
DROP INDEX assessment_signal_idempotency_outcomes_attempt_received_idx;
|
||||
DROP TABLE assessment_signal_idempotency_outcomes;
|
||||
DROP TRIGGER assessment_signal_event_immutable ON assessment_signal_events;
|
||||
DROP FUNCTION assessment_signal_event_immutable();
|
||||
DROP TRIGGER assessment_signal_event_guard ON assessment_signal_events;
|
||||
DROP FUNCTION assessment_signal_event_guard();
|
||||
DROP INDEX assessment_signal_events_attempt_idx;
|
||||
DROP TABLE assessment_signal_events;
|
||||
DROP TRIGGER assessment_signal_batch_immutable ON assessment_signal_batches;
|
||||
DROP FUNCTION assessment_signal_batch_immutable();
|
||||
DROP INDEX assessment_signal_batches_attempt_received_idx;
|
||||
DROP TABLE assessment_signal_batches;
|
||||
ALTER TABLE assessment_attempt_items
|
||||
DROP CONSTRAINT assessment_attempt_items_attempt_id_id_key;
|
||||
@@ -0,0 +1,203 @@
|
||||
-- +goose Up
|
||||
-- Assessment completion supports the deliberately separate express outcome,
|
||||
-- and answers/finalization store immutable public responses for key replay.
|
||||
|
||||
ALTER TABLE assessment_attempts
|
||||
DROP CONSTRAINT assessment_attempts_outcome,
|
||||
ADD CONSTRAINT assessment_attempts_outcome CHECK (
|
||||
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined', 'demonstration')
|
||||
);
|
||||
|
||||
ALTER TABLE assessment_attempt_idempotency_outcomes
|
||||
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation,
|
||||
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status,
|
||||
ADD COLUMN pending_item_ids uuid[] NOT NULL DEFAULT '{}'::uuid[],
|
||||
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (
|
||||
operation IN ('create', 'session', 'answer', 'finalize')
|
||||
),
|
||||
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
|
||||
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
OR (operation = 'create' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL)
|
||||
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
OR (operation IN ('answer', 'finalize') AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
OR (operation IN ('answer', 'finalize') AND status_code = 404 AND problem_code = 'not_found' AND response_snapshot IS NULL)
|
||||
OR (operation = 'answer' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL AND cardinality(pending_item_ids) = 0)
|
||||
OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL)
|
||||
),
|
||||
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items CHECK (
|
||||
cardinality(pending_item_ids) <= 220 AND array_position(pending_item_ids, NULL) IS NULL AND
|
||||
(cardinality(pending_item_ids) = 0 OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict'))
|
||||
);
|
||||
|
||||
-- A completed result is stored once with its exact score, rationale, and
|
||||
-- pinned inputs. The public projection has no answer keys or submitted answers.
|
||||
CREATE TABLE assessment_attempt_results (
|
||||
attempt_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
result_snapshot jsonb NOT NULL,
|
||||
schema_version smallint NOT NULL DEFAULT 1,
|
||||
kind text NOT NULL,
|
||||
mode text NOT NULL,
|
||||
outcome text NOT NULL,
|
||||
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
|
||||
product_policy_version integer NOT NULL,
|
||||
grading_policy_version_id uuid REFERENCES policy_versions (id),
|
||||
opening_id uuid REFERENCES assessment_category_openings (id),
|
||||
opening_manifest_sha256 bytea,
|
||||
training_binding_id uuid REFERENCES assessment_training_bank_bindings (id),
|
||||
training_manifest_sha256 bytea,
|
||||
bank_version text NOT NULL,
|
||||
algorithm_version text NOT NULL,
|
||||
rationale_rule text NOT NULL,
|
||||
pass_mark_basis_points integer,
|
||||
scored_items smallint,
|
||||
raw_score smallint,
|
||||
pass_points smallint,
|
||||
decided_at timestamptz NOT NULL,
|
||||
CONSTRAINT assessment_attempt_results_pkey PRIMARY KEY (attempt_id),
|
||||
CONSTRAINT assessment_attempt_results_owner_fk FOREIGN KEY (attempt_id, user_id)
|
||||
REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE,
|
||||
CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1),
|
||||
CONSTRAINT assessment_attempt_results_snapshot CHECK (
|
||||
jsonb_typeof(result_snapshot) = 'object' AND octet_length(result_snapshot::text) <= 65536 AND
|
||||
NOT (result_snapshot ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) AND
|
||||
NOT ((result_snapshot->'attempt') ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id'])
|
||||
),
|
||||
CONSTRAINT assessment_attempt_results_versions CHECK (
|
||||
product_policy_version > 0 AND bank_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' AND
|
||||
algorithm_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$'
|
||||
),
|
||||
CONSTRAINT assessment_attempt_results_decision CHECK (
|
||||
(kind IN ('root', 'corrective') AND mode = 'demo_basic' AND outcome IN ('confirmed', 'not_confirmed')
|
||||
AND rationale_rule = 'demo_basic_pass_mark'
|
||||
AND grading_policy_version_id IS NOT NULL AND opening_id IS NOT NULL
|
||||
AND opening_manifest_sha256 IS NOT NULL AND octet_length(opening_manifest_sha256) = 32
|
||||
AND training_binding_id IS NULL AND training_manifest_sha256 IS NULL
|
||||
AND pass_mark_basis_points BETWEEN 1 AND 10000
|
||||
AND scored_items IS NOT NULL AND scored_items BETWEEN 1 AND 100
|
||||
AND raw_score IS NOT NULL AND raw_score BETWEEN 0 AND scored_items
|
||||
AND pass_points IS NOT NULL AND pass_points BETWEEN 1 AND scored_items
|
||||
AND pass_points = ((scored_items * pass_mark_basis_points + 9999) / 10000)
|
||||
AND ((outcome = 'confirmed') = (raw_score >= pass_points)))
|
||||
OR (kind = 'demo_express' AND mode = 'demo_express' AND outcome = 'demonstration'
|
||||
AND rationale_rule = 'demonstration_only'
|
||||
AND grading_policy_version_id IS NULL AND opening_id IS NULL AND opening_manifest_sha256 IS NULL
|
||||
AND training_binding_id IS NOT NULL AND training_manifest_sha256 IS NOT NULL
|
||||
AND octet_length(training_manifest_sha256) = 32 AND pass_mark_basis_points IS NULL
|
||||
AND scored_items IS NULL AND raw_score IS NULL AND pass_points IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
-- Keep the decision row bound to the completed attempt and exact pinned inputs.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_result_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
attempt assessment_attempts%ROWTYPE;
|
||||
BEGIN
|
||||
SELECT * INTO attempt
|
||||
FROM assessment_attempts
|
||||
WHERE id = NEW.attempt_id AND user_id = NEW.user_id
|
||||
FOR SHARE;
|
||||
|
||||
IF NOT FOUND OR attempt.state <> 'completed' OR attempt.kind <> NEW.kind OR attempt.mode <> NEW.mode OR
|
||||
attempt.outcome <> NEW.outcome OR attempt.product_policy_version_id <> NEW.product_policy_version_id OR
|
||||
attempt.product_policy_version <> NEW.product_policy_version OR attempt.grading_policy_version_id IS DISTINCT FROM NEW.grading_policy_version_id OR
|
||||
attempt.opening_id IS DISTINCT FROM NEW.opening_id OR attempt.opening_manifest_sha256 IS DISTINCT FROM NEW.opening_manifest_sha256 OR
|
||||
attempt.training_binding_id IS DISTINCT FROM NEW.training_binding_id OR attempt.training_manifest_sha256 IS DISTINCT FROM NEW.training_manifest_sha256 OR
|
||||
attempt.bank_version <> NEW.bank_version OR attempt.algorithm_version <> NEW.algorithm_version OR
|
||||
attempt.ended_at IS DISTINCT FROM NEW.decided_at OR
|
||||
(NEW.result_snapshot->>'outcome') IS DISTINCT FROM NEW.outcome OR
|
||||
(NEW.result_snapshot->>'decided_at')::timestamptz IS DISTINCT FROM NEW.decided_at OR
|
||||
(NEW.result_snapshot->'attempt'->>'id')::uuid IS DISTINCT FROM NEW.attempt_id OR
|
||||
(NEW.result_snapshot->'attempt'->>'kind') IS DISTINCT FROM NEW.kind OR
|
||||
(NEW.result_snapshot->'attempt'->>'mode') IS DISTINCT FROM NEW.mode OR
|
||||
(NEW.result_snapshot->'pins'->>'product_policy_version_id')::uuid IS DISTINCT FROM NEW.product_policy_version_id OR
|
||||
(NEW.result_snapshot->'pins'->>'product_policy_version')::integer IS DISTINCT FROM NEW.product_policy_version OR
|
||||
(NEW.result_snapshot->'pins'->>'bank_version') IS DISTINCT FROM NEW.bank_version OR
|
||||
(NEW.result_snapshot->'pins'->>'algorithm_version') IS DISTINCT FROM NEW.algorithm_version OR
|
||||
(NEW.result_snapshot->'pins'->>'opening_id')::uuid IS DISTINCT FROM NEW.opening_id OR
|
||||
decode(NEW.result_snapshot->'pins'->>'opening_manifest_sha256', 'hex') IS DISTINCT FROM NEW.opening_manifest_sha256 OR
|
||||
(NEW.result_snapshot->'pins'->>'training_binding_id')::uuid IS DISTINCT FROM NEW.training_binding_id OR
|
||||
decode(NEW.result_snapshot->'pins'->>'training_manifest_sha256', 'hex') IS DISTINCT FROM NEW.training_manifest_sha256 OR
|
||||
(NEW.result_snapshot->'rationale'->>'rule') IS DISTINCT FROM NEW.rationale_rule OR
|
||||
(NEW.kind IN ('root', 'corrective') AND (
|
||||
(NEW.result_snapshot->'basic_score'->>'points')::smallint IS DISTINCT FROM NEW.raw_score OR
|
||||
(NEW.result_snapshot->'basic_score'->>'max_points')::smallint IS DISTINCT FROM NEW.scored_items OR
|
||||
(NEW.result_snapshot->'basic_score'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points OR
|
||||
(NEW.result_snapshot->'rationale'->>'pass_mark_basis_points')::integer IS DISTINCT FROM NEW.pass_mark_basis_points OR
|
||||
(NEW.result_snapshot->'rationale'->>'scored_items')::smallint IS DISTINCT FROM NEW.scored_items OR
|
||||
(NEW.result_snapshot->'rationale'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points)) OR
|
||||
(NEW.kind = 'demo_express' AND NEW.result_snapshot ? 'basic_score') THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_snapshot_match',
|
||||
MESSAGE = 'assessment result does not match its completed attempt';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_result_guard
|
||||
BEFORE INSERT ON assessment_attempt_results
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_guard();
|
||||
|
||||
-- Results cannot be overwritten or deleted independently of owner deletion.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_attempt_result_refuse_mutation() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_result_immutable',
|
||||
MESSAGE = 'assessment result snapshots are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_attempt_result_refuse_mutation
|
||||
BEFORE UPDATE OR DELETE ON assessment_attempt_results
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_refuse_mutation();
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM assessment_attempts WHERE outcome = 'demonstration'
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM assessment_attempt_idempotency_outcomes WHERE operation IN ('answer', 'finalize')
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM assessment_attempt_results
|
||||
) THEN
|
||||
RAISE EXCEPTION 'assessment command data uses migration 00029 and must be retained';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TRIGGER assessment_attempt_result_refuse_mutation ON assessment_attempt_results;
|
||||
DROP FUNCTION assessment_attempt_result_refuse_mutation();
|
||||
DROP TRIGGER assessment_attempt_result_guard ON assessment_attempt_results;
|
||||
DROP FUNCTION assessment_attempt_result_guard();
|
||||
DROP TABLE assessment_attempt_results;
|
||||
|
||||
ALTER TABLE assessment_attempt_idempotency_outcomes
|
||||
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status,
|
||||
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation,
|
||||
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items,
|
||||
DROP COLUMN pending_item_ids,
|
||||
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')),
|
||||
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
|
||||
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL)
|
||||
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
|
||||
);
|
||||
|
||||
ALTER TABLE assessment_attempts
|
||||
DROP CONSTRAINT assessment_attempts_outcome,
|
||||
ADD CONSTRAINT assessment_attempts_outcome CHECK (
|
||||
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined')
|
||||
);
|
||||
@@ -0,0 +1,168 @@
|
||||
-- +goose Up
|
||||
-- Immutable audit records for employer reads of anonymous cards and, when a
|
||||
-- future grant-backed operation exists, selected contact fields. The table
|
||||
-- contains identifiers and field codes only, never the viewed content.
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
|
||||
SELECT
|
||||
cardinality(field_codes) BETWEEN 0 AND 6
|
||||
AND array_position(field_codes, NULL) IS NULL
|
||||
AND field_codes = ARRAY(
|
||||
SELECT DISTINCT code COLLATE "C"
|
||||
FROM unnest(field_codes) AS code
|
||||
ORDER BY code COLLATE "C"
|
||||
)
|
||||
AND (
|
||||
(
|
||||
kind = 'card_viewed'
|
||||
AND field_codes <@ ARRAY[
|
||||
'categories', 'experience', 'salary_compatibility',
|
||||
'self_assessment', 'stack', 'work_formats'
|
||||
]::text []
|
||||
)
|
||||
OR (
|
||||
kind = 'contact_read'
|
||||
AND cardinality(field_codes) BETWEEN 1 AND 4
|
||||
AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text []
|
||||
)
|
||||
);
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TABLE candidate_card_access_events (
|
||||
id uuid NOT NULL,
|
||||
candidate_id uuid NOT NULL,
|
||||
organization_id uuid NOT NULL,
|
||||
actor_id uuid,
|
||||
kind text NOT NULL,
|
||||
field_codes text [] NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
CONSTRAINT candidate_card_access_events_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT candidate_card_access_events_candidate_fkey FOREIGN KEY (candidate_id)
|
||||
REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT candidate_card_access_events_organization_fkey FOREIGN KEY (organization_id)
|
||||
REFERENCES organizations (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT candidate_card_access_events_actor_fkey FOREIGN KEY (actor_id)
|
||||
REFERENCES users (id) ON DELETE SET NULL,
|
||||
CONSTRAINT candidate_card_access_events_kind_known CHECK (
|
||||
kind IN ('card_viewed', 'contact_read')
|
||||
),
|
||||
CONSTRAINT candidate_card_access_events_fields_valid CHECK (
|
||||
candidate_card_access_fields_are_valid(kind, field_codes)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX candidate_card_access_events_candidate_occurred_idx
|
||||
ON candidate_card_access_events (candidate_id, occurred_at DESC, id DESC);
|
||||
|
||||
CREATE INDEX candidate_card_access_events_organization_occurred_idx
|
||||
ON candidate_card_access_events (organization_id, occurred_at DESC, id DESC);
|
||||
|
||||
-- Records cannot be altered after insertion. Deletion is allowed only for
|
||||
-- unverified-account cleanup; confirmed-account history remains evidence.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_card_access_events_refuse_update() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
-- Actor deletion may anonymize the foreign key while preserving every
|
||||
-- other part of the historical event.
|
||||
IF pg_trigger_depth() > 1
|
||||
AND OLD.actor_id IS NOT NULL
|
||||
AND NEW.actor_id IS NULL
|
||||
AND NEW.id IS NOT DISTINCT FROM OLD.id
|
||||
AND NEW.candidate_id IS NOT DISTINCT FROM OLD.candidate_id
|
||||
AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id
|
||||
AND NEW.kind IS NOT DISTINCT FROM OLD.kind
|
||||
AND NEW.field_codes IS NOT DISTINCT FROM OLD.field_codes
|
||||
AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_card_access_events_immutable',
|
||||
TABLE = 'candidate_card_access_events',
|
||||
MESSAGE = 'candidate card access events are append-only';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_card_access_events_refuse_update
|
||||
BEFORE UPDATE ON candidate_card_access_events
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_update();
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_card_access_events_refuse_delete() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE users.id = OLD.candidate_id AND users.email_verified_at IS NOT NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_card_access_events_retained',
|
||||
TABLE = 'candidate_card_access_events',
|
||||
MESSAGE = 'candidate card access events of a confirmed account are retained';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_card_access_events_refuse_delete
|
||||
BEFORE DELETE ON candidate_card_access_events
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_delete();
|
||||
|
||||
-- Protect a confirmed account from a direct DELETE that would otherwise
|
||||
-- cascade away its access history. The unverified registration cleanup may
|
||||
-- still remove those accounts and their records.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION candidate_card_access_events_protect_account() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF OLD.email_verified_at IS NOT NULL AND EXISTS (
|
||||
SELECT 1 FROM candidate_card_access_events
|
||||
WHERE candidate_card_access_events.candidate_id = OLD.id
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_card_access_events_retained',
|
||||
TABLE = 'users',
|
||||
MESSAGE = 'confirmed account has retained card access history';
|
||||
END IF;
|
||||
RETURN OLD;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER candidate_card_access_events_protect_account
|
||||
BEFORE DELETE ON users
|
||||
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_protect_account();
|
||||
|
||||
-- +goose Down
|
||||
-- Do not remove durable access evidence as a side effect of rolling back the
|
||||
-- schema. Operators must export or explicitly resolve retained history first.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM candidate_card_access_events) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'candidate_card_access_events_retained',
|
||||
TABLE = 'candidate_card_access_events',
|
||||
MESSAGE = 'candidate card access history must be retained before rollback';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TRIGGER candidate_card_access_events_protect_account ON users;
|
||||
DROP FUNCTION candidate_card_access_events_protect_account();
|
||||
DROP TRIGGER candidate_card_access_events_refuse_delete ON candidate_card_access_events;
|
||||
DROP FUNCTION candidate_card_access_events_refuse_delete();
|
||||
DROP TRIGGER candidate_card_access_events_refuse_update ON candidate_card_access_events;
|
||||
DROP FUNCTION candidate_card_access_events_refuse_update();
|
||||
DROP TABLE candidate_card_access_events;
|
||||
DROP FUNCTION candidate_card_access_fields_are_valid(text, text []);
|
||||
@@ -11,24 +11,28 @@ import (
|
||||
|
||||
// directPublicationReaders are the only queries that may name the table
|
||||
// candidate_publications. The first three are the candidate's own settings
|
||||
// queries; every read on behalf of an organization must go through the view
|
||||
// candidate_effective_publications (published and backed by an unrevoked C2)
|
||||
// and exclude the hidden organizations, as ReadPublicationVisibleToOrganization
|
||||
// does. A new query that reads the table directly fails this test, so it
|
||||
// cannot leak a closed or revoked publication by accident.
|
||||
// queries; the remaining reads are narrowly scoped lock/recheck operations
|
||||
// that require current C2. Organization reads also exclude hidden
|
||||
// organizations, and candidate preview reads remain owner-scoped. A new
|
||||
// query that reads the table directly fails this test until it is reviewed.
|
||||
//
|
||||
// Only queries/*.sql are covered: the project keeps SQL in sqlc queries and
|
||||
// migrations, and the standards forbid raw SQL in Go code.
|
||||
var directPublicationReaders = []string{
|
||||
"ReadCandidatePrivacySettings",
|
||||
"ReadCandidatePublication",
|
||||
"InsertCandidatePublication",
|
||||
"UpdateCandidatePublication",
|
||||
}
|
||||
|
||||
var ownerScopedPublicationQueries = []string{
|
||||
"LockPublicationForCandidatePreview",
|
||||
"LockVisiblePublicationForView",
|
||||
"LockCandidatePublicationForConsentRevocation",
|
||||
}
|
||||
|
||||
var ownerPreviewQueries = []string{"ReadCandidateViewSourceForPreview"}
|
||||
|
||||
var (
|
||||
// sqlc accepts both comment forms and tolerates trailing whitespace.
|
||||
queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`)
|
||||
@@ -66,11 +70,11 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
// Comments may name the table; statements may not.
|
||||
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
|
||||
name := text[header[2]:header[3]]
|
||||
statements[name] = strings.Join(strings.Fields(statement), " ")
|
||||
if publicationTableName.MatchString(statement) {
|
||||
found = append(found, name)
|
||||
statements[name] = strings.Join(strings.Fields(statement), " ")
|
||||
}
|
||||
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) {
|
||||
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) && !slices.Contains(ownerPreviewQueries, name) {
|
||||
t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name)
|
||||
}
|
||||
}
|
||||
@@ -81,9 +85,6 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
if !slices.Equal(found, want) {
|
||||
t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want)
|
||||
}
|
||||
if strings.Contains(strings.Join(found, ","), "Visible") {
|
||||
t.Fatal("the organization-facing read names the table directly")
|
||||
}
|
||||
closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"])
|
||||
for _, required := range []string{
|
||||
"select greatest(candidate_publications.published_at, consent_records.revoked_at)",
|
||||
@@ -100,7 +101,53 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
t.Errorf("consent revocation query lacks %q: %s", required, closeQuery)
|
||||
}
|
||||
}
|
||||
settingsQuery := strings.ToLower(statements["ReadCandidatePrivacySettings"])
|
||||
for _, required := range []string{
|
||||
"users.id = sqlc.arg(user_id)",
|
||||
"left join candidate_publications",
|
||||
"left join consent_records",
|
||||
"left join candidate_search_statuses",
|
||||
"from candidate_hidden_organizations",
|
||||
} {
|
||||
if !strings.Contains(settingsQuery, required) {
|
||||
t.Errorf("candidate settings query lacks %q: %s", required, settingsQuery)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"candidate_profiles", "profile_claims", "candidate_questionnaires", "contact_email", "contact_phone"} {
|
||||
if strings.Contains(settingsQuery, forbidden) {
|
||||
t.Errorf("candidate settings query reaches private profile data %q: %s", forbidden, settingsQuery)
|
||||
}
|
||||
}
|
||||
if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") {
|
||||
t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery)
|
||||
}
|
||||
previewQuery := strings.ToLower(statements["ReadCandidateViewSourceForPreview"])
|
||||
for _, required := range []string{
|
||||
"from candidate_effective_publications as effective",
|
||||
"where effective.user_id = sqlc.arg(candidate_id)",
|
||||
"claim.kind in ('stack', 'role', 'experience')",
|
||||
"coalesce(questionnaire.work_formats, '{}'::text[])",
|
||||
} {
|
||||
if !strings.Contains(previewQuery, required) {
|
||||
t.Errorf("owner preview query lacks %q: %s", required, previewQuery)
|
||||
}
|
||||
}
|
||||
visibleLock := strings.ToLower(statements["LockVisiblePublicationForView"])
|
||||
for _, required := range []string{
|
||||
"candidate_publications.user_id = sqlc.arg(candidate_id)",
|
||||
"candidate_publications.state = 'published'",
|
||||
"candidate_publications.consent_record_id = sqlc.arg(consent_record_id)",
|
||||
"consent_records.purpose = 'c2'",
|
||||
"consent_records.revoked_at is null",
|
||||
"candidate_hidden_organizations",
|
||||
"for share of candidate_publications, consent_records",
|
||||
} {
|
||||
if !strings.Contains(visibleLock, required) {
|
||||
t.Errorf("organization card lock lacks %q: %s", required, visibleLock)
|
||||
}
|
||||
}
|
||||
visibleSource := strings.ToLower(statements["ListVisibleCandidateViewSources"])
|
||||
if !effectiveViewName.MatchString(visibleSource) || !hiddenTableName.MatchString(visibleSource) {
|
||||
t.Errorf("organization cohort source must use the effective publication view and hidden-organization filter: %s", visibleSource)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
-- Finds candidate-requested selections across currently opened categories.
|
||||
-- The adapter validates policy and manifest freshness, locks the category,
|
||||
-- then runs this query again before it returns any pinned families.
|
||||
-- name: ResolveCurrentAssessmentSelection :many
|
||||
WITH current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
), current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
WHERE binding.specialization = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
AND (
|
||||
(sqlc.narg(task_language)::text IS NULL AND cardinality(binding.task_languages) = 0)
|
||||
OR sqlc.narg(task_language)::text = ANY(binding.task_languages)
|
||||
)
|
||||
ORDER BY opening.category;
|
||||
|
||||
-- Serializes root quota checks for one candidate before taking its optional
|
||||
-- specialization or training lock. All callers acquire these locks in order.
|
||||
-- name: LockAssessmentAttemptScope :exec
|
||||
WITH candidate_lock AS MATERIALIZED (
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:user:' || sqlc.arg(user_id)::text,
|
||||
0
|
||||
))
|
||||
)
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:track:' || sqlc.arg(user_id)::text || ':' ||
|
||||
COALESCE(sqlc.narg(specialization)::text, 'training'),
|
||||
0
|
||||
))
|
||||
FROM candidate_lock;
|
||||
|
||||
-- Locks the active real attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveAssessmentAttemptForSpecialization :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE;
|
||||
|
||||
-- Locks the one active express attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveTrainingAssessmentAttempt :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND kind = 'demo_express'
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads the latest root in a specialization, optionally restricted to grade.
|
||||
-- name: GetLatestRootAssessmentAttempt :one
|
||||
SELECT
|
||||
attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome,
|
||||
attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language,
|
||||
attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version,
|
||||
attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256,
|
||||
attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version,
|
||||
attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at,
|
||||
attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used,
|
||||
attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.specialization = sqlc.arg(specialization)
|
||||
AND attempt.kind = 'root'
|
||||
AND (sqlc.narg(target_grade)::text IS NULL OR attempt.target_grade = sqlc.narg(target_grade)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE OF attempt;
|
||||
|
||||
-- Counts root attempts only; the caller applies the effective policy's
|
||||
-- configured window and the product's approved accounting scope.
|
||||
-- name: CountRootAssessmentAttemptsSince :one
|
||||
SELECT count(*)::bigint
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND (sqlc.narg(specialization)::text IS NULL OR attempt.specialization = sqlc.narg(specialization)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable');
|
||||
|
||||
-- Lists explicit immutable training bindings for the effective product
|
||||
-- policy. Callers reject more than one matching active binding as ambiguous.
|
||||
-- name: ListCurrentAssessmentTrainingBindings :many
|
||||
SELECT
|
||||
binding.id,
|
||||
binding.category,
|
||||
binding.product_policy_version_id,
|
||||
binding.item_count,
|
||||
binding.manifest_sha256,
|
||||
binding.family_manifest,
|
||||
policy.version AS product_policy_version
|
||||
FROM assessment_training_bank_bindings AS binding
|
||||
JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id
|
||||
WHERE policy.policy_key = 'product'
|
||||
AND policy.effective_at <= statement_timestamp()
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM policy_versions AS newer
|
||||
WHERE newer.policy_key = 'product'
|
||||
AND newer.effective_at <= statement_timestamp()
|
||||
AND newer.version > policy.version
|
||||
)
|
||||
ORDER BY binding.category, binding.created_at DESC, binding.id;
|
||||
|
||||
-- Reads the exact family membership pinned by a training binding.
|
||||
-- name: ListAssessmentTrainingBindingFamilies :many
|
||||
SELECT
|
||||
family_id,
|
||||
ordinal,
|
||||
family_key,
|
||||
family_version,
|
||||
content_sha256
|
||||
FROM assessment_training_bank_binding_families
|
||||
WHERE binding_id = sqlc.arg(binding_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Inserts the attempt header. The database guard rechecks the current policy,
|
||||
-- opening or disjoint training binding, and immutable pins.
|
||||
-- name: InsertAssessmentAttempt :exec
|
||||
INSERT INTO assessment_attempts (
|
||||
id,
|
||||
user_id,
|
||||
kind,
|
||||
mode,
|
||||
state,
|
||||
outcome,
|
||||
bank_category,
|
||||
specialization,
|
||||
target_grade,
|
||||
task_language,
|
||||
root_attempt_id,
|
||||
product_policy_version_id,
|
||||
product_policy_version,
|
||||
grading_policy_version_id,
|
||||
opening_id,
|
||||
opening_manifest_sha256,
|
||||
training_binding_id,
|
||||
training_manifest_sha256,
|
||||
bank_version,
|
||||
algorithm_version,
|
||||
created_at,
|
||||
updated_at,
|
||||
expires_at,
|
||||
chain_deadline,
|
||||
idle_timeout_seconds,
|
||||
max_sessions,
|
||||
sessions_used,
|
||||
session_started_at,
|
||||
last_activity_at,
|
||||
version,
|
||||
ended_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(mode),
|
||||
sqlc.arg(state),
|
||||
sqlc.narg(outcome),
|
||||
sqlc.arg(bank_category),
|
||||
sqlc.narg(specialization),
|
||||
sqlc.narg(target_grade),
|
||||
sqlc.narg(task_language),
|
||||
sqlc.arg(root_attempt_id),
|
||||
sqlc.arg(product_policy_version_id),
|
||||
sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id),
|
||||
sqlc.narg(opening_id),
|
||||
sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id),
|
||||
sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version),
|
||||
sqlc.arg(algorithm_version),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at),
|
||||
sqlc.arg(expires_at),
|
||||
sqlc.narg(chain_deadline),
|
||||
sqlc.arg(idle_timeout_seconds),
|
||||
sqlc.arg(max_sessions),
|
||||
sqlc.arg(sessions_used),
|
||||
sqlc.arg(session_started_at),
|
||||
sqlc.arg(last_activity_at),
|
||||
sqlc.arg(version),
|
||||
sqlc.narg(ended_at)
|
||||
);
|
||||
|
||||
-- Stores the immutable generated variant and empty answer slot.
|
||||
-- name: InsertAssessmentAttemptItem :exec
|
||||
INSERT INTO assessment_attempt_items (
|
||||
id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
family_id,
|
||||
family_key,
|
||||
family_version,
|
||||
family_content_sha256,
|
||||
variant,
|
||||
answer,
|
||||
answered_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(family_id),
|
||||
sqlc.arg(family_key),
|
||||
sqlc.arg(family_version),
|
||||
sqlc.arg(family_content_sha256),
|
||||
sqlc.arg(variant),
|
||||
sqlc.narg(answer),
|
||||
sqlc.narg(answered_at)
|
||||
);
|
||||
|
||||
-- Returns a full private attempt only to its candidate.
|
||||
-- name: GetAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads the immutable attempt kind without locking the row. Session commands
|
||||
-- use this only to decide whether C3 applies before acquiring the row lock.
|
||||
-- name: GetAssessmentAttemptKindForCandidate :one
|
||||
SELECT kind
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Locks one owner-scoped attempt while a session command performs its CAS.
|
||||
-- name: LockAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads chain headers in creation order. The use case verifies root eligibility
|
||||
-- and descending target grades in the domain before it creates a correction.
|
||||
-- name: ListAssessmentAttemptChain :many
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND (id = sqlc.arg(root_attempt_id) OR root_attempt_id = sqlc.arg(root_attempt_id))
|
||||
ORDER BY created_at, id
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads private frozen variants and candidate answer bytes in stable order.
|
||||
-- name: ListAssessmentAttemptItems :many
|
||||
SELECT
|
||||
id, attempt_id, ordinal, family_id, family_key, family_version,
|
||||
family_content_sha256, variant::text AS variant, answer, answered_at
|
||||
FROM assessment_attempt_items
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Applies a versioned session transition after the attempt row is locked.
|
||||
-- name: UpdateAssessmentAttemptSession :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
sessions_used = sqlc.arg(sessions_used),
|
||||
session_started_at = sqlc.arg(session_started_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- Stores one final answer before advancing the enclosing attempt version.
|
||||
-- The caller holds the owner-scoped attempt row lock for the surrounding unit.
|
||||
-- name: UpdateAssessmentAttemptItemAnswer :one
|
||||
UPDATE assessment_attempt_items
|
||||
SET answer = sqlc.arg(answer), answered_at = sqlc.arg(answered_at)
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
AND id = sqlc.arg(item_id)
|
||||
AND answer IS NULL
|
||||
RETURNING id;
|
||||
|
||||
-- Applies an answer, expiry, or finalization transition after the attempt row
|
||||
-- is locked. Session limits and all immutable pins remain unchanged.
|
||||
-- name: UpdateAssessmentAttemptTransition :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- A newly reserved generic idempotency window can replace an expired typed
|
||||
-- outcome before the new immutable response is inserted.
|
||||
-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec
|
||||
DELETE FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertAssessmentAttemptIdempotencyOutcome :exec
|
||||
INSERT INTO assessment_attempt_idempotency_outcomes (
|
||||
scope_hash, operation, status_code, problem_code, response_snapshot,
|
||||
response_schema_version, pending_item_ids, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(operation), sqlc.arg(status_code),
|
||||
sqlc.narg(problem_code), sqlc.narg(response_snapshot), 1,
|
||||
sqlc.arg(pending_item_ids)::uuid[], transaction_timestamp()
|
||||
);
|
||||
|
||||
-- name: GetAssessmentAttemptIdempotencyOutcome :one
|
||||
SELECT operation, status_code, problem_code,
|
||||
CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot,
|
||||
pending_item_ids
|
||||
FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Stores one immutable candidate-visible result with the decision rationale
|
||||
-- and source versions used by its finalized attempt.
|
||||
-- name: InsertAssessmentAttemptResult :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome,
|
||||
product_policy_version_id, product_policy_version,
|
||||
grading_policy_version_id, opening_id, opening_manifest_sha256,
|
||||
training_binding_id, training_manifest_sha256, bank_version, algorithm_version,
|
||||
rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at
|
||||
)
|
||||
VALUES (
|
||||
sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot)::jsonb, 1,
|
||||
sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome),
|
||||
sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id), sqlc.narg(opening_id), sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id), sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version), sqlc.arg(algorithm_version), sqlc.arg(rationale_rule),
|
||||
sqlc.narg(pass_mark_basis_points), sqlc.narg(scored_items), sqlc.narg(raw_score),
|
||||
sqlc.narg(pass_points), sqlc.arg(decided_at)
|
||||
);
|
||||
|
||||
-- Reads a result only for the owning candidate.
|
||||
-- name: GetAssessmentAttemptResult :one
|
||||
SELECT result_snapshot::text AS result_snapshot
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
@@ -0,0 +1,173 @@
|
||||
-- Returns current reviewed grade/language bindings and the live published
|
||||
-- family manifest at one caller-supplied database time. The adapter verifies
|
||||
-- the pinned manifest hash before exposing only family keys.
|
||||
-- name: ListCurrentAssessmentAvailabilitySelections :many
|
||||
WITH current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= sqlc.arg(as_of)::timestamptz
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
), current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families,
|
||||
opened_at
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category;
|
||||
|
||||
-- Reads an active real attempt without taking the write lock used by create.
|
||||
-- The availability GET never expires or otherwise mutates this row.
|
||||
-- name: GetAssessmentAvailabilityActiveAttempt :one
|
||||
SELECT id, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Reads roots within the policy horizon and the last header in each correction
|
||||
-- chain. It deliberately omits frozen items, answers, and row locks.
|
||||
-- name: ListAssessmentAvailabilityRootSummaries :many
|
||||
SELECT
|
||||
root.target_grade AS root_target_grade,
|
||||
root.created_at AS root_created_at,
|
||||
root.updated_at AS root_updated_at,
|
||||
root.expires_at AS root_expires_at,
|
||||
root.state AS root_state,
|
||||
root.outcome AS root_outcome,
|
||||
root.chain_deadline AS root_chain_deadline,
|
||||
latest.target_grade AS latest_target_grade,
|
||||
latest.updated_at AS latest_updated_at,
|
||||
latest.expires_at AS latest_expires_at,
|
||||
latest.state AS latest_state,
|
||||
latest.outcome AS latest_outcome,
|
||||
latest.chain_deadline AS latest_chain_deadline,
|
||||
COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error
|
||||
FROM assessment_attempts AS root
|
||||
JOIN LATERAL (
|
||||
SELECT attempt.*
|
||||
FROM assessment_attempts AS attempt
|
||||
WHERE attempt.user_id = root.user_id
|
||||
AND attempt.root_attempt_id = root.id
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
) AS latest ON true
|
||||
LEFT JOIN assessment_attempt_results AS root_result
|
||||
ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id
|
||||
LEFT JOIN assessment_attempt_results AS latest_result
|
||||
ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id
|
||||
WHERE root.user_id = sqlc.arg(user_id)
|
||||
AND root.specialization = sqlc.arg(specialization)
|
||||
AND root.kind = 'root'
|
||||
AND root.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND root.state <> 'insufficient_bank'
|
||||
AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY root.created_at DESC, root.id DESC;
|
||||
|
||||
-- Counts eligible root attempts in a policy window and computes the instant
|
||||
-- at which one additional root slot opens. The microsecond adjustment matches
|
||||
-- the creation predicate created_at >= since at PostgreSQL timestamp precision.
|
||||
-- name: GetAssessmentRootQuotaAvailability :one
|
||||
WITH eligible AS (
|
||||
SELECT attempt.id, attempt.created_at
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND attempt.created_at <= sqlc.arg(as_of)::timestamptz
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
), total AS (
|
||||
SELECT count(*)::bigint AS attempt_count FROM eligible
|
||||
)
|
||||
SELECT
|
||||
total.attempt_count,
|
||||
CASE WHEN total.attempt_count >= sqlc.arg(max_attempts)::bigint THEN (
|
||||
SELECT eligible.created_at
|
||||
+ make_interval(secs => sqlc.arg(window_seconds)::double precision)
|
||||
+ interval '1 microsecond'
|
||||
FROM eligible
|
||||
ORDER BY eligible.created_at, eligible.id
|
||||
LIMIT 1
|
||||
OFFSET (total.attempt_count - sqlc.arg(max_attempts)::bigint)
|
||||
) ELSE NULL::timestamptz END AS available_at
|
||||
FROM total;
|
||||
|
||||
-- Counts family instances disclosed after the non-repeat boundary. The first
|
||||
-- item is disclosed when the attempt is created; each later item is disclosed
|
||||
-- when the preceding answer is accepted. This per-item timestamp prevents a
|
||||
-- long-running attempt from making later items appear older than they are.
|
||||
-- Counting the first unanswered item after expiry is conservative when the
|
||||
-- final response was lost, while frozen future items remain excluded.
|
||||
-- name: ListAssessmentDisclosedFamilyKeys :many
|
||||
WITH progress AS (
|
||||
SELECT
|
||||
attempt.id AS attempt_id,
|
||||
attempt.created_at,
|
||||
COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal
|
||||
FROM assessment_attempts AS attempt
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
AND attempt.expires_at > sqlc.arg(since)::timestamptz
|
||||
GROUP BY attempt.id
|
||||
), disclosed AS (
|
||||
SELECT
|
||||
item.family_key,
|
||||
CASE
|
||||
WHEN item.ordinal = 1 THEN progress.created_at
|
||||
ELSE previous.answered_at
|
||||
END AS disclosed_at
|
||||
FROM progress
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id
|
||||
LEFT JOIN assessment_attempt_items AS previous
|
||||
ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1
|
||||
WHERE item.ordinal <= progress.last_disclosed_ordinal
|
||||
)
|
||||
SELECT DISTINCT disclosed.family_key
|
||||
FROM disclosed
|
||||
WHERE disclosed.disclosed_at > sqlc.arg(since)::timestamptz
|
||||
ORDER BY disclosed.family_key;
|
||||
@@ -0,0 +1,78 @@
|
||||
-- New outcomes share the generic idempotency row and are counted for the
|
||||
-- attempt's rolling receipt window. Replays bypass this query in the usecase.
|
||||
-- name: CountRecentAssessmentSignalOutcomes :one
|
||||
SELECT
|
||||
count(*)::bigint AS outcome_count,
|
||||
COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE
|
||||
attempt_id = sqlc.arg(attempt_id)
|
||||
AND received_at > sqlc.arg(since);
|
||||
|
||||
-- The attempt row is already locked by the caller. Store a parent before its
|
||||
-- bounded child events, in the same transaction as the immutable receipt.
|
||||
-- name: InsertAssessmentSignalBatch :exec
|
||||
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(received_at),
|
||||
sqlc.arg(event_count)
|
||||
);
|
||||
|
||||
-- Each inserted event is checked by the database guard against attempt state
|
||||
-- and the aggregate capacity as a second line of defense.
|
||||
-- name: InsertAssessmentSignalEvent :exec
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
item_instance_id,
|
||||
kind,
|
||||
occurred_at,
|
||||
duration_ms,
|
||||
size_bytes
|
||||
) VALUES (
|
||||
sqlc.arg(batch_id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(item_instance_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(occurred_at),
|
||||
sqlc.narg(duration_ms)::integer,
|
||||
sqlc.narg(size_bytes)::integer
|
||||
);
|
||||
|
||||
-- Count events only for the already owner-locked attempt.
|
||||
-- name: CountAssessmentSignalEvents :one
|
||||
SELECT count(*)::bigint AS event_count
|
||||
FROM assessment_signal_events
|
||||
WHERE attempt_id = sqlc.arg(attempt_id);
|
||||
|
||||
-- The generic reservation has already established that a previous outcome is
|
||||
-- expired before this child is removed and replaced in the same transaction.
|
||||
-- name: DeleteExpiredAssessmentSignalOutcome :exec
|
||||
DELETE FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Save exactly one immutable response receipt for each live idempotency scope.
|
||||
-- name: InsertAssessmentSignalOutcome :exec
|
||||
INSERT INTO assessment_signal_idempotency_outcomes (
|
||||
scope_hash,
|
||||
attempt_id,
|
||||
status,
|
||||
accepted_events,
|
||||
received_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(status),
|
||||
sqlc.arg(accepted_events),
|
||||
sqlc.arg(received_at)
|
||||
);
|
||||
|
||||
-- Read only the receipt associated with the reserved idempotency scope.
|
||||
-- name: GetAssessmentSignalOutcome :one
|
||||
SELECT status, accepted_events, received_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -229,6 +229,35 @@ WHERE
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keeps the current C3 grant stable through a real assessment transaction.
|
||||
-- Revocation updates this row and therefore waits until the caller commits.
|
||||
-- name: LockCurrentConsentForUse :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = sqlc.arg(subject_id)
|
||||
AND purpose = 'c3'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- Locks the active registration C1 while its pending registration is applied.
|
||||
-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
|
||||
@@ -58,6 +58,34 @@ WHERE
|
||||
AND need_id = sqlc.arg(need_id)
|
||||
AND version = sqlc.arg(version);
|
||||
|
||||
-- Read one bounded newest-first page of current needs. Both the organization
|
||||
-- scope and the tuple cursor are applied before the limit.
|
||||
-- name: ListOrganizationNeeds :many
|
||||
SELECT
|
||||
need.organization_id,
|
||||
need.id AS need_id,
|
||||
need.current_version,
|
||||
need.requirements_version,
|
||||
need.created_at,
|
||||
need.updated_at,
|
||||
version.snapshot::text AS snapshot
|
||||
FROM organization_needs AS need
|
||||
INNER JOIN organization_need_versions AS version
|
||||
ON version.organization_id = need.organization_id
|
||||
AND version.need_id = need.id
|
||||
AND version.version = need.current_version
|
||||
WHERE
|
||||
need.organization_id = sqlc.arg(organization_id)
|
||||
AND (
|
||||
sqlc.narg(after_created_at)::timestamptz IS NULL
|
||||
OR (need.created_at, need.id) < (
|
||||
sqlc.narg(after_created_at)::timestamptz,
|
||||
sqlc.narg(after_need_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY need.created_at DESC, need.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The conditional parent update is the compare-and-swap. Appending the
|
||||
-- snapshot is part of the same SQL statement, so a failed insert leaves the
|
||||
-- parent pointer unchanged even before the surrounding transaction rolls
|
||||
@@ -100,3 +128,19 @@ WITH advanced AS (
|
||||
)
|
||||
SELECT appended.snapshot
|
||||
FROM appended;
|
||||
|
||||
-- The generic idempotency scope serializes retries. Replacing the child row
|
||||
-- is safe only in the transaction that reserves an expired scope for a new
|
||||
-- create; live retries read and return the stored response without writing.
|
||||
-- name: SaveOrganizationNeedCreationResult :exec
|
||||
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
||||
VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb)
|
||||
ON CONFLICT (scope_hash) DO UPDATE
|
||||
SET snapshot = excluded.snapshot;
|
||||
|
||||
-- Read only the immutable original response. The current need may have moved
|
||||
-- to a later version since this result was created.
|
||||
-- name: GetOrganizationNeedCreationResult :one
|
||||
SELECT snapshot::text AS snapshot
|
||||
FROM organization_need_creation_results
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -97,6 +97,32 @@ WHERE
|
||||
AND membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active';
|
||||
|
||||
-- Locks the organization first and then the active membership, using the
|
||||
-- same order as organization profile writes. A company operation keeps both
|
||||
-- share locks until its transaction commits, so a concurrent revocation
|
||||
-- cannot authorize a write after it has committed.
|
||||
-- name: LockActiveMembership :one
|
||||
WITH locked_organization AS MATERIALIZED (
|
||||
SELECT organizations.id
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
FOR SHARE
|
||||
)
|
||||
SELECT
|
||||
membership.id AS membership_id,
|
||||
membership.organization_id,
|
||||
membership.user_id,
|
||||
membership.role,
|
||||
membership.state,
|
||||
membership.created_at,
|
||||
membership.updated_at
|
||||
FROM memberships AS membership
|
||||
INNER JOIN locked_organization ON locked_organization.id = membership.organization_id
|
||||
WHERE
|
||||
membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active'
|
||||
FOR SHARE OF membership;
|
||||
|
||||
-- Changes the profile of an organization over the version the caller read
|
||||
-- and advances the version in the same statement. It names no verification
|
||||
-- column, so a profile update cannot move the trust level. The change
|
||||
|
||||
@@ -6,6 +6,39 @@
|
||||
-- looking, and hides nobody; no statement creates a row except an explicit
|
||||
-- act of the candidate.
|
||||
|
||||
-- Reads the candidate-owned settings and hidden count from one statement
|
||||
-- snapshot. Missing setting rows are restored as the closed/not-looking
|
||||
-- defaults in the adapter. The account row scopes the result but does not
|
||||
-- expose private profile values.
|
||||
-- name: ReadCandidatePrivacySettings :one
|
||||
SELECT
|
||||
users.id AS user_id,
|
||||
candidate_publications.state AS publication_state,
|
||||
candidate_publications.fields AS publication_fields,
|
||||
candidate_publications.consent_record_id AS publication_consent_record_id,
|
||||
candidate_publications.published_at AS publication_published_at,
|
||||
candidate_publications.closed_at AS publication_closed_at,
|
||||
candidate_publications.version AS publication_version,
|
||||
consent_records.revoked_at AS publication_consent_revoked_at,
|
||||
candidate_search_statuses.status AS search_status,
|
||||
candidate_search_statuses.confirmed_at AS search_confirmed_at,
|
||||
candidate_search_statuses.lapses_at AS search_lapses_at,
|
||||
candidate_search_statuses.policy_version_id AS search_policy_version_id,
|
||||
candidate_search_statuses.version AS search_version,
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = users.id
|
||||
) AS hidden_count
|
||||
FROM users
|
||||
LEFT JOIN candidate_publications
|
||||
ON candidate_publications.user_id = users.id
|
||||
LEFT JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
LEFT JOIN candidate_search_statuses
|
||||
ON candidate_search_statuses.user_id = users.id
|
||||
WHERE users.id = sqlc.arg(user_id);
|
||||
|
||||
-- Reads the publication with the revocation state of the C2 record behind it
|
||||
-- in one statement, so the stored setting and the ledger come from one
|
||||
-- snapshot. The effective state is computed from them: published only while
|
||||
@@ -319,3 +352,74 @@ WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
);
|
||||
|
||||
-- Records a successfully authorized view after visibility and quota checks.
|
||||
-- The audit contains only identities, the access kind, published field codes,
|
||||
-- and time; it never receives the projection content, ranking, or filters.
|
||||
-- name: InsertCandidateCardAccessEvent :exec
|
||||
INSERT INTO candidate_card_access_events (
|
||||
id,
|
||||
candidate_id,
|
||||
organization_id,
|
||||
actor_id,
|
||||
kind,
|
||||
field_codes,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(candidate_id),
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.narg(actor_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(field_codes),
|
||||
sqlc.arg(occurred_at)
|
||||
);
|
||||
|
||||
-- Lists only the current candidate's own access history. It deliberately
|
||||
-- omits the employee, requested card fields, and search context. The privacy
|
||||
-- read adapter resolves an organization name only through this recorded
|
||||
-- access relation, which is already visible to the candidate.
|
||||
-- name: ListCandidateCardAccessEvents :many
|
||||
SELECT
|
||||
candidate_card_access_events.id,
|
||||
candidate_card_access_events.candidate_id,
|
||||
candidate_card_access_events.organization_id,
|
||||
candidate_card_access_events.actor_id,
|
||||
candidate_card_access_events.kind,
|
||||
candidate_card_access_events.field_codes,
|
||||
candidate_card_access_events.occurred_at,
|
||||
organizations.name AS organization_name
|
||||
FROM candidate_card_access_events
|
||||
INNER JOIN organizations
|
||||
ON organizations.id = candidate_card_access_events.organization_id
|
||||
WHERE
|
||||
candidate_card_access_events.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The candidate may name an organization in privacy settings only if that
|
||||
-- organization already appears in their own access history or is already
|
||||
-- hidden. Unknown and unseen organizations produce the same no-row result.
|
||||
-- name: CandidateCanSeeOrganization :one
|
||||
SELECT organizations.id, organizations.name
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM candidate_card_access_events
|
||||
WHERE candidate_card_access_events.candidate_id = sqlc.arg(user_id)
|
||||
AND candidate_card_access_events.organization_id = organizations.id
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = sqlc.arg(user_id)
|
||||
AND candidate_hidden_organizations.organization_id = organizations.id
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,181 @@
|
||||
-- Organization-facing anonymous candidate projection inputs. The calling
|
||||
-- usecase has already authorized the active organization membership. This
|
||||
-- single statement snapshot filters both revoked/unpublished C2 states and
|
||||
-- candidates hidden from this organization before any profile value is read.
|
||||
-- The projection reads only stack, declared role, and experience dates. It
|
||||
-- deliberately excludes names, contacts, salary, location, soft skills,
|
||||
-- employer names, summaries, and imported excerpts.
|
||||
-- name: ListVisibleCandidateViewSources :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal;
|
||||
|
||||
-- Lock the account before an organization checks candidate visibility. The
|
||||
-- hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
|
||||
-- a hide either commits before the later visibility recheck or waits for the
|
||||
-- read transaction to finish.
|
||||
-- name: LockCandidateAccountForView :one
|
||||
SELECT users.id
|
||||
FROM users
|
||||
WHERE users.id = sqlc.arg(candidate_id)
|
||||
FOR SHARE;
|
||||
|
||||
-- Lock the current C2 before locking the publication. C2 revocation updates
|
||||
-- this row before it locks the publication, so preserving this order avoids
|
||||
-- a lock inversion and makes the current consent stable through the read.
|
||||
-- name: LockCurrentC2ForView :one
|
||||
SELECT consent_records.id
|
||||
FROM consent_records
|
||||
WHERE
|
||||
consent_records.subject_id = sqlc.arg(candidate_id)
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
ORDER BY consent_records.granted_at DESC, consent_records.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- Lock and recheck one candidate's exact current publication only after the
|
||||
-- active C2 row is share-locked. No row includes unpublished, revoked, stale
|
||||
-- publication, and organization-hidden states.
|
||||
-- name: LockVisiblePublicationForView :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = sqlc.arg(candidate_id)
|
||||
AND candidate_publications.state = 'published'
|
||||
AND candidate_publications.consent_record_id = sqlc.arg(consent_record_id)
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = candidate_publications.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
)
|
||||
FOR SHARE OF candidate_publications, consent_records;
|
||||
|
||||
-- Lock a candidate's current publication for the private preview. This has
|
||||
-- no organization context and never enters the employer read quota or audit.
|
||||
-- name: LockPublicationForCandidatePreview :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = sqlc.arg(candidate_id)
|
||||
AND candidate_publications.state = 'published'
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
FOR SHARE OF candidate_publications, consent_records;
|
||||
|
||||
-- Read the candidate's current private projection inputs after the caller
|
||||
-- locks its active C2 and publication. It selects only fields allowed in the
|
||||
-- anonymous-card projection and is never used for employer visibility.
|
||||
-- name: ReadCandidateViewSourceForPreview :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE effective.user_id = sqlc.arg(candidate_id)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal;
|
||||
@@ -0,0 +1,154 @@
|
||||
-- Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
|
||||
-- request are expected and do not expose request contents.
|
||||
-- name: NextSupportCaseNumber :one
|
||||
WITH next_value AS MATERIALIZED (
|
||||
SELECT nextval('support_case_number_seq') AS value
|
||||
)
|
||||
SELECT
|
||||
'SC-' || sqlc.arg(utc_year)::text || '-' ||
|
||||
CASE
|
||||
WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0')
|
||||
ELSE next_value.value::text
|
||||
END::text AS case_number
|
||||
FROM next_value;
|
||||
|
||||
-- The initial public history is inserted in the caller's case transaction.
|
||||
-- Any unique business conflict leaves the transaction usable so the caller can
|
||||
-- store the immutable 409 outcome under the request's idempotency key.
|
||||
-- name: InsertSupportCase :execrows
|
||||
INSERT INTO support_cases (
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(id), sqlc.arg(case_number), sqlc.arg(owner_id), sqlc.arg(case_type),
|
||||
sqlc.arg(status), sqlc.arg(description), sqlc.narg(object_type), sqlc.narg(object_id),
|
||||
sqlc.narg(assessment_specialization), sqlc.narg(assessment_grade),
|
||||
sqlc.narg(complaint_reason), sqlc.narg(rubric_version), sqlc.narg(rubric_opening_id),
|
||||
sqlc.narg(rubric_policy_version_id), sqlc.arg(target_business_days),
|
||||
sqlc.arg(target_due_at), sqlc.narg(target_answered_at), sqlc.arg(target_policy_version),
|
||||
sqlc.arg(target_calendar_version), sqlc.narg(decision_outcome), sqlc.narg(decision_reason),
|
||||
sqlc.narg(decision_at), sqlc.arg(created_at), sqlc.arg(updated_at)
|
||||
)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: InsertSupportCaseEvent :exec
|
||||
INSERT INTO support_case_events (
|
||||
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
) VALUES (
|
||||
sqlc.arg(case_id), sqlc.arg(sequence), sqlc.arg(event_kind), sqlc.arg(actor_kind),
|
||||
sqlc.arg(occurred_at), sqlc.narg(status), sqlc.narg(message)
|
||||
);
|
||||
|
||||
-- Reads a full owner-scoped record. Object values are identifiers only.
|
||||
-- name: ReadOwnedSupportCase :one
|
||||
SELECT
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
FROM support_cases
|
||||
WHERE id = sqlc.arg(case_id) AND owner_id = sqlc.arg(owner_id);
|
||||
|
||||
-- Reads the immutable public history only after the case owner has matched.
|
||||
-- name: ReadSupportCaseEvents :many
|
||||
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
FROM support_case_events
|
||||
WHERE case_id = sqlc.arg(case_id)
|
||||
ORDER BY sequence;
|
||||
|
||||
-- Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
-- and event history. The tuple cursor matches the composite sort key.
|
||||
-- name: ListOwnedSupportCases :many
|
||||
WITH cursor_input AS MATERIALIZED (
|
||||
SELECT
|
||||
sqlc.narg(after_created_at)::timestamptz AS after_created_at,
|
||||
sqlc.narg(after_id)::uuid AS after_id
|
||||
)
|
||||
SELECT
|
||||
id, case_number, case_type, status, object_type, object_id,
|
||||
assessment_specialization, assessment_grade, target_business_days,
|
||||
target_due_at, target_answered_at, target_policy_version,
|
||||
target_calendar_version, decision_outcome, created_at, updated_at
|
||||
FROM support_cases
|
||||
CROSS JOIN cursor_input
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
AND (
|
||||
cursor_input.after_created_at IS NULL
|
||||
OR (created_at, id) < (
|
||||
cursor_input.after_created_at,
|
||||
cursor_input.after_id
|
||||
)
|
||||
)
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
-- responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
-- name: DeleteSupportCaseCreateOutcome :exec
|
||||
DELETE FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertSupportCaseCreateOutcome :exec
|
||||
INSERT INTO support_case_create_outcomes (
|
||||
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(outcome_kind),
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(case_snapshot)::jsonb END,
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(target_was_late)::boolean END,
|
||||
sqlc.arg(created_at)
|
||||
);
|
||||
|
||||
-- name: ReadSupportCaseCreateOutcome :one
|
||||
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
|
||||
FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Serialize per-owner budget checks even before the first event exists.
|
||||
-- name: LockSupportCaseRequestBudget :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.support.case.requests:' || sqlc.arg(owner_id)::uuid::text, 0)
|
||||
);
|
||||
|
||||
-- Read the latest serialized event so a temporarily regressing application
|
||||
-- clock cannot make the next request fall before an event already counted.
|
||||
-- name: LatestSupportCaseRequestEvent :one
|
||||
SELECT requested_at
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
ORDER BY requested_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keep up to the maximum supported window, regardless of the current policy.
|
||||
-- The bounded delete prevents one create from doing unbounded cleanup work.
|
||||
-- name: PruneSupportCaseRequestEvents :execrows
|
||||
WITH expired AS MATERIALIZED (
|
||||
SELECT source.id
|
||||
FROM support_case_request_events AS source
|
||||
WHERE source.owner_id = sqlc.arg(owner_id)
|
||||
AND source.requested_at <= sqlc.arg(at)::timestamptz - interval '24 hours'
|
||||
ORDER BY source.requested_at, source.id
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM support_case_request_events AS event
|
||||
USING expired
|
||||
WHERE event.id = expired.id;
|
||||
|
||||
-- The strict lower boundary means an event exactly one window old no longer
|
||||
-- counts. The use case derives Retry-After from first_in_window.
|
||||
-- name: CountSupportCaseRequestEvents :one
|
||||
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
AND requested_at > sqlc.arg(window_start)::timestamptz
|
||||
AND requested_at <= sqlc.arg(at)::timestamptz;
|
||||
|
||||
-- name: InsertSupportCaseRequestEvent :exec
|
||||
INSERT INTO support_case_request_events (owner_id, requested_at)
|
||||
VALUES (sqlc.arg(owner_id), sqlc.arg(requested_at));
|
||||
@@ -0,0 +1,53 @@
|
||||
-- Lists every current reviewed category binding for one exact public target.
|
||||
-- Manual support cases have no task-language selector, so the use case must
|
||||
-- accept a rubric only when one distinct current opening matches.
|
||||
-- name: ResolveCurrentSupportCaseRubrics :many
|
||||
WITH current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
), current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
WHERE binding.specialization = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
ORDER BY opening.category;
|
||||
@@ -0,0 +1,461 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestAssessmentAnswerAndResultPersistAcrossRouterReconstruction(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "answer-owner@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234")
|
||||
|
||||
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
|
||||
"answer-flow-create", "203.0.113.43:1234")
|
||||
if create.Code != http.StatusCreated {
|
||||
t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String())
|
||||
}
|
||||
var publicAttempt assessmentAnswerHTTPAttempt
|
||||
if err := json.Unmarshal(create.Body.Bytes(), &publicAttempt); err != nil || publicAttempt.ID == uuid.Nil || publicAttempt.CurrentItem == nil {
|
||||
t.Fatalf("created attempt = %+v, decode error %v", publicAttempt, err)
|
||||
}
|
||||
items := readAssessmentAnswerHTTPItems(t, ctx, harness, publicAttempt.ID)
|
||||
if len(items) < 2 || items[0].ID != publicAttempt.CurrentItem.ID {
|
||||
t.Fatalf("frozen item count/current item = %d/%s, want ordered item list starting at current item", len(items), publicAttempt.CurrentItem.ID)
|
||||
}
|
||||
|
||||
finalizePath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + "/finalize"
|
||||
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": publicAttempt.Version})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal early finalize: %v", err)
|
||||
}
|
||||
earlyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
|
||||
var pendingProblem struct {
|
||||
Code string `json:"code"`
|
||||
PendingItemIDs []uuid.UUID `json:"pending_item_ids"`
|
||||
}
|
||||
if earlyFinalize.Code != http.StatusConflict || json.Unmarshal(earlyFinalize.Body.Bytes(), &pendingProblem) != nil ||
|
||||
pendingProblem.Code != "state_conflict" || len(pendingProblem.PendingItemIDs) != len(items) {
|
||||
t.Fatalf("early finalize = %d %s, want state_conflict with %d pending item IDs", earlyFinalize.Code, earlyFinalize.Body.String(), len(items))
|
||||
}
|
||||
for index, item := range items {
|
||||
if pendingProblem.PendingItemIDs[index] != item.ID {
|
||||
t.Fatalf("pending item %d = %s, want frozen item %s", index, pendingProblem.PendingItemIDs[index], item.ID)
|
||||
}
|
||||
}
|
||||
finalizeReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
|
||||
if finalizeReplay.Code != earlyFinalize.Code ||
|
||||
assessmentHTTPBodyWithoutTraceID(t, finalizeReplay.Body.String()) != assessmentHTTPBodyWithoutTraceID(t, earlyFinalize.Body.String()) {
|
||||
t.Fatalf("early finalize replay = %d %s, want stored %d %s", finalizeReplay.Code, finalizeReplay.Body.String(), earlyFinalize.Code, earlyFinalize.Body.String())
|
||||
}
|
||||
|
||||
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, publicAttempt.Version, items[0], false)
|
||||
withClientScore := strings.TrimSuffix(string(firstAnswer), "}") + `,"score":100}`
|
||||
clientScore := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", withClientScore,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
|
||||
if clientScore.Code != http.StatusBadRequest {
|
||||
t.Fatalf("answer with client score = %d %s, want rejected request", clientScore.Code, clientScore.Body.String())
|
||||
}
|
||||
answerScope := harness.keyring.IdempotencyScope("assessment_attempt.answer", "answer-flow-first", candidate.ID.String())
|
||||
var badScoreOutcomeCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash=$1", answerScope[:]).Scan(&badScoreOutcomeCount); err != nil || badScoreOutcomeCount != 0 {
|
||||
t.Fatalf("invalid client score reserved idempotency row count=%d error=%v, want zero", badScoreOutcomeCount, err)
|
||||
}
|
||||
|
||||
firstAccepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
|
||||
var firstSnapshot assessmentAnswerHTTPAttempt
|
||||
if firstAccepted.Code != http.StatusOK || json.Unmarshal(firstAccepted.Body.Bytes(), &firstSnapshot) != nil ||
|
||||
firstSnapshot.Version != publicAttempt.Version+1 || firstSnapshot.CurrentItem == nil || firstSnapshot.CurrentItem.ID != items[1].ID {
|
||||
t.Fatalf("first answer = %d %s, want next frozen item and incremented version", firstAccepted.Code, firstAccepted.Body.String())
|
||||
}
|
||||
storedAnswer, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
|
||||
if len(storedAnswer) == 0 || answeredAt.IsZero() {
|
||||
t.Fatalf("first answer storage = bytes %d, answered_at %s; want canonical answer and server time", len(storedAnswer), answeredAt)
|
||||
}
|
||||
answerReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
|
||||
if answerReplay.Code != firstAccepted.Code || answerReplay.Body.String() != firstAccepted.Body.String() {
|
||||
t.Fatalf("answer replay = %d %s, want stored %d %s", answerReplay.Code, answerReplay.Body.String(), firstAccepted.Code, firstAccepted.Body.String())
|
||||
}
|
||||
|
||||
// A reconstructed service graph and router read the committed answer and
|
||||
// its server timestamp from PostgreSQL, not the old handler's memory.
|
||||
harness.pool.Close()
|
||||
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
readPath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String()
|
||||
reconstructedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, readPath, "", "",
|
||||
cookie.Value, "", "", "203.0.113.46:1234")
|
||||
var reconstructedAttempt assessmentAnswerHTTPAttempt
|
||||
if reconstructedRead.Code != http.StatusOK || json.Unmarshal(reconstructedRead.Body.Bytes(), &reconstructedAttempt) != nil ||
|
||||
reconstructedAttempt.Version != firstSnapshot.Version || reconstructedAttempt.CurrentItem == nil ||
|
||||
reconstructedAttempt.CurrentItem.ID != firstSnapshot.CurrentItem.ID {
|
||||
t.Fatalf("GET after router reconstruction = %d %s, want version %d and item %s", reconstructedRead.Code, reconstructedRead.Body.String(), firstSnapshot.Version, firstSnapshot.CurrentItem.ID)
|
||||
}
|
||||
reconstructedAnswer, reconstructedAnsweredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
|
||||
if string(reconstructedAnswer) != string(storedAnswer) || !reconstructedAnsweredAt.Equal(answeredAt) {
|
||||
t.Fatalf("answer after router reconstruction differs: bytes equal=%v timestamp=%s want %s", string(reconstructedAnswer) == string(storedAnswer), reconstructedAnsweredAt, answeredAt)
|
||||
}
|
||||
|
||||
currentVersion := reconstructedAttempt.Version
|
||||
for _, item := range items[1:] {
|
||||
body := assessmentAnswerHTTPBody(t, currentVersion, item)
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(body),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-item-%d", item.Ordinal),
|
||||
fmt.Sprintf("203.0.113.%d:1234", 50+item.Ordinal))
|
||||
var next assessmentAnswerHTTPAttempt
|
||||
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != currentVersion+1 {
|
||||
t.Fatalf("answer frozen item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), currentVersion+1)
|
||||
}
|
||||
if item.Ordinal < int32(len(items)) && (next.CurrentItem == nil || next.CurrentItem.ID != items[item.Ordinal].ID) {
|
||||
t.Fatalf("answer item %d returned current item %+v, want %s", item.Ordinal, next.CurrentItem, items[item.Ordinal].ID)
|
||||
}
|
||||
if item.Ordinal == int32(len(items)) && (next.State != "ready_to_finalize" || next.CurrentItem != nil) {
|
||||
t.Fatalf("final answer returned state=%s current_item=%+v, want ready_to_finalize", next.State, next.CurrentItem)
|
||||
}
|
||||
currentVersion = next.Version
|
||||
}
|
||||
|
||||
finalizeBody, err = json.Marshal(map[string]int64{"expected_version": currentVersion})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal finalization: %v", err)
|
||||
}
|
||||
finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.90:1234")
|
||||
var completed assessmentAnswerHTTPAttempt
|
||||
if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" {
|
||||
t.Fatalf("finalize complete attempt = %d %s, want completed", finalized.Code, finalized.Body.String())
|
||||
}
|
||||
resultPath := readPath + "/result"
|
||||
resultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
|
||||
cookie.Value, "", "", "203.0.113.91:1234")
|
||||
var realResult map[string]any
|
||||
if resultResponse.Code != http.StatusOK || json.Unmarshal(resultResponse.Body.Bytes(), &realResult) != nil ||
|
||||
realResult["attempt_id"] != publicAttempt.ID.String() || realResult["outcome"] != "confirmed" {
|
||||
t.Fatalf("read completed result = %d %s, want persisted confirmed result", resultResponse.Code, resultResponse.Body.String())
|
||||
}
|
||||
score, ok := realResult["basic_score"].(map[string]any)
|
||||
points, pointsOK := score["points"].(float64)
|
||||
maxPoints, maxPointsOK := score["max_points"].(float64)
|
||||
if !ok || !pointsOK || !maxPointsOK || points != maxPoints-1 || score["pass_points"] == nil {
|
||||
t.Fatalf("real result basic score = %#v, want one incorrect server-scored item", realResult["basic_score"])
|
||||
}
|
||||
sameKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.94:1234")
|
||||
if sameKeyFinalize.Code != finalized.Code || sameKeyFinalize.Body.String() != finalized.Body.String() {
|
||||
t.Fatalf("completed finalize replay = %d %s, want stored %d %s", sameKeyFinalize.Code, sameKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
|
||||
}
|
||||
newFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": completed.Version})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal completed finalize retry: %v", err)
|
||||
}
|
||||
newKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(newFinalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize-again", "203.0.113.95:1234")
|
||||
if newKeyFinalize.Code != finalized.Code || newKeyFinalize.Body.String() != finalized.Body.String() {
|
||||
t.Fatalf("new-key completed finalize = %d %s, want existing terminal projection %d %s", newKeyFinalize.Code, newKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
|
||||
}
|
||||
var resultRowCount int64
|
||||
var persistedVersion int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempt_results WHERE attempt_id=$1", publicAttempt.ID).Scan(&resultRowCount); err != nil {
|
||||
t.Fatalf("count immutable result rows: %v", err)
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT version FROM assessment_attempts WHERE id=$1", publicAttempt.ID).Scan(&persistedVersion); err != nil {
|
||||
t.Fatalf("read finalized attempt version: %v", err)
|
||||
}
|
||||
if resultRowCount != 1 || persistedVersion != completed.Version {
|
||||
t.Fatalf("finalize retries left %d result rows and version %d, want one row and version %d", resultRowCount, persistedVersion, completed.Version)
|
||||
}
|
||||
resultSnapshot, productPolicyID, openingID, rawScore, passMark, rawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, publicAttempt.ID)
|
||||
if resultSnapshot["outcome"] != "confirmed" || !rawScoreValid || rawScore != int16(score["points"].(float64)) {
|
||||
t.Fatalf("stored result outcome/score = %v/%d (valid %v), API result = %v/%v", resultSnapshot["outcome"], rawScore, rawScoreValid, realResult["outcome"], score["points"])
|
||||
}
|
||||
pins, ok := resultSnapshot["pins"].(map[string]any)
|
||||
if !ok || pins["product_policy_version_id"] != productPolicyID.String() || pins["opening_id"] != openingID.String() ||
|
||||
!strings.Contains(stringMustJSON(t, resultSnapshot), `"product_policy_version_id":"`+productPolicyID.String()+`"`) {
|
||||
t.Fatalf("stored result pin IDs are not UUID strings: %#v", resultSnapshot["pins"])
|
||||
}
|
||||
if passMark < 1 || strings.Contains(resultResponse.Body.String(), "ReferenceAnswer") || strings.Contains(resultResponse.Body.String(), "answer_key") {
|
||||
t.Fatalf("result exposed private source or lost its stored pass mark: body=%s pass_mark=%d", resultResponse.Body.String(), passMark)
|
||||
}
|
||||
|
||||
// The result projection is read from the immutable stored snapshot after a
|
||||
// second router/pool reconstruction and stays byte-for-byte stable.
|
||||
harness.pool.Close()
|
||||
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
restartedResult := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
|
||||
cookie.Value, "", "", "203.0.113.92:1234")
|
||||
if restartedResult.Code != http.StatusOK || restartedResult.Body.String() != resultResponse.Body.String() {
|
||||
t.Fatalf("result after router reconstruction = %d %s, want stored projection %s", restartedResult.Code, restartedResult.Body.String(), resultResponse.Body.String())
|
||||
}
|
||||
|
||||
var rootAttemptsBeforeExpress int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsBeforeExpress); err != nil {
|
||||
t.Fatalf("count real attempts before express completion: %v", err)
|
||||
}
|
||||
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-create", "203.0.113.93:1234")
|
||||
var training assessmentAnswerHTTPAttempt
|
||||
if trainingCreate.Code != http.StatusCreated || json.Unmarshal(trainingCreate.Body.Bytes(), &training) != nil || training.ID == uuid.Nil {
|
||||
t.Fatalf("create express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
|
||||
}
|
||||
trainingItems := readAssessmentAnswerHTTPItems(t, ctx, harness, training.ID)
|
||||
trainingVersion := training.Version
|
||||
for _, item := range trainingItems {
|
||||
body := assessmentAnswerHTTPBody(t, trainingVersion, item)
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/answers", string(body),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-express-%d", item.Ordinal),
|
||||
fmt.Sprintf("203.0.113.%d:1234", 100+item.Ordinal))
|
||||
var next assessmentAnswerHTTPAttempt
|
||||
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != trainingVersion+1 {
|
||||
t.Fatalf("answer express item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
|
||||
}
|
||||
trainingVersion = next.Version
|
||||
}
|
||||
trainingFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": trainingVersion})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal express finalization: %v", err)
|
||||
}
|
||||
trainingFinalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/finalize", string(trainingFinalizeBody),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-finalize", "203.0.113.110:1234")
|
||||
if trainingFinalized.Code != http.StatusOK {
|
||||
t.Fatalf("finalize express attempt = %d %s", trainingFinalized.Code, trainingFinalized.Body.String())
|
||||
}
|
||||
trainingResultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet,
|
||||
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/result", "", "", cookie.Value, "", "", "203.0.113.111:1234")
|
||||
var trainingResult map[string]any
|
||||
if trainingResultResponse.Code != http.StatusOK || json.Unmarshal(trainingResultResponse.Body.Bytes(), &trainingResult) != nil ||
|
||||
trainingResult["outcome"] != "demonstration" || trainingResult["mode"] != "demo_express" ||
|
||||
trainingResult["basic_score"] != nil || trainingResult["confirmed_grade"] != nil || trainingResult["specialization"] != nil {
|
||||
t.Fatalf("express result = %d %s, want demonstration without score or grade", trainingResultResponse.Code, trainingResultResponse.Body.String())
|
||||
}
|
||||
_, _, _, expressRawScore, _, expressRawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, training.ID)
|
||||
if expressRawScoreValid {
|
||||
t.Fatalf("express result stored raw score %d, want SQL NULL", expressRawScore)
|
||||
}
|
||||
var rootAttemptsAfterExpress int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsAfterExpress); err != nil {
|
||||
t.Fatalf("count real attempts after express completion: %v", err)
|
||||
}
|
||||
if rootAttemptsAfterExpress != rootAttemptsBeforeExpress {
|
||||
t.Fatalf("express completion changed real root quota count from %d to %d", rootAttemptsBeforeExpress, rootAttemptsAfterExpress)
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentAnswerHTTPAttempt struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Version int64 `json:"version"`
|
||||
State string `json:"state"`
|
||||
CurrentItem *struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
} `json:"current_item"`
|
||||
}
|
||||
|
||||
type assessmentAnswerHTTPItem struct {
|
||||
ID uuid.UUID
|
||||
Ordinal int32
|
||||
Variant domain.AssessmentVariant
|
||||
}
|
||||
|
||||
func readAssessmentAnswerHTTPItems(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
) []assessmentAnswerHTTPItem {
|
||||
t.Helper()
|
||||
rows, err := harness.pool.Query(ctx, `SELECT id, ordinal, variant FROM assessment_attempt_items WHERE attempt_id=$1 ORDER BY ordinal`, attemptID)
|
||||
if err != nil {
|
||||
t.Fatalf("read frozen assessment items: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]assessmentAnswerHTTPItem, 0)
|
||||
for rows.Next() {
|
||||
var item assessmentAnswerHTTPItem
|
||||
var encoded []byte
|
||||
if err := rows.Scan(&item.ID, &item.Ordinal, &encoded); err != nil {
|
||||
t.Fatalf("scan frozen assessment item: %v", err)
|
||||
}
|
||||
item.Variant, err = domain.UnmarshalAssessmentAttemptVariant(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("restore frozen assessment variant: %v", err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatalf("iterate frozen assessment items: %v", err)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func readAssessmentAnswerHTTPItem(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID, itemID uuid.UUID,
|
||||
) ([]byte, time.Time) {
|
||||
t.Helper()
|
||||
var answer []byte
|
||||
var answeredAt time.Time
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT answer, answered_at FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2`,
|
||||
attemptID, itemID).Scan(&answer, &answeredAt); err != nil {
|
||||
t.Fatalf("read stored answer and server time: %v", err)
|
||||
}
|
||||
return answer, answeredAt.UTC()
|
||||
}
|
||||
|
||||
func assessmentAnswerHTTPBody(t *testing.T, version int64, item assessmentAnswerHTTPItem) []byte {
|
||||
return assessmentAnswerHTTPBodyWithCorrectness(t, version, item, true)
|
||||
}
|
||||
|
||||
func assessmentAnswerHTTPBodyWithCorrectness(
|
||||
t *testing.T,
|
||||
version int64,
|
||||
item assessmentAnswerHTTPItem,
|
||||
wantCorrect bool,
|
||||
) []byte {
|
||||
t.Helper()
|
||||
var answer []byte
|
||||
switch item.Variant.AnswerFormat {
|
||||
case domain.AnswerFormatInteger:
|
||||
reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64)
|
||||
if err != nil {
|
||||
t.Fatalf("parse frozen answer key %q: %v", item.Variant.ReferenceAnswer, err)
|
||||
}
|
||||
if !wantCorrect {
|
||||
reference++
|
||||
}
|
||||
answer = []byte(fmt.Sprintf(`{"format":"number","number":%d}`, reference))
|
||||
case domain.AnswerFormatIntegerSequence:
|
||||
parts := strings.Fields(item.Variant.ReferenceAnswer)
|
||||
if !wantCorrect && len(parts) < 2 {
|
||||
t.Fatalf("frozen sequence answer %q has fewer than two tasks", item.Variant.ReferenceAnswer)
|
||||
}
|
||||
elements := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
elements = append(elements, "job_"+part)
|
||||
}
|
||||
if !wantCorrect {
|
||||
elements[0], elements[1] = elements[1], elements[0]
|
||||
}
|
||||
var err error
|
||||
answer, err = json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
ElementIDs []string `json:"element_ids"`
|
||||
}{Format: "order", ElementIDs: elements})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal order answer: %v", err)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat)
|
||||
}
|
||||
_, correct, err := domain.CanonicalAssessmentAnswerForVariant(answer, item.Variant)
|
||||
if err != nil || correct != wantCorrect {
|
||||
t.Fatalf("fixture answer for item %s has correctness %v, want %v: error %v", item.ID, correct, wantCorrect, err)
|
||||
}
|
||||
body, err := json.Marshal(struct {
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
ItemID uuid.UUID `json:"item_id"`
|
||||
Answer json.RawMessage `json:"answer"`
|
||||
}{ExpectedVersion: version, ItemID: item.ID, Answer: answer})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal answer command: %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func readAssessmentAttemptHTTPResult(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
) (map[string]any, uuid.UUID, uuid.UUID, int16, int32, bool) {
|
||||
t.Helper()
|
||||
var encoded []byte
|
||||
var productPolicyID uuid.UUID
|
||||
var storedOpeningID pgtype.UUID
|
||||
var rawScore pgtype.Int2
|
||||
var passMark pgtype.Int4
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT result_snapshot, product_policy_version_id, opening_id, raw_score, pass_mark_basis_points
|
||||
FROM assessment_attempt_results WHERE attempt_id=$1`, attemptID).
|
||||
Scan(&encoded, &productPolicyID, &storedOpeningID, &rawScore, &passMark); err != nil {
|
||||
t.Fatalf("read immutable assessment result row: %v", err)
|
||||
}
|
||||
var openingID uuid.UUID
|
||||
if storedOpeningID.Valid {
|
||||
openingID = uuid.UUID(storedOpeningID.Bytes)
|
||||
}
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(encoded, &document); err != nil {
|
||||
t.Fatalf("decode immutable assessment result document: %v", err)
|
||||
}
|
||||
if !rawScore.Valid || !passMark.Valid {
|
||||
return document, productPolicyID, openingID, 0, 0, rawScore.Valid
|
||||
}
|
||||
return document, productPolicyID, openingID, rawScore.Int16, passMark.Int32, rawScore.Valid
|
||||
}
|
||||
|
||||
func stringMustJSON(t *testing.T, value any) string {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal result snapshot for assertion: %v", err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
|
||||
func assessmentHTTPBodyWithoutTraceID(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
var document map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(body), &document); err != nil {
|
||||
t.Fatalf("decode HTTP problem response: %v", err)
|
||||
}
|
||||
delete(document, "trace_id")
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal HTTP problem response: %v", err)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,509 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
assessmentpolicy "lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
type assessmentAvailabilityHTTPGrade struct {
|
||||
Grade string `json:"grade"`
|
||||
Status string `json:"status"`
|
||||
Mode *string `json:"mode"`
|
||||
TimeLimitSeconds *int32 `json:"time_limit_seconds"`
|
||||
MaxSessions *int32 `json:"max_sessions"`
|
||||
MaxItems *int32 `json:"max_items"`
|
||||
PracticeRequired *bool `json:"practice_required"`
|
||||
}
|
||||
|
||||
type assessmentAvailabilityHTTPSpecialization struct {
|
||||
Specialization string `json:"specialization"`
|
||||
ActiveAttempt *uuid.UUID `json:"active_attempt_id"`
|
||||
Grades []assessmentAvailabilityHTTPGrade `json:"grades"`
|
||||
}
|
||||
|
||||
type assessmentAvailabilityHTTPProjection struct {
|
||||
Specializations []assessmentAvailabilityHTTPSpecialization `json:"specializations"`
|
||||
}
|
||||
|
||||
func TestAssessmentAvailabilityHTTPIsCandidateScopedAndReadOnly(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-http-candidate@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.50:1234")
|
||||
|
||||
unauthenticated := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", "", "", "", "203.0.113.51:1234")
|
||||
requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated")
|
||||
employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "availability-http-employer@example.test", passwordHash)
|
||||
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "203.0.113.52:1234")
|
||||
employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", employerCookie.Value, "", "", "203.0.113.53:1234")
|
||||
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
|
||||
|
||||
path := "/api/v1/me/assessment-availability"
|
||||
emptyRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.54:1234")
|
||||
var emptyProjection struct {
|
||||
Specializations []json.RawMessage `json:"specializations"`
|
||||
}
|
||||
if emptyRead.Code != http.StatusOK || emptyRead.Header().Get("Cache-Control") != "no-store" ||
|
||||
json.Unmarshal(emptyRead.Body.Bytes(), &emptyProjection) != nil || emptyProjection.Specializations == nil || len(emptyProjection.Specializations) != 0 {
|
||||
t.Fatalf("availability before questionnaire = %d %s, Cache-Control=%q, want empty candidate projection",
|
||||
emptyRead.Code, emptyRead.Body.String(), emptyRead.Header().Get("Cache-Control"))
|
||||
}
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "203.0.113.55:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "203.0.113.56:1234")
|
||||
|
||||
available := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.57:1234")
|
||||
var initial assessmentAvailabilityHTTPProjection
|
||||
if available.Code != http.StatusOK || available.Header().Get("Cache-Control") != "no-store" ||
|
||||
json.Unmarshal(available.Body.Bytes(), &initial) != nil || len(initial.Specializations) != 2 {
|
||||
t.Fatalf("availability after questionnaire = %d %s, Cache-Control=%q, want both saved specializations",
|
||||
available.Code, available.Body.String(), available.Header().Get("Cache-Control"))
|
||||
}
|
||||
backend := findAssessmentAvailabilitySpecialization(t, initial, "backend")
|
||||
for _, target := range []string{"intern", "junior"} {
|
||||
grade := findAssessmentAvailabilityGrade(t, backend, target)
|
||||
if grade.Status != "available" || grade.Mode == nil || *grade.Mode != "demo_basic" ||
|
||||
grade.TimeLimitSeconds == nil || *grade.TimeLimitSeconds != 72*60*60 ||
|
||||
grade.MaxSessions == nil || *grade.MaxSessions != 1 || grade.MaxItems == nil || *grade.MaxItems != 13 ||
|
||||
grade.PracticeRequired == nil || *grade.PracticeRequired {
|
||||
t.Fatalf("backend %s availability = %+v, response=%s, want the published demo_basic start limits",
|
||||
target, grade, available.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The questionnaire self-assesses junior, while this request selects the
|
||||
// offered intern bank. The stored questionnaire grade is not a target gate.
|
||||
created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBodyWithGrade(t, "backend", "intern"), sessionHTTPTestOrigin,
|
||||
candidateCookie.Value, candidateCSRF, "availability-create-different-grade", "203.0.113.58:1234")
|
||||
var activeAttempt assessmentAnswerHTTPAttempt
|
||||
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &activeAttempt) != nil || activeAttempt.ID == uuid.Nil {
|
||||
t.Fatalf("create attempt at offered grade different from self-assessment = %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
|
||||
// Re-login immediately before the read-only measurement so the session
|
||||
// activity coalescing window cannot obscure a write caused by the GET.
|
||||
candidateCookie, candidateCSRF = loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.59:1234")
|
||||
token, err := domain.ParseSecretToken(candidateCookie.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("parse synthetic session token for state comparison: %v", err)
|
||||
}
|
||||
tokenHash := token.Hash()
|
||||
type availabilityReadState struct {
|
||||
attemptVersion int64
|
||||
sessionsUsed int32
|
||||
updatedAt time.Time
|
||||
sessionSeenAt time.Time
|
||||
attemptRows int64
|
||||
itemRows int64
|
||||
answeredItems int64
|
||||
idempotency int64
|
||||
}
|
||||
readAvailabilityState := func() availabilityReadState {
|
||||
t.Helper()
|
||||
var state availabilityReadState
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT version, sessions_used, updated_at FROM assessment_attempts WHERE id=$1", activeAttempt.ID).
|
||||
Scan(&state.attemptVersion, &state.sessionsUsed, &state.updatedAt); err != nil {
|
||||
t.Fatalf("read attempt state before/after availability: %v", err)
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT last_seen_at FROM sessions WHERE token_hash=$1", tokenHash[:]).Scan(&state.sessionSeenAt); err != nil {
|
||||
t.Fatalf("read session activity before/after availability: %v", err)
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT (SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'),
|
||||
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2),
|
||||
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2 AND answered_at IS NOT NULL),
|
||||
(SELECT count(*) FROM idempotency_records)`, candidate.ID, activeAttempt.ID).
|
||||
Scan(&state.attemptRows, &state.itemRows, &state.answeredItems, &state.idempotency); err != nil {
|
||||
t.Fatalf("read attempt/quota state before/after availability: %v", err)
|
||||
}
|
||||
return state
|
||||
}
|
||||
before := readAvailabilityState()
|
||||
for index := 0; index < 2; index++ {
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.60:1234")
|
||||
var current assessmentAvailabilityHTTPProjection
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" ||
|
||||
json.Unmarshal(response.Body.Bytes(), ¤t) != nil {
|
||||
t.Fatalf("repeated availability GET %d = %d %s, Cache-Control=%q", index+1, response.Code,
|
||||
response.Body.String(), response.Header().Get("Cache-Control"))
|
||||
}
|
||||
backend = findAssessmentAvailabilitySpecialization(t, current, "backend")
|
||||
if backend.ActiveAttempt == nil || *backend.ActiveAttempt != activeAttempt.ID {
|
||||
t.Fatalf("repeated availability GET %d active attempt = %v, want %s", index+1, backend.ActiveAttempt, activeAttempt.ID)
|
||||
}
|
||||
for _, grade := range backend.Grades {
|
||||
if grade.Status != "active_attempt" {
|
||||
t.Fatalf("backend grade %s status = %q while an attempt is active", grade.Grade, grade.Status)
|
||||
}
|
||||
}
|
||||
}
|
||||
after := readAvailabilityState()
|
||||
if before.attemptVersion != after.attemptVersion || before.sessionsUsed != after.sessionsUsed ||
|
||||
!before.updatedAt.Equal(after.updatedAt) || !before.sessionSeenAt.Equal(after.sessionSeenAt) ||
|
||||
before.attemptRows != after.attemptRows || before.itemRows != after.itemRows ||
|
||||
before.answeredItems != after.answeredItems || before.idempotency != after.idempotency {
|
||||
t.Fatalf("availability GET wrote state: before=%+v after=%+v", before, after)
|
||||
}
|
||||
|
||||
adaptive := domain.DemoProductPolicyV2()
|
||||
adaptive.Assessment.Calibration = domain.AssessmentCalibrationCalibrated
|
||||
adaptive.Assessment.Attempt.RealMode = domain.AssessmentRealModeAdaptive
|
||||
adaptive.Assessment.Attempt.BasicPassMark = 0
|
||||
publisher := assessmentpolicy.NewPublisher(postgres.NewPolicyStore(harness.pool).Policies(), time.Now)
|
||||
adaptiveVersion, err := publisher.Publish(ctx, assessmentpolicy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: adaptive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish explicit adaptive policy for unavailable-mode check: %v", err)
|
||||
}
|
||||
adaptiveBank := assessment.NewBank(postgres.NewTransactor(harness.pool))
|
||||
adaptiveFixture := assessmentFixture{
|
||||
ctx: ctx, pool: harness.pool, store: postgres.NewAssessmentBankStore(harness.pool),
|
||||
transactor: postgres.NewTransactor(harness.pool), bank: adaptiveBank,
|
||||
demoBundle: loadDemoBundleFile(t),
|
||||
}
|
||||
adaptiveRequired, err := domain.RequiredPublishedAssessmentFamilies(adaptiveVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("read adaptive policy family requirement: %v", err)
|
||||
}
|
||||
var publishedBackendFamilies int32
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT count(DISTINCT family_key)::integer
|
||||
FROM assessment_families
|
||||
WHERE category='backend' AND lifecycle='published' AND review_status='approved'`).Scan(&publishedBackendFamilies); err != nil {
|
||||
t.Fatalf("count current backend families for adaptive opening: %v", err)
|
||||
}
|
||||
if publishedBackendFamilies < adaptiveRequired {
|
||||
adaptiveBundle := adaptiveFixture.reviewedBundle(int(adaptiveRequired - publishedBackendFamilies))
|
||||
adaptiveBundle.Name = "availability-adaptive-backend"
|
||||
adaptiveBundle.Category = "backend"
|
||||
for index := range adaptiveBundle.Families {
|
||||
adaptiveBundle.Families[index].Key = fmt.Sprintf("availability-adaptive-backend-%02d", index+1)
|
||||
adaptiveBundle.Families[index].Specialization = string(domain.SpecializationBackend)
|
||||
}
|
||||
if _, err := adaptiveBank.ImportBundle(ctx, adaptiveBundle); err != nil {
|
||||
t.Fatalf("import additional reviewed backend families for adaptive opening: %v", err)
|
||||
}
|
||||
publishAssessmentAttemptFixtureFamilies(ctx, t, adaptiveBank, adaptiveBundle)
|
||||
}
|
||||
openAssessmentAttemptFixtureCategory(
|
||||
ctx, t, adaptiveBank, adaptiveVersion.ID(), domain.AssessmentCategory("backend"),
|
||||
domain.SpecializationBackend, domain.GradeJunior,
|
||||
)
|
||||
adaptiveCandidate := createSessionHTTPUser(
|
||||
ctx, t, harness.sessionHTTPHarness, "availability-adaptive-candidate@example.test", passwordHash, true,
|
||||
)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", adaptiveCandidate.ID); err != nil {
|
||||
t.Fatalf("set adaptive candidate onboarding step: %v", err)
|
||||
}
|
||||
adaptiveCookie, adaptiveCSRF := loginConsentHTTP(
|
||||
t, harness.sessionHTTPHarness, adaptiveCandidate.Email.Address(), "203.0.113.63:1234",
|
||||
)
|
||||
if response := assessmentAvailabilityBackendQuestionnaireRequest(t, harness, adaptiveCookie.Value, adaptiveCSRF, "203.0.113.64:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save adaptive candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, adaptiveCookie, adaptiveCSRF, "203.0.113.65:1234")
|
||||
unsupported := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", adaptiveCookie.Value, "", "", "203.0.113.66:1234")
|
||||
requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented")
|
||||
var rootCountBefore, idempotencyBefore int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
|
||||
Scan(&rootCountBefore); err != nil {
|
||||
t.Fatalf("read adaptive candidate root attempt count before denied POST: %v", err)
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyBefore); err != nil {
|
||||
t.Fatalf("read idempotency count before denied adaptive POST: %v", err)
|
||||
}
|
||||
adaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
|
||||
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.67:1234")
|
||||
requireSessionProblem(t, adaptiveCreate, http.StatusConflict, "state_conflict")
|
||||
var rootCountAfter int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
|
||||
Scan(&rootCountAfter); err != nil {
|
||||
t.Fatalf("read root attempts after unsupported adaptive create: %v", err)
|
||||
}
|
||||
var idempotencyAfter int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfter); err != nil {
|
||||
t.Fatalf("read idempotency count after denied adaptive POST: %v", err)
|
||||
}
|
||||
if rootCountAfter != rootCountBefore {
|
||||
t.Fatalf("unsupported adaptive create changed root attempt count from %d to %d", rootCountBefore, rootCountAfter)
|
||||
}
|
||||
if idempotencyAfter != idempotencyBefore+1 {
|
||||
t.Fatalf("unsupported adaptive create idempotency row count = %d, want one immutable 409 outcome after %d", idempotencyAfter, idempotencyBefore)
|
||||
}
|
||||
replayedAdaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
|
||||
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.68:1234")
|
||||
requireSessionProblem(t, replayedAdaptiveCreate, http.StatusConflict, "state_conflict")
|
||||
var idempotencyAfterReplay int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfterReplay); err != nil {
|
||||
t.Fatalf("read idempotency count after adaptive 409 replay: %v", err)
|
||||
}
|
||||
if idempotencyAfterReplay != idempotencyAfter {
|
||||
t.Fatalf("adaptive 409 replay added idempotency rows: before replay=%d after=%d", idempotencyAfter, idempotencyAfterReplay)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAvailabilityBackendQuestionnaireRequest(
|
||||
t *testing.T,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
cookie, csrf, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"expected_version": 0,
|
||||
"specializations": []any{
|
||||
map[string]any{
|
||||
"specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"},
|
||||
"stack": []string{}, "experience": nil,
|
||||
},
|
||||
},
|
||||
"work_context": map[string]any{"work_formats": []string{"remote"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal backend-only adaptive questionnaire: %v", err)
|
||||
}
|
||||
return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body),
|
||||
sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr)
|
||||
}
|
||||
|
||||
func createAssessmentAvailabilityEmployer(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
address, err := domain.NewEmailAddress(email)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer,
|
||||
RegisteredAt: harness.clock.Now().Truncate(time.Microsecond),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser(employer) error = %v", err)
|
||||
}
|
||||
if err := harness.store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create synthetic employer: %v", err)
|
||||
}
|
||||
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion,
|
||||
harness.clock.Now().Add(time.Microsecond))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
|
||||
}
|
||||
return verified
|
||||
}
|
||||
|
||||
func findAssessmentAvailabilitySpecialization(
|
||||
t *testing.T,
|
||||
availability assessmentAvailabilityHTTPProjection,
|
||||
want string,
|
||||
) assessmentAvailabilityHTTPSpecialization {
|
||||
t.Helper()
|
||||
for _, specialization := range availability.Specializations {
|
||||
if specialization.Specialization == want {
|
||||
return specialization
|
||||
}
|
||||
}
|
||||
t.Fatalf("availability does not contain specialization %q", want)
|
||||
return assessmentAvailabilityHTTPSpecialization{}
|
||||
}
|
||||
|
||||
func findAssessmentAvailabilityGrade(
|
||||
t *testing.T,
|
||||
specialization assessmentAvailabilityHTTPSpecialization,
|
||||
want string,
|
||||
) assessmentAvailabilityHTTPGrade {
|
||||
t.Helper()
|
||||
for _, grade := range specialization.Grades {
|
||||
if grade.Grade == want {
|
||||
return grade
|
||||
}
|
||||
}
|
||||
t.Fatalf("availability for %q does not contain grade %q", specialization.Specialization, want)
|
||||
return assessmentAvailabilityHTTPGrade{}
|
||||
}
|
||||
|
||||
func TestAssessmentDisclosedFamilyCutoffUsesItemDisclosureTime(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-owner@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234")
|
||||
|
||||
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
|
||||
"availability-disclosure-create", "203.0.113.43:1234")
|
||||
var attempt assessmentAnswerHTTPAttempt
|
||||
if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
|
||||
t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String())
|
||||
}
|
||||
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
|
||||
if len(items) < 3 {
|
||||
t.Fatalf("frozen item count = %d, want at least three items", len(items))
|
||||
}
|
||||
var createdAt time.Time
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT created_at FROM assessment_attempts WHERE id=$1", attempt.ID).Scan(&createdAt); err != nil {
|
||||
t.Fatalf("read attempt creation time: %v", err)
|
||||
}
|
||||
since := createdAt.UTC().Add(time.Microsecond)
|
||||
|
||||
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, attempt.Version, items[0], false)
|
||||
accepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
|
||||
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(firstAnswer),
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "availability-disclosure-answer", "203.0.113.44:1234")
|
||||
if accepted.Code != http.StatusOK {
|
||||
t.Fatalf("answer first item = %d %s", accepted.Code, accepted.Body.String())
|
||||
}
|
||||
_, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, attempt.ID, items[0].ID)
|
||||
if !answeredAt.After(since) {
|
||||
t.Fatalf("first answer timestamp %s must be after cutoff %s to establish distinct disclosure times", answeredAt, since)
|
||||
}
|
||||
|
||||
familyKey := func(itemID uuid.UUID) domain.AssessmentFamilyKey {
|
||||
t.Helper()
|
||||
var stored string
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT family_key FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2", attempt.ID, itemID).Scan(&stored); err != nil {
|
||||
t.Fatalf("read frozen item family key: %v", err)
|
||||
}
|
||||
key, err := domain.ParseAssessmentFamilyKey(stored)
|
||||
if err != nil {
|
||||
t.Fatalf("parse frozen item family key: %v", err)
|
||||
}
|
||||
return key
|
||||
}
|
||||
firstKey, secondKey, thirdKey := familyKey(items[0].ID), familyKey(items[1].ID), familyKey(items[2].ID)
|
||||
var disclosed []domain.AssessmentFamilyKey
|
||||
transactor := postgres.NewTransactor(harness.pool)
|
||||
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var readErr error
|
||||
disclosed, readErr = unit.AssessmentAttempts().ListDisclosedFamilyKeys(txctx, candidate.ID, since)
|
||||
return readErr
|
||||
}); err != nil {
|
||||
t.Fatalf("read disclosed family keys after the rolling cutoff: %v", err)
|
||||
}
|
||||
contains := func(want domain.AssessmentFamilyKey) bool {
|
||||
for _, key := range disclosed {
|
||||
if key == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if contains(firstKey) || !contains(secondKey) || contains(thirdKey) {
|
||||
t.Fatalf("disclosed families = %v; want first excluded, second included, and future third excluded", disclosed)
|
||||
}
|
||||
|
||||
var countBefore int32
|
||||
var latestBefore bool
|
||||
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var readErr error
|
||||
countBefore, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
_, latestBefore, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
|
||||
txctx, candidate.ID, domain.SpecializationBackend, nil,
|
||||
)
|
||||
return readErr
|
||||
}); err != nil {
|
||||
t.Fatalf("read eligible root quota and retry history: %v", err)
|
||||
}
|
||||
if countBefore != 1 || !latestBefore {
|
||||
t.Fatalf("eligible root before platform failure = count %d/latest %v, want 1/true", countBefore, latestBefore)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `
|
||||
WITH failure_time AS (SELECT clock_timestamp() AS at)
|
||||
UPDATE assessment_attempts
|
||||
SET state='insufficient_bank',
|
||||
updated_at=failure_time.at,
|
||||
ended_at=failure_time.at,
|
||||
version=version+1
|
||||
FROM failure_time
|
||||
WHERE id=$1`, attempt.ID); err != nil {
|
||||
t.Fatalf("mark isolated attempt as a system bank failure: %v", err)
|
||||
}
|
||||
var countAfter int32
|
||||
var latestAfter bool
|
||||
var quotaAfter outbound.AssessmentRootQuotaSnapshot
|
||||
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var readErr error
|
||||
countAfter, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
_, latestAfter, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
|
||||
txctx, candidate.ID, domain.SpecializationBackend, nil,
|
||||
)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
asOf, timeErr := unit.AssessmentBank().DatabaseTime(txctx)
|
||||
if timeErr != nil {
|
||||
return timeErr
|
||||
}
|
||||
quotaAfter, readErr = unit.AssessmentAttempts().GetRootQuotaSnapshot(
|
||||
txctx, candidate.ID, createdAt.Add(-time.Second), asOf, 24*time.Hour, 1,
|
||||
)
|
||||
return readErr
|
||||
}); err != nil {
|
||||
t.Fatalf("read quota and retry history after platform failure: %v", err)
|
||||
}
|
||||
if countAfter != 0 || latestAfter || quotaAfter.Count != 0 || quotaAfter.AvailableAt != nil {
|
||||
t.Fatalf("platform failure remains in availability history: count=%d latest=%v quota=%+v, want excluded", countAfter, latestAfter, quotaAfter)
|
||||
}
|
||||
}
|
||||
@@ -122,7 +122,7 @@ func TestAssessmentBank(t *testing.T) {
|
||||
"edit the version": `UPDATE assessment_families SET version = version + 10`,
|
||||
"edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`,
|
||||
"delete": `DELETE FROM assessment_families`,
|
||||
"truncate": `TRUNCATE assessment_families`,
|
||||
"truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events`,
|
||||
} {
|
||||
_, err := fixture.pool.Exec(ctx, statement)
|
||||
assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable")
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const assessmentSignalHTTPTimeout = 6 * time.Minute
|
||||
|
||||
func TestAssessmentSignalsOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentSignalHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
t.Cleanup(harness.pool.Close)
|
||||
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-owner@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.202:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "signal-training", "192.0.2.203:1234")
|
||||
if trainingCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create demo attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
|
||||
}
|
||||
trainingAttempt, trainingItem := assessmentSignalAttemptItem(t, trainingCreate.Body.Bytes())
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.204:1234")
|
||||
|
||||
trainingBody := assessmentSignalBody(t, trainingItem, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
|
||||
trainingSignal := submitAssessmentSignal(t, harness, trainingAttempt, cookie, csrf, "signal-demo", trainingBody, "192.0.2.205:1234")
|
||||
requireSessionProblem(t, trainingSignal, http.StatusConflict, "state_conflict")
|
||||
|
||||
rootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "signal-root", "192.0.2.206:1234")
|
||||
if rootCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create real assessment attempt = %d %s", rootCreate.Code, rootCreate.Body.String())
|
||||
}
|
||||
attemptID, itemID := assessmentSignalAttemptItem(t, rootCreate.Body.Bytes())
|
||||
occurredAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
body := assessmentSignalBody(t, itemID, occurredAt, "fullscreen_exit", nil)
|
||||
|
||||
badItemBody := assessmentSignalBody(t, uuid.New(), occurredAt, "fullscreen_exit", nil)
|
||||
badItem := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-bad-item", badItemBody, "192.0.2.207:1234")
|
||||
if badItem.Code != http.StatusBadRequest {
|
||||
t.Fatalf("foreign item signal = %d %s, want 400", badItem.Code, badItem.Body.String())
|
||||
}
|
||||
oldTimestampBody := assessmentSignalBody(t, itemID, occurredAt.Add(-10*time.Minute), "fullscreen_exit", nil)
|
||||
oldTimestamp := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-old-time", oldTimestampBody, "192.0.2.208:1234")
|
||||
if oldTimestamp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("out-of-window client timestamp = %d %s, want 400", oldTimestamp.Code, oldTimestamp.Body.String())
|
||||
}
|
||||
|
||||
oversizedBody := `{"events":[]}` + strings.Repeat(" ", 32<<10)
|
||||
oversized := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-oversized", oversizedBody, "192.0.2.209:1234")
|
||||
requireSessionProblem(t, oversized, http.StatusRequestEntityTooLarge, "payload_too_large")
|
||||
|
||||
accepted := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.210:1234")
|
||||
assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 1)
|
||||
if accepted.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("signal receipt Cache-Control = %q, want no-store", accepted.Header().Get("Cache-Control"))
|
||||
}
|
||||
var receipt map[string]any
|
||||
if err := json.Unmarshal(accepted.Body.Bytes(), &receipt); err != nil || len(receipt) != 3 {
|
||||
t.Fatalf("receipt fields = %+v, decode error %v", receipt, err)
|
||||
}
|
||||
for _, privateField := range []string{"events", "item_instance_id", "size_bytes", "answer", "score", "result"} {
|
||||
if _, exposed := receipt[privateField]; exposed {
|
||||
t.Fatalf("signal receipt exposed %q", privateField)
|
||||
}
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
|
||||
assertAssessmentSignalImmutability(t, ctx, harness.pool, attemptID)
|
||||
|
||||
replay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.211:1234")
|
||||
if replay.Code != accepted.Code || replay.Body.String() != accepted.Body.String() {
|
||||
t.Fatalf("same-key signal replay = %d %s, want original %d %s", replay.Code, replay.Body.String(), accepted.Code, accepted.Body.String())
|
||||
}
|
||||
changedBody := assessmentSignalBody(t, itemID, occurredAt.Add(time.Second), "fullscreen_exit", nil)
|
||||
changedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.212:1234")
|
||||
requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
|
||||
expiredScope := harness.keyring.IdempotencyScope("assessment_attempt.signals", "signal-first", candidate.ID.String())
|
||||
applicationNow := harness.clock.Now()
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE idempotency_records
|
||||
SET created_at = $2::timestamptz - INTERVAL '25 hours', expires_at = $2::timestamptz - INTERVAL '1 second'
|
||||
WHERE scope_hash = $1`, expiredScope[:], applicationNow); err != nil {
|
||||
t.Fatalf("expire signal idempotency scope fixture: %v", err)
|
||||
}
|
||||
expiredReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.224:1234")
|
||||
assertSignalReceipt(t, expiredReplay, http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 2, 2, 1)
|
||||
|
||||
assertAssessmentSignalMeasurementChecks(t, ctx, harness.pool, attemptID, itemID)
|
||||
|
||||
concurrentBodies := []string{
|
||||
assessmentSignalBody(t, itemID, occurredAt.Add(2*time.Second), "copy", int32Pointer(12)),
|
||||
assessmentSignalBody(t, itemID, occurredAt.Add(3*time.Second), "copy", int32Pointer(13)),
|
||||
}
|
||||
concurrentResponses := make([]*httptest.ResponseRecorder, len(concurrentBodies))
|
||||
start := make(chan struct{})
|
||||
var wait sync.WaitGroup
|
||||
for index := range concurrentBodies {
|
||||
wait.Add(1)
|
||||
go func(index int) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
concurrentResponses[index] = submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-concurrent", concurrentBodies[index], fmt.Sprintf("198.51.100.%d:1234", index+10))
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
acceptedIndex := -1
|
||||
conflictIndex := -1
|
||||
for index, response := range concurrentResponses {
|
||||
switch response.Code {
|
||||
case http.StatusOK:
|
||||
acceptedIndex = index
|
||||
case http.StatusUnprocessableEntity:
|
||||
requireSessionProblem(t, response, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
conflictIndex = index
|
||||
default:
|
||||
t.Fatalf("concurrent signal %d = %d %s", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if acceptedIndex < 0 || conflictIndex < 0 || acceptedIndex == conflictIndex {
|
||||
t.Fatalf("concurrent same-key outcomes accepted=%d conflict=%d", acceptedIndex, conflictIndex)
|
||||
}
|
||||
assertSignalReceipt(t, concurrentResponses[acceptedIndex], http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
|
||||
|
||||
otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-other@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", otherCandidate.ID); err != nil {
|
||||
t.Fatalf("set cascade candidate onboarding step: %v", err)
|
||||
}
|
||||
otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.213:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "192.0.2.220:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save cascade candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "192.0.2.221:1234")
|
||||
foreignAttempt := submitAssessmentSignal(t, harness, attemptID, otherCookie, otherCSRF, "signal-foreign", body, "192.0.2.214:1234")
|
||||
requireSessionProblem(t, foreignAttempt, http.StatusNotFound, "not_found")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
|
||||
otherRootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "signal-cascade", "192.0.2.222:1234")
|
||||
if otherRootCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create cascade candidate attempt = %d %s", otherRootCreate.Code, otherRootCreate.Body.String())
|
||||
}
|
||||
otherAttemptID, otherItemID := assessmentSignalAttemptItem(t, otherRootCreate.Body.Bytes())
|
||||
otherSignalBody := assessmentSignalBody(t, otherItemID, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
|
||||
otherAccepted := submitAssessmentSignal(t, harness, otherAttemptID, otherCookie, otherCSRF, "signal-cascade", otherSignalBody, "192.0.2.223:1234")
|
||||
assertSignalReceipt(t, otherAccepted, http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
|
||||
|
||||
revokeC3 := assessmentAttemptHTTPRequest(t, harness, http.MethodDelete, "/api/v1/me/consents/c3", "",
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "", "192.0.2.215:1234")
|
||||
if revokeC3.Code != http.StatusNoContent {
|
||||
t.Fatalf("revoke C3 = %d %s", revokeC3.Code, revokeC3.Body.String())
|
||||
}
|
||||
withoutC3 := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-no-c3", body, "192.0.2.216:1234")
|
||||
requireSessionProblem(t, withoutC3, http.StatusForbidden, "forbidden")
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.217:1234")
|
||||
|
||||
seedAssessmentSignalCapacity(ctx, t, harness.pool, attemptID, itemID, 10000)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 2)
|
||||
saturatedBody := assessmentSignalBody(t, itemID, occurredAt.Add(4*time.Second), "fullscreen_exit", nil)
|
||||
saturated := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.218:1234")
|
||||
assertSignalReceipt(t, saturated, http.StatusOK, "saturated", 0)
|
||||
saturatedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.219:1234")
|
||||
if saturatedReplay.Body.String() != saturated.Body.String() {
|
||||
t.Fatalf("saturated replay = %s, want %s", saturatedReplay.Body.String(), saturated.Body.String())
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 3)
|
||||
|
||||
for next := signalOutcomeCount(t, ctx, harness.pool, attemptID); next < 30; next++ {
|
||||
key := fmt.Sprintf("signal-rate-%02d", next)
|
||||
response := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, key, saturatedBody, fmt.Sprintf("203.0.113.%d:1234", next+1))
|
||||
assertSignalReceipt(t, response, http.StatusOK, "saturated", 0)
|
||||
}
|
||||
limitedKey := "signal-rate-retry"
|
||||
limited := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, limitedKey, saturatedBody, "203.0.113.80:1234")
|
||||
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
|
||||
if limited.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("rate-limited signal response omitted Retry-After")
|
||||
}
|
||||
scope := harness.keyring.IdempotencyScope("assessment_attempt.signals", limitedKey, candidate.ID.String())
|
||||
var consumed int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash = $1", scope[:]).Scan(&consumed); err != nil {
|
||||
t.Fatalf("check rejected idempotency scope: %v", err)
|
||||
}
|
||||
if consumed != 0 {
|
||||
t.Fatalf("rate-limited idempotency scopes = %d, want 0", consumed)
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 30)
|
||||
|
||||
terminalizeAttempt(t, ctx, harness.pool, attemptID)
|
||||
terminal := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-terminal", saturatedBody, "203.0.113.81:1234")
|
||||
requireSessionProblem(t, terminal, http.StatusConflict, "state_conflict")
|
||||
|
||||
if _, err := harness.pool.Exec(ctx, "DELETE FROM assessment_attempts WHERE id = $1", attemptID); err != nil {
|
||||
t.Fatalf("delete attempt for signal cascade test: %v", err)
|
||||
}
|
||||
deletedAttemptReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "203.0.113.82:1234")
|
||||
requireSessionProblem(t, deletedAttemptReplay, http.StatusNotFound, "not_found")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 0, 0, 0)
|
||||
|
||||
_, accountDeleteErr := harness.pool.Exec(ctx, "DELETE FROM users WHERE id = $1", otherCandidate.ID)
|
||||
assertSQLError(t, "delete account with retained consent history", accountDeleteErr, consentRestrictViolation, "consent_records_subject_id_fkey")
|
||||
var retainedConsentRecords int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", otherCandidate.ID).Scan(&retainedConsentRecords); err != nil {
|
||||
t.Fatalf("count retained consent records after rejected account deletion: %v", err)
|
||||
}
|
||||
if retainedConsentRecords == 0 {
|
||||
t.Fatal("account deletion removed the candidate's retained consent records")
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
|
||||
}
|
||||
|
||||
func assessmentSignalAttemptItem(t *testing.T, body []byte) (uuid.UUID, uuid.UUID) {
|
||||
t.Helper()
|
||||
var attempt struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
CurrentItem *struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
} `json:"current_item"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil || attempt.CurrentItem.ID == uuid.Nil {
|
||||
t.Fatalf("decode signal test attempt and item: %+v, error %v", attempt, err)
|
||||
}
|
||||
return attempt.ID, attempt.CurrentItem.ID
|
||||
}
|
||||
|
||||
func assessmentSignalBody(t *testing.T, itemID uuid.UUID, occurredAt time.Time, kind string, size *int32) string {
|
||||
t.Helper()
|
||||
event := map[string]any{
|
||||
"kind": kind, "item_instance_id": itemID, "occurred_at": occurredAt.UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
if size != nil {
|
||||
event["size_bytes"] = *size
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"events": []any{event}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal signal test body: %v", err)
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func int32Pointer(value int32) *int32 { return &value }
|
||||
|
||||
func submitAssessmentSignal(
|
||||
t *testing.T,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
cookie *http.Cookie,
|
||||
csrf, key, body, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
path := "/api/v1/me/assessment-attempts/" + attemptID.String() + "/signals"
|
||||
return assessmentAttemptHTTPRequest(t, harness, http.MethodPost, path, body,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, key, remoteAddr)
|
||||
}
|
||||
|
||||
func assertSignalReceipt(t *testing.T, response *httptest.ResponseRecorder, status int, receiptStatus string, accepted int) {
|
||||
t.Helper()
|
||||
var receipt struct {
|
||||
Status string `json:"status"`
|
||||
AcceptedEvents int `json:"accepted_events"`
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
}
|
||||
if response.Code != status || json.Unmarshal(response.Body.Bytes(), &receipt) != nil ||
|
||||
receipt.Status != receiptStatus || receipt.AcceptedEvents != accepted || receipt.ReceivedAt.IsZero() {
|
||||
t.Fatalf("signal receipt = %d %s, want %d/%s/%d", response.Code, response.Body.String(), status, receiptStatus, accepted)
|
||||
}
|
||||
}
|
||||
|
||||
func assertSignalStoredCounts(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
wantEvents, wantBatches, wantOutcomes int64,
|
||||
) {
|
||||
t.Helper()
|
||||
for _, check := range []struct {
|
||||
table string
|
||||
want int64
|
||||
}{
|
||||
{table: "assessment_signal_events", want: wantEvents},
|
||||
{table: "assessment_signal_batches", want: wantBatches},
|
||||
{table: "assessment_signal_idempotency_outcomes", want: wantOutcomes},
|
||||
} {
|
||||
var got int64
|
||||
query := "SELECT count(*) FROM " + check.table + " WHERE attempt_id = $1"
|
||||
if err := harness.pool.QueryRow(ctx, query, attemptID).Scan(&got); err != nil {
|
||||
t.Fatalf("count %s: %v", check.table, err)
|
||||
}
|
||||
if got != check.want {
|
||||
t.Fatalf("%s rows = %d, want %d", check.table, got, check.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAssessmentSignalMeasurementChecks(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID, itemID uuid.UUID) {
|
||||
t.Helper()
|
||||
for index, kind := range []string{"focus_loss", "copy"} {
|
||||
batchID := uuid.New()
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin measurement check %d: %v", index, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES ($1, $2, clock_timestamp(), 1)`, batchID, attemptID); err != nil {
|
||||
t.Fatalf("insert measurement boundary batch: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO assessment_signal_events (
|
||||
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
|
||||
) VALUES ($1, $2, 1, $3, $4, clock_timestamp(), NULL, NULL)`, batchID, attemptID, itemID, kind)
|
||||
assertPgError(t, "reject null measurement for "+kind, err, "23514", "assessment_signal_events_measurement")
|
||||
if err := tx.Rollback(ctx); err != nil {
|
||||
t.Fatalf("rollback measurement check %d: %v", index, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAssessmentSignalImmutability(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
|
||||
t.Helper()
|
||||
var batchID uuid.UUID
|
||||
if err := pool.QueryRow(ctx, `SELECT id FROM assessment_signal_batches
|
||||
WHERE attempt_id = $1 ORDER BY received_at, id LIMIT 1`, attemptID).Scan(&batchID); err != nil {
|
||||
t.Fatalf("read signal batch for immutability checks: %v", err)
|
||||
}
|
||||
_, err := pool.Exec(ctx, "UPDATE assessment_signal_batches SET event_count = event_count WHERE id = $1", batchID)
|
||||
assertPgError(t, "reject signal batch update", err, "23000", "assessment_signal_batches_immutable")
|
||||
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_batches WHERE id = $1", batchID)
|
||||
assertPgError(t, "reject direct signal batch deletion", err, "23000", "assessment_signal_batches_immutable")
|
||||
var ordinal int32
|
||||
if err := pool.QueryRow(ctx, `SELECT ordinal FROM assessment_signal_events
|
||||
WHERE batch_id = $1 ORDER BY ordinal LIMIT 1`, batchID).Scan(&ordinal); err != nil {
|
||||
t.Fatalf("read signal event for immutability checks: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, "UPDATE assessment_signal_events SET occurred_at = occurred_at WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
|
||||
assertPgError(t, "reject signal event update", err, "23000", "assessment_signal_events_immutable")
|
||||
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_events WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
|
||||
assertPgError(t, "reject direct signal event deletion", err, "23000", "assessment_signal_events_immutable")
|
||||
|
||||
var scopeHash []byte
|
||||
if err := pool.QueryRow(ctx, `SELECT scope_hash FROM assessment_signal_idempotency_outcomes
|
||||
WHERE attempt_id = $1 ORDER BY received_at LIMIT 1`, attemptID).Scan(&scopeHash); err != nil {
|
||||
t.Fatalf("read signal outcome for immutability check: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, "UPDATE assessment_signal_idempotency_outcomes SET status = status WHERE scope_hash = $1", scopeHash)
|
||||
assertPgError(t, "reject signal outcome update", err, "23000", "assessment_signal_idempotency_outcomes_immutable")
|
||||
}
|
||||
|
||||
func seedAssessmentSignalCapacity(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
pool *pgxpool.Pool,
|
||||
attemptID, itemID uuid.UUID,
|
||||
wantTotal int64,
|
||||
) {
|
||||
t.Helper()
|
||||
var existing int64
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_events WHERE attempt_id = $1", attemptID).Scan(&existing); err != nil {
|
||||
t.Fatalf("read signal count before capacity fixture: %v", err)
|
||||
}
|
||||
remaining := wantTotal - existing
|
||||
if remaining <= 0 {
|
||||
t.Fatalf("capacity fixture has no remaining rows: existing=%d target=%d", existing, wantTotal)
|
||||
}
|
||||
batchCount := int((remaining + 49) / 50)
|
||||
batchIDs := make([]uuid.UUID, batchCount)
|
||||
for index := range batchIDs {
|
||||
batchIDs[index] = uuid.New()
|
||||
}
|
||||
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("begin bounded capacity fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events DISABLE TRIGGER assessment_signal_event_guard"); err != nil {
|
||||
t.Fatalf("disable only the capacity backstop for isolated fixture: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
SELECT batch.batch_id, $1, clock_timestamp(), LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)`, attemptID, batchIDs, remaining); err != nil {
|
||||
t.Fatalf("insert bounded signal capacity batches: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `WITH batches AS (
|
||||
SELECT batch.batch_id, LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer AS event_count
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)
|
||||
)
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
|
||||
)
|
||||
SELECT batches.batch_id, $1, event.ordinality::integer, $4, 'fullscreen_exit', clock_timestamp(), NULL, NULL
|
||||
FROM batches
|
||||
CROSS JOIN LATERAL generate_series(1, batches.event_count) AS event(ordinality)`, attemptID, batchIDs, remaining, itemID); err != nil {
|
||||
t.Fatalf("insert bounded signal capacity events: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events ENABLE TRIGGER assessment_signal_event_guard"); err != nil {
|
||||
t.Fatalf("restore signal capacity trigger: %v", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit isolated signal capacity fixture: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func signalOutcomeCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_idempotency_outcomes WHERE attempt_id = $1", attemptID).Scan(&count); err != nil {
|
||||
t.Fatalf("count signal receipts: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const candidateCardAccessMigrationVersion = 30
|
||||
|
||||
func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("Up() error = %v", err)
|
||||
}
|
||||
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
identity := identityFixture{
|
||||
ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now,
|
||||
}
|
||||
candidate := identity.createUser(t, "candidate@example.com", domain.ScenarioCandidate, now.Add(-time.Hour))
|
||||
organizationFixture := organizationFixture{
|
||||
ctx: ctx, pool: pool, identity: identity,
|
||||
transactor: postgresadapter.NewTransactor(pool), now: now,
|
||||
}
|
||||
owner := organizationFixture.employer(t, "owner@example.com")
|
||||
organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events (
|
||||
id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at
|
||||
) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`,
|
||||
uuid.New(), candidate.ID, organization.ID(), owner.ID, now); err != nil {
|
||||
t.Fatalf("insert retained card access event: %v", err)
|
||||
}
|
||||
|
||||
_, err := migrator.DownOne(ctx)
|
||||
assertPgError(t, "DownOne() with retained card access history", err, privacyIntegrityViolation, "candidate_card_access_events_retained")
|
||||
|
||||
var tableExists bool
|
||||
if err := pool.QueryRow(ctx, `SELECT to_regclass('public.candidate_card_access_events') IS NOT NULL`).Scan(&tableExists); err != nil {
|
||||
t.Fatalf("check access history table after refused rollback: %v", err)
|
||||
}
|
||||
if !tableExists {
|
||||
t.Fatal("candidate_card_access_events was removed despite retained history")
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1`, candidate.ID).Scan(&count); err != nil {
|
||||
t.Fatalf("read retained access event after refused rollback: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("retained access event count = %d, want 1", count)
|
||||
}
|
||||
statuses, err := migrator.Status(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Status() after refused rollback: %v", err)
|
||||
}
|
||||
version30Applied := false
|
||||
for _, status := range statuses {
|
||||
if status.Version == candidateCardAccessMigrationVersion {
|
||||
version30Applied = status.Applied
|
||||
break
|
||||
}
|
||||
}
|
||||
if !version30Applied {
|
||||
t.Fatal("migration 30 is not applied after its guarded Down() failed")
|
||||
}
|
||||
}
|
||||
|
||||
func rollBackToCandidateCardAccessVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) {
|
||||
t.Helper()
|
||||
for {
|
||||
statuses, err := migrator.Status(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Status() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err)
|
||||
}
|
||||
version30Applied := false
|
||||
laterMigrationApplied := false
|
||||
for _, status := range statuses {
|
||||
if !status.Applied {
|
||||
continue
|
||||
}
|
||||
if status.Version == candidateCardAccessMigrationVersion {
|
||||
version30Applied = true
|
||||
}
|
||||
if status.Version > candidateCardAccessMigrationVersion {
|
||||
laterMigrationApplied = true
|
||||
}
|
||||
}
|
||||
if !version30Applied {
|
||||
t.Fatalf("migration %d is not applied", candidateCardAccessMigrationVersion)
|
||||
}
|
||||
if !laterMigrationApplied {
|
||||
return
|
||||
}
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err)
|
||||
}
|
||||
if result.Version <= candidateCardAccessMigrationVersion {
|
||||
t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, candidateCardAccessMigrationVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/anonymousprofile"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/consent"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const candidatePrivacyHTTPTestTimeout = 5 * time.Minute
|
||||
|
||||
type candidatePrivacyHTTPHarness struct {
|
||||
*sessionHTTPHarness
|
||||
key domain.CandidateViewPseudonymKey
|
||||
settings *candidateprivacy.Service
|
||||
}
|
||||
|
||||
func TestCandidatePrivacyHTTPReadsRecheckCurrentVisibility(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyHTTPTestTimeout)
|
||||
defer cancel()
|
||||
harness := newCandidatePrivacyHTTPHarness(ctx, t, env)
|
||||
truncateTables(ctx, t, harness.pool, usersDependentTables...)
|
||||
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), harness.clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
||||
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
||||
}
|
||||
|
||||
now := harness.clock.Now()
|
||||
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
|
||||
organizations := organizationFixture{
|
||||
ctx: ctx, pool: harness.pool, identity: identity,
|
||||
transactor: postgresadapter.NewTransactor(harness.pool), now: now,
|
||||
}
|
||||
privacy := candidatePrivacyFixture{
|
||||
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
|
||||
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
|
||||
}
|
||||
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, now: now}
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-target@example.test", passwordHash, true)
|
||||
candidates := []domain.User{candidate}
|
||||
for index := 1; index < 5; index++ {
|
||||
other := privacy.candidate(t, fmt.Sprintf("privacy-cohort-%d@example.test", index))
|
||||
verifyPrivacyCohortCandidate(t, privacy, other)
|
||||
candidates = append(candidates, other)
|
||||
}
|
||||
for _, member := range candidates {
|
||||
input := domain.CandidateProfileInput{Stack: privacyCohortConfirmedItems("go")}
|
||||
if member.ID == candidate.ID {
|
||||
input.FullName = confirmedDecision("Private Candidate Name")
|
||||
input.Email = confirmedDecision("private-card-email@example.test")
|
||||
}
|
||||
profiles.save(t, member.ID, input, 0)
|
||||
if member.ID == candidate.ID {
|
||||
continue
|
||||
}
|
||||
c2 := privacy.grant(t, member.ID, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, member.ID, c2.ID(), 0, domain.CardFieldStack)
|
||||
}
|
||||
|
||||
employer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
organizationA := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization A"), now)
|
||||
organizationB := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization B"), now)
|
||||
organizationC := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization C"), now)
|
||||
inactiveOrganization := organizations.create(t, employer, organizations.completeProfile(t, "Privacy inactive organization"), now)
|
||||
organizations.setMembershipState(t, inactiveOrganization.ID(), employer.ID, domain.MembershipStateLeft)
|
||||
foreignEmployer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-foreign-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
foreignOrganization := organizations.create(t, foreignEmployer, organizations.completeProfile(t, "Privacy foreign organization"), now)
|
||||
|
||||
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.170:1234")
|
||||
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.171:1234")
|
||||
initialSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.172:1234")
|
||||
if initialSettings.Code != http.StatusOK || initialSettings.Header().Get("Cache-Control") != "no-store" ||
|
||||
!strings.Contains(initialSettings.Body.String(), `"state":"closed"`) || !strings.Contains(initialSettings.Body.String(), `"closed_reason":"never_published"`) {
|
||||
t.Fatalf("initial privacy settings = %d Cache-Control=%q %s", initialSettings.Code, initialSettings.Header().Get("Cache-Control"), initialSettings.Body.String())
|
||||
}
|
||||
c2Grant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
|
||||
"c2", privacyC2Version, sessionHTTPTestOrigin)
|
||||
if c2Grant.Code != http.StatusOK {
|
||||
t.Fatalf("C2 grant = %d %s", c2Grant.Code, c2Grant.Body.String())
|
||||
}
|
||||
publication := harness.request(t, http.MethodPut, "/api/v1/me/privacy/publication",
|
||||
`{"expected_version":0,"state":"published","fields":["stack"]}`,
|
||||
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.173:1234")
|
||||
if publication.Code != http.StatusOK || publication.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("publication = %d Cache-Control=%q %s", publication.Code, publication.Header().Get("Cache-Control"), publication.Body.String())
|
||||
}
|
||||
|
||||
aliasA, err := harness.key.ForOrganization(organizationA.ID(), candidate.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(A) error = %v", err)
|
||||
}
|
||||
aliasB, err := harness.key.ForOrganization(organizationB.ID(), candidate.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(B) error = %v", err)
|
||||
}
|
||||
if aliasA == aliasB {
|
||||
t.Fatalf("organization-scoped aliases unexpectedly match: %q", aliasA)
|
||||
}
|
||||
assertCandidatePrivacyContactPortFixture(t, ctx, harness, employer.ID, organizationA.ID(), candidate.ID, aliasA)
|
||||
unknownOrganization := uuid.New()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
organizationID uuid.UUID
|
||||
wantStatus int
|
||||
wantCode string
|
||||
useCandidate bool
|
||||
}{
|
||||
{name: "active employer membership", organizationID: organizationA.ID(), wantStatus: http.StatusOK},
|
||||
{name: "candidate account", organizationID: organizationA.ID(), wantStatus: http.StatusForbidden, wantCode: "forbidden", useCandidate: true},
|
||||
{name: "inactive membership", organizationID: inactiveOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
||||
{name: "foreign membership", organizationID: foreignOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
||||
{name: "unknown organization", organizationID: unknownOrganization, wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
cookie := employerCookie.Value
|
||||
if test.useCandidate {
|
||||
cookie = candidateCookie.Value
|
||||
}
|
||||
response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, test.organizationID, aliasA, cookie)
|
||||
if response.Code != test.wantStatus {
|
||||
t.Fatalf("card response = %d %s, want %d", response.Code, response.Body.String(), test.wantStatus)
|
||||
}
|
||||
if test.wantCode != "" {
|
||||
requireSessionProblem(t, response, test.wantStatus, test.wantCode)
|
||||
}
|
||||
if test.wantStatus == http.StatusOK {
|
||||
if response.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("card Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
|
||||
}
|
||||
var card struct {
|
||||
Pseudonym string `json:"pseudonym"`
|
||||
Stack []string `json:"stack"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &card); err != nil || card.Pseudonym != aliasA || len(card.Stack) != 1 || card.Stack[0] != "go" {
|
||||
t.Fatalf("anonymous card = %+v, %v; body=%s", card, err, response.Body.String())
|
||||
}
|
||||
for _, privateValue := range []string{candidate.ID.String(), candidate.Email.Address(), "Private Candidate Name", "private-card-email@example.test"} {
|
||||
if strings.Contains(response.Body.String(), privateValue) {
|
||||
t.Errorf("anonymous card contains private value %q", privateValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
||||
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationA.ID(), []string{"stack"})
|
||||
|
||||
preview := harness.request(t, http.MethodGet, "/api/v1/me/privacy/preview", "", "", candidateCookie.Value, "", "192.0.2.174:1234")
|
||||
if preview.Code != http.StatusOK || preview.Header().Get("Cache-Control") != "no-store" ||
|
||||
strings.Contains(preview.Body.String(), aliasA) || strings.Contains(preview.Body.String(), candidate.ID.String()) {
|
||||
t.Fatalf("private preview = %d Cache-Control=%q %s", preview.Code, preview.Header().Get("Cache-Control"), preview.Body.String())
|
||||
}
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
||||
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
||||
|
||||
hideA := harness.request(t, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
|
||||
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.175:1234")
|
||||
if hideA.Code != http.StatusOK || hideA.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("hide organization A = %d Cache-Control=%q %s", hideA.Code, hideA.Header().Get("Cache-Control"), hideA.Body.String())
|
||||
}
|
||||
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("card after hiding A = %d %s, want generic 404", response.Code, response.Body.String())
|
||||
}
|
||||
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusOK {
|
||||
t.Fatalf("card for B after hiding A = %d %s, want independent organization access", response.Code, response.Body.String())
|
||||
}
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
||||
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationB.ID(), []string{"stack"})
|
||||
unhideA := harness.request(t, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
|
||||
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.176:1234")
|
||||
if unhideA.Code != http.StatusNoContent {
|
||||
t.Fatalf("unhide organization A = %d %s, want 204", unhideA.Code, unhideA.Body.String())
|
||||
}
|
||||
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusOK {
|
||||
t.Fatalf("card after unhiding A = %d %s, want restored visibility while C2 is active", response.Code, response.Body.String())
|
||||
}
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
||||
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 2)
|
||||
directHidden, err := harness.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: candidate.ID, Limit: 20})
|
||||
if err != nil || len(directHidden.Items) != 0 || directHidden.HasMore {
|
||||
t.Fatalf("direct hidden organization list = %+v, %v; want an empty page after unhide", directHidden, err)
|
||||
}
|
||||
hiddenList := harness.request(t, http.MethodGet, "/api/v1/me/privacy/hidden-organizations", "", "", candidateCookie.Value, "", "192.0.2.177:1234")
|
||||
if hiddenList.Code != http.StatusOK || !strings.Contains(hiddenList.Body.String(), `"items":[]`) || hiddenList.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("hidden organizations after unhide = %d Cache-Control=%q %s", hiddenList.Code, hiddenList.Header().Get("Cache-Control"), hiddenList.Body.String())
|
||||
}
|
||||
privacyHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/history", "", "", candidateCookie.Value, "", "192.0.2.178:1234")
|
||||
if privacyHistory.Code != http.StatusOK || !strings.Contains(privacyHistory.Body.String(), "publication_opened") ||
|
||||
!strings.Contains(privacyHistory.Body.String(), "organization_hidden") || !strings.Contains(privacyHistory.Body.String(), "organization_unhidden") {
|
||||
t.Fatalf("privacy history = %d %s", privacyHistory.Code, privacyHistory.Body.String())
|
||||
}
|
||||
accessHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/access-history", "", "", candidateCookie.Value, "", "192.0.2.179:1234")
|
||||
if accessHistory.Code != http.StatusOK || accessHistory.Header().Get("Cache-Control") != "no-store" || !strings.Contains(accessHistory.Body.String(), "Privacy organization A") || !strings.Contains(accessHistory.Body.String(), "Privacy organization B") {
|
||||
t.Fatalf("card access history = %d Cache-Control=%q %s", accessHistory.Code, accessHistory.Header().Get("Cache-Control"), accessHistory.Body.String())
|
||||
}
|
||||
|
||||
// Hold the candidate account row so the employer read reaches and waits on
|
||||
// its FOR SHARE visibility lock. Commit the competing hide only after the
|
||||
// lock wait is observed; a visibility recheck must reject the stale cohort.
|
||||
lockTx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin visibility race transaction: %v", err)
|
||||
}
|
||||
defer func() { _ = lockTx.Rollback(context.Background()) }()
|
||||
if _, err := lockTx.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR UPDATE`, candidate.ID); err != nil {
|
||||
t.Fatalf("lock candidate row for visibility race: %v", err)
|
||||
}
|
||||
aliasC, err := harness.key.ForOrganization(organizationC.ID(), candidate.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(C) error = %v", err)
|
||||
}
|
||||
raceResult := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() {
|
||||
raceResult <- candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationC.ID(), aliasC, employerCookie.Value)
|
||||
}()
|
||||
monitor := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-monitor")
|
||||
if waitEvent, waiting := waitForLockWait(ctx, monitor, "candidate-privacy-http"); !waiting || waitEvent == "" {
|
||||
t.Fatalf("card read did not wait for candidate visibility lock, wait event %q", waitEvent)
|
||||
}
|
||||
if _, err := lockTx.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, organizationC.ID(), now.Add(time.Second)); err != nil {
|
||||
t.Fatalf("commit concurrent candidate hide fixture: %v", err)
|
||||
}
|
||||
if err := lockTx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit visibility race transaction: %v", err)
|
||||
}
|
||||
raceResponse := <-raceResult
|
||||
if raceResponse.Code != http.StatusNotFound {
|
||||
t.Fatalf("card read that waited behind a hide = %d %s, want generic 404", raceResponse.Code, raceResponse.Body.String())
|
||||
}
|
||||
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
|
||||
|
||||
revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.180:1234")
|
||||
if revoke.Code != http.StatusNoContent {
|
||||
t.Fatalf("C2 revoke = %d %s, want 204", revoke.Code, revoke.Body.String())
|
||||
}
|
||||
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("card after C2 revoke = %d %s, want generic 404", response.Code, response.Body.String())
|
||||
}
|
||||
regrant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
|
||||
"c2", privacyC2Version, sessionHTTPTestOrigin)
|
||||
if regrant.Code != http.StatusOK {
|
||||
t.Fatalf("C2 regrant = %d %s", regrant.Code, regrant.Body.String())
|
||||
}
|
||||
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("card after C2 regrant without republication = %d %s, want generic 404", response.Code, response.Body.String())
|
||||
}
|
||||
closedSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.181:1234")
|
||||
if closedSettings.Code != http.StatusOK || !strings.Contains(closedSettings.Body.String(), `"state":"closed"`) {
|
||||
t.Fatalf("settings after C2 revoke and regrant = %d %s, want closed publication", closedSettings.Code, closedSettings.Body.String())
|
||||
}
|
||||
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
||||
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
||||
}
|
||||
|
||||
func newCandidatePrivacyHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *candidatePrivacyHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-http")
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
key, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials,
|
||||
Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
|
||||
}, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionService() error = %v", err)
|
||||
}
|
||||
consentStore := postgresadapter.NewConsentStore(pool)
|
||||
consentQueries := consent.NewQueryService(consentStore, clock.Now)
|
||||
consentCommands := consent.NewService(transactor, clock.Now)
|
||||
privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateprivacy.NewService() error = %v", err)
|
||||
}
|
||||
quota := companyquota.NewService(clock.Now)
|
||||
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now)
|
||||
privacyViews, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: clock.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateview.NewService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
||||
consentHandler := v1.NewConsentHandler(consentQueries, consentCommands)
|
||||
privacyHandler := v1.NewPrivacyHandler(privacyViews, privacySettings, env.Config.AppPublicURL)
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &candidatePrivacyHTTPHarness{
|
||||
sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs},
|
||||
key: key, settings: privacySettings,
|
||||
}
|
||||
}
|
||||
|
||||
func candidatePrivacyCardRequest(t *testing.T, harness *sessionHTTPHarness, organizationID uuid.UUID, handle, cookie string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", organizationID, handle)
|
||||
return harness.request(t, http.MethodGet, path, "", "", cookie, "", "192.0.2.190:1234")
|
||||
}
|
||||
|
||||
func assertPrivacyCardAccessCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed'`, candidateID, organizationID).Scan(&count); err != nil {
|
||||
t.Fatalf("count candidate card access events: %v", err)
|
||||
}
|
||||
if count != want {
|
||||
t.Fatalf("card access event count = %d, want %d", count, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPrivacyCardViewQuotaCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, candidateID, organizationID).Scan(&count); err != nil {
|
||||
t.Fatalf("count card-view quota usage: %v", err)
|
||||
}
|
||||
if count != want {
|
||||
t.Fatalf("card-view quota usage count = %d, want %d", count, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPrivacyCardAccessFields(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want []string) {
|
||||
t.Helper()
|
||||
var fields []string
|
||||
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id LIMIT 1`, candidateID, organizationID).Scan(&fields); err != nil {
|
||||
t.Fatalf("read card-view audit fields: %v", err)
|
||||
}
|
||||
if len(fields) != len(want) {
|
||||
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
|
||||
}
|
||||
for index := range fields {
|
||||
if fields[index] != want[index] {
|
||||
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type candidatePrivacyContactGrantState uint8
|
||||
|
||||
const (
|
||||
candidatePrivacyContactGrantAbsent candidatePrivacyContactGrantState = iota
|
||||
candidatePrivacyContactGrantActive
|
||||
candidatePrivacyContactGrantRevoked
|
||||
)
|
||||
|
||||
type candidatePrivacyContactGrantFixture struct {
|
||||
state candidatePrivacyContactGrantState
|
||||
workflowAccepted bool
|
||||
organizationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
fields domain.ContactFieldSet
|
||||
}
|
||||
|
||||
func (fixture *candidatePrivacyContactGrantFixture) currentFields(organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
|
||||
if fixture == nil || fixture.state != candidatePrivacyContactGrantActive ||
|
||||
fixture.organizationID != organizationID || fixture.candidateID != candidateID {
|
||||
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
|
||||
}
|
||||
// Workflow acceptance is deliberately not used as authorization evidence.
|
||||
return fixture.fields, nil
|
||||
}
|
||||
|
||||
type candidatePrivacyContactTransactor struct {
|
||||
inner outbound.Transactor
|
||||
fixture *candidatePrivacyContactGrantFixture
|
||||
}
|
||||
|
||||
func (transactor candidatePrivacyContactTransactor) WithinTransaction(
|
||||
ctx context.Context,
|
||||
fn func(context.Context, outbound.UnitOfWork) error,
|
||||
) error {
|
||||
return transactor.inner.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
view := candidatePrivacyContactView{
|
||||
PrivacyViewRepository: unit.PrivacyView(),
|
||||
fixture: transactor.fixture,
|
||||
}
|
||||
return fn(ctx, candidatePrivacyContactUnit{UnitOfWork: unit, view: view})
|
||||
})
|
||||
}
|
||||
|
||||
type candidatePrivacyContactUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
view outbound.PrivacyViewRepository
|
||||
}
|
||||
|
||||
func (unit candidatePrivacyContactUnit) PrivacyView() outbound.PrivacyViewRepository {
|
||||
return unit.view
|
||||
}
|
||||
|
||||
type candidatePrivacyContactView struct {
|
||||
outbound.PrivacyViewRepository
|
||||
fixture *candidatePrivacyContactGrantFixture
|
||||
}
|
||||
|
||||
func (view candidatePrivacyContactView) CurrentFields(_ context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
|
||||
return view.fixture.currentFields(organizationID, candidateID)
|
||||
}
|
||||
|
||||
func assertCandidatePrivacyContactPortFixture(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *candidatePrivacyHTTPHarness,
|
||||
actorID, organizationID, candidateID uuid.UUID,
|
||||
handle string,
|
||||
) {
|
||||
t.Helper()
|
||||
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail, domain.ContactFieldPhone)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactFieldSet() error = %v", err)
|
||||
}
|
||||
fixture := &candidatePrivacyContactGrantFixture{
|
||||
organizationID: organizationID,
|
||||
candidateID: candidateID,
|
||||
fields: fields,
|
||||
}
|
||||
transactor := candidatePrivacyContactTransactor{
|
||||
inner: postgresadapter.NewTransactor(harness.pool),
|
||||
fixture: fixture,
|
||||
}
|
||||
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(harness.pool), harness.key, harness.clock.Now)
|
||||
quota := companyquota.NewService(harness.clock.Now)
|
||||
service, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: harness.key, Clock: harness.clock.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateview.NewService() error = %v", err)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
state candidatePrivacyContactGrantState
|
||||
want bool
|
||||
}{
|
||||
{name: "active grant returns selected fields", state: candidatePrivacyContactGrantActive, want: true},
|
||||
{name: "workflow acceptance without a grant stays closed", state: candidatePrivacyContactGrantAbsent},
|
||||
{name: "revoked grant stays closed", state: candidatePrivacyContactGrantRevoked},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
fixture.state = test.state
|
||||
fixture.workflowAccepted = true
|
||||
got, err := service.CurrentContactFields(ctx, actorID, organizationID, handle)
|
||||
if test.want {
|
||||
if err != nil {
|
||||
t.Fatalf("CurrentContactFields() error = %v", err)
|
||||
}
|
||||
gotFields := got.Fields()
|
||||
wantFields := fields.Fields()
|
||||
if len(gotFields) != len(wantFields) {
|
||||
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
|
||||
}
|
||||
for index := range wantFields {
|
||||
if gotFields[index] != wantFields[index] {
|
||||
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, outbound.ErrContactAccessClosed) {
|
||||
t.Fatalf("CurrentContactFields() error = %v, want closed contact access", err)
|
||||
}
|
||||
assertPrivacyContactAudit(t, ctx, harness.pool, candidateID, organizationID, test.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertPrivacyContactAudit(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, checkFields bool) {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&count); err != nil {
|
||||
t.Fatalf("count contact-read audit events: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("contact-read audit count = %d, want one successful read and no records for denied reads", count)
|
||||
}
|
||||
if !checkFields {
|
||||
return
|
||||
}
|
||||
var fields []string
|
||||
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&fields); err != nil {
|
||||
t.Fatalf("read contact-read audit fields: %v", err)
|
||||
}
|
||||
if len(fields) != 2 || fields[0] != "email" || fields[1] != "phone" {
|
||||
t.Fatalf("contact-read audit fields = %v, want [email phone]", fields)
|
||||
}
|
||||
}
|
||||
@@ -36,11 +36,13 @@ var (
|
||||
candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"}
|
||||
candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"}
|
||||
candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"}
|
||||
candidateCardAccessEventsTable = pgx.Identifier{"candidate_card_access_events"}
|
||||
// candidatePrivacyTables reference users, organizations, and the consent
|
||||
// ledger, so every TRUNCATE of those names them through
|
||||
// usersDependentTables.
|
||||
candidatePrivacyTables = []pgx.Identifier{
|
||||
candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, candidateSearchStatusesTable, candidatePublicationsTable,
|
||||
candidateCardAccessEventsTable, candidatePrivacyEventsTable, candidateHiddenOrganizationsTable,
|
||||
candidateSearchStatusesTable, candidatePublicationsTable,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -772,6 +774,66 @@ func TestCandidatePrivacyStorage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestCandidateCardAccessEventRetentionAndActorAnonymization(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
|
||||
fixture := candidatePrivacyFixture{
|
||||
ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity,
|
||||
organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now},
|
||||
ledger: postgresadapter.NewConsentStore(pool), now: now,
|
||||
}
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
|
||||
candidate := fixture.candidate(t, "privacy-owner@example.test")
|
||||
verifyPrivacyCohortCandidate(t, fixture, candidate)
|
||||
organizationOwner := fixture.organizations.employer(t, "privacy-organization-owner@example.test")
|
||||
organization := fixture.organizations.create(t, organizationOwner,
|
||||
fixture.organizations.completeProfile(t, "Access history organization"), now)
|
||||
actor := fixture.candidate(t, "privacy-viewer@example.test")
|
||||
|
||||
access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
||||
CandidateID: candidate.ID, OrganizationID: organization.ID(), ActorID: actor.ID,
|
||||
Kind: domain.CandidateCardAccessCardViewed, OccurredAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateCardAccess() error = %v", err)
|
||||
}
|
||||
queries := sqlc.New(pool)
|
||||
if err := queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{
|
||||
ID: uuidParam(access.ID()), CandidateID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization.ID()),
|
||||
ActorID: uuidParam(actor.ID), Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: timeParam(access.OccurredAt()),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertCandidateCardAccessEvent(pseudonym-only) error = %v", err)
|
||||
}
|
||||
|
||||
_, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET field_codes = ARRAY['location'] WHERE id = $1`, access.ID())
|
||||
assertPgError(t, "reject card access field update", err, privacyIntegrityViolation, "candidate_card_access_events_immutable")
|
||||
_, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET actor_id = NULL WHERE id = $1`, access.ID())
|
||||
assertPgError(t, "reject direct card access actor anonymization", err, privacyIntegrityViolation, "candidate_card_access_events_immutable")
|
||||
_, err = pool.Exec(ctx, `DELETE FROM candidate_card_access_events WHERE id = $1`, access.ID())
|
||||
assertPgError(t, "reject card access deletion", err, privacyIntegrityViolation, "candidate_card_access_events_retained")
|
||||
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, actor.ID); err != nil {
|
||||
t.Fatalf("DELETE audit actor = %v", err)
|
||||
}
|
||||
var storedCandidate, storedOrganization uuid.UUID
|
||||
var storedActor pgtype.UUID
|
||||
var kind string
|
||||
var fields []string
|
||||
if err := pool.QueryRow(ctx, `SELECT candidate_id, organization_id, actor_id, kind, field_codes FROM candidate_card_access_events WHERE id = $1`, access.ID()).
|
||||
Scan(&storedCandidate, &storedOrganization, &storedActor, &kind, &fields); err != nil {
|
||||
t.Fatalf("read retained card access = %v", err)
|
||||
}
|
||||
if storedCandidate != candidate.ID || storedOrganization != organization.ID() || storedActor.Valid ||
|
||||
kind != string(domain.CandidateCardAccessCardViewed) || len(fields) != 0 {
|
||||
t.Fatalf("retained access = candidate %s org %s actor %+v kind %s fields %v", storedCandidate, storedOrganization, storedActor, kind, fields)
|
||||
}
|
||||
}
|
||||
|
||||
func containsWord(column, word string) bool {
|
||||
for _, part := range splitIdentifier(column) {
|
||||
if part == word {
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
needusecase "lincodex/backend/internal/usecase/need"
|
||||
"lincodex/backend/internal/usecase/organization"
|
||||
)
|
||||
|
||||
func TestOrganizationNeedOwnerWorkflowOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
|
||||
defer cancel()
|
||||
harness := newNeedHTTPHarness(ctx, t, env)
|
||||
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
|
||||
truncateTables(ctx, t, harness.pool, resetTables...)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
now := harness.clock.Now()
|
||||
owner := createOrganizationHTTPUser(ctx, t, harness, "need-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
foreign := createOrganizationHTTPUser(ctx, t, harness, "need-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
recruiter := createOrganizationHTTPUser(ctx, t, harness, "need-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
candidate := createOrganizationHTTPUser(ctx, t, harness, "need-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
|
||||
unverified := createOrganizationHTTPUser(ctx, t, harness, "need-unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now)
|
||||
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
|
||||
foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address())
|
||||
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
|
||||
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
|
||||
unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass,
|
||||
env.Config.AppPublicURL, "", "192.0.2.44:1234")
|
||||
requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified")
|
||||
|
||||
organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "need-http-company")
|
||||
insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now)
|
||||
basePath := "/api/v1/organizations/" + organizationID.String() + "/needs"
|
||||
initialSource := `{"title":"Payments backend","source_text":"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."}`
|
||||
createdResponses := parallelNeedRequests(t, harness, http.MethodPost, basePath, initialSource,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-create-1", 2)
|
||||
if createdResponses[0].Code != http.StatusCreated || createdResponses[1].Code != http.StatusCreated ||
|
||||
createdResponses[0].Header().Get("Cache-Control") != "no-store" || string(createdResponses[0].Body.Bytes()) != string(createdResponses[1].Body.Bytes()) {
|
||||
t.Fatalf("concurrent need create responses = %d %s and %d %s, want the same 201 response",
|
||||
createdResponses[0].Code, createdResponses[0].Body.String(), createdResponses[1].Code, createdResponses[1].Body.String())
|
||||
}
|
||||
originalBody := append([]byte(nil), createdResponses[0].Body.Bytes()...)
|
||||
created := decodeNeedHTTPResponse(t, originalBody)
|
||||
if created.ID == uuid.Nil || created.Version != 1 || created.RequirementsVersion != 1 || created.Recommendations.Status != string(domain.NeedRecommendationsNotAvailable) {
|
||||
t.Fatalf("created need identity or recommendation state = %+v", created)
|
||||
}
|
||||
if created.Requirements.Specialization.Status != string(domain.NeedValueExtracted) ||
|
||||
created.Requirements.Specialization.Source == nil || created.Requirements.Specialization.Source.Origin != string(domain.NeedValueExtractedFromText) ||
|
||||
created.Requirements.Grade.Status != string(domain.NeedValueUnknown) || created.Requirements.Grade.Value != nil {
|
||||
t.Fatalf("source extraction invented or omitted a need value: %+v", created.Requirements)
|
||||
}
|
||||
gotSkills := make([]string, 0, len(created.Requirements.RequiredSkills))
|
||||
for _, skill := range created.Requirements.RequiredSkills {
|
||||
if skill.Status == string(domain.NeedItemExtracted) && skill.Source.Origin == string(domain.NeedValueExtractedFromText) {
|
||||
gotSkills = append(gotSkills, skill.Name)
|
||||
}
|
||||
}
|
||||
if !equalNeedStrings(gotSkills, []string{"Go", "PostgreSQL", "Temporal"}) {
|
||||
t.Fatalf("extracted required skills = %v, want Go, PostgreSQL, Temporal", gotSkills)
|
||||
}
|
||||
if len(created.Readiness.MissingFields) == 0 {
|
||||
t.Fatal("incomplete source text need has no readiness questions")
|
||||
}
|
||||
needPath := basePath + "/" + created.ID.String()
|
||||
|
||||
changedKeyBody := `{"title":"Different request"}`
|
||||
changedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, changedKeyBody,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
|
||||
requireSessionProblem(t, changedKey, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
|
||||
invalidNUL := organizationHTTPRequest(t, harness, http.MethodPost, basePath,
|
||||
`{"title":"Bad\u0000title"}`, env.Config.AppPublicURL, ownerSession, "need-http-invalid-nul")
|
||||
requireSessionProblem(t, invalidNUL, http.StatusBadRequest, "validation_failed")
|
||||
var invalidProblem struct {
|
||||
Errors []struct {
|
||||
Pointer string `json:"pointer"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(invalidNUL.Body.Bytes(), &invalidProblem); err != nil || len(invalidProblem.Errors) == 0 {
|
||||
t.Fatalf("NUL validation body = %s, decode error %v", invalidNUL.Body.String(), err)
|
||||
}
|
||||
updated := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
|
||||
`{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"}]}`,
|
||||
env.Config.AppPublicURL, ownerSession, "")
|
||||
if updated.Code != http.StatusOK {
|
||||
t.Fatalf("confirm extracted skill = %d %s, want 200", updated.Code, updated.Body.String())
|
||||
}
|
||||
confirmed := decodeNeedHTTPResponse(t, updated.Body.Bytes())
|
||||
if confirmed.Version != 2 || confirmed.RequirementsVersion != 2 || confirmed.Recommendations.Status != string(domain.NeedRecommendationsPending) ||
|
||||
len(confirmed.Requirements.RequiredSkills) != 1 || confirmed.Requirements.RequiredSkills[0].Name != "Go" ||
|
||||
confirmed.Requirements.RequiredSkills[0].Status != string(domain.NeedItemConfirmed) {
|
||||
t.Fatalf("confirmed need state = %+v", confirmed)
|
||||
}
|
||||
currentRead := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", ownerSession, "")
|
||||
if currentRead.Code != http.StatusOK || string(currentRead.Body.Bytes()) == string(originalBody) {
|
||||
t.Fatalf("current need read = %d %s, want edited current version", currentRead.Code, currentRead.Body.String())
|
||||
}
|
||||
immutableReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, initialSource,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
|
||||
if immutableReplay.Code != http.StatusCreated || string(immutableReplay.Body.Bytes()) != string(originalBody) {
|
||||
t.Fatalf("live create replay = %d %s, want the original 201 body %s", immutableReplay.Code, immutableReplay.Body.String(), originalBody)
|
||||
}
|
||||
|
||||
expiryKeyBody := `{"title":"Boundary need"}`
|
||||
expiryKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
|
||||
if expiryKey.Code != http.StatusCreated {
|
||||
t.Fatalf("create need for expiry boundary = %d %s, want 201", expiryKey.Code, expiryKey.Body.String())
|
||||
}
|
||||
expiryOriginal := decodeNeedHTTPResponse(t, expiryKey.Body.Bytes())
|
||||
boundary := harness.clock.Now()
|
||||
expired, err := harness.pool.Exec(ctx,
|
||||
`UPDATE idempotency_records AS record
|
||||
SET created_at = $1, expires_at = $2
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM organization_need_creation_results AS result
|
||||
WHERE result.scope_hash = record.scope_hash
|
||||
AND result.snapshot #>> '{need,title}' = 'Boundary need'
|
||||
)`,
|
||||
boundary.Add(-outbound.IdempotencyRetention), boundary)
|
||||
if err != nil {
|
||||
t.Fatalf("expire need create key at exact 24-hour boundary: %v", err)
|
||||
}
|
||||
if expired.RowsAffected() != 1 {
|
||||
t.Fatalf("expired need create rows = %d, want 1", expired.RowsAffected())
|
||||
}
|
||||
reusedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
|
||||
if reusedKey.Code != http.StatusCreated {
|
||||
t.Fatalf("create after exact 24-hour replay boundary = %d %s, want a new 201", reusedKey.Code, reusedKey.Body.String())
|
||||
}
|
||||
replacement := decodeNeedHTTPResponse(t, reusedKey.Body.Bytes())
|
||||
if replacement.ID == expiryOriginal.ID || replacement.Version != 1 {
|
||||
t.Fatalf("expired key reused old need snapshot: %+v", replacement)
|
||||
}
|
||||
expiredReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
|
||||
if expiredReplay.Code != http.StatusCreated || string(expiredReplay.Body.Bytes()) != string(reusedKey.Body.Bytes()) {
|
||||
t.Fatalf("replay after expired-key reuse = %d %s, want exact replacement response %s", expiredReplay.Code, expiredReplay.Body.String(), reusedKey.Body.String())
|
||||
}
|
||||
|
||||
identicalUpdates := parallelNeedRequests(t, harness, http.MethodPatch, needPath,
|
||||
`{"expected_version":2,"title":"Platform engineer"}`, env.Config.AppPublicURL, ownerSession, "", 2)
|
||||
for index, response := range identicalUpdates {
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("identical concurrent update %d = %d %s, want 200", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
concurrentCurrent := decodeNeedHTTPResponse(t, identicalUpdates[0].Body.Bytes())
|
||||
if concurrentCurrent.Version != 3 || concurrentCurrent.Title != "Platform engineer" {
|
||||
t.Fatalf("identical concurrent update result = version %d title %q, want version 3", concurrentCurrent.Version, concurrentCurrent.Title)
|
||||
}
|
||||
differentUpdates := parallelNeedRequestsWithBodies(t, harness, http.MethodPatch, needPath,
|
||||
[]string{`{"expected_version":3,"title":"Payments platform"}`, `{"expected_version":3,"title":"Cloud platform"}`},
|
||||
env.Config.AppPublicURL, ownerSession)
|
||||
var winner needHTTPResponse
|
||||
successes := 0
|
||||
conflicts := 0
|
||||
for index, response := range differentUpdates {
|
||||
switch response.Code {
|
||||
case http.StatusOK:
|
||||
successes++
|
||||
winner = decodeNeedHTTPResponse(t, response.Body.Bytes())
|
||||
case http.StatusPreconditionFailed:
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("different concurrent update %d = %d %s, want 200 or 412", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if successes != 1 || conflicts != 1 || winner.Version != 4 {
|
||||
t.Fatalf("different concurrent updates had %d successes and %d conflicts; winner = %+v, want one version 4 success", successes, conflicts, winner)
|
||||
}
|
||||
|
||||
staleNoOp := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
|
||||
fmt.Sprintf(`{"expected_version":3,"title":%q}`, winner.Title), env.Config.AppPublicURL, ownerSession, "")
|
||||
if staleNoOp.Code != http.StatusOK || decodeNeedHTTPResponse(t, staleNoOp.Body.Bytes()).Version != 4 {
|
||||
t.Fatalf("stale no-op update = %d %s, want current version 4", staleNoOp.Code, staleNoOp.Body.String())
|
||||
}
|
||||
staleInvalid := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
|
||||
`{"expected_version":3,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"go","status":"confirmed"}]}`,
|
||||
env.Config.AppPublicURL, ownerSession, "")
|
||||
requireSessionProblem(t, staleInvalid, http.StatusPreconditionFailed, "version_conflict")
|
||||
|
||||
secondNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Second need"}`,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-create-2")
|
||||
thirdNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Third need"}`,
|
||||
env.Config.AppPublicURL, ownerSession, "need-http-create-3")
|
||||
if secondNeed.Code != http.StatusCreated || thirdNeed.Code != http.StatusCreated {
|
||||
t.Fatalf("create needs for pagination = %d %s and %d %s, want 201", secondNeed.Code, secondNeed.Body.String(), thirdNeed.Code, thirdNeed.Body.String())
|
||||
}
|
||||
firstPage := readNeedHTTPPage(t, harness, ownerSession, basePath+"?limit=1")
|
||||
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
|
||||
t.Fatalf("first need page = %+v, want one item and cursor", firstPage)
|
||||
}
|
||||
secondPage := readNeedHTTPPage(t, harness, ownerSession,
|
||||
basePath+"?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor))
|
||||
if len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil ||
|
||||
firstPage.Items[0].ID == secondPage.Items[0].ID {
|
||||
t.Fatalf("second need page = %+v, want the next distinct item", secondPage)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
session organizationHTTPSession
|
||||
want int
|
||||
}{
|
||||
{name: "foreign owner", session: foreignSession, want: http.StatusNotFound},
|
||||
{name: "active recruiter", session: recruiterSession, want: http.StatusForbidden},
|
||||
{name: "candidate", session: candidateSession, want: http.StatusForbidden},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
response := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", test.session, "")
|
||||
if response.Code != test.want {
|
||||
t.Fatalf("need read = %d %s, want %d", response.Code, response.Body.String(), test.want)
|
||||
}
|
||||
if strings.Contains(response.Body.String(), "Payments backend") || strings.Contains(response.Body.String(), "PostgreSQL") {
|
||||
t.Fatalf("denied response contains need data: %s", response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
var versionCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2", organizationID, created.ID).Scan(&versionCount); err != nil {
|
||||
t.Fatalf("read immutable need history: %v", err)
|
||||
}
|
||||
if versionCount != 4 {
|
||||
t.Fatalf("need history rows = %d, want 4", versionCount)
|
||||
}
|
||||
}
|
||||
|
||||
type needHTTPResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Version int64 `json:"version"`
|
||||
RequirementsVersion int64 `json:"requirements_version"`
|
||||
Requirements struct {
|
||||
Specialization struct {
|
||||
Status string `json:"status"`
|
||||
Value *string `json:"value"`
|
||||
Source *struct {
|
||||
Origin string `json:"origin"`
|
||||
} `json:"source"`
|
||||
} `json:"specialization"`
|
||||
Grade struct {
|
||||
Status string `json:"status"`
|
||||
Value *string `json:"value"`
|
||||
} `json:"grade"`
|
||||
RequiredSkills []struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
Source struct {
|
||||
Origin string `json:"origin"`
|
||||
} `json:"source"`
|
||||
} `json:"required_skills"`
|
||||
} `json:"requirements"`
|
||||
Readiness struct {
|
||||
MissingFields []json.RawMessage `json:"missing_fields"`
|
||||
} `json:"readiness"`
|
||||
Recommendations struct {
|
||||
Status string `json:"status"`
|
||||
} `json:"recommendations"`
|
||||
}
|
||||
|
||||
func decodeNeedHTTPResponse(t *testing.T, encoded []byte) needHTTPResponse {
|
||||
t.Helper()
|
||||
var response needHTTPResponse
|
||||
if err := json.Unmarshal(encoded, &response); err != nil {
|
||||
t.Fatalf("decode need response: %v", err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func equalNeedStrings(left, right []string) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for index := range left {
|
||||
if left[index] != right[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type needHTTPPage struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
|
||||
func readNeedHTTPPage(t *testing.T, harness *sessionHTTPHarness, session organizationHTTPSession, path string) needHTTPPage {
|
||||
t.Helper()
|
||||
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("list organization needs = %d %s, want 200", response.Code, response.Body.String())
|
||||
}
|
||||
var page needHTTPPage
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatalf("decode need list response: %v", err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func parallelNeedRequests(
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
method, path, body, origin string,
|
||||
session organizationHTTPSession,
|
||||
idempotencyKey string,
|
||||
count int,
|
||||
) []*httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
responses := make([]*httptest.ResponseRecorder, count)
|
||||
var group sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for index := range count {
|
||||
group.Go(func() {
|
||||
<-start
|
||||
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, idempotencyKey)
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
return responses
|
||||
}
|
||||
|
||||
func parallelNeedRequestsWithBodies(
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
method, path string,
|
||||
bodies []string,
|
||||
origin string,
|
||||
session organizationHTTPSession,
|
||||
) []*httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
responses := make([]*httptest.ResponseRecorder, len(bodies))
|
||||
var group sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for index, body := range bodies {
|
||||
group.Go(func() {
|
||||
<-start
|
||||
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, "")
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
return responses
|
||||
}
|
||||
|
||||
func newNeedHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
sessionService, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: postgresadapter.NewTransactor(pool),
|
||||
Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials,
|
||||
Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
|
||||
}, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
|
||||
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: env.Config.IdentitySessionIdleTimeout,
|
||||
AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionService() error = %v", err)
|
||||
}
|
||||
organizationService, err := organization.NewService(organization.Dependencies{
|
||||
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("organization.NewService() error = %v", err)
|
||||
}
|
||||
needService, err := needusecase.NewService(needusecase.Dependencies{
|
||||
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("need.NewService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil,
|
||||
v1.WithSessionService(sessionService),
|
||||
v1.WithPublicOrigin(env.Config.AppPublicURL),
|
||||
)
|
||||
organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
|
||||
needHandler := v1.NewNeedHandler(needService)
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
|
||||
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
|
||||
}
|
||||
|
||||
func needHTTPPath(organizationID, needID uuid.UUID) string {
|
||||
return fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
@@ -310,13 +311,207 @@ func TestOrganizationNeedsStorage(t *testing.T) {
|
||||
largeID := uuid.New()
|
||||
body["id"] = largeID.String()
|
||||
body["requirements_version"] = 1
|
||||
body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotBytes+1)
|
||||
body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotStorageBytes+1)
|
||||
oversized, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("encode oversized storage snapshot: %v", err)
|
||||
}
|
||||
insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot")
|
||||
})
|
||||
|
||||
t.Run("maximum bounded need shape stays within JSONB representation headroom", func(t *testing.T) {
|
||||
reset(t)
|
||||
owner := fixture.employer(t, "owner@example.com")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Большой профиль"), now)
|
||||
maximum := maximumBoundedIntegrationNeed(t, organization.ID(), now.Add(time.Minute))
|
||||
compact, err := json.Marshal(maximum.Snapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal maximum bounded need: %v", err)
|
||||
}
|
||||
if len(compact) > domain.MaxNeedSnapshotBytes {
|
||||
t.Fatalf("maximum bounded need compact JSON = %d bytes, exceeds %d", len(compact), domain.MaxNeedSnapshotBytes)
|
||||
}
|
||||
if len(compact) < 64*1024 {
|
||||
t.Fatalf("maximum bounded need compact JSON = %d bytes, want a substantial combined source and requirement payload", len(compact))
|
||||
}
|
||||
fixture.createNeed(t, maximum)
|
||||
var storedBytes int
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT octet_length(snapshot::text)
|
||||
FROM organization_need_versions
|
||||
WHERE organization_id = $1 AND need_id = $2 AND version = 1
|
||||
`, organization.ID(), maximum.ID()).Scan(&storedBytes); err != nil {
|
||||
t.Fatalf("measure maximum need JSONB text size: %v", err)
|
||||
}
|
||||
if storedBytes < len(compact) || storedBytes-len(compact) > domain.MaxNeedJSONBTextHeadroom || storedBytes > domain.MaxNeedSnapshotStorageBytes {
|
||||
t.Fatalf("maximum need storage = %d bytes, compact=%d headroom=%d; want storage within the explicit JSONB margin",
|
||||
storedBytes, len(compact), domain.MaxNeedJSONBTextHeadroom)
|
||||
}
|
||||
if _, err := fixture.getNeed(organization.ID(), maximum.ID()); err != nil {
|
||||
t.Fatalf("restore maximum bounded need: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations to rollback test database: %v", err)
|
||||
}
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
fixture := organizationFixture{
|
||||
ctx: ctx, pool: pool,
|
||||
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
|
||||
transactor: postgresadapter.NewTransactor(pool), now: now,
|
||||
}
|
||||
scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize))
|
||||
fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize))
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO idempotency_records (scope_hash, fingerprint, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`, scope, fingerprint, now, now.Add(outbound.IdempotencyRetention)); err != nil {
|
||||
t.Fatalf("insert live idempotency row: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
||||
VALUES ($1, '{"need":{},"readiness":{},"recommendations":{}}'::jsonb)
|
||||
`, scope); err != nil {
|
||||
t.Fatalf("insert live creation result: %v", err)
|
||||
}
|
||||
if _, err := migrator.DownOne(ctx); err == nil {
|
||||
t.Fatal("DownOne() succeeded while a need creation replay remained live")
|
||||
}
|
||||
assertNeedResultMigrationPresent(ctx, t, pool, 1)
|
||||
|
||||
if _, err := pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2 WHERE scope_hash = $3",
|
||||
now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil {
|
||||
t.Fatalf("expire idempotency replay before checking historical bounds: %v", err)
|
||||
}
|
||||
owner := fixture.employer(t, "need-migration-owner@example.test")
|
||||
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
|
||||
need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute))
|
||||
encoded, err := json.Marshal(need.Snapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal rollback snapshot: %v", err)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(encoded, &body); err != nil {
|
||||
t.Fatalf("decode rollback snapshot: %v", err)
|
||||
}
|
||||
body["rollback_bound_fixture"] = strings.Repeat("p", 265000)
|
||||
encoded, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("encode rollback-bound snapshot: %v", err)
|
||||
}
|
||||
var storageSize int
|
||||
if err := pool.QueryRow(ctx, "SELECT octet_length($1::jsonb::text)", encoded).Scan(&storageSize); err != nil {
|
||||
t.Fatalf("measure rollback-bound snapshot: %v", err)
|
||||
}
|
||||
if storageSize <= domain.MaxNeedSnapshotBytes || storageSize > domain.MaxNeedSnapshotStorageBytes {
|
||||
t.Fatalf("rollback fixture JSONB size = %d, want (%d, %d]", storageSize, domain.MaxNeedSnapshotBytes, domain.MaxNeedSnapshotStorageBytes)
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin oversized-history fixture transaction: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at)
|
||||
VALUES ($1, $2, 1, 1, $3, $3)
|
||||
`, need.ID(), organization.ID(), now.Add(time.Minute)); err != nil {
|
||||
t.Fatalf("insert oversized-history need parent: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot)
|
||||
VALUES ($1, $2, 1, $3::jsonb)
|
||||
`, organization.ID(), need.ID(), encoded); err != nil {
|
||||
t.Fatalf("insert snapshot within current storage bound: %v", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit oversized-history fixture: %v", err)
|
||||
}
|
||||
if _, err := migrator.DownOne(ctx); err == nil {
|
||||
t.Fatal("DownOne() succeeded while retained need history exceeded the prior bound")
|
||||
}
|
||||
assertNeedResultMigrationPresent(ctx, t, pool, 1)
|
||||
}
|
||||
|
||||
func assertNeedResultMigrationPresent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, resultRows int64) {
|
||||
t.Helper()
|
||||
var tableExists bool
|
||||
var rows int64
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT to_regclass('organization_need_creation_results') IS NOT NULL,
|
||||
(SELECT count(*) FROM organization_need_creation_results)
|
||||
`).Scan(&tableExists, &rows); err != nil {
|
||||
t.Fatalf("inspect migration preflight after rollback attempt: %v", err)
|
||||
}
|
||||
if !tableExists || rows != resultRows {
|
||||
t.Fatalf("migration rollback changed state: result table exists=%t rows=%d, want true/%d", tableExists, rows, resultRows)
|
||||
}
|
||||
}
|
||||
|
||||
func maximumBoundedIntegrationNeed(t *testing.T, organizationID uuid.UUID, at time.Time) domain.Need {
|
||||
t.Helper()
|
||||
quote := strings.Repeat("q", 300)
|
||||
extractedVersion := int64(1)
|
||||
extractor := "need-rules.2026-10.1"
|
||||
source := domain.NeedValueSource{
|
||||
Origin: domain.NeedValueExtractedFromText, Quote: "e,
|
||||
ExtractedInVersion: &extractedVersion, ExtractionVersion: &extractor,
|
||||
}
|
||||
makeSkills := func(prefix string) []domain.NeedSkill {
|
||||
skills := make([]domain.NeedSkill, 0, 30)
|
||||
for index := range 30 {
|
||||
name := fmt.Sprintf("%s-%02d-%s", prefix, index, strings.Repeat("s", 80))
|
||||
skills = append(skills, domain.NeedSkill{Name: name, Status: domain.NeedItemExtracted, Source: source})
|
||||
}
|
||||
return skills
|
||||
}
|
||||
tasks := make([]domain.NeedTask, 0, 20)
|
||||
for index := range 20 {
|
||||
prefix := fmt.Sprintf("task-%02d-", index)
|
||||
tasks = append(tasks, domain.NeedTask{
|
||||
Text: prefix + strings.Repeat("t", 290-len(prefix)), Status: domain.NeedItemExtracted, Source: source,
|
||||
})
|
||||
}
|
||||
rejected := make([]domain.NeedRejectedSuggestion, 0, domain.MaxNeedRejectedSuggestions)
|
||||
for index := range domain.MaxNeedRejectedSuggestions {
|
||||
rejected = append(rejected, domain.NeedRejectedSuggestion{
|
||||
Field: domain.NeedRejectedSkills, Value: fmt.Sprintf("rejected-%02d-%s", index, strings.Repeat("r", 280)),
|
||||
})
|
||||
}
|
||||
manual := &domain.NeedValueSource{Origin: domain.NeedValueManual}
|
||||
formats := []domain.NeedWorkFormat{domain.NeedWorkFormatRemote, domain.NeedWorkFormatOffice, domain.NeedWorkFormatHybrid}
|
||||
grade := domain.GradeSenior
|
||||
specialization := domain.SpecializationBackend
|
||||
domainName := strings.Repeat("d", 100)
|
||||
location := strings.Repeat("l", 100)
|
||||
formatValue := formats
|
||||
salary := domain.NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"}
|
||||
requirements := domain.NeedRequirements{
|
||||
Specialization: domain.NeedValue[domain.SpecializationCode]{Status: domain.NeedValueConfirmed, Value: &specialization, Source: manual},
|
||||
Grade: domain.NeedValue[domain.GradeCode]{Status: domain.NeedValueConfirmed, Value: &grade, Source: manual},
|
||||
RequiredSkills: makeSkills("required"), DesiredSkills: makeSkills("desired"), Tasks: tasks,
|
||||
Domain: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &domainName, Source: manual},
|
||||
WorkFormats: domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueConfirmed, Value: &formatValue, Source: manual},
|
||||
Location: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &location, Source: manual},
|
||||
Salary: domain.NeedValue[domain.NeedSalaryRange]{Status: domain.NeedValueConfirmed, Value: &salary, Source: manual},
|
||||
}
|
||||
need, err := domain.NewNeed(domain.NeedSnapshot{
|
||||
ID: uuid.New(), OrganizationID: organizationID, Title: strings.Repeat("n", 200), SourceText: needIntegrationPointer(strings.Repeat("s", 10000)),
|
||||
Version: 1, RequirementsVersion: 1, Requirements: requirements, RejectedSuggestions: rejected,
|
||||
CreatedAt: at, UpdatedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed(maximum bounded shape) error = %v", err)
|
||||
}
|
||||
return need
|
||||
}
|
||||
|
||||
func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) {
|
||||
|
||||
@@ -39,17 +39,27 @@ var (
|
||||
// organizationTables are emptied together: memberships reference both
|
||||
// users and organizations. Creation snapshots reference idempotency records.
|
||||
organizationTables = []pgx.Identifier{
|
||||
{"candidate_card_access_events"},
|
||||
{"organization_need_versions"}, {"organization_needs"},
|
||||
{"organization_need_creation_results"},
|
||||
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
|
||||
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
|
||||
}
|
||||
candidateQuestionnaireTables = []pgx.Identifier{
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
assessmentAttemptTables = []pgx.Identifier{
|
||||
{"assessment_attempt_results"},
|
||||
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
|
||||
{"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"},
|
||||
}
|
||||
supportCaseTables = []pgx.Identifier{
|
||||
{"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"},
|
||||
}
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
@@ -242,9 +242,13 @@ func TestPolicyVersions(t *testing.T) {
|
||||
SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}},
|
||||
{name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}},
|
||||
{name: "delete of every row", sql: `DELETE FROM policy_versions`},
|
||||
// Include referencing quota tables so PostgreSQL reaches the
|
||||
// Include referencing tables so PostgreSQL reaches the
|
||||
// immutable-policy trigger instead of its foreign-key precheck.
|
||||
{name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, company_card_view_quota_usage`},
|
||||
{name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage,
|
||||
company_card_view_quota_usage, assessment_training_bank_bindings,
|
||||
assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items,
|
||||
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
|
||||
assessment_signal_events, assessment_signal_batches, assessment_attempt_results`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/anonymousprofile"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestOrganizationAnonymousCandidateProjectionHonorsC2AndHiding(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
|
||||
policies := postgresadapter.NewPolicyStore(pool)
|
||||
if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
||||
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
||||
}
|
||||
fixture := candidatePrivacyFixture{
|
||||
ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity,
|
||||
organizations: organizationFixture{
|
||||
ctx: ctx, pool: pool, identity: identity,
|
||||
transactor: postgresadapter.NewTransactor(pool), now: now,
|
||||
},
|
||||
ledger: postgresadapter.NewConsentStore(pool), now: now,
|
||||
}
|
||||
truncateTables(ctx, t, pool, usersDependentTables...)
|
||||
owner := fixture.organizations.employer(t, "owner@example.test")
|
||||
organization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization"), now)
|
||||
organizationB := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization B"), now)
|
||||
profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now}
|
||||
|
||||
visible := make([]uuid.UUID, 0, 5)
|
||||
for index := range 5 {
|
||||
candidate := fixture.candidate(t, fmt.Sprintf("visible-%d@example.test", index))
|
||||
verifyPrivacyCohortCandidate(t, fixture, candidate)
|
||||
consent := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Duration(index)*time.Second))
|
||||
fixture.publish(t, candidate.ID, consent.ID(), 0,
|
||||
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
|
||||
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility,
|
||||
)
|
||||
profiles.save(t, candidate.ID, domain.CandidateProfileInput{
|
||||
FullName: confirmedDecision("Private Name Marker"),
|
||||
Email: confirmedDecision("private-contact-marker@example.test"),
|
||||
Stack: privacyCohortConfirmedItems(
|
||||
"go", "UniqueStackMarker",
|
||||
),
|
||||
Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}),
|
||||
Experience: privacyCohortConfirmedItems(domain.ProfileExperience{
|
||||
EmployerName: "Private Employer Marker", Specialization: domain.SpecializationBackend,
|
||||
StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private Summary Marker",
|
||||
}),
|
||||
SoftSkills: privacyCohortConfirmedItems("Private Soft Skill Marker"),
|
||||
Location: confirmedDecision("Private Location Marker"),
|
||||
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{
|
||||
Amount: 180_000, TaxBasis: domain.ProfileTaxNet,
|
||||
}),
|
||||
}, 0)
|
||||
if _, err := fixture.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
|
||||
UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now),
|
||||
}); err != nil {
|
||||
t.Fatalf("InsertCandidateQuestionnaire() error = %v", err)
|
||||
}
|
||||
visible = append(visible, candidate.ID)
|
||||
}
|
||||
|
||||
hidden := fixture.candidate(t, "hidden@example.test")
|
||||
verifyPrivacyCohortCandidate(t, fixture, hidden)
|
||||
hiddenConsent := fixture.grant(t, hidden.ID, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
fixture.publish(t, hidden.ID, hiddenConsent.ID(), 0, domain.CardFieldStack)
|
||||
fixture.hide(t, hidden.ID, organization.ID(), now)
|
||||
|
||||
revoked := fixture.candidate(t, "revoked@example.test")
|
||||
verifyPrivacyCohortCandidate(t, fixture, revoked)
|
||||
revokedConsent := fixture.grant(t, revoked.ID, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
fixture.publish(t, revoked.ID, revokedConsent.ID(), 0, domain.CardFieldStack)
|
||||
fixture.revokeC2(t, revoked.ID, now.Add(time.Minute))
|
||||
|
||||
reader := postgresadapter.NewPrivacyCohortStore(pool)
|
||||
sources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources() error = %v", err)
|
||||
}
|
||||
if len(sources) != len(visible) {
|
||||
t.Fatalf("visible sources = %d, want %d after excluding hidden and revoked candidates", len(sources), len(visible))
|
||||
}
|
||||
sourcesB, err := reader.ListVisibleCandidateViewSources(ctx, organizationB.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources(B) error = %v", err)
|
||||
}
|
||||
sourcesAAgain, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources(A again) error = %v", err)
|
||||
}
|
||||
if len(sourcesB) != len(visible)+1 || len(sourcesAAgain) != len(visible) {
|
||||
t.Fatalf("visible sources A/B/A = %d/%d/%d, want %d/6/%d with B still seeing the organization-hidden candidate", len(sources), len(sourcesB), len(sourcesAAgain), len(visible), len(visible))
|
||||
}
|
||||
candidateID := sources[0].CandidateID()
|
||||
if !privacyCohortHasSource(sourcesB, candidateID) || !privacyCohortHasSource(sourcesAAgain, candidateID) {
|
||||
t.Fatal("the same candidate was not visible in repository reads A/B/A")
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("dedicated-anonymous-view-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
aliasA, err := key.ForOrganization(organization.ID(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(A) error = %v", err)
|
||||
}
|
||||
aliasB, err := key.ForOrganization(organizationB.ID(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(B) error = %v", err)
|
||||
}
|
||||
aliasAAgain, err := key.ForOrganization(organization.ID(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization(A again) error = %v", err)
|
||||
}
|
||||
if aliasA != aliasAAgain || aliasA == aliasB {
|
||||
t.Fatalf("repository-backed A/B/A aliases = %q/%q/%q, want stable A and distinct B", aliasA, aliasB, aliasAAgain)
|
||||
}
|
||||
service := anonymousprofile.NewService(reader, key, func() time.Time { return now.Add(2 * time.Minute) })
|
||||
views, err := service.ListVisible(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible() error = %v", err)
|
||||
}
|
||||
if len(views) != 5 {
|
||||
t.Fatalf("ListVisible() returned %d views, want the five-member cohort", len(views))
|
||||
}
|
||||
if !privacyCohortHasViewAlias(views, aliasA) {
|
||||
t.Fatal("organization A projection did not contain its stable candidate alias")
|
||||
}
|
||||
viewsB, err := service.ListVisible(ctx, organizationB.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(B) error = %v", err)
|
||||
}
|
||||
viewsAAgain, err := service.ListVisible(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(A again) error = %v", err)
|
||||
}
|
||||
if len(viewsB) != 5 || !privacyCohortHasViewAlias(viewsB, aliasB) || !privacyCohortHasViewAlias(viewsAAgain, aliasAAgain) {
|
||||
t.Fatalf("service projection A/B/A = %d/%d/%d aliases present=%t/%t", len(views), len(viewsB), len(viewsAAgain), privacyCohortHasViewAlias(viewsB, aliasB), privacyCohortHasViewAlias(viewsAAgain, aliasAAgain))
|
||||
}
|
||||
for _, view := range views {
|
||||
if view.ExperienceBand == nil || *view.ExperienceBand != domain.CandidateExperienceBandThreeToSix {
|
||||
t.Errorf("experience band = %v, want 3_6", view.ExperienceBand)
|
||||
}
|
||||
if len(view.Skills) != 1 || view.Skills[0] != domain.CandidateViewSkillGo {
|
||||
t.Errorf("skills = %v, want only the recognized canonical value", view.Skills)
|
||||
}
|
||||
if len(view.WorkFormats) != 1 || view.WorkFormats[0] != domain.QuestionnaireWorkFormatRemote {
|
||||
t.Errorf("work formats = %v, want explicitly selected remote", view.WorkFormats)
|
||||
}
|
||||
if len(view.Categories) != 0 || len(view.SelfAssessment) != 1 || view.SelfAssessment[0].DeclaredGrade == nil {
|
||||
t.Errorf("confirmed categories and self-assessment were not kept separate: categories=%v self_assessment=%v", view.Categories, view.SelfAssessment)
|
||||
}
|
||||
if view.SalaryCompatibility != nil {
|
||||
t.Errorf("salary compatibility = %v, want unknown without an approved computed result", view.SalaryCompatibility)
|
||||
}
|
||||
}
|
||||
encoded, err := json.Marshal(views)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
for _, marker := range []string{
|
||||
"Private Name Marker", "private-contact-marker@example.test", "Private Employer Marker",
|
||||
"Private Summary Marker", "Private Soft Skill Marker", "Private Location Marker",
|
||||
"UniqueStackMarker", "180000", hidden.ID.String(), revoked.ID.String(),
|
||||
} {
|
||||
if strings.Contains(string(encoded), marker) {
|
||||
t.Errorf("organization-facing cohort contains private marker %q", marker)
|
||||
}
|
||||
}
|
||||
|
||||
fixture.hide(t, visible[0], organization.ID(), now.Add(3*time.Minute))
|
||||
fourSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources(four) error = %v", err)
|
||||
}
|
||||
fourViews, err := service.ListVisible(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(four) error = %v", err)
|
||||
}
|
||||
if len(fourSources) != 4 || len(fourViews) != 0 {
|
||||
t.Fatalf("cohort of four sources/views = %d/%d, want 4/0 after suppression", len(fourSources), len(fourViews))
|
||||
}
|
||||
for index := 1; index < len(visible)-1; index++ {
|
||||
fixture.hide(t, visible[index], organization.ID(), now.Add(time.Duration(index+3)*time.Minute))
|
||||
}
|
||||
oneSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources(one) error = %v", err)
|
||||
}
|
||||
oneViews, err := service.ListVisible(ctx, organization.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisible(one) error = %v", err)
|
||||
}
|
||||
if len(oneSources) != 1 || len(oneViews) != 0 {
|
||||
t.Fatalf("cohort of one source/view = %d/%d, want 1/0 after suppression", len(oneSources), len(oneViews))
|
||||
}
|
||||
}
|
||||
|
||||
func privacyCohortHasSource(sources []domain.CandidateViewSource, candidateID uuid.UUID) bool {
|
||||
for _, source := range sources {
|
||||
if source.CandidateID() == candidateID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func privacyCohortHasViewAlias(views []domain.AnonymousCandidateViewDTO, alias string) bool {
|
||||
for _, view := range views {
|
||||
if view.Pseudonym == alias {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func verifyPrivacyCohortCandidate(t *testing.T, fixture candidatePrivacyFixture, candidate domain.User) {
|
||||
t.Helper()
|
||||
if _, err := fixture.identity.store.Users().MarkEmailVerified(fixture.ctx, candidate.ID, candidate.RegistrationVersion, fixture.now); err != nil {
|
||||
t.Fatalf("MarkEmailVerified() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func privacyCohortConfirmedItems[V comparable](values ...V) []domain.ProfileClaimInput[V] {
|
||||
items := make([]domain.ProfileClaimInput[V], 0, len(values))
|
||||
for _, value := range values {
|
||||
items = append(items, domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed})
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,746 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/argon2id"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
"lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
const supportCaseHTTPTimeout = 5 * time.Minute
|
||||
|
||||
type supportCaseHTTPHarness struct {
|
||||
*sessionHTTPHarness
|
||||
supportClock *testClock
|
||||
}
|
||||
|
||||
func TestSupportCasesOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-owner@example.test", passwordHash, true)
|
||||
other := createSupportCaseHTTPEmployer(ctx, t, harness, "support-other@example.test", passwordHash)
|
||||
ownerLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.231:1234")
|
||||
otherLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.232:1234")
|
||||
ownerCookie, ownerCSRF := supportCaseLoginCredentials(t, ownerLogin)
|
||||
otherCookie, otherCSRF := supportCaseLoginCredentials(t, otherLogin)
|
||||
|
||||
if got := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", "", "", "", "192.0.2.233:1234").Code; got != http.StatusUnauthorized {
|
||||
t.Fatalf("guest list status = %d, want 401", got)
|
||||
}
|
||||
|
||||
createSupport := `{"type":"support","description":"The assessment is unavailable; please help with access."}`
|
||||
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
|
||||
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.234:1234")
|
||||
if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("create support case = %d Cache-Control=%q: %s, want 201 no-store; server logs: %s", created.Code,
|
||||
created.Header().Get("Cache-Control"), created.Body.String(), harness.logs.String())
|
||||
}
|
||||
var createdBody supportCaseHTTPResponse
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &createdBody); err != nil {
|
||||
t.Fatalf("decode created support case: %v", err)
|
||||
}
|
||||
if createdBody.ID == "" || createdBody.Number == "" || createdBody.Type != "support" || createdBody.Status != "submitted" ||
|
||||
createdBody.Description != "The assessment is unavailable; please help with access." || len(createdBody.History) != 1 || createdBody.History[0].Kind != "created" {
|
||||
t.Fatalf("created support case = %+v", createdBody)
|
||||
}
|
||||
|
||||
replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
|
||||
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1234")
|
||||
if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() {
|
||||
t.Fatalf("same-key replay = %d %s, want original 201 body %s", replay.Code, replay.Body.String(), created.Body.String())
|
||||
}
|
||||
var supportCaseCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE id = $1::uuid", createdBody.ID).Scan(&supportCaseCount); err != nil {
|
||||
t.Fatalf("count idempotent support case: %v", err)
|
||||
}
|
||||
if supportCaseCount != 1 {
|
||||
t.Fatalf("same-key support create stored %d cases, want exactly one", supportCaseCount)
|
||||
}
|
||||
changedBody := `{"type":"support","description":"The assessment result is missing; please investigate."}`
|
||||
changedReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", changedBody,
|
||||
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1236")
|
||||
requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
|
||||
assertSupportCaseCount(t, ctx, harness, owner.ID, 1)
|
||||
csrfDenied := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
|
||||
ownerCookie, "", "support-csrf-denied", "192.0.2.235:1237")
|
||||
requireSessionProblem(t, csrfDenied, http.StatusForbidden, "csrf_check_failed")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
|
||||
assertSupportCaseCount(t, ctx, harness, owner.ID, 1)
|
||||
ownRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+createdBody.ID,
|
||||
"", ownerCookie, "", "", "192.0.2.235:1235")
|
||||
var ownReadBody supportCaseHTTPResponse
|
||||
if ownRead.Code != http.StatusOK || ownRead.Header().Get("Cache-Control") != "no-store" ||
|
||||
json.Unmarshal(ownRead.Body.Bytes(), &ownReadBody) != nil || ownReadBody.ID != createdBody.ID ||
|
||||
ownReadBody.Number != createdBody.Number || ownReadBody.Status != "submitted" {
|
||||
t.Fatalf("owner GET = %d Cache-Control=%q %s, want own submitted case %s", ownRead.Code,
|
||||
ownRead.Header().Get("Cache-Control"), ownRead.Body.String(), createdBody.ID)
|
||||
}
|
||||
|
||||
manualBody := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}`
|
||||
manual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
|
||||
ownerCookie, ownerCSRF, "support-manual-1", "192.0.2.236:1234")
|
||||
if manual.Code != http.StatusCreated {
|
||||
t.Fatalf("manual assessment request without C3 or an earlier attempt = %d %s, want 201", manual.Code, manual.Body.String())
|
||||
}
|
||||
var manualCase supportCaseHTTPResponse
|
||||
if err := json.Unmarshal(manual.Body.Bytes(), &manualCase); err != nil {
|
||||
t.Fatalf("decode manual assessment request: %v", err)
|
||||
}
|
||||
if manualCase.Type != "manual_assessment" || manualCase.Status != "waiting_expert" || len(manualCase.History) != 2 ||
|
||||
manualCase.History[1].Kind != "status_changed" || manualCase.RubricVersion != nil ||
|
||||
manualCase.ResponseTarget.BusinessDays != 5 || manualCase.ResponseTarget.Kind != "operational_goal" {
|
||||
t.Fatalf("manual assessment request = %+v, want expert queue, optional rubric, and five-day operational target", manualCase)
|
||||
}
|
||||
manualRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+manualCase.ID,
|
||||
"", ownerCookie, "", "", "192.0.2.236:1235")
|
||||
var manualReadBody supportCaseHTTPResponse
|
||||
if manualRead.Code != http.StatusOK || json.Unmarshal(manualRead.Body.Bytes(), &manualReadBody) != nil ||
|
||||
manualReadBody.ID != manualCase.ID || manualReadBody.Status != "waiting_expert" || manualReadBody.RubricVersion != nil {
|
||||
t.Fatalf("manual case GET = %d %s, want unchanged waiting_expert case without a rubric", manualRead.Code, manualRead.Body.String())
|
||||
}
|
||||
var attemptCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil {
|
||||
t.Fatalf("read assessment attempts: %v", err)
|
||||
}
|
||||
if attemptCount != 0 {
|
||||
t.Fatalf("manual request unexpectedly has %d prior assessment attempts", attemptCount)
|
||||
}
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 4)
|
||||
duplicateManual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
|
||||
ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1236")
|
||||
requireSessionProblem(t, duplicateManual, http.StatusConflict, "state_conflict")
|
||||
duplicateManualReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
|
||||
ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1237")
|
||||
requireSessionProblem(t, duplicateManualReplay, http.StatusConflict, "state_conflict")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 6)
|
||||
var openManualCount int64
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases
|
||||
WHERE owner_id = $1 AND case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed')`, owner.ID).
|
||||
Scan(&openManualCount); err != nil {
|
||||
t.Fatalf("count open manual assessment cases: %v", err)
|
||||
}
|
||||
if openManualCount != 1 {
|
||||
t.Fatalf("duplicate manual request created %d open cases, want one", openManualCount)
|
||||
}
|
||||
invalidDescription := `{"type":"support","description":"\u0085"}`
|
||||
invalidDomain := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription,
|
||||
ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1238")
|
||||
requireSessionProblem(t, invalidDomain, http.StatusBadRequest, "validation_failed")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 7)
|
||||
invalidDomainRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription,
|
||||
ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1239")
|
||||
requireSessionProblem(t, invalidDomainRetry, http.StatusBadRequest, "validation_failed")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 8)
|
||||
var consentCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil {
|
||||
t.Fatalf("read consent side effects: %v", err)
|
||||
}
|
||||
if consentCount != 0 {
|
||||
t.Fatalf("manual assessment changed consent records to %d, want none", consentCount)
|
||||
}
|
||||
companyLimited := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
|
||||
otherCookie, otherCSRF, "support-employer-manual", "192.0.2.236:1241")
|
||||
requireSessionProblem(t, companyLimited, http.StatusForbidden, "forbidden")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, other.ID, 0)
|
||||
resetSupportCaseRequestEvents(t, ctx, harness, owner.ID)
|
||||
harness.supportClock.Advance(24 * time.Hour)
|
||||
expiredKeyBody := `{"type":"support","description":"The original support key expired and was accepted again."}`
|
||||
expiredKeyRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", expiredKeyBody,
|
||||
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.236:1240")
|
||||
var expiredKeyCase supportCaseHTTPResponse
|
||||
if expiredKeyRetry.Code != http.StatusCreated || json.Unmarshal(expiredKeyRetry.Body.Bytes(), &expiredKeyCase) != nil ||
|
||||
expiredKeyCase.ID == createdBody.ID || expiredKeyCase.Number == createdBody.Number ||
|
||||
expiredKeyCase.Description != "The original support key expired and was accepted again." {
|
||||
t.Fatalf("same key at exact 24-hour expiry = %d %s, want a new 201 case", expiredKeyRetry.Code, expiredKeyRetry.Body.String())
|
||||
}
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 1)
|
||||
|
||||
otherCase := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
|
||||
otherCookie, otherCSRF, "support-other-1", "192.0.2.237:1234")
|
||||
if otherCase.Code != http.StatusCreated {
|
||||
t.Fatalf("other account create = %d %s, want 201", otherCase.Code, otherCase.Body.String())
|
||||
}
|
||||
var otherCaseBody supportCaseHTTPResponse
|
||||
if err := json.Unmarshal(otherCase.Body.Bytes(), &otherCaseBody); err != nil {
|
||||
t.Fatalf("decode other account case: %v", err)
|
||||
}
|
||||
foreignReference := fmt.Sprintf(`{"type":"support","description":"Reference another account's case.","object":{"type":"support_case","id":%q}}`, otherCaseBody.ID)
|
||||
foreign := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference,
|
||||
ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.238:1234")
|
||||
requireSessionProblem(t, foreign, http.StatusNotFound, "not_found")
|
||||
foreignReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference,
|
||||
ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.239:1234")
|
||||
requireSessionProblem(t, foreignReplay, http.StatusNotFound, "not_found")
|
||||
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
|
||||
foreignRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+otherCaseBody.ID,
|
||||
"", ownerCookie, "", "", "192.0.2.240:1234")
|
||||
requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found")
|
||||
|
||||
list := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", ownerCookie, "", "", "192.0.2.241:1234")
|
||||
if list.Code != http.StatusOK || list.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("list own cases = %d Cache-Control=%q: %s", list.Code, list.Header().Get("Cache-Control"), list.Body.String())
|
||||
}
|
||||
var listBody struct {
|
||||
Items []json.RawMessage `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(list.Body.Bytes(), &listBody); err != nil {
|
||||
t.Fatalf("decode own support case list: %v", err)
|
||||
}
|
||||
if len(listBody.Items) != 3 || strings.Contains(list.Body.String(), "The assessment is unavailable") || strings.Contains(list.Body.String(), "history") {
|
||||
t.Fatalf("owner list leaked another case or full-case fields: %s", list.Body.String())
|
||||
}
|
||||
pageOne := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases?limit=1", "",
|
||||
ownerCookie, "", "", "192.0.2.241:1235")
|
||||
var firstPage struct {
|
||||
Items []json.RawMessage `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
if pageOne.Code != http.StatusOK || json.Unmarshal(pageOne.Body.Bytes(), &firstPage) != nil ||
|
||||
len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
|
||||
t.Fatalf("first support-case page = %d %s, want a cursor for more results", pageOne.Code, pageOne.Body.String())
|
||||
}
|
||||
pageTwo := supportCaseHTTP(t, harness, http.MethodGet,
|
||||
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "",
|
||||
ownerCookie, "", "", "192.0.2.241:1236")
|
||||
var secondPage struct {
|
||||
Items []json.RawMessage `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
if pageTwo.Code != http.StatusOK || json.Unmarshal(pageTwo.Body.Bytes(), &secondPage) != nil ||
|
||||
len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil ||
|
||||
string(secondPage.Items[0]) == string(firstPage.Items[0]) {
|
||||
t.Fatalf("second support-case page = %d %s, want one item and another page", pageTwo.Code, pageTwo.Body.String())
|
||||
}
|
||||
pageThree := supportCaseHTTP(t, harness, http.MethodGet,
|
||||
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*secondPage.Page.NextCursor), "",
|
||||
ownerCookie, "", "", "192.0.2.241:1237")
|
||||
var lastPage struct {
|
||||
Items []json.RawMessage `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
} `json:"page"`
|
||||
}
|
||||
if pageThree.Code != http.StatusOK || json.Unmarshal(pageThree.Body.Bytes(), &lastPage) != nil ||
|
||||
len(lastPage.Items) != 1 || lastPage.Page.HasMore {
|
||||
t.Fatalf("last support-case page = %d %s, want one item without another page", pageThree.Code, pageThree.Body.String())
|
||||
}
|
||||
foreignCursor := supportCaseHTTP(t, harness, http.MethodGet,
|
||||
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "",
|
||||
otherCookie, "", "", "192.0.2.241:1238")
|
||||
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
|
||||
|
||||
resetSupportCaseRequestEvents(t, ctx, harness, owner.ID, other.ID)
|
||||
for index := range 10 {
|
||||
body := fmt.Sprintf(`{"type":"support","description":"Rate limit request %d."}`, index)
|
||||
response := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
|
||||
ownerCookie, ownerCSRF, fmt.Sprintf("support-limit-%d", index), fmt.Sprintf("192.0.2.%d:1234", 242+index))
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("within-limit create %d = %d %s, want 201", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
overLimit := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases",
|
||||
`{"type":"support","description":"This request exceeds the account budget."}`,
|
||||
ownerCookie, ownerCSRF, "support-limit-over", "192.0.2.247:1234")
|
||||
if overLimit.Code != http.StatusTooManyRequests || overLimit.Header().Get("Retry-After") == "" {
|
||||
t.Fatalf("eleventh owner create = %d Retry-After=%q %s, want 429 with a retry interval", overLimit.Code, overLimit.Header().Get("Retry-After"), overLimit.Body.String())
|
||||
}
|
||||
assertRowCount(ctx, t, harness.pool, pgx.Identifier{"support_case_request_events"}, 10)
|
||||
}
|
||||
|
||||
func TestManualAssessmentPinsPublishedRubricAcrossReplayAndReopening(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv)
|
||||
|
||||
firstPolicy, opening, bank, metadata := seedSupportManualRubric(ctx, t, harness)
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-rubric-owner@example.test", passwordHash, true)
|
||||
login := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass,
|
||||
sessionHTTPTestOrigin, "", "192.0.2.251:1234")
|
||||
cookie, csrf := supportCaseLoginCredentials(t, login)
|
||||
body := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}`
|
||||
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
|
||||
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1234")
|
||||
var original supportCaseHTTPResponse
|
||||
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &original) != nil ||
|
||||
original.RubricVersion == nil || *original.RubricVersion != firstPolicy.Version() || original.Status != "waiting_expert" {
|
||||
t.Fatalf("manual request with a current reviewed rubric = %d %s, want 201 pinned to policy version %d",
|
||||
created.Code, created.Body.String(), firstPolicy.Version())
|
||||
}
|
||||
if strings.Contains(created.Body.String(), "rubric_opening_id") || strings.Contains(created.Body.String(), "rubric_policy_version_id") {
|
||||
t.Fatalf("public response exposed private rubric pin columns: %s", created.Body.String())
|
||||
}
|
||||
|
||||
assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID())
|
||||
var consentCount, attemptCount int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil {
|
||||
t.Fatalf("read manual-assessment consent side effects: %v", err)
|
||||
}
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil {
|
||||
t.Fatalf("read manual-assessment attempt side effects: %v", err)
|
||||
}
|
||||
if consentCount != 0 || attemptCount != 0 {
|
||||
t.Fatalf("manual request created %d consent records and %d attempts; want neither", consentCount, attemptCount)
|
||||
}
|
||||
read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID,
|
||||
"", cookie, "", "", "192.0.2.252:1235")
|
||||
var readBody supportCaseHTTPResponse
|
||||
if read.Code != http.StatusOK || json.Unmarshal(read.Body.Bytes(), &readBody) != nil ||
|
||||
readBody.ID != original.ID || readBody.RubricVersion == nil || *readBody.RubricVersion != firstPolicy.Version() {
|
||||
t.Fatalf("manual case GET = %d %s, want the original rubric version", read.Code, read.Body.String())
|
||||
}
|
||||
replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
|
||||
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1236")
|
||||
if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() {
|
||||
t.Fatalf("same-key manual replay = %d %s, want the immutable original response %s", replay.Code, replay.Body.String(), created.Body.String())
|
||||
}
|
||||
|
||||
secondProductPolicy := domain.DemoProductPolicyV2()
|
||||
secondProductPolicy.Assessment.MaxAttemptsPerWindow++
|
||||
secondPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now).Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
|
||||
Author: domain.DemoPolicySeedAuthor, Policy: secondProductPolicy,
|
||||
})
|
||||
if err != nil || secondPolicy.Version() <= firstPolicy.Version() {
|
||||
t.Fatalf("publish later product policy = v%d, %v; want a later immutable version", secondPolicy.Version(), err)
|
||||
}
|
||||
harness.supportClock.now = secondPolicy.EffectiveAt()
|
||||
secondOpening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: opening.Category, GradingPolicyID: secondPolicy.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata,
|
||||
})
|
||||
if err != nil || secondOpening.ID == opening.ID {
|
||||
t.Fatalf("reopen category under later policy = %+v, %v; want a distinct current opening", secondOpening, err)
|
||||
}
|
||||
current, err := bank.CategoryAvailability(ctx, opening.Category)
|
||||
if err != nil || current.ID != secondOpening.ID {
|
||||
t.Fatalf("current category opening = %+v, %v; want the later opening", current, err)
|
||||
}
|
||||
|
||||
readAfterReopening := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID,
|
||||
"", cookie, "", "", "192.0.2.252:1237")
|
||||
replayAfterReopening := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
|
||||
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1238")
|
||||
var readAfterBody supportCaseHTTPResponse
|
||||
if readAfterReopening.Code != http.StatusOK || json.Unmarshal(readAfterReopening.Body.Bytes(), &readAfterBody) != nil ||
|
||||
readAfterBody.RubricVersion == nil || *readAfterBody.RubricVersion != firstPolicy.Version() ||
|
||||
replayAfterReopening.Code != http.StatusCreated || replayAfterReopening.Body.String() != created.Body.String() {
|
||||
t.Fatalf("old manual case changed after category reopening: GET=%d %s replay=%d %s",
|
||||
readAfterReopening.Code, readAfterReopening.Body.String(), replayAfterReopening.Code, replayAfterReopening.Body.String())
|
||||
}
|
||||
assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID())
|
||||
}
|
||||
|
||||
func seedSupportManualRubric(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *supportCaseHTTPHarness,
|
||||
) (domain.PolicyVersion, domain.AssessmentCategoryOpening, *assessment.Bank, domain.AssessmentCategoryCatalogMetadata) {
|
||||
t.Helper()
|
||||
policyStore := postgresadapter.NewPolicyStore(harness.pool)
|
||||
policyVersion, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, harness.supportClock.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("read current support policy for reviewed bank fixture: %v", err)
|
||||
}
|
||||
transactor := postgresadapter.NewTransactor(harness.pool)
|
||||
bank := assessment.NewBank(transactor)
|
||||
fixture := assessmentFixture{demoBundle: loadDemoBundleFile(t)}
|
||||
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
|
||||
if err != nil {
|
||||
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
|
||||
}
|
||||
bundle := fixture.reviewedBundle(int(required))
|
||||
bundle.Name = "support-case-manual-rubric"
|
||||
bundle.Category = "support-case-manual-rubric"
|
||||
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
|
||||
t.Fatalf("ImportBundle(support rubric fixture) error = %v", err)
|
||||
}
|
||||
for _, family := range bundle.Families {
|
||||
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
|
||||
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
|
||||
}
|
||||
}
|
||||
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
|
||||
domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err)
|
||||
}
|
||||
category := domain.AssessmentCategory(bundle.Category)
|
||||
opening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
|
||||
Category: category, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("OpenCategory(support rubric fixture) error = %v", err)
|
||||
}
|
||||
return policyVersion, opening, bank, metadata
|
||||
}
|
||||
|
||||
func assertStoredSupportRubricPin(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *supportCaseHTTPHarness,
|
||||
caseID string,
|
||||
version int32,
|
||||
openingID uuid.UUID,
|
||||
policyID uuid.UUID,
|
||||
) {
|
||||
t.Helper()
|
||||
var storedVersion int32
|
||||
var storedOpeningID, storedPolicyID uuid.UUID
|
||||
err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id, rubric_policy_version_id
|
||||
FROM support_cases WHERE id = $1::uuid`, caseID).Scan(&storedVersion, &storedOpeningID, &storedPolicyID)
|
||||
if err != nil || storedVersion != version || storedOpeningID != openingID || storedPolicyID != policyID {
|
||||
t.Fatalf("stored private rubric pin = v%d opening %s policy %s, %v; want v%d opening %s policy %s",
|
||||
storedVersion, storedOpeningID, storedPolicyID, err, version, openingID, policyID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
passwordHash, err := identity.NewCredentials(hasher).HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
address, err := domain.NewEmailAddress("support-budget@example.test")
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
registeredAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioCandidate, RegisteredAt: registeredAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser() error = %v", err)
|
||||
}
|
||||
if err := store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create(user) error = %v", err)
|
||||
}
|
||||
if _, err := store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)); err != nil {
|
||||
t.Fatalf("MarkEmailVerified() error = %v", err)
|
||||
}
|
||||
|
||||
productPolicy := domain.DemoProductPolicyV2()
|
||||
baseSupport := domain.DemoSupportPolicy()
|
||||
limitedSupport, err := domain.NewSupportPolicy(domain.SupportPolicyInput{
|
||||
SupportResponseDays: baseSupport.SupportResponseDays(), ComplaintResponseDays: baseSupport.ComplaintResponseDays(),
|
||||
ManualAssessmentResponseDays: baseSupport.ManualAssessmentResponseDays(), AppealResponseDays: baseSupport.AppealResponseDays(),
|
||||
MaxRequestsPerWindow: 1, RequestWindow: time.Hour, MaxAppealsPerTarget: baseSupport.MaxAppealsPerTarget(),
|
||||
PauseWhenWaitingForUser: baseSupport.PausesWhenWaitingForUser(), BusinessCalendarVersion: baseSupport.BusinessCalendarVersion(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportPolicy() error = %v", err)
|
||||
}
|
||||
productPolicy.Support = &limitedSupport
|
||||
policyClock := time.Now
|
||||
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), policyClock).Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: productPolicy,
|
||||
}); err != nil {
|
||||
t.Fatalf("publish budget test policy: %v", err)
|
||||
}
|
||||
|
||||
firstTimestamp := time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond)
|
||||
var clockCalls atomic.Int32
|
||||
clock := func() time.Time {
|
||||
if clockCalls.Add(1) == 1 {
|
||||
return firstTimestamp
|
||||
}
|
||||
return firstTimestamp.Add(-time.Hour)
|
||||
}
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCaseService() error = %v", err)
|
||||
}
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
for index := range 2 {
|
||||
go func(index int) {
|
||||
<-start
|
||||
_, err := service.Create(ctx, supportcase.CreateCommand{
|
||||
ActorID: user.ID, IdempotencyKey: fmt.Sprintf("support-budget-%d", index),
|
||||
Type: domain.SupportCaseTypeSupport, Description: fmt.Sprintf("Budget request %d.", index),
|
||||
})
|
||||
results <- err
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
firstError, secondError := <-results, <-results
|
||||
if clockCalls.Load() != 2 {
|
||||
t.Fatalf("service clock calls = %d, want one post-lock sample per request", clockCalls.Load())
|
||||
}
|
||||
successes := 0
|
||||
limited := 0
|
||||
for _, err := range []error{firstError, secondError} {
|
||||
switch {
|
||||
case err == nil:
|
||||
successes++
|
||||
case errors.Is(err, supportcase.ErrRateLimited):
|
||||
limited++
|
||||
default:
|
||||
t.Fatalf("concurrent request error = %v, want one create and one rate limit", err)
|
||||
}
|
||||
}
|
||||
if successes != 1 || limited != 1 {
|
||||
t.Fatalf("concurrent requests had %d creates and %d rate limits, want one each", successes, limited)
|
||||
}
|
||||
assertRowCount(ctx, t, pool, pgx.Identifier{"support_cases"}, 1)
|
||||
assertRowCount(ctx, t, pool, pgx.Identifier{"support_case_request_events"}, 1)
|
||||
}
|
||||
|
||||
func requireSupportCaseRequestCount(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *supportCaseHTTPHarness,
|
||||
ownerID uuid.UUID,
|
||||
want int64,
|
||||
) {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
"SELECT count(*) FROM support_case_request_events WHERE owner_id = $1", ownerID,
|
||||
).Scan(&count); err != nil {
|
||||
t.Fatalf("count support request events for owner: %v", err)
|
||||
}
|
||||
if count != want {
|
||||
t.Fatalf("support request events for owner = %d, want %d", count, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertSupportCaseCount(t *testing.T, ctx context.Context, harness *supportCaseHTTPHarness, ownerID uuid.UUID, want int64) {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE owner_id = $1", ownerID).Scan(&count); err != nil {
|
||||
t.Fatalf("count support cases for owner: %v", err)
|
||||
}
|
||||
if count != want {
|
||||
t.Fatalf("support cases for owner = %d, want %d", count, want)
|
||||
}
|
||||
}
|
||||
|
||||
func resetSupportCaseRequestEvents(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *supportCaseHTTPHarness,
|
||||
ownerIDs ...uuid.UUID,
|
||||
) {
|
||||
t.Helper()
|
||||
for _, ownerID := range ownerIDs {
|
||||
if _, err := harness.pool.Exec(ctx, "DELETE FROM support_case_request_events WHERE owner_id = $1", ownerID); err != nil {
|
||||
t.Fatalf("reset support request events for owner: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createSupportCaseHTTPEmployer(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *supportCaseHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
address, err := domain.NewEmailAddress(email)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
registeredAt := harness.clock.Now().Truncate(time.Microsecond)
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser(employer) error = %v", err)
|
||||
}
|
||||
if err := harness.store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create(employer) error = %v", err)
|
||||
}
|
||||
user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
type supportCaseHTTPResponse struct {
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Description string `json:"description"`
|
||||
RubricVersion *int32 `json:"rubric_version"`
|
||||
History []struct {
|
||||
Kind string `json:"kind"`
|
||||
} `json:"history"`
|
||||
ResponseTarget struct {
|
||||
Kind string `json:"kind"`
|
||||
BusinessDays int32 `json:"business_days"`
|
||||
} `json:"response_target"`
|
||||
}
|
||||
|
||||
func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *supportCaseHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
hasher, err := argon2id.NewHasher(1)
|
||||
if err != nil {
|
||||
t.Fatalf("NewHasher() error = %v", err)
|
||||
}
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
supportClock := &testClock{now: clock.Now()}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
||||
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(),
|
||||
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
|
||||
}, identity.SessionSettings{
|
||||
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
||||
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSessionService() error = %v", err)
|
||||
}
|
||||
publishedPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).Publish(ctx, policy.PublishInput{
|
||||
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV2(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("publish explicit support demo policy: %v", err)
|
||||
}
|
||||
// Publication time comes from PostgreSQL and is later than the fixed
|
||||
// session clock. Start support requests at the returned effective time.
|
||||
supportClock.now = publishedPolicy.EffectiveAt()
|
||||
service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: supportClock.Now})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCaseService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil,
|
||||
v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL),
|
||||
)
|
||||
supportHandler := v1.NewSupportHandler(service)
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
|
||||
prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return &supportCaseHTTPHarness{
|
||||
sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs},
|
||||
supportClock: supportClock,
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseLoginCredentials(t *testing.T, response *httptest.ResponseRecorder) (string, string) {
|
||||
t.Helper()
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("login support case account = %d %s, want 201", response.Code, response.Body.String())
|
||||
}
|
||||
cookie := requireSessionCookie(t, response)
|
||||
var body struct {
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
|
||||
t.Fatalf("decode support case login response: %v", err)
|
||||
}
|
||||
return cookie.Value, body.CSRFToken
|
||||
}
|
||||
|
||||
func supportCaseHTTP(
|
||||
t *testing.T,
|
||||
harness *supportCaseHTTPHarness,
|
||||
method, path, body, cookie, csrf, idempotencyKey, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if method == http.MethodPost {
|
||||
request.Header.Set("Origin", sessionHTTPTestOrigin)
|
||||
request.Header.Set("Idempotency-Key", idempotencyKey)
|
||||
}
|
||||
if cookie != "" {
|
||||
request.Header.Set("Cookie", "__Host-lincodex_session="+cookie)
|
||||
}
|
||||
if csrf != "" {
|
||||
request.Header.Set("X-CSRF-Token", csrf)
|
||||
}
|
||||
request.RemoteAddr = remoteAddr
|
||||
response := httptest.NewRecorder()
|
||||
harness.router.ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
@@ -33,6 +33,7 @@ var regexMap = map[string]ogenregex.Regexp{
|
||||
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
|
||||
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
|
||||
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
|
||||
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
|
||||
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
|
||||
}
|
||||
var (
|
||||
|
||||
@@ -2503,9 +2503,10 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -4057,21 +4058,22 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
|
||||
|
||||
// handleGetMyCardPreviewRequest handles GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -5713,6 +5715,234 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationCandidateCardRequest handles GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetOrganizationCandidateCard"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateCardOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: GetOrganizationCandidateCardOperation,
|
||||
ID: "GetOrganizationCandidateCard",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateCardOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeGetOrganizationCandidateCardParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response GetOrganizationCandidateCardRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetOrganizationCandidateCardOperation,
|
||||
OperationSummary: "Read one currently visible anonymous candidate card.",
|
||||
OperationID: "GetOrganizationCandidateCard",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}: params.CandidateHandle,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetOrganizationCandidateCardParams
|
||||
Response = GetOrganizationCandidateCardRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetOrganizationCandidateCardParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeGetOrganizationCandidateCardResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -6800,11 +7030,12 @@ func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -7042,16 +7273,15 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -9674,6 +9904,263 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
|
||||
}
|
||||
}
|
||||
|
||||
// handleRecordMyAssessmentAttemptSignalsRequest handles RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
func (s *Server) handleRecordMyAssessmentAttemptSignalsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("RecordMyAssessmentAttemptSignals"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/signals"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), RecordMyAssessmentAttemptSignalsOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: RecordMyAssessmentAttemptSignalsOperation,
|
||||
ID: "RecordMyAssessmentAttemptSignals",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, RecordMyAssessmentAttemptSignalsOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCsrf(ctx, RecordMyAssessmentAttemptSignalsOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCsrf",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCsrf", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 1
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000011},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
params, err := decodeRecordMyAssessmentAttemptSignalsParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeRecordMyAssessmentAttemptSignalsRequest(r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeRequestError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeRequest", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := close(); err != nil {
|
||||
recordError("CloseRequest", err)
|
||||
}
|
||||
}()
|
||||
|
||||
var response RecordMyAssessmentAttemptSignalsRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: RecordMyAssessmentAttemptSignalsOperation,
|
||||
OperationSummary: "Store a bounded batch of client-reported assessment signals.",
|
||||
OperationID: "RecordMyAssessmentAttemptSignals",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
}: params.AttemptID,
|
||||
{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}: params.IdempotencyKey,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *AssessmentSignalBatch
|
||||
Params = RecordMyAssessmentAttemptSignalsParams
|
||||
Response = RecordMyAssessmentAttemptSignalsRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackRecordMyAssessmentAttemptSignalsParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeRecordMyAssessmentAttemptSignalsResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleRegisterAccountRequest handles RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
@@ -93,6 +93,10 @@ type GetMySupportCaseRes interface {
|
||||
getMySupportCaseRes()
|
||||
}
|
||||
|
||||
type GetOrganizationCandidateCardRes interface {
|
||||
getOrganizationCandidateCardRes()
|
||||
}
|
||||
|
||||
type GetOrganizationInvitationContactsRes interface {
|
||||
getOrganizationInvitationContactsRes()
|
||||
}
|
||||
@@ -165,6 +169,10 @@ type RaiseOrganizationInvitationSalaryRes interface {
|
||||
raiseOrganizationInvitationSalaryRes()
|
||||
}
|
||||
|
||||
type RecordMyAssessmentAttemptSignalsRes interface {
|
||||
recordMyAssessmentAttemptSignalsRes()
|
||||
}
|
||||
|
||||
type RegisterAccountRes interface {
|
||||
registerAccountRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,7 @@ const (
|
||||
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
|
||||
GetMySupportCaseOperation OperationName = "GetMySupportCase"
|
||||
GetOrganizationOperation OperationName = "GetOrganization"
|
||||
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
|
||||
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
|
||||
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
|
||||
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
|
||||
@@ -49,6 +50,7 @@ const (
|
||||
LoginOperation OperationName = "Login"
|
||||
LogoutOperation OperationName = "Logout"
|
||||
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
|
||||
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
|
||||
RegisterAccountOperation OperationName = "RegisterAccount"
|
||||
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
|
||||
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
|
||||
|
||||
@@ -1776,6 +1776,147 @@ func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Reque
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateCardParams is parameters of GetOrganizationCandidateCard operation.
|
||||
type GetOrganizationCandidateCardParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
// this organization, checked by the server on every request; the identifier itself grants nothing. An
|
||||
// organization without such a membership and an unknown identifier both answer 404 not_found, so
|
||||
// organizations cannot be enumerated.
|
||||
OrgID uuid.UUID
|
||||
// Organization-scoped opaque candidate alias issued by the current visible card projection. The server
|
||||
// resolves it only for the organization in the path and rechecks current membership, publication
|
||||
// consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all
|
||||
// answer the same 404.
|
||||
CandidateHandle CandidateHandle
|
||||
}
|
||||
|
||||
func unpackGetOrganizationCandidateCardParams(packed middleware.Parameters) (params GetOrganizationCandidateCardParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}
|
||||
params.CandidateHandle = packed[key].(CandidateHandle)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetOrganizationCandidateCardParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationCandidateCardParams, _ error) {
|
||||
// Decode path: org_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "org_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.OrgID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode path: candidate_handle.
|
||||
if err := func() error {
|
||||
param := args[1]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[1])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "candidate_handle",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotCandidateHandleVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCandidateHandleVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.CandidateHandle = CandidateHandle(paramsDotCandidateHandleVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := params.CandidateHandle.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
|
||||
type GetOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -4263,6 +4404,155 @@ func decodeRaiseOrganizationInvitationSalaryParams(args [2]string, argsEscaped b
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// RecordMyAssessmentAttemptSignalsParams is parameters of RecordMyAssessmentAttemptSignals operation.
|
||||
type RecordMyAssessmentAttemptSignalsParams struct {
|
||||
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
|
||||
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
|
||||
AttemptID uuid.UUID
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
|
||||
// request by method, path, and body.
|
||||
//
|
||||
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
|
||||
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
|
||||
// not_found or 409 state_conflict. A replay does not repeat the side effect.
|
||||
//
|
||||
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
|
||||
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
|
||||
// precondition_required (nothing changed; read the resource again and retry), 422
|
||||
// idempotency_key_reused, 429, and every 5xx.
|
||||
//
|
||||
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
|
||||
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
|
||||
// before any other key check; a running request with the same fingerprint returns 409
|
||||
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
|
||||
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
|
||||
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func unpackRecordMyAssessmentAttemptSignalsParams(packed middleware.Parameters) (params RecordMyAssessmentAttemptSignalsParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttemptID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}
|
||||
params.IdempotencyKey = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeRecordMyAssessmentAttemptSignalsParams(args [1]string, argsEscaped bool, r *http.Request) (params RecordMyAssessmentAttemptSignalsParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode path: attempt_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "attempt_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.AttemptID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode header: Idempotency-Key.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Idempotency-Key",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.IdempotencyKey = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 255,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.IdempotencyKey)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// RegisterAccountParams is parameters of RegisterAccount operation.
|
||||
type RegisterAccountParams struct {
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
|
||||
@@ -1041,6 +1041,85 @@ func (s *Server) decodeRaiseOrganizationInvitationSalaryRequest(r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRecordMyAssessmentAttemptSignalsRequest(r *http.Request) (
|
||||
req *AssessmentSignalBatch,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request AssessmentSignalBatch
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRegisterAccountRequest(r *http.Request) (
|
||||
req *RegistrationRequest,
|
||||
rawBody []byte,
|
||||
|
||||
@@ -1291,7 +1291,7 @@ func encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAtte
|
||||
|
||||
return nil
|
||||
|
||||
case *FinalizeMyAssessmentAttemptConflict:
|
||||
case *AssessmentFinalizeConflictProblem:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(409)
|
||||
|
||||
@@ -2215,6 +2215,121 @@ func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseW
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationCandidateCardResponse(response GetOrganizationCandidateCardRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *AnonymousCardContentHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateCardBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateCardUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateCardForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *GetOrganizationCandidateCardNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -3651,6 +3766,157 @@ func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationI
|
||||
}
|
||||
}
|
||||
|
||||
func encodeRecordMyAssessmentAttemptSignalsResponse(response RecordMyAssessmentAttemptSignalsRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *AssessmentSignalReceiptHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsBadRequest:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(400)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsConflict:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(409)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(413)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsUnprocessableEntity:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(422)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *IdentityRequestAccepted:
|
||||
|
||||
@@ -11,40 +11,43 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
rn69AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn62AllowedHeaders = map[string]string{
|
||||
rn65AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn59AllowedHeaders = map[string]string{
|
||||
rn61AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn25AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
rn67AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn9AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn20AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
rn78AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn71AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn48AllowedHeaders = map[string]string{
|
||||
rn50AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
@@ -57,17 +60,17 @@ var (
|
||||
rn17AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
rn80AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn51AllowedHeaders = map[string]string{
|
||||
rn53AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "X-Csrf-Token",
|
||||
}
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn73AllowedHeaders = map[string]string{
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn36AllowedHeaders = map[string]string{
|
||||
@@ -88,22 +91,22 @@ var (
|
||||
rn14AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn41AllowedHeaders = map[string]string{
|
||||
rn43AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn61AllowedHeaders = map[string]string{
|
||||
rn63AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
rn73AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn77AllowedHeaders = map[string]string{
|
||||
rn81AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn44AllowedHeaders = map[string]string{
|
||||
rn46AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
)
|
||||
@@ -260,7 +263,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn66AllowedHeaders,
|
||||
allowedHeaders: rn69AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -337,7 +340,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn62AllowedHeaders,
|
||||
allowedHeaders: rn65AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -361,7 +364,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn59AllowedHeaders,
|
||||
allowedHeaders: rn61AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -441,7 +444,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
allowedHeaders: rn67AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -551,7 +554,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -614,31 +617,72 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
case 's': // Prefix: "sessions"
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'e': // Prefix: "essions"
|
||||
|
||||
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn78AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "ignals"
|
||||
|
||||
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleRecordMyAssessmentAttemptSignalsRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
@@ -787,7 +831,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
allowedHeaders: rn71AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -821,7 +865,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn48AllowedHeaders,
|
||||
allowedHeaders: rn50AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1004,7 +1048,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
allowedHeaders: rn80AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1184,7 +1228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn51AllowedHeaders,
|
||||
allowedHeaders: rn53AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1275,7 +1319,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1302,7 +1346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn73AllowedHeaders,
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1512,6 +1556,43 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "candidate-cards/"
|
||||
|
||||
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetOrganizationCandidateCardRequest([2]string{
|
||||
args[0],
|
||||
args[1],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -1574,7 +1655,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn41AllowedHeaders,
|
||||
allowedHeaders: rn43AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -1654,7 +1735,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn61AllowedHeaders,
|
||||
allowedHeaders: rn63AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1682,7 +1763,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
allowedHeaders: rn73AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1712,7 +1793,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
allowedHeaders: rn81AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1790,7 +1871,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn44AllowedHeaders,
|
||||
allowedHeaders: rn46AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -2384,29 +2465,68 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
}
|
||||
|
||||
case 's': // Prefix: "sessions"
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = StartMyAssessmentAttemptSessionOperation
|
||||
r.summary = "Start or resume a work session for the current candidate's attempt."
|
||||
r.operationID = "StartMyAssessmentAttemptSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'e': // Prefix: "essions"
|
||||
|
||||
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = StartMyAssessmentAttemptSessionOperation
|
||||
r.summary = "Start or resume a work session for the current candidate's attempt."
|
||||
r.operationID = "StartMyAssessmentAttemptSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "ignals"
|
||||
|
||||
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = RecordMyAssessmentAttemptSignalsOperation
|
||||
r.summary = "Store a bounded batch of client-reported assessment signals."
|
||||
r.operationID = "RecordMyAssessmentAttemptSignals"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/signals"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3294,6 +3414,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "candidate-cards/"
|
||||
|
||||
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetOrganizationCandidateCardOperation
|
||||
r.summary = "Read one currently visible anonymous candidate card."
|
||||
r.operationID = "GetOrganizationCandidateCard"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"
|
||||
r.args = args
|
||||
r.count = 2
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -78,6 +78,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
GetMyQuestionnaireOperation: []string{},
|
||||
GetMySupportCaseOperation: []string{},
|
||||
GetOrganizationOperation: []string{},
|
||||
GetOrganizationCandidateCardOperation: []string{},
|
||||
GetOrganizationInvitationOperation: []string{},
|
||||
GetOrganizationInvitationContactsOperation: []string{},
|
||||
GetOrganizationNeedOperation: []string{},
|
||||
@@ -94,6 +95,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
ListOrganizationNeedsOperation: []string{},
|
||||
LogoutOperation: []string{},
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
@@ -148,6 +150,7 @@ var operationRolesSessionCsrf = map[string][]string{
|
||||
HideOrganizationOperation: []string{},
|
||||
LogoutOperation: []string{},
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
|
||||
@@ -479,9 +479,10 @@ type Handler interface {
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -600,21 +601,22 @@ type Handler interface {
|
||||
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
|
||||
// GetMyCardPreview implements GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -764,6 +766,36 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}
|
||||
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
|
||||
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (GetOrganizationCandidateCardRes, error)
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -901,11 +933,12 @@ type Handler interface {
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -931,16 +964,15 @@ type Handler interface {
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -1189,6 +1221,32 @@ type Handler interface {
|
||||
//
|
||||
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise
|
||||
RaiseOrganizationInvitationSalary(ctx context.Context, req *InvitationSalaryRaise, params RaiseOrganizationInvitationSalaryParams) (RaiseOrganizationInvitationSalaryRes, error)
|
||||
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (RecordMyAssessmentAttemptSignalsRes, error)
|
||||
// RegisterAccount implements RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
@@ -511,9 +511,10 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -656,21 +657,22 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
|
||||
|
||||
// GetMyCardPreview implements GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -844,6 +846,39 @@ func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrgan
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
func (UnimplementedHandler) GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (r GetOrganizationCandidateCardRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -996,11 +1031,12 @@ func (UnimplementedHandler) GrantMyConsent(ctx context.Context, req *ConsentSett
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -1029,16 +1065,15 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -1323,6 +1358,35 @@ func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Contex
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
func (UnimplementedHandler) RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (r RecordMyAssessmentAttemptSignalsRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RegisterAccount implements RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
package apitypes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// AssessmentNumber preserves the JSON number token for exact answer comparison.
|
||||
type AssessmentNumber string
|
||||
|
||||
func (number *AssessmentNumber) UnmarshalJSON(encoded []byte) error {
|
||||
if number == nil {
|
||||
return errors.New("assessment number target is nil")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return errors.New("assessment answer number is invalid")
|
||||
}
|
||||
parsed, ok := value.(json.Number)
|
||||
if !ok {
|
||||
return errors.New("assessment answer must be a JSON number")
|
||||
}
|
||||
var extra any
|
||||
if !errors.Is(decoder.Decode(&extra), io.EOF) {
|
||||
return errors.New("assessment answer number has trailing data")
|
||||
}
|
||||
*number = AssessmentNumber(parsed.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (number AssessmentNumber) MarshalJSON() ([]byte, error) {
|
||||
encoded := []byte(number)
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return nil, errors.New("assessment answer number is invalid")
|
||||
}
|
||||
if _, ok := value.(json.Number); !ok {
|
||||
return nil, errors.New("assessment answer must be a JSON number")
|
||||
}
|
||||
var extra any
|
||||
if !errors.Is(decoder.Decode(&extra), io.EOF) {
|
||||
return nil, errors.New("assessment answer number has trailing data")
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func (number AssessmentNumber) String() string {
|
||||
return string(number)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package apitypes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAssessmentNumberPreservesOnlyJSONNumberTokens(t *testing.T) {
|
||||
var number AssessmentNumber
|
||||
if err := json.Unmarshal([]byte(`1.0000000000000001`), &number); err != nil {
|
||||
t.Fatalf("UnmarshalJSON() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(number)
|
||||
if err != nil || string(encoded) != `1.0000000000000001` {
|
||||
t.Fatalf("MarshalJSON() = %s, error %v; want original exact token", encoded, err)
|
||||
}
|
||||
for _, input := range []string{`"1"`, `null`, `true`, `1 2`} {
|
||||
if err := json.Unmarshal([]byte(input), &number); err == nil {
|
||||
t.Errorf("UnmarshalJSON(%s) unexpectedly succeeded", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const maxAssessmentSignalBodyBytes int64 = 32 << 10
|
||||
|
||||
// limitAssessmentSignalBody is called only after the generated router has
|
||||
// matched the signal operation. It leaves decoding and authentication order
|
||||
// to the generated server while bounding both fixed-length and chunked bodies.
|
||||
func limitAssessmentSignalBody(w http.ResponseWriter, request *http.Request) {
|
||||
if request.Body != nil {
|
||||
request.Body = http.MaxBytesReader(w, request.Body, maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLimitAssessmentSignalBodyBoundsFixedAndChunkedBodies(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
contentLength int64
|
||||
}{
|
||||
{name: "content length", contentLength: maxAssessmentSignalBodyBytes + 1},
|
||||
{name: "chunked body", contentLength: -1},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes+1))))
|
||||
request.ContentLength = testCase.contentLength
|
||||
response := httptest.NewRecorder()
|
||||
limitAssessmentSignalBody(response, request)
|
||||
|
||||
body, err := io.ReadAll(request.Body)
|
||||
var limitError *http.MaxBytesError
|
||||
if !errors.As(err, &limitError) {
|
||||
t.Fatalf("ReadAll() error = %v, want MaxBytesError", err)
|
||||
}
|
||||
if int64(len(body)) != maxAssessmentSignalBodyBytes {
|
||||
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitAssessmentSignalBodyAllowsExactLimit(t *testing.T) {
|
||||
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes))))
|
||||
response := httptest.NewRecorder()
|
||||
limitAssessmentSignalBody(response, request)
|
||||
|
||||
body, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll() error = %v", err)
|
||||
}
|
||||
if int64(len(body)) != maxAssessmentSignalBodyBytes {
|
||||
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,12 @@ var (
|
||||
publicationSchemas = []string{"Publication", "PublicationUpdate", "PublicationVersion", "PublicationState", "PublicationClosedReason", "CardField", "CardFieldSet"}
|
||||
searchStatusSchemas = []string{"SearchStatus", "SearchStatusUpdate", "SearchStatusVersion", "SearchStatusValue"}
|
||||
hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"}
|
||||
privacyOnlySchemas = []string{"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList"}
|
||||
privacyOnlySchemas = []string{
|
||||
"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus",
|
||||
"CandidateExperienceBand", "CandidateWorkFormat", "CandidateSalaryCompatibility",
|
||||
"PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList",
|
||||
}
|
||||
// sharedLeafSchemas are the reusable leaves that the privacy family may
|
||||
// refer to; none of them identifies a person or carries a contact.
|
||||
sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"}
|
||||
@@ -207,13 +212,16 @@ func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) {
|
||||
|
||||
// The published field set cannot name a name, a contact, or the salary.
|
||||
fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"}))
|
||||
want := []string{"categories", "stack", "experience", "soft_skills", "location", "relocation"}
|
||||
want := []string{
|
||||
"categories", "stack", "experience", "soft_skills", "location", "relocation",
|
||||
"self_assessment", "work_formats", "salary_compatibility",
|
||||
}
|
||||
slices.Sort(fields)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(fields, want) {
|
||||
t.Errorf("CardField = %v, want %v", fields, want)
|
||||
}
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != uint64(len(want)) {
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 9 {
|
||||
t.Error("CardFieldSet must hold distinct items and at most one per field")
|
||||
}
|
||||
status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"}))
|
||||
@@ -233,7 +241,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
if card == nil {
|
||||
t.Fatal("the contract has no AnonymousCardContent")
|
||||
}
|
||||
if got, want := propertyNames(card), []string{"categories", "experience_months", "location", "relocation", "soft_skills", "stack"}; !slices.Equal(got, want) {
|
||||
if got, want := propertyNames(card), []string{
|
||||
"categories", "experience_band", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
|
||||
}; !slices.Equal(got, want) {
|
||||
t.Errorf("AnonymousCardContent properties = %v, want %v", got, want)
|
||||
}
|
||||
if card.AdditionalProperties.Bool == nil || *card.AdditionalProperties.Bool {
|
||||
@@ -241,7 +251,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
// Each property is a card field and nothing else; a null is a hidden or
|
||||
// missing value, never a flag that tells which.
|
||||
for _, forbidden := range []string{"email", "phone", "telegram", "contact", "name", "salary", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume"} {
|
||||
for _, forbidden := range []string{
|
||||
"email", "phone", "telegram", "contact", "name", "salary_minimum", "salary_amount", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume",
|
||||
} {
|
||||
for _, name := range propertyNames(card) {
|
||||
if strings.Contains(name, forbidden) {
|
||||
t.Errorf("AnonymousCardContent has the property %q, which looks like %q", name, forbidden)
|
||||
@@ -250,7 +262,11 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
// What the card and the preview reach is a small closed list of leaves.
|
||||
allowed := []string{"AnonymousCardContent", "CardCategory", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode", "GradeCode", "StackTag", "Timestamp", "CardPreview"}
|
||||
allowed := []string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview",
|
||||
}
|
||||
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
|
||||
if !slices.Contains(allowed, reached) {
|
||||
@@ -296,6 +312,14 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, item)) {
|
||||
if path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" &&
|
||||
slices.Contains([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility",
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, ac
|
||||
return authorizer(ctx, actorID, organizationID)
|
||||
}
|
||||
|
||||
func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testing.T) {
|
||||
func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T) {
|
||||
organizationID := uuid.New()
|
||||
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID)
|
||||
if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
|
||||
@@ -49,6 +49,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
|
||||
}
|
||||
|
||||
for _, operation := range []apiadapter.OperationName{
|
||||
// Card reads lock any active membership inside their read transaction;
|
||||
// the owner-only capability does not apply to that operation.
|
||||
apiadapter.GetOrganizationCandidateCardOperation,
|
||||
apiadapter.HideOrganizationOperation,
|
||||
apiadapter.UnhideOrganizationOperation,
|
||||
apiadapter.RevokeMyOrganizationContactConsentOperation,
|
||||
@@ -62,7 +65,7 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
|
||||
return ogenmiddleware.Response{}, nil
|
||||
})
|
||||
if err != nil || !called {
|
||||
t.Fatalf("candidate/self-scoped operation: called=%v err=%v; want pass-through", called, err)
|
||||
t.Fatalf("operation outside owner scope: called=%v err=%v; want pass-through", called, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -131,6 +134,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
}
|
||||
seen := make(map[string]string, len(ownerCompanyOperations))
|
||||
seenExceptions := make(map[string]bool, len(candidateExceptions))
|
||||
seenCardRead := false
|
||||
for path, methods := range document.Paths {
|
||||
for _, operation := range methods {
|
||||
if operation.OperationID == "" {
|
||||
@@ -150,6 +154,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if !strings.Contains(path, "{org_id}") {
|
||||
continue
|
||||
}
|
||||
// The card usecase checks and locks active membership together with
|
||||
// current visibility and quota. It does not require the owner role.
|
||||
if operation.OperationID == "GetOrganizationCandidateCard" &&
|
||||
path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" {
|
||||
seenCardRead = true
|
||||
continue
|
||||
}
|
||||
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
|
||||
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
|
||||
seenExceptions[operation.OperationID] = true
|
||||
@@ -168,6 +179,9 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation)
|
||||
}
|
||||
}
|
||||
if !seenCardRead {
|
||||
t.Error("transaction-authorized candidate card read is absent or moved")
|
||||
}
|
||||
}
|
||||
|
||||
type companyContextAuthenticator struct {
|
||||
|
||||
@@ -79,7 +79,7 @@ func NewRouter(
|
||||
// server aborts the response; the kit Recoverer would swallow that panic.
|
||||
router.Group(func(public chi.Router) {
|
||||
public.Use(problems.Recover)
|
||||
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer))
|
||||
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(limitOperationBody(apiServer)))
|
||||
// Unknown /api paths outside the versioned prefix are also problems,
|
||||
// so every error under /api has the contract's format.
|
||||
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
|
||||
@@ -88,6 +88,16 @@ func NewRouter(
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func limitOperationBody(server *apiadapter.Server) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
operation, found := server.FindPath(r.Method, r.URL)
|
||||
if found && operation.PathPattern() == publicPrefix+"/me/assessment-attempts/{attempt_id}/signals" {
|
||||
limitAssessmentSignalBody(w, r)
|
||||
}
|
||||
server.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current"
|
||||
|
||||
@@ -1413,7 +1413,7 @@ const (
|
||||
`"offer_type":"full_time","tasks":["Развивать сервис выплат"],"team":"Команда платежей из шести человек",` +
|
||||
`"tech_stack":["Go","PostgreSQL"],"work_formats":["remote"],"location":null,` +
|
||||
`"communication_method":` + invitationCommunication + `,"salary":` + invitationSalary + `,"package":` + invitationPackage + `}`
|
||||
validInvitationCreate = `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt",` +
|
||||
validInvitationCreate = `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",` +
|
||||
`"need":{"need_id":"01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12","requirements_version":3},` +
|
||||
`"response_period_days":7,"terms":` + validInvitationTerms + `}`
|
||||
validInvitationAccept = `{"expected_version":5,"terms_version":3,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`
|
||||
@@ -1422,7 +1422,7 @@ const (
|
||||
// invitationCreateWithTerms returns a CreateOrganizationInvitation body whose
|
||||
// terms are the valid terms with one replacement applied.
|
||||
func invitationCreateWithTerms(old, replacement string) string {
|
||||
return `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
|
||||
return `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
|
||||
}
|
||||
|
||||
// The schema alone must accept a complete invitation and reject what the
|
||||
@@ -1476,7 +1476,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "create a direct draft with the default response period",
|
||||
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","need":null,"terms":` + validInvitationTerms + `}`),
|
||||
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","need":null,"terms":` + validInvitationTerms + `}`),
|
||||
},
|
||||
{
|
||||
// The cross-field salary rules and the place of work for an
|
||||
@@ -1505,12 +1505,12 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "create for a candidate named by an email address",
|
||||
request: create(strings.Replace(validInvitationCreate, `"cand_7Qm2xVb9Lr4Kp0Zt"`, `"candidate@example.com"`, 1)),
|
||||
request: create(strings.Replace(validInvitationCreate, `"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"`, `"candidate@example.com"`, 1)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create without terms",
|
||||
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt"}`),
|
||||
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/terms", code: "required",
|
||||
},
|
||||
{
|
||||
@@ -1659,7 +1659,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "update that changes the candidate",
|
||||
request: update(`{"expected_version":1,"candidate_handle":"cand_Hx3Tn8Wq1Ys6Fd2Vb"}`),
|
||||
request: update(`{"expected_version":1,"candidate_handle":"cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -17,14 +17,19 @@ import (
|
||||
type Handler struct {
|
||||
api.UnimplementedHandler
|
||||
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
questionnaire *QuestionnaireHandler
|
||||
catalog *CatalogHandler
|
||||
organization *OrganizationHandler
|
||||
problems *problem.Responder
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
questionnaire *QuestionnaireHandler
|
||||
catalog *CatalogHandler
|
||||
organization *OrganizationHandler
|
||||
need *NeedHandler
|
||||
support *SupportHandler
|
||||
assessment *AssessmentHandler
|
||||
assessmentSignals *AssessmentSignalHandler
|
||||
privacy *PrivacyHandler
|
||||
problems *problem.Responder
|
||||
}
|
||||
|
||||
var _ api.Handler = (*Handler)(nil)
|
||||
@@ -62,6 +67,31 @@ func WithOrganization(organization *OrganizationHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.organization = organization }
|
||||
}
|
||||
|
||||
// WithNeed serves organization-scoped hiring needs.
|
||||
func WithNeed(need *NeedHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.need = need }
|
||||
}
|
||||
|
||||
// WithSupport serves account-owned support cases.
|
||||
func WithSupport(support *SupportHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.support = support }
|
||||
}
|
||||
|
||||
// WithAssessment serves candidate-owned assessment attempts and sessions.
|
||||
func WithAssessment(assessment *AssessmentHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.assessment = assessment }
|
||||
}
|
||||
|
||||
// WithAssessmentSignals serves bounded candidate assessment event receipts.
|
||||
func WithAssessmentSignals(signals *AssessmentSignalHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.assessmentSignals = signals }
|
||||
}
|
||||
|
||||
// WithPrivacy serves current publication and candidate-card visibility operations.
|
||||
func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.privacy = privacy }
|
||||
}
|
||||
|
||||
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
|
||||
handler := &Handler{health: health, problems: problems}
|
||||
for _, option := range options {
|
||||
|
||||
@@ -0,0 +1,799 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentOperations serves candidate-owned attempt reads and commands.
|
||||
type AssessmentOperations interface {
|
||||
CreateAttempt(ctx context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error)
|
||||
GetMyAssessmentAvailability(ctx context.Context, userID uuid.UUID) (assessmentusecase.AssessmentAvailability, error)
|
||||
GetMyAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error)
|
||||
StartSession(ctx context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error)
|
||||
}
|
||||
|
||||
// AssessmentHandler serves the candidate's frozen assessment attempts.
|
||||
type AssessmentHandler struct {
|
||||
operations AssessmentOperations
|
||||
}
|
||||
|
||||
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewAssessmentHandler - assessment operations must not be nil")
|
||||
}
|
||||
return &AssessmentHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request api.AssessmentAttemptCreate,
|
||||
params api.CreateMyAssessmentAttemptParams,
|
||||
) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.CreateMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.CreateMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
) (api.GetMyAssessmentAvailabilityRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentAvailability(ctx)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentAvailability(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentAttemptParams,
|
||||
) (api.GetMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentAttempt(ctx, params)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentAttempt(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) StartMyAssessmentAttemptSession(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAttemptSessionStart,
|
||||
params api.StartMyAssessmentAttemptSessionParams,
|
||||
) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.StartMyAssessmentAttemptSession(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.StartMyAssessmentAttemptSession(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) SubmitMyAssessmentAnswer(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAnswerSubmission,
|
||||
params api.SubmitMyAssessmentAnswerParams,
|
||||
) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.SubmitMyAssessmentAnswer(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.SubmitMyAssessmentAnswer(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) FinalizeMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentFinalization,
|
||||
params api.FinalizeMyAssessmentAttemptParams,
|
||||
) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.FinalizeMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.FinalizeMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentResult(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentResultParams,
|
||||
) (api.GetMyAssessmentResultRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentResult(ctx, params)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentResult(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) CreateMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request api.AssessmentAttemptCreate,
|
||||
params api.CreateMyAssessmentAttemptParams,
|
||||
) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, valid := assessmentCreateCommand(principal.UserID, params.IdempotencyKey, request)
|
||||
if !valid {
|
||||
return assessmentCreateInvalid(ctx, ""), nil
|
||||
}
|
||||
result, err := handler.operations.CreateAttempt(ctx, command)
|
||||
if err != nil {
|
||||
return assessmentCreateFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode == 409 {
|
||||
return (*api.CreateMyAssessmentAttemptConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
}
|
||||
if result.Outcome.StatusCode != 201 {
|
||||
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - unexpected stored status %d", result.Outcome.StatusCode)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentAttemptParams,
|
||||
) (api.GetMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
snapshot, err := handler.operations.GetMyAttempt(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
|
||||
if err != nil {
|
||||
return assessmentAttemptReadFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(snapshot)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAttemptSessionStart,
|
||||
params api.StartMyAssessmentAttemptSessionParams,
|
||||
) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.StartMyAssessmentAttemptSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
result, err := handler.operations.StartSession(ctx, assessmentusecase.StartAttemptSessionCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentSessionFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.StartMyAssessmentAttemptSession - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAnswerSubmission,
|
||||
params api.SubmitMyAssessmentAnswerParams,
|
||||
) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SubmitMyAssessmentAnswerUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
answer, valid := assessmentAnswerJSON(request.Answer)
|
||||
if !valid {
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/answer").Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
SubmitAnswer(ctx context.Context, command assessmentusecase.SubmitAttemptAnswerCommand) (outbound.AssessmentAttemptCommandResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - answer operation is unavailable")
|
||||
}
|
||||
result, err := operations.SubmitAnswer(ctx, assessmentusecase.SubmitAttemptAnswerCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
|
||||
IdempotencyKey: params.IdempotencyKey, Answer: answer,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentAnswerFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode != 200 {
|
||||
return assessmentAnswerCommandProblem(ctx, result.Outcome)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.SubmitMyAssessmentAnswer - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentFinalization,
|
||||
params api.FinalizeMyAssessmentAttemptParams,
|
||||
) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.FinalizeMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
FinalizeAttempt(ctx context.Context, command assessmentusecase.FinalizeAssessmentAttemptCommand) (outbound.AssessmentAttemptCommandResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - finalize operation is unavailable")
|
||||
}
|
||||
result, err := operations.FinalizeAttempt(ctx, assessmentusecase.FinalizeAssessmentAttemptCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentFinalizeFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode != 200 {
|
||||
return assessmentFinalizeCommandProblem(ctx, result.Outcome)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.FinalizeMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentResult(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentResultParams,
|
||||
) (api.GetMyAssessmentResultRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentResultUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
GetMyResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (assessmentusecase.AssessmentAttemptResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.GetMyAssessmentResult - result operation is unavailable")
|
||||
}
|
||||
result, err := operations.GetMyResult(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
|
||||
if err != nil {
|
||||
return assessmentResultFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentResultResponse(result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentResult - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentResultHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func assessmentAnswerJSON(answer api.AssessmentAnswer) ([]byte, bool) {
|
||||
encoded, err := answer.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
func assessmentCreateCommand(actorID uuid.UUID, key string, request api.AssessmentAttemptCreate) (assessmentusecase.CreateAttemptCommand, bool) {
|
||||
command := assessmentusecase.CreateAttemptCommand{ActorID: actorID, IdempotencyKey: key}
|
||||
switch request.Type {
|
||||
case api.AssessmentQualifiedAttemptCreateAssessmentAttemptCreate:
|
||||
value, ok := request.GetAssessmentQualifiedAttemptCreate()
|
||||
if !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindRoot
|
||||
command.Specialization = specializationPointer(value.Specialization)
|
||||
command.TargetGrade = gradePointer(value.TargetGrade)
|
||||
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
|
||||
case api.AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate:
|
||||
value, ok := request.GetAssessmentCorrectiveAttemptCreate()
|
||||
if !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindCorrective
|
||||
command.Specialization = specializationPointer(value.Specialization)
|
||||
command.TargetGrade = gradePointer(value.TargetGrade)
|
||||
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
|
||||
command.RootAttemptID = domain.AssessmentAttemptID(value.RootAttemptID)
|
||||
case api.AssessmentExpressAttemptCreateAssessmentAttemptCreate:
|
||||
if _, ok := request.GetAssessmentExpressAttemptCreate(); !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindDemoExpress
|
||||
default:
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
return command, true
|
||||
}
|
||||
|
||||
func specializationPointer(value api.SpecializationCode) *domain.SpecializationCode {
|
||||
code := domain.SpecializationCode(value)
|
||||
return &code
|
||||
}
|
||||
|
||||
func gradePointer(value api.GradeCode) *domain.GradeCode {
|
||||
code := domain.GradeCode(value)
|
||||
return &code
|
||||
}
|
||||
|
||||
func taskLanguagePointer(value api.NilTaskLanguage) *domain.TaskLanguageCode {
|
||||
language, ok := value.Get()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
code := domain.TaskLanguageCode(language)
|
||||
return &code
|
||||
}
|
||||
|
||||
func assessmentCreateFailure(ctx context.Context, err error) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.CreateMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.CreateMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return assessmentCreateInvalidHeader(ctx), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return assessmentCreateInvalid(ctx, attemptFieldPointer(err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAttemptReadFailure(ctx context.Context, err error) (api.GetMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.GetMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.StartMyAssessmentAttemptSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.StartMyAssessmentAttemptSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.StartMyAssessmentAttemptSessionPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.StartMyAssessmentAttemptSessionUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.SubmitMyAssessmentAnswerForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentFinalizeFailure(ctx context.Context, err error) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.FinalizeMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.FinalizeMyAssessmentAttemptPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return assessmentFinalizeConflictProblem(ctx, nil), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.FinalizeMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentResultFailure(ctx context.Context, err error) (api.GetMyAssessmentResultRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentResultForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.GetMyAssessmentResultNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return (*api.GetMyAssessmentResultConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
switch outcome.StatusCode {
|
||||
case 404:
|
||||
if outcome.ProblemCode == "not_found" {
|
||||
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
}
|
||||
case 409:
|
||||
if outcome.ProblemCode == "state_conflict" {
|
||||
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - stored problem outcome is invalid")
|
||||
}
|
||||
|
||||
func assessmentFinalizeCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
switch outcome.StatusCode {
|
||||
case 404:
|
||||
if outcome.ProblemCode == "not_found" {
|
||||
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
}
|
||||
case 409:
|
||||
if outcome.ProblemCode == "state_conflict" {
|
||||
return assessmentFinalizeConflictProblem(ctx, outcome.PendingItemIDs), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - stored problem outcome is invalid")
|
||||
}
|
||||
|
||||
func assessmentFinalizeConflictProblem(
|
||||
ctx context.Context,
|
||||
pendingItemIDs []uuid.UUID,
|
||||
) *api.AssessmentFinalizeConflictProblem {
|
||||
base := problem.New(ctx, api.ProblemCodeStateConflict).Response
|
||||
return &api.AssessmentFinalizeConflictProblem{
|
||||
Type: base.Type, Title: base.Title, Status: base.Status,
|
||||
Code: api.AssessmentFinalizeConflictProblemCodeStateConflict,
|
||||
Detail: base.Detail, Instance: base.Instance, TraceID: base.TraceID, Errors: base.Errors,
|
||||
PendingItemIds: append([]uuid.UUID(nil), pendingItemIDs...),
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentResult, error) {
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindDemoExpress {
|
||||
if result.Outcome != domain.AssessmentAttemptOutcomeDemonstration || result.DecidedAt.IsZero() || result.Summary == "" {
|
||||
return api.AssessmentResult{}, errors.New("express result is incomplete")
|
||||
}
|
||||
return api.NewAssessmentExpressResultAssessmentResult(api.AssessmentExpressResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Kind: api.AssessmentExpressResultKindDemoExpress,
|
||||
Mode: api.AssessmentExpressResultModeDemoExpress, Versions: assessmentResultVersions(result.Attempt),
|
||||
Outcome: api.AssessmentExpressResultOutcomeDemonstration,
|
||||
CalibrationStatus: api.AssessmentExpressResultCalibrationStatusUncalibrated,
|
||||
Limitations: []api.AssessmentExpressResultLimitationsItem{api.AssessmentExpressResultLimitationsItemDemonstrationOnly},
|
||||
Practices: []api.AssessmentPracticeResult{}, Gaps: []api.AssessmentGap{},
|
||||
Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
|
||||
type assessmentRealResultResponseFields struct {
|
||||
rootAttemptID api.NilUUID
|
||||
chainDeadline api.NilTimestamp
|
||||
taskLanguage api.NilTaskLanguage
|
||||
outcome api.AssessmentOutcome
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
fields := assessmentRealResultResponseFields{
|
||||
outcome: api.AssessmentOutcome(result.Outcome), limitations: make([]api.AssessmentLimitation, 0, len(result.Limitations)),
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindCorrective {
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return assessmentRealResultResponseFields{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
fields.rootAttemptID.SetTo(result.Attempt.RootAttemptID.UUID())
|
||||
fields.chainDeadline.SetTo(api.Timestamp(*result.Attempt.ChainDeadline))
|
||||
} else {
|
||||
fields.rootAttemptID.SetToNull()
|
||||
fields.chainDeadline.SetToNull()
|
||||
}
|
||||
if result.Attempt.TaskLanguage == nil {
|
||||
fields.taskLanguage.SetToNull()
|
||||
} else {
|
||||
fields.taskLanguage.SetTo(api.TaskLanguage(*result.Attempt.TaskLanguage))
|
||||
}
|
||||
if result.NotDeterminedReason == "" {
|
||||
fields.reason.SetToNull()
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
fields.basicScore.SetToNull()
|
||||
} else {
|
||||
fields.basicScore.SetTo(api.BasicScore{
|
||||
Points: result.BasicScore.Points, MaxPoints: result.BasicScore.MaxPoints, PassPoints: result.BasicScore.PassPoints,
|
||||
})
|
||||
}
|
||||
for _, limitation := range result.Limitations {
|
||||
fields.limitations = append(fields.limitations, api.AssessmentLimitation(limitation))
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentItemsSeconds(result assessmentusecase.AssessmentAttemptResult) int32 {
|
||||
seconds := int64(result.DecidedAt.Sub(result.Attempt.StartedAt) / time.Second)
|
||||
if seconds < 0 || seconds > 1<<31-1 {
|
||||
return 0
|
||||
}
|
||||
return int32(seconds)
|
||||
}
|
||||
|
||||
func nilInt32() api.NilInt32 {
|
||||
var value api.NilInt32
|
||||
value.SetToNull()
|
||||
return value
|
||||
}
|
||||
|
||||
func assessmentCreateInvalid(ctx context.Context, pointer string) api.CreateMyAssessmentAttemptRes {
|
||||
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response)
|
||||
}
|
||||
|
||||
func assessmentCreateInvalidHeader(ctx context.Context) api.CreateMyAssessmentAttemptRes {
|
||||
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response)
|
||||
}
|
||||
|
||||
func attemptFieldPointer(err error) string {
|
||||
fieldError, ok := errors.AsType[*assessmentusecase.AttemptFieldError](err)
|
||||
if !ok || fieldError == nil {
|
||||
return ""
|
||||
}
|
||||
return fieldError.Pointer
|
||||
}
|
||||
|
||||
func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
|
||||
current, err := assessmentCurrentItem(snapshot.CurrentItem)
|
||||
if err != nil {
|
||||
return api.AssessmentAttempt{}, err
|
||||
}
|
||||
fields := assessmentAttemptFields(snapshot, current)
|
||||
switch snapshot.Kind {
|
||||
case domain.AssessmentAttemptKindRoot:
|
||||
return api.NewAssessmentQualifiedAttemptAssessmentAttempt(api.AssessmentQualifiedAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedAttemptKindRoot, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentQualifiedAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
case domain.AssessmentAttemptKindCorrective:
|
||||
return api.NewAssessmentCorrectiveAttemptAssessmentAttempt(api.AssessmentCorrectiveAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveAttemptKindCorrective, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentCorrectiveAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
case domain.AssessmentAttemptKindDemoExpress:
|
||||
return api.NewAssessmentExpressAttemptAssessmentAttempt(api.AssessmentExpressAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentExpressAttemptKindDemoExpress, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentExpressAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
default:
|
||||
return api.AssessmentAttempt{}, errors.New("unknown assessment attempt kind")
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentAttemptResponseFields struct {
|
||||
specialization api.NilSpecializationCode
|
||||
targetGrade api.NilGradeCode
|
||||
taskLanguage api.NilTaskLanguage
|
||||
rootAttemptID api.NilUUID
|
||||
chainDeadline api.NilTimestamp
|
||||
versions api.AssessmentVersions
|
||||
startedAt api.Timestamp
|
||||
expiresAt api.Timestamp
|
||||
sessions api.NilAssessmentSessions
|
||||
finishedAt api.NilTimestamp
|
||||
progress api.AssessmentProgress
|
||||
currentItem api.NilAssessmentItem
|
||||
}
|
||||
|
||||
func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, currentItem api.NilAssessmentItem) assessmentAttemptResponseFields {
|
||||
fields := assessmentAttemptResponseFields{
|
||||
versions: api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
|
||||
},
|
||||
startedAt: api.Timestamp(snapshot.StartedAt), expiresAt: api.Timestamp(snapshot.ExpiresAt),
|
||||
progress: api.AssessmentProgress{AnsweredItems: snapshot.AnsweredItems, MaxItems: snapshot.MaxItems},
|
||||
currentItem: currentItem,
|
||||
}
|
||||
setAttemptTrackFields(&fields, snapshot)
|
||||
setAttemptSessionFields(&fields, snapshot)
|
||||
setAttemptEndFields(&fields, snapshot)
|
||||
return fields
|
||||
}
|
||||
|
||||
func setAttemptTrackFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.Specialization == nil {
|
||||
fields.specialization.SetToNull()
|
||||
} else {
|
||||
fields.specialization.SetTo(api.SpecializationCode(*snapshot.Specialization))
|
||||
}
|
||||
if snapshot.TargetGrade == nil {
|
||||
fields.targetGrade.SetToNull()
|
||||
} else {
|
||||
fields.targetGrade.SetTo(api.GradeCode(*snapshot.TargetGrade))
|
||||
}
|
||||
if snapshot.TaskLanguage == nil {
|
||||
fields.taskLanguage.SetToNull()
|
||||
} else {
|
||||
fields.taskLanguage.SetTo(api.TaskLanguage(*snapshot.TaskLanguage))
|
||||
}
|
||||
if snapshot.RootAttemptID == nil {
|
||||
fields.rootAttemptID.SetToNull()
|
||||
} else {
|
||||
fields.rootAttemptID.SetTo(snapshot.RootAttemptID.UUID())
|
||||
}
|
||||
if snapshot.ChainDeadline == nil {
|
||||
fields.chainDeadline.SetToNull()
|
||||
} else {
|
||||
fields.chainDeadline.SetTo(api.Timestamp(*snapshot.ChainDeadline))
|
||||
}
|
||||
}
|
||||
|
||||
func setAttemptSessionFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.MaxSessions <= 0 {
|
||||
fields.sessions.SetToNull()
|
||||
return
|
||||
}
|
||||
fields.sessions.SetTo(api.AssessmentSessions{
|
||||
Used: snapshot.SessionsUsed, Max: snapshot.MaxSessions, IdleTimeoutSeconds: snapshot.IdleTimeout,
|
||||
})
|
||||
}
|
||||
|
||||
func setAttemptEndFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.FinishedAt == nil {
|
||||
fields.finishedAt.SetToNull()
|
||||
return
|
||||
}
|
||||
fields.finishedAt.SetTo(api.Timestamp(*snapshot.FinishedAt))
|
||||
}
|
||||
|
||||
func assessmentCurrentItem(item *domain.AssessmentAttemptPublicItem) (api.NilAssessmentItem, error) {
|
||||
var current api.NilAssessmentItem
|
||||
if item == nil {
|
||||
current.SetToNull()
|
||||
return current, nil
|
||||
}
|
||||
content, err := assessmentItemContent(item.Content)
|
||||
if err != nil {
|
||||
return api.NilAssessmentItem{}, err
|
||||
}
|
||||
current.SetTo(api.AssessmentItem{
|
||||
ID: api.AssessmentItemId(item.ID), Sequence: item.Sequence, Prompt: item.Prompt, Content: content,
|
||||
})
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func assessmentItemContent(content domain.AssessmentAttemptPublicItemContent) (api.ItemContent, error) {
|
||||
switch content.Format {
|
||||
case "number":
|
||||
var unit api.NilString
|
||||
if content.Unit == nil {
|
||||
unit.SetToNull()
|
||||
} else {
|
||||
unit.SetTo(*content.Unit)
|
||||
}
|
||||
return api.NewNumberItemContentItemContent(api.NumberItemContent{Format: api.NumberItemContentFormatNumber, Unit: unit}), nil
|
||||
case "order":
|
||||
elements := make([]api.AssessmentOption, 0, len(content.Elements))
|
||||
for _, element := range content.Elements {
|
||||
elements = append(elements, api.AssessmentOption{ID: api.AssessmentOptionId(element.ID), Text: element.Text})
|
||||
}
|
||||
return api.NewOrderItemContentItemContent(api.OrderItemContent{Format: api.OrderItemContentFormatOrder, Elements: elements}), nil
|
||||
default:
|
||||
return api.ItemContent{}, errors.New("unsupported public assessment item format")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
) (api.GetMyAssessmentAvailabilityRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentAvailabilityUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
availability, err := handler.operations.GetMyAssessmentAvailability(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentAvailabilityForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAssessmentAvailabilityNotImplemented):
|
||||
return nil, problem.New(ctx, api.ProblemCodeNotImplemented)
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
response, err := assessmentAvailabilityResponse(availability)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAvailability - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAvailabilityHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func assessmentAvailabilityResponse(
|
||||
availability assessmentusecase.AssessmentAvailability,
|
||||
) (api.AssessmentAvailability, error) {
|
||||
response := api.AssessmentAvailability{Specializations: make([]api.AssessmentSpecializationAvailability, 0, len(availability.Specializations))}
|
||||
for _, item := range availability.Specializations {
|
||||
if !item.Specialization.IsKnown() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown specialization")
|
||||
}
|
||||
specialization := api.AssessmentSpecializationAvailability{
|
||||
Specialization: api.SpecializationCode(item.Specialization),
|
||||
Grades: make([]api.AssessmentGradeAvailability, 0, len(item.Grades)),
|
||||
}
|
||||
specialization.ConfirmedGrade.SetToNull()
|
||||
if item.ConfirmedGrade != nil {
|
||||
if !item.ConfirmedGrade.IsKnown() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown confirmed grade")
|
||||
}
|
||||
specialization.ConfirmedGrade.SetTo(api.GradeCode(*item.ConfirmedGrade))
|
||||
}
|
||||
specialization.ActiveAttemptID.SetToNull()
|
||||
if item.ActiveAttemptID != nil {
|
||||
if item.ActiveAttemptID.IsZero() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an invalid active attempt ID")
|
||||
}
|
||||
specialization.ActiveAttemptID.SetTo(item.ActiveAttemptID.UUID())
|
||||
}
|
||||
for _, grade := range item.Grades {
|
||||
mapped, err := assessmentGradeAvailabilityResponse(grade)
|
||||
if err != nil {
|
||||
return api.AssessmentAvailability{}, err
|
||||
}
|
||||
specialization.Grades = append(specialization.Grades, mapped)
|
||||
}
|
||||
response.Specializations = append(response.Specializations, specialization)
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func assessmentGradeAvailabilityResponse(
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) (api.AssessmentGradeAvailability, error) {
|
||||
if !grade.Grade.IsKnown() {
|
||||
return api.AssessmentGradeAvailability{}, errors.New("assessment availability has an unknown grade")
|
||||
}
|
||||
response := api.AssessmentGradeAvailability{Grade: api.GradeCode(grade.Grade)}
|
||||
response.Mode.SetToNull()
|
||||
response.AvailableAt.SetToNull()
|
||||
response.TimeLimitSeconds.SetToNull()
|
||||
response.MaxSessions.SetToNull()
|
||||
response.MaxItems.SetToNull()
|
||||
response.PracticeRequired.SetToNull()
|
||||
status, err := assessmentAvailabilityStatus(grade)
|
||||
if err != nil {
|
||||
return api.AssessmentGradeAvailability{}, err
|
||||
}
|
||||
response.Status = status
|
||||
if err := setAssessmentAvailabilityLimits(&response, grade); err != nil {
|
||||
return api.AssessmentGradeAvailability{}, err
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func assessmentAvailabilityStatus(
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) (api.AssessmentGradeAvailabilityStatus, error) {
|
||||
switch grade.Status {
|
||||
case assessmentusecase.AvailabilityStatusAvailable:
|
||||
return api.AssessmentGradeAvailabilityStatusAvailable, nil
|
||||
case assessmentusecase.AvailabilityStatusActiveAttempt:
|
||||
return api.AssessmentGradeAvailabilityStatusActiveAttempt, nil
|
||||
case assessmentusecase.AvailabilityStatusCooldown:
|
||||
if grade.AvailableAt == nil || grade.AvailableAt.IsZero() {
|
||||
return "", errors.New("assessment cooldown has no available time")
|
||||
}
|
||||
return api.AssessmentGradeAvailabilityStatusCooldown, nil
|
||||
case assessmentusecase.AvailabilityStatusInsufficientBank:
|
||||
return api.AssessmentGradeAvailabilityStatusInsufficientBank, nil
|
||||
default:
|
||||
return "", errors.New("assessment availability has an unknown status")
|
||||
}
|
||||
}
|
||||
|
||||
func setAssessmentAvailabilityLimits(
|
||||
response *api.AssessmentGradeAvailability,
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) error {
|
||||
if grade.Status == assessmentusecase.AvailabilityStatusInsufficientBank {
|
||||
return validateInsufficientBankLimits(grade)
|
||||
}
|
||||
if err := validateAssessmentAttemptLimits(grade); err != nil {
|
||||
return err
|
||||
}
|
||||
if grade.Status == assessmentusecase.AvailabilityStatusCooldown {
|
||||
response.AvailableAt.SetTo(api.Timestamp(grade.AvailableAt.UTC()))
|
||||
}
|
||||
response.Mode.SetTo(api.AssessmentRealMode(*grade.Mode))
|
||||
response.TimeLimitSeconds.SetTo(*grade.TimeLimitSeconds)
|
||||
response.MaxSessions.SetTo(*grade.MaxSessions)
|
||||
response.MaxItems.SetTo(*grade.MaxItems)
|
||||
response.PracticeRequired.SetTo(*grade.PracticeRequired)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateInsufficientBankLimits(grade assessmentusecase.GradeAvailability) error {
|
||||
if grade.Mode != nil || grade.AvailableAt != nil || grade.TimeLimitSeconds != nil || grade.MaxSessions != nil ||
|
||||
grade.MaxItems != nil || grade.PracticeRequired != nil {
|
||||
return errors.New("insufficient-bank availability contains attempt limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssessmentAttemptLimits(grade assessmentusecase.GradeAvailability) error {
|
||||
if grade.Mode == nil || *grade.Mode != domain.AssessmentRealModeDemoBasic || grade.TimeLimitSeconds == nil ||
|
||||
*grade.TimeLimitSeconds <= 0 || grade.MaxSessions == nil || *grade.MaxSessions <= 0 || grade.MaxItems == nil ||
|
||||
*grade.MaxItems <= 0 || grade.PracticeRequired == nil {
|
||||
return errors.New("available assessment has incomplete attempt limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func TestGetMyAssessmentAvailabilityMapsReadOnlyCandidateProjection(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
activeAttemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
availableAt := time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC)
|
||||
seconds, sessions, items := int32(3600), int32(2), int32(25)
|
||||
mode := domain.AssessmentRealModeDemoBasic
|
||||
practice := false
|
||||
operations := &assessmentOperationsStub{availability: assessmentusecase.AssessmentAvailability{
|
||||
Specializations: []assessmentusecase.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationCode("backend"), ActiveAttemptID: &activeAttemptID,
|
||||
Grades: []assessmentusecase.GradeAvailability{
|
||||
{Grade: domain.GradeIntern, Status: assessmentusecase.AvailabilityStatusActiveAttempt,
|
||||
Mode: &mode, TimeLimitSeconds: &seconds, MaxSessions: &sessions, MaxItems: &items, PracticeRequired: &practice},
|
||||
{Grade: domain.GradeJunior, Status: assessmentusecase.AvailabilityStatusCooldown,
|
||||
Mode: &mode, AvailableAt: &availableAt, TimeLimitSeconds: &seconds, MaxSessions: &sessions,
|
||||
MaxItems: &items, PracticeRequired: &practice},
|
||||
{Grade: domain.GradeMiddle, Status: assessmentusecase.AvailabilityStatusInsufficientBank},
|
||||
},
|
||||
}},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
response, err := handler.GetMyAssessmentAvailability(principalForTest(userID))
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAvailability() error = %v", err)
|
||||
}
|
||||
headers, ok := response.(*api.AssessmentAvailabilityHeaders)
|
||||
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore || operations.availabilityCalls != 1 ||
|
||||
operations.availabilityUserID != userID {
|
||||
t.Fatalf("availability response = %T %+v, calls=%d user=%s", response, response, operations.availabilityCalls, operations.availabilityUserID)
|
||||
}
|
||||
if len(headers.Response.Specializations) != 1 {
|
||||
t.Fatalf("specializations = %+v", headers.Response.Specializations)
|
||||
}
|
||||
specialization := headers.Response.Specializations[0]
|
||||
if specialization.Specialization != api.SpecializationCodeBackend || !specialization.ConfirmedGrade.IsNull() {
|
||||
t.Fatalf("specialization = %+v", specialization)
|
||||
}
|
||||
if activeID, found := specialization.ActiveAttemptID.Get(); !found || activeID != activeAttemptID.UUID() {
|
||||
t.Fatalf("active attempt ID = %+v, %v", specialization.ActiveAttemptID, found)
|
||||
}
|
||||
if len(specialization.Grades) != 3 {
|
||||
t.Fatalf("grade availability = %+v", specialization.Grades)
|
||||
}
|
||||
if row := specialization.Grades[0]; row.Status != api.AssessmentGradeAvailabilityStatusActiveAttempt ||
|
||||
row.Mode.IsNull() || !row.AvailableAt.IsNull() || row.TimeLimitSeconds.IsNull() {
|
||||
// Active rows carry their mode and limits but never an available_at value.
|
||||
t.Fatalf("active grade projection = %+v", row)
|
||||
}
|
||||
if row := specialization.Grades[1]; row.Status != api.AssessmentGradeAvailabilityStatusCooldown ||
|
||||
row.AvailableAt.IsNull() || row.AvailableAt.Value != api.Timestamp(availableAt) || row.TimeLimitSeconds.IsNull() {
|
||||
t.Fatalf("cooldown grade projection = %+v", row)
|
||||
}
|
||||
if row := specialization.Grades[2]; row.Status != api.AssessmentGradeAvailabilityStatusInsufficientBank ||
|
||||
!row.Mode.IsNull() || !row.TimeLimitSeconds.IsNull() || !row.AvailableAt.IsNull() {
|
||||
t.Fatalf("insufficient-bank projection = %+v", row)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetMyAssessmentAvailabilityMapsAuthAndUnavailableMode(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{availabilityErr: assessmentusecase.ErrAssessmentAvailabilityNotImplemented}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
unauthenticated, err := handler.GetMyAssessmentAvailability(noPrincipalContext())
|
||||
if err != nil {
|
||||
t.Fatalf("unauthenticated availability error = %v", err)
|
||||
}
|
||||
if _, ok := unauthenticated.(*api.GetMyAssessmentAvailabilityUnauthorized); !ok || operations.availabilityCalls != 0 {
|
||||
t.Fatalf("unauthenticated response = %T, calls=%d", unauthenticated, operations.availabilityCalls)
|
||||
}
|
||||
_, err = handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
|
||||
var statusError *api.ProblemStatusCode
|
||||
if !errors.As(err, &statusError) || statusError.GetStatusCode() != 501 {
|
||||
t.Fatalf("unavailable mode error = %v, want a 501 problem", err)
|
||||
}
|
||||
operations.availabilityErr = assessmentusecase.ErrAttemptForbidden
|
||||
forbidden, err := handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
|
||||
if err != nil {
|
||||
t.Fatalf("forbidden availability error = %v", err)
|
||||
}
|
||||
if _, ok := forbidden.(*api.GetMyAssessmentAvailabilityForbidden); !ok {
|
||||
t.Fatalf("forbidden response = %T", forbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func noPrincipalContext() context.Context { return context.Background() }
|
||||
@@ -0,0 +1,190 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type AssessmentSignalOperations interface {
|
||||
RecordSignals(ctx context.Context, command assessmentusecase.RecordSignalsCommand) (domain.AssessmentSignalReceipt, error)
|
||||
}
|
||||
|
||||
// AssessmentSignalHandler maps the typed candidate contract to domain input.
|
||||
// It never logs or returns event details.
|
||||
type AssessmentSignalHandler struct {
|
||||
operations AssessmentSignalOperations
|
||||
}
|
||||
|
||||
func NewAssessmentSignalHandler(operations AssessmentSignalOperations) *AssessmentSignalHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewAssessmentSignalHandler - assessment signal operations must not be nil")
|
||||
}
|
||||
return &AssessmentSignalHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) RecordMyAssessmentAttemptSignals(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentSignalBatch,
|
||||
params api.RecordMyAssessmentAttemptSignalsParams,
|
||||
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
if handler.assessmentSignals == nil {
|
||||
return handler.UnimplementedHandler.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
return handler.assessmentSignals.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *AssessmentSignalHandler) RecordMyAssessmentAttemptSignals(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentSignalBatch,
|
||||
params api.RecordMyAssessmentAttemptSignalsParams,
|
||||
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.RecordMyAssessmentAttemptSignalsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return signalInvalidBody(ctx), nil
|
||||
}
|
||||
events, valid := assessmentSignalEvents(request.Events)
|
||||
if !valid {
|
||||
return signalInvalidBody(ctx), nil
|
||||
}
|
||||
receipt, err := handler.operations.RecordSignals(ctx, assessmentusecase.RecordSignalsCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
IdempotencyKey: params.IdempotencyKey, Events: events,
|
||||
})
|
||||
if err != nil {
|
||||
return signalFailure(ctx, err)
|
||||
}
|
||||
return &api.AssessmentSignalReceiptHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentSignalReceipt{
|
||||
Status: api.AssessmentSignalReceiptStatus(receipt.Status()), AcceptedEvents: receipt.AcceptedEvents(),
|
||||
ReceivedAt: api.Timestamp(receipt.ReceivedAt()),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentSignalEvents(requestEvents []api.AssessmentSignalEvent) ([]domain.AssessmentSignalEvent, bool) {
|
||||
if len(requestEvents) == 0 || len(requestEvents) > 50 {
|
||||
return nil, false
|
||||
}
|
||||
events := make([]domain.AssessmentSignalEvent, 0, len(requestEvents))
|
||||
for _, requestEvent := range requestEvents {
|
||||
input, valid := assessmentSignalEventInput(requestEvent)
|
||||
if !valid {
|
||||
return nil, false
|
||||
}
|
||||
event, err := domain.NewAssessmentSignalEvent(input)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
events = append(events, event)
|
||||
}
|
||||
return events, true
|
||||
}
|
||||
|
||||
func assessmentSignalEventInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
switch requestEvent.Type {
|
||||
case api.AssessmentFocusLossSignalAssessmentSignalEvent:
|
||||
return assessmentFocusLossInput(requestEvent)
|
||||
case api.AssessmentSignalEventCopyAssessmentSignalEvent,
|
||||
api.AssessmentSignalEventPasteAssessmentSignalEvent,
|
||||
api.AssessmentSignalEventCutAssessmentSignalEvent:
|
||||
return assessmentClipboardInput(requestEvent)
|
||||
case api.AssessmentFullscreenExitSignalAssessmentSignalEvent:
|
||||
return assessmentFullscreenExitInput(requestEvent)
|
||||
default:
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentFocusLossInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentFocusLossSignal()
|
||||
if !ok || value.Kind != api.AssessmentFocusLossSignalKindFocusLoss {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
duration := value.DurationMs
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt), DurationMS: &duration,
|
||||
}, true
|
||||
}
|
||||
|
||||
func assessmentClipboardInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentClipboardSignal()
|
||||
if !ok {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
kind := domain.AssessmentSignalKind(value.Kind)
|
||||
if kind != domain.AssessmentSignalKind(requestEvent.Type) {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
size := value.SizeBytes
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: kind, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt), SizeBytes: &size,
|
||||
}, true
|
||||
}
|
||||
|
||||
func assessmentFullscreenExitInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentFullscreenExitSignal()
|
||||
if !ok || value.Kind != api.AssessmentFullscreenExitSignalKindFullscreenExit {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt),
|
||||
}, true
|
||||
}
|
||||
|
||||
func signalInvalidBody(ctx context.Context) *api.RecordMyAssessmentAttemptSignalsBadRequest {
|
||||
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response,
|
||||
)
|
||||
}
|
||||
|
||||
func signalFailure(ctx context.Context, err error) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptSignalForbidden), errors.Is(err, assessmentusecase.ErrAttemptSignalConsentRequired):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptSignalStateConflict):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(
|
||||
&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response,
|
||||
), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
|
||||
), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptSignalRequest), errors.Is(err, domain.ErrInvalidAssessmentSignal):
|
||||
return signalInvalidBody(ctx), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptSignalRateLimited):
|
||||
limited, ok := errors.AsType[*assessmentusecase.SignalRateLimitError](err)
|
||||
if !ok || limited == nil {
|
||||
return nil, err
|
||||
}
|
||||
wait := time.Until(limited.RetryAt)
|
||||
if wait < time.Second {
|
||||
wait = time.Second
|
||||
}
|
||||
seconds := int32(math.Ceil(wait.Seconds()))
|
||||
return problem.RateLimited(ctx, seconds), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type assessmentSignalOperationsStub struct {
|
||||
command assessmentusecase.RecordSignalsCommand
|
||||
receipt domain.AssessmentSignalReceipt
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (stub *assessmentSignalOperationsStub) RecordSignals(
|
||||
_ context.Context,
|
||||
command assessmentusecase.RecordSignalsCommand,
|
||||
) (domain.AssessmentSignalReceipt, error) {
|
||||
stub.calls++
|
||||
stub.command = command
|
||||
return stub.receipt, stub.err
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
|
||||
actorID, attemptID, itemID := uuid.New(), uuid.New(), uuid.New()
|
||||
at := api.Timestamp(time.Date(2026, time.October, 7, 12, 0, 0, 123456000, time.UTC))
|
||||
duration, size := int32(4500), int32(32)
|
||||
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{
|
||||
api.NewAssessmentFocusLossSignalAssessmentSignalEvent(api.AssessmentFocusLossSignal{
|
||||
Kind: api.AssessmentFocusLossSignalKindFocusLoss, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, DurationMs: duration,
|
||||
}),
|
||||
api.NewAssessmentSignalEventCopyAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindCopy, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentSignalEventPasteAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindPaste, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentSignalEventCutAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindCut, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
|
||||
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at,
|
||||
}),
|
||||
}}
|
||||
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 5, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalReceipt() error = %v", err)
|
||||
}
|
||||
operations := &assessmentSignalOperationsStub{receipt: receipt}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
result, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(actorID), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: attemptID, IdempotencyKey: "event-batch"})
|
||||
if err != nil {
|
||||
t.Fatalf("RecordMyAssessmentAttemptSignals() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.AssessmentSignalReceiptHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("RecordMyAssessmentAttemptSignals() result = %T, want receipt headers", result)
|
||||
}
|
||||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 5 ||
|
||||
response.Response.Status != api.AssessmentSignalReceiptStatusAccepted {
|
||||
t.Fatalf("receipt response = %+v", response)
|
||||
}
|
||||
command := operations.command
|
||||
if operations.calls != 1 || command.ActorID != actorID || command.AttemptID != domain.AssessmentAttemptID(attemptID) ||
|
||||
command.IdempotencyKey != "event-batch" || len(command.Events) != 5 {
|
||||
t.Fatalf("record command = %+v, calls %d", command, operations.calls)
|
||||
}
|
||||
wantKinds := []domain.AssessmentSignalKind{
|
||||
domain.AssessmentSignalFocusLoss, domain.AssessmentSignalCopy, domain.AssessmentSignalPaste,
|
||||
domain.AssessmentSignalCut, domain.AssessmentSignalFullscreenExit,
|
||||
}
|
||||
for index, event := range command.Events {
|
||||
if event.Kind() != wantKinds[index] || event.ItemInstanceID() != itemID || !event.OccurredAt().Equal(time.Time(at)) {
|
||||
t.Errorf("event %d = %s / %s / %s", index, event.Kind(), event.ItemInstanceID(), event.OccurredAt())
|
||||
}
|
||||
}
|
||||
if got, ok := command.Events[0].DurationMS(); !ok || got != duration {
|
||||
t.Errorf("focus duration = %d, %v; want %d, true", got, ok, duration)
|
||||
}
|
||||
for _, index := range []int{1, 2, 3} {
|
||||
if got, ok := command.Events[index].SizeBytes(); !ok || got != size {
|
||||
t.Errorf("clipboard size at %d = %d, %v; want %d, true", index, got, ok, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerMapsAuthorizationAndBusinessProblems(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
err error
|
||||
want any
|
||||
}{
|
||||
{name: "forbidden", err: assessmentusecase.ErrAttemptSignalConsentRequired, want: (*api.RecordMyAssessmentAttemptSignalsForbidden)(nil)},
|
||||
{name: "missing attempt", err: assessmentusecase.ErrAttemptNotFound, want: (*api.RecordMyAssessmentAttemptSignalsNotFound)(nil)},
|
||||
{name: "state conflict", err: assessmentusecase.ErrAttemptSignalStateConflict, want: (*api.RecordMyAssessmentAttemptSignalsConflict)(nil)},
|
||||
{name: "key reused", err: assessmentusecase.ErrAttemptKeyReused, want: (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(nil)},
|
||||
{name: "invalid key", err: assessmentusecase.ErrInvalidAttemptKey, want: (*api.RecordMyAssessmentAttemptSignalsBadRequest)(nil)},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
result, err := signalFailure(context.Background(), testCase.err)
|
||||
if err != nil {
|
||||
t.Fatalf("signalFailure() error = %v", err)
|
||||
}
|
||||
if result == nil || reflect.TypeOf(result) != reflect.TypeOf(testCase.want) {
|
||||
t.Fatalf("signalFailure() result = %T, want %T", result, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
result, err := signalFailure(context.Background(), &assessmentusecase.SignalRateLimitError{RetryAt: time.Now().Add(4 * time.Second)})
|
||||
if err != nil {
|
||||
t.Fatalf("signalFailure(rate limit) error = %v", err)
|
||||
}
|
||||
limited, ok := result.(*api.TooManyRequestsHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("signalFailure(rate limit) result = %T", result)
|
||||
}
|
||||
if seconds, present := limited.RetryAfter.Get(); !present || seconds < 1 || seconds > 4 {
|
||||
t.Fatalf("Retry-After = %d, %v; want 1 to 4 seconds", seconds, present)
|
||||
}
|
||||
|
||||
operations := &assessmentSignalOperationsStub{}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
unauthorized, err := handler.RecordMyAssessmentAttemptSignals(context.Background(), &api.AssessmentSignalBatch{}, api.RecordMyAssessmentAttemptSignalsParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("unauthenticated RecordMyAssessmentAttemptSignals() error = %v", err)
|
||||
}
|
||||
if _, ok := unauthorized.(*api.RecordMyAssessmentAttemptSignalsUnauthorized); !ok || operations.calls != 0 {
|
||||
t.Fatalf("unauthenticated result = %T, calls %d", unauthorized, operations.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerRejectsWrongVariantAndInternalErrorsPropagate(t *testing.T) {
|
||||
operations := &assessmentSignalOperationsStub{err: errors.New("private storage failure")}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{{Type: "unknown"}}}
|
||||
invalid, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("invalid variant error = %v", err)
|
||||
}
|
||||
if _, ok := invalid.(*api.RecordMyAssessmentAttemptSignalsBadRequest); !ok || operations.calls != 0 {
|
||||
t.Fatalf("invalid variant result = %T, calls %d", invalid, operations.calls)
|
||||
}
|
||||
|
||||
request.Events = []api.AssessmentSignalEvent{
|
||||
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
|
||||
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(uuid.New()),
|
||||
OccurredAt: api.Timestamp(time.Now()),
|
||||
}),
|
||||
}
|
||||
_, err = handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err == nil || err.Error() != "private storage failure" {
|
||||
t.Fatalf("internal error = %v, want sanitized propagation to responder", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func TestCreateAssessmentAttemptMapsRootAndPublicSnapshot(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
snapshot := assessmentPublicSnapshot()
|
||||
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
|
||||
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: snapshot},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
request := api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(api.AssessmentQualifiedAttemptCreate{
|
||||
Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior",
|
||||
TaskLanguage: api.NewNilTaskLanguage(api.TaskLanguage("go")),
|
||||
})
|
||||
response, err := handler.CreateMyAssessmentAttempt(principalForTest(userID), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "create-key"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if operations.createCalls != 1 || operations.createCommand.ActorID != userID || operations.createCommand.Kind != domain.AssessmentAttemptKindRoot ||
|
||||
operations.createCommand.IdempotencyKey != "create-key" || operations.createCommand.Specialization == nil ||
|
||||
*operations.createCommand.Specialization != "backend" || operations.createCommand.TargetGrade == nil ||
|
||||
*operations.createCommand.TargetGrade != "junior" || operations.createCommand.TaskLanguage == nil ||
|
||||
*operations.createCommand.TaskLanguage != "go" {
|
||||
t.Fatalf("CreateAttempt() command = %+v, calls %d", operations.createCommand, operations.createCalls)
|
||||
}
|
||||
headers, ok := response.(*api.AssessmentAttemptHeaders)
|
||||
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore {
|
||||
t.Fatalf("create response = %T %+v, want no-store headers", response, response)
|
||||
}
|
||||
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
|
||||
if !ok || qualified.ID != snapshot.ID.UUID() || qualified.Version != api.AssessmentAttemptVersion(snapshot.Version) ||
|
||||
qualified.CurrentItem.IsNull() || qualified.Progress.MaxItems != snapshot.MaxItems ||
|
||||
qualified.Versions.AlgorithmVersion != api.AssessmentVersionLabel(snapshot.AlgorithmVersion) {
|
||||
t.Fatalf("qualified attempt response = %+v, %v", qualified, ok)
|
||||
}
|
||||
item, ok := qualified.CurrentItem.Get()
|
||||
if !ok || item.Prompt != "Choose the number" || !item.Content.IsNumberItemContent() {
|
||||
t.Fatalf("current item = %+v, %v", item, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAssessmentAttemptMapsPersistedConflictAndRejectsGuest(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
|
||||
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
request := api.NewAssessmentExpressAttemptCreateAssessmentAttemptCreate(api.AssessmentExpressAttemptCreate{
|
||||
Kind: api.AssessmentExpressAttemptCreateKindDemoExpress,
|
||||
})
|
||||
response, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := response.(*api.CreateMyAssessmentAttemptConflict); !ok {
|
||||
t.Fatalf("state conflict response = %T, want conflict", response)
|
||||
}
|
||||
if operations.createCommand.Kind != domain.AssessmentAttemptKindDemoExpress || operations.createCommand.Specialization != nil {
|
||||
t.Fatalf("express command = %+v", operations.createCommand)
|
||||
}
|
||||
response, err = handler.CreateMyAssessmentAttempt(context.Background(), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
|
||||
if err != nil {
|
||||
t.Fatalf("guest CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := response.(*api.CreateMyAssessmentAttemptUnauthorized); !ok || operations.createCalls != 1 {
|
||||
t.Fatalf("guest create response = %T, operations called %d", response, operations.createCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartAndReadAssessmentAttemptUseVerifiedPrincipal(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
snapshot := assessmentPublicSnapshot()
|
||||
operations := &assessmentOperationsStub{
|
||||
read: snapshot,
|
||||
start: outbound.AssessmentAttemptSessionResult{Response: snapshot},
|
||||
}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
ctx := principalForTest(userID)
|
||||
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if operations.readUserID != userID || operations.readAttemptID != snapshot.ID {
|
||||
t.Fatalf("GetMyAttempt() IDs = %s/%s", operations.readUserID, operations.readAttemptID)
|
||||
}
|
||||
if _, ok := read.(*api.AssessmentAttemptHeaders); !ok {
|
||||
t.Fatalf("read response = %T, want attempt headers", read)
|
||||
}
|
||||
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{
|
||||
ExpectedVersion: api.AssessmentAttemptVersion(7),
|
||||
}, api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
|
||||
}
|
||||
if operations.startCommand.ActorID != userID || operations.startCommand.AttemptID != snapshot.ID ||
|
||||
operations.startCommand.ExpectedVersion != 7 || operations.startCommand.IdempotencyKey != "session-key" {
|
||||
t.Fatalf("StartSession() command = %+v", operations.startCommand)
|
||||
}
|
||||
if _, ok := started.(*api.AssessmentAttemptHeaders); !ok {
|
||||
t.Fatalf("start response = %T, want attempt headers", started)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptFailuresMapWithoutExposingInternalErrors(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{startErr: assessmentusecase.ErrAttemptVersionConflict}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
response, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
|
||||
&api.AssessmentAttemptSessionStart{ExpectedVersion: 3},
|
||||
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
|
||||
}
|
||||
problem, ok := response.(*api.StartMyAssessmentAttemptSessionPreconditionFailed)
|
||||
if !ok || api.Problem(*problem).Code != api.ProblemCodeVersionConflict {
|
||||
t.Fatalf("version conflict response = %T %+v", response, response)
|
||||
}
|
||||
|
||||
operations.readErr = assessmentusecase.ErrAttemptNotFound
|
||||
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: uuid.New()})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := read.(*api.GetMyAssessmentAttemptNotFound); !ok {
|
||||
t.Fatalf("missing attempt response = %T", read)
|
||||
}
|
||||
|
||||
operations.createErr = &assessmentusecase.AttemptFieldError{Pointer: "/task_language", Reason: "is not available"}
|
||||
create, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(
|
||||
api.AssessmentQualifiedAttemptCreate{Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior"},
|
||||
), api.CreateMyAssessmentAttemptParams{IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
badRequest, ok := create.(*api.CreateMyAssessmentAttemptBadRequest)
|
||||
if !ok || len(api.Problem(*badRequest).Errors) != 1 || api.Problem(*badRequest).Errors[0].Pointer != "/task_language" {
|
||||
t.Fatalf("validation response = %T %+v", create, create)
|
||||
}
|
||||
|
||||
operations.startErr = errors.New("private database detail")
|
||||
if _, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
|
||||
&api.AssessmentAttemptSessionStart{ExpectedVersion: 1},
|
||||
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"}); err == nil || err.Error() != "private database detail" {
|
||||
t.Fatalf("unexpected internal error mapping = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmedAttemptResultDoesNotInferStoredGradeFromTarget(t *testing.T) {
|
||||
result := assessmentusecase.AssessmentAttemptResult{
|
||||
Attempt: domain.AssessmentAttemptPublicSnapshot{
|
||||
Kind: domain.AssessmentAttemptKindRoot, TargetGrade: domainCodePointer(domain.GradeCode("junior")),
|
||||
},
|
||||
Outcome: domain.AssessmentAttemptOutcomeConfirmed,
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
t.Fatalf("assessmentRealResultFields() error = %v", err)
|
||||
}
|
||||
if !fields.confirmedGrade.IsNull() {
|
||||
t.Fatalf("confirmed grade = %+v, want null until a stored grade decision exists", fields.confirmedGrade)
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentOperationsStub struct {
|
||||
availabilityCalls int
|
||||
availabilityUserID uuid.UUID
|
||||
availability assessmentusecase.AssessmentAvailability
|
||||
availabilityErr error
|
||||
createCalls int
|
||||
createCommand assessmentusecase.CreateAttemptCommand
|
||||
create outbound.AssessmentAttemptCreateResult
|
||||
createErr error
|
||||
read domain.AssessmentAttemptPublicSnapshot
|
||||
readUserID uuid.UUID
|
||||
readAttemptID domain.AssessmentAttemptID
|
||||
readErr error
|
||||
startCommand assessmentusecase.StartAttemptSessionCommand
|
||||
start outbound.AssessmentAttemptSessionResult
|
||||
startErr error
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) GetMyAssessmentAvailability(
|
||||
_ context.Context,
|
||||
userID uuid.UUID,
|
||||
) (assessmentusecase.AssessmentAvailability, error) {
|
||||
stub.availabilityCalls++
|
||||
stub.availabilityUserID = userID
|
||||
return stub.availability, stub.availabilityErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) CreateAttempt(_ context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error) {
|
||||
stub.createCalls++
|
||||
stub.createCommand = command
|
||||
return stub.create, stub.createErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) GetMyAttempt(_ context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error) {
|
||||
stub.readUserID, stub.readAttemptID = userID, attemptID
|
||||
return stub.read, stub.readErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) StartSession(_ context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error) {
|
||||
stub.startCommand = command
|
||||
return stub.start, stub.startErr
|
||||
}
|
||||
|
||||
func principalForTest(userID uuid.UUID) context.Context {
|
||||
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
|
||||
}
|
||||
|
||||
func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
|
||||
started := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
return domain.AssessmentAttemptPublicSnapshot{
|
||||
ID: domain.AssessmentAttemptID(uuid.New()), Version: 7, Kind: domain.AssessmentAttemptKindRoot,
|
||||
Mode: domain.AssessmentAttemptModeDemoBasic, State: domain.AssessmentAttemptStateInProgress,
|
||||
Specialization: domainCodePointer(domain.SpecializationCode("backend")), TargetGrade: domainCodePointer(domain.GradeCode("junior")),
|
||||
PolicyVersion: 2, BankVersion: "bank-v1", AlgorithmVersion: "assessment.v1", StartedAt: started,
|
||||
ExpiresAt: started.Add(30 * time.Minute), MaxItems: 10, SessionsUsed: 1, MaxSessions: 2, IdleTimeout: 1800,
|
||||
CurrentItem: &domain.AssessmentAttemptPublicItem{ID: uuid.New(), Sequence: 1, Prompt: "Choose the number",
|
||||
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"}}, Practices: []domain.AssessmentAttemptPublicPractice{},
|
||||
}
|
||||
}
|
||||
|
||||
func domainCodePointer[T ~string](value T) *T {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
needusecase "lincodex/backend/internal/usecase/need"
|
||||
)
|
||||
|
||||
const (
|
||||
needCursorVersion = 1
|
||||
needCursorBytes = 61
|
||||
defaultNeedLimit = 20
|
||||
maxNeedCursorTime = uint64(253402300799)
|
||||
)
|
||||
|
||||
// NeedOperations are the owner-scoped need reads and commands served by HTTP.
|
||||
type NeedOperations interface {
|
||||
Create(ctx context.Context, command needusecase.CreateCommand) (domain.NeedResponseSnapshot, error)
|
||||
Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error)
|
||||
List(ctx context.Context, command needusecase.ListCommand) (outbound.NeedPage, error)
|
||||
Update(ctx context.Context, command needusecase.UpdateCommand) (domain.Need, error)
|
||||
}
|
||||
|
||||
// NeedHandler serves company need routes without trusting membership in a
|
||||
// request body or retaining tenant data between requests.
|
||||
type NeedHandler struct {
|
||||
operations NeedOperations
|
||||
}
|
||||
|
||||
func NewNeedHandler(operations NeedOperations) *NeedHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewNeedHandler - need operations must not be nil")
|
||||
}
|
||||
return &NeedHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) ListOrganizationNeeds(ctx context.Context, params api.ListOrganizationNeedsParams) (api.ListOrganizationNeedsRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.ListOrganizationNeeds(ctx, params)
|
||||
}
|
||||
return handler.need.ListOrganizationNeeds(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateOrganizationNeed(ctx context.Context, request *api.NeedCreate, params api.CreateOrganizationNeedParams) (api.CreateOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.CreateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
return handler.need.CreateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationNeed(ctx context.Context, params api.GetOrganizationNeedParams) (api.GetOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationNeed(ctx, params)
|
||||
}
|
||||
return handler.need.GetOrganizationNeed(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) UpdateOrganizationNeed(ctx context.Context, request *api.NeedUpdate, params api.UpdateOrganizationNeedParams) (api.UpdateOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.UpdateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
return handler.need.UpdateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) CreateOrganizationNeed(
|
||||
ctx context.Context,
|
||||
request *api.NeedCreate,
|
||||
params api.CreateOrganizationNeedParams,
|
||||
) (api.CreateOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
canonical, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NeedHandler.CreateOrganizationNeed - encode canonical request")
|
||||
}
|
||||
snapshot, err := handler.operations.Create(ctx, needusecase.CreateCommand{
|
||||
ActorID: principal.UserID, OrganizationID: params.OrgID, IdempotencyKey: params.IdempotencyKey,
|
||||
CanonicalBody: canonical, Input: createNeedInput(request),
|
||||
})
|
||||
if err != nil {
|
||||
return needCreateFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(snapshot)}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) GetOrganizationNeed(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationNeedParams,
|
||||
) (api.GetOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
need, err := handler.operations.Get(ctx, principal.UserID, params.OrgID, params.NeedID)
|
||||
if err != nil {
|
||||
return needReadFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) ListOrganizationNeeds(
|
||||
ctx context.Context,
|
||||
params api.ListOrganizationNeedsParams,
|
||||
) (api.ListOrganizationNeedsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListOrganizationNeedsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, pointer := needListCommand(principal.UserID, params)
|
||||
if pointer != "" {
|
||||
return needListInvalid(ctx, pointer), nil
|
||||
}
|
||||
page, err := handler.operations.List(ctx, command)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified):
|
||||
return (*api.ListOrganizationNeedsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.ListOrganizationNeedsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
items := make([]api.NeedSummary, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, needSummaryFromDomain(item))
|
||||
}
|
||||
next := api.NilString{}
|
||||
next.SetToNull()
|
||||
if page.HasMore && len(page.Items) > 0 {
|
||||
cursor, err := encodeNeedCursor(principal.UserID, params.OrgID, outbound.NeedCreationPosition(page.Items[len(page.Items)-1]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NeedHandler.ListOrganizationNeeds - encode cursor: %w", err)
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return &api.NeedListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.NeedList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) UpdateOrganizationNeed(
|
||||
ctx context.Context,
|
||||
request *api.NeedUpdate,
|
||||
params api.UpdateOrganizationNeedParams,
|
||||
) (api.UpdateOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.UpdateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.UpdateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
need, err := handler.operations.Update(ctx, needusecase.UpdateCommand{
|
||||
ActorID: principal.UserID, OrganizationID: params.OrgID, NeedID: params.NeedID, Input: updateNeedInput(request),
|
||||
})
|
||||
if err != nil {
|
||||
return needUpdateFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
|
||||
}
|
||||
|
||||
func needCreateFailure(ctx context.Context, err error) (api.CreateOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.CreateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.CreateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, needusecase.ErrIdempotencyKeyReused):
|
||||
return (*api.CreateOrganizationNeedUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidIdempotencyKey):
|
||||
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
|
||||
return (*api.CreateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needReadFailure(ctx context.Context, err error) (api.GetOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.GetOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
|
||||
return (*api.GetOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needUpdateFailure(ctx context.Context, err error) (api.UpdateOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.UpdateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
|
||||
return (*api.UpdateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, domain.ErrNeedVersionConflict), errors.Is(err, outbound.ErrNeedVersionConflict):
|
||||
return (*api.UpdateOrganizationNeedPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
|
||||
return (*api.UpdateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needValidationProblem(ctx context.Context, err error) *api.Problem {
|
||||
field, ok := errors.AsType[*needusecase.ValidationError](err)
|
||||
if !ok {
|
||||
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response
|
||||
}
|
||||
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response
|
||||
}
|
||||
|
||||
func needListInvalid(ctx context.Context, pointer string) *api.ListOrganizationNeedsBadRequest {
|
||||
return (*api.ListOrganizationNeedsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response)
|
||||
}
|
||||
|
||||
func needListCommand(actorID uuid.UUID, params api.ListOrganizationNeedsParams) (needusecase.ListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
limit = defaultNeedLimit
|
||||
}
|
||||
if limit < 1 || limit > outbound.MaxNeedPageSize {
|
||||
return needusecase.ListCommand{}, "limit"
|
||||
}
|
||||
command := needusecase.ListCommand{ActorID: actorID, OrganizationID: params.OrgID, Limit: limit}
|
||||
if cursor, ok := params.Cursor.Get(); ok {
|
||||
position, err := decodeNeedCursor(cursor, actorID, params.OrgID)
|
||||
if err != nil {
|
||||
return needusecase.ListCommand{}, "cursor"
|
||||
}
|
||||
command.After = &position
|
||||
}
|
||||
return command, ""
|
||||
}
|
||||
|
||||
func encodeNeedCursor(actorID, organizationID uuid.UUID, position outbound.NeedListPosition) (string, error) {
|
||||
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil || position.NeedID == uuid.Nil || position.CreatedAt.IsZero() ||
|
||||
position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxNeedCursorTime ||
|
||||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
|
||||
return "", errors.New("need cursor requires an actor, organization, and valid page position")
|
||||
}
|
||||
var value [needCursorBytes]byte
|
||||
value[0] = needCursorVersion
|
||||
copy(value[1:17], actorID[:])
|
||||
copy(value[17:33], organizationID[:])
|
||||
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
|
||||
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
|
||||
copy(value[45:61], position.NeedID[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodeNeedCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.NeedListPosition, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != needCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != needCursorVersion ||
|
||||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor is invalid")
|
||||
}
|
||||
seconds := binary.BigEndian.Uint64(value[33:41])
|
||||
nanos := binary.BigEndian.Uint32(value[41:45])
|
||||
needID := uuid.UUID(value[45:61])
|
||||
if seconds > uint64(math.MaxInt64) || seconds > maxNeedCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || needID == uuid.Nil {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor position is invalid")
|
||||
}
|
||||
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
|
||||
if createdAt.IsZero() {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor timestamp is invalid")
|
||||
}
|
||||
return outbound.NeedListPosition{CreatedAt: createdAt, NeedID: needID}, nil
|
||||
}
|
||||
|
||||
func createNeedInput(request *api.NeedCreate) needusecase.CreateInput {
|
||||
input := needusecase.CreateInput{Title: string(request.Title)}
|
||||
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
|
||||
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
|
||||
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
|
||||
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
|
||||
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
|
||||
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
|
||||
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
|
||||
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
|
||||
input.RequiredSkills = skillInputs(request.RequiredSkills)
|
||||
input.DesiredSkills = skillInputs(request.DesiredSkills)
|
||||
input.Tasks = taskInputs(request.Tasks)
|
||||
return input
|
||||
}
|
||||
|
||||
func updateNeedInput(request *api.NeedUpdate) needusecase.UpdateInput {
|
||||
input := needusecase.UpdateInput{ExpectedVersion: int64(request.ExpectedVersion)}
|
||||
if request.Title.Set {
|
||||
input.Title = needusecase.Field[string]{Set: true, Value: string(request.Title.Value)}
|
||||
}
|
||||
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
|
||||
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
|
||||
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
|
||||
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
|
||||
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
|
||||
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
|
||||
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
|
||||
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
|
||||
input.RequiredSkills = skillInputs(request.RequiredSkills)
|
||||
input.DesiredSkills = skillInputs(request.DesiredSkills)
|
||||
input.Tasks = taskInputs(request.Tasks)
|
||||
return input
|
||||
}
|
||||
|
||||
func uuidField(set, null bool, value uuid.UUID) needusecase.Field[uuid.UUID] {
|
||||
return needusecase.Field[uuid.UUID]{Set: set, Null: null, Value: value}
|
||||
}
|
||||
|
||||
func stringField(set, null bool, value string) needusecase.Field[string] {
|
||||
return needusecase.Field[string]{Set: set, Null: null, Value: value}
|
||||
}
|
||||
|
||||
func specializationInput(set, null bool, value api.NeedSpecializationInput) needusecase.Field[needusecase.Decision[domain.SpecializationCode]] {
|
||||
return needusecase.Field[needusecase.Decision[domain.SpecializationCode]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.SpecializationCode]{Value: domain.SpecializationCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func gradeInput(set, null bool, value api.NeedGradeInput) needusecase.Field[needusecase.Decision[domain.GradeCode]] {
|
||||
return needusecase.Field[needusecase.Decision[domain.GradeCode]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.GradeCode]{Value: domain.GradeCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func domainInput(set, null bool, value api.NeedDomainInput) needusecase.Field[needusecase.Decision[string]] {
|
||||
return needusecase.Field[needusecase.Decision[string]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func workFormatsInput(set, null bool, value api.NeedWorkFormatsInput) needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]] {
|
||||
formats := make([]domain.NeedWorkFormat, 0, len(value.Value))
|
||||
for _, format := range value.Value {
|
||||
formats = append(formats, domain.NeedWorkFormat(format))
|
||||
}
|
||||
return needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[[]domain.NeedWorkFormat]{Value: formats, Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func locationInput(set, null bool, value api.NeedLocationInput) needusecase.Field[needusecase.Decision[string]] {
|
||||
return needusecase.Field[needusecase.Decision[string]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func salaryInput(set, null bool, value api.NeedSalaryInput) needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]] {
|
||||
rangeValue := domain.NeedSalaryRange{
|
||||
SalaryFrom: int64(value.Value.SalaryFrom), SalaryTo: int64(value.Value.SalaryTo),
|
||||
Currency: string(value.Value.Currency), Period: string(value.Value.Period), TaxBasis: string(value.Value.TaxBasis),
|
||||
}
|
||||
return needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.NeedSalaryRange]{Value: rangeValue, Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func skillInputs(values []api.NeedSkillInput) []needusecase.SkillInput {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
result := make([]needusecase.SkillInput, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, needusecase.SkillInput{Name: string(value.Name), Status: domain.NeedItemStatus(value.Status)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func taskInputs(values []api.NeedTaskInput) []needusecase.TaskInput {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
result := make([]needusecase.TaskInput, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, needusecase.TaskInput{Text: string(value.Text), Status: domain.NeedItemStatus(value.Status)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needResponse(snapshot domain.NeedResponseSnapshot) api.Need {
|
||||
needSnapshot := snapshot.Need
|
||||
return api.Need{
|
||||
ID: needSnapshot.ID, OrganizationID: needSnapshot.OrganizationID,
|
||||
VacancyID: needNullableUUID(needSnapshot.VacancyID), Title: api.NeedTitle(needSnapshot.Title),
|
||||
SourceText: needNullableSourceText(needSnapshot.SourceText), Version: api.NeedVersion(needSnapshot.Version),
|
||||
RequirementsVersion: api.NeedVersion(needSnapshot.RequirementsVersion),
|
||||
Requirements: needRequirements(needSnapshot.Requirements), Readiness: needReadiness(snapshot.Readiness),
|
||||
Recommendations: needRecommendations(snapshot.Recommendations),
|
||||
CreatedAt: api.Timestamp(needSnapshot.CreatedAt), UpdatedAt: api.Timestamp(needSnapshot.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func needSummaryFromDomain(need domain.Need) api.NeedSummary {
|
||||
snapshot := need.Snapshot()
|
||||
return api.NeedSummary{
|
||||
ID: snapshot.ID, VacancyID: needNullableUUID(snapshot.VacancyID), Title: api.NeedTitle(snapshot.Title),
|
||||
Version: api.NeedVersion(snapshot.Version), Specialization: needSpecialization(snapshot.Requirements.Specialization),
|
||||
Grade: needGrade(snapshot.Requirements.Grade), Readiness: needReadiness(need.Readiness()),
|
||||
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func needRequirements(requirements domain.NeedRequirements) api.NeedRequirementSet {
|
||||
return api.NeedRequirementSet{
|
||||
Specialization: needSpecialization(requirements.Specialization), Grade: needGrade(requirements.Grade),
|
||||
RequiredSkills: needSkills(requirements.RequiredSkills), DesiredSkills: needSkills(requirements.DesiredSkills),
|
||||
Tasks: needTasks(requirements.Tasks), Domain: needDomain(requirements.Domain),
|
||||
WorkFormats: needWorkFormats(requirements.WorkFormats), Location: needLocation(requirements.Location),
|
||||
Salary: needSalary(requirements.Salary),
|
||||
}
|
||||
}
|
||||
|
||||
func needSpecialization(value domain.NeedValue[domain.SpecializationCode]) api.NeedSpecialization {
|
||||
result := api.NeedSpecialization{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.SpecializationCode(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needGrade(value domain.NeedValue[domain.GradeCode]) api.NeedGrade {
|
||||
result := api.NeedGrade{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.GradeCode(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needDomain(value domain.NeedValue[string]) api.NeedDomain {
|
||||
result := api.NeedDomain{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.NeedDomainName(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needLocation(value domain.NeedValue[string]) api.NeedLocation {
|
||||
result := api.NeedLocation{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.NeedLocationName(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needWorkFormats(value domain.NeedValue[[]domain.NeedWorkFormat]) api.NeedWorkFormats {
|
||||
result := api.NeedWorkFormats{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value = nil
|
||||
return result
|
||||
}
|
||||
result.Value = make([]api.WorkFormat, 0, len(*value.Value))
|
||||
for _, format := range *value.Value {
|
||||
result.Value = append(result.Value, api.WorkFormat(format))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needSalary(value domain.NeedValue[domain.NeedSalaryRange]) api.NeedSalary {
|
||||
result := api.NeedSalary{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
return result
|
||||
}
|
||||
rangeValue := api.SalaryRange{
|
||||
SalaryFrom: api.RubAmount(value.Value.SalaryFrom), SalaryTo: api.RubAmount(value.Value.SalaryTo),
|
||||
Currency: api.CurrencyCode(value.Value.Currency), Period: api.SalaryPeriod(value.Value.Period),
|
||||
TaxBasis: api.SalaryTaxBasis(value.Value.TaxBasis),
|
||||
}
|
||||
result.Value.SetTo(rangeValue)
|
||||
return result
|
||||
}
|
||||
|
||||
func needSkills(values []domain.NeedSkill) []api.NeedSkill {
|
||||
result := make([]api.NeedSkill, 0, len(values))
|
||||
for _, value := range values {
|
||||
item := api.NeedSkill{Name: api.SkillName(value.Name), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)}
|
||||
if value.TaxonomyCode == nil {
|
||||
item.TaxonomyCode.SetToNull()
|
||||
} else {
|
||||
item.TaxonomyCode.SetTo(api.SkillTaxonomyCode(*value.TaxonomyCode))
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needTasks(values []domain.NeedTask) []api.NeedTask {
|
||||
result := make([]api.NeedTask, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, api.NeedTask{Text: api.NeedTaskText(value.Text), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needReadiness(readiness domain.NeedReadinessReport) api.NeedReadinessReport {
|
||||
missing := make([]api.NeedMissingField, 0, len(readiness.MissingFields))
|
||||
for _, field := range readiness.MissingFields {
|
||||
missing = append(missing, api.NeedMissingField{
|
||||
Field: api.NeedFieldName(field.Field), Reason: api.NeedMissingReason(field.Reason), Question: field.Question,
|
||||
})
|
||||
}
|
||||
return api.NeedReadinessReport{Status: api.NeedReadinessStatus(readiness.Status), MissingFields: missing}
|
||||
}
|
||||
|
||||
func needRecommendations(recommendations domain.NeedCategoryRecommendations) api.NeedCategoryRecommendations {
|
||||
result := api.NeedCategoryRecommendations{
|
||||
Status: api.NeedRecommendationStatus(recommendations.Status),
|
||||
RequirementsVersion: api.NeedVersion(recommendations.RequirementsVersion),
|
||||
Categories: make([]api.NeedCategoryRecommendation, 0, len(recommendations.Categories)),
|
||||
}
|
||||
if recommendations.PolicyVersion == nil {
|
||||
result.PolicyVersion.SetToNull()
|
||||
} else {
|
||||
result.PolicyVersion.SetTo(*recommendations.PolicyVersion)
|
||||
}
|
||||
if recommendations.AlgorithmVersion == nil {
|
||||
result.AlgorithmVersion.SetToNull()
|
||||
} else {
|
||||
result.AlgorithmVersion.SetTo(api.NeedVersionLabel(*recommendations.AlgorithmVersion))
|
||||
}
|
||||
if recommendations.ComputedAt == nil {
|
||||
result.ComputedAt.SetToNull()
|
||||
} else {
|
||||
result.ComputedAt.SetTo(api.Timestamp(*recommendations.ComputedAt))
|
||||
}
|
||||
for _, category := range recommendations.Categories {
|
||||
result.Categories = append(result.Categories, needCategoryRecommendation(category))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needCategoryRecommendation(value domain.NeedCategoryRecommendation) api.NeedCategoryRecommendation {
|
||||
result := api.NeedCategoryRecommendation{
|
||||
Specialization: api.SpecializationCode(value.Specialization), Grade: api.GradeCode(value.Grade),
|
||||
SkillOverlap: api.NeedSkillOverlap{Share: value.SkillOverlap.Share},
|
||||
Money: api.NeedMoneyFit{Status: api.NeedMoneyStatus(value.Money.Status)}, Supply: api.NeedSupplyBand(value.Supply),
|
||||
}
|
||||
if value.Score == nil {
|
||||
result.Score.SetToNull()
|
||||
} else {
|
||||
result.Score.SetTo(*value.Score)
|
||||
}
|
||||
if value.Money.Share == nil {
|
||||
result.Money.Share.SetToNull()
|
||||
} else {
|
||||
result.Money.Share.SetTo(*value.Money.Share)
|
||||
}
|
||||
result.SkillOverlap.CoveredSkills = needSkillNames(value.SkillOverlap.CoveredSkills)
|
||||
result.SkillOverlap.UncoveredSkills = needSkillNames(value.SkillOverlap.UncoveredSkills)
|
||||
return result
|
||||
}
|
||||
|
||||
func needSkillNames(values []string) []api.SkillName {
|
||||
result := make([]api.SkillName, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, api.SkillName(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needValueSource(value domain.NeedValueSource) api.NeedValueSource {
|
||||
result := api.NeedValueSource{Origin: api.NeedValueOrigin(value.Origin)}
|
||||
setNeedSourceOptionals(&result, value)
|
||||
return result
|
||||
}
|
||||
|
||||
func needNullableSource(value *domain.NeedValueSource) api.NilNeedValueSource {
|
||||
var result api.NilNeedValueSource
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(needValueSource(*value))
|
||||
return result
|
||||
}
|
||||
|
||||
func setNeedSourceOptionals(result *api.NeedValueSource, value domain.NeedValueSource) {
|
||||
if value.Quote == nil {
|
||||
result.Quote.SetToNull()
|
||||
} else {
|
||||
result.Quote.SetTo(api.NeedSourceQuote(*value.Quote))
|
||||
}
|
||||
if value.ExtractedInVersion == nil {
|
||||
result.ExtractedInVersion.SetToNull()
|
||||
} else {
|
||||
result.ExtractedInVersion.SetTo(api.NeedVersion(*value.ExtractedInVersion))
|
||||
}
|
||||
if value.ExtractionVersion == nil {
|
||||
result.ExtractionVersion.SetToNull()
|
||||
} else {
|
||||
result.ExtractionVersion.SetTo(api.NeedVersionLabel(*value.ExtractionVersion))
|
||||
}
|
||||
}
|
||||
|
||||
func needNullableUUID(value *uuid.UUID) api.NilUUID {
|
||||
var result api.NilUUID
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
} else {
|
||||
result.SetTo(*value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needNullableSourceText(value *string) api.NilNeedSourceText {
|
||||
var result api.NilNeedSourceText
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
} else {
|
||||
result.SetTo(api.NeedSourceText(*value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestNeedCreateMappingPreservesAbsenceNullAndEmptyLists(t *testing.T) {
|
||||
request := &api.NeedCreate{Title: api.NeedTitle("Payments backend"), RequiredSkills: []api.NeedSkillInput{}}
|
||||
request.SourceText.SetTo(api.NeedSourceText("Requirements: Go"))
|
||||
request.VacancyID.SetToNull()
|
||||
|
||||
input := createNeedInput(request)
|
||||
if input.Title != "Payments backend" || !input.SourceText.Set || input.SourceText.Null || input.SourceText.Value != "Requirements: Go" {
|
||||
t.Fatalf("create mapping lost title or source text: %+v", input)
|
||||
}
|
||||
if !input.VacancyID.Set || !input.VacancyID.Null {
|
||||
t.Fatalf("explicit null vacancy mapped as %+v", input.VacancyID)
|
||||
}
|
||||
if input.Grade.Set || input.Specialization.Set || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
|
||||
t.Fatalf("create mapping did not distinguish absent fields from an empty list: %+v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedUpdateMappingPreservesFieldPresenceAndListReplacement(t *testing.T) {
|
||||
request := &api.NeedUpdate{ExpectedVersion: 4, RequiredSkills: []api.NeedSkillInput{}}
|
||||
request.Title.SetTo(api.NeedTitle("Platform backend"))
|
||||
request.SourceText.SetToNull()
|
||||
|
||||
input := updateNeedInput(request)
|
||||
if input.ExpectedVersion != 4 || !input.Title.Set || input.Title.Null || input.Title.Value != "Platform backend" {
|
||||
t.Fatalf("update mapping lost expected version or title: %+v", input)
|
||||
}
|
||||
if !input.SourceText.Set || !input.SourceText.Null || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
|
||||
t.Fatalf("update mapping did not preserve null and list replacement: %+v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedResponseDoesNotExposePrivateSuppressionState(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
need, err := domain.NewNeed(domain.NeedSnapshot{
|
||||
ID: uuid.Must(uuid.NewV7()), OrganizationID: uuid.Must(uuid.NewV7()), Title: "Payments backend",
|
||||
Version: 1, RequirementsVersion: 1, Requirements: domain.EmptyNeedRequirements(),
|
||||
RejectedSuggestions: []domain.NeedRejectedSuggestion{{Field: domain.NeedRejectedSkills, Value: "postgresql"}},
|
||||
CreatedAt: createdAt, UpdatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(needResponse(need.ResponseSnapshot()))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal public need: %v", err)
|
||||
}
|
||||
if strings.Contains(string(encoded), "rejected_suggestions") || strings.Contains(string(encoded), "postgresql") {
|
||||
t.Fatalf("public need exposed private suppression state: %s", encoded)
|
||||
}
|
||||
if !strings.Contains(string(encoded), `"recommendations":{"status":"not_available"`) {
|
||||
t.Fatalf("need response did not report the unavailable calculator honestly: %s", encoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedCursorIsBoundToActorAndOrganization(t *testing.T) {
|
||||
actorID := uuid.Must(uuid.NewV7())
|
||||
organizationID := uuid.Must(uuid.NewV7())
|
||||
position := outbound.NeedListPosition{
|
||||
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
|
||||
NeedID: uuid.Must(uuid.NewV7()),
|
||||
}
|
||||
cursor, err := encodeNeedCursor(actorID, organizationID, position)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeNeedCursor() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeNeedCursor(cursor, actorID, organizationID)
|
||||
if err != nil || decoded.NeedID != position.NeedID || !decoded.CreatedAt.Equal(position.CreatedAt) {
|
||||
t.Fatalf("decodeNeedCursor() = %+v, %v, want %+v", decoded, err, position)
|
||||
}
|
||||
if _, err := decodeNeedCursor(cursor, uuid.Must(uuid.NewV7()), organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a cursor from another actor")
|
||||
}
|
||||
if _, err := decodeNeedCursor(cursor, actorID, uuid.Must(uuid.NewV7())); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a cursor from another organization")
|
||||
}
|
||||
|
||||
encoded, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
encoded[33] = 0x80
|
||||
invalidTimestamp := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(invalidTimestamp, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted an out-of-range timestamp")
|
||||
}
|
||||
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
binary.BigEndian.PutUint64(encoded[33:41], maxNeedCursorTime+1)
|
||||
outsideDateTime := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(outsideDateTime, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a timestamp outside the contract date-time range")
|
||||
}
|
||||
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
binary.BigEndian.PutUint32(encoded[41:45], 123456001)
|
||||
subMicrosecond := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(subMicrosecond, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted precision that PostgreSQL cannot preserve")
|
||||
}
|
||||
if _, err := encodeNeedCursor(actorID, organizationID, outbound.NeedListPosition{
|
||||
CreatedAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), NeedID: position.NeedID,
|
||||
}); err == nil {
|
||||
t.Fatal("encodeNeedCursor() accepted a timestamp outside the contract date-time range")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
const (
|
||||
privacyCursorVersion = 1
|
||||
privacyCursorBytes = 46
|
||||
defaultPrivacyLimit = 20
|
||||
privacyCursorEvents = 1
|
||||
privacyCursorHidden = 2
|
||||
privacyCursorAccess = 3
|
||||
)
|
||||
|
||||
// CandidateViewOperations serves private previews, owner access history, and
|
||||
// organization-scoped anonymous card reads.
|
||||
type CandidateViewOperations interface {
|
||||
GetOrganizationCard(ctx context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error)
|
||||
GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (candidateview.PreviewResult, error)
|
||||
ListMyCardAccessHistory(ctx context.Context, query outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error)
|
||||
}
|
||||
|
||||
// CandidatePrivacyOperations serves candidate-owned publication and privacy
|
||||
// settings.
|
||||
type CandidatePrivacyOperations interface {
|
||||
GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error)
|
||||
SetMyPublication(ctx context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error)
|
||||
SetMySearchStatus(ctx context.Context, userID uuid.UUID, expectedVersion int64, value domain.SearchStatusValue) (domain.SearchStatus, time.Time, error)
|
||||
ListMyPrivacyHistory(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error)
|
||||
ListMyHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error)
|
||||
HideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error)
|
||||
UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error
|
||||
}
|
||||
|
||||
// PrivacyHandler binds the privacy read and settings use cases to the v1 API.
|
||||
type PrivacyHandler struct {
|
||||
views CandidateViewOperations
|
||||
settings CandidatePrivacyOperations
|
||||
publicOrigin string
|
||||
}
|
||||
|
||||
func NewPrivacyHandler(views CandidateViewOperations, settings CandidatePrivacyOperations, publicOrigin string) *PrivacyHandler {
|
||||
if views == nil || settings == nil {
|
||||
panic("v1.NewPrivacyHandler - view and settings operations must not be nil")
|
||||
}
|
||||
return &PrivacyHandler{views: views, settings: settings, publicOrigin: publicOrigin}
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetMyCardPreview(ctx)
|
||||
}
|
||||
return handler.privacy.GetMyCardPreview(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetMyPrivacySettings(ctx)
|
||||
}
|
||||
return handler.privacy.GetMyPrivacySettings(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationCandidateCard(ctx, params)
|
||||
}
|
||||
return handler.privacy.GetOrganizationCandidateCard(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.HideOrganization(ctx, params)
|
||||
}
|
||||
return handler.privacy.HideOrganization(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyCardAccessHistory(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyCardAccessHistory(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyHiddenOrganizations(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyHiddenOrganizations(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyPrivacyHistory(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyPrivacyHistory(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.SetMyPublication(ctx, request)
|
||||
}
|
||||
return handler.privacy.SetMyPublication(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.SetMySearchStatus(ctx, request)
|
||||
}
|
||||
return handler.privacy.SetMySearchStatus(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.UnhideOrganization(ctx, params)
|
||||
}
|
||||
return handler.privacy.UnhideOrganization(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyCardPreviewUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
preview, err := handler.views.GetMyCardPreview(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateview.ErrForbidden) {
|
||||
return (*api.GetMyCardPreviewForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.CardPreviewHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: cardPreviewResponse(preview)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyPrivacySettingsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
settings, err := handler.settings.GetMyPrivacySettings(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.GetMyPrivacySettingsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.PrivacySettingsHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: privacySettingsResponse(settings)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationCandidateCardUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
view, err := handler.views.GetOrganizationCard(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateview.ErrForbidden):
|
||||
return (*api.GetOrganizationCandidateCardForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.GetOrganizationCandidateCardNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
|
||||
return (*api.GetOrganizationCandidateCardBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
|
||||
}
|
||||
if limited, ok := candidateViewRateLimited(ctx, err); ok {
|
||||
return limited, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.AnonymousCardContentHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: anonymousCardResponse(view)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyCardAccessHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorAccess)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyCardAccessHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.CandidateCardAccessPosition
|
||||
if cursor != nil {
|
||||
position := outbound.CandidateCardAccessPosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.views.ListMyCardAccessHistory(ctx, outbound.CandidateCardAccessListQuery{CandidateID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateview.ErrForbidden) || errors.Is(err, candidateprivacy.ErrForbidden) {
|
||||
return (*api.ListMyCardAccessHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.CardAccess, 0, len(page.Items))
|
||||
for _, access := range page.Items {
|
||||
organization := api.NilPrivacyOrganization{}
|
||||
if name := page.OrganizationNames[access.OrganizationID()]; name != "" {
|
||||
organization.SetTo(api.PrivacyOrganization{ID: access.OrganizationID(), Name: name})
|
||||
} else {
|
||||
organization.SetToNull()
|
||||
}
|
||||
items = append(items, api.CardAccess{
|
||||
ID: access.ID(), Kind: api.CardAccessKind(access.Kind()), OccurredAt: api.Timestamp(access.OccurredAt()), Organization: organization,
|
||||
})
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorAccess, last.OccurredAt(), last.ID())
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyCardAccessHistory - encode cursor: %w", err)
|
||||
}
|
||||
return &api.CardAccessListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.CardAccessList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyHiddenOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorHidden)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyHiddenOrganizationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.HiddenOrganizationPosition
|
||||
if cursor != nil {
|
||||
position := outbound.HiddenOrganizationPosition{HiddenAt: cursor.at, OrganizationID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.ListMyHiddenOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.HiddenOrganization, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, hiddenOrganizationResponse(item))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorHidden, last.HiddenAt, last.OrganizationID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyHiddenOrganizations - encode cursor: %w", err)
|
||||
}
|
||||
return &api.HiddenOrganizationListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.HiddenOrganizationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyPrivacyHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvents)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyPrivacyHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.CandidatePrivacyEventPosition
|
||||
if cursor != nil {
|
||||
position := outbound.CandidatePrivacyEventPosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.settings.ListMyPrivacyHistory(ctx, outbound.CandidatePrivacyEventListQuery{UserID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.ListMyPrivacyHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.PrivacyEvent, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, privacyEventResponse(item))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorEvents, last.OccurredAt, last.ID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyPrivacyHistory - encode cursor: %w", err)
|
||||
}
|
||||
return &api.PrivacyEventListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.PrivacyEventList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SetMyPublicationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SetMyPublicationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
fields := make([]domain.CardField, 0, len(request.Fields))
|
||||
for _, field := range request.Fields {
|
||||
fields = append(fields, domain.CardField(field))
|
||||
}
|
||||
publication, err := handler.settings.SetMyPublication(ctx, principal.UserID, int64(request.ExpectedVersion), domain.PublicationState(request.State), fields)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, domain.ErrVisibilityVersionConflict):
|
||||
return (*api.SetMyPublicationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, domain.ErrPublicationConsentRequired):
|
||||
return (*api.SetMyPublicationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationBody, "/state", "consent_required")), nil
|
||||
case errors.Is(err, domain.ErrInvalidVisibility):
|
||||
return (*api.SetMyPublicationBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.PublicationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: publicationResponse(publication)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SetMySearchStatusUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SetMySearchStatusBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
status, asOf, err := handler.settings.SetMySearchStatus(ctx, principal.UserID, int64(request.ExpectedVersion), domain.SearchStatusValue(request.Value))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, domain.ErrVisibilityVersionConflict):
|
||||
return (*api.SetMySearchStatusPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, domain.ErrInvalidVisibility):
|
||||
return (*api.SetMySearchStatusBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.SearchStatusHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: searchStatusResponse(status, asOf)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.HideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
hidden, err := handler.settings.HideOrganization(ctx, principal.UserID, params.OrgID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrCandidatePrivacyOrganizationNotVisible), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.HideOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, outbound.ErrCandidateHiddenOrganizationLimit):
|
||||
return (*api.HideOrganizationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationPath, "/org_id", "limit_reached")), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.HiddenOrganizationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: hiddenOrganizationResponse(hidden)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.UnhideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if err := handler.settings.UnhideOrganization(ctx, principal.UserID, params.OrgID); err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.UnhideOrganizationNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
|
||||
}
|
||||
|
||||
type privacyCursor struct {
|
||||
at time.Time
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID, kind byte) (int32, *privacyCursor, string) {
|
||||
pageLimit, set := limit.Get()
|
||||
if !set {
|
||||
pageLimit = defaultPrivacyLimit
|
||||
}
|
||||
if pageLimit < 1 || pageLimit > outbound.MaxPrivacyPageSize {
|
||||
return 0, nil, "limit"
|
||||
}
|
||||
value, set := cursor.Get()
|
||||
if !set {
|
||||
return pageLimit, nil, ""
|
||||
}
|
||||
position, err := decodePrivacyCursor(value, owner, kind)
|
||||
if err != nil {
|
||||
return 0, nil, "cursor"
|
||||
}
|
||||
return pageLimit, &position, ""
|
||||
}
|
||||
|
||||
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
|
||||
at = at.UTC()
|
||||
seconds, nanos := at.Unix(), at.Nanosecond()
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorAccess || at.IsZero() ||
|
||||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
|
||||
return "", errors.New("privacy cursor requires an owner and valid page position")
|
||||
}
|
||||
var value [privacyCursorBytes]byte
|
||||
value[0], value[1] = privacyCursorVersion, kind
|
||||
copy(value[2:18], owner[:])
|
||||
writePrivacyCursorSeconds(value[18:26], seconds)
|
||||
binary.BigEndian.PutUint32(value[26:30], uint32(nanos))
|
||||
copy(value[30:46], id[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodePrivacyCursor(cursor string, owner uuid.UUID, kind byte) (privacyCursor, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != privacyCursorBytes || owner == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != privacyCursorVersion || value[1] != kind ||
|
||||
uuid.UUID(value[2:18]) != owner {
|
||||
return privacyCursor{}, errors.New("privacy cursor is invalid")
|
||||
}
|
||||
seconds := decodePrivacyCursorSeconds(value[18:26])
|
||||
nanos := binary.BigEndian.Uint32(value[26:30])
|
||||
id := uuid.UUID(value[30:46])
|
||||
if nanos >= 1_000_000_000 || nanos%1_000 != 0 || id == uuid.Nil {
|
||||
return privacyCursor{}, errors.New("privacy cursor position is invalid")
|
||||
}
|
||||
at := time.Unix(seconds, int64(nanos)).UTC()
|
||||
if at.IsZero() || at.Year() < 1 || at.Year() > 9999 {
|
||||
return privacyCursor{}, errors.New("privacy cursor timestamp is invalid")
|
||||
}
|
||||
return privacyCursor{at: at, id: id}, nil
|
||||
}
|
||||
|
||||
func writePrivacyCursorSeconds(encoded []byte, seconds int64) {
|
||||
encoded[0] = byte((seconds >> 56) & 0xff)
|
||||
encoded[1] = byte((seconds >> 48) & 0xff)
|
||||
encoded[2] = byte((seconds >> 40) & 0xff)
|
||||
encoded[3] = byte((seconds >> 32) & 0xff)
|
||||
encoded[4] = byte((seconds >> 24) & 0xff)
|
||||
encoded[5] = byte((seconds >> 16) & 0xff)
|
||||
encoded[6] = byte((seconds >> 8) & 0xff)
|
||||
encoded[7] = byte(seconds & 0xff)
|
||||
}
|
||||
|
||||
func decodePrivacyCursorSeconds(encoded []byte) int64 {
|
||||
high := int64(binary.BigEndian.Uint32(encoded[:4]))
|
||||
low := int64(binary.BigEndian.Uint32(encoded[4:]))
|
||||
return high<<32 | low
|
||||
}
|
||||
|
||||
func privacyNextCursor(hasMore bool, itemCount int, encode func() (string, error)) (api.NilString, error) {
|
||||
var next api.NilString
|
||||
next.SetToNull()
|
||||
if !hasMore {
|
||||
return next, nil
|
||||
}
|
||||
if itemCount == 0 {
|
||||
return api.NilString{}, errors.New("privacy page has_more without items")
|
||||
}
|
||||
if hasMore {
|
||||
cursor, err := encode()
|
||||
if err != nil {
|
||||
return api.NilString{}, err
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
|
||||
state := api.PublicationStateClosed
|
||||
if preview.Published {
|
||||
state = api.PublicationStatePublished
|
||||
}
|
||||
fields := make(api.CardFieldSet, 0, len(preview.Fields.Fields()))
|
||||
for _, field := range preview.Fields.Fields() {
|
||||
fields = append(fields, api.CardField(field))
|
||||
}
|
||||
card := api.NilAnonymousCardContent{}
|
||||
if preview.Card == nil {
|
||||
card.SetToNull()
|
||||
} else {
|
||||
card.SetTo(anonymousCardResponse(*preview.Card))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
}
|
||||
|
||||
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
|
||||
content := api.AnonymousCardContent{Pseudonym: view.Pseudonym}
|
||||
for _, category := range view.Categories {
|
||||
content.Categories = append(content.Categories, api.CardCategory{
|
||||
Specialization: api.SpecializationCode(category.Specialization), Grade: api.GradeCode(category.Grade),
|
||||
Strength: api.CardCategoryStrength(category.Strength),
|
||||
})
|
||||
}
|
||||
for _, skill := range view.Skills {
|
||||
content.Stack = append(content.Stack, api.AnonymousCardContentStackItem(skill))
|
||||
}
|
||||
for _, assessment := range view.SelfAssessment {
|
||||
grade := api.OptNilGradeCode{}
|
||||
if assessment.DeclaredGrade == nil {
|
||||
grade.SetToNull()
|
||||
} else {
|
||||
grade.SetTo(api.GradeCode(*assessment.DeclaredGrade))
|
||||
}
|
||||
content.SelfAssessment = append(content.SelfAssessment, api.CardSelfAssessment{
|
||||
Specialization: api.SpecializationCode(assessment.Specialization),
|
||||
ConfirmationStatus: api.CardSelfAssessmentConfirmationStatus(assessment.ConfirmationStatus),
|
||||
DeclaredGrade: grade,
|
||||
})
|
||||
}
|
||||
content.ExperienceBand.SetToNull()
|
||||
if view.ExperienceBand != nil {
|
||||
content.ExperienceBand.SetTo(api.CandidateExperienceBand(*view.ExperienceBand))
|
||||
}
|
||||
for _, format := range view.WorkFormats {
|
||||
content.WorkFormats = append(content.WorkFormats, api.CandidateWorkFormat(format))
|
||||
}
|
||||
content.SalaryCompatibility.SetToNull()
|
||||
if view.SalaryCompatibility != nil {
|
||||
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
func privacySettingsResponse(settings outbound.CandidatePrivacySettings) api.PrivacySettings {
|
||||
return api.PrivacySettings{
|
||||
Publication: publicationResponse(settings.Publication),
|
||||
SearchStatus: searchStatusResponse(settings.SearchStatus, settings.AsOf),
|
||||
HiddenOrganizationsTotal: int(settings.HiddenCount),
|
||||
}
|
||||
}
|
||||
|
||||
func publicationResponse(publication domain.Publication) api.Publication {
|
||||
response := api.Publication{State: api.PublicationState(publication.State()), Version: api.PublicationVersion(publication.Version())}
|
||||
response.ClosedReason.SetToNull()
|
||||
if reason := publication.ClosedReason(); reason != "" {
|
||||
response.ClosedReason.SetTo(api.PublicationClosedReason(reason))
|
||||
}
|
||||
response.ConsentID.SetToNull()
|
||||
if consentID := publication.ConsentRecordID(); consentID != uuid.Nil {
|
||||
response.ConsentID.SetTo(consentID)
|
||||
}
|
||||
response.PublishedAt.SetToNull()
|
||||
if publishedAt := publication.PublishedAt(); !publishedAt.IsZero() {
|
||||
response.PublishedAt.SetTo(api.Timestamp(publishedAt))
|
||||
}
|
||||
for _, field := range publication.Fields().Fields() {
|
||||
response.Fields = append(response.Fields, api.CardField(field))
|
||||
}
|
||||
if response.Fields == nil {
|
||||
response.Fields = api.CardFieldSet{}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func searchStatusResponse(status domain.SearchStatus, asOf time.Time) api.SearchStatus {
|
||||
response := api.SearchStatus{Value: api.SearchStatusValue(status.Effective(asOf)), Lapsed: status.Lapsed(asOf), Version: api.SearchStatusVersion(status.Version())}
|
||||
response.ConfirmedAt.SetToNull()
|
||||
if confirmedAt := status.ConfirmedAt(); !confirmedAt.IsZero() {
|
||||
response.ConfirmedAt.SetTo(api.Timestamp(confirmedAt))
|
||||
}
|
||||
response.LapsesAt.SetToNull()
|
||||
if lapsesAt := status.LapsesAt(); !lapsesAt.IsZero() {
|
||||
response.LapsesAt.SetTo(api.Timestamp(lapsesAt))
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func privacyEventResponse(event outbound.CandidatePrivacyEventRecord) api.PrivacyEvent {
|
||||
response := api.PrivacyEvent{ID: event.ID, Kind: api.PrivacyEventKind(event.Kind), OccurredAt: api.Timestamp(event.OccurredAt)}
|
||||
if event.Fields == nil {
|
||||
response.Fields = nil
|
||||
} else {
|
||||
response.Fields = make(api.CardFieldSet, 0, len(event.Fields.Fields()))
|
||||
for _, field := range event.Fields.Fields() {
|
||||
response.Fields = append(response.Fields, api.CardField(field))
|
||||
}
|
||||
}
|
||||
response.ConsentID.SetToNull()
|
||||
if event.ConsentRecordID != uuid.Nil {
|
||||
response.ConsentID.SetTo(event.ConsentRecordID)
|
||||
}
|
||||
response.Organization.SetToNull()
|
||||
if event.OrganizationID != uuid.Nil && event.OrganizationName != "" {
|
||||
response.Organization.SetTo(api.PrivacyOrganization{ID: event.OrganizationID, Name: event.OrganizationName})
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func hiddenOrganizationResponse(hidden outbound.HiddenOrganizationRecord) api.HiddenOrganization {
|
||||
return api.HiddenOrganization{
|
||||
Organization: api.PrivacyOrganization{ID: hidden.OrganizationID, Name: hidden.OrganizationName},
|
||||
HiddenAt: api.Timestamp(hidden.HiddenAt),
|
||||
}
|
||||
}
|
||||
|
||||
func privacyVisibilityInvalid(ctx context.Context, err error) *api.ProblemStatusCode {
|
||||
field, ok := errors.AsType[*domain.VisibilityFieldError](err)
|
||||
if !ok {
|
||||
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
|
||||
}
|
||||
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
|
||||
}
|
||||
|
||||
func privacyStateConflict(ctx context.Context, location api.ProblemFieldLocation, pointer, code string) *api.Problem {
|
||||
response := problem.New(ctx, api.ProblemCodeStateConflict).Response
|
||||
response.Errors = []api.ProblemFieldError{{
|
||||
In: location, Pointer: pointer, Code: code,
|
||||
Message: "The requested setting cannot be applied in the current state.",
|
||||
}}
|
||||
return &response
|
||||
}
|
||||
|
||||
func candidateViewRateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
|
||||
limited, ok := errors.AsType[*candidateview.RateLimitedError](err)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), true
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
func TestPrivacyGetOrganizationCandidateCardMapsClosedProjection(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
view := domain.AnonymousCandidateViewDTO{
|
||||
Pseudonym: "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Categories: []domain.CandidateViewCategory{{
|
||||
Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStrong,
|
||||
}},
|
||||
Skills: []domain.CandidateViewSkillCode{"go"},
|
||||
SelfAssessment: []domain.CandidateViewSelfAssessment{{
|
||||
Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed,
|
||||
}},
|
||||
}
|
||||
views := &privacyViewStub{card: view}
|
||||
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
|
||||
response, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
|
||||
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrganizationCandidateCard() error = %v", err)
|
||||
}
|
||||
body, ok := response.(*api.AnonymousCardContentHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("GetOrganizationCandidateCard() response = %T, want AnonymousCardContentHeaders", response)
|
||||
}
|
||||
if body.CacheControl != api.CacheControlNoStoreNoStore || body.Response.Pseudonym != view.Pseudonym ||
|
||||
len(body.Response.Categories) != 1 || body.Response.Categories[0].Strength != api.CardCategoryStrengthStrong ||
|
||||
len(body.Response.Stack) != 1 || body.Response.Stack[0] != "go" ||
|
||||
len(body.Response.SelfAssessment) != 1 || body.Response.SelfAssessment[0].ConfirmationStatus != api.CardSelfAssessmentConfirmationStatusUnconfirmed {
|
||||
t.Fatalf("anonymous content mapping = %+v", body)
|
||||
}
|
||||
if views.actorID != userID || views.organizationID != organizationID || views.handle != view.Pseudonym {
|
||||
t.Fatalf("read scope = actor %s organization %s handle %q", views.actorID, views.organizationID, views.handle)
|
||||
}
|
||||
if strings.Contains(view.String(), userID.String()) {
|
||||
t.Fatal("anonymous view string exposed the internal account ID")
|
||||
}
|
||||
|
||||
views.err = &candidateview.RateLimitedError{RetryAt: time.Now().Add(2 * time.Second)}
|
||||
limited, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
|
||||
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("rate-limited GetOrganizationCandidateCard() error = %v", err)
|
||||
}
|
||||
limitedBody, ok := limited.(*api.TooManyRequestsHeaders)
|
||||
if !ok || !limitedBody.RetryAfter.IsSet() || limitedBody.RetryAfter.Value < 1 {
|
||||
t.Fatalf("rate-limit response = %#v, want 429 and Retry-After", limited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyPublicationMapsConsentConflictAndVersionErrors(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
settings := &privacySettingsStub{publicationErr: domain.ErrPublicationConsentRequired}
|
||||
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(userID, "https://app.example.test")
|
||||
request := &api.PublicationUpdate{ExpectedVersion: 0, State: api.PublicationStatePublished, Fields: []api.CardField{api.CardFieldStack}}
|
||||
|
||||
response, err := handler.SetMyPublication(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("SetMyPublication() error = %v", err)
|
||||
}
|
||||
conflict, ok := response.(*api.SetMyPublicationConflict)
|
||||
if !ok || conflict.Code != api.ProblemCodeStateConflict || len(conflict.Errors) != 1 ||
|
||||
conflict.Errors[0].Pointer != "/state" || conflict.Errors[0].Code != "consent_required" {
|
||||
t.Fatalf("publication consent response = %#v, want a scoped consent_required conflict", response)
|
||||
}
|
||||
if settings.userID != userID || settings.publicationExpectedVersion != 0 || settings.publicationState != domain.PublicationPublished ||
|
||||
len(settings.publicationFields) != 1 || settings.publicationFields[0] != domain.CardFieldStack {
|
||||
t.Fatalf("publication command = actor %s version %d state %q fields %v", settings.userID, settings.publicationExpectedVersion, settings.publicationState, settings.publicationFields)
|
||||
}
|
||||
|
||||
settings.publicationErr = domain.ErrVisibilityVersionConflict
|
||||
response, err = handler.SetMyPublication(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("stale SetMyPublication() error = %v", err)
|
||||
}
|
||||
precondition, ok := response.(*api.SetMyPublicationPreconditionFailed)
|
||||
if !ok || precondition.Code != api.ProblemCodeVersionConflict {
|
||||
t.Fatalf("publication version response = %#v, want 412 version_conflict", response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyListsRejectForeignAndMalformedCursorsBeforeRead(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
views := &privacyViewStub{}
|
||||
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(ownerID, "")
|
||||
|
||||
encoded, err := encodePrivacyCursor(ownerID, privacyCursorAccess, time.Date(2026, 10, 7, 12, 0, 0, 123000, time.UTC), uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
if _, err := decodePrivacyCursor(encoded, uuid.New(), privacyCursorAccess); err == nil {
|
||||
t.Fatal("decodePrivacyCursor() accepted a cursor belonging to another owner")
|
||||
}
|
||||
if _, err := decodePrivacyCursor(encoded, ownerID, privacyCursorEvents); err == nil {
|
||||
t.Fatal("decodePrivacyCursor() accepted a cursor from another listing")
|
||||
}
|
||||
|
||||
response, err := handler.ListMyCardAccessHistory(ctx, api.ListMyCardAccessHistoryParams{Cursor: api.NewOptString("malformed")})
|
||||
if err != nil {
|
||||
t.Fatalf("invalid-cursor list error = %v", err)
|
||||
}
|
||||
badCursor, ok := response.(*api.ListMyCardAccessHistoryBadRequest)
|
||||
if !ok || badCursor.Code != api.ProblemCodeValidationFailed || views.accessCalls != 0 {
|
||||
t.Fatalf("invalid cursor response = %#v, read calls = %d", response, views.accessCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyCursorRoundTripsSignedTimestampBoundaries(t *testing.T) {
|
||||
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
|
||||
recordID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
|
||||
times := map[string]time.Time{
|
||||
"current positive time": time.Date(2026, 10, 7, 12, 34, 56, 123456000, time.UTC),
|
||||
"before unix epoch": time.Unix(-1, 123456000).UTC(),
|
||||
"end of year 9999": time.Date(9999, 12, 31, 23, 59, 59, 999999000, time.UTC),
|
||||
}
|
||||
for name, want := range times {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
cursor, err := encodePrivacyCursor(ownerID, privacyCursorAccess, want, recordID)
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
got, err := decodePrivacyCursor(cursor, ownerID, privacyCursorAccess)
|
||||
if err != nil {
|
||||
t.Fatalf("decodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
if !got.at.Equal(want) || got.id != recordID {
|
||||
t.Fatalf("decoded cursor = (%s, %s), want (%s, %s)", got.at, got.id, want, recordID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyCursorAcceptsExistingVersionOneToken(t *testing.T) {
|
||||
const legacyCursor = "AQMAESIzRFVmd4iZqrvM3e7___________8HW8oA_-7dzLuqmYh3ZlVEMyIRAA"
|
||||
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
|
||||
wantID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
|
||||
wantTime := time.Unix(-1, 123456000).UTC()
|
||||
|
||||
got, err := decodePrivacyCursor(legacyCursor, ownerID, privacyCursorAccess)
|
||||
if err != nil {
|
||||
t.Fatalf("decodePrivacyCursor(existing token) error = %v", err)
|
||||
}
|
||||
if !got.at.Equal(wantTime) || got.id != wantID {
|
||||
t.Fatalf("decoded legacy cursor = (%s, %s), want (%s, %s)", got.at, got.id, wantTime, wantID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyWriteRejectsOriginBeforeCallingSettings(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
settings := &privacySettingsStub{}
|
||||
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
|
||||
request := &api.SearchStatusUpdate{ExpectedVersion: 0, Value: api.SearchStatusValueLooking}
|
||||
|
||||
response, err := handler.SetMySearchStatus(privacyHTTPContext(userID, "https://attacker.example.test"), request)
|
||||
if err != nil {
|
||||
t.Fatalf("SetMySearchStatus() error = %v", err)
|
||||
}
|
||||
forbidden, ok := response.(*api.SetMySearchStatusForbidden)
|
||||
if !ok || forbidden.Code != api.ProblemCodeCsrfCheckFailed || settings.searchCalls != 0 {
|
||||
t.Fatalf("cross-origin response = %#v, search calls = %d", response, settings.searchCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyMappingKeepsNullAndEmptyPublicationFieldsDistinct(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
closed, err := domain.NewPublication(userID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPublication() error = %v", err)
|
||||
}
|
||||
response := publicationResponse(closed)
|
||||
if response.State != api.PublicationStateClosed || response.Version != 0 || response.ClosedReason.IsNull() ||
|
||||
response.ClosedReason.Value != api.PublicationClosedReasonNeverPublished || response.Fields == nil || len(response.Fields) != 0 ||
|
||||
!response.ConsentID.IsNull() || !response.PublishedAt.IsNull() {
|
||||
t.Fatalf("closed publication response = %+v", response)
|
||||
}
|
||||
|
||||
search, err := domain.NewSearchStatus(userID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSearchStatus() error = %v", err)
|
||||
}
|
||||
searchResponse := searchStatusResponse(search, time.Now())
|
||||
if searchResponse.Value != api.SearchStatusValueNotLooking || searchResponse.Lapsed || !searchResponse.ConfirmedAt.IsNull() || !searchResponse.LapsesAt.IsNull() {
|
||||
t.Fatalf("initial search status response = %+v", searchResponse)
|
||||
}
|
||||
}
|
||||
|
||||
func privacyHTTPContext(userID uuid.UUID, origin string) context.Context {
|
||||
request := httptest.NewRequest(http.MethodGet, "https://app.example.test/", nil)
|
||||
if origin != "" {
|
||||
request.Header.Set("Origin", origin)
|
||||
}
|
||||
capture := &privacyRequestContextCapture{}
|
||||
httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request)
|
||||
return context.WithValue(capture.context, principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
|
||||
}
|
||||
|
||||
type privacyRequestContextCapture struct{ context context.Context }
|
||||
|
||||
func (capture *privacyRequestContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
|
||||
// The middleware supplies the request context that carries origin metadata.
|
||||
capture.context = request.Context()
|
||||
}
|
||||
|
||||
type privacyViewStub struct {
|
||||
card domain.AnonymousCandidateViewDTO
|
||||
preview candidateview.PreviewResult
|
||||
access outbound.CandidateCardAccessListPage
|
||||
err error
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
handle string
|
||||
accessCalls int
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) GetOrganizationCard(_ context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error) {
|
||||
stub.actorID, stub.organizationID, stub.handle = actorID, organizationID, handle
|
||||
return stub.card, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) GetMyCardPreview(context.Context, uuid.UUID) (candidateview.PreviewResult, error) {
|
||||
return stub.preview, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) ListMyCardAccessHistory(context.Context, outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error) {
|
||||
stub.accessCalls++
|
||||
return stub.access, stub.err
|
||||
}
|
||||
|
||||
type privacySettingsStub struct {
|
||||
settings outbound.CandidatePrivacySettings
|
||||
publication domain.Publication
|
||||
publicationErr error
|
||||
userID uuid.UUID
|
||||
publicationExpectedVersion int64
|
||||
publicationState domain.PublicationState
|
||||
publicationFields []domain.CardField
|
||||
searchCalls int
|
||||
err error
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) GetMyPrivacySettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
return stub.settings, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) SetMyPublication(_ context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error) {
|
||||
stub.userID = userID
|
||||
stub.publicationExpectedVersion, stub.publicationState = expectedVersion, state
|
||||
stub.publicationFields = append([]domain.CardField(nil), fields...)
|
||||
return stub.publication, stub.publicationErr
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) SetMySearchStatus(context.Context, uuid.UUID, int64, domain.SearchStatusValue) (domain.SearchStatus, time.Time, error) {
|
||||
stub.searchCalls++
|
||||
return domain.SearchStatus{}, time.Time{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) ListMyPrivacyHistory(context.Context, outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
|
||||
return outbound.CandidatePrivacyEventPage{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) ListMyHiddenOrganizations(context.Context, outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
|
||||
return outbound.HiddenOrganizationPage{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) HideOrganization(context.Context, uuid.UUID, uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
|
||||
return outbound.HiddenOrganizationRecord{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) UnhideOrganization(context.Context, uuid.UUID, uuid.UUID) error {
|
||||
return stub.err
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
supportcase "lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
const (
|
||||
supportCaseCursorVersion = 1
|
||||
supportCaseCursorBytes = 45
|
||||
defaultSupportCaseLimit = 20
|
||||
maxSupportCaseCursorUnixSeconds = uint64(253_402_300_799)
|
||||
)
|
||||
|
||||
// SupportOperations serves owner-scoped support-case creation and reads.
|
||||
type SupportOperations interface {
|
||||
Create(ctx context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error)
|
||||
GetMyCase(ctx context.Context, ownerID uuid.UUID, id domain.SupportCaseID) (domain.SupportCase, error)
|
||||
ListMyCases(ctx context.Context, command supportcase.ListCommand) (outbound.SupportCaseListPage, error)
|
||||
}
|
||||
|
||||
// SupportHandler serves support-case operations without accepting an owner
|
||||
// identity from the request body or path.
|
||||
type SupportHandler struct {
|
||||
operations SupportOperations
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewSupportHandler(operations SupportOperations) *SupportHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewSupportHandler - support operations must not be nil")
|
||||
}
|
||||
return &SupportHandler{operations: operations, now: time.Now}
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateMySupportCase(
|
||||
ctx context.Context,
|
||||
request api.SupportCaseCreate,
|
||||
params api.CreateMySupportCaseParams,
|
||||
) (api.CreateMySupportCaseRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.CreateMySupportCase(ctx, request, params)
|
||||
}
|
||||
return handler.support.CreateMySupportCase(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMySupportCase(
|
||||
ctx context.Context,
|
||||
params api.GetMySupportCaseParams,
|
||||
) (api.GetMySupportCaseRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.GetMySupportCase(ctx, params)
|
||||
}
|
||||
return handler.support.GetMySupportCase(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMySupportCases(
|
||||
ctx context.Context,
|
||||
params api.ListMySupportCasesParams,
|
||||
) (api.ListMySupportCasesRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.ListMySupportCases(ctx, params)
|
||||
}
|
||||
return handler.support.ListMySupportCases(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) CreateMySupportCase(
|
||||
ctx context.Context,
|
||||
request api.SupportCaseCreate,
|
||||
params api.CreateMySupportCaseParams,
|
||||
) (api.CreateMySupportCaseRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
canonicalBody, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - encode canonical request")
|
||||
}
|
||||
command, valid := supportCaseCreateCommand(request)
|
||||
if !valid {
|
||||
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
command.ActorID = principal.UserID
|
||||
command.IdempotencyKey = params.IdempotencyKey
|
||||
command.CanonicalBody = canonicalBody
|
||||
result, err := handler.operations.Create(ctx, command)
|
||||
if err != nil {
|
||||
return supportCaseCreateFailure(ctx, err)
|
||||
}
|
||||
response, err := supportCaseResponse(result.Case, result.TargetLate)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - map case: %w", err)
|
||||
}
|
||||
return &api.SupportCaseHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) GetMySupportCase(
|
||||
ctx context.Context,
|
||||
params api.GetMySupportCaseParams,
|
||||
) (api.GetMySupportCaseRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
supportCase, err := handler.operations.GetMyCase(ctx, principal.UserID, domain.SupportCaseID(params.CaseID))
|
||||
if err != nil {
|
||||
return supportCaseReadFailure(ctx, err)
|
||||
}
|
||||
late := supportCase.ResponseTarget().IsLate(handler.now().UTC())
|
||||
response, err := supportCaseResponse(supportCase, late)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.GetMySupportCase - map case: %w", err)
|
||||
}
|
||||
return &api.SupportCaseHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) ListMySupportCases(
|
||||
ctx context.Context,
|
||||
params api.ListMySupportCasesParams,
|
||||
) (api.ListMySupportCasesRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, pointer := supportCaseListCommand(principal.UserID, params)
|
||||
if pointer != "" {
|
||||
return supportCaseListInvalid(ctx, pointer), nil
|
||||
}
|
||||
page, err := handler.operations.ListMyCases(ctx, command)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
|
||||
errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
items := make([]api.SupportCaseSummary, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
late := supportResponseTargetLate(item.ResponseTarget, handler.now().UTC())
|
||||
summary, err := supportCaseSummaryResponse(item, late)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - map summary: %w", err)
|
||||
}
|
||||
items = append(items, summary)
|
||||
}
|
||||
next := api.NilString{}
|
||||
next.SetToNull()
|
||||
if page.HasMore && len(page.Items) > 0 {
|
||||
cursor, err := encodeSupportCaseCursor(principal.UserID, outbound.SupportCasePositionOf(page.Items[len(page.Items)-1]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - encode cursor: %w", err)
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return &api.SupportCaseListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.SupportCaseList{
|
||||
Items: items,
|
||||
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func supportCaseCreateCommand(request api.SupportCaseCreate) (supportcase.CreateCommand, bool) {
|
||||
var command supportcase.CreateCommand
|
||||
switch request.Type {
|
||||
case api.SupportCaseCreateSupportSupportCaseCreate:
|
||||
value := request.SupportCaseCreateSupport
|
||||
command.Type = domain.SupportCaseTypeSupport
|
||||
command.Description = string(value.Description)
|
||||
if object, ok := value.Object.Get(); ok {
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
|
||||
}
|
||||
if target, ok := value.AssessmentTarget.Get(); ok {
|
||||
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
|
||||
Specialization: domain.SpecializationCode(target.Specialization), Grade: domain.GradeCode(target.Grade),
|
||||
}
|
||||
}
|
||||
case api.SupportCaseCreateComplaintSupportCaseCreate:
|
||||
value := request.SupportCaseCreateComplaint
|
||||
command.Type = domain.SupportCaseTypeComplaint
|
||||
command.Description = string(value.Description)
|
||||
command.ComplaintReason = supportComplaintReasonPointer(domain.SupportCaseComplaintReason(value.ComplaintReason))
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateGradeAppealSupportCaseCreate:
|
||||
value := request.SupportCaseCreateGradeAppeal
|
||||
command.Type = domain.SupportCaseTypeGradeAppeal
|
||||
command.Description = string(value.Description)
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateAnticheatAppealSupportCaseCreate:
|
||||
value := request.SupportCaseCreateAnticheatAppeal
|
||||
command.Type = domain.SupportCaseTypeAnticheatAppeal
|
||||
command.Description = string(value.Description)
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateManualAssessmentSupportCaseCreate:
|
||||
value := request.SupportCaseCreateManualAssessment
|
||||
command.Type = domain.SupportCaseTypeManualAssessment
|
||||
command.Description = string(value.Description)
|
||||
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
|
||||
Specialization: domain.SpecializationCode(value.AssessmentTarget.Specialization),
|
||||
Grade: domain.GradeCode(value.AssessmentTarget.Grade),
|
||||
}
|
||||
if object, ok := value.Object.Get(); ok {
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
|
||||
}
|
||||
default:
|
||||
return supportcase.CreateCommand{}, false
|
||||
}
|
||||
return command, true
|
||||
}
|
||||
|
||||
func supportCaseCreateFailure(ctx context.Context, err error) (api.CreateMySupportCaseRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified):
|
||||
return (*api.CreateMySupportCaseForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
case errors.Is(err, outbound.ErrSupportCaseNotFound):
|
||||
return (*api.CreateMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, supportcase.ErrStateConflict), errors.Is(err, outbound.ErrSupportCaseConflict):
|
||||
return (*api.CreateMySupportCaseConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, supportcase.ErrIdempotencyKeyReused):
|
||||
return (*api.CreateMySupportCaseUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, supportcase.ErrInvalidIdempotencyKey):
|
||||
return (*api.CreateMySupportCaseBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
|
||||
), nil
|
||||
case errors.Is(err, supportcase.ErrRateLimited):
|
||||
limited, ok := errors.AsType[*supportcase.RateLimitedError](err)
|
||||
if !ok || limited == nil {
|
||||
return nil, errors.New("SupportHandler.CreateMySupportCase - rate limit error has no retry interval")
|
||||
}
|
||||
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), nil
|
||||
case errors.Is(err, supportcase.ErrInvalidCreateRequest), errors.Is(err, domain.ErrInvalidSupportCase):
|
||||
fieldError, ok := errors.AsType[*domain.SupportCaseFieldError](err)
|
||||
if !ok {
|
||||
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
return (*api.CreateMySupportCaseBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response,
|
||||
), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseReadFailure(ctx context.Context, err error) (api.GetMySupportCaseRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
|
||||
errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
case errors.Is(err, outbound.ErrSupportCaseNotFound):
|
||||
return (*api.GetMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseListCommand(actorID uuid.UUID, params api.ListMySupportCasesParams) (supportcase.ListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
limit = defaultSupportCaseLimit
|
||||
}
|
||||
if limit < 1 || limit > outbound.MaxSupportCasePageSize {
|
||||
return supportcase.ListCommand{}, "limit"
|
||||
}
|
||||
command := supportcase.ListCommand{ActorID: actorID, Limit: limit}
|
||||
if cursor, ok := params.Cursor.Get(); ok {
|
||||
position, err := decodeSupportCaseCursor(cursor, actorID)
|
||||
if err != nil {
|
||||
return supportcase.ListCommand{}, "cursor"
|
||||
}
|
||||
command.After = &position
|
||||
}
|
||||
return command, ""
|
||||
}
|
||||
|
||||
func supportCaseListInvalid(ctx context.Context, pointer string) *api.ListMySupportCasesBadRequest {
|
||||
return (*api.ListMySupportCasesBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response,
|
||||
)
|
||||
}
|
||||
|
||||
func encodeSupportCaseCursor(actorID uuid.UUID, position outbound.SupportCaseListPosition) (string, error) {
|
||||
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
|
||||
if actorID == uuid.Nil || position.ID.IsZero() || !validSupportCaseCursorTime(position.CreatedAt) ||
|
||||
seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 {
|
||||
return "", errors.New("support case cursor requires an actor and a valid position")
|
||||
}
|
||||
var value [supportCaseCursorBytes]byte
|
||||
value[0] = supportCaseCursorVersion
|
||||
copy(value[1:17], actorID[:])
|
||||
binary.BigEndian.PutUint64(value[17:25], uint64(seconds))
|
||||
binary.BigEndian.PutUint32(value[25:29], uint32(nanos))
|
||||
caseID := position.ID.UUID()
|
||||
copy(value[29:45], caseID[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodeSupportCaseCursor(cursor string, actorID uuid.UUID) (outbound.SupportCaseListPosition, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != supportCaseCursorBytes || actorID == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != supportCaseCursorVersion ||
|
||||
uuid.UUID(value[1:17]) != actorID {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor is invalid")
|
||||
}
|
||||
nanos := binary.BigEndian.Uint32(value[25:29])
|
||||
caseID := uuid.UUID(value[29:45])
|
||||
seconds := binary.BigEndian.Uint64(value[17:25])
|
||||
if nanos >= 1_000_000_000 || caseID == uuid.Nil || seconds > maxSupportCaseCursorUnixSeconds {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor position is invalid")
|
||||
}
|
||||
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
|
||||
if !validSupportCaseCursorTime(createdAt) {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor timestamp is invalid")
|
||||
}
|
||||
return outbound.SupportCaseListPosition{CreatedAt: createdAt, ID: domain.SupportCaseID(caseID)}, nil
|
||||
}
|
||||
|
||||
func validSupportCaseCursorTime(value time.Time) bool {
|
||||
utc := value.UTC()
|
||||
return !value.IsZero() && utc.Year() >= 1 && utc.Year() <= 9999 && value.Unix() >= 0 &&
|
||||
value.Nanosecond()%int(time.Microsecond) == 0
|
||||
}
|
||||
|
||||
func supportCaseResponse(supportCase domain.SupportCase, targetLate bool) (api.SupportCase, error) {
|
||||
snapshot := supportCase.Snapshot()
|
||||
target, err := checkedSupportResponseTarget(snapshot.ResponseTarget, targetLate)
|
||||
if err != nil {
|
||||
return api.SupportCase{}, err
|
||||
}
|
||||
response := api.SupportCase{
|
||||
ID: snapshot.ID.UUID(), Number: api.SupportCaseNumber(snapshot.Number),
|
||||
Type: api.SupportCaseType(snapshot.Type), Status: api.SupportCaseStatus(snapshot.Status),
|
||||
Description: api.SupportCaseDescription(snapshot.Description),
|
||||
ResponseTarget: target,
|
||||
History: make([]api.SupportCaseEvent, 0, len(snapshot.History)),
|
||||
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
|
||||
}
|
||||
response.Object = supportCaseObject(snapshot.Object)
|
||||
response.AssessmentTarget = supportCaseAssessmentTarget(snapshot.AssessmentTarget)
|
||||
response.ComplaintReason = supportCaseComplaintReason(snapshot.ComplaintReason)
|
||||
response.RubricVersion = supportCaseInt32(snapshot.RubricVersion)
|
||||
response.Decision = supportCaseDecision(snapshot.Decision)
|
||||
for _, event := range snapshot.History {
|
||||
response.History = append(response.History, supportCaseEvent(event))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func supportCaseSummaryResponse(summary domain.SupportCaseSummary, targetLate bool) (api.SupportCaseSummary, error) {
|
||||
target, err := checkedSupportResponseTarget(summary.ResponseTarget, targetLate)
|
||||
if err != nil {
|
||||
return api.SupportCaseSummary{}, err
|
||||
}
|
||||
response := api.SupportCaseSummary{
|
||||
ID: summary.ID.UUID(), Number: api.SupportCaseNumber(summary.Number),
|
||||
Type: api.SupportCaseType(summary.Type), Status: api.SupportCaseStatus(summary.Status),
|
||||
Object: supportCaseObject(summary.Object), AssessmentTarget: supportCaseAssessmentTarget(summary.AssessmentTarget),
|
||||
ResponseTarget: target, CreatedAt: api.Timestamp(summary.CreatedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt),
|
||||
}
|
||||
if summary.DecisionOutcome == nil {
|
||||
response.DecisionOutcome.SetToNull()
|
||||
} else {
|
||||
response.DecisionOutcome.SetTo(api.SupportCaseDecisionOutcome(*summary.DecisionOutcome))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func checkedSupportResponseTarget(snapshot domain.SupportResponseTargetSnapshot, late bool) (api.SupportResponseTarget, error) {
|
||||
if _, err := domain.NewSupportResponseTarget(snapshot); err != nil {
|
||||
return api.SupportResponseTarget{}, err
|
||||
}
|
||||
response := api.SupportResponseTarget{
|
||||
Kind: api.SupportResponseTargetKindOperationalGoal,
|
||||
BusinessDays: int32(snapshot.BusinessDays), DueAt: api.Timestamp(snapshot.DueAt),
|
||||
Late: late, PolicyVersion: snapshot.PolicyVersion,
|
||||
}
|
||||
if snapshot.AnsweredAt == nil {
|
||||
response.AnsweredAt.SetToNull()
|
||||
} else {
|
||||
response.AnsweredAt.SetTo(api.Timestamp(*snapshot.AnsweredAt))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func supportResponseTargetLate(snapshot domain.SupportResponseTargetSnapshot, at time.Time) bool {
|
||||
target, err := domain.NewSupportResponseTarget(snapshot)
|
||||
return err == nil && target.IsLate(at)
|
||||
}
|
||||
|
||||
func supportCaseObject(reference *domain.SupportCaseReference) api.NilSupportCaseObjectReference {
|
||||
var result api.NilSupportCaseObjectReference
|
||||
if reference == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseObjectReference{Type: api.SupportCaseObjectType(reference.Type), ID: reference.ID})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseAssessmentTarget(target *domain.SupportCaseAssessmentTarget) api.NilSupportCaseAssessmentTarget {
|
||||
var result api.NilSupportCaseAssessmentTarget
|
||||
if target == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseAssessmentTarget{
|
||||
Specialization: api.SpecializationCode(target.Specialization), Grade: api.GradeCode(target.Grade),
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseComplaintReason(reason *domain.SupportCaseComplaintReason) api.NilSupportCaseComplaintReason {
|
||||
var result api.NilSupportCaseComplaintReason
|
||||
if reason == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseComplaintReason(*reason))
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseInt32(value *int32) api.NilInt32 {
|
||||
var result api.NilInt32
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(*value)
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseDecision(decision *domain.SupportCaseDecisionSnapshot) api.NilSupportCaseDecision {
|
||||
var result api.NilSupportCaseDecision
|
||||
if decision == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseDecision{
|
||||
Outcome: api.SupportCaseDecisionOutcome(decision.Outcome),
|
||||
Reason: api.SupportCasePublicText(decision.Reason), DecidedAt: api.Timestamp(decision.DecidedAt),
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseEvent(event domain.SupportCaseEventSnapshot) api.SupportCaseEvent {
|
||||
result := api.SupportCaseEvent{
|
||||
Sequence: event.Sequence, Kind: api.SupportCaseEventKind(event.Kind),
|
||||
Actor: api.SupportCaseActorKind(event.Actor), OccurredAt: api.Timestamp(event.OccurredAt),
|
||||
}
|
||||
if event.Status == nil {
|
||||
result.Status.SetToNull()
|
||||
} else {
|
||||
result.Status.SetTo(api.SupportCaseStatus(*event.Status))
|
||||
}
|
||||
if event.Message == nil {
|
||||
result.Message.SetToNull()
|
||||
} else {
|
||||
result.Message.SetTo(api.SupportCasePublicText(*event.Message))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func supportComplaintReasonPointer(value domain.SupportCaseComplaintReason) *domain.SupportCaseComplaintReason {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
supportcase "lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
func TestSupportCaseCreateCommandMapsManualRequestWithoutPriorAttempt(t *testing.T) {
|
||||
request := api.SupportCaseCreate{
|
||||
Type: api.SupportCaseCreateManualAssessmentSupportCaseCreate,
|
||||
SupportCaseCreateManualAssessment: api.SupportCaseCreateManualAssessment{
|
||||
Type: api.SupportCaseCreateManualAssessmentTypeManualAssessment,
|
||||
Description: api.SupportCaseDescription("Please assess my Go skills."),
|
||||
AssessmentTarget: api.SupportCaseAssessmentTarget{
|
||||
Specialization: api.SpecializationCodeBackend,
|
||||
Grade: api.GradeCodeJunior,
|
||||
},
|
||||
},
|
||||
}
|
||||
command, valid := supportCaseCreateCommand(request)
|
||||
if !valid || command.Type != domain.SupportCaseTypeManualAssessment || command.Description != "Please assess my Go skills." ||
|
||||
command.AssessmentTarget == nil || command.AssessmentTarget.Specialization != domain.SpecializationBackend ||
|
||||
command.AssessmentTarget.Grade != domain.GradeJunior || command.Object != nil {
|
||||
t.Fatalf("supportCaseCreateCommand() = %+v, %v; want a standalone manual-assessment request", command, valid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseCursorIsBoundToOwnerAndStoredPrecision(t *testing.T) {
|
||||
ownerID := uuid.Must(uuid.NewV7())
|
||||
position := outbound.SupportCaseListPosition{
|
||||
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
|
||||
ID: domain.SupportCaseID(uuid.Must(uuid.NewV7())),
|
||||
}
|
||||
cursor, err := encodeSupportCaseCursor(ownerID, position)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeSupportCaseCursor() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeSupportCaseCursor(cursor, ownerID)
|
||||
if err != nil || decoded.ID != position.ID || !decoded.CreatedAt.Equal(position.CreatedAt) {
|
||||
t.Fatalf("decodeSupportCaseCursor() = %+v, %v, want %+v", decoded, err, position)
|
||||
}
|
||||
if _, err := decodeSupportCaseCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
|
||||
t.Fatal("decodeSupportCaseCursor() accepted a cursor from another owner")
|
||||
}
|
||||
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{
|
||||
CreatedAt: position.CreatedAt.Add(time.Nanosecond), ID: position.ID,
|
||||
}); err == nil {
|
||||
t.Fatal("encodeSupportCaseCursor() accepted precision PostgreSQL cannot preserve")
|
||||
}
|
||||
for _, invalidTime := range []time.Time{
|
||||
time.Unix(-1, 0).UTC(),
|
||||
time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC),
|
||||
} {
|
||||
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{CreatedAt: invalidTime, ID: position.ID}); err == nil {
|
||||
t.Errorf("encodeSupportCaseCursor() accepted unsupported time %v", invalidTime)
|
||||
}
|
||||
}
|
||||
for name, mutate := range map[string]func([]byte){
|
||||
"out-of-range year": func(value []byte) {
|
||||
binary.BigEndian.PutUint64(value[17:25], uint64(time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()))
|
||||
},
|
||||
"sub-microsecond precision": func(value []byte) {
|
||||
binary.BigEndian.PutUint32(value[25:29], 1)
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeString() error = %v", err)
|
||||
}
|
||||
mutate(value)
|
||||
invalid := base64.RawURLEncoding.EncodeToString(value)
|
||||
if _, err := decodeSupportCaseCursor(invalid, ownerID); err == nil {
|
||||
t.Fatal("decodeSupportCaseCursor() accepted an unsupported position")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseRateLimitErrorPreservesRetryAfter(t *testing.T) {
|
||||
result, err := supportCaseCreateFailure(principalTestContext(), &supportcase.RateLimitedError{
|
||||
RetryAfter: 1500 * time.Millisecond,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("supportCaseCreateFailure() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.TooManyRequestsHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("supportCaseCreateFailure() result = %T, want *TooManyRequestsHeaders", result)
|
||||
}
|
||||
if seconds, present := response.RetryAfter.Get(); !present || seconds != 2 {
|
||||
t.Fatalf("Retry-After = %d, %v; want 2 seconds", seconds, present)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseReadAuthorizationFailuresUseDocumented401(t *testing.T) {
|
||||
for _, operation := range []string{"get", "list"} {
|
||||
for _, failure := range []error{supportcase.ErrForbidden, supportcase.ErrEmailNotVerified} {
|
||||
t.Run(operation+"/"+failure.Error(), func(t *testing.T) {
|
||||
operations := &supportOperationsStub{getError: failure, listError: failure}
|
||||
handler := NewSupportHandler(operations)
|
||||
if operation == "get" {
|
||||
result, err := handler.GetMySupportCase(principalTestContext(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMySupportCase() error = %v", err)
|
||||
}
|
||||
if _, ok := result.(*api.GetMySupportCaseUnauthorized); !ok {
|
||||
t.Fatalf("GetMySupportCase() result = %T, want documented 401", result)
|
||||
}
|
||||
return
|
||||
}
|
||||
result, err := handler.ListMySupportCases(principalTestContext(), api.ListMySupportCasesParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListMySupportCases() error = %v", err)
|
||||
}
|
||||
if _, ok := result.(*api.ListMySupportCasesUnauthorized); !ok {
|
||||
t.Fatalf("ListMySupportCases() result = %T, want documented 401", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseHandlerBindsCreateToPrincipalAndReturnsNoStore(t *testing.T) {
|
||||
ctx := principalTestContext()
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
t.Fatal("principalTestContext() did not set a principal")
|
||||
}
|
||||
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
responseTarget, err := domain.DemoSupportPolicy().ResponseTarget(domain.SupportCaseTypeSupport, 4, createdAt)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponseTarget() error = %v", err)
|
||||
}
|
||||
supportCase, err := domain.NewSupportCase(domain.NewSupportCaseInput{
|
||||
Number: "SC-2026-000123", OwnerID: principal.UserID, Type: domain.SupportCaseTypeSupport,
|
||||
Description: "Please help with my account.", ResponseTarget: responseTarget, CreatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCase() error = %v", err)
|
||||
}
|
||||
operations := &supportOperationsStub{createResult: supportcase.CreateResult{Case: supportCase}}
|
||||
handler := NewSupportHandler(operations)
|
||||
request := api.SupportCaseCreate{
|
||||
Type: api.SupportCaseCreateSupportSupportCaseCreate,
|
||||
SupportCaseCreateSupport: api.SupportCaseCreateSupport{
|
||||
Type: api.SupportCaseCreateSupportTypeSupport,
|
||||
Description: api.SupportCaseDescription("Please help with my account."),
|
||||
},
|
||||
}
|
||||
result, err := handler.CreateMySupportCase(ctx, request, api.CreateMySupportCaseParams{IdempotencyKey: "support-key-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMySupportCase() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.SupportCaseHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("CreateMySupportCase() result type = %T, want *SupportCaseHeaders", result)
|
||||
}
|
||||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.ID != supportCase.ID().UUID() ||
|
||||
response.Response.Type != api.SupportCaseTypeSupport || response.Response.Description != "Please help with my account." {
|
||||
t.Fatalf("CreateMySupportCase() response = %+v", response)
|
||||
}
|
||||
if operations.createCommand.ActorID != principal.UserID || operations.createCommand.IdempotencyKey != "support-key-1" ||
|
||||
operations.createCommand.Description != "Please help with my account." || len(operations.createCommand.CanonicalBody) == 0 {
|
||||
t.Fatalf("create command did not preserve authenticated scope and body: %+v", operations.createCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseHandlerRejectsMissingPrincipalBeforeCallingOperations(t *testing.T) {
|
||||
operations := &supportOperationsStub{}
|
||||
handler := NewSupportHandler(operations)
|
||||
_, err := handler.GetMySupportCase(context.Background(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMySupportCase() error = %v", err)
|
||||
}
|
||||
if operations.getCalls != 0 {
|
||||
t.Fatalf("operations.GetMyCase calls = %d, want none", operations.getCalls)
|
||||
}
|
||||
}
|
||||
|
||||
type supportOperationsStub struct {
|
||||
createCommand supportcase.CreateCommand
|
||||
createResult supportcase.CreateResult
|
||||
createError error
|
||||
getResult domain.SupportCase
|
||||
getError error
|
||||
getCalls int
|
||||
listPage outbound.SupportCaseListPage
|
||||
listError error
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) Create(_ context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error) {
|
||||
stub.createCommand = command
|
||||
return stub.createResult, stub.createError
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) GetMyCase(_ context.Context, _ uuid.UUID, _ domain.SupportCaseID) (domain.SupportCase, error) {
|
||||
stub.getCalls++
|
||||
return stub.getResult, stub.getError
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) ListMyCases(_ context.Context, _ supportcase.ListCommand) (outbound.SupportCaseListPage, error) {
|
||||
return stub.listPage, stub.listError
|
||||
}
|
||||
|
||||
var _ SupportOperations = (*supportOperationsStub)(nil)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func (repository assessmentAttemptRepository) GetAvailabilityActiveAttempt(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (outbound.AssessmentActiveAttemptSummary, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetAvailabilityActiveAttempt"
|
||||
if userID == uuid.Nil || !specialization.IsKnown() {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - candidate track is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentAvailabilityActiveAttempt(ctx, sqlc.GetAssessmentAvailabilityActiveAttemptParams{
|
||||
UserID: pgUUID(userID), Specialization: pgText(string(specialization)),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - read active attempt: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if !row.ID.Valid || row.ID.Bytes == uuid.Nil || !row.ExpiresAt.Valid {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - active attempt summary is invalid", location)
|
||||
}
|
||||
return outbound.AssessmentActiveAttemptSummary{
|
||||
ID: domain.AssessmentAttemptID(row.ID.Bytes), ExpiresAt: row.ExpiresAt.Time,
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) ListAvailabilityRootSummaries(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
since time.Time,
|
||||
) ([]outbound.AssessmentRootAvailabilitySummary, error) {
|
||||
const location = "assessmentAttemptRepository.ListAvailabilityRootSummaries"
|
||||
if userID == uuid.Nil || !specialization.IsKnown() || since.IsZero() {
|
||||
return nil, fmt.Errorf("%s - candidate track and horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentAvailabilityRootSummaries(ctx, sqlc.ListAssessmentAvailabilityRootSummariesParams{
|
||||
UserID: pgUUID(userID), Specialization: pgText(string(specialization)), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - read root summaries: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
summaries := make([]outbound.AssessmentRootAvailabilitySummary, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
summary, err := restoreAvailabilityRootSummary(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore root summary: %w", location, err)
|
||||
}
|
||||
summaries = append(summaries, summary)
|
||||
}
|
||||
return summaries, nil
|
||||
}
|
||||
|
||||
func restoreAvailabilityRootSummary(
|
||||
row sqlc.ListAssessmentAvailabilityRootSummariesRow,
|
||||
) (outbound.AssessmentRootAvailabilitySummary, error) {
|
||||
if !validAvailabilityRootSummary(row) {
|
||||
return outbound.AssessmentRootAvailabilitySummary{}, errors.New("stored assessment root summary is invalid")
|
||||
}
|
||||
rootGrade := domain.GradeCode(row.RootTargetGrade.String)
|
||||
latestGrade := domain.GradeCode(row.LatestTargetGrade.String)
|
||||
return outbound.AssessmentRootAvailabilitySummary{
|
||||
RootTargetGrade: rootGrade, RootCreatedAt: row.RootCreatedAt.Time,
|
||||
RootUpdatedAt: row.RootUpdatedAt.Time, RootExpiresAt: row.RootExpiresAt.Time,
|
||||
RootState: domain.AssessmentAttemptState(row.RootState), RootOutcome: domain.AssessmentAttemptOutcome(row.RootOutcome.String),
|
||||
RootChainDeadline: row.RootChainDeadline.Time, LatestTargetGrade: latestGrade,
|
||||
LatestUpdatedAt: row.LatestUpdatedAt.Time, LatestExpiresAt: row.LatestExpiresAt.Time,
|
||||
LatestState: domain.AssessmentAttemptState(row.LatestState), LatestOutcome: domain.AssessmentAttemptOutcome(row.LatestOutcome.String),
|
||||
LatestChainDeadline: row.LatestChainDeadline.Time, LatestPlatformError: row.LatestPlatformError,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validAvailabilityRootSummary(row sqlc.ListAssessmentAvailabilityRootSummariesRow) bool {
|
||||
rootGrade, latestGrade := domain.GradeCode(row.RootTargetGrade.String), domain.GradeCode(row.LatestTargetGrade.String)
|
||||
return row.RootTargetGrade.Valid && rootGrade.IsKnown() && row.LatestTargetGrade.Valid && latestGrade.IsKnown() &&
|
||||
row.RootCreatedAt.Valid && row.RootUpdatedAt.Valid && row.RootExpiresAt.Valid && row.RootChainDeadline.Valid &&
|
||||
row.LatestUpdatedAt.Valid && row.LatestExpiresAt.Valid && row.LatestChainDeadline.Valid &&
|
||||
validAvailabilityAttemptState(row.RootState) && validAvailabilityAttemptState(row.LatestState) &&
|
||||
validAvailabilityOutcome(row.RootOutcome) && validAvailabilityOutcome(row.LatestOutcome)
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) GetRootQuotaSnapshot(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
since, asOf time.Time,
|
||||
window time.Duration,
|
||||
maxAttempts int32,
|
||||
) (outbound.AssessmentRootQuotaSnapshot, error) {
|
||||
const location = "assessmentAttemptRepository.GetRootQuotaSnapshot"
|
||||
if userID == uuid.Nil || since.IsZero() || asOf.IsZero() || !asOf.After(since) || window <= 0 ||
|
||||
maxAttempts < 1 || window%time.Second != 0 {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - candidate and quota window are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
seconds := window.Seconds()
|
||||
if math.IsInf(seconds, 0) || math.IsNaN(seconds) {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - quota window exceeds supported precision: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentRootQuotaAvailability(ctx, sqlc.GetAssessmentRootQuotaAvailabilityParams{
|
||||
MaxAttempts: int64(maxAttempts), WindowSeconds: seconds, UserID: pgUUID(userID),
|
||||
Since: pgTime(since), AsOf: pgTime(asOf),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - read root quota: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if row.AttemptCount < 0 || row.AttemptCount > math.MaxInt32 {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - root quota count is outside the supported range", location)
|
||||
}
|
||||
snapshot := outbound.AssessmentRootQuotaSnapshot{Count: int32(row.AttemptCount)}
|
||||
if row.AvailableAt.Valid {
|
||||
availableAt := row.AvailableAt.Time
|
||||
snapshot.AvailableAt = &availableAt
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) ListDisclosedFamilyKeys(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
since time.Time,
|
||||
) ([]domain.AssessmentFamilyKey, error) {
|
||||
const location = "assessmentAttemptRepository.ListDisclosedFamilyKeys"
|
||||
if userID == uuid.Nil || since.IsZero() {
|
||||
return nil, fmt.Errorf("%s - candidate and disclosure horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentDisclosedFamilyKeys(ctx, sqlc.ListAssessmentDisclosedFamilyKeysParams{
|
||||
UserID: pgUUID(userID), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - read disclosed family keys: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
keys := make([]domain.AssessmentFamilyKey, 0, len(rows))
|
||||
for _, storedKey := range rows {
|
||||
key, err := domain.ParseAssessmentFamilyKey(storedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - stored family key is invalid: %w", location, err)
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func validAvailabilityAttemptState(state string) bool {
|
||||
switch domain.AssessmentAttemptState(state) {
|
||||
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
|
||||
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize,
|
||||
domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
|
||||
domain.AssessmentAttemptStateInsufficientBank:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validAvailabilityOutcome(outcome pgtype.Text) bool {
|
||||
if !outcome.Valid {
|
||||
return true
|
||||
}
|
||||
switch domain.AssessmentAttemptOutcome(outcome.String) {
|
||||
case domain.AssessmentAttemptOutcomeConfirmed, domain.AssessmentAttemptOutcomeNotConfirmed,
|
||||
domain.AssessmentAttemptOutcomeNotDetermined, domain.AssessmentAttemptOutcomeDemonstration:
|
||||
return domain.AssessmentAttemptOutcome(outcome.String) != domain.AssessmentAttemptOutcomeDemonstration
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
type assessmentAttemptResultDocument struct {
|
||||
SchemaVersion int32 `json:"schema_version"`
|
||||
Attempt assessmentAttemptPublicResultDocument `json:"attempt"`
|
||||
Pins assessmentAttemptResultPinsDocument `json:"pins"`
|
||||
Outcome domain.AssessmentAttemptOutcome `json:"outcome"`
|
||||
NotDeterminedReason string `json:"not_determined_reason,omitempty"`
|
||||
BasicScore *domain.AssessmentBasicScore `json:"basic_score,omitempty"`
|
||||
Rationale domain.AssessmentAttemptDecisionRationale `json:"rationale"`
|
||||
Limitations []string `json:"limitations"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
type assessmentAttemptPublicResultDocument struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Version int64 `json:"version"`
|
||||
Kind domain.AssessmentAttemptKind `json:"kind"`
|
||||
Mode domain.AssessmentAttemptMode `json:"mode"`
|
||||
State domain.AssessmentAttemptState `json:"state"`
|
||||
Specialization *domain.SpecializationCode `json:"specialization"`
|
||||
TargetGrade *domain.GradeCode `json:"target_grade"`
|
||||
TaskLanguage *domain.TaskLanguageCode `json:"task_language"`
|
||||
RootAttemptID *uuid.UUID `json:"root_attempt_id,omitempty"`
|
||||
ChainDeadline *time.Time `json:"chain_deadline,omitempty"`
|
||||
PolicyVersion int32 `json:"policy_version"`
|
||||
BankVersion string `json:"bank_version"`
|
||||
AlgorithmVersion string `json:"algorithm_version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
MaxItems int32 `json:"max_items"`
|
||||
AnsweredItems int32 `json:"answered_items"`
|
||||
SessionsUsed int32 `json:"sessions_used"`
|
||||
MaxSessions int32 `json:"max_sessions"`
|
||||
IdleTimeout int32 `json:"idle_timeout_seconds"`
|
||||
CurrentItem *domain.AssessmentAttemptPublicItem `json:"current_item"`
|
||||
Practices []domain.AssessmentAttemptPublicPractice `json:"practices"`
|
||||
}
|
||||
|
||||
type assessmentAttemptResultPinsDocument struct {
|
||||
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID *uuid.UUID `json:"grading_policy_version_id,omitempty"`
|
||||
OpeningID *uuid.UUID `json:"opening_id,omitempty"`
|
||||
OpeningManifestHash *string `json:"opening_manifest_sha256,omitempty"`
|
||||
TrainingBindingID *uuid.UUID `json:"training_binding_id,omitempty"`
|
||||
TrainingManifestHash *string `json:"training_manifest_sha256,omitempty"`
|
||||
BankVersion string `json:"bank_version"`
|
||||
AlgorithmVersion string `json:"algorithm_version"`
|
||||
}
|
||||
|
||||
func marshalAssessmentAttemptResultDocument(result domain.AssessmentAttemptResultSnapshot) ([]byte, error) {
|
||||
const location = "postgres.marshalAssessmentAttemptResultDocument"
|
||||
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
document := assessmentAttemptResultDocumentFromSnapshot(validated)
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil || len(encoded) > 65536 {
|
||||
return nil, fmt.Errorf("%s - encode bounded result: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func decodeAssessmentAttemptResultDocument(encoded []byte) (domain.AssessmentAttemptResultSnapshot, error) {
|
||||
const location = "postgres.decodeAssessmentAttemptResultDocument"
|
||||
if len(encoded) == 0 || len(encoded) > 65536 || !json.Valid(encoded) {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var document assessmentAttemptResultDocument
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - decode stored document: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document has trailing data: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
result, err := assessmentAttemptResultSnapshotFromDocument(document)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - restore version pins: %w", location, err)
|
||||
}
|
||||
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - validate stored result: %w", location, err)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func assessmentAttemptResultDocumentFromSnapshot(
|
||||
result domain.AssessmentAttemptResultSnapshot,
|
||||
) assessmentAttemptResultDocument {
|
||||
attempt := result.Attempt
|
||||
documentAttempt := assessmentAttemptPublicResultDocument{
|
||||
ID: attempt.ID.UUID(), Version: attempt.Version, Kind: attempt.Kind, Mode: attempt.Mode,
|
||||
State: attempt.State, Specialization: attempt.Specialization, TargetGrade: attempt.TargetGrade,
|
||||
TaskLanguage: attempt.TaskLanguage, ChainDeadline: attempt.ChainDeadline,
|
||||
PolicyVersion: attempt.PolicyVersion, BankVersion: attempt.BankVersion,
|
||||
AlgorithmVersion: attempt.AlgorithmVersion, StartedAt: attempt.StartedAt,
|
||||
ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
|
||||
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
|
||||
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
|
||||
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
|
||||
}
|
||||
if attempt.RootAttemptID != nil {
|
||||
rootID := attempt.RootAttemptID.UUID()
|
||||
documentAttempt.RootAttemptID = &rootID
|
||||
}
|
||||
pins := result.Pins
|
||||
gradingPolicyVersionID := optionalAssessmentPolicyVersionUUID(pins.GradingPolicyVersionID)
|
||||
openingID := optionalAssessmentUUID(pins.OpeningID)
|
||||
openingManifestHash := optionalAssessmentDigest(pins.OpeningManifestHash)
|
||||
trainingBindingID := optionalAssessmentUUID(pins.TrainingBindingID)
|
||||
trainingManifestHash := optionalAssessmentDigest(pins.TrainingManifestHash)
|
||||
return assessmentAttemptResultDocument{
|
||||
SchemaVersion: result.SchemaVersion, Attempt: documentAttempt,
|
||||
Pins: assessmentAttemptResultPinsDocument{
|
||||
ProductPolicyVersionID: uuid.UUID(pins.ProductPolicyVersionID), ProductPolicyVersion: pins.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: gradingPolicyVersionID, OpeningID: openingID,
|
||||
OpeningManifestHash: openingManifestHash, TrainingBindingID: trainingBindingID,
|
||||
TrainingManifestHash: trainingManifestHash, BankVersion: pins.BankVersion,
|
||||
AlgorithmVersion: pins.AlgorithmVersion,
|
||||
},
|
||||
Outcome: result.Outcome, NotDeterminedReason: result.NotDeterminedReason,
|
||||
BasicScore: result.BasicScore, Rationale: result.Rationale,
|
||||
Limitations: result.Limitations, Summary: result.Summary, DecidedAt: result.DecidedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAttemptResultSnapshotFromDocument(
|
||||
document assessmentAttemptResultDocument,
|
||||
) (domain.AssessmentAttemptResultSnapshot, error) {
|
||||
attempt := document.Attempt
|
||||
snapshotAttempt := domain.AssessmentAttemptPublicSnapshot{
|
||||
ID: domain.AssessmentAttemptID(attempt.ID), Version: attempt.Version, Kind: attempt.Kind,
|
||||
Mode: attempt.Mode, State: attempt.State, Specialization: attempt.Specialization,
|
||||
TargetGrade: attempt.TargetGrade, TaskLanguage: attempt.TaskLanguage,
|
||||
ChainDeadline: attempt.ChainDeadline, PolicyVersion: attempt.PolicyVersion,
|
||||
BankVersion: attempt.BankVersion, AlgorithmVersion: attempt.AlgorithmVersion,
|
||||
StartedAt: attempt.StartedAt, ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
|
||||
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
|
||||
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
|
||||
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
|
||||
}
|
||||
if attempt.RootAttemptID != nil {
|
||||
rootID := domain.AssessmentAttemptID(*attempt.RootAttemptID)
|
||||
snapshotAttempt.RootAttemptID = &rootID
|
||||
}
|
||||
pins := document.Pins
|
||||
openingManifestHash, err := restoreOptionalAssessmentDigest(pins.OpeningManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, err
|
||||
}
|
||||
trainingManifestHash, err := restoreOptionalAssessmentDigest(pins.TrainingManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, err
|
||||
}
|
||||
return domain.AssessmentAttemptResultSnapshot{
|
||||
SchemaVersion: document.SchemaVersion, Attempt: snapshotAttempt,
|
||||
Pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(pins.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: pins.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: assessmentPolicyVersionIDFromOptionalUUID(pins.GradingPolicyVersionID),
|
||||
OpeningID: assessmentUUIDFromOptional(pins.OpeningID), OpeningManifestHash: openingManifestHash,
|
||||
TrainingBindingID: assessmentUUIDFromOptional(pins.TrainingBindingID), TrainingManifestHash: trainingManifestHash,
|
||||
BankVersion: pins.BankVersion, AlgorithmVersion: pins.AlgorithmVersion,
|
||||
},
|
||||
Outcome: document.Outcome, NotDeterminedReason: document.NotDeterminedReason,
|
||||
BasicScore: document.BasicScore, Rationale: document.Rationale,
|
||||
Limitations: document.Limitations, Summary: document.Summary, DecidedAt: document.DecidedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func optionalAssessmentPolicyVersionUUID(value domain.PolicyVersionID) *uuid.UUID {
|
||||
if value == domain.PolicyVersionID(uuid.Nil) {
|
||||
return nil
|
||||
}
|
||||
id := uuid.UUID(value)
|
||||
return &id
|
||||
}
|
||||
|
||||
func optionalAssessmentUUID(value uuid.UUID) *uuid.UUID {
|
||||
if value == uuid.Nil {
|
||||
return nil
|
||||
}
|
||||
return &value
|
||||
}
|
||||
|
||||
func optionalAssessmentDigest(value [sha256.Size]byte) *string {
|
||||
if value == [sha256.Size]byte{} {
|
||||
return nil
|
||||
}
|
||||
digest := hex.EncodeToString(value[:])
|
||||
return &digest
|
||||
}
|
||||
|
||||
func assessmentPolicyVersionIDFromOptionalUUID(value *uuid.UUID) domain.PolicyVersionID {
|
||||
if value == nil {
|
||||
return domain.PolicyVersionID(uuid.Nil)
|
||||
}
|
||||
return domain.PolicyVersionID(*value)
|
||||
}
|
||||
|
||||
func assessmentUUIDFromOptional(value *uuid.UUID) uuid.UUID {
|
||||
if value == nil {
|
||||
return uuid.Nil
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
||||
func restoreOptionalAssessmentDigest(value *string) ([sha256.Size]byte, error) {
|
||||
if value == nil {
|
||||
return [sha256.Size]byte{}, nil
|
||||
}
|
||||
digest, err := hex.DecodeString(*value)
|
||||
if err != nil || len(digest) != sha256.Size || hex.EncodeToString(digest) != *value {
|
||||
return [sha256.Size]byte{}, domain.ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var restored [sha256.Size]byte
|
||||
copy(restored[:], digest)
|
||||
return restored, nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestAssessmentAttemptResultDocumentUsesNullableUUIDPins(t *testing.T) {
|
||||
attemptID := uuid.New()
|
||||
productPolicyID := uuid.New()
|
||||
gradingPolicyID := uuid.New()
|
||||
openingID := uuid.New()
|
||||
trainingBindingID := uuid.New()
|
||||
openingHash := [32]byte{1, 2, 3}
|
||||
trainingHash := [32]byte{4, 5, 6}
|
||||
tests := []struct {
|
||||
name string
|
||||
pins domain.AssessmentAttemptResultPins
|
||||
presentPinFields []string
|
||||
absentPinFields []string
|
||||
}{
|
||||
{
|
||||
name: "real assessment",
|
||||
pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
|
||||
GradingPolicyVersionID: domain.PolicyVersionID(gradingPolicyID), OpeningID: openingID,
|
||||
OpeningManifestHash: openingHash, BankVersion: "bank.v1", AlgorithmVersion: "demo_basic.v1",
|
||||
},
|
||||
presentPinFields: []string{productPolicyID.String(), gradingPolicyID.String(), openingID.String(), hex.EncodeToString(openingHash[:])},
|
||||
absentPinFields: []string{trainingBindingID.String(), "00000000-0000-0000-0000-000000000000"},
|
||||
},
|
||||
{
|
||||
name: "express training",
|
||||
pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
|
||||
TrainingBindingID: trainingBindingID, TrainingManifestHash: trainingHash,
|
||||
BankVersion: "bank.v1", AlgorithmVersion: "demo_express.v1",
|
||||
},
|
||||
presentPinFields: []string{productPolicyID.String(), trainingBindingID.String(), hex.EncodeToString(trainingHash[:])},
|
||||
absentPinFields: []string{gradingPolicyID.String(), openingID.String(), "00000000-0000-0000-0000-000000000000"},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
document := assessmentAttemptResultDocumentFromSnapshot(domain.AssessmentAttemptResultSnapshot{
|
||||
Attempt: domain.AssessmentAttemptPublicSnapshot{ID: domain.AssessmentAttemptID(attemptID)},
|
||||
Pins: test.pins,
|
||||
})
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal result document: %v", err)
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
||||
t.Fatalf("decode result document: %v", err)
|
||||
}
|
||||
pins, ok := decoded["pins"].(map[string]any)
|
||||
if !ok || pins["product_policy_version_id"] != productPolicyID.String() {
|
||||
t.Fatalf("result pins = %#v, want UUID string for product policy", decoded["pins"])
|
||||
}
|
||||
for _, value := range test.presentPinFields {
|
||||
if !strings.Contains(string(encoded), `"`+value+`"`) {
|
||||
t.Errorf("encoded result does not contain string pin %q: %s", value, encoded)
|
||||
}
|
||||
}
|
||||
for _, value := range test.absentPinFields {
|
||||
if strings.Contains(string(encoded), value) {
|
||||
t.Errorf("encoded result contains unrelated or zero pin %q: %s", value, encoded)
|
||||
}
|
||||
}
|
||||
restored, err := assessmentAttemptResultSnapshotFromDocument(document)
|
||||
if err != nil || restored.Pins != test.pins {
|
||||
t.Fatalf("restore result pins = %+v, error %v, want %+v", restored.Pins, err, test.pins)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreAssessmentAttemptResultDocumentRejectsNoncanonicalPinHash(t *testing.T) {
|
||||
productPolicyID := uuid.New()
|
||||
openingID := uuid.New()
|
||||
wrongHash := "01"
|
||||
document := assessmentAttemptResultDocument{
|
||||
Pins: assessmentAttemptResultPinsDocument{
|
||||
ProductPolicyVersionID: productPolicyID,
|
||||
OpeningID: &openingID,
|
||||
OpeningManifestHash: &wrongHash,
|
||||
},
|
||||
}
|
||||
if _, err := assessmentAttemptResultSnapshotFromDocument(document); err == nil {
|
||||
t.Fatal("assessmentAttemptResultSnapshotFromDocument() accepted an invalid pin hash")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func (repository assessmentBankRepository) ListCurrentAssessmentAvailabilitySelections(
|
||||
ctx context.Context,
|
||||
asOf time.Time,
|
||||
) ([]outbound.AssessmentAvailabilitySelection, error) {
|
||||
const location = "assessmentBankRepository.ListCurrentAssessmentAvailabilitySelections"
|
||||
if asOf.IsZero() {
|
||||
return nil, fmt.Errorf("%s - database time is required: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
rows, err := repository.queries.ListCurrentAssessmentAvailabilitySelections(ctx, pgTime(asOf))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
selections := make([]outbound.AssessmentAvailabilitySelection, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
metadataRow := sqlc.ListCurrentSpecializationAvailabilityRow{
|
||||
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
|
||||
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
|
||||
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
|
||||
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
|
||||
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
|
||||
}
|
||||
metadata, current, err := currentAssessmentCatalogMetadata(metadataRow)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate reviewed binding: %w", location, err)
|
||||
}
|
||||
if !current {
|
||||
continue
|
||||
}
|
||||
if !row.OpeningID.Valid || row.OpeningID.Bytes == [16]byte{} ||
|
||||
!row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
|
||||
return nil, fmt.Errorf("%s - current binding identity is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
manifest, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - decode verified family manifest: %w", location, err)
|
||||
}
|
||||
familyKeys := make([]domain.AssessmentFamilyKey, 0, len(manifest))
|
||||
for _, entry := range manifest {
|
||||
familyKeys = append(familyKeys, entry.FamilyKey)
|
||||
}
|
||||
selections = append(selections, outbound.AssessmentAvailabilitySelection{
|
||||
OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
|
||||
ProductPolicyVersion: row.EffectivePolicyVersion.Int32,
|
||||
Specialization: metadata.Specialization(), Grade: metadata.Grade(),
|
||||
TaskLanguages: metadata.TaskLanguages(), FamilyKeys: familyKeys,
|
||||
})
|
||||
}
|
||||
return selections, nil
|
||||
}
|
||||
@@ -43,6 +43,19 @@ func TestMapAssessmentErrorRecognizesBankConstraints(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedFamilyLookupMapsOnlyMissingFamiliesToUnavailable(t *testing.T) {
|
||||
missing := mapPinnedFamilyLookupError(errors.Join(errors.New("select pinned family"), outbound.ErrAssessmentFamilyNotFound))
|
||||
if !errors.Is(missing, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
t.Fatalf("map missing pinned family error = %v, want ErrAssessmentSelectionUnavailable", missing)
|
||||
}
|
||||
|
||||
transient := errors.New("database connection reset")
|
||||
got := mapPinnedFamilyLookupError(transient)
|
||||
if !errors.Is(got, transient) || errors.Is(got, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
t.Fatalf("map transient pinned family error = %v, want original infrastructure error", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockCategoryWorksOnlyInsideATransaction(t *testing.T) {
|
||||
// A repository without queries proves that no statement runs.
|
||||
standalone := assessmentBankRepository{transactional: false}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
@@ -94,6 +95,419 @@ func (repository assessmentBankRepository) ListCurrentSpecializationAvailability
|
||||
return buildAssessmentCatalogAvailability(aggregates), nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ResolveCurrentSelection(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
) (outbound.AssessmentBankSelection, error) {
|
||||
const location = "assessmentBankRepository.ResolveCurrentSelection"
|
||||
if !repository.transactional {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - current selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
initial, err := repository.currentSelectionRows(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - read candidate selection: %w", location, err)
|
||||
}
|
||||
if len(initial) == 0 {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - no current reviewed selection: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
if len(initial) > 1 {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - multiple current reviewed selections: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
|
||||
}
|
||||
category := domain.AssessmentCategory(initial[0].Category)
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - lock selected category: %w", location, err)
|
||||
}
|
||||
current, err := repository.currentSelectionRows(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - recheck candidate selection: %w", location, err)
|
||||
}
|
||||
if len(current) == 0 || len(current) > 1 || current[0].Category != string(category) ||
|
||||
current[0].OpeningID.Bytes != initial[0].OpeningID.Bytes {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - selection changed while locking: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
return repository.currentSelectionFromRow(ctx, current[0])
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentSelectionRows(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
) ([]sqlc.ResolveCurrentAssessmentSelectionRow, error) {
|
||||
var selectedLanguage pgtype.Text
|
||||
if language != nil {
|
||||
selectedLanguage = pgText(string(*language))
|
||||
}
|
||||
rows, err := repository.queries.ResolveCurrentAssessmentSelection(ctx, sqlc.ResolveCurrentAssessmentSelectionParams{
|
||||
Specialization: string(specialization), Grade: string(grade), TaskLanguage: selectedLanguage,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapAssessmentError(err)
|
||||
}
|
||||
current := make([]sqlc.ResolveCurrentAssessmentSelectionRow, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
metadata, available, err := currentAssessmentSelectionMetadata(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("validate current catalog binding: %w", err)
|
||||
}
|
||||
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade ||
|
||||
!assessmentCatalogLanguageMatches(metadata.TaskLanguages(), language) {
|
||||
continue
|
||||
}
|
||||
current = append(current, row)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func currentAssessmentSelectionMetadata(
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
|
||||
return currentAssessmentCatalogMetadata(sqlc.ListCurrentSpecializationAvailabilityRow{
|
||||
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
|
||||
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
|
||||
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
|
||||
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
|
||||
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
|
||||
})
|
||||
}
|
||||
|
||||
func assessmentCatalogLanguageMatches(
|
||||
available []domain.TaskLanguageCode,
|
||||
requested *domain.TaskLanguageCode,
|
||||
) bool {
|
||||
if requested == nil {
|
||||
return len(available) == 0
|
||||
}
|
||||
return slices.Contains(available, *requested)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentSelectionFromRow(
|
||||
ctx context.Context,
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (outbound.AssessmentBankSelection, error) {
|
||||
const location = "assessmentBankRepository.currentSelectionFromRow"
|
||||
if !row.EffectivePolicyID.Valid || !row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
|
||||
return outbound.AssessmentBankSelection{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
opening, err := repository.selectionOpening(ctx, row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current opening: %w", location, err)
|
||||
}
|
||||
entries, manifestSHA, err := currentSelectionManifest(row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
|
||||
}
|
||||
families, err := repository.resolveCurrentSelectionFamilies(ctx, opening.Category, entries)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
|
||||
}
|
||||
return outbound.AssessmentBankSelection{
|
||||
Opening: opening, ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
|
||||
ProductPolicyVersion: row.EffectivePolicyVersion.Int32, ManifestSHA: manifestSHA, Families: families,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) selectionOpening(
|
||||
ctx context.Context,
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (domain.AssessmentCategoryOpening, error) {
|
||||
opening, err := repository.GetCurrentCategoryOpening(ctx, domain.AssessmentCategory(row.Category))
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, err
|
||||
}
|
||||
if opening.ID != row.OpeningID.Bytes || opening.PolicyVersionID != domain.PolicyVersionID(row.PolicyVersionID.Bytes) ||
|
||||
opening.RequiredFamilies != row.RequiredFamilies || row.PublishedCount < row.RequiredFamilies {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
func currentSelectionManifest(
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
|
||||
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
|
||||
if err != nil {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil || len(entries) != int(row.PublishedCount) || !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return entries, fingerprint, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveCurrentSelectionFamilies(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entries []domain.AssessmentCategoryManifestEntry,
|
||||
) ([]domain.AssessmentFamily, error) {
|
||||
families := make([]domain.AssessmentFamily, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
|
||||
if err != nil {
|
||||
return nil, mapPinnedFamilyLookupError(err)
|
||||
}
|
||||
hash := family.ContentHash()
|
||||
if family.Category() != category || family.Lifecycle() != domain.AssessmentLifecyclePublished ||
|
||||
family.ReviewStatus() != domain.AssessmentReviewApproved || !slices.Equal(hash[:], entry.ContentSHA256) {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
families = append(families, family)
|
||||
}
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func mapPinnedFamilyLookupError(err error) error {
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ResolveCurrentTrainingSelection(
|
||||
ctx context.Context,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) (outbound.AssessmentTrainingBankSelection, error) {
|
||||
const location = "assessmentBankRepository.ResolveCurrentTrainingSelection"
|
||||
if !repository.transactional {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - training selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
initial, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
locked, err := repository.lockCurrentTrainingCategories(ctx, initial, productPolicyID, productPolicyVersion)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - lock training categories: %w", location, err)
|
||||
}
|
||||
current, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - recheck current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
selections, err := repository.currentTrainingSelections(ctx, current, locked, productPolicyID, productPolicyVersion)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current bindings: %w", location, err)
|
||||
}
|
||||
if len(selections) == 0 {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - no current reviewed training binding: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
if len(selections) > 1 {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - multiple current reviewed training bindings: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
|
||||
}
|
||||
return selections[0], nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) lockCurrentTrainingCategories(
|
||||
ctx context.Context,
|
||||
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) (map[domain.AssessmentCategory]struct{}, error) {
|
||||
locked := make(map[domain.AssessmentCategory]struct{})
|
||||
for _, row := range rows {
|
||||
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
|
||||
continue
|
||||
}
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
if _, exists := locked[category]; exists {
|
||||
continue
|
||||
}
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locked[category] = struct{}{}
|
||||
}
|
||||
return locked, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentTrainingSelections(
|
||||
ctx context.Context,
|
||||
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
locked map[domain.AssessmentCategory]struct{},
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) ([]outbound.AssessmentTrainingBankSelection, error) {
|
||||
selections := make([]outbound.AssessmentTrainingBankSelection, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
|
||||
continue
|
||||
}
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
if _, ok := locked[category]; !ok {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
selection, err := repository.currentTrainingSelectionFromRow(ctx, row)
|
||||
if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selections = append(selections, selection)
|
||||
}
|
||||
return selections, nil
|
||||
}
|
||||
|
||||
func matchesProductPolicy(
|
||||
rowID pgtype.UUID,
|
||||
rowVersion int32,
|
||||
policyID domain.PolicyVersionID,
|
||||
policyVersion int32,
|
||||
) bool {
|
||||
return rowID.Bytes == uuid.UUID(policyID) && rowVersion == policyVersion
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentTrainingSelectionFromRow(
|
||||
ctx context.Context,
|
||||
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
) (outbound.AssessmentTrainingBankSelection, error) {
|
||||
const location = "assessmentBankRepository.currentTrainingSelectionFromRow"
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
entries, manifestSHA, err := repository.validateCurrentTrainingManifest(ctx, category, row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
|
||||
}
|
||||
members, err := repository.queries.ListAssessmentTrainingBindingFamilies(ctx, pgUUID(row.ID.Bytes))
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read pinned training families: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
families, err := repository.resolveCurrentTrainingFamilies(ctx, category, entries, members)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
|
||||
}
|
||||
return outbound.AssessmentTrainingBankSelection{
|
||||
BindingID: row.ID.Bytes, Category: category,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, ManifestSHA: manifestSHA, Families: families,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) validateCurrentTrainingManifest(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
|
||||
entries, err := decodeAssessmentCategoryManifest(string(row.FamilyManifest))
|
||||
if err != nil || len(entries) != int(row.ItemCount) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
manifestSHA, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil || !slices.Equal(manifestSHA[:], row.ManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
liveEntries, err := repository.currentPublishedManifestEntries(ctx, category)
|
||||
if err != nil {
|
||||
return nil, [sha256.Size]byte{}, err
|
||||
}
|
||||
liveHash, err := assessmentCategoryManifestFingerprint(liveEntries)
|
||||
if err != nil || !assessmentManifestEntriesEqual(entries, liveEntries) || !slices.Equal(liveHash[:], row.ManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return entries, manifestSHA, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentPublishedManifestEntries(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, error) {
|
||||
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(category))
|
||||
if err != nil {
|
||||
return nil, mapAssessmentError(err)
|
||||
}
|
||||
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
key, parseErr := domain.ParseAssessmentFamilyKey(row.FamilyKey)
|
||||
if parseErr != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
|
||||
return nil, domain.ErrInvalidAssessmentFamily
|
||||
}
|
||||
entries = append(entries, domain.AssessmentCategoryManifestEntry{
|
||||
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
|
||||
})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveCurrentTrainingFamilies(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entries []domain.AssessmentCategoryManifestEntry,
|
||||
members []sqlc.ListAssessmentTrainingBindingFamiliesRow,
|
||||
) ([]domain.AssessmentFamily, error) {
|
||||
if len(members) != len(entries) {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
if entries[i].FamilyKey == entries[j].FamilyKey {
|
||||
return entries[i].Version < entries[j].Version
|
||||
}
|
||||
return entries[i].FamilyKey < entries[j].FamilyKey
|
||||
})
|
||||
families := make([]domain.AssessmentFamily, 0, len(entries))
|
||||
for index, entry := range entries {
|
||||
family, err := repository.resolveTrainingFamily(ctx, category, entry, members[index], index)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
families = append(families, family)
|
||||
}
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveTrainingFamily(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entry domain.AssessmentCategoryManifestEntry,
|
||||
member sqlc.ListAssessmentTrainingBindingFamiliesRow,
|
||||
index int,
|
||||
) (domain.AssessmentFamily, error) {
|
||||
if member.Ordinal < 1 || int64(member.Ordinal) != int64(index)+1 || member.FamilyKey != string(entry.FamilyKey) ||
|
||||
member.FamilyVersion != entry.Version || !slices.Equal(member.ContentSha256, entry.ContentSHA256) {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, mapPinnedFamilyLookupError(err)
|
||||
}
|
||||
hash := family.ContentHash()
|
||||
if family.ID().UUID() != member.FamilyID.Bytes || family.Category() != category ||
|
||||
family.Lifecycle() != domain.AssessmentLifecyclePublished || family.ReviewStatus() != domain.AssessmentReviewApproved ||
|
||||
!slices.Equal(hash[:], entry.ContentSHA256) {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
func assessmentManifestEntriesEqual(
|
||||
left []domain.AssessmentCategoryManifestEntry,
|
||||
right []domain.AssessmentCategoryManifestEntry,
|
||||
) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
canonical := func(entries []domain.AssessmentCategoryManifestEntry) []domain.AssessmentCategoryManifestEntry {
|
||||
result := slices.Clone(entries)
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].FamilyKey == result[j].FamilyKey {
|
||||
return result[i].Version < result[j].Version
|
||||
}
|
||||
return result[i].FamilyKey < result[j].FamilyKey
|
||||
})
|
||||
return result
|
||||
}
|
||||
orderedLeft, orderedRight := canonical(left), canonical(right)
|
||||
for index := range orderedLeft {
|
||||
if orderedLeft[index].FamilyKey != orderedRight[index].FamilyKey ||
|
||||
orderedLeft[index].Version != orderedRight[index].Version ||
|
||||
!slices.Equal(orderedLeft[index].ContentSHA256, orderedRight[index].ContentSHA256) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func currentAssessmentCatalogMetadata(
|
||||
row sqlc.ListCurrentSpecializationAvailabilityRow,
|
||||
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const assessmentSignalBatchEventLimit = 50
|
||||
|
||||
var (
|
||||
_ outbound.AssessmentSignalRepositories = (*UnitOfWork)(nil)
|
||||
_ outbound.AssessmentSignalRepository = assessmentSignalRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) AssessmentSignals() outbound.AssessmentSignalRepository {
|
||||
return assessmentSignalRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type assessmentSignalRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) CountRecentOutcomes(
|
||||
ctx context.Context,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
since time.Time,
|
||||
) (int64, time.Time, error) {
|
||||
const location = "assessmentSignalRepository.CountRecentOutcomes"
|
||||
if attemptID.IsZero() || since.IsZero() {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - attempt and window start are required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
row, err := repository.queries.CountRecentAssessmentSignalOutcomes(ctx, sqlc.CountRecentAssessmentSignalOutcomesParams{
|
||||
AttemptID: pgUUID(attemptID.UUID()), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - count recent receipts: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
if row.OutcomeCount < 0 {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - stored receipt count is negative", location)
|
||||
}
|
||||
oldest, err := quotaWindowEarliest(row.OldestAt)
|
||||
if err != nil {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - read oldest receipt: %w", location, err)
|
||||
}
|
||||
return row.OutcomeCount, oldest, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) CountAttemptEvents(
|
||||
ctx context.Context,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (int64, error) {
|
||||
const location = "assessmentSignalRepository.CountAttemptEvents"
|
||||
if attemptID.IsZero() {
|
||||
return 0, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
count, err := repository.queries.CountAssessmentSignalEvents(ctx, pgUUID(attemptID.UUID()))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s - count stored events: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
if count < 0 {
|
||||
return 0, fmt.Errorf("%s - stored event count is negative", location)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) SaveBatch(ctx context.Context, batch domain.AssessmentSignalBatch) error {
|
||||
const location = "assessmentSignalRepository.SaveBatch"
|
||||
if _, err := domain.NewAssessmentSignalBatch(batch.ID(), batch.AttemptID(), batch.ReceivedAt(), batch.Events()); err != nil {
|
||||
return fmt.Errorf("%s - batch is invalid: %w", location, err)
|
||||
}
|
||||
events := batch.Events()
|
||||
eventCount, err := assessmentSignalBatchEventCount(events)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - event count is outside the database bound: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentSignalBatch(ctx, sqlc.InsertAssessmentSignalBatchParams{
|
||||
ID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), ReceivedAt: pgTime(batch.ReceivedAt()),
|
||||
EventCount: eventCount,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert batch receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
for index, event := range events {
|
||||
duration, hasDuration := event.DurationMS()
|
||||
size, hasSize := event.SizeBytes()
|
||||
if err := repository.queries.InsertAssessmentSignalEvent(ctx, sqlc.InsertAssessmentSignalEventParams{
|
||||
BatchID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), Ordinal: int32(index + 1),
|
||||
ItemInstanceID: pgUUID(event.ItemInstanceID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
|
||||
DurationMs: nullableSignalMeasurement(duration, hasDuration), SizeBytes: nullableSignalMeasurement(size, hasSize),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert event metadata: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func assessmentSignalBatchEventCount(events []domain.AssessmentSignalEvent) (int32, error) {
|
||||
if len(events) < 1 || len(events) > assessmentSignalBatchEventLimit {
|
||||
return 0, domain.ErrInvalidAssessmentSignal
|
||||
}
|
||||
var count int32
|
||||
for range events {
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) SaveOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
receipt domain.AssessmentSignalReceipt,
|
||||
) error {
|
||||
const location = "assessmentSignalRepository.SaveOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) || attemptID.IsZero() {
|
||||
return fmt.Errorf("%s - scope and attempt ID are required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
if _, err := domain.NewAssessmentSignalReceipt(receipt.Status(), receipt.AcceptedEvents(), receipt.ReceivedAt()); err != nil {
|
||||
return fmt.Errorf("%s - receipt is invalid: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentSignalOutcome(ctx, sqlc.InsertAssessmentSignalOutcomeParams{
|
||||
ScopeHash: scope[:], AttemptID: pgUUID(attemptID.UUID()), Status: string(receipt.Status()),
|
||||
AcceptedEvents: receipt.AcceptedEvents(), ReceivedAt: pgTime(receipt.ReceivedAt()),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) DeleteExpiredOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
) error {
|
||||
const location = "assessmentSignalRepository.DeleteExpiredOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
|
||||
return fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
if err := repository.queries.DeleteExpiredAssessmentSignalOutcome(ctx, scope[:]); err != nil {
|
||||
return fmt.Errorf("%s - remove expired receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) GetOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
) (domain.AssessmentSignalReceipt, error) {
|
||||
const location = "assessmentSignalRepository.GetOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentSignalOutcome(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt does not exist: %w", location, outbound.ErrAssessmentSignalOutcomeNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - read immutable receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
receivedAt, err := requiredSignalReceiptTime(row.ReceivedAt)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt time: %w", location, err)
|
||||
}
|
||||
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptStatus(row.Status), row.AcceptedEvents, receivedAt)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt: %w", location, err)
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func nullableSignalMeasurement(value int32, valid bool) pgtype.Int4 {
|
||||
if !valid {
|
||||
return pgtype.Int4{}
|
||||
}
|
||||
return pgtype.Int4{Int32: value, Valid: true}
|
||||
}
|
||||
|
||||
func requiredSignalReceiptTime(value pgtype.Timestamptz) (time.Time, error) {
|
||||
if !value.Valid || value.Time.IsZero() {
|
||||
return time.Time{}, domain.ErrInvalidAssessmentSignal
|
||||
}
|
||||
return value.Time.UTC(), nil
|
||||
}
|
||||
@@ -256,6 +256,22 @@ func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, pu
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockCurrentForUse(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
purpose domain.ConsentPurpose,
|
||||
) (domain.ConsentRecord, error) {
|
||||
const location = "consentLedger.LockCurrentForUse"
|
||||
if subjectID == uuid.Nil || purpose != domain.ConsentPurposeAutoCategorization {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - only a valid subject and C3 can authorize automated use: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
row, err := ledger.queries.LockCurrentConsentForUse(ctx, pgUUID(subjectID))
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - lock current C3 record: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
|
||||
}
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockRegistration(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
|
||||
@@ -18,12 +18,24 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.NeedRepository = needRepository{}
|
||||
var (
|
||||
_ outbound.NeedRepository = needRepository{}
|
||||
_ outbound.NeedListRepository = needRepository{}
|
||||
_ outbound.NeedCreationResultRepository = needRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) Needs() outbound.NeedRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) NeedLists() outbound.NeedListRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) NeedCreationResults() outbound.NeedCreationResultRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type needRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
@@ -99,6 +111,129 @@ func (repository needRepository) GetVersion(
|
||||
return restoreNeedSnapshot(location, encoded, organizationID, needID, version, 0, nil, nil)
|
||||
}
|
||||
|
||||
func (repository needRepository) List(ctx context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
||||
const location = "needRepository.List"
|
||||
if query.OrganizationID == uuid.Nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxNeedPageSize {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
|
||||
}
|
||||
params := sqlc.ListOrganizationNeedsParams{
|
||||
OrganizationID: pgUUID(query.OrganizationID),
|
||||
RowLimit: query.Limit + 1,
|
||||
}
|
||||
if query.After != nil {
|
||||
if err := validateNeedListPosition(location, *query.After); err != nil {
|
||||
return outbound.NeedPage{}, err
|
||||
}
|
||||
params.AfterCreatedAt = pgTime(query.After.CreatedAt)
|
||||
params.AfterNeedID = pgUUID(query.After.NeedID)
|
||||
}
|
||||
rows, err := repository.queries.ListOrganizationNeeds(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - select current needs: %w", location, mapNeedError(err))
|
||||
}
|
||||
page := outbound.NeedPage{HasMore: len(rows) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
page.Items = make([]domain.Need, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.OrganizationID.Valid || !row.NeedID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != query.OrganizationID {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - current need row has invalid scope or metadata", location)
|
||||
}
|
||||
need, err := restoreNeedSnapshot(
|
||||
location, row.Snapshot, query.OrganizationID, uuid.UUID(row.NeedID.Bytes),
|
||||
row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time,
|
||||
)
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, err
|
||||
}
|
||||
page.Items = append(page.Items, need)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func validateNeedListPosition(location string, position outbound.NeedListPosition) error {
|
||||
createdAt := position.CreatedAt
|
||||
if position.NeedID == uuid.Nil || createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 ||
|
||||
createdAt.Unix() < 0 || createdAt.Nanosecond()%int(time.Microsecond) != 0 {
|
||||
return fmt.Errorf("%s - pagination position is outside the stored need timestamp range: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository needRepository) SaveCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
snapshot domain.NeedResponseSnapshot,
|
||||
) error {
|
||||
const location = "needRepository.SaveCreationResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
_, encoded, err := encodeNeedCreationResult(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate and encode response snapshot: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.SaveOrganizationNeedCreationResult(ctx, sqlc.SaveOrganizationNeedCreationResultParams{
|
||||
ScopeHash: scope[:], Snapshot: encoded,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - store response snapshot: %w", location, mapNeedError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository needRepository) GetCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
const location = "needRepository.GetCreationResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
encoded, err := repository.queries.GetOrganizationNeedCreationResult(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read response snapshot: %w", location, mapNeedError(err))
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultStorageBytes {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot exceeds its bound", location)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var snapshot domain.NeedResponseSnapshot
|
||||
if err := decoder.Decode(&snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot is invalid", location)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot has trailing data", location)
|
||||
}
|
||||
validated, _, err := encodeNeedCreationResult(snapshot)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - restore response snapshot: %w", location, err)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func encodeNeedCreationResult(snapshot domain.NeedResponseSnapshot) (domain.NeedResponseSnapshot, []byte, error) {
|
||||
validated, err := domain.RestoreNeedResponseSnapshot(snapshot)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, nil, err
|
||||
}
|
||||
encoded, err := json.Marshal(validated)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("encode need response snapshot: %w", err)
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultBytes {
|
||||
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("need response snapshot exceeds its storage bound: %w", domain.ErrInvalidNeed)
|
||||
}
|
||||
return validated, encoded, nil
|
||||
}
|
||||
|
||||
func (repository needRepository) Save(
|
||||
ctx context.Context,
|
||||
organizationID, needID uuid.UUID,
|
||||
@@ -216,7 +351,7 @@ func restoreNeedSnapshot(
|
||||
version, requirementsVersion int64,
|
||||
createdAt, updatedAt *time.Time,
|
||||
) (domain.Need, error) {
|
||||
if len(encoded) > domain.MaxNeedSnapshotBytes {
|
||||
if len(encoded) > domain.MaxNeedSnapshotStorageBytes {
|
||||
return domain.Need{}, fmt.Errorf("%s - stored snapshot exceeds its bound", location)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
||||
@@ -269,6 +404,9 @@ func mapNeedError(err error) error {
|
||||
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_needs_organization_fkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_need_creation_results_idempotency_fkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
||||
}
|
||||
if pgError.Code == uniqueViolationCode && pgError.ConstraintName == "organization_needs_pkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - need ID already exists: %w", outbound.ErrNeedAlreadyExists)
|
||||
}
|
||||
|
||||
@@ -316,6 +316,33 @@ func (repository organizationRepository) GetForMember(
|
||||
return organization, membership, nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) LockActiveMembership(
|
||||
ctx context.Context,
|
||||
organizationID, userID uuid.UUID,
|
||||
) (domain.Membership, error) {
|
||||
const location = "organizationRepository.LockActiveMembership"
|
||||
row, err := repository.queries.LockActiveMembership(ctx, sqlc.LockActiveMembershipParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
UserID: pgUUID(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - lock active membership: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
|
||||
}
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: optionalUUID(row.MembershipID),
|
||||
OrganizationID: optionalUUID(row.OrganizationID),
|
||||
UserID: optionalUUID(row.UserID),
|
||||
Role: row.Role,
|
||||
State: row.State,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
UpdatedAt: row.UpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
// representativeJSON is one element of the representatives column that
|
||||
// GetOrganizationForMember aggregates in the same statement as the
|
||||
// organization, so the profile and the list come from one snapshot.
|
||||
|
||||
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user