381 lines
15 KiB
Go
381 lines
15 KiB
Go
package assessment
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
assessmentSignalOperation = "assessment_attempt.signals"
|
|
assessmentSignalRateWindow = time.Minute
|
|
assessmentSignalMaxReceipts = int64(30)
|
|
assessmentSignalMaxEvents = int64(10000)
|
|
assessmentSignalTimestampSkew = 5 * time.Minute
|
|
assessmentSignalMaximumBodySize = 32 << 10
|
|
assessmentSignalMaximumEvents = 50
|
|
)
|
|
|
|
var (
|
|
ErrAttemptSignalForbidden = errors.New("assessment signals are forbidden")
|
|
ErrAttemptSignalConsentRequired = errors.New("assessment signals require current C3 consent")
|
|
ErrAttemptSignalStateConflict = errors.New("assessment attempt cannot accept signals")
|
|
ErrAttemptSignalRateLimited = errors.New("assessment signal receipt rate limit exceeded")
|
|
ErrInvalidAttemptSignalRequest = errors.New("invalid assessment signal request")
|
|
)
|
|
|
|
// SignalRateLimitError carries the first time a new receipt can be retried.
|
|
// Its message contains no candidate, attempt, or event data.
|
|
type SignalRateLimitError struct {
|
|
RetryAt time.Time
|
|
}
|
|
|
|
func (limitError *SignalRateLimitError) Error() string {
|
|
return ErrAttemptSignalRateLimited.Error()
|
|
}
|
|
|
|
func (limitError *SignalRateLimitError) Unwrap() error {
|
|
return ErrAttemptSignalRateLimited
|
|
}
|
|
|
|
// SignalService stores bounded client-reported event metadata for real
|
|
// assessment attempts. The signals do not participate in grading.
|
|
type SignalService struct {
|
|
transactor outbound.Transactor
|
|
keyring Keyring
|
|
clock func() time.Time
|
|
}
|
|
|
|
func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) {
|
|
if transactor == nil || keyring == nil || clock == nil {
|
|
return nil, errors.New("assessment.NewSignalService - every dependency must be set")
|
|
}
|
|
return &SignalService{transactor: transactor, keyring: keyring, clock: clock}, nil
|
|
}
|
|
|
|
type RecordSignalsCommand struct {
|
|
ActorID uuid.UUID
|
|
AttemptID domain.AssessmentAttemptID
|
|
IdempotencyKey string
|
|
Events []domain.AssessmentSignalEvent
|
|
}
|
|
|
|
type canonicalSignalRequest struct {
|
|
AttemptID string `json:"attempt_id"`
|
|
Events []canonicalSignalEvent `json:"events"`
|
|
}
|
|
|
|
type canonicalSignalEvent struct {
|
|
Kind domain.AssessmentSignalKind `json:"kind"`
|
|
ItemInstanceID uuid.UUID `json:"item_instance_id"`
|
|
OccurredAt time.Time `json:"occurred_at"`
|
|
DurationMS *int32 `json:"duration_ms,omitempty"`
|
|
SizeBytes *int32 `json:"size_bytes,omitempty"`
|
|
}
|
|
|
|
type signalIdempotencyRequest struct {
|
|
scope outbound.AssessmentAttemptIdempotencyScope
|
|
record outbound.IdempotencyRecord
|
|
}
|
|
|
|
// RecordSignals stores all events in a batch or stores none. A replay returns
|
|
// the original receipt without rechecking or repeating storage effects.
|
|
func (service *SignalService) RecordSignals(
|
|
ctx context.Context,
|
|
command RecordSignalsCommand,
|
|
) (domain.AssessmentSignalReceipt, error) {
|
|
const location = "SignalService.RecordSignals"
|
|
canonicalEvents, body, err := canonicalSignalBody(command)
|
|
if err != nil {
|
|
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate request: %w", location, err)
|
|
}
|
|
now, err := assessmentIdempotencyTime(service.clock())
|
|
if err != nil {
|
|
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - validate application time: %w", location, err)
|
|
}
|
|
request, err := service.prepareSignalIdempotency(command, body, now)
|
|
if err != nil {
|
|
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - prepare idempotency: %w", location, err)
|
|
}
|
|
|
|
var receipt domain.AssessmentSignalReceipt
|
|
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
|
|
return err
|
|
}
|
|
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - reserve idempotency: %w", location, err)
|
|
}
|
|
repository := unit.AssessmentSignals()
|
|
if !created {
|
|
if stored.Fingerprint != request.record.Fingerprint {
|
|
return fmt.Errorf("%s - compare request fingerprint: %w", location, ErrAttemptKeyReused)
|
|
}
|
|
if err := requireReplayableSignalAttempt(ctx, unit, command); err != nil {
|
|
return fmt.Errorf("%s - verify owner-scoped attempt before replay: %w", location, err)
|
|
}
|
|
receipt, err = repository.GetOutcome(ctx, request.scope)
|
|
if err != nil {
|
|
if errors.Is(err, outbound.ErrAssessmentSignalOutcomeNotFound) {
|
|
if attemptErr := requireReplayableSignalAttempt(ctx, unit, command); attemptErr != nil {
|
|
return fmt.Errorf("%s - verify attempt after missing receipt: %w", location, attemptErr)
|
|
}
|
|
}
|
|
return fmt.Errorf("%s - read immutable receipt: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
if err := repository.DeleteExpiredOutcome(ctx, request.scope); err != nil {
|
|
return fmt.Errorf("%s - remove expired receipt: %w", location, err)
|
|
}
|
|
return service.recordNewSignals(ctx, unit, repository, command, canonicalEvents, request.scope, &receipt)
|
|
})
|
|
if err != nil {
|
|
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - transaction: %w", location, err)
|
|
}
|
|
return receipt, nil
|
|
}
|
|
|
|
func requireReplayableSignalAttempt(ctx context.Context, unit outbound.UnitOfWork, command RecordSignalsCommand) error {
|
|
const location = "SignalService.requireReplayableSignalAttempt"
|
|
kind, err := unit.AssessmentAttempts().GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
|
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
|
return fmt.Errorf("%s - owner-scoped attempt is missing: %w", location, ErrAttemptNotFound)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
|
}
|
|
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
|
|
return fmt.Errorf("%s - training attempts do not have signal receipts: %w", location, ErrAttemptSignalStateConflict)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (service *SignalService) recordNewSignals(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
repository outbound.AssessmentSignalRepository,
|
|
command RecordSignalsCommand,
|
|
events []domain.AssessmentSignalEvent,
|
|
scope outbound.AssessmentAttemptIdempotencyScope,
|
|
receipt *domain.AssessmentSignalReceipt,
|
|
) error {
|
|
const location = "SignalService.recordNewSignals"
|
|
attempt, err := lockAttemptForSignals(ctx, unit, command)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - lock attempt and C3 consent: %w", location, err)
|
|
}
|
|
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
|
|
}
|
|
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
|
|
if !attempt.IsActive() || !databaseTime.Before(attempt.ExpiresAt()) {
|
|
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptSignalStateConflict)
|
|
}
|
|
if err := validateSignalItemsAndTimes(attempt, events, databaseTime); err != nil {
|
|
return fmt.Errorf("%s - validate item binding and timestamp: %w", location, err)
|
|
}
|
|
if err := checkSignalReceiptRate(ctx, repository, attempt.ID(), databaseTime); err != nil {
|
|
return fmt.Errorf("%s - check receipt rate: %w", location, err)
|
|
}
|
|
status, acceptedCount, err := service.persistSignalBatch(ctx, repository, attempt.ID(), events, databaseTime)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - persist bounded event batch: %w", location, err)
|
|
}
|
|
newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build receipt: %w", location, err)
|
|
}
|
|
if err := repository.SaveOutcome(ctx, scope, attempt.ID(), newReceipt); err != nil {
|
|
return fmt.Errorf("%s - store immutable receipt: %w", location, err)
|
|
}
|
|
*receipt = newReceipt
|
|
return nil
|
|
}
|
|
|
|
func lockAttemptForSignals(
|
|
ctx context.Context,
|
|
unit outbound.UnitOfWork,
|
|
command RecordSignalsCommand,
|
|
) (domain.AssessmentAttempt, error) {
|
|
const location = "SignalService.lockAttemptForSignals"
|
|
attempts := unit.AssessmentAttempts()
|
|
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
|
|
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
|
|
}
|
|
if err != nil {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
|
|
}
|
|
if kind != domain.AssessmentAttemptKindRoot && kind != domain.AssessmentAttemptKindCorrective {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - training attempts do not accept signals: %w", location, ErrAttemptSignalStateConflict)
|
|
}
|
|
if _, err := unit.ConsentLedger().LockCurrentForUse(ctx, command.ActorID, domain.ConsentPurposeAutoCategorization); err != nil {
|
|
if errors.Is(err, outbound.ErrConsentNotFound) {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - require current C3 consent: %w", location, ErrAttemptSignalConsentRequired)
|
|
}
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock current C3 consent: %w", location, err)
|
|
}
|
|
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
|
|
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
|
|
}
|
|
if err != nil {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
|
}
|
|
if attempt.Kind() != kind {
|
|
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt kind changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
|
}
|
|
return attempt, nil
|
|
}
|
|
|
|
func checkSignalReceiptRate(
|
|
ctx context.Context,
|
|
repository outbound.AssessmentSignalRepository,
|
|
attemptID domain.AssessmentAttemptID,
|
|
databaseTime time.Time,
|
|
) error {
|
|
const location = "SignalService.checkSignalReceiptRate"
|
|
count, oldest, err := repository.CountRecentOutcomes(ctx, attemptID, databaseTime.Add(-assessmentSignalRateWindow))
|
|
if err != nil {
|
|
return fmt.Errorf("%s - count recent receipts: %w", location, err)
|
|
}
|
|
if count < assessmentSignalMaxReceipts {
|
|
return nil
|
|
}
|
|
retryAt := oldest.Add(assessmentSignalRateWindow).UTC().Truncate(time.Microsecond)
|
|
if !retryAt.After(databaseTime) {
|
|
retryAt = databaseTime.Add(time.Second).Truncate(time.Second)
|
|
}
|
|
return fmt.Errorf("%s - wait for the next receipt window: %w", location, &SignalRateLimitError{RetryAt: retryAt})
|
|
}
|
|
|
|
func (service *SignalService) persistSignalBatch(
|
|
ctx context.Context,
|
|
repository outbound.AssessmentSignalRepository,
|
|
attemptID domain.AssessmentAttemptID,
|
|
events []domain.AssessmentSignalEvent,
|
|
databaseTime time.Time,
|
|
) (domain.AssessmentSignalReceiptStatus, int32, error) {
|
|
const location = "SignalService.persistSignalBatch"
|
|
acceptedCount, err := assessmentSignalEventCount(len(events))
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("%s - event count is invalid: %w", location, err)
|
|
}
|
|
storedCount, err := repository.CountAttemptEvents(ctx, attemptID)
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("%s - count stored events: %w", location, err)
|
|
}
|
|
if storedCount+int64(len(events)) > assessmentSignalMaxEvents {
|
|
return domain.AssessmentSignalReceiptSaturated, 0, nil
|
|
}
|
|
batchID, err := uuid.NewV7()
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("%s - generate batch ID: %w", location, err)
|
|
}
|
|
batch, err := domain.NewAssessmentSignalBatch(batchID, attemptID, databaseTime, events)
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("%s - build event batch: %w", location, err)
|
|
}
|
|
if err := repository.SaveBatch(ctx, batch); err != nil {
|
|
return "", 0, fmt.Errorf("%s - store event batch: %w", location, err)
|
|
}
|
|
return domain.AssessmentSignalReceiptAccepted, acceptedCount, nil
|
|
}
|
|
|
|
func assessmentSignalEventCount(count int) (int32, error) {
|
|
if count < 1 || count > assessmentSignalMaximumEvents {
|
|
return 0, ErrInvalidAttemptSignalRequest
|
|
}
|
|
return int32(count), nil
|
|
}
|
|
|
|
func (service *SignalService) prepareSignalIdempotency(
|
|
command RecordSignalsCommand,
|
|
body []byte,
|
|
now time.Time,
|
|
) (signalIdempotencyRequest, error) {
|
|
if !validAttemptIdempotencyKey(command.IdempotencyKey) {
|
|
return signalIdempotencyRequest{}, ErrInvalidAttemptKey
|
|
}
|
|
expiresAt := now.Add(outbound.IdempotencyRetention)
|
|
if !expiresAt.After(now) || expiresAt.Year() > 9999 {
|
|
return signalIdempotencyRequest{}, ErrInvalidAttemptSignalRequest
|
|
}
|
|
scopeBytes := service.keyring.IdempotencyScope(assessmentSignalOperation, command.IdempotencyKey, command.ActorID.String())
|
|
return signalIdempotencyRequest{
|
|
scope: outbound.AssessmentAttemptIdempotencyScope(scopeBytes),
|
|
record: outbound.IdempotencyRecord{
|
|
Scope: scopeBytes, Fingerprint: service.keyring.Fingerprint(body), CreatedAt: now, ExpiresAt: expiresAt,
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func canonicalSignalBody(command RecordSignalsCommand) ([]domain.AssessmentSignalEvent, []byte, error) {
|
|
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || len(command.Events) == 0 || len(command.Events) > assessmentSignalMaximumEvents {
|
|
return nil, nil, ErrInvalidAttemptSignalRequest
|
|
}
|
|
canonical := canonicalSignalRequest{AttemptID: command.AttemptID.String(), Events: make([]canonicalSignalEvent, 0, len(command.Events))}
|
|
validated := make([]domain.AssessmentSignalEvent, 0, len(command.Events))
|
|
for _, event := range command.Events {
|
|
duration, hasDuration := event.DurationMS()
|
|
size, hasSize := event.SizeBytes()
|
|
input := domain.AssessmentSignalEventInput{
|
|
Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt(),
|
|
}
|
|
encodedEvent := canonicalSignalEvent{Kind: event.Kind(), ItemInstanceID: event.ItemInstanceID(), OccurredAt: event.OccurredAt()}
|
|
if hasDuration {
|
|
input.DurationMS = &duration
|
|
encodedEvent.DurationMS = &duration
|
|
}
|
|
if hasSize {
|
|
input.SizeBytes = &size
|
|
encodedEvent.SizeBytes = &size
|
|
}
|
|
checked, err := domain.NewAssessmentSignalEvent(input)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("%w", ErrInvalidAttemptSignalRequest)
|
|
}
|
|
validated = append(validated, checked)
|
|
canonical.Events = append(canonical.Events, encodedEvent)
|
|
}
|
|
body, err := json.Marshal(canonical)
|
|
if err != nil || len(body) == 0 || len(body) > assessmentSignalMaximumBodySize {
|
|
return nil, nil, ErrInvalidAttemptSignalRequest
|
|
}
|
|
return validated, body, nil
|
|
}
|
|
|
|
func validateSignalItemsAndTimes(
|
|
attempt domain.AssessmentAttempt,
|
|
events []domain.AssessmentSignalEvent,
|
|
databaseTime time.Time,
|
|
) error {
|
|
snapshot := attempt.Snapshot()
|
|
itemIDs := make(map[uuid.UUID]struct{}, len(snapshot.Items))
|
|
for _, item := range snapshot.Items {
|
|
itemIDs[item.ID] = struct{}{}
|
|
}
|
|
earliest := snapshot.CreatedAt.UTC().Add(-assessmentSignalTimestampSkew)
|
|
latest := databaseTime.Add(assessmentSignalTimestampSkew)
|
|
for _, event := range events {
|
|
if _, exists := itemIDs[event.ItemInstanceID()]; !exists {
|
|
return ErrInvalidAttemptSignalRequest
|
|
}
|
|
occurredAt := event.OccurredAt()
|
|
if occurredAt.Before(earliest) || occurredAt.After(latest) {
|
|
return ErrInvalidAttemptSignalRequest
|
|
}
|
|
}
|
|
return nil
|
|
}
|