feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -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.
@@ -0,0 +1,207 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.PrivacyCohortRepository = privacyCohortRepository{}
// PrivacyCohortStore reads the current visible candidate cohort outside a
// transaction. The single query provides one consistent publication and
// hidden-organization snapshot.
type PrivacyCohortStore struct {
queries *sqlc.Queries
}
func NewPrivacyCohortStore(pool *pgxpool.Pool) *PrivacyCohortStore {
return &PrivacyCohortStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (unit *UnitOfWork) PrivacyCohort() outbound.PrivacyCohortRepository {
return privacyCohortRepository{queries: unit.queries}
}
func (unit *UnitOfWork) PrivacyView() outbound.PrivacyViewRepository {
return privacyCohortRepository{queries: unit.queries}
}
func (store *PrivacyCohortStore) ListVisibleCandidateViewSources(
ctx context.Context,
organizationID uuid.UUID,
) ([]domain.CandidateViewSource, error) {
return (privacyCohortRepository{queries: store.queries}).ListVisibleCandidateViewSources(ctx, organizationID)
}
type privacyCohortRepository struct {
queries *sqlc.Queries
}
type privacyCohortCandidate struct {
id uuid.UUID
fields domain.CardFieldSet
claims []domain.StoredProfileClaim
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
workFormats []domain.QuestionnaireWorkFormat
}
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
ctx context.Context,
organizationID uuid.UUID,
) ([]domain.CandidateViewSource, error) {
const location = "privacyCohortRepository.ListVisibleCandidateViewSources"
if organizationID == uuid.Nil {
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
rows, err := repository.queries.ListVisibleCandidateViewSources(ctx, pgUUID(organizationID))
if err != nil {
return nil, fmt.Errorf("%s - select visible sources: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
if len(rows) == 0 {
return []domain.CandidateViewSource{}, nil
}
result := make([]domain.CandidateViewSource, 0, len(rows))
current := privacyCohortCandidate{}
for _, row := range rows {
candidateID, err := privacyCohortUUID(row.UserID)
if err != nil {
return nil, fmt.Errorf("%s - source identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
}
if current.id != uuid.Nil && current.id != candidateID {
source, err := buildPrivacyCohortSource(current)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
result = append(result, source)
current = privacyCohortCandidate{}
}
if current.id == uuid.Nil {
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
}
if row.Kind.Valid {
claim, err := privacyCohortStoredClaim(row)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate claims: %w", location, err)
}
current.claims = append(current.claims, claim)
}
}
source, err := buildPrivacyCohortSource(current)
if err != nil {
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
}
result = append(result, source)
return result, nil
}
func newPrivacyCohortCandidate(
candidateID uuid.UUID,
fieldCodes []string,
workFormatCodes []string,
acknowledgementsValue any,
) (privacyCohortCandidate, error) {
fields := make([]domain.CardField, 0, len(fieldCodes))
for _, code := range fieldCodes {
fields = append(fields, domain.CardField(code))
}
fieldSet, err := domain.NewCardFieldSet(fields)
if err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid publication fields: %w", domain.ErrInvalidCandidateViewSource)
}
workFormats := make([]domain.QuestionnaireWorkFormat, 0, len(workFormatCodes))
for _, code := range workFormatCodes {
workFormats = append(workFormats, domain.QuestionnaireWorkFormat(code))
}
acknowledgementsJSON, err := privacyCohortEncodedJSONBytes(acknowledgementsValue)
if err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
}
var acknowledgements []domain.ProfileParallelPeriodAcknowledgement
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
}
return privacyCohortCandidate{
id: candidateID, fields: fieldSet, workFormats: workFormats,
acknowledgements: acknowledgements,
}, nil
}
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
value, err := privacyCohortJSONBytes(row.SafeValue)
if err != nil {
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
}
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
}
confirmedAt := time.Time{}
if row.ConfirmedAt.Valid {
confirmedAt = row.ConfirmedAt.Time.UTC()
}
return domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
}, nil
}
func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.CandidateViewSource, error) {
content, err := domain.RestoreCandidateProfileContentWithParallelPeriods(candidate.claims, candidate.acknowledgements)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
}
return domain.NewCandidateViewSource(
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
candidate.workFormats, nil,
)
}
func privacyCohortJSONBytes(value any) ([]byte, error) {
switch typed := value.(type) {
case []byte:
return slices.Clone(typed), nil
case json.RawMessage:
return slices.Clone(typed), nil
default:
encoded, err := json.Marshal(typed)
if err != nil {
return nil, errors.New("JSON projection has an unexpected type")
}
return encoded, nil
}
}
func privacyCohortEncodedJSONBytes(value any) ([]byte, error) {
switch typed := value.(type) {
case string:
return []byte(typed), nil
case []byte:
return slices.Clone(typed), nil
case json.RawMessage:
return slices.Clone(typed), nil
default:
return nil, errors.New("encoded JSON projection has an unexpected type")
}
}
func privacyCohortUUID(value pgtype.UUID) (uuid.UUID, error) {
if !value.Valid || value.Bytes == uuid.Nil {
return uuid.Nil, domain.ErrInvalidCandidateViewSource
}
return uuid.UUID(value.Bytes), nil
}
@@ -0,0 +1,441 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.PrivacySettingsRepository = privacySettingsRepository{}
var privacySettingsConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "candidate_publications_consent_fkey"}: outbound.ErrConsentNotFound,
{foreignKeyViolationCode, "candidate_hidden_organizations_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "candidate_hidden_organizations_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
{foreignKeyViolationCode, "candidate_privacy_events_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "candidate_privacy_events_consent_fkey"}: outbound.ErrConsentNotFound,
{foreignKeyViolationCode, "candidate_privacy_events_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
{checkViolationCode, "candidate_hidden_organizations_limit"}: outbound.ErrCandidateHiddenOrganizationLimit,
}
func (unit *UnitOfWork) PrivacySettings() outbound.PrivacySettingsRepository {
return privacySettingsRepository{queries: unit.queries}
}
type privacySettingsRepository struct {
queries *sqlc.Queries
}
func (repository privacySettingsRepository) ReadSettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
const location = "privacySettingsRepository.ReadSettings"
if userID == uuid.Nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.ReadCandidatePrivacySettings(ctx, pgUUID(userID))
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - select settings: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrUserNotFound))
}
if got, err := privacySettingsUUID(row.UserID); err != nil || got != userID {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - result identity is invalid: %w", location, domain.ErrInvalidVisibility)
}
publication, err := publicationFromSettingsRow(userID, row)
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore publication: %w", location, err)
}
searchStatus, err := searchStatusFromSettingsRow(userID, row)
if err != nil {
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore search status: %w", location, err)
}
return outbound.CandidatePrivacySettings{
Publication: publication, SearchStatus: searchStatus, HiddenCount: row.HiddenCount,
}, nil
}
func publicationFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.Publication, error) {
if !row.PublicationState.Valid {
return domain.NewPublication(userID)
}
consentID, err := privacySettingsUUID(row.PublicationConsentRecordID)
if err != nil {
return domain.Publication{}, fmt.Errorf("publication consent ID is invalid: %w", domain.ErrInvalidVisibility)
}
if !row.PublicationVersion.Valid || !row.PublicationPublishedAt.Valid {
return domain.Publication{}, fmt.Errorf("publication snapshot is incomplete: %w", domain.ErrInvalidVisibility)
}
stored := domain.StoredPublication{
UserID: userID, State: row.PublicationState.String, Fields: row.PublicationFields,
ConsentRecordID: consentID, PublishedAt: row.PublicationPublishedAt.Time.UTC(),
ClosedAt: privacySettingsTime(row.PublicationClosedAt), Version: row.PublicationVersion.Int64,
ConsentRevoked: row.PublicationConsentRevokedAt.Valid,
}
return domain.RestorePublication(stored)
}
func searchStatusFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.SearchStatus, error) {
if !row.SearchStatus.Valid {
return domain.NewSearchStatus(userID)
}
if !row.SearchVersion.Valid {
return domain.SearchStatus{}, fmt.Errorf("search status snapshot is incomplete: %w", domain.ErrInvalidVisibility)
}
var policyVersionID domain.PolicyVersionID
if row.SearchPolicyVersionID.Valid {
policyVersionID = domain.PolicyVersionID(row.SearchPolicyVersionID.Bytes)
}
return domain.RestoreSearchStatus(domain.StoredSearchStatus{
UserID: userID, Status: row.SearchStatus.String,
ConfirmedAt: privacySettingsTime(row.SearchConfirmedAt), LapsesAt: privacySettingsTime(row.SearchLapsesAt),
PolicyVersionID: policyVersionID, Version: row.SearchVersion.Int64,
})
}
func (repository privacySettingsRepository) LockCurrentC2ForPublication(ctx context.Context, userID uuid.UUID) (uuid.UUID, error) {
const location = "privacySettingsRepository.LockCurrentC2ForPublication"
if userID == uuid.Nil {
return uuid.Nil, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
}
id, err := repository.queries.LockCurrentC2Record(ctx, pgUUID(userID))
if err != nil {
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrConsentNotFound))
}
return privacySettingsUUID(id)
}
func (repository privacySettingsRepository) SavePublication(ctx context.Context, publication domain.Publication, expectedVersion int64) error {
const location = "privacySettingsRepository.SavePublication"
if publication.UserID() == uuid.Nil || publication.Version() != expectedVersion+1 || expectedVersion < 0 {
return fmt.Errorf("%s - publication version is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.InsertCandidatePublicationParams{
UserID: pgUUID(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(),
ConsentRecordID: privacySettingsOptionalUUID(publication.ConsentRecordID()),
PublishedAt: pgTime(publication.PublishedAt()), ClosedAt: privacySettingsOptionalTime(publication.ClosedAt()),
At: pgTime(privacySettingsPublicationUpdatedAt(publication)),
}
var err error
if expectedVersion == 0 {
_, err = repository.queries.InsertCandidatePublication(ctx, params)
} else {
_, err = repository.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{
State: params.State, Fields: params.Fields, ConsentRecordID: params.ConsentRecordID,
PublishedAt: params.PublishedAt, ClosedAt: params.ClosedAt, At: params.At,
UserID: params.UserID, ExpectedVersion: expectedVersion,
})
}
if err != nil {
return fmt.Errorf("%s - persist publication: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
}
return nil
}
func privacySettingsPublicationUpdatedAt(publication domain.Publication) time.Time {
if publication.StoredState() == domain.PublicationClosed {
return publication.ClosedAt()
}
return publication.PublishedAt()
}
func (repository privacySettingsRepository) SaveSearchStatus(ctx context.Context, status domain.SearchStatus, expectedVersion int64, at time.Time) error {
const location = "privacySettingsRepository.SaveSearchStatus"
if status.UserID() == uuid.Nil || status.Version() != expectedVersion+1 || expectedVersion < 0 {
return fmt.Errorf("%s - status version is invalid: %w", location, domain.ErrInvalidVisibility)
}
policyID := status.PolicyVersionID().UUID()
params := sqlc.InsertCandidateSearchStatusParams{
UserID: pgUUID(status.UserID()), Status: string(status.StoredValue()),
ConfirmedAt: privacySettingsOptionalTime(status.ConfirmedAt()),
LapsesAt: privacySettingsOptionalTime(status.LapsesAt()), PolicyVersionID: privacySettingsOptionalUUID(policyID),
At: pgTime(at.UTC().Truncate(time.Microsecond)),
}
var err error
if expectedVersion == 0 {
_, err = repository.queries.InsertCandidateSearchStatus(ctx, params)
} else {
_, err = repository.queries.UpdateCandidateSearchStatus(ctx, sqlc.UpdateCandidateSearchStatusParams{
UserID: params.UserID, Status: params.Status, ConfirmedAt: params.ConfirmedAt, LapsesAt: params.LapsesAt,
PolicyVersionID: params.PolicyVersionID, At: params.At, ExpectedVersion: expectedVersion,
})
}
if err != nil {
return fmt.Errorf("%s - persist status: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
}
return nil
}
func (repository privacySettingsRepository) CountHiddenOrganizations(ctx context.Context, userID uuid.UUID) (int64, error) {
if userID == uuid.Nil {
return 0, domain.ErrInvalidVisibility
}
count, err := repository.queries.CountCandidateHiddenOrganizations(ctx, pgUUID(userID))
if err != nil {
return 0, fmt.Errorf("privacySettingsRepository.CountHiddenOrganizations - count records: %w", mapPrivacySettingsError(err))
}
return count, nil
}
func (repository privacySettingsRepository) GetHiddenOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
const location = "privacySettingsRepository.GetHiddenOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
})
if err != nil {
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - select record: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacySettingsNotFound))
}
return hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
}
func (repository privacySettingsRepository) CandidateCanSeeOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.CandidateVisibleOrganization, error) {
const location = "privacySettingsRepository.CandidateCanSeeOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
row, err := repository.queries.CandidateCanSeeOrganization(ctx, sqlc.CandidateCanSeeOrganizationParams{
OrganizationID: pgUUID(organizationID), UserID: pgUUID(userID),
})
if err != nil {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - select visible organization: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacyOrganizationNotVisible))
}
id, err := privacySettingsUUID(row.ID)
if err != nil || id != organizationID || row.Name == "" {
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - organization snapshot is invalid: %w", location, domain.ErrInvalidVisibility)
}
return outbound.CandidateVisibleOrganization{ID: id, Name: row.Name}, nil
}
func (repository privacySettingsRepository) HideOrganization(ctx context.Context, hidden domain.HiddenOrganization) (bool, error) {
const location = "privacySettingsRepository.HideOrganization"
if hidden.UserID() == uuid.Nil || hidden.OrganizationID() == uuid.Nil || hidden.HiddenAt().IsZero() {
return false, fmt.Errorf("%s - hiding is invalid: %w", location, domain.ErrInvalidVisibility)
}
_, err := repository.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{
UserID: pgUUID(hidden.UserID()), OrganizationID: pgUUID(hidden.OrganizationID()), At: pgTime(hidden.HiddenAt()),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - insert record: %w", location, mapPrivacySettingsError(err))
}
return true, nil
}
func (repository privacySettingsRepository) UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (bool, error) {
const location = "privacySettingsRepository.UnhideOrganization"
if userID == uuid.Nil || organizationID == uuid.Nil {
return false, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
}
_, err := repository.queries.DeleteCandidateHiddenOrganization(ctx, sqlc.DeleteCandidateHiddenOrganizationParams{
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - delete record: %w", location, mapPrivacySettingsError(err))
}
return true, nil
}
func (repository privacySettingsRepository) ListHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
const location = "privacySettingsRepository.ListHiddenOrganizations"
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.ListCandidateHiddenOrganizationsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.HiddenAt.IsZero() || query.After.OrganizationID == uuid.Nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
}
params.AfterHiddenAt = pgTime(query.After.HiddenAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListCandidateHiddenOrganizations(ctx, params)
if err != nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - select records: %w", location, mapPrivacySettingsError(err))
}
page := outbound.HiddenOrganizationPage{Items: make([]outbound.HiddenOrganizationRecord, 0, min(len(rows), int(query.Limit)))}
for index, row := range rows {
if index == int(query.Limit) {
page.HasMore = true
break
}
record, err := hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
if err != nil {
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - restore record: %w", location, err)
}
page.Items = append(page.Items, record)
}
return page, nil
}
func (repository privacySettingsRepository) RecordPrivacyEvent(ctx context.Context, event domain.PrivacyEvent) error {
const location = "privacySettingsRepository.RecordPrivacyEvent"
if event.ID() == uuid.Nil || event.UserID() == uuid.Nil || !event.Kind().Valid() || event.OccurredAt().IsZero() {
return fmt.Errorf("%s - event is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.InsertCandidatePrivacyEventParams{
ID: pgUUID(event.ID()), UserID: pgUUID(event.UserID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
}
if event.HasFieldSet() {
params.Fields = event.Fields().Codes()
}
if event.ConsentRecordID() != uuid.Nil {
params.ConsentRecordID = pgUUID(event.ConsentRecordID())
}
if event.OrganizationID() != uuid.Nil {
params.OrganizationID = pgUUID(event.OrganizationID())
}
if err := repository.queries.InsertCandidatePrivacyEvent(ctx, params); err != nil {
return fmt.Errorf("%s - insert event: %w", location, mapPrivacySettingsError(err))
}
return nil
}
func (repository privacySettingsRepository) ListPrivacyEvents(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
const location = "privacySettingsRepository.ListPrivacyEvents"
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
}
params := sqlc.ListCandidatePrivacyEventsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.OccurredAt.IsZero() || query.After.ID == uuid.Nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
}
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := repository.queries.ListCandidatePrivacyEvents(ctx, params)
if err != nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - select events: %w", location, mapPrivacySettingsError(err))
}
page := outbound.CandidatePrivacyEventPage{Items: make([]outbound.CandidatePrivacyEventRecord, 0, min(len(rows), int(query.Limit)))}
for index, row := range rows {
if index == int(query.Limit) {
page.HasMore = true
break
}
record, err := privacyEventFromRow(row)
if err != nil {
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - restore event: %w", location, err)
}
page.Items = append(page.Items, record)
}
return page, nil
}
func privacyEventFromRow(row sqlc.ListCandidatePrivacyEventsRow) (outbound.CandidatePrivacyEventRecord, error) {
id, err := privacySettingsUUID(row.ID)
if err != nil || !row.OccurredAt.Valid {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
record := outbound.CandidatePrivacyEventRecord{ID: id, Kind: domain.PrivacyEventKind(row.Kind), OccurredAt: row.OccurredAt.Time.UTC()}
if !record.Kind.Valid() {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
if row.Fields != nil {
fields, err := domain.NewCardFieldSet(stringsToCardFields(row.Fields))
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
}
record.Fields = &fields
}
if row.ConsentRecordID.Valid {
record.ConsentRecordID, err = privacySettingsUUID(row.ConsentRecordID)
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, err
}
}
if row.OrganizationID.Valid {
record.OrganizationID, err = privacySettingsUUID(row.OrganizationID)
if err != nil {
return outbound.CandidatePrivacyEventRecord{}, err
}
}
if row.OrganizationName.Valid {
record.OrganizationName = row.OrganizationName.String
}
return record, nil
}
func hiddenOrganizationFromRow(id pgtype.UUID, name string, hiddenAt pgtype.Timestamptz) (outbound.HiddenOrganizationRecord, error) {
organizationID, err := privacySettingsUUID(id)
if err != nil || name == "" || !hiddenAt.Valid {
return outbound.HiddenOrganizationRecord{}, domain.ErrInvalidVisibility
}
return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: name, HiddenAt: hiddenAt.Time.UTC()}, nil
}
func privacySettingsOptionalTime(value time.Time) pgtype.Timestamptz {
if value.IsZero() {
return pgtype.Timestamptz{}
}
return pgTime(value)
}
func privacySettingsOptionalUUID(value uuid.UUID) pgtype.UUID {
if value == uuid.Nil {
return pgtype.UUID{}
}
return pgUUID(value)
}
func privacySettingsTime(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time.UTC()
}
func privacySettingsUUID(value pgtype.UUID) (uuid.UUID, error) {
if !value.Valid || uuid.UUID(value.Bytes) == uuid.Nil {
return uuid.Nil, domain.ErrInvalidVisibility
}
return uuid.UUID(value.Bytes), nil
}
func stringsToCardFields(codes []string) []domain.CardField {
fields := make([]domain.CardField, 0, len(codes))
for _, code := range codes {
fields = append(fields, domain.CardField(code))
}
return fields
}
func mapPrivacySettingsNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapPrivacySettingsError(err)
}
func mapPrivacySettingsWriteError(err, noRows error) error {
if errors.Is(err, pgx.ErrNoRows) {
return noRows
}
return mapPrivacySettingsError(err)
}
func mapPrivacySettingsError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
violation := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
if sentinel, ok := privacySettingsConstraintErrors[violation]; ok {
return fmt.Errorf("postgres.mapPrivacySettingsError - constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
@@ -0,0 +1,267 @@
package postgres
import (
"context"
"errors"
"fmt"
"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"
)
var _ outbound.PrivacyViewRepository = privacyCohortRepository{}
// CurrentFields stays closed until invitation grants have transaction-bound
// persistence. The C4 ledger alone does not identify a live invitation grant.
func (privacyCohortRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
}
func (privacyCohortRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error {
// No C4 contact-grant persistence exists in this release. Contact reads are
// closed by default, so there is no persisted grant to reactivate later.
return nil
}
func (repository privacyCohortRepository) LockCandidateAccountForView(ctx context.Context, candidateID uuid.UUID) error {
const location = "privacyCohortRepository.LockCandidateAccountForView"
if candidateID == uuid.Nil {
return fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockCandidateAccountForView(ctx, pgUUID(candidateID))
if err != nil {
return fmt.Errorf("%s - lock candidate account: %w", location,
mapNoRows(sanitizeConnectError(err), outbound.ErrUserNotFound))
}
return nil
}
func (repository privacyCohortRepository) LockCurrentC2ForView(ctx context.Context, candidateID uuid.UUID) (uuid.UUID, error) {
const location = "privacyCohortRepository.LockCurrentC2ForView"
if candidateID == uuid.Nil {
return uuid.Nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
consentID, err := repository.queries.LockCurrentC2ForView(ctx, pgUUID(candidateID))
if err != nil {
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location,
mapNoRows(sanitizeConnectError(err), outbound.ErrCandidateC2Unavailable))
}
return privacyCohortUUID(consentID)
}
func (repository privacyCohortRepository) LockVisiblePublicationForView(
ctx context.Context,
organizationID, candidateID, consentRecordID uuid.UUID,
) (bool, error) {
const location = "privacyCohortRepository.LockVisiblePublicationForView"
if organizationID == uuid.Nil || candidateID == uuid.Nil || consentRecordID == uuid.Nil {
return false, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockVisiblePublicationForView(ctx, sqlc.LockVisiblePublicationForViewParams{
OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), ConsentRecordID: pgUUID(consentRecordID),
})
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - lock visible publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return true, nil
}
func (repository privacyCohortRepository) LockPublicationForPreview(ctx context.Context, candidateID uuid.UUID) (bool, error) {
const location = "privacyCohortRepository.LockPublicationForPreview"
if candidateID == uuid.Nil {
return false, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
_, err := repository.queries.LockPublicationForCandidatePreview(ctx, pgUUID(candidateID))
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("%s - lock current publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return true, nil
}
func (repository privacyCohortRepository) ReadCandidateViewSourceForPreview(
ctx context.Context,
candidateID uuid.UUID,
) (domain.CandidateViewSource, error) {
const location = "privacyCohortRepository.ReadCandidateViewSourceForPreview"
if candidateID == uuid.Nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
}
rows, err := repository.queries.ReadCandidateViewSourceForPreview(ctx, pgUUID(candidateID))
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - read candidate projection: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
if len(rows) == 0 {
return domain.CandidateViewSource{}, fmt.Errorf("%s - current publication has no projection row: %w", location, outbound.ErrPrivacyCohortUnavailable)
}
return buildPreviewCandidateViewSource(candidateID, rows)
}
func buildPreviewCandidateViewSource(
candidateID uuid.UUID,
rows []sqlc.ReadCandidateViewSourceForPreviewRow,
) (domain.CandidateViewSource, error) {
const location = "buildPreviewCandidateViewSource"
first := rows[0]
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
}
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
}
for _, row := range rows {
if row.Kind.Valid {
claim, err := previewStoredClaim(row)
if err != nil {
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate claim: %w", location, err)
}
candidate.claims = append(candidate.claims, claim)
}
}
return buildPrivacyCohortSource(candidate)
}
func previewStoredClaim(row sqlc.ReadCandidateViewSourceForPreviewRow) (domain.StoredProfileClaim, error) {
value, err := privacyCohortJSONBytes(row.SafeValue)
if err != nil {
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
}
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
}
confirmedAt := timeValueOrZero(row.ConfirmedAt)
return domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
}, nil
}
func timeValueOrZero(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time.UTC()
}
func (repository privacyCohortRepository) RecordCandidateCardAccess(ctx context.Context, access domain.CandidateCardAccess) error {
const location = "privacyCohortRepository.RecordCandidateCardAccess"
if access.IsZero() || access.ActorID() == uuid.Nil {
return fmt.Errorf("%s - access event is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
err := repository.queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{
ID: pgUUID(access.ID()), CandidateID: pgUUID(access.CandidateID()),
OrganizationID: pgUUID(access.OrganizationID()), ActorID: pgUUID(access.ActorID()),
Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: pgTime(access.OccurredAt()),
})
if err != nil {
return fmt.Errorf("%s - insert access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
func (repository privacyCohortRepository) ListCandidateCardAccess(
ctx context.Context,
query outbound.CandidateCardAccessListQuery,
) (outbound.CandidateCardAccessListPage, error) {
const location = "privacyCohortRepository.ListCandidateCardAccess"
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxCandidateCardAccessPageSize {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
params := sqlc.ListCandidateCardAccessEventsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := repository.queries.ListCandidateCardAccessEvents(ctx, params)
if err != nil {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - list access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return buildCandidateCardAccessPage(query.CandidateID, query.Limit, rows)
}
func buildCandidateCardAccessPage(
candidateID uuid.UUID,
limit int32,
rows []sqlc.ListCandidateCardAccessEventsRow,
) (outbound.CandidateCardAccessListPage, error) {
const location = "buildCandidateCardAccessPage"
page := outbound.CandidateCardAccessListPage{
Items: make([]domain.CandidateCardAccess, 0, min(len(rows), int(limit))),
OrganizationNames: make(map[uuid.UUID]string),
}
if len(rows) > int(limit) {
page.HasMore = true
rows = rows[:limit]
}
for _, row := range rows {
access, organizationID, err := restoreCandidateCardAccessEvent(row, candidateID)
if err != nil {
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - restore access event: %w", location, err)
}
page.Items = append(page.Items, access)
page.OrganizationNames[organizationID] = row.OrganizationName
}
return page, nil
}
func restoreCandidateCardAccessEvent(
row sqlc.ListCandidateCardAccessEventsRow,
expectedCandidateID uuid.UUID,
) (domain.CandidateCardAccess, uuid.UUID, error) {
const location = "restoreCandidateCardAccessEvent"
id, err := privacyCohortUUID(row.ID)
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access identifier is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
candidateID, err := privacyCohortUUID(row.CandidateID)
if err != nil || candidateID != expectedCandidateID {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access candidate is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
organizationID, err := privacyCohortUUID(row.OrganizationID)
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access organization is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
}
access, err := domain.RestoreCandidateCardAccess(id, restoreCandidateCardAccessInput(row, candidateID, organizationID))
if err != nil {
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access event values are invalid: %w", location, err)
}
return access, organizationID, nil
}
func restoreCandidateCardAccessInput(
row sqlc.ListCandidateCardAccessEventsRow,
candidateID, organizationID uuid.UUID,
) domain.CandidateCardAccessInput {
var projectionFields []domain.CardField
var contactFields []domain.ContactField
for _, code := range row.FieldCodes {
if field := domain.CardField(code); field.Valid() {
projectionFields = append(projectionFields, field)
continue
}
contactFields = append(contactFields, domain.ContactField(code))
}
input := domain.CandidateCardAccessInput{
CandidateID: candidateID, OrganizationID: organizationID,
ActorID: optionalUUID(row.ActorID), Kind: domain.CandidateCardAccessKind(row.Kind),
ProjectionFields: projectionFields, ContactFields: contactFields,
OccurredAt: timeValueOrZero(row.OccurredAt),
}
return input
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,365 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_availability.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentAvailabilityActiveAttempt = `-- name: GetAssessmentAvailabilityActiveAttempt :one
SELECT id, expires_at
FROM assessment_attempts
WHERE user_id = $1
AND specialization = $2
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
`
type GetAssessmentAvailabilityActiveAttemptParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
}
type GetAssessmentAvailabilityActiveAttemptRow struct {
ID pgtype.UUID
ExpiresAt pgtype.Timestamptz
}
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
func (q *Queries) GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error) {
row := q.db.QueryRow(ctx, getAssessmentAvailabilityActiveAttempt, arg.UserID, arg.Specialization)
var i GetAssessmentAvailabilityActiveAttemptRow
err := row.Scan(&i.ID, &i.ExpiresAt)
return i, err
}
const getAssessmentRootQuotaAvailability = `-- 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 = $3
AND attempt.kind = 'root'
AND attempt.state <> 'insufficient_bank'
AND attempt.created_at >= $4::timestamptz
AND attempt.created_at <= $5::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 >= $1::bigint THEN (
SELECT eligible.created_at
+ make_interval(secs => $2::double precision)
+ interval '1 microsecond'
FROM eligible
ORDER BY eligible.created_at, eligible.id
LIMIT 1
OFFSET (total.attempt_count - $1::bigint)
) ELSE NULL::timestamptz END AS available_at
FROM total
`
type GetAssessmentRootQuotaAvailabilityParams struct {
MaxAttempts int64
WindowSeconds float64
UserID pgtype.UUID
Since pgtype.Timestamptz
AsOf pgtype.Timestamptz
}
type GetAssessmentRootQuotaAvailabilityRow struct {
AttemptCount int64
AvailableAt pgtype.Timestamptz
}
// 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.
func (q *Queries) GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error) {
row := q.db.QueryRow(ctx, getAssessmentRootQuotaAvailability,
arg.MaxAttempts,
arg.WindowSeconds,
arg.UserID,
arg.Since,
arg.AsOf,
)
var i GetAssessmentRootQuotaAvailabilityRow
err := row.Scan(&i.AttemptCount, &i.AvailableAt)
return i, err
}
const listAssessmentAvailabilityRootSummaries = `-- 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.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
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 = $1
AND root.specialization = $2
AND root.kind = 'root'
AND root.created_at >= $3::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
`
type ListAssessmentAvailabilityRootSummariesParams struct {
UserID pgtype.UUID
Specialization pgtype.Text
Since pgtype.Timestamptz
}
type ListAssessmentAvailabilityRootSummariesRow struct {
RootTargetGrade pgtype.Text
RootCreatedAt pgtype.Timestamptz
RootUpdatedAt pgtype.Timestamptz
RootExpiresAt pgtype.Timestamptz
RootState string
RootOutcome pgtype.Text
RootChainDeadline pgtype.Timestamptz
LatestTargetGrade pgtype.Text
LatestUpdatedAt pgtype.Timestamptz
LatestExpiresAt pgtype.Timestamptz
LatestState string
LatestOutcome pgtype.Text
LatestChainDeadline pgtype.Timestamptz
LatestPlatformError string
}
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
func (q *Queries) ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error) {
rows, err := q.db.Query(ctx, listAssessmentAvailabilityRootSummaries, arg.UserID, arg.Specialization, arg.Since)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentAvailabilityRootSummariesRow
for rows.Next() {
var i ListAssessmentAvailabilityRootSummariesRow
if err := rows.Scan(
&i.RootTargetGrade,
&i.RootCreatedAt,
&i.RootUpdatedAt,
&i.RootExpiresAt,
&i.RootState,
&i.RootOutcome,
&i.RootChainDeadline,
&i.LatestTargetGrade,
&i.LatestUpdatedAt,
&i.LatestExpiresAt,
&i.LatestState,
&i.LatestOutcome,
&i.LatestChainDeadline,
&i.LatestPlatformError,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentDisclosedFamilyKeys = `-- 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 = $2
AND attempt.kind IN ('root', 'corrective')
AND attempt.expires_at > $1::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 > $1::timestamptz
ORDER BY disclosed.family_key
`
type ListAssessmentDisclosedFamilyKeysParams struct {
Since pgtype.Timestamptz
UserID pgtype.UUID
}
// 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.
func (q *Queries) ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error) {
rows, err := q.db.Query(ctx, listAssessmentDisclosedFamilyKeys, arg.Since, arg.UserID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var family_key string
if err := rows.Scan(&family_key); err != nil {
return nil, err
}
items = append(items, family_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCurrentAssessmentAvailabilitySelections = `-- name: ListCurrentAssessmentAvailabilitySelections :many
WITH current_policy AS (
SELECT id, version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= $1::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
`
type ListCurrentAssessmentAvailabilitySelectionsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// 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.
func (q *Queries) ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error) {
rows, err := q.db.Query(ctx, listCurrentAssessmentAvailabilitySelections, asOf)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentAssessmentAvailabilitySelectionsRow
for rows.Next() {
var i ListCurrentAssessmentAvailabilitySelectionsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,201 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signals.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countAssessmentSignalEvents = `-- name: CountAssessmentSignalEvents :one
SELECT count(*)::bigint AS event_count
FROM assessment_signal_events
WHERE attempt_id = $1
`
// Count events only for the already owner-locked attempt.
func (q *Queries) CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countAssessmentSignalEvents, attemptID)
var event_count int64
err := row.Scan(&event_count)
return event_count, err
}
const countRecentAssessmentSignalOutcomes = `-- name: CountRecentAssessmentSignalOutcomes :one
SELECT
count(*)::bigint AS outcome_count,
COALESCE(min(received_at), $1::timestamptz) AS oldest_at
FROM assessment_signal_idempotency_outcomes
WHERE
attempt_id = $2
AND received_at > $1
`
type CountRecentAssessmentSignalOutcomesParams struct {
Since pgtype.Timestamptz
AttemptID pgtype.UUID
}
type CountRecentAssessmentSignalOutcomesRow struct {
OutcomeCount int64
OldestAt interface{}
}
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
func (q *Queries) CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error) {
row := q.db.QueryRow(ctx, countRecentAssessmentSignalOutcomes, arg.Since, arg.AttemptID)
var i CountRecentAssessmentSignalOutcomesRow
err := row.Scan(&i.OutcomeCount, &i.OldestAt)
return i, err
}
const deleteExpiredAssessmentSignalOutcome = `-- name: DeleteExpiredAssessmentSignalOutcome :exec
DELETE FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
func (q *Queries) DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteExpiredAssessmentSignalOutcome, scopeHash)
return err
}
const getAssessmentSignalOutcome = `-- name: GetAssessmentSignalOutcome :one
SELECT status, accepted_events, received_at
FROM assessment_signal_idempotency_outcomes
WHERE scope_hash = $1
`
type GetAssessmentSignalOutcomeRow struct {
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Read only the receipt associated with the reserved idempotency scope.
func (q *Queries) GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error) {
row := q.db.QueryRow(ctx, getAssessmentSignalOutcome, scopeHash)
var i GetAssessmentSignalOutcomeRow
err := row.Scan(&i.Status, &i.AcceptedEvents, &i.ReceivedAt)
return i, err
}
const insertAssessmentSignalBatch = `-- name: InsertAssessmentSignalBatch :exec
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
VALUES (
$1,
$2,
$3,
$4
)
`
type InsertAssessmentSignalBatchParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
// 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.
func (q *Queries) InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalBatch,
arg.ID,
arg.AttemptID,
arg.ReceivedAt,
arg.EventCount,
)
return err
}
const insertAssessmentSignalEvent = `-- name: InsertAssessmentSignalEvent :exec
INSERT INTO assessment_signal_events (
batch_id,
attempt_id,
ordinal,
item_instance_id,
kind,
occurred_at,
duration_ms,
size_bytes
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7::integer,
$8::integer
)
`
type InsertAssessmentSignalEventParams struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
func (q *Queries) InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalEvent,
arg.BatchID,
arg.AttemptID,
arg.Ordinal,
arg.ItemInstanceID,
arg.Kind,
arg.OccurredAt,
arg.DurationMs,
arg.SizeBytes,
)
return err
}
const insertAssessmentSignalOutcome = `-- name: InsertAssessmentSignalOutcome :exec
INSERT INTO assessment_signal_idempotency_outcomes (
scope_hash,
attempt_id,
status,
accepted_events,
received_at
) VALUES (
$1,
$2,
$3,
$4,
$5
)
`
type InsertAssessmentSignalOutcomeParams struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
// Save exactly one immutable response receipt for each live idempotency scope.
func (q *Queries) InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalOutcome,
arg.ScopeHash,
arg.AttemptID,
arg.Status,
arg.AcceptedEvents,
arg.ReceivedAt,
)
return err
}
@@ -871,6 +871,79 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
return items, nil
}
const lockCurrentConsentForUse = `-- 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 = $1
AND purpose = 'c3'
AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC
LIMIT 1
FOR SHARE
`
type LockCurrentConsentForUseRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
func (q *Queries) LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) {
row := q.db.QueryRow(ctx, lockCurrentConsentForUse, subjectID)
var i LockCurrentConsentForUseRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
SELECT
id,
@@ -16,6 +16,89 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentAttempt struct {
ID pgtype.UUID
UserID pgtype.UUID
Kind string
Mode string
State string
Outcome pgtype.Text
BankCategory string
Specialization pgtype.Text
TargetGrade pgtype.Text
TaskLanguage pgtype.Text
RootAttemptID pgtype.UUID
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ChainDeadline pgtype.Timestamptz
IdleTimeoutSeconds int32
MaxSessions int32
SessionsUsed int32
SessionStartedAt pgtype.Timestamptz
LastActivityAt pgtype.Timestamptz
Version int64
EndedAt pgtype.Timestamptz
}
type AssessmentAttemptIdempotencyOutcome struct {
ScopeHash []byte
Operation string
StatusCode int16
ProblemCode pgtype.Text
ResponseSnapshot []byte
ResponseSchemaVersion int16
CreatedAt pgtype.Timestamptz
PendingItemIds []pgtype.UUID
}
type AssessmentAttemptItem struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
FamilyContentSha256 []byte
Variant []byte
Answer []byte
AnsweredAt pgtype.Timestamptz
}
type AssessmentAttemptResult struct {
AttemptID pgtype.UUID
UserID pgtype.UUID
ResultSnapshot []byte
SchemaVersion int16
Kind string
Mode string
Outcome string
ProductPolicyVersionID pgtype.UUID
ProductPolicyVersion int32
GradingPolicyVersionID pgtype.UUID
OpeningID pgtype.UUID
OpeningManifestSha256 []byte
TrainingBindingID pgtype.UUID
TrainingManifestSha256 []byte
BankVersion string
AlgorithmVersion string
RationaleRule string
PassMarkBasisPoints pgtype.Int4
ScoredItems pgtype.Int2
RawScore pgtype.Int2
PassPoints pgtype.Int2
DecidedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
@@ -60,6 +143,62 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type AssessmentSignalBatch struct {
ID pgtype.UUID
AttemptID pgtype.UUID
ReceivedAt pgtype.Timestamptz
EventCount int32
}
type AssessmentSignalEvent struct {
BatchID pgtype.UUID
AttemptID pgtype.UUID
Ordinal int32
ItemInstanceID pgtype.UUID
Kind string
OccurredAt pgtype.Timestamptz
DurationMs pgtype.Int4
SizeBytes pgtype.Int4
}
type AssessmentSignalIdempotencyOutcome struct {
ScopeHash []byte
AttemptID pgtype.UUID
Status string
AcceptedEvents int32
ReceivedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBinding struct {
ID pgtype.UUID
Category string
ProductPolicyVersionID pgtype.UUID
ItemCount int32
ManifestSha256 []byte
FamilyManifest []byte
ReviewedBy string
CreatedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBindingFamily struct {
BindingID pgtype.UUID
Ordinal int32
FamilyID pgtype.UUID
FamilyKey string
FamilyVersion int32
ContentSha256 []byte
}
type CandidateCardAccessEvent struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
type CandidateEffectivePublication struct {
UserID pgtype.UUID
Fields []string
@@ -405,6 +544,11 @@ type OrganizationNeed struct {
UpdatedAt pgtype.Timestamptz
}
type OrganizationNeedCreationResult struct {
ScopeHash []byte
Snapshot []byte
}
type OrganizationNeedVersion struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
@@ -472,6 +616,57 @@ type Session struct {
RevokedAt pgtype.Timestamptz
}
type SupportCase struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type SupportCaseCreateOutcome struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate pgtype.Bool
CreatedAt pgtype.Timestamptz
}
type SupportCaseEvent struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
type SupportCaseRequestEvent struct {
ID int64
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
type User struct {
ID pgtype.UUID
Email string
@@ -80,6 +80,21 @@ func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrgani
return snapshot, err
}
const getOrganizationNeedCreationResult = `-- name: GetOrganizationNeedCreationResult :one
SELECT snapshot::text AS snapshot
FROM organization_need_creation_results
WHERE scope_hash = $1
`
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
func (q *Queries) GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
row := q.db.QueryRow(ctx, getOrganizationNeedCreationResult, scopeHash)
var snapshot string
err := row.Scan(&snapshot)
return snapshot, err
}
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
INSERT INTO organization_needs (
id,
@@ -152,6 +167,85 @@ func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertO
return err
}
const listOrganizationNeeds = `-- 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 = $1
AND (
$2::timestamptz IS NULL
OR (need.created_at, need.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY need.created_at DESC, need.id DESC
LIMIT $4
`
type ListOrganizationNeedsParams struct {
OrganizationID pgtype.UUID
AfterCreatedAt pgtype.Timestamptz
AfterNeedID pgtype.UUID
RowLimit int32
}
type ListOrganizationNeedsRow struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
CurrentVersion int64
RequirementsVersion int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Snapshot string
}
// Read one bounded newest-first page of current needs. Both the organization
// scope and the tuple cursor are applied before the limit.
func (q *Queries) ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error) {
rows, err := q.db.Query(ctx, listOrganizationNeeds,
arg.OrganizationID,
arg.AfterCreatedAt,
arg.AfterNeedID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationNeedsRow
for rows.Next() {
var i ListOrganizationNeedsRow
if err := rows.Scan(
&i.OrganizationID,
&i.NeedID,
&i.CurrentVersion,
&i.RequirementsVersion,
&i.CreatedAt,
&i.UpdatedAt,
&i.Snapshot,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
SELECT
need.organization_id,
@@ -224,3 +318,23 @@ func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrgan
err := row.Scan(&snapshot)
return snapshot, err
}
const saveOrganizationNeedCreationResult = `-- name: SaveOrganizationNeedCreationResult :exec
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
VALUES ($1, $2::jsonb)
ON CONFLICT (scope_hash) DO UPDATE
SET snapshot = excluded.snapshot
`
type SaveOrganizationNeedCreationResultParams struct {
ScopeHash []byte
Snapshot []byte
}
// 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.
func (q *Queries) SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error {
_, err := q.db.Exec(ctx, saveOrganizationNeedCreationResult, arg.ScopeHash, arg.Snapshot)
return err
}
@@ -405,6 +405,63 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
return items, nil
}
const lockActiveMembership = `-- name: LockActiveMembership :one
WITH locked_organization AS MATERIALIZED (
SELECT organizations.id
FROM organizations
WHERE organizations.id = $2
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 = $1
AND membership.state = 'active'
FOR SHARE OF membership
`
type LockActiveMembershipParams struct {
UserID pgtype.UUID
OrganizationID pgtype.UUID
}
type LockActiveMembershipRow struct {
MembershipID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// 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.
func (q *Queries) LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error) {
row := q.db.QueryRow(ctx, lockActiveMembership, arg.UserID, arg.OrganizationID)
var i LockActiveMembershipRow
err := row.Scan(
&i.MembershipID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
INSERT INTO organization_creation_results (scope_hash, snapshot)
VALUES ($1, $2)
@@ -11,6 +11,44 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const candidateCanSeeOrganization = `-- name: CandidateCanSeeOrganization :one
SELECT organizations.id, organizations.name
FROM organizations
WHERE organizations.id = $1
AND (
EXISTS (
SELECT 1 FROM candidate_card_access_events
WHERE candidate_card_access_events.candidate_id = $2
AND candidate_card_access_events.organization_id = organizations.id
)
OR EXISTS (
SELECT 1 FROM candidate_hidden_organizations
WHERE candidate_hidden_organizations.user_id = $2
AND candidate_hidden_organizations.organization_id = organizations.id
)
)
`
type CandidateCanSeeOrganizationParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type CandidateCanSeeOrganizationRow struct {
ID pgtype.UUID
Name string
}
// 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.
func (q *Queries) CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error) {
row := q.db.QueryRow(ctx, candidateCanSeeOrganization, arg.OrganizationID, arg.UserID)
var i CandidateCanSeeOrganizationRow
err := row.Scan(&i.ID, &i.Name)
return i, err
}
const countCandidateHiddenOrganizations = `-- name: CountCandidateHiddenOrganizations :one
SELECT count(*) AS total
FROM candidate_hidden_organizations
@@ -79,6 +117,52 @@ func (q *Queries) GetCandidateHiddenOrganization(ctx context.Context, arg GetCan
return i, err
}
const insertCandidateCardAccessEvent = `-- name: InsertCandidateCardAccessEvent :exec
INSERT INTO candidate_card_access_events (
id,
candidate_id,
organization_id,
actor_id,
kind,
field_codes,
occurred_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertCandidateCardAccessEventParams struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
}
// 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.
func (q *Queries) InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error {
_, err := q.db.Exec(ctx, insertCandidateCardAccessEvent,
arg.ID,
arg.CandidateID,
arg.OrganizationID,
arg.ActorID,
arg.Kind,
arg.FieldCodes,
arg.OccurredAt,
)
return err
}
const insertCandidateHiddenOrganization = `-- name: InsertCandidateHiddenOrganization :one
INSERT INTO candidate_hidden_organizations (
user_id,
@@ -272,6 +356,88 @@ func (q *Queries) InsertCandidateSearchStatus(ctx context.Context, arg InsertCan
return i, err
}
const listCandidateCardAccessEvents = `-- 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 = $1
AND (
$2::timestamptz IS NULL
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
LIMIT $4
`
type ListCandidateCardAccessEventsParams struct {
CandidateID pgtype.UUID
AfterOccurredAt pgtype.Timestamptz
AfterID pgtype.UUID
RowLimit int32
}
type ListCandidateCardAccessEventsRow struct {
ID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ActorID pgtype.UUID
Kind string
FieldCodes []string
OccurredAt pgtype.Timestamptz
OrganizationName string
}
// 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.
func (q *Queries) ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error) {
rows, err := q.db.Query(ctx, listCandidateCardAccessEvents,
arg.CandidateID,
arg.AfterOccurredAt,
arg.AfterID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateCardAccessEventsRow
for rows.Next() {
var i ListCandidateCardAccessEventsRow
if err := rows.Scan(
&i.ID,
&i.CandidateID,
&i.OrganizationID,
&i.ActorID,
&i.Kind,
&i.FieldCodes,
&i.OccurredAt,
&i.OrganizationName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidateHiddenOrganizations = `-- name: ListCandidateHiddenOrganizations :many
SELECT
candidate_hidden_organizations.organization_id,
@@ -480,8 +646,88 @@ func (q *Queries) LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID
return id, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
const readCandidatePrivacySettings = `-- 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 = $1
`
type ReadCandidatePrivacySettingsRow struct {
UserID pgtype.UUID
PublicationState pgtype.Text
PublicationFields []string
PublicationConsentRecordID pgtype.UUID
PublicationPublishedAt pgtype.Timestamptz
PublicationClosedAt pgtype.Timestamptz
PublicationVersion pgtype.Int8
PublicationConsentRevokedAt pgtype.Timestamptz
SearchStatus pgtype.Text
SearchConfirmedAt pgtype.Timestamptz
SearchLapsesAt pgtype.Timestamptz
SearchPolicyVersionID pgtype.UUID
SearchVersion pgtype.Int8
HiddenCount int64
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// 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.
func (q *Queries) ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error) {
row := q.db.QueryRow(ctx, readCandidatePrivacySettings, userID)
var i ReadCandidatePrivacySettingsRow
err := row.Scan(
&i.UserID,
&i.PublicationState,
&i.PublicationFields,
&i.PublicationConsentRecordID,
&i.PublicationPublishedAt,
&i.PublicationClosedAt,
&i.PublicationVersion,
&i.PublicationConsentRevokedAt,
&i.SearchStatus,
&i.SearchConfirmedAt,
&i.SearchLapsesAt,
&i.SearchPolicyVersionID,
&i.SearchVersion,
&i.HiddenCount,
)
return i, err
}
const readCandidatePublication = `-- name: ReadCandidatePublication :one
SELECT
candidate_publications.user_id,
candidate_publications.state,
@@ -512,13 +758,6 @@ type ReadCandidatePublicationRow struct {
ConsentRevokedAt pgtype.Timestamptz
}
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// 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
@@ -0,0 +1,330 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: privacy_cohort.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const listVisibleCandidateViewSources = `-- 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 = $1
)
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ListVisibleCandidateViewSourcesRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// 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.
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListVisibleCandidateViewSourcesRow
for rows.Next() {
var i ListVisibleCandidateViewSourcesRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockCandidateAccountForView = `-- name: LockCandidateAccountForView :one
SELECT users.id
FROM users
WHERE users.id = $1
FOR SHARE
`
// 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.
func (q *Queries) LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCandidateAccountForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockCurrentC2ForView = `-- name: LockCurrentC2ForView :one
SELECT consent_records.id
FROM consent_records
WHERE
consent_records.subject_id = $1
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 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.
func (q *Queries) LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCurrentC2ForView, candidateID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockPublicationForCandidatePreview = `-- 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 = $1
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
`
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
func (q *Queries) LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockPublicationForCandidatePreview, candidateID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const lockVisiblePublicationForView = `-- 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 = $1
AND candidate_publications.state = 'published'
AND candidate_publications.consent_record_id = $2
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 = $3
)
FOR SHARE OF candidate_publications, consent_records
`
type LockVisiblePublicationForViewParams struct {
CandidateID pgtype.UUID
ConsentRecordID pgtype.UUID
OrganizationID pgtype.UUID
}
// 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.
func (q *Queries) LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockVisiblePublicationForView, arg.CandidateID, arg.ConsentRecordID, arg.OrganizationID)
var user_id pgtype.UUID
err := row.Scan(&user_id)
return user_id, err
}
const readCandidateViewSourceForPreview = `-- 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 = $1
ORDER BY effective.user_id, claim.kind, claim.ordinal
`
type ReadCandidateViewSourceForPreviewRow struct {
UserID pgtype.UUID
Fields []string
Kind pgtype.Text
Ordinal pgtype.Int2
SafeValue interface{}
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
WorkFormats []string
ParallelPeriodAcknowledgements interface{}
}
// 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.
func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error) {
rows, err := q.db.Query(ctx, readCandidateViewSourceForPreview, candidateID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadCandidateViewSourceForPreviewRow
for rows.Next() {
var i ReadCandidateViewSourceForPreviewRow
if err := rows.Scan(
&i.UserID,
&i.Fields,
&i.Kind,
&i.Ordinal,
&i.SafeValue,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.WorkFormats,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -60,6 +60,10 @@ type Querier interface {
// redacts the bodies of a token mail like any other cancellation. now is the
// application clock.
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
// 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.
CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error)
// Claims the most overdue delivery that the sending worker may send, in one
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
// (the literals match the predicate of deliveries_due_idx, so an idle poll
@@ -118,6 +122,8 @@ type Querier interface {
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Count events only for the already owner-locked attempt.
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
@@ -125,10 +131,22 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// New outcomes share the generic idempotency row and are counted for the
// attempt's rolling receipt window. Replays bypass this query in the usecase.
CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error)
// Counts root attempts only; the caller applies the effective policy's
// configured window and the product's approved accounting scope.
CountRootAssessmentAttemptsSince(ctx context.Context, arg CountRootAssessmentAttemptsSinceParams) (int64, error)
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error)
// Creates one durable deletion request per subject until a worker completes it.
// The caller appends the matching outbox intent in the same transaction only
// when this insert returns a row.
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
// A newly reserved generic idempotency window can replace an expired typed
// outcome before the new immutable response is inserted.
DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error
// Lifts one hiding. No row returns when the organization was not hidden, so
// the caller writes the history event only for a real deletion and answers
// 204 either way.
@@ -142,9 +160,15 @@ type Querier interface {
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
// The generic reservation has already established that a previous outcome is
// expired before this child is removed and replaced in the same transaction.
DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -190,9 +214,30 @@ type Querier interface {
// Reads the durable active deletion request when an earlier request already
// exists. A completed request does not suppress a later explicit request.
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
// Locks the active real attempt after LockAssessmentAttemptScope.
GetActiveAssessmentAttemptForSpecialization(ctx context.Context, arg GetActiveAssessmentAttemptForSpecializationParams) (AssessmentAttempt, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
// Locks the one active express attempt after LockAssessmentAttemptScope.
GetActiveTrainingAssessmentAttempt(ctx context.Context, userID pgtype.UUID) (AssessmentAttempt, error)
// Returns a full private attempt only to its candidate.
GetAssessmentAttemptForCandidate(ctx context.Context, arg GetAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
GetAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentAttemptIdempotencyOutcomeRow, error)
// Reads the immutable attempt kind without locking the row. Session commands
// use this only to decide whether C3 applies before acquiring the row lock.
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
// Reads a result only for the owning candidate.
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
// 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.
GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error)
// Read only the receipt associated with the reserved idempotency scope.
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
// Reads one hiding of the candidate with the current name of the
// organization.
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
@@ -236,6 +281,8 @@ type Querier interface {
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the latest root in a specialization, optionally restricted to grade.
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
@@ -250,6 +297,9 @@ type Querier interface {
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Read only the immutable original response. The current need may have moved
// to a later version since this result was created.
GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -278,6 +328,15 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Inserts the attempt header. The database guard rechecks the current policy,
// opening or disjoint training binding, and immutable pins.
InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error
InsertAssessmentAttemptIdempotencyOutcome(ctx context.Context, arg InsertAssessmentAttemptIdempotencyOutcomeParams) error
// Stores the immutable generated variant and empty answer slot.
InsertAssessmentAttemptItem(ctx context.Context, arg InsertAssessmentAttemptItemParams) error
// Stores one immutable candidate-visible result with the decision rationale
// and source versions used by its finalized attempt.
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
@@ -292,6 +351,18 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
// 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.
InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error
// Save exactly one immutable response receipt for each live idempotency scope.
InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error
// 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.
InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error
// Hides one organization. No row returns when the pair already exists, and
// the caller reads the existing record with its original time. The foreign key
// refuses an unknown organization (SQLSTATE 23503); the caller answers it
@@ -390,12 +461,44 @@ type Querier interface {
// transaction and then inserts nothing, or inserts after its rollback.
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
// 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.
InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error)
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
// Reads chain headers in creation order. The use case verifies root eligibility
// and descending target grades in the domain before it creates a correction.
ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error)
// Reads private frozen variants and candidate answer bytes in stable order.
ListAssessmentAttemptItems(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAttemptItemsRow, error)
// Reads roots within the policy horizon and the last header in each correction
// chain. It deliberately omits frozen items, answers, and row locks.
ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error)
// 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.
ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error)
// One page of the versions of a category in key and version order, after the
// given position; an empty key and version 0 start at the beginning. The
// (family_key, version) unique index serves the scan.
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
// Reads the exact family membership pinned by a training binding.
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
// 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.
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
// One page of the candidate's hidden organizations, newest first with the
// organization identifier as the tie-breaker. The page continues after the
// (hidden_at, organization_id) position of the last record of the previous
@@ -414,12 +517,22 @@ type Querier interface {
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
// 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.
ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error)
// Lists explicit immutable training bindings for the effective product
// policy. Callers reject more than one matching active binding as ambiguous.
ListCurrentAssessmentTrainingBindings(ctx context.Context) ([]ListCurrentAssessmentTrainingBindingsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Read one bounded newest-first page of current needs. Both the organization
// scope and the tuple cursor are applied before the limit.
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
@@ -428,10 +541,36 @@ type Querier interface {
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
// 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.
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
// 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.
LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error)
// Locks one owner-scoped attempt while a session command performs its CAS.
LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
// Serializes root quota checks for one candidate before taking its optional
// specialization or training lock. All callers acquire these locks in order.
LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error
// Serializes the operations that change which versions of a category are
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// 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.
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the candidate's published row only when it refers to a C2 record
// revoked by this transaction. The setting remains linked to that immutable
// record; ReadCandidatePublication computes the effective closed state and
@@ -452,6 +591,10 @@ type Querier interface {
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// 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.
LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Takes the candidate's current unrevoked C2 record for a publication and
// keeps it locked until the transaction ends. The share lock conflicts with
// the revocation stamp (an UPDATE of the row), so a revocation either commits
@@ -461,6 +604,9 @@ type Querier interface {
// publication and must re-read the effective state (ReadCandidatePublication)
// in that transaction to build its response.
LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error)
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -482,8 +628,17 @@ type Querier interface {
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Lock a candidate's current publication for the private preview. This has
// no organization context and never enters the employer read quota or audit.
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
// Locks the active registration C1 while its pending registration is applied.
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
// Serialize per-owner budget checks even before the first event exists.
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
// 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.
LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error)
// Notes that a request is about to start, by the database clock, and clears
// the count of worker failures. For an operator-authorized send, this sets
// its single-use marker without overwriting the original first-send time. The
@@ -504,10 +659,16 @@ type Querier interface {
// Verifies the email only for the registration version the consumed token
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error)
Ping(ctx context.Context) (int32, error)
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error)
// Moves a draft to published by the named operator and returns the row with
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
@@ -515,6 +676,18 @@ type Querier interface {
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// 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.
ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
@@ -523,13 +696,6 @@ type Querier interface {
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
// Queries of the candidate visibility settings: the publication of
// the card, the search status, the hidden organizations, and the history of
// these settings. Every statement is scoped by the candidate's user_id, and
// no statement selects another account's row. No statement reads or writes a
// profile value, a name, or a contact. A candidate with no row is closed, not
// looking, and hides nobody; no statement creates a row except an explicit
// act of the candidate.
// 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
@@ -542,10 +708,16 @@ type Querier interface {
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error)
// 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.
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error)
// Read one current version with its organization-scoped parent metadata.
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
// Read one historical version without exposing another organization's record.
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
// Reads a full owner-scoped record. Object values are identifiers only.
ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error)
// The organization-facing read of a candidate's publication: the effective
// view (published and backed by an unrevoked C2) and no hiding of the reading
// organization. No row means the organization reads nothing, whichever of
@@ -557,6 +729,9 @@ type Querier interface {
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error)
// Reads the immutable public history only after the case owner has matched.
ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
@@ -609,6 +784,14 @@ type Querier interface {
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
// 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.
ResolveCurrentAssessmentSelection(ctx context.Context, arg ResolveCurrentAssessmentSelectionParams) ([]ResolveCurrentAssessmentSelectionRow, error)
// 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.
ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error)
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
@@ -625,6 +808,10 @@ type Querier interface {
// and owner membership. A reused expired scope replaces the snapshot in the
// same transaction as the new organization.
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
// 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.
SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error
// Bounds a consumer transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a process that froze or lost the network inside the
@@ -661,6 +848,14 @@ type Querier interface {
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
// Stores one final answer before advancing the enclosing attempt version.
// The caller holds the owner-scoped attempt row lock for the surrounding unit.
UpdateAssessmentAttemptItemAnswer(ctx context.Context, arg UpdateAssessmentAttemptItemAnswerParams) (pgtype.UUID, error)
// Applies a versioned session transition after the attempt row is locked.
UpdateAssessmentAttemptSession(ctx context.Context, arg UpdateAssessmentAttemptSessionParams) (AssessmentAttempt, error)
// Applies an answer, expiry, or finalization transition after the attempt row
// is locked. Session limits and all immutable pins remain unchanged.
UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error)
// Replaces the publication over the version the caller read and advances the
// version in the same statement. No row returns for a stale version, which
// the caller answers as a version conflict. The update time never moves back,
@@ -0,0 +1,502 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_cases.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countSupportCaseRequestEvents = `-- name: CountSupportCaseRequestEvents :one
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
FROM support_case_request_events
WHERE owner_id = $1
AND requested_at > $2::timestamptz
AND requested_at <= $3::timestamptz
`
type CountSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
WindowStart pgtype.Timestamptz
At pgtype.Timestamptz
}
type CountSupportCaseRequestEventsRow struct {
EventCount int64
FirstInWindow interface{}
}
// The strict lower boundary means an event exactly one window old no longer
// counts. The use case derives Retry-After from first_in_window.
func (q *Queries) CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error) {
row := q.db.QueryRow(ctx, countSupportCaseRequestEvents, arg.OwnerID, arg.WindowStart, arg.At)
var i CountSupportCaseRequestEventsRow
err := row.Scan(&i.EventCount, &i.FirstInWindow)
return i, err
}
const deleteSupportCaseCreateOutcome = `-- name: DeleteSupportCaseCreateOutcome :exec
DELETE FROM support_case_create_outcomes
WHERE scope_hash = $1
`
// No raw Idempotency-Key or request body reaches these statements. Failure
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
func (q *Queries) DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error {
_, err := q.db.Exec(ctx, deleteSupportCaseCreateOutcome, scopeHash)
return err
}
const insertSupportCase = `-- 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 (
$1, $2, $3, $4,
$5, $6, $7, $8,
$9, $10,
$11, $12, $13,
$14, $15,
$16, $17, $18,
$19, $20, $21,
$22, $23, $24
)
ON CONFLICT DO NOTHING
`
type InsertSupportCaseParams struct {
ID pgtype.UUID
CaseNumber string
OwnerID pgtype.UUID
CaseType string
Status string
Description string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
ComplaintReason pgtype.Text
RubricVersion pgtype.Int4
RubricOpeningID pgtype.UUID
RubricPolicyVersionID pgtype.UUID
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
DecisionReason pgtype.Text
DecisionAt pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// 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.
func (q *Queries) InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error) {
result, err := q.db.Exec(ctx, insertSupportCase,
arg.ID,
arg.CaseNumber,
arg.OwnerID,
arg.CaseType,
arg.Status,
arg.Description,
arg.ObjectType,
arg.ObjectID,
arg.AssessmentSpecialization,
arg.AssessmentGrade,
arg.ComplaintReason,
arg.RubricVersion,
arg.RubricOpeningID,
arg.RubricPolicyVersionID,
arg.TargetBusinessDays,
arg.TargetDueAt,
arg.TargetAnsweredAt,
arg.TargetPolicyVersion,
arg.TargetCalendarVersion,
arg.DecisionOutcome,
arg.DecisionReason,
arg.DecisionAt,
arg.CreatedAt,
arg.UpdatedAt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertSupportCaseCreateOutcome = `-- name: InsertSupportCaseCreateOutcome :exec
INSERT INTO support_case_create_outcomes (
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
) VALUES (
$1, $2,
CASE WHEN $2::text = 'created' THEN $3::jsonb END,
CASE WHEN $2::text = 'created' THEN $4::boolean END,
$5
)
`
type InsertSupportCaseCreateOutcomeParams struct {
ScopeHash []byte
OutcomeKind string
CaseSnapshot []byte
TargetWasLate bool
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseCreateOutcome,
arg.ScopeHash,
arg.OutcomeKind,
arg.CaseSnapshot,
arg.TargetWasLate,
arg.CreatedAt,
)
return err
}
const insertSupportCaseEvent = `-- name: InsertSupportCaseEvent :exec
INSERT INTO support_case_events (
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
) VALUES (
$1, $2, $3, $4,
$5, $6, $7
)
`
type InsertSupportCaseEventParams struct {
CaseID pgtype.UUID
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
func (q *Queries) InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseEvent,
arg.CaseID,
arg.Sequence,
arg.EventKind,
arg.ActorKind,
arg.OccurredAt,
arg.Status,
arg.Message,
)
return err
}
const insertSupportCaseRequestEvent = `-- name: InsertSupportCaseRequestEvent :exec
INSERT INTO support_case_request_events (owner_id, requested_at)
VALUES ($1, $2)
`
type InsertSupportCaseRequestEventParams struct {
OwnerID pgtype.UUID
RequestedAt pgtype.Timestamptz
}
func (q *Queries) InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error {
_, err := q.db.Exec(ctx, insertSupportCaseRequestEvent, arg.OwnerID, arg.RequestedAt)
return err
}
const latestSupportCaseRequestEvent = `-- name: LatestSupportCaseRequestEvent :one
SELECT requested_at
FROM support_case_request_events
WHERE owner_id = $1
ORDER BY requested_at DESC, id DESC
LIMIT 1
`
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
func (q *Queries) LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, latestSupportCaseRequestEvent, ownerID)
var requested_at pgtype.Timestamptz
err := row.Scan(&requested_at)
return requested_at, err
}
const listOwnedSupportCases = `-- name: ListOwnedSupportCases :many
WITH cursor_input AS MATERIALIZED (
SELECT
$3::timestamptz AS after_created_at,
$4::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 = $1
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 $2
`
type ListOwnedSupportCasesParams struct {
OwnerID pgtype.UUID
RowLimit int32
AfterCreatedAt pgtype.Timestamptz
AfterID pgtype.UUID
}
type ListOwnedSupportCasesRow struct {
ID pgtype.UUID
CaseNumber string
CaseType string
Status string
ObjectType pgtype.Text
ObjectID pgtype.UUID
AssessmentSpecialization pgtype.Text
AssessmentGrade pgtype.Text
TargetBusinessDays int32
TargetDueAt pgtype.Timestamptz
TargetAnsweredAt pgtype.Timestamptz
TargetPolicyVersion int32
TargetCalendarVersion int32
DecisionOutcome pgtype.Text
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
// and event history. The tuple cursor matches the composite sort key.
func (q *Queries) ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error) {
rows, err := q.db.Query(ctx, listOwnedSupportCases,
arg.OwnerID,
arg.RowLimit,
arg.AfterCreatedAt,
arg.AfterID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOwnedSupportCasesRow
for rows.Next() {
var i ListOwnedSupportCasesRow
if err := rows.Scan(
&i.ID,
&i.CaseNumber,
&i.CaseType,
&i.Status,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSupportCaseRequestBudget = `-- name: LockSupportCaseRequestBudget :exec
SELECT pg_advisory_xact_lock(
hashtextextended('lincodex.support.case.requests:' || $1::uuid::text, 0)
)
`
// Serialize per-owner budget checks even before the first event exists.
func (q *Queries) LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error {
_, err := q.db.Exec(ctx, lockSupportCaseRequestBudget, ownerID)
return err
}
const nextSupportCaseNumber = `-- name: NextSupportCaseNumber :one
WITH next_value AS MATERIALIZED (
SELECT nextval('support_case_number_seq') AS value
)
SELECT
'SC-' || $1::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
`
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
// request are expected and do not expose request contents.
func (q *Queries) NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error) {
row := q.db.QueryRow(ctx, nextSupportCaseNumber, utcYear)
var case_number interface{}
err := row.Scan(&case_number)
return case_number, err
}
const pruneSupportCaseRequestEvents = `-- name: PruneSupportCaseRequestEvents :execrows
WITH expired AS MATERIALIZED (
SELECT source.id
FROM support_case_request_events AS source
WHERE source.owner_id = $1
AND source.requested_at <= $2::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
`
type PruneSupportCaseRequestEventsParams struct {
OwnerID pgtype.UUID
At pgtype.Timestamptz
}
// Keep up to the maximum supported window, regardless of the current policy.
// The bounded delete prevents one create from doing unbounded cleanup work.
func (q *Queries) PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error) {
result, err := q.db.Exec(ctx, pruneSupportCaseRequestEvents, arg.OwnerID, arg.At)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const readOwnedSupportCase = `-- 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 = $1 AND owner_id = $2
`
type ReadOwnedSupportCaseParams struct {
CaseID pgtype.UUID
OwnerID pgtype.UUID
}
// Reads a full owner-scoped record. Object values are identifiers only.
func (q *Queries) ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error) {
row := q.db.QueryRow(ctx, readOwnedSupportCase, arg.CaseID, arg.OwnerID)
var i SupportCase
err := row.Scan(
&i.ID,
&i.CaseNumber,
&i.OwnerID,
&i.CaseType,
&i.Status,
&i.Description,
&i.ObjectType,
&i.ObjectID,
&i.AssessmentSpecialization,
&i.AssessmentGrade,
&i.ComplaintReason,
&i.RubricVersion,
&i.RubricOpeningID,
&i.RubricPolicyVersionID,
&i.TargetBusinessDays,
&i.TargetDueAt,
&i.TargetAnsweredAt,
&i.TargetPolicyVersion,
&i.TargetCalendarVersion,
&i.DecisionOutcome,
&i.DecisionReason,
&i.DecisionAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const readSupportCaseCreateOutcome = `-- name: ReadSupportCaseCreateOutcome :one
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
FROM support_case_create_outcomes
WHERE scope_hash = $1
`
type ReadSupportCaseCreateOutcomeRow struct {
OutcomeKind string
CaseSnapshot interface{}
TargetWasLate pgtype.Bool
}
func (q *Queries) ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error) {
row := q.db.QueryRow(ctx, readSupportCaseCreateOutcome, scopeHash)
var i ReadSupportCaseCreateOutcomeRow
err := row.Scan(&i.OutcomeKind, &i.CaseSnapshot, &i.TargetWasLate)
return i, err
}
const readSupportCaseEvents = `-- name: ReadSupportCaseEvents :many
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
FROM support_case_events
WHERE case_id = $1
ORDER BY sequence
`
type ReadSupportCaseEventsRow struct {
Sequence int32
EventKind string
ActorKind string
OccurredAt pgtype.Timestamptz
Status pgtype.Text
Message pgtype.Text
}
// Reads the immutable public history only after the case owner has matched.
func (q *Queries) ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error) {
rows, err := q.db.Query(ctx, readSupportCaseEvents, caseID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadSupportCaseEventsRow
for rows.Next() {
var i ReadSupportCaseEventsRow
if err := rows.Scan(
&i.Sequence,
&i.EventKind,
&i.ActorKind,
&i.OccurredAt,
&i.Status,
&i.Message,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,120 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support_rubrics.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const resolveCurrentSupportCaseRubrics = `-- 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 = $1
AND binding.grade = $2
ORDER BY opening.category
`
type ResolveCurrentSupportCaseRubricsParams struct {
Specialization string
Grade string
}
type ResolveCurrentSupportCaseRubricsRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
EffectivePolicyVersion pgtype.Int4
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// 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.
func (q *Queries) ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error) {
rows, err := q.db.Query(ctx, resolveCurrentSupportCaseRubrics, arg.Specialization, arg.Grade)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ResolveCurrentSupportCaseRubricsRow
for rows.Next() {
var i ResolveCurrentSupportCaseRubricsRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.EffectivePolicyVersion,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,618 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const maxSupportCaseSnapshotBytes = 1 << 20
var supportCaseConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "support_cases_owner_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "support_case_create_outcomes_scope_hash_fkey"}: outbound.ErrIdempotencyRecordNotFound,
}
var (
_ outbound.SupportCaseRepository = supportCaseRepository{}
_ outbound.SupportCaseCreateOutcomeRepository = supportCaseRepository{}
_ outbound.SupportCaseRequestLimitRepository = supportCaseRepository{}
_ outbound.SupportCaseRepositories = (*UnitOfWork)(nil)
)
func (unit *UnitOfWork) SupportCases() outbound.SupportCaseRepository {
return supportCaseRepository{queries: unit.queries}
}
func (unit *UnitOfWork) SupportCaseCreateOutcomes() outbound.SupportCaseCreateOutcomeRepository {
return supportCaseRepository{queries: unit.queries}
}
func (unit *UnitOfWork) SupportCaseRequestLimits() outbound.SupportCaseRequestLimitRepository {
return supportCaseRepository{queries: unit.queries}
}
type supportCaseRepository struct {
queries *sqlc.Queries
}
func (repository supportCaseRepository) NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) {
const location = "supportCaseRepository.NextNumber"
if createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 {
return "", fmt.Errorf("%s - creation time is invalid: %w", location, domain.ErrInvalidSupportCase)
}
value, err := repository.queries.NextSupportCaseNumber(ctx, fmt.Sprintf("%04d", createdAt.UTC().Year()))
if err != nil {
return "", fmt.Errorf("%s - allocate number: %w", location, mapSupportCaseError(err))
}
var number string
switch stored := value.(type) {
case string:
number = stored
case []byte:
number = string(stored)
default:
return "", fmt.Errorf("%s - database returned an invalid number type", location)
}
parsed, err := domain.ParseSupportCaseNumber(number)
if err != nil {
return "", fmt.Errorf("%s - database returned an invalid number", location)
}
return parsed, nil
}
func (repository supportCaseRepository) Create(ctx context.Context, supportCase domain.SupportCase) error {
const location = "supportCaseRepository.Create"
if supportCase.IsZero() {
return fmt.Errorf("%s - case is not initialized: %w", location, domain.ErrInvalidSupportCase)
}
snapshot := supportCase.Snapshot()
validated, err := domain.RestoreSupportCase(snapshot)
if err != nil {
return fmt.Errorf("%s - validate case: %w", location, err)
}
snapshot = validated.Snapshot()
row := supportCaseInsertParams(snapshot)
inserted, err := repository.queries.InsertSupportCase(ctx, row)
if err != nil {
return fmt.Errorf("%s - insert case: %w", location, mapSupportCaseError(err))
}
if inserted != 1 {
return fmt.Errorf("%s - unique business rule rejected the case: %w", location, outbound.ErrSupportCaseConflict)
}
for _, event := range snapshot.History {
if err := repository.queries.InsertSupportCaseEvent(ctx, supportCaseEventParams(snapshot.ID.UUID(), event)); err != nil {
return fmt.Errorf("%s - insert public event: %w", location, mapSupportCaseError(err))
}
}
return nil
}
func (repository supportCaseRepository) GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) {
const location = "supportCaseRepository.GetOwned"
if ownerID == uuid.Nil || caseID.IsZero() {
return domain.SupportCase{}, fmt.Errorf("%s - scope identifiers are invalid: %w", location, domain.ErrInvalidSupportCase)
}
row, err := repository.queries.ReadOwnedSupportCase(ctx, sqlc.ReadOwnedSupportCaseParams{
CaseID: pgUUID(caseID.UUID()), OwnerID: pgUUID(ownerID),
})
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - read owner-scoped case: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseNotFound))
}
events, err := repository.queries.ReadSupportCaseEvents(ctx, pgUUID(caseID.UUID()))
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - read public history: %w", location, mapSupportCaseError(err))
}
snapshot, err := supportCaseSnapshotFromRow(row, events)
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - restore stored case: %w", location, err)
}
if snapshot.OwnerID != ownerID || snapshot.ID != caseID {
return domain.SupportCase{}, fmt.Errorf("%s - stored case scope does not match query", location)
}
supportCase, err := domain.RestoreSupportCase(snapshot)
if err != nil {
return domain.SupportCase{}, fmt.Errorf("%s - validate stored case: %w", location, err)
}
return supportCase, nil
}
func (repository supportCaseRepository) ListOwned(ctx context.Context, query outbound.SupportCaseListQuery) (outbound.SupportCaseListPage, error) {
const location = "supportCaseRepository.ListOwned"
if query.OwnerID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxSupportCasePageSize {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - owner and page limit are invalid: %w", location, domain.ErrInvalidSupportCase)
}
params := sqlc.ListOwnedSupportCasesParams{OwnerID: pgUUID(query.OwnerID), RowLimit: query.Limit + 1}
if query.After != nil {
if query.After.ID.IsZero() || !validSupportCasePositionTime(query.After.CreatedAt) {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - cursor position is invalid: %w", location, domain.ErrInvalidSupportCase)
}
params.AfterCreatedAt = pgTime(query.After.CreatedAt.UTC())
params.AfterID = pgUUID(query.After.ID.UUID())
}
rows, err := repository.queries.ListOwnedSupportCases(ctx, params)
if err != nil {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - select owner-scoped summaries: %w", location, mapSupportCaseError(err))
}
page := outbound.SupportCaseListPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]domain.SupportCaseSummary, 0, len(rows))
for _, row := range rows {
summary, err := supportCaseSummaryFromRow(row)
if err != nil {
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - restore stored summary: %w", location, err)
}
page.Items = append(page.Items, summary)
}
return page, nil
}
func (repository supportCaseRepository) DeleteCreateOutcome(ctx context.Context, scope [outbound.IdempotencyDigestSize]byte) error {
const location = "supportCaseRepository.DeleteCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return fmt.Errorf("%s - idempotency scope must be set", location)
}
if err := repository.queries.DeleteSupportCaseCreateOutcome(ctx, scope[:]); err != nil {
return fmt.Errorf("%s - delete expired outcome: %w", location, mapSupportCaseError(err))
}
return nil
}
func (repository supportCaseRepository) SaveCreateOutcome(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
outcome domain.SupportCaseCreateOutcome,
createdAt time.Time,
) error {
const location = "supportCaseRepository.SaveCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) || !validSupportCasePositionTime(createdAt) {
return fmt.Errorf("%s - scope and creation time must be valid", location)
}
validated, err := domain.RestoreSupportCaseCreateOutcome(outcome.Snapshot())
if err != nil {
return fmt.Errorf("%s - validate outcome: %w", location, err)
}
snapshot := validated.Snapshot()
encoded := []byte(`{}`)
var targetWasLate bool
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
encoded, err = json.Marshal(snapshot.Case)
if err != nil {
return fmt.Errorf("%s - encode outcome snapshot", location)
}
if len(encoded) > maxSupportCaseSnapshotBytes {
return fmt.Errorf("%s - outcome snapshot exceeds its storage bound: %w", location, domain.ErrInvalidSupportCase)
}
targetWasLate = snapshot.TargetWasLate
}
if err := repository.queries.InsertSupportCaseCreateOutcome(ctx, sqlc.InsertSupportCaseCreateOutcomeParams{
ScopeHash: scope[:], OutcomeKind: string(snapshot.Kind), CaseSnapshot: encoded,
TargetWasLate: targetWasLate, CreatedAt: pgTime(createdAt.UTC().Truncate(time.Microsecond)),
}); err != nil {
return fmt.Errorf("%s - insert immutable outcome: %w", location, mapSupportCaseError(err))
}
return nil
}
func (repository supportCaseRepository) GetCreateOutcome(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
) (domain.SupportCaseCreateOutcome, error) {
const location = "supportCaseRepository.GetCreateOutcome"
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - idempotency scope must be set", location)
}
row, err := repository.queries.ReadSupportCaseCreateOutcome(ctx, scope[:])
if err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - read immutable outcome: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseCreateOutcomeNotFound))
}
snapshot := domain.SupportCaseCreateOutcomeSnapshot{Kind: domain.SupportCaseCreateOutcomeKind(row.OutcomeKind)}
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
encoded, ok := supportCaseJSONBytes(row.CaseSnapshot)
if !ok || len(encoded) == 0 || len(encoded) > maxSupportCaseSnapshotBytes || !row.TargetWasLate.Valid {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored created outcome is invalid", location)
}
var stored domain.SupportCaseSnapshot
if err := decodeSupportCaseJSON(encoded, &stored); err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored case snapshot is invalid", location)
}
snapshot.Case = &stored
snapshot.TargetWasLate = row.TargetWasLate.Bool
} else if row.TargetWasLate.Valid {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored failure outcome has a late flag", location)
}
outcome, err := domain.RestoreSupportCaseCreateOutcome(snapshot)
if err != nil {
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
}
return outcome, nil
}
func (repository supportCaseRepository) Consume(
ctx context.Context,
ownerID uuid.UUID,
at time.Time,
maxRequests int32,
window time.Duration,
) (outbound.SupportCaseRequestLimitResult, error) {
const location = "supportCaseRepository.Consume"
if ownerID == uuid.Nil || !validSupportCasePositionTime(at) || maxRequests < 1 || window < time.Second ||
window > domain.MaxSupportRequestWindow || window%time.Second != 0 {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - request budget parameters are invalid: %w", location, domain.ErrInvalidSupportCase)
}
at = at.UTC().Truncate(time.Microsecond)
if _, err := repository.queries.PruneSupportCaseRequestEvents(ctx, sqlc.PruneSupportCaseRequestEventsParams{
OwnerID: pgUUID(ownerID), At: pgTime(at),
}); err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - prune request history: %w", location, mapSupportCaseError(err))
}
windowStart := at.Add(-window)
count, err := repository.queries.CountSupportCaseRequestEvents(ctx, sqlc.CountSupportCaseRequestEventsParams{
OwnerID: pgUUID(ownerID), WindowStart: pgTime(windowStart), At: pgTime(at),
})
if err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - count request history: %w", location, mapSupportCaseError(err))
}
if count.EventCount >= int64(maxRequests) {
first, ok := supportCaseFirstEventTime(count.FirstInWindow)
if !ok {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - oldest qualifying event is missing", location)
}
retryAfter := first.Add(window).Sub(at)
if retryAfter <= 0 {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - retry interval is invalid", location)
}
return outbound.SupportCaseRequestLimitResult{Allowed: false, RetryAfter: retryAfter}, nil
}
if err := repository.queries.InsertSupportCaseRequestEvent(ctx, sqlc.InsertSupportCaseRequestEventParams{
OwnerID: pgUUID(ownerID), RequestedAt: pgTime(at),
}); err != nil {
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - record request: %w", location, mapSupportCaseError(err))
}
return outbound.SupportCaseRequestLimitResult{Allowed: true}, nil
}
func (repository supportCaseRepository) LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) {
const location = "supportCaseRepository.LockOwner"
if ownerID == uuid.Nil {
return time.Time{}, fmt.Errorf("%s - owner ID must be set", location)
}
if err := repository.queries.LockSupportCaseRequestBudget(ctx, pgUUID(ownerID)); err != nil {
return time.Time{}, fmt.Errorf("%s - take transaction lock: %w", location, mapSupportCaseError(err))
}
latest, err := repository.queries.LatestSupportCaseRequestEvent(ctx, pgUUID(ownerID))
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, fmt.Errorf("%s - read latest request timestamp: %w", location, mapSupportCaseError(err))
}
if !validSupportCasePositionTime(latest.Time) {
return time.Time{}, fmt.Errorf("%s - stored request timestamp is invalid", location)
}
return latest.Time.UTC().Truncate(time.Microsecond), nil
}
func supportCaseInsertParams(snapshot domain.SupportCaseSnapshot) sqlc.InsertSupportCaseParams {
return sqlc.InsertSupportCaseParams{
ID: pgUUID(snapshot.ID.UUID()), CaseNumber: snapshot.Number.String(), OwnerID: pgUUID(snapshot.OwnerID),
CaseType: string(snapshot.Type), Status: string(snapshot.Status), Description: snapshot.Description,
ObjectType: optionalSupportText(snapshot.Object, func(value *domain.SupportCaseReference) string { return string(value.Type) }),
ObjectID: optionalSupportUUID(snapshot.Object),
AssessmentSpecialization: optionalSupportAssessment(snapshot.AssessmentTarget, true),
AssessmentGrade: optionalSupportAssessment(snapshot.AssessmentTarget, false),
ComplaintReason: optionalSupportComplaint(snapshot.ComplaintReason), RubricVersion: optionalSupportInt32(snapshot.RubricVersion),
RubricOpeningID: optionalSupportUUIDPointer(snapshot.RubricOpeningID),
RubricPolicyVersionID: optionalSupportPolicyID(snapshot.RubricPolicyID),
TargetBusinessDays: int32(snapshot.ResponseTarget.BusinessDays), TargetDueAt: pgTime(snapshot.ResponseTarget.DueAt),
TargetAnsweredAt: pgOptionalTime(snapshot.ResponseTarget.AnsweredAt), TargetPolicyVersion: snapshot.ResponseTarget.PolicyVersion,
TargetCalendarVersion: snapshot.ResponseTarget.CalendarVersion,
DecisionOutcome: optionalSupportDecision(snapshot.Decision, true), DecisionReason: optionalSupportDecision(snapshot.Decision, false),
DecisionAt: optionalSupportDecisionTime(snapshot.Decision), CreatedAt: pgTime(snapshot.CreatedAt), UpdatedAt: pgTime(snapshot.UpdatedAt),
}
}
func supportCaseEventParams(caseID uuid.UUID, event domain.SupportCaseEventSnapshot) sqlc.InsertSupportCaseEventParams {
return sqlc.InsertSupportCaseEventParams{
CaseID: pgUUID(caseID), Sequence: event.Sequence, EventKind: string(event.Kind), ActorKind: string(event.Actor),
OccurredAt: pgTime(event.OccurredAt), Status: optionalSupportEventStatus(event.Status), Message: optionalSupportEventMessage(event.Message),
}
}
func supportCaseSnapshotFromRow(row sqlc.SupportCase, events []sqlc.ReadSupportCaseEventsRow) (domain.SupportCaseSnapshot, error) {
const location = "supportCaseSnapshotFromRow"
if !row.ID.Valid || !row.OwnerID.Valid || !row.TargetDueAt.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - required stored fields are missing", location)
}
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
if err != nil {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - case number is invalid", location)
}
snapshot := domain.SupportCaseSnapshot{
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, OwnerID: uuid.UUID(row.OwnerID.Bytes),
Type: domain.SupportCaseType(row.CaseType), Status: domain.SupportCaseStatus(row.Status), Description: row.Description,
Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
ComplaintReason: optionalSupportCaseComplaint(row.ComplaintReason), RubricVersion: optionalSupportCaseInt4(row.RubricVersion),
RubricOpeningID: optionalSupportCaseUUID(row.RubricOpeningID),
RubricPolicyID: optionalSupportCasePolicyID(row.RubricPolicyVersionID),
ResponseTarget: domain.SupportResponseTargetSnapshot{
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
CalendarVersion: row.TargetCalendarVersion,
},
Decision: supportCaseDecisionFromColumns(row.DecisionOutcome, row.DecisionReason, row.DecisionAt),
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
History: make([]domain.SupportCaseEventSnapshot, 0, len(events)),
}
for _, stored := range events {
if !stored.OccurredAt.Valid {
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - stored event timestamp is missing", location)
}
snapshot.History = append(snapshot.History, domain.SupportCaseEventSnapshot{
Sequence: stored.Sequence, Kind: domain.SupportCaseEventKind(stored.EventKind), Actor: domain.SupportCaseActorKind(stored.ActorKind),
OccurredAt: stored.OccurredAt.Time, Status: optionalSupportCaseStatus(stored.Status), Message: optionalSupportCaseText(stored.Message),
})
}
return snapshot, nil
}
func supportCaseSummaryFromRow(row sqlc.ListOwnedSupportCasesRow) (domain.SupportCaseSummary, error) {
const location = "supportCaseSummaryFromRow"
if !row.ID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || !row.TargetDueAt.Valid {
return domain.SupportCaseSummary{}, fmt.Errorf("%s - required stored fields are missing", location)
}
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
if err != nil {
return domain.SupportCaseSummary{}, fmt.Errorf("%s - case number is invalid", location)
}
summary := domain.SupportCaseSummary{
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, Type: domain.SupportCaseType(row.CaseType),
Status: domain.SupportCaseStatus(row.Status), Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
ResponseTarget: domain.SupportResponseTargetSnapshot{
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
CalendarVersion: row.TargetCalendarVersion,
},
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
if row.DecisionOutcome.Valid {
outcome := domain.SupportCaseDecisionOutcome(row.DecisionOutcome.String)
summary.DecisionOutcome = &outcome
}
return domain.RestoreSupportCaseSummary(summary)
}
func supportCaseReferenceFromColumns(objectType pgtype.Text, objectID pgtype.UUID) *domain.SupportCaseReference {
if !objectType.Valid && !objectID.Valid {
return nil
}
return &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(objectType.String), ID: uuid.UUID(objectID.Bytes)}
}
func supportCaseAssessmentFromColumns(specialization, grade pgtype.Text) *domain.SupportCaseAssessmentTarget {
if !specialization.Valid && !grade.Valid {
return nil
}
return &domain.SupportCaseAssessmentTarget{
Specialization: domain.SpecializationCode(specialization.String), Grade: domain.GradeCode(grade.String),
}
}
func supportCaseDecisionFromColumns(outcome, reason pgtype.Text, at pgtype.Timestamptz) *domain.SupportCaseDecisionSnapshot {
if !outcome.Valid && !reason.Valid && !at.Valid {
return nil
}
return &domain.SupportCaseDecisionSnapshot{
Outcome: domain.SupportCaseDecisionOutcome(outcome.String), Reason: reason.String, DecidedAt: at.Time,
}
}
func optionalSupportText[T any](value *T, selectValue func(*T) string) pgtype.Text {
if value == nil {
return pgtype.Text{}
}
return pgText(selectValue(value))
}
func optionalSupportUUID(reference *domain.SupportCaseReference) pgtype.UUID {
if reference == nil {
return pgtype.UUID{}
}
return pgUUID(reference.ID)
}
func optionalSupportUUIDPointer(value *uuid.UUID) pgtype.UUID {
if value == nil {
return pgtype.UUID{}
}
return pgUUID(*value)
}
func optionalSupportPolicyID(value *domain.PolicyVersionID) pgtype.UUID {
if value == nil {
return pgtype.UUID{}
}
return pgUUID(value.UUID())
}
func optionalSupportAssessment(target *domain.SupportCaseAssessmentTarget, specialization bool) pgtype.Text {
if target == nil {
return pgtype.Text{}
}
if specialization {
return pgText(string(target.Specialization))
}
return pgText(string(target.Grade))
}
func optionalSupportComplaint(reason *domain.SupportCaseComplaintReason) pgtype.Text {
if reason == nil {
return pgtype.Text{}
}
return pgText(string(*reason))
}
func optionalSupportInt32(value *int32) pgtype.Int4 {
if value == nil {
return pgtype.Int4{}
}
return pgtype.Int4{Int32: *value, Valid: true}
}
func optionalSupportDecision(decision *domain.SupportCaseDecisionSnapshot, outcome bool) pgtype.Text {
if decision == nil {
return pgtype.Text{}
}
if outcome {
return pgText(string(decision.Outcome))
}
return pgText(decision.Reason)
}
func optionalSupportDecisionTime(decision *domain.SupportCaseDecisionSnapshot) pgtype.Timestamptz {
if decision == nil {
return pgtype.Timestamptz{}
}
return pgTime(decision.DecidedAt)
}
func optionalSupportEventStatus(status *domain.SupportCaseStatus) pgtype.Text {
if status == nil {
return pgtype.Text{}
}
return pgText(string(*status))
}
func optionalSupportEventMessage(message *string) pgtype.Text {
if message == nil {
return pgtype.Text{}
}
return pgText(*message)
}
func optionalSupportCaseComplaint(value pgtype.Text) *domain.SupportCaseComplaintReason {
if !value.Valid {
return nil
}
result := domain.SupportCaseComplaintReason(value.String)
return &result
}
func optionalSupportCaseInt4(value pgtype.Int4) *int32 {
if !value.Valid {
return nil
}
return &value.Int32
}
func optionalSupportCaseUUID(value pgtype.UUID) *uuid.UUID {
if !value.Valid {
return nil
}
result := uuid.UUID(value.Bytes)
return &result
}
func optionalSupportCasePolicyID(value pgtype.UUID) *domain.PolicyVersionID {
if !value.Valid {
return nil
}
result := domain.PolicyVersionID(value.Bytes)
return &result
}
func optionalSupportCaseStatus(value pgtype.Text) *domain.SupportCaseStatus {
if !value.Valid {
return nil
}
result := domain.SupportCaseStatus(value.String)
return &result
}
func optionalSupportCaseText(value pgtype.Text) *string {
if !value.Valid {
return nil
}
result := value.String
return &result
}
func supportCaseFirstEventTime(value any) (time.Time, bool) {
switch typed := value.(type) {
case time.Time:
return typed, !typed.IsZero()
case pgtype.Timestamptz:
return typed.Time, typed.Valid && !typed.Time.IsZero()
case *time.Time:
if typed != nil {
return *typed, !typed.IsZero()
}
case nil:
return time.Time{}, false
}
return time.Time{}, false
}
func supportCaseJSONBytes(value any) ([]byte, bool) {
switch typed := value.(type) {
case string:
return []byte(typed), true
case []byte:
return typed, true
default:
return nil, false
}
}
func decodeSupportCaseJSON(encoded []byte, destination any) error {
decoder := json.NewDecoder(bytes.NewReader(encoded))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return err
}
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
return errors.New("stored support case snapshot contains trailing data")
}
return nil
}
func validSupportCasePositionTime(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 &&
value.Nanosecond()%int(time.Microsecond) == 0
}
func mapSupportCaseNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapSupportCaseError(err)
}
func mapSupportCaseError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
key := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
if sentinel, ok := supportCaseConstraintErrors[key]; ok {
return fmt.Errorf("postgres.mapSupportCaseError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
@@ -0,0 +1,152 @@
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.SupportCaseRubricRepository = supportCaseRubricRepository{}
type supportCaseRubricRepository struct {
queries *sqlc.Queries
bank assessmentBankRepository
}
func (unit *UnitOfWork) SupportCaseRubrics() outbound.SupportCaseRubricRepository {
return supportCaseRubricRepository{
queries: unit.queries,
bank: assessmentBankRepository{queries: unit.queries, transactional: true},
}
}
func (repository supportCaseRubricRepository) ResolveCurrent(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) (*outbound.SupportCaseRubric, error) {
const location = "supportCaseRubricRepository.ResolveCurrent"
if !repository.bank.transactional {
return nil, fmt.Errorf("%s - rubric resolution needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
}
if !specialization.IsKnown() || !grade.IsKnown() {
return nil, fmt.Errorf("%s - target is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
row, available, err := repository.currentUniqueOpening(ctx, specialization, grade)
if err != nil {
return nil, fmt.Errorf("%s - resolve current target opening: %w", location, err)
}
if !available {
return nil, nil
}
selectionRow := supportRubricSelectionRow(row)
selection, err := repository.bank.currentSelectionFromRow(ctx, selectionRow)
if err != nil {
return nil, fmt.Errorf("%s - validate reviewed rubric manifest: %w", location, err)
}
if !supportRubricSelectionMatches(selection, row) {
return nil, fmt.Errorf("%s - current rubric pin changed during resolution: %w", location, outbound.ErrAssessmentSelectionUnavailable)
}
return &outbound.SupportCaseRubric{
Version: selection.ProductPolicyVersion,
OpeningID: selection.Opening.ID,
PolicyVersionID: selection.Opening.PolicyVersionID,
}, nil
}
func (repository supportCaseRubricRepository) currentUniqueOpening(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool, error) {
initial, err := repository.currentRows(ctx, specialization, grade)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("read current target bindings: %w", err)
}
initialRow, unique := uniqueSupportRubricOpening(initial)
if !unique {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
}
category, err := domain.ParseAssessmentCategory(initialRow.Category)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("parse current category: %w", domain.ErrInvalidAssessmentFamily)
}
if err := repository.bank.LockCategory(ctx, category); err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("lock current category: %w", err)
}
current, err := repository.currentRows(ctx, specialization, grade)
if err != nil {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("recheck current target bindings: %w", err)
}
currentRow, unique := uniqueSupportRubricOpening(current)
if !unique || currentRow.OpeningID.Bytes != initialRow.OpeningID.Bytes {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
}
return currentRow, true, nil
}
func supportRubricSelectionMatches(
selection outbound.AssessmentBankSelection,
row sqlc.ResolveCurrentSupportCaseRubricsRow,
) bool {
return selection.ProductPolicyVersion > 0 && !selection.Opening.PolicyVersionID.IsZero() &&
selection.Opening.ID == row.OpeningID.Bytes &&
selection.Opening.PolicyVersionID == domain.PolicyVersionID(row.PolicyVersionID.Bytes) &&
selection.ProductPolicyVersion == row.EffectivePolicyVersion.Int32
}
func (repository supportCaseRubricRepository) currentRows(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) ([]sqlc.ResolveCurrentSupportCaseRubricsRow, error) {
rows, err := repository.queries.ResolveCurrentSupportCaseRubrics(ctx, sqlc.ResolveCurrentSupportCaseRubricsParams{
Specialization: string(specialization), Grade: string(grade),
})
if err != nil {
return nil, mapAssessmentError(err)
}
current := make([]sqlc.ResolveCurrentSupportCaseRubricsRow, 0, len(rows))
for _, row := range rows {
metadata, available, err := currentAssessmentSelectionMetadata(supportRubricSelectionRow(row))
if err != nil {
return nil, fmt.Errorf("validate current catalog binding: %w", err)
}
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade {
continue
}
current = append(current, row)
}
return current, nil
}
func supportRubricSelectionRow(row sqlc.ResolveCurrentSupportCaseRubricsRow) sqlc.ResolveCurrentAssessmentSelectionRow {
return sqlc.ResolveCurrentAssessmentSelectionRow(row)
}
func uniqueSupportRubricOpening(
rows []sqlc.ResolveCurrentSupportCaseRubricsRow,
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool) {
var selected sqlc.ResolveCurrentSupportCaseRubricsRow
seen := make(map[uuid.UUID]struct{}, len(rows))
for _, row := range rows {
if !row.OpeningID.Valid || row.OpeningID.Bytes == uuid.Nil {
continue
}
if _, exists := seen[row.OpeningID.Bytes]; exists {
continue
}
seen[row.OpeningID.Bytes] = struct{}{}
if len(seen) > 1 {
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false
}
selected = row
}
return selected, len(seen) == 1
}
@@ -37,6 +37,7 @@ func NewTransactor(pool *pgxpool.Pool) *Transactor {
}
var _ outbound.Transactor = (*Transactor)(nil)
var _ outbound.ReadOnlySnapshotTransactor = (*Transactor)(nil)
// transactionContextKey marks a context passed to a transaction callback so a
// nested WithinTransaction call fails instead of opening a second connection.
@@ -81,6 +82,42 @@ func (transactor *Transactor) WithinTransaction(
return nil
}
// WithinReadOnlySnapshot runs a callback against one repeatable-read snapshot.
// PostgreSQL rejects writes made through the supplied UnitOfWork.
func (transactor *Transactor) WithinReadOnlySnapshot(
ctx context.Context,
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
) error {
if ctx.Value(transactionContextKey{}) != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", outbound.ErrNestedTransaction)
}
options := pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}
tx, err := transactor.pool.BeginTx(ctx, options)
if err != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", sanitizeConnectError(err))
}
finished := false
defer func() {
if !finished {
_ = rollback(ctx, tx)
}
}()
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
finished = true
if fnErr != nil {
fnErr = markTransactionConflict(fnErr)
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinReadOnlySnapshot - roll back transaction: %w", rollbackErr))
}
return fnErr
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - commit transaction: %w", markTransactionConflict(err))
}
return nil
}
func rollback(ctx context.Context, tx pgx.Tx) error {
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
defer cancel()