Files

183 lines
6.8 KiB
Go

// Package semantic keeps the stored vectors of candidate cards and need
// snapshots current and checks the GitHub repositories of projects. Every
// change that can move a vector schedules a durable job in the transaction of
// the change; the jobs call the ML service and GitHub later, so no user
// request ever waits for either.
package semantic
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"slices"
"strconv"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Job kinds. Renaming one strands the jobs scheduled under the old name.
const (
CandidateJobKind = "semantic.candidate"
NeedJobKind = "semantic.need"
RepositoryCheckJobKind = "profile.repository_check"
)
const (
// vectorJobAttempts lets a vector job outlast an ML outage of about an
// hour and a half with the default backoff; the backfill command repairs
// anything older.
vectorJobAttempts = 20
// repositoryJobAttempts bounds retries of network and server failures;
// a rate limit reschedules instead of failing.
repositoryJobAttempts = 5
// repositoryDigestBytes is the length of the repository digest in a job
// key and payload: the repository address names an account, so jobs
// carry only its digest.
repositoryDigestBytes = 8
)
// Trigger schedules the jobs. With vectors off it schedules no vector job;
// with repository checks off it records the request but schedules no check.
type Trigger struct {
vectors bool
repositories bool
}
// NewTrigger returns the scheduler of the enabled features.
func NewTrigger(vectors, repositories bool) *Trigger {
return &Trigger{vectors: vectors, repositories: repositories}
}
// CandidateChanged schedules a refresh of the card vectors of a candidate.
// Every change gets its own job; a job that finds nothing changed is a no-op.
func (trigger *Trigger) CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error {
if trigger == nil || !trigger.vectors {
return nil
}
occurrence, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("semantic.Trigger.CandidateChanged - generate key: %w", err)
}
return schedule(ctx, unit, CandidateJobKind, candidateID.String()+":"+occurrence.String(), at,
map[string]string{"candidate_id": candidateID.String()}, vectorJobAttempts)
}
// NeedRequirementsChanged schedules the vectors of a new requirements
// snapshot. The key is the snapshot, so a repeat schedules nothing.
func (trigger *Trigger) NeedRequirementsChanged(
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
) error {
if trigger == nil || !trigger.vectors {
return nil
}
return schedule(ctx, unit, NeedJobKind, needID.String()+":"+strconv.FormatInt(requirementsVersion, 10), at,
map[string]any{
"organization_id": organizationID.String(), "need_id": needID.String(),
"requirements_version": requirementsVersion,
}, vectorJobAttempts)
}
// RepositoriesChanged follows a profile save: it removes the checks of
// repositories that no project links any more and requests a check of every
// newly linked repository. A repository that was linked before keeps its
// check; the candidate asks for a new one explicitly.
func (trigger *Trigger) RepositoriesChanged(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID,
previous, current []domain.GitHubRepository, at time.Time,
) error {
const location = "semantic.Trigger.RepositoriesChanged"
keys := make([]string, 0, len(current))
for _, repository := range current {
keys = append(keys, repository.Key())
}
if err := unit.ProjectRepositories().DeleteUnlinked(ctx, candidateID, keys); err != nil {
return fmt.Errorf("%s - remove unlinked checks: %w", location, err)
}
known := make(map[string]bool, len(previous))
for _, repository := range previous {
known[repository.Key()] = true
}
for _, repository := range current {
if known[repository.Key()] {
continue
}
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
return fmt.Errorf("%s - request check: %w", location, err)
}
}
return nil
}
// RequestChecks requests a new check of every given repository.
func (trigger *Trigger) RequestChecks(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repositories []domain.GitHubRepository, at time.Time,
) error {
for _, repository := range repositories {
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
return fmt.Errorf("semantic.Trigger.RequestChecks - request check: %w", err)
}
}
return nil
}
func (trigger *Trigger) requestCheck(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repository domain.GitHubRepository, at time.Time,
) error {
if err := unit.ProjectRepositories().Request(ctx, candidateID, repository.Key(), at); err != nil {
return err
}
if trigger == nil || !trigger.repositories {
return nil
}
return scheduleRepositoryCheck(ctx, unit, candidateID, repository.Key(), at)
}
func scheduleRepositoryCheck(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, key string, at time.Time) error {
occurrence, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("generate key: %w", err)
}
digest := repositoryDigest(key)
return schedule(ctx, unit, RepositoryCheckJobKind, candidateID.String()+":"+digest+":"+occurrence.String(), at,
map[string]string{"candidate_id": candidateID.String(), "repository": digest}, repositoryJobAttempts)
}
// repositoryDigest identifies a repository in a job without naming its owner.
func repositoryDigest(key string) string {
digest := sha256.Sum256([]byte(key))
return hex.EncodeToString(digest[:repositoryDigestBytes])
}
func schedule(ctx context.Context, unit outbound.UnitOfWork, kind, key string, at time.Time, payload any, attempts int) error {
encoded, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("semantic.schedule - encode payload: %w", err)
}
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{Kind: kind, Key: key, DueAt: at, Payload: encoded, MaxAttempts: attempts})
if err != nil {
return fmt.Errorf("semantic.schedule - build job: %w", err)
}
if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil {
return fmt.Errorf("semantic.schedule - schedule job: %w", err)
}
return nil
}
// linkedRepositories returns the repositories of the current projects that
// match a digest.
func linkedRepository(content domain.CandidateProfileContent, digest string) (domain.GitHubRepository, bool) {
index := slices.IndexFunc(content.ProjectRepositories(), func(repository domain.GitHubRepository) bool {
return repositoryDigest(repository.Key()) == digest
})
if index < 0 {
return domain.GitHubRepository{}, false
}
return content.ProjectRepositories()[index], true
}