Files
lincodex/backend/internal/port/outbound/semantic.go
T

182 lines
7.6 KiB
Go

package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrEmbedderUnavailable reports that the ML service could not encode
// now: it is not ready, unreachable, slow, or the circuit is open. A
// later attempt may succeed.
ErrEmbedderUnavailable = errors.New("text embedder is unavailable")
// ErrEmbedderRejected reports a request or a response that breaks the
// ML contract; repeating it gives the same result.
ErrEmbedderRejected = errors.New("text embedder rejected the request")
// ErrRepositoryFetchUnavailable reports that the public GitHub API could
// not answer now, for example because of its rate limit.
ErrRepositoryFetchUnavailable = errors.New("repository metadata is unavailable")
)
// EmbeddingKind is the side of the retrieval pair; see the ML contract.
type EmbeddingKind string
const (
EmbeddingQuery EmbeddingKind = "query"
EmbeddingDocument EmbeddingKind = "document"
)
// MaxEmbeddingBatch is the number of texts of one ML request, the contract
// bound.
const MaxEmbeddingBatch = 32
// TextEmbedder encodes texts with the ML service. Texts are personal data
// or an organization's need text: an implementation never logs them.
type TextEmbedder interface {
// Embed encodes the texts with the named model of the service and
// returns one normalized vector per text in order and the identity of
// the model that produced them. At most MaxEmbeddingBatch texts are sent
// at once. A model that the service does not serve is ErrEmbedderRejected.
Embed(ctx context.Context, modelID string, kind EmbeddingKind, texts []string) (domain.SemanticModel, []domain.SemanticVector, error)
}
// StoredSemanticItem is one vector to store with the digests of its text.
type StoredSemanticItem struct {
Key string
ContentDigest [32]byte
LabelDigest []byte
Vector domain.SemanticVector
}
// SemanticItemVector is a stored item vector of a candidate.
type SemanticItemVector struct {
Key string
LabelDigest []byte
Vector domain.SemanticVector
}
// SemanticVectorRepository stores and reads vectors inside the caller's
// transaction.
type SemanticVectorRepository interface {
// Lock serializes the vector jobs of one subject until the transaction
// ends.
Lock(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error
// Replace makes the given items the only vectors of the subject for the
// model: it deletes the other rows of that subject and model first.
Replace(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel, items []StoredSemanticItem, at time.Time) error
// DeleteSubject removes every vector of a subject, of any model.
DeleteSubject(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error
// Digests returns the content digest of every stored item of the subject
// and model, by item key.
Digests(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel) (map[string][32]byte, error)
// CandidateWholeVectors returns the whole-view vector of each candidate
// that has one for the model.
CandidateWholeVectors(ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID) (map[uuid.UUID]domain.SemanticVector, error)
// CandidateItemVectors returns the item vectors of each candidate.
CandidateItemVectors(ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID) (map[uuid.UUID][]SemanticItemVector, error)
// NeedVectors returns the stored vectors of a need whose content digest
// is one of digests, by item key.
NeedVectors(ctx context.Context, needID uuid.UUID, model domain.SemanticModel, digests [][32]byte) (map[string]domain.SemanticVector, error)
// CandidatesAfter lists the candidates with a saved profile after a cursor.
CandidatesAfter(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error)
// NeedsAfter lists needs after a cursor with their current requirements
// version.
NeedsAfter(ctx context.Context, after uuid.UUID, limit int) ([]NeedReference, error)
}
// NeedReference names one need and its current requirements snapshot.
type NeedReference struct {
OrganizationID uuid.UUID
NeedID uuid.UUID
RequirementsVersion int64
}
// RepositoryCheckState is the state of a repository check; see
// ProfileRepositoryCheckState in the public contract.
type RepositoryCheckState string
const (
RepositoryCheckPending RepositoryCheckState = "pending"
RepositoryCheckVerified RepositoryCheckState = "verified"
RepositoryCheckNotFound RepositoryCheckState = "not_found"
RepositoryCheckUnavailable RepositoryCheckState = "unavailable"
)
// RepositoryFailureClass is the bounded cause of an unavailable check.
type RepositoryFailureClass string
const (
RepositoryFailureRateLimited RepositoryFailureClass = "rate_limited"
RepositoryFailureServerError RepositoryFailureClass = "server_error"
RepositoryFailureNetwork RepositoryFailureClass = "network"
RepositoryFailureInvalidResponse RepositoryFailureClass = "invalid_response"
)
// RepositoryCheck is the stored check of one linked repository. Evidence
// is set only for a verified repository.
type RepositoryCheck struct {
Key string
State RepositoryCheckState
GitHubID int64
Evidence domain.RepositoryEvidence
RepositoryETag string
ReadmeETag string
Failure RepositoryFailureClass
CheckedAt time.Time
RequestedAt time.Time
}
// ProjectRepositoryStore keeps the repository checks of candidates inside
// the caller's transaction.
type ProjectRepositoryStore interface {
List(ctx context.Context, candidateID uuid.UUID) ([]RepositoryCheck, error)
// GetForUpdate locks and returns the check, or false when none exists.
GetForUpdate(ctx context.Context, candidateID uuid.UUID, key string) (RepositoryCheck, bool, error)
// Request creates a pending check or records a new request of a known one.
Request(ctx context.Context, candidateID uuid.UUID, key string, at time.Time) error
// Save stores the result of a finished check.
Save(ctx context.Context, candidateID uuid.UUID, check RepositoryCheck) error
// DeleteUnlinked removes the checks of repositories not in linkedKeys.
DeleteUnlinked(ctx context.Context, candidateID uuid.UUID, linkedKeys []string) error
// LatestRequest returns the time of the newest check request, or the zero
// time when the candidate has none.
LatestRequest(ctx context.Context, candidateID uuid.UUID) (time.Time, error)
}
// RepositoryFetch is what one check read from the public GitHub API.
type RepositoryFetch struct {
// Found is false when the repository does not exist or is not public.
Found bool
GitHubID int64
Evidence domain.RepositoryEvidence
// NotModified is true when the conditional request matched the stored
// ETag: the stored evidence is still current.
NotModified bool
RepositoryETag string
ReadmeETag string
}
// RepositoryFetchError carries the bounded failure class and, for a rate
// limit, when GitHub allows the next request.
type RepositoryFetchError struct {
Class RepositoryFailureClass
RetryAfter time.Duration
}
func (err *RepositoryFetchError) Error() string {
return "repository fetch failed: " + string(err.Class)
}
func (err *RepositoryFetchError) Unwrap() error { return ErrRepositoryFetchUnavailable }
// RepositoryMetadataFetcher reads public repository metadata. The only host
// it may contact is the public GitHub API.
type RepositoryMetadataFetcher interface {
Fetch(ctx context.Context, repository domain.GitHubRepository, previous RepositoryCheck) (RepositoryFetch, error)
}