Files

263 lines
11 KiB
Go

package assessment
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrAttemptWorkSessionBusy reports that another open page holds the work
// session of the attempt. It lasts until that page releases the session or
// stops renewing it, so it is never stored under an idempotency key.
ErrAttemptWorkSessionBusy = errors.New("assessment work session is held by another page")
// ErrAttemptWorkSessionState reports an attempt that has no work session to
// hold: a training run, or an attempt that has ended or is past its deadline.
ErrAttemptWorkSessionState = errors.New("assessment attempt has no work session to hold")
// ErrInvalidWorkSessionClient reports a page identifier of the wrong shape.
ErrInvalidWorkSessionClient = errors.New("invalid assessment work session client")
)
const (
minWorkClientBytes = 16
maxWorkClientBytes = 64
)
// WorkSessionDigester derives the keyed digest that stands for an open page in
// the stored lease. The digest binds the attempt and cannot be turned back into
// the identifier the page generated.
type WorkSessionDigester interface {
AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest
AssessmentDigestKeyVersion() int16
}
// WorkSessions keeps one open page per real attempt: the page that holds the
// work session of the attempt works on it, and any other page is refused until
// the holder closes or stops renewing. It does not change an attempt, a result,
// or a score, and it is a convenience rule, not a security boundary: a client
// that never holds the session is refused only while another page does.
type WorkSessions struct {
transactor outbound.Transactor
digester WorkSessionDigester
observer *SignalObserver
}
// NewWorkSessions fails at startup when a dependency is missing.
func NewWorkSessions(transactor outbound.Transactor, digester WorkSessionDigester) (*WorkSessions, error) {
if transactor == nil || digester == nil {
return nil, errors.New("assessment.NewWorkSessions - every dependency must be set")
}
return &WorkSessions{transactor: transactor, digester: digester}, nil
}
// WithSignalObserver makes every hold write an origin mark, which is when a
// switch to another session, network, or User-Agent is noticed.
func (sessions *WorkSessions) WithSignalObserver(observer *SignalObserver) *WorkSessions {
sessions.observer = observer
return sessions
}
// WithWorkSessions makes the answer and session commands refuse a page that
// does not hold the work session while another page does.
func (service *AttemptService) WithWorkSessions(sessions *WorkSessions) *AttemptService {
service.workSessions = sessions
return service
}
// HoldWorkSessionCommand is one hold or renewal from an open page.
type HoldWorkSessionCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
// Client is the identifier the page generated when it loaded.
Client string
Origin RequestOrigin
}
// WorkSessionHold is the answer to a hold: when it ends unless renewed, and how
// often the page renews it.
type WorkSessionHold struct {
HeldUntil time.Time
RenewEvery time.Duration
}
// Hold makes the page the holder of the work session, or renews its hold. It
// refuses with ErrAttemptWorkSessionBusy while another page holds it. The
// request origin of an accepted hold is recorded for the server signals.
func (sessions *WorkSessions) Hold(ctx context.Context, command HoldWorkSessionCommand) (WorkSessionHold, error) {
const location = "WorkSessions.Hold"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
return WorkSessionHold{}, fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
}
var hold WorkSessionHold
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
attempts := unit.AssessmentAttempts()
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if !isRealAttemptKind(kind) {
return fmt.Errorf("%s - a training run has no protected work session: %w", location, ErrAttemptWorkSessionState)
}
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
return fmt.Errorf("%s - authorize work session: %w", location, err)
}
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after attempt lock: %w", location, err)
}
now := databaseTime.UTC().Truncate(time.Microsecond)
if !attempt.IsActive() || !now.Before(attempt.ExpiresAt()) {
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptWorkSessionState)
}
hold, err = sessions.holdInTransaction(ctx, unit, attempt.ID(), command, now)
return err
})
if err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return hold, nil
}
func (sessions *WorkSessions) holdInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
attemptID domain.AssessmentAttemptID,
command HoldWorkSessionCommand,
now time.Time,
) (WorkSessionHold, error) {
const location = "WorkSessions.holdInTransaction"
leases := unit.AssessmentWorkLeases()
holder := sessions.digester.AssessmentWorkClientDigest(attemptID.UUID(), command.Client)
current, found, err := leases.Get(ctx, attemptID)
if err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - read lease: %w", location, err)
}
if found && !current.AdmitsHolder(holder, now) {
return WorkSessionHold{}, fmt.Errorf("%s - another page holds the session until %s: %w", location, current.HeldUntil().Format(time.RFC3339), ErrAttemptWorkSessionBusy)
}
next := current.Held(attemptID, holder, sessions.digester.AssessmentDigestKeyVersion(), now)
if err := leases.Save(ctx, next); err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - store lease: %w", location, err)
}
if err := sessions.observer.recordOrigin(ctx, unit.AssessmentSignals(), attemptID, domain.AssessmentOriginWorkSession, now, command.Origin); err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - record request origin: %w", location, err)
}
return WorkSessionHold{HeldUntil: next.HeldUntil(), RenewEvery: domain.AssessmentWorkLeaseRenewEvery}, nil
}
// ReleaseWorkSessionCommand is the release of a page that is closing.
type ReleaseWorkSessionCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
Client string
}
// Release frees the work session when the page holds it. It reveals nothing:
// a page that is not the holder, and an attempt that is not held, are no-ops.
func (sessions *WorkSessions) Release(ctx context.Context, command ReleaseWorkSessionCommand) error {
const location = "WorkSessions.Release"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
return fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
}
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
attempts := unit.AssessmentAttempts()
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
leases := unit.AssessmentWorkLeases()
current, found, err := leases.Get(ctx, attempt.ID())
if err != nil {
return fmt.Errorf("%s - read lease: %w", location, err)
}
if !found {
return nil
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time: %w", location, err)
}
released := current.ReleasedBy(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), command.Client), databaseTime.UTC().Truncate(time.Microsecond))
if released.ReleasedAt.Equal(current.ReleasedAt) {
return nil
}
if err := leases.Save(ctx, released); err != nil {
return fmt.Errorf("%s - store released lease: %w", location, err)
}
return nil
})
if err != nil {
return fmt.Errorf("%s - transaction: %w", location, err)
}
return nil
}
// requireHolder refuses a command from a page that does not hold the work
// session while another page does. The caller holds the row lock of the attempt
// and passes the database time read after it. A page that sent no identifier
// counts as one anonymous page, so omitting the header is no way around the
// rule; an attempt that nobody holds accepts every page. A training run, and a
// service without work sessions, are never refused.
func (sessions *WorkSessions) requireHolder(
ctx context.Context,
unit outbound.UnitOfWork,
attempt domain.AssessmentAttempt,
client string,
now time.Time,
) error {
const location = "WorkSessions.requireHolder"
if sessions == nil || !isRealAttemptKind(attempt.Kind()) {
return nil
}
current, found, err := unit.AssessmentWorkLeases().Get(ctx, attempt.ID())
if err != nil {
return fmt.Errorf("%s - read lease: %w", location, err)
}
if !found || current.AdmitsHolder(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), client), now) {
return nil
}
return fmt.Errorf("%s - another page holds the work session: %w", location, ErrAttemptWorkSessionBusy)
}
// validWorkClient accepts 16 to 64 characters of A-Z, a-z, 0-9, '_' and '-',
// the shape of a random identifier encoded for a header.
func validWorkClient(value string) bool {
if len(value) < minWorkClientBytes || len(value) > maxWorkClientBytes {
return false
}
for index := range len(value) {
character := value[index]
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9' || character == '_' || character == '-' {
continue
}
return false
}
return true
}