347 lines
14 KiB
Go
347 lines
14 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/binary"
|
|
"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"
|
|
)
|
|
|
|
// SemanticVectors returns the vector repository of the transaction.
|
|
func (unit *UnitOfWork) SemanticVectors() outbound.SemanticVectorRepository {
|
|
return semanticVectorRepository{queries: unit.queries}
|
|
}
|
|
|
|
// ProjectRepositories returns the repository check store of the transaction.
|
|
func (unit *UnitOfWork) ProjectRepositories() outbound.ProjectRepositoryStore {
|
|
return projectRepositoryStore{queries: unit.queries}
|
|
}
|
|
|
|
type semanticVectorRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func subjectColumns(kind domain.SemanticSubjectKind, subjectID uuid.UUID) (pgtype.UUID, pgtype.UUID, error) {
|
|
switch kind {
|
|
case domain.SemanticSubjectCandidate:
|
|
return pgUUID(subjectID), pgtype.UUID{}, nil
|
|
case domain.SemanticSubjectNeed:
|
|
return pgtype.UUID{}, pgUUID(subjectID), nil
|
|
default:
|
|
return pgtype.UUID{}, pgtype.UUID{}, fmt.Errorf("postgres.subjectColumns - subject kind is unknown: %w", domain.ErrInvalidSemanticVector)
|
|
}
|
|
}
|
|
|
|
func (repository semanticVectorRepository) Replace(
|
|
ctx context.Context,
|
|
kind domain.SemanticSubjectKind,
|
|
subjectID uuid.UUID,
|
|
model domain.SemanticModel,
|
|
items []outbound.StoredSemanticItem,
|
|
at time.Time,
|
|
) error {
|
|
const location = "semanticVectorRepository.Replace"
|
|
candidateID, needID, err := subjectColumns(kind, subjectID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := repository.queries.DeleteSemanticVectorsOfModel(ctx, sqlc.DeleteSemanticVectorsOfModelParams{
|
|
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
|
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - delete previous vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
for _, item := range items {
|
|
if err := repository.queries.InsertSemanticVector(ctx, sqlc.InsertSemanticVectorParams{
|
|
SubjectKind: string(kind), SubjectID: pgUUID(subjectID), CandidateID: candidateID, NeedID: needID,
|
|
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
ItemKey: item.Key, ContentSha256: item.ContentDigest[:], LabelSha256: item.LabelDigest,
|
|
Dimension: int32(len(item.Vector)), Vector: item.Vector.Encode(), ComputedAt: pgTime(at), //nolint:gosec // a domain vector has at most 4096 dimensions
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - insert vector: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// semanticLockNamespace keeps the advisory lock keys of vector jobs apart
|
|
// from any other advisory lock of the database.
|
|
const semanticLockNamespace = 0x53454d41 // "SEMA"
|
|
|
|
func (repository semanticVectorRepository) Lock(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
|
|
digest := sha256.Sum256([]byte(string(kind) + ":" + subjectID.String()))
|
|
key := int64(binary.BigEndian.Uint64(digest[:8])>>16) ^ semanticLockNamespace
|
|
if err := repository.queries.LockSemanticSubject(ctx, key); err != nil {
|
|
return fmt.Errorf("semanticVectorRepository.Lock - take lock: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) DeleteSubject(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
|
|
if err := repository.queries.DeleteSemanticVectorsOfSubject(ctx, sqlc.DeleteSemanticVectorsOfSubjectParams{
|
|
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
|
}); err != nil {
|
|
return fmt.Errorf("semanticVectorRepository.DeleteSubject - delete vectors: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) Digests(
|
|
ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel,
|
|
) (map[string][32]byte, error) {
|
|
rows, err := repository.queries.ListSemanticVectorDigests(ctx, sqlc.ListSemanticVectorDigestsParams{
|
|
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
|
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("semanticVectorRepository.Digests - select digests: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
digests := make(map[string][32]byte, len(rows))
|
|
for _, row := range rows {
|
|
var digest [32]byte
|
|
if len(row.ContentSha256) != len(digest) {
|
|
return nil, fmt.Errorf("semanticVectorRepository.Digests - digest length is invalid: %w", domain.ErrInvalidSemanticVector)
|
|
}
|
|
copy(digest[:], row.ContentSha256)
|
|
digests[row.ItemKey] = digest
|
|
}
|
|
return digests, nil
|
|
}
|
|
|
|
func pgUUIDs(ids []uuid.UUID) []pgtype.UUID {
|
|
values := make([]pgtype.UUID, 0, len(ids))
|
|
for _, id := range ids {
|
|
values = append(values, pgUUID(id))
|
|
}
|
|
return values
|
|
}
|
|
|
|
func (repository semanticVectorRepository) CandidateWholeVectors(
|
|
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
|
|
) (map[uuid.UUID]domain.SemanticVector, error) {
|
|
const location = "semanticVectorRepository.CandidateWholeVectors"
|
|
vectors := make(map[uuid.UUID]domain.SemanticVector)
|
|
if len(candidateIDs) == 0 {
|
|
return vectors, nil
|
|
}
|
|
rows, err := repository.queries.ListCandidateWholeVectors(ctx, sqlc.ListCandidateWholeVectorsParams{
|
|
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
CandidateIds: pgUUIDs(candidateIDs),
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
for _, row := range rows {
|
|
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
|
if err != nil || !row.CandidateID.Valid {
|
|
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
|
}
|
|
vectors[uuid.UUID(row.CandidateID.Bytes)] = vector
|
|
}
|
|
return vectors, nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) CandidateItemVectors(
|
|
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
|
|
) (map[uuid.UUID][]outbound.SemanticItemVector, error) {
|
|
const location = "semanticVectorRepository.CandidateItemVectors"
|
|
vectors := make(map[uuid.UUID][]outbound.SemanticItemVector)
|
|
if len(candidateIDs) == 0 {
|
|
return vectors, nil
|
|
}
|
|
rows, err := repository.queries.ListCandidateItemVectors(ctx, sqlc.ListCandidateItemVectorsParams{
|
|
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
CandidateIds: pgUUIDs(candidateIDs),
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
for _, row := range rows {
|
|
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
|
if err != nil || !row.CandidateID.Valid {
|
|
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
|
}
|
|
id := uuid.UUID(row.CandidateID.Bytes)
|
|
vectors[id] = append(vectors[id], outbound.SemanticItemVector{Key: row.ItemKey, LabelDigest: row.LabelSha256, Vector: vector})
|
|
}
|
|
return vectors, nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) NeedVectors(
|
|
ctx context.Context, needID uuid.UUID, model domain.SemanticModel, digests [][32]byte,
|
|
) (map[string]domain.SemanticVector, error) {
|
|
const location = "semanticVectorRepository.NeedVectors"
|
|
vectors := make(map[string]domain.SemanticVector)
|
|
if len(digests) == 0 {
|
|
return vectors, nil
|
|
}
|
|
values := make([][]byte, 0, len(digests))
|
|
for _, digest := range digests {
|
|
values = append(values, digest[:])
|
|
}
|
|
rows, err := repository.queries.ListNeedVectors(ctx, sqlc.ListNeedVectorsParams{
|
|
NeedID: pgUUID(needID), ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
|
ContentDigests: values,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
for _, row := range rows {
|
|
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
|
}
|
|
vectors[row.ItemKey] = vector
|
|
}
|
|
return vectors, nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) CandidatesAfter(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error) {
|
|
rows, err := repository.queries.ListProfileCandidatesAfter(ctx, sqlc.ListProfileCandidatesAfterParams{
|
|
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("semanticVectorRepository.CandidatesAfter - select candidates: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
ids := make([]uuid.UUID, 0, len(rows))
|
|
for _, row := range rows {
|
|
ids = append(ids, uuid.UUID(row.Bytes))
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
func (repository semanticVectorRepository) NeedsAfter(ctx context.Context, after uuid.UUID, limit int) ([]outbound.NeedReference, error) {
|
|
rows, err := repository.queries.ListNeedsAfter(ctx, sqlc.ListNeedsAfterParams{
|
|
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("semanticVectorRepository.NeedsAfter - select needs: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
needs := make([]outbound.NeedReference, 0, len(rows))
|
|
for _, row := range rows {
|
|
needs = append(needs, outbound.NeedReference{
|
|
NeedID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
|
|
RequirementsVersion: row.RequirementsVersion,
|
|
})
|
|
}
|
|
return needs, nil
|
|
}
|
|
|
|
type projectRepositoryStore struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func repositoryCheckFromRow(row sqlc.CandidateProjectRepository) outbound.RepositoryCheck {
|
|
check := outbound.RepositoryCheck{
|
|
Key: row.RepositoryKey, State: outbound.RepositoryCheckState(row.State),
|
|
GitHubID: row.GithubID.Int64, RepositoryETag: row.RepositoryEtag.String, ReadmeETag: row.ReadmeEtag.String,
|
|
Failure: outbound.RepositoryFailureClass(row.FailureClass.String), RequestedAt: row.RequestedAt.Time.UTC(),
|
|
Evidence: domain.RepositoryEvidence{
|
|
Description: row.Description.String, Topics: row.Topics, Languages: row.Languages,
|
|
ReadmeExcerpt: row.ReadmeExcerpt.String,
|
|
},
|
|
}
|
|
if row.CheckedAt.Valid {
|
|
check.CheckedAt = row.CheckedAt.Time.UTC()
|
|
}
|
|
return check
|
|
}
|
|
|
|
func (store projectRepositoryStore) List(ctx context.Context, candidateID uuid.UUID) ([]outbound.RepositoryCheck, error) {
|
|
rows, err := store.queries.ListCandidateProjectRepositories(ctx, pgUUID(candidateID))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("projectRepositoryStore.List - select checks: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
checks := make([]outbound.RepositoryCheck, 0, len(rows))
|
|
for _, row := range rows {
|
|
checks = append(checks, repositoryCheckFromRow(row))
|
|
}
|
|
return checks, nil
|
|
}
|
|
|
|
func (store projectRepositoryStore) GetForUpdate(ctx context.Context, candidateID uuid.UUID, key string) (outbound.RepositoryCheck, bool, error) {
|
|
row, err := store.queries.GetCandidateProjectRepositoryForUpdate(ctx, sqlc.GetCandidateProjectRepositoryForUpdateParams{
|
|
CandidateID: pgUUID(candidateID), RepositoryKey: key,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return outbound.RepositoryCheck{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return outbound.RepositoryCheck{}, false, fmt.Errorf("projectRepositoryStore.GetForUpdate - select check: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return repositoryCheckFromRow(row), true, nil
|
|
}
|
|
|
|
func (store projectRepositoryStore) Request(ctx context.Context, candidateID uuid.UUID, key string, at time.Time) error {
|
|
if err := store.queries.RequestCandidateProjectRepositoryCheck(ctx, sqlc.RequestCandidateProjectRepositoryCheckParams{
|
|
CandidateID: pgUUID(candidateID), RepositoryKey: key, RequestedAt: pgTime(at),
|
|
}); err != nil {
|
|
return fmt.Errorf("projectRepositoryStore.Request - record request: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func optionalPgText(value string) pgtype.Text {
|
|
if value == "" {
|
|
return pgtype.Text{}
|
|
}
|
|
return pgText(value)
|
|
}
|
|
|
|
func (store projectRepositoryStore) Save(ctx context.Context, candidateID uuid.UUID, check outbound.RepositoryCheck) error {
|
|
params := sqlc.SaveCandidateProjectRepositoryCheckParams{
|
|
State: string(check.State), Topics: []string{}, Languages: []string{},
|
|
RepositoryEtag: optionalPgText(check.RepositoryETag), ReadmeEtag: optionalPgText(check.ReadmeETag),
|
|
FailureClass: optionalPgText(string(check.Failure)), CheckedAt: pgTime(check.CheckedAt),
|
|
CandidateID: pgUUID(candidateID), RepositoryKey: check.Key,
|
|
}
|
|
if check.State == outbound.RepositoryCheckVerified {
|
|
params.GithubID = pgtype.Int8{Int64: check.GitHubID, Valid: check.GitHubID > 0}
|
|
params.Description = optionalPgText(check.Evidence.Description)
|
|
params.ReadmeExcerpt = optionalPgText(check.Evidence.ReadmeExcerpt)
|
|
if check.Evidence.Topics != nil {
|
|
params.Topics = check.Evidence.Topics
|
|
}
|
|
if check.Evidence.Languages != nil {
|
|
params.Languages = check.Evidence.Languages
|
|
}
|
|
}
|
|
if err := store.queries.SaveCandidateProjectRepositoryCheck(ctx, params); err != nil {
|
|
return fmt.Errorf("projectRepositoryStore.Save - store check: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store projectRepositoryStore) DeleteUnlinked(ctx context.Context, candidateID uuid.UUID, linkedKeys []string) error {
|
|
if linkedKeys == nil {
|
|
linkedKeys = []string{}
|
|
}
|
|
if err := store.queries.DeleteUnlinkedCandidateProjectRepositories(ctx, sqlc.DeleteUnlinkedCandidateProjectRepositoriesParams{
|
|
CandidateID: pgUUID(candidateID), LinkedKeys: linkedKeys,
|
|
}); err != nil {
|
|
return fmt.Errorf("projectRepositoryStore.DeleteUnlinked - delete checks: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store projectRepositoryStore) LatestRequest(ctx context.Context, candidateID uuid.UUID) (time.Time, error) {
|
|
latest, err := store.queries.GetLatestRepositoryCheckRequest(ctx, pgUUID(candidateID))
|
|
if err != nil {
|
|
return time.Time{}, fmt.Errorf("projectRepositoryStore.LatestRequest - select request: %w", markTransactionConflict(sanitizeConnectError(err)))
|
|
}
|
|
if !latest.Valid {
|
|
return time.Time{}, nil
|
|
}
|
|
return latest.Time.UTC(), nil
|
|
}
|