feat(matching): rank with semantic embeddings and explain matches by evidence
This commit is contained in:
1 parent
facc1789b1
commit
24b64d698a
215 files changed
+16951
-327
No files matched your search
@@ -0,0 +1,360 @@
|
||||
// Package github reads public repository metadata from the public GitHub
|
||||
// REST API. It is SSRF-safe by construction: the only origin it contacts is
|
||||
// https://api.github.com, a repository coordinate is validated by the domain
|
||||
// before it becomes a path, and a redirect to any other origin is refused.
|
||||
package github
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// apiOrigin is the only origin the fetcher ever contacts.
|
||||
apiOrigin = "https://api.github.com"
|
||||
apiVersion = "2022-11-28"
|
||||
userAgent = "lincodex-repository-check"
|
||||
// Response caps: a repository document is a few KiB, the language map
|
||||
// smaller; a README is read only up to its excerpt budget.
|
||||
maxMetadataBytes = 1 << 20
|
||||
maxReadmeBytes = 64 << 10
|
||||
// maxRedirects bounds same-origin redirects, such as a renamed repository.
|
||||
maxRedirects = 3
|
||||
// The stored bounds of candidate_project_repositories.
|
||||
maxDescriptionRunes = 1000
|
||||
maxReadmeRunes = 4000
|
||||
maxTopics = 20
|
||||
// maxLanguages keeps the main languages by size.
|
||||
maxLanguages = 3
|
||||
// Rate limit waits are clamped, so a wrong header cannot stall a check
|
||||
// for days or make it spin.
|
||||
minRateLimitWait = time.Minute
|
||||
maxRateLimitWait = time.Hour
|
||||
)
|
||||
|
||||
// Fetcher implements outbound.RepositoryMetadataFetcher.
|
||||
type Fetcher struct {
|
||||
client *http.Client
|
||||
origin string
|
||||
token string
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
var _ outbound.RepositoryMetadataFetcher = (*Fetcher)(nil)
|
||||
|
||||
// NewFetcher builds a fetcher for api.github.com. token is optional; it is
|
||||
// sent only to that origin and never logged.
|
||||
func NewFetcher(timeout time.Duration, token string, clock func() time.Time) (*Fetcher, error) {
|
||||
return newFetcher(apiOrigin, timeout, token, clock, &http.Transport{
|
||||
// No proxy from the environment: the request goes to GitHub directly.
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
|
||||
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
|
||||
TLSHandshakeTimeout: timeout,
|
||||
ResponseHeaderTimeout: timeout,
|
||||
MaxIdleConns: 4,
|
||||
IdleConnTimeout: time.Minute,
|
||||
ForceAttemptHTTP2: true,
|
||||
})
|
||||
}
|
||||
|
||||
// newFetcher lets tests point the fetcher at an httptest server; production
|
||||
// code reaches it only through NewFetcher with the fixed origin.
|
||||
func newFetcher(origin string, timeout time.Duration, token string, clock func() time.Time, transport http.RoundTripper) (*Fetcher, error) {
|
||||
if timeout <= 0 || clock == nil || transport == nil {
|
||||
return nil, errors.New("github.newFetcher - timeout, clock, and transport must be set")
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || parsed.Path != "" {
|
||||
return nil, errors.New("github.newFetcher - origin is invalid")
|
||||
}
|
||||
return &Fetcher{
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(request *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxRedirects {
|
||||
return errors.New("too many redirects")
|
||||
}
|
||||
if request.URL.Scheme != parsed.Scheme || request.URL.Host != parsed.Host {
|
||||
return errors.New("redirect to another origin")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
origin: parsed.Scheme + "://" + parsed.Host,
|
||||
token: token,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type repositoryDocument struct {
|
||||
ID int64 `json:"id"`
|
||||
Private bool `json:"private"`
|
||||
Visibility string `json:"visibility"`
|
||||
Description *string `json:"description"`
|
||||
Topics []string `json:"topics"`
|
||||
}
|
||||
|
||||
// Fetch reads the repository, its languages, and its README. A repository
|
||||
// that does not exist or is not public is Found=false with no metadata.
|
||||
func (fetcher *Fetcher) Fetch(
|
||||
ctx context.Context, repository domain.GitHubRepository, previous outbound.RepositoryCheck,
|
||||
) (outbound.RepositoryFetch, error) {
|
||||
if repository.IsZero() {
|
||||
return outbound.RepositoryFetch{}, fmt.Errorf("github.Fetcher.Fetch - repository is not set: %w", domain.ErrInvalidGitHubRepository)
|
||||
}
|
||||
base := "/repos/" + url.PathEscape(repository.Owner()) + "/" + url.PathEscape(repository.Name())
|
||||
repositoryETag := ""
|
||||
if previous.State == outbound.RepositoryCheckVerified {
|
||||
repositoryETag = previous.RepositoryETag
|
||||
}
|
||||
response, err := fetcher.get(ctx, base, "application/vnd.github+json", repositoryETag, maxMetadataBytes)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
switch {
|
||||
case response.status == http.StatusNotModified && repositoryETag != "":
|
||||
return outbound.RepositoryFetch{
|
||||
Found: true, NotModified: true, GitHubID: previous.GitHubID, Evidence: previous.Evidence,
|
||||
RepositoryETag: previous.RepositoryETag, ReadmeETag: previous.ReadmeETag,
|
||||
}, nil
|
||||
case response.status == http.StatusNotFound || response.status == http.StatusGone ||
|
||||
response.status == http.StatusUnavailableForLegalReasons:
|
||||
return outbound.RepositoryFetch{Found: false}, nil
|
||||
case response.status != http.StatusOK:
|
||||
return outbound.RepositoryFetch{}, fetcher.statusError(response)
|
||||
}
|
||||
return fetcher.publicRepository(ctx, base, response)
|
||||
}
|
||||
|
||||
// publicRepository reads the metadata of a repository document that GitHub
|
||||
// returned: a private or internal one is not found, a public one gets its
|
||||
// languages and README.
|
||||
func (fetcher *Fetcher) publicRepository(ctx context.Context, base string, response fetched) (outbound.RepositoryFetch, error) {
|
||||
var document repositoryDocument
|
||||
if err := json.Unmarshal(response.body, &document); err != nil || document.ID <= 0 {
|
||||
return outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
if document.Private || (document.Visibility != "" && document.Visibility != "public") {
|
||||
return outbound.RepositoryFetch{Found: false}, nil
|
||||
}
|
||||
languages, err := fetcher.languages(ctx, base)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
readme, readmeETag, err := fetcher.readme(ctx, base)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
description := ""
|
||||
if document.Description != nil {
|
||||
description = truncate(plainLine(*document.Description), maxDescriptionRunes)
|
||||
}
|
||||
return outbound.RepositoryFetch{
|
||||
Found: true, GitHubID: document.ID, RepositoryETag: boundedETag(response.etag), ReadmeETag: readmeETag,
|
||||
Evidence: domain.RepositoryEvidence{
|
||||
Description: description, Topics: cleanTopics(document.Topics), Languages: languages, ReadmeExcerpt: readme,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) languages(ctx context.Context, base string) ([]string, error) {
|
||||
response, err := fetcher.get(ctx, base+"/languages", "application/vnd.github+json", "", maxMetadataBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.status == http.StatusNotFound {
|
||||
return []string{}, nil
|
||||
}
|
||||
if response.status != http.StatusOK {
|
||||
return nil, fetcher.statusError(response)
|
||||
}
|
||||
var sizes map[string]int64
|
||||
if err := json.Unmarshal(response.body, &sizes); err != nil {
|
||||
return nil, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
type language struct {
|
||||
name string
|
||||
bytes int64
|
||||
}
|
||||
var ordered []language
|
||||
for name, size := range sizes {
|
||||
if clean := plainLine(name); clean != "" && utf8.RuneCountInString(clean) <= 50 {
|
||||
ordered = append(ordered, language{name: clean, bytes: size})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(ordered, func(left, right language) int {
|
||||
return cmp.Or(cmp.Compare(right.bytes, left.bytes), strings.Compare(left.name, right.name))
|
||||
})
|
||||
names := make([]string, 0, maxLanguages)
|
||||
for _, item := range ordered[:min(len(ordered), maxLanguages)] {
|
||||
names = append(names, item.name)
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) readme(ctx context.Context, base string) (string, string, error) {
|
||||
response, err := fetcher.get(ctx, base+"/readme", "application/vnd.github.raw+json", "", maxReadmeBytes)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if response.status == http.StatusNotFound {
|
||||
return "", "", nil
|
||||
}
|
||||
if response.status != http.StatusOK {
|
||||
return "", "", fetcher.statusError(response)
|
||||
}
|
||||
// A cut body may end inside a multi-byte character; invalid bytes are
|
||||
// dropped instead of failing the check.
|
||||
text := strings.ToValidUTF8(string(response.body), "")
|
||||
return truncate(MarkdownToText(text), maxReadmeRunes), boundedETag(response.etag), nil
|
||||
}
|
||||
|
||||
type fetched struct {
|
||||
status int
|
||||
etag string
|
||||
body []byte
|
||||
headers http.Header
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) get(ctx context.Context, path, accept, etag string, limit int64) (fetched, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, fetcher.origin+path, nil)
|
||||
if err != nil {
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
request.Header.Set("Accept", accept)
|
||||
request.Header.Set("User-Agent", userAgent)
|
||||
request.Header.Set("X-GitHub-Api-Version", apiVersion)
|
||||
if etag != "" {
|
||||
request.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
if fetcher.token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+fetcher.token)
|
||||
}
|
||||
response, err := fetcher.client.Do(request)
|
||||
if err != nil {
|
||||
// The error can carry the URL; only the class leaves this function.
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, limit))
|
||||
if err != nil {
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
return fetched{status: response.StatusCode, etag: response.Header.Get("ETag"), body: body, headers: response.Header}, nil
|
||||
}
|
||||
|
||||
// statusError classifies an unexpected status. GitHub reports an exhausted
|
||||
// rate limit as 403 or 429 with x-ratelimit-remaining 0 or Retry-After.
|
||||
func (fetcher *Fetcher) statusError(response fetched) error {
|
||||
limited := response.status == http.StatusTooManyRequests ||
|
||||
(response.status == http.StatusForbidden &&
|
||||
(response.headers.Get("X-RateLimit-Remaining") == "0" || response.headers.Get("Retry-After") != ""))
|
||||
switch {
|
||||
case limited:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: fetcher.rateLimitWait(response.headers)}
|
||||
case response.status >= http.StatusInternalServerError:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureServerError}
|
||||
default:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) rateLimitWait(headers http.Header) time.Duration {
|
||||
wait := minRateLimitWait
|
||||
if seconds, err := strconv.ParseInt(headers.Get("Retry-After"), 10, 64); err == nil && seconds > 0 {
|
||||
wait = time.Duration(seconds) * time.Second
|
||||
} else if reset, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64); err == nil {
|
||||
wait = time.Unix(reset, 0).Sub(fetcher.clock())
|
||||
}
|
||||
return min(max(wait, minRateLimitWait), maxRateLimitWait)
|
||||
}
|
||||
|
||||
func boundedETag(etag string) string {
|
||||
if etag == "" || len(etag) > 200 || strings.ContainsFunc(etag, func(character rune) bool { return character < 0x20 || character > 0x7e }) {
|
||||
return ""
|
||||
}
|
||||
return etag
|
||||
}
|
||||
|
||||
func cleanTopics(topics []string) []string {
|
||||
cleaned := make([]string, 0, min(len(topics), maxTopics))
|
||||
for _, topic := range topics {
|
||||
if len(cleaned) == maxTopics {
|
||||
break
|
||||
}
|
||||
if clean := plainLine(topic); clean != "" && utf8.RuneCountInString(clean) <= 50 {
|
||||
cleaned = append(cleaned, clean)
|
||||
}
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// plainLine keeps printable text on one line.
|
||||
func plainLine(value string) string {
|
||||
value = strings.Map(func(character rune) rune {
|
||||
if character < 0x20 || character == 0x7f || character == '
' || character == '
' {
|
||||
return ' '
|
||||
}
|
||||
return character
|
||||
}, value)
|
||||
return strings.Join(strings.Fields(value), " ")
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if utf8.RuneCountInString(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(string([]rune(value)[:limit]))
|
||||
}
|
||||
|
||||
var (
|
||||
fencedCodePattern = regexp.MustCompile("(?s)```.*?(```|$)|~~~.*?(~~~|$)")
|
||||
htmlCommentPatter = regexp.MustCompile(`(?s)<!--.*?-->`)
|
||||
htmlTagPattern = regexp.MustCompile(`(?s)<[^>]{0,500}>`)
|
||||
imagePattern = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
|
||||
linkPattern = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
|
||||
referencePattern = regexp.MustCompile(`(?m)^\s*\[[^\]]+\]:\s*\S+.*$`)
|
||||
urlPattern = regexp.MustCompile(`https?://\S+`)
|
||||
headingPattern = regexp.MustCompile(`(?m)^\s{0,3}#{1,6}\s*`)
|
||||
listPattern = regexp.MustCompile(`(?m)^\s*(?:[-*+]|\d+[.)])\s+`)
|
||||
quotePattern = regexp.MustCompile(`(?m)^\s*>\s?`)
|
||||
emphasisPattern = regexp.MustCompile("[*_`~|]+")
|
||||
rulePattern = regexp.MustCompile(`(?m)^\s*[-=*_]{3,}\s*$`)
|
||||
)
|
||||
|
||||
// MarkdownToText turns a README into plain text for ranking: code blocks,
|
||||
// HTML, images, link targets, and bare URLs are removed and the markup
|
||||
// characters are dropped. The result is never rendered.
|
||||
func MarkdownToText(markdown string) string {
|
||||
text := strings.ReplaceAll(markdown, "\r\n", "\n")
|
||||
for _, step := range []struct {
|
||||
pattern *regexp.Regexp
|
||||
replacement string
|
||||
}{
|
||||
{fencedCodePattern, " "}, {htmlCommentPatter, " "}, {imagePattern, " "}, {linkPattern, "$1"},
|
||||
{referencePattern, " "}, {htmlTagPattern, " "}, {urlPattern, " "}, {rulePattern, " "},
|
||||
{headingPattern, ""}, {listPattern, ""}, {quotePattern, ""}, {emphasisPattern, " "},
|
||||
} {
|
||||
text = step.pattern.ReplaceAllString(text, step.replacement)
|
||||
}
|
||||
return plainLine(text)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var testNow = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
type recordedRequest struct {
|
||||
path, authorization, accept, ifNoneMatch string
|
||||
}
|
||||
|
||||
type fakeGitHub struct {
|
||||
mutex sync.Mutex
|
||||
requests []recordedRequest
|
||||
handler func(writer http.ResponseWriter, request *http.Request)
|
||||
}
|
||||
|
||||
func (fake *fakeGitHub) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
fake.mutex.Lock()
|
||||
fake.requests = append(fake.requests, recordedRequest{
|
||||
path: request.URL.EscapedPath(), authorization: request.Header.Get("Authorization"),
|
||||
accept: request.Header.Get("Accept"), ifNoneMatch: request.Header.Get("If-None-Match"),
|
||||
})
|
||||
fake.mutex.Unlock()
|
||||
fake.handler(writer, request)
|
||||
}
|
||||
|
||||
func publicRepository(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/repos/Example/ledger":
|
||||
writer.Header().Set("ETag", `"repo-1"`)
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"public","description":"Payments\nledger","topics":["payments","go"],"language":"Go"}`))
|
||||
case "/repos/Example/ledger/languages":
|
||||
_, _ = writer.Write([]byte(`{"Shell":10,"Go":5000,"Python":900,"Makefile":5}`))
|
||||
case "/repos/Example/ledger/readme":
|
||||
writer.Header().Set("ETag", `"readme-1"`)
|
||||
_, _ = writer.Write([]byte("# Ledger\n\nIdempotent [callbacks](https://example.test/x) with `outbox`.\n\n```sh\nmake run\n```\n<img src=x onerror=alert(1)>"))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestFetcher(t *testing.T, fake *fakeGitHub, token string) *Fetcher {
|
||||
t.Helper()
|
||||
server := httptest.NewTLSServer(fake)
|
||||
t.Cleanup(server.Close)
|
||||
fetcher, err := newFetcher(server.URL, time.Second, token, func() time.Time { return testNow }, server.Client().Transport)
|
||||
if err != nil {
|
||||
t.Fatalf("newFetcher() error = %v", err)
|
||||
}
|
||||
return fetcher
|
||||
}
|
||||
|
||||
func repository(t *testing.T, raw string) domain.GitHubRepository {
|
||||
t.Helper()
|
||||
parsed, err := domain.ParseGitHubRepositoryURL(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestFetchReadsPublicMetadataAsPlainText(t *testing.T) {
|
||||
fake := &fakeGitHub{handler: publicRepository}
|
||||
fetcher := newTestFetcher(t, fake, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() error = %v", err)
|
||||
}
|
||||
if !result.Found || result.GitHubID != 7 || result.RepositoryETag != `"repo-1"` || result.ReadmeETag != `"readme-1"` {
|
||||
t.Fatalf("result = %+v", result)
|
||||
}
|
||||
evidence := result.Evidence
|
||||
if evidence.Description != "Payments ledger" || strings.Join(evidence.Topics, ",") != "payments,go" ||
|
||||
strings.Join(evidence.Languages, ",") != "Go,Python,Shell" {
|
||||
t.Fatalf("evidence = %+v", evidence)
|
||||
}
|
||||
if evidence.ReadmeExcerpt != "Ledger Idempotent callbacks with outbox ." {
|
||||
t.Fatalf("readme = %q, want plain text without markup, links, code, or HTML", evidence.ReadmeExcerpt)
|
||||
}
|
||||
for _, request := range fake.requests {
|
||||
if request.authorization != "" {
|
||||
t.Fatalf("a request without a token sent Authorization %q", request.authorization)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchSendsTheTokenAndTheStoredETag(t *testing.T) {
|
||||
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Header.Get("If-None-Match") == `"repo-1"` {
|
||||
writer.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
publicRepository(writer, request)
|
||||
}}
|
||||
fetcher := newTestFetcher(t, fake, "secret-token")
|
||||
previous := outbound.RepositoryCheck{
|
||||
State: outbound.RepositoryCheckVerified, RepositoryETag: `"repo-1"`, GitHubID: 7,
|
||||
Evidence: domain.RepositoryEvidence{Description: "kept"},
|
||||
}
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), previous)
|
||||
if err != nil || !result.NotModified || result.Evidence.Description != "kept" {
|
||||
t.Fatalf("Fetch(not modified) = %+v, %v", result, err)
|
||||
}
|
||||
if len(fake.requests) != 1 || fake.requests[0].authorization != "Bearer secret-token" || fake.requests[0].ifNoneMatch != `"repo-1"` {
|
||||
t.Fatalf("requests = %+v", fake.requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchTreatsMissingAndPrivateRepositoriesAsNotFound(t *testing.T) {
|
||||
for name, handler := range map[string]http.HandlerFunc{
|
||||
"missing": http.NotFound,
|
||||
"private": func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":true,"visibility":"private","description":"secret"}`))
|
||||
},
|
||||
"internal": func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"internal"}`))
|
||||
},
|
||||
} {
|
||||
fetcher := newTestFetcher(t, &fakeGitHub{handler: handler}, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil || result.Found || result.Evidence.Description != "" {
|
||||
t.Errorf("%s: result = %+v, %v; want not found without metadata", name, result, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchClassifiesRateLimitsAndFailures(t *testing.T) {
|
||||
reset := strconv.FormatInt(testNow.Add(20*time.Minute).Unix(), 10)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
write func(http.ResponseWriter)
|
||||
class outbound.RepositoryFailureClass
|
||||
wait time.Duration
|
||||
}{
|
||||
{"primary limit", func(writer http.ResponseWriter) {
|
||||
writer.Header().Set("X-RateLimit-Remaining", "0")
|
||||
writer.Header().Set("X-RateLimit-Reset", reset)
|
||||
writer.WriteHeader(http.StatusForbidden)
|
||||
}, outbound.RepositoryFailureRateLimited, 20 * time.Minute},
|
||||
{"secondary limit", func(writer http.ResponseWriter) {
|
||||
writer.Header().Set("Retry-After", "5")
|
||||
writer.WriteHeader(http.StatusTooManyRequests)
|
||||
}, outbound.RepositoryFailureRateLimited, minRateLimitWait},
|
||||
{"server error", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusBadGateway) }, outbound.RepositoryFailureServerError, 0},
|
||||
{"bad token", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusUnauthorized) }, outbound.RepositoryFailureInvalidResponse, 0},
|
||||
{"broken body", func(writer http.ResponseWriter) { _, _ = writer.Write([]byte(`{"id":`)) }, outbound.RepositoryFailureInvalidResponse, 0},
|
||||
} {
|
||||
fetcher := newTestFetcher(t, &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) { test.write(writer) }}, "")
|
||||
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
var fetchError *outbound.RepositoryFetchError
|
||||
if !errors.As(err, &fetchError) || fetchError.Class != test.class || fetchError.RetryAfter != test.wait {
|
||||
t.Errorf("%s: error = %v, want class %s wait %s", test.name, err, test.class, test.wait)
|
||||
}
|
||||
if !errors.Is(err, outbound.ErrRepositoryFetchUnavailable) {
|
||||
t.Errorf("%s: error does not match ErrRepositoryFetchUnavailable", test.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchFollowsOnlySameOriginRedirects(t *testing.T) {
|
||||
other := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
t.Error("the fetcher followed a redirect to another origin")
|
||||
_, _ = writer.Write([]byte(`{"id":1}`))
|
||||
}))
|
||||
defer other.Close()
|
||||
fake := &fakeGitHub{}
|
||||
fake.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/repos/Example/renamed":
|
||||
http.Redirect(writer, request, "/repos/Example/ledger", http.StatusMovedPermanently)
|
||||
case "/repos/Example/escape":
|
||||
http.Redirect(writer, request, other.URL+"/repos/Example/ledger", http.StatusMovedPermanently)
|
||||
default:
|
||||
publicRepository(writer, request)
|
||||
}
|
||||
}
|
||||
fetcher := newTestFetcher(t, fake, "secret-token")
|
||||
if result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/renamed"), outbound.RepositoryCheck{}); err != nil || !result.Found {
|
||||
t.Fatalf("same-origin redirect = %+v, %v", result, err)
|
||||
}
|
||||
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/escape"), outbound.RepositoryCheck{})
|
||||
var fetchError *outbound.RepositoryFetchError
|
||||
if !errors.As(err, &fetchError) || fetchError.Class != outbound.RepositoryFailureNetwork {
|
||||
t.Fatalf("cross-origin redirect error = %v, want a refused request", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsTheBodiesItReads(t *testing.T) {
|
||||
huge := strings.Repeat("word ", maxReadmeBytes)
|
||||
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path == "/repos/Example/ledger/readme" {
|
||||
_, _ = writer.Write([]byte(huge))
|
||||
return
|
||||
}
|
||||
publicRepository(writer, request)
|
||||
}}
|
||||
fetcher := newTestFetcher(t, fake, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() error = %v", err)
|
||||
}
|
||||
if runes := len([]rune(result.Evidence.ReadmeExcerpt)); runes == 0 || runes > maxReadmeRunes {
|
||||
t.Fatalf("readme excerpt has %d runes, want at most %d", runes, maxReadmeRunes)
|
||||
}
|
||||
oversized := &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"description":"` + strings.Repeat("x", maxMetadataBytes) + `"}`))
|
||||
}}
|
||||
if _, err := newTestFetcher(t, oversized, "").Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{}); err == nil {
|
||||
t.Fatal("a repository document over the cap was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFetcherUsesOnlyTheGitHubOrigin(t *testing.T) {
|
||||
fetcher, err := NewFetcher(time.Second, "", time.Now)
|
||||
if err != nil || fetcher.origin != "https://api.github.com" {
|
||||
t.Fatalf("NewFetcher() origin = %q, %v", fetcher.origin, err)
|
||||
}
|
||||
if _, err := fetcher.Fetch(context.Background(), domain.GitHubRepository{}, outbound.RepositoryCheck{}); !errors.Is(err, domain.ErrInvalidGitHubRepository) {
|
||||
t.Fatalf("Fetch(zero repository) error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import (
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
|
||||
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
|
||||
"^[A-Za-z0-9._/-]+$": ogenregex.MustCompile("^[A-Za-z0-9._/-]+$"),
|
||||
"^[a-z0-9._-]+$": ogenregex.MustCompile("^[a-z0-9._-]+$"),
|
||||
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
|
||||
}
|
||||
var (
|
||||
|
||||
@@ -27,6 +27,19 @@ func trimTrailingSlashes(u *url.URL) {
|
||||
|
||||
// Invoker invokes operations described by OpenAPI v3 specification.
|
||||
type Invoker interface {
|
||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||
//
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
||||
// service never logs it.
|
||||
//
|
||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||
// names a model that the service does not serve, answers 400.
|
||||
//
|
||||
// POST /v1/embeddings
|
||||
CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error)
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
@@ -80,6 +93,96 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
|
||||
return u
|
||||
}
|
||||
|
||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||
//
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
||||
// service never logs it.
|
||||
//
|
||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||
// names a model that the service does not serve, answers 400.
|
||||
//
|
||||
// POST /v1/embeddings
|
||||
func (c *Client) CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error) {
|
||||
res, err := c.sendCreateMLEmbeddings(ctx, request)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (res CreateMLEmbeddingsRes, err error) {
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("CreateMLEmbeddings"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.URLTemplateKey.String("/v1/embeddings"),
|
||||
}
|
||||
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
|
||||
}()
|
||||
|
||||
// Increment request counter.
|
||||
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, CreateMLEmbeddingsOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
clientSpanKind,
|
||||
)
|
||||
// Track stage for error reporting.
|
||||
var stage string
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, stage)
|
||||
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
stage = "BuildURL"
|
||||
u := uri.Clone(c.requestURL(ctx))
|
||||
var pathParts [1]string
|
||||
pathParts[0] = "/v1/embeddings"
|
||||
uri.AddPathParts(u, pathParts[:]...)
|
||||
|
||||
stage = "EncodeRequest"
|
||||
r, err := ht.NewRequest(ctx, "POST", u)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "create request")
|
||||
}
|
||||
if err := encodeCreateMLEmbeddingsRequest(request, r); err != nil {
|
||||
return res, errors.Wrap(err, "encode request")
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
body := resp.Body
|
||||
defer func() {
|
||||
// Drain the body to EOF before closing, so the underlying
|
||||
// connection can be reused by the Transport regardless of the
|
||||
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
|
||||
_, _ = io.Copy(io.Discard, body)
|
||||
_ = body.Close()
|
||||
}()
|
||||
|
||||
stage = "DecodeResponse"
|
||||
result, err := decodeCreateMLEmbeddingsResponse(resp)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package api
|
||||
|
||||
type CreateMLEmbeddingsRes interface {
|
||||
createMLEmbeddingsRes()
|
||||
}
|
||||
|
||||
type GetMLReadyzRes interface {
|
||||
getMLReadyzRes()
|
||||
}
|
||||
@@ -11,6 +11,576 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// Encode encodes EmbeddingInputKind as json.
|
||||
func (s EmbeddingInputKind) Encode(e *jx.Encoder) {
|
||||
e.Str(string(s))
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingInputKind from json.
|
||||
func (s *EmbeddingInputKind) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingInputKind to nil")
|
||||
}
|
||||
v, err := d.StrBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Try to use constant string.
|
||||
switch EmbeddingInputKind(v) {
|
||||
case EmbeddingInputKindQuery:
|
||||
*s = EmbeddingInputKindQuery
|
||||
case EmbeddingInputKindDocument:
|
||||
*s = EmbeddingInputKindDocument
|
||||
default:
|
||||
*s = EmbeddingInputKind(v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingInputKind) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingInputKind) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingModel) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingModel) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("id")
|
||||
e.Str(s.ID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("revision")
|
||||
e.Str(s.Revision)
|
||||
}
|
||||
{
|
||||
e.FieldStart("dimension")
|
||||
e.Int32(s.Dimension)
|
||||
}
|
||||
{
|
||||
e.FieldStart("max_tokens")
|
||||
e.Int32(s.MaxTokens)
|
||||
}
|
||||
{
|
||||
e.FieldStart("prompt_version")
|
||||
e.Str(s.PromptVersion)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingModel = [5]string{
|
||||
0: "id",
|
||||
1: "revision",
|
||||
2: "dimension",
|
||||
3: "max_tokens",
|
||||
4: "prompt_version",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingModel from json.
|
||||
func (s *EmbeddingModel) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingModel to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "id":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.ID = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"id\"")
|
||||
}
|
||||
case "revision":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Revision = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"revision\"")
|
||||
}
|
||||
case "dimension":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.Dimension = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"dimension\"")
|
||||
}
|
||||
case "max_tokens":
|
||||
requiredBitSet[0] |= 1 << 3
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.MaxTokens = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"max_tokens\"")
|
||||
}
|
||||
case "prompt_version":
|
||||
requiredBitSet[0] |= 1 << 4
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.PromptVersion = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"prompt_version\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingModel")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00011111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingModel) {
|
||||
name = jsonFieldsNameOfEmbeddingModel[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingModel) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingModel) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingRequest) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingRequest) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
if s.Model.Set {
|
||||
e.FieldStart("model")
|
||||
s.Model.Encode(e)
|
||||
}
|
||||
}
|
||||
{
|
||||
e.FieldStart("kind")
|
||||
s.Kind.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("texts")
|
||||
e.ArrStart()
|
||||
for _, elem := range s.Texts {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingRequest = [3]string{
|
||||
0: "model",
|
||||
1: "kind",
|
||||
2: "texts",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingRequest from json.
|
||||
func (s *EmbeddingRequest) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingRequest to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "model":
|
||||
if err := func() error {
|
||||
s.Model.Reset()
|
||||
if err := s.Model.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"model\"")
|
||||
}
|
||||
case "kind":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
if err := s.Kind.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"kind\"")
|
||||
}
|
||||
case "texts":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
s.Texts = make([]EmbeddingText, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem EmbeddingText
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Texts = append(s.Texts, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"texts\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingRequest")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000110,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingRequest) {
|
||||
name = jsonFieldsNameOfEmbeddingRequest[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingRequest) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingRequest) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingResponse) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingResponse) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("model")
|
||||
s.Model.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("kind")
|
||||
s.Kind.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("vectors")
|
||||
e.ArrStart()
|
||||
for _, elem := range s.Vectors {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingResponse = [3]string{
|
||||
0: "model",
|
||||
1: "kind",
|
||||
2: "vectors",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingResponse from json.
|
||||
func (s *EmbeddingResponse) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingResponse to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "model":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Model.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"model\"")
|
||||
}
|
||||
case "kind":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
if err := s.Kind.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"kind\"")
|
||||
}
|
||||
case "vectors":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
s.Vectors = make([]EmbeddingVector, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem EmbeddingVector
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Vectors = append(s.Vectors, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"vectors\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingResponse")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingResponse) {
|
||||
name = jsonFieldsNameOfEmbeddingResponse[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingResponse) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingResponse) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes EmbeddingText as json.
|
||||
func (s EmbeddingText) Encode(e *jx.Encoder) {
|
||||
unwrapped := string(s)
|
||||
|
||||
e.Str(unwrapped)
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingText from json.
|
||||
func (s *EmbeddingText) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingText to nil")
|
||||
}
|
||||
var unwrapped string
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
unwrapped = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = EmbeddingText(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingText) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingText) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes EmbeddingVector as json.
|
||||
func (s EmbeddingVector) Encode(e *jx.Encoder) {
|
||||
unwrapped := []float32(s)
|
||||
|
||||
e.ArrStart()
|
||||
for _, elem := range unwrapped {
|
||||
e.Float32(elem)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingVector from json.
|
||||
func (s *EmbeddingVector) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingVector to nil")
|
||||
}
|
||||
var unwrapped []float32
|
||||
if err := func() error {
|
||||
unwrapped = make([]float32, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem float32
|
||||
v, err := d.Float32()
|
||||
elem = float32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
unwrapped = append(unwrapped, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = EmbeddingVector(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingVector) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingVector) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes GetMLReadyzOK as json.
|
||||
func (s *GetMLReadyzOK) Encode(e *jx.Encoder) {
|
||||
unwrapped := (*MLReadinessResponse)(s)
|
||||
@@ -668,6 +1238,8 @@ func (s *ProblemCode) Decode(d *jx.Decoder) error {
|
||||
*s = ProblemCodeInternal
|
||||
case ProblemCodeNotImplemented:
|
||||
*s = ProblemCodeNotImplemented
|
||||
case ProblemCodeServiceUnavailable:
|
||||
*s = ProblemCodeServiceUnavailable
|
||||
default:
|
||||
*s = ProblemCode(v)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ package api
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
GetMLHealthzOperation OperationName = "GetMLHealthz"
|
||||
GetMLReadyzOperation OperationName = "GetMLReadyz"
|
||||
CreateMLEmbeddingsOperation OperationName = "CreateMLEmbeddings"
|
||||
GetMLHealthzOperation OperationName = "GetMLHealthz"
|
||||
GetMLReadyzOperation OperationName = "GetMLReadyz"
|
||||
)
|
||||
@@ -1,3 +1,25 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
func encodeCreateMLEmbeddingsRequest(
|
||||
req *EmbeddingRequest,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
e := new(jx.Encoder)
|
||||
{
|
||||
req.Encode(e)
|
||||
}
|
||||
encoded := e.Bytes()
|
||||
ht.SetBody(r, bytes.NewReader(encoded), contentType)
|
||||
return nil
|
||||
}
|
||||
@@ -13,6 +13,248 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddingsRes, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response EmbeddingResponse
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
// Code 400.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsBadRequest{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 413:
|
||||
// Code 413.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsRequestEntityTooLarge{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 503:
|
||||
// Code 503.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsServiceUnavailable{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ProblemStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &ProblemStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
|
||||
@@ -12,6 +12,223 @@ func (s *ProblemStatusCode) Error() string {
|
||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||
}
|
||||
|
||||
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsRequestEntityTooLarge ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsRequestEntityTooLarge) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
||||
|
||||
// Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so
|
||||
// callers never send model instructions.
|
||||
//
|
||||
// - query: the side that searches, such as a hiring need or one requirement of it. The service
|
||||
// prepends the retrieval instruction of the model.
|
||||
// - document: the side that is searched, such as a candidate card or one item of it. The service adds
|
||||
// no prompt.
|
||||
//
|
||||
// Ref: #/components/schemas/EmbeddingInputKind
|
||||
type EmbeddingInputKind string
|
||||
|
||||
const (
|
||||
EmbeddingInputKindQuery EmbeddingInputKind = "query"
|
||||
EmbeddingInputKindDocument EmbeddingInputKind = "document"
|
||||
)
|
||||
|
||||
// AllValues returns all EmbeddingInputKind values.
|
||||
func (EmbeddingInputKind) AllValues() []EmbeddingInputKind {
|
||||
return []EmbeddingInputKind{
|
||||
EmbeddingInputKindQuery,
|
||||
EmbeddingInputKindDocument,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EmbeddingInputKind) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EmbeddingInputKindQuery:
|
||||
return []byte(s), nil
|
||||
case EmbeddingInputKindDocument:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EmbeddingInputKind) UnmarshalText(data []byte) error {
|
||||
switch EmbeddingInputKind(data) {
|
||||
case EmbeddingInputKindQuery:
|
||||
*s = EmbeddingInputKindQuery
|
||||
return nil
|
||||
case EmbeddingInputKindDocument:
|
||||
*s = EmbeddingInputKindDocument
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// The model that produced the vectors. A caller stores these values with every vector and never
|
||||
// compares vectors of different models, revisions, or prompt versions.
|
||||
// Ref: #/components/schemas/EmbeddingModel
|
||||
type EmbeddingModel struct {
|
||||
// Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
|
||||
ID string `json:"id"`
|
||||
// Pinned revision of the weights, a commit hash for a published model.
|
||||
Revision string `json:"revision"`
|
||||
// Length of every vector.
|
||||
Dimension int32 `json:"dimension"`
|
||||
// Token limit after which a text is truncated.
|
||||
MaxTokens int32 `json:"max_tokens"`
|
||||
// Version of the prompt and pooling recipe of the service. A change of the query instruction or the
|
||||
// pooling changes it.
|
||||
PromptVersion string `json:"prompt_version"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *EmbeddingModel) GetID() string {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetRevision returns the value of Revision.
|
||||
func (s *EmbeddingModel) GetRevision() string {
|
||||
return s.Revision
|
||||
}
|
||||
|
||||
// GetDimension returns the value of Dimension.
|
||||
func (s *EmbeddingModel) GetDimension() int32 {
|
||||
return s.Dimension
|
||||
}
|
||||
|
||||
// GetMaxTokens returns the value of MaxTokens.
|
||||
func (s *EmbeddingModel) GetMaxTokens() int32 {
|
||||
return s.MaxTokens
|
||||
}
|
||||
|
||||
// GetPromptVersion returns the value of PromptVersion.
|
||||
func (s *EmbeddingModel) GetPromptVersion() string {
|
||||
return s.PromptVersion
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *EmbeddingModel) SetID(val string) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetRevision sets the value of Revision.
|
||||
func (s *EmbeddingModel) SetRevision(val string) {
|
||||
s.Revision = val
|
||||
}
|
||||
|
||||
// SetDimension sets the value of Dimension.
|
||||
func (s *EmbeddingModel) SetDimension(val int32) {
|
||||
s.Dimension = val
|
||||
}
|
||||
|
||||
// SetMaxTokens sets the value of MaxTokens.
|
||||
func (s *EmbeddingModel) SetMaxTokens(val int32) {
|
||||
s.MaxTokens = val
|
||||
}
|
||||
|
||||
// SetPromptVersion sets the value of PromptVersion.
|
||||
func (s *EmbeddingModel) SetPromptVersion(val string) {
|
||||
s.PromptVersion = val
|
||||
}
|
||||
|
||||
// Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are
|
||||
// ordered by length with the request position as the tie-breaker, encoded in micro-batches of the
|
||||
// configured size, and returned in request order. The same texts in the same request on the same image
|
||||
// and thread count give the same vectors.
|
||||
// Ref: #/components/schemas/EmbeddingRequest
|
||||
type EmbeddingRequest struct {
|
||||
// Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of
|
||||
// the service. A service may load several models, for example the members of an ensemble; a model it
|
||||
// does not serve answers 400 validation_failed with the pointer `/model`.
|
||||
Model OptString `json:"model"`
|
||||
Kind EmbeddingInputKind `json:"kind"`
|
||||
Texts []EmbeddingText `json:"texts"`
|
||||
}
|
||||
|
||||
// GetModel returns the value of Model.
|
||||
func (s *EmbeddingRequest) GetModel() OptString {
|
||||
return s.Model
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EmbeddingRequest) GetKind() EmbeddingInputKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetTexts returns the value of Texts.
|
||||
func (s *EmbeddingRequest) GetTexts() []EmbeddingText {
|
||||
return s.Texts
|
||||
}
|
||||
|
||||
// SetModel sets the value of Model.
|
||||
func (s *EmbeddingRequest) SetModel(val OptString) {
|
||||
s.Model = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EmbeddingRequest) SetKind(val EmbeddingInputKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetTexts sets the value of Texts.
|
||||
func (s *EmbeddingRequest) SetTexts(val []EmbeddingText) {
|
||||
s.Texts = val
|
||||
}
|
||||
|
||||
// Vectors in the order of the request texts.
|
||||
// Ref: #/components/schemas/EmbeddingResponse
|
||||
type EmbeddingResponse struct {
|
||||
Model EmbeddingModel `json:"model"`
|
||||
Kind EmbeddingInputKind `json:"kind"`
|
||||
Vectors []EmbeddingVector `json:"vectors"`
|
||||
}
|
||||
|
||||
// GetModel returns the value of Model.
|
||||
func (s *EmbeddingResponse) GetModel() EmbeddingModel {
|
||||
return s.Model
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EmbeddingResponse) GetKind() EmbeddingInputKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetVectors returns the value of Vectors.
|
||||
func (s *EmbeddingResponse) GetVectors() []EmbeddingVector {
|
||||
return s.Vectors
|
||||
}
|
||||
|
||||
// SetModel sets the value of Model.
|
||||
func (s *EmbeddingResponse) SetModel(val EmbeddingModel) {
|
||||
s.Model = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EmbeddingResponse) SetKind(val EmbeddingInputKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetVectors sets the value of Vectors.
|
||||
func (s *EmbeddingResponse) SetVectors(val []EmbeddingVector) {
|
||||
s.Vectors = val
|
||||
}
|
||||
|
||||
func (*EmbeddingResponse) createMLEmbeddingsRes() {}
|
||||
|
||||
type EmbeddingText string
|
||||
|
||||
type EmbeddingVector []float32
|
||||
|
||||
type GetMLReadyzOK MLReadinessResponse
|
||||
|
||||
func (*GetMLReadyzOK) getMLReadyzRes() {}
|
||||
@@ -297,6 +514,8 @@ func (s *Problem) SetErrors(val []ProblemFieldError) {
|
||||
// - rate_limited (429): too many requests; see Retry-After.
|
||||
// - internal (500): unexpected server error.
|
||||
// - not_implemented (501): the operation is in the contract but not implemented yet.
|
||||
// - service_unavailable (503): the service cannot serve the request now, for example while a model
|
||||
// loads; retry later.
|
||||
//
|
||||
// The enum keeps the public API codes so both contracts share one Problem shape. The identity codes
|
||||
// verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and
|
||||
@@ -325,6 +544,7 @@ const (
|
||||
ProblemCodeRateLimited ProblemCode = "rate_limited"
|
||||
ProblemCodeInternal ProblemCode = "internal"
|
||||
ProblemCodeNotImplemented ProblemCode = "not_implemented"
|
||||
ProblemCodeServiceUnavailable ProblemCode = "service_unavailable"
|
||||
)
|
||||
|
||||
// AllValues returns all ProblemCode values.
|
||||
@@ -350,6 +570,7 @@ func (ProblemCode) AllValues() []ProblemCode {
|
||||
ProblemCodeRateLimited,
|
||||
ProblemCodeInternal,
|
||||
ProblemCodeNotImplemented,
|
||||
ProblemCodeServiceUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,6 +617,8 @@ func (s ProblemCode) MarshalText() ([]byte, error) {
|
||||
return []byte(s), nil
|
||||
case ProblemCodeNotImplemented:
|
||||
return []byte(s), nil
|
||||
case ProblemCodeServiceUnavailable:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
@@ -464,6 +687,9 @@ func (s *ProblemCode) UnmarshalText(data []byte) error {
|
||||
case ProblemCodeNotImplemented:
|
||||
*s = ProblemCodeNotImplemented
|
||||
return nil
|
||||
case ProblemCodeServiceUnavailable:
|
||||
*s = ProblemCodeServiceUnavailable
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,376 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *CreateMLEmbeddingsBadRequest) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsRequestEntityTooLarge) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingInputKind) Validate() error {
|
||||
switch s {
|
||||
case "query":
|
||||
return nil
|
||||
case "document":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EmbeddingModel) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 200,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.ID)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "id",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 64,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Revision)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "revision",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 4096,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.Dimension)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "dimension",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 32768,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.MaxTokens)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "max_tokens",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 64,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[a-z0-9._-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.PromptVersion)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "prompt_version",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EmbeddingRequest) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if value, ok := s.Model.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 200,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "model",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Texts == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 32,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Texts)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Texts {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "texts",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EmbeddingResponse) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Model.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "model",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Vectors == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 32,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Vectors)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Vectors {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "vectors",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingText) Validate() error {
|
||||
alias := (string)(s)
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 8000,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(alias)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingVector) Validate() error {
|
||||
alias := ([]float32)(s)
|
||||
if alias == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 4096,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(alias)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range alias {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(elem)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetMLReadyzOK) Validate() error {
|
||||
alias := (*MLReadinessResponse)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -349,6 +719,8 @@ func (s ProblemCode) Validate() error {
|
||||
return nil
|
||||
case "not_implemented":
|
||||
return nil
|
||||
case "service_unavailable":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package ml is the client of the internal ML service. The generated ogen
|
||||
// client in ./api carries the contract; this adapter adds the request
|
||||
// timeout, a response size cap, a circuit breaker, batching, and the checks
|
||||
// that turn the response into domain vectors.
|
||||
package ml
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/ml/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxResponseBytes caps one response: 32 vectors of 4096 floats as JSON
|
||||
// stay far below it.
|
||||
maxResponseBytes = 16 << 20
|
||||
// maxTextRunes is the contract bound of one text; longer texts are cut
|
||||
// before they are sent, the model truncates at its token limit anyway.
|
||||
maxTextRunes = 8000
|
||||
)
|
||||
|
||||
// Settings configure the client.
|
||||
type Settings struct {
|
||||
// BaseURL is the ML service origin, for example http://ml:8000.
|
||||
BaseURL string
|
||||
// Timeout bounds one HTTP request.
|
||||
Timeout time.Duration
|
||||
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
||||
FailureThreshold int
|
||||
OpenDuration time.Duration
|
||||
}
|
||||
|
||||
// Embedder implements outbound.TextEmbedder over HTTP.
|
||||
type Embedder struct {
|
||||
client *api.Client
|
||||
breaker *breaker
|
||||
}
|
||||
|
||||
var _ outbound.TextEmbedder = (*Embedder)(nil)
|
||||
|
||||
// NewEmbedder validates the settings and builds the client. Nothing connects.
|
||||
func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
|
||||
const location = "ml.NewEmbedder"
|
||||
parsed, err := url.Parse(settings.BaseURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil {
|
||||
return nil, errors.New(location + " - ML service URL must be an http or https origin without credentials")
|
||||
}
|
||||
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
|
||||
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Timeout: settings.Timeout,
|
||||
Transport: limitedTransport{next: http.DefaultTransport},
|
||||
// The service is a fixed internal origin; a redirect is never expected.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
client, err := api.NewClient(parsed.String(), api.WithClient(httpClient))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
||||
}
|
||||
return &Embedder{
|
||||
client: client,
|
||||
breaker: &breaker{threshold: settings.FailureThreshold, open: settings.OpenDuration, clock: clock},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed encodes texts with the named model in contract-sized batches and
|
||||
// checks that every batch came from the same model. The caller compares the
|
||||
// returned identity with the one it expects.
|
||||
func (embedder *Embedder) Embed(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
const location = "ml.Embedder.Embed"
|
||||
var model domain.SemanticModel
|
||||
vectors := make([]domain.SemanticVector, 0, len(texts))
|
||||
for start := 0; start < len(texts); start += outbound.MaxEmbeddingBatch {
|
||||
end := min(start+outbound.MaxEmbeddingBatch, len(texts))
|
||||
batchModel, batch, err := embedder.embedBatch(ctx, modelID, kind, texts[start:end])
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - encode batch: %w", location, err)
|
||||
}
|
||||
if start > 0 && batchModel != model {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - the model changed between batches: %w", location, outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
model = batchModel
|
||||
vectors = append(vectors, batch...)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func (embedder *Embedder) embedBatch(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
if len(texts) == 0 {
|
||||
return domain.SemanticModel{}, nil, nil
|
||||
}
|
||||
if !embedder.breaker.allow() {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("circuit is open: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
request := &api.EmbeddingRequest{
|
||||
Model: api.NewOptString(modelID), Kind: api.EmbeddingInputKind(kind), Texts: make([]api.EmbeddingText, 0, len(texts)),
|
||||
}
|
||||
for _, text := range texts {
|
||||
request.Texts = append(request.Texts, api.EmbeddingText(cutRunes(text, maxTextRunes)))
|
||||
}
|
||||
result, err := embedder.client.CreateMLEmbeddings(ctx, request)
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
// The client error can quote the URL but never the request body.
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("call the ML service: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
switch response := result.(type) {
|
||||
case *api.EmbeddingResponse:
|
||||
model, vectors, err := decodeResponse(response, kind, len(texts))
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, err
|
||||
}
|
||||
embedder.breaker.success()
|
||||
return model, vectors, nil
|
||||
case *api.CreateMLEmbeddingsServiceUnavailable:
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
||||
default:
|
||||
// 400 or 413: the request breaks the contract or names a model the
|
||||
// service does not serve, and a repeat cannot fix it.
|
||||
embedder.breaker.success()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeResponse(response *api.EmbeddingResponse, kind outbound.EmbeddingKind, count int) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
model := domain.SemanticModel{
|
||||
ID: response.Model.ID, Revision: response.Model.Revision, PromptVersion: response.Model.PromptVersion,
|
||||
}
|
||||
if err := model.Validate(); err != nil || string(response.Kind) != string(kind) || len(response.Vectors) != count {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the response does not match the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors := make([]domain.SemanticVector, 0, count)
|
||||
for _, raw := range response.Vectors {
|
||||
if len(raw) != int(response.Model.Dimension) {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector has the wrong dimension: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vector, err := domain.NewSemanticVector(raw)
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector is invalid: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors = append(vectors, vector)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func cutRunes(text string, limit int) string {
|
||||
runes := []rune(text)
|
||||
if len(runes) <= limit {
|
||||
return text
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
// limitedTransport caps the bytes read from a response body.
|
||||
type limitedTransport struct {
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (transport limitedTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := transport.next.RoundTrip(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body = limitedBody{Reader: io.LimitReader(response.Body, maxResponseBytes), Closer: response.Body}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// breaker opens after threshold consecutive failures and lets one probe
|
||||
// through after the open duration; a success closes it.
|
||||
type breaker struct {
|
||||
mutex sync.Mutex
|
||||
threshold int
|
||||
open time.Duration
|
||||
clock func() time.Time
|
||||
failures int
|
||||
openUntil time.Time
|
||||
probing bool
|
||||
}
|
||||
|
||||
func (circuit *breaker) allow() bool {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
if circuit.failures < circuit.threshold {
|
||||
return true
|
||||
}
|
||||
if circuit.clock().Before(circuit.openUntil) || circuit.probing {
|
||||
return false
|
||||
}
|
||||
circuit.probing = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (circuit *breaker) success() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures, circuit.probing = 0, false
|
||||
}
|
||||
|
||||
func (circuit *breaker) failure() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures++
|
||||
circuit.probing = false
|
||||
if circuit.failures >= circuit.threshold {
|
||||
circuit.openUntil = circuit.clock().Add(circuit.open)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package ml
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type fakeService struct {
|
||||
mutex sync.Mutex
|
||||
requests int
|
||||
batches []int
|
||||
models []string
|
||||
respond func(writer http.ResponseWriter, kind string, texts []string)
|
||||
}
|
||||
|
||||
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
var body struct {
|
||||
Model string `json:"model"`
|
||||
Kind string `json:"kind"`
|
||||
Texts []string `json:"texts"`
|
||||
}
|
||||
_ = json.NewDecoder(request.Body).Decode(&body)
|
||||
service.mutex.Lock()
|
||||
service.requests++
|
||||
service.batches = append(service.batches, len(body.Texts))
|
||||
service.models = append(service.models, body.Model)
|
||||
service.mutex.Unlock()
|
||||
service.respond(writer, body.Kind, body.Texts)
|
||||
}
|
||||
|
||||
func validResponse(writer http.ResponseWriter, kind string, texts []string) {
|
||||
vectors := make([][]float32, 0, len(texts))
|
||||
for range texts {
|
||||
vectors = append(vectors, []float32{0.6, 0.8})
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"model": map[string]any{"id": "example/model", "revision": "abc", "dimension": 2, "max_tokens": 1024, "prompt_version": "v1"},
|
||||
"kind": kind, "vectors": vectors,
|
||||
})
|
||||
}
|
||||
|
||||
func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time) *Embedder {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(service)
|
||||
t.Cleanup(server.Close)
|
||||
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmbedder() error = %v", err)
|
||||
}
|
||||
return embedder
|
||||
}
|
||||
|
||||
func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) {
|
||||
service := &fakeService{respond: validResponse}
|
||||
embedder := newTestEmbedder(t, service, time.Now)
|
||||
texts := make([]string, 40)
|
||||
for index := range texts {
|
||||
texts[index] = "text"
|
||||
}
|
||||
model, vectors, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, texts)
|
||||
if err != nil || len(vectors) != 40 || model.ID != "example/model" || model.PromptVersion != "v1" {
|
||||
t.Fatalf("Embed() = %+v, %d vectors, %v", model, len(vectors), err)
|
||||
}
|
||||
if len(service.batches) != 2 || service.batches[0] != outbound.MaxEmbeddingBatch || service.batches[1] != 8 {
|
||||
t.Fatalf("batches = %v, want 32 and 8", service.batches)
|
||||
}
|
||||
if strings.Join(service.models, ",") != "example/model,example/model" {
|
||||
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
|
||||
for name, respond := range map[string]func(http.ResponseWriter, string, []string){
|
||||
"too few vectors": func(writer http.ResponseWriter, kind string, texts []string) { validResponse(writer, kind, texts[:1]) },
|
||||
"not normalized": func(writer http.ResponseWriter, kind string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"model": map[string]any{"id": "m/x", "revision": "r", "dimension": 2, "max_tokens": 1, "prompt_version": "v"},
|
||||
"kind": kind, "vectors": [][]float32{{1, 1}, {1, 1}},
|
||||
})
|
||||
},
|
||||
"bad request": func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:validation_failed","title":"x","status":400,"code":"validation_failed"}`))
|
||||
},
|
||||
} {
|
||||
embedder := newTestEmbedder(t, &fakeService{respond: respond}, time.Now)
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a", "b"}); !errors.Is(err, outbound.ErrEmbedderRejected) {
|
||||
t.Errorf("%s: error = %v, want ErrEmbedderRejected", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedOpensTheCircuitAfterRepeatedFailures(t *testing.T) {
|
||||
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
clock := func() time.Time { return now }
|
||||
service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"x","status":503,"code":"service_unavailable"}`))
|
||||
}}
|
||||
embedder := newTestEmbedder(t, service, clock)
|
||||
for range 3 {
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); !errors.Is(err, outbound.ErrEmbedderUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrEmbedderUnavailable", err)
|
||||
}
|
||||
}
|
||||
if service.requests != 2 {
|
||||
t.Fatalf("requests = %d, want the circuit to stop calling after 2 failures", service.requests)
|
||||
}
|
||||
now = now.Add(2 * time.Minute)
|
||||
service.respond = validResponse
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); err != nil {
|
||||
t.Fatalf("probe after the open duration error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedNeverQuotesTextsInErrors(t *testing.T) {
|
||||
embedder := newTestEmbedder(t, &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.WriteHeader(http.StatusInternalServerError)
|
||||
}}, time.Now)
|
||||
_, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, []string{"Jane Doe private summary"})
|
||||
if err == nil || strings.Contains(err.Error(), "Jane") {
|
||||
t.Fatalf("error = %v, want a failure without the text", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) {
|
||||
for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} {
|
||||
if _, err := NewEmbedder(Settings{BaseURL: raw, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,9 @@ type privacyCohortCandidate struct {
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
categories []domain.CandidateViewConfirmedCategoryInput
|
||||
// verifiedRepositories holds the keys of the repositories whose latest
|
||||
// check found them public.
|
||||
verifiedRepositories map[string]bool
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
@@ -94,6 +97,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
current.verifiedRepositories = verifiedRepositorySet(row.VerifiedRepositories)
|
||||
}
|
||||
if row.Kind.Valid {
|
||||
claim, err := privacyCohortStoredClaim(row)
|
||||
@@ -210,11 +214,22 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
||||
candidate.workFormats, nil,
|
||||
candidate.id, candidate.fields,
|
||||
domain.CandidateViewProfileFromContentWithRepositories(content, candidate.verifiedRepositories),
|
||||
candidate.categories, candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
// verifiedRepositorySet turns the keys of the verified repositories of one
|
||||
// candidate into a set.
|
||||
func verifiedRepositorySet(keys []string) map[string]bool {
|
||||
set := make(map[string]bool, len(keys))
|
||||
for _, key := range keys {
|
||||
set[key] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func privacyCohortJSONBytes(value any) ([]byte, error) {
|
||||
switch typed := value.(type) {
|
||||
case []byte:
|
||||
|
||||
@@ -134,6 +134,7 @@ func buildPreviewCandidateViewSource(
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
candidate.verifiedRepositories = verifiedRepositorySet(first.VerifiedRepositories)
|
||||
for _, row := range rows {
|
||||
if row.Kind.Valid {
|
||||
claim, err := previewStoredClaim(row)
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
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
|
||||
}
|
||||
@@ -361,6 +361,24 @@ type CandidateProfileOverlapConfirmation struct {
|
||||
SecondEndedOn pgtype.Text
|
||||
}
|
||||
|
||||
type CandidateProjectRepository struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
State string
|
||||
GithubID pgtype.Int8
|
||||
Description pgtype.Text
|
||||
Topics []string
|
||||
Languages []string
|
||||
ReadmeExcerpt pgtype.Text
|
||||
RepositoryEtag pgtype.Text
|
||||
ReadmeEtag pgtype.Text
|
||||
FailureClass pgtype.Text
|
||||
CheckedAt pgtype.Timestamptz
|
||||
RequestedAt pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidatePublication struct {
|
||||
UserID pgtype.UUID
|
||||
State string
|
||||
@@ -838,6 +856,22 @@ type ScheduledJob struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SemanticVector struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
ComputedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -68,11 +68,21 @@ SELECT
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
) AS confirmed_categories,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
|
||||
FROM candidate_project_repositories AS repository
|
||||
WHERE
|
||||
repository.candidate_id = effective.user_id
|
||||
AND repository.state = 'verified'
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS verified_repositories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
AND claim.kind IN ('stack', 'role', 'experience', 'project')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE NOT EXISTS (
|
||||
@@ -98,15 +108,18 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
VerifiedRepositories []string
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// The projection reads only stack, declared role, experience dates, and
|
||||
// projects with the keys of their verified repositories. It deliberately
|
||||
// excludes names, contacts, salary, location, soft skills, employer names,
|
||||
// summaries, and imported excerpts; the repository address of a project stays
|
||||
// in the private input and never reaches the card. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
@@ -132,6 +145,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
&i.VerifiedRepositories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -301,11 +315,21 @@ SELECT
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
) AS confirmed_categories,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
|
||||
FROM candidate_project_repositories AS repository
|
||||
WHERE
|
||||
repository.candidate_id = effective.user_id
|
||||
AND repository.state = 'verified'
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS verified_repositories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
AND claim.kind IN ('stack', 'role', 'experience', 'project')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE effective.user_id = $1
|
||||
@@ -326,6 +350,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
VerifiedRepositories []string
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
@@ -354,6 +379,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
&i.VerifiedRepositories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: project_repositories.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteUnlinkedCandidateProjectRepositories = `-- name: DeleteUnlinkedCandidateProjectRepositories :exec
|
||||
DELETE FROM candidate_project_repositories
|
||||
WHERE
|
||||
candidate_id = $1
|
||||
AND NOT (repository_key = ANY($2::text []))
|
||||
`
|
||||
|
||||
type DeleteUnlinkedCandidateProjectRepositoriesParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
LinkedKeys []string
|
||||
}
|
||||
|
||||
// Removes the checks of repositories that no project links any more.
|
||||
func (q *Queries) DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteUnlinkedCandidateProjectRepositories, arg.CandidateID, arg.LinkedKeys)
|
||||
return err
|
||||
}
|
||||
|
||||
const getCandidateProjectRepositoryForUpdate = `-- name: GetCandidateProjectRepositoryForUpdate :one
|
||||
SELECT
|
||||
candidate_id, repository_key, state, github_id, description, topics,
|
||||
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
|
||||
checked_at, requested_at, created_at, updated_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1 AND repository_key = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type GetCandidateProjectRepositoryForUpdateParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
}
|
||||
|
||||
func (q *Queries) GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error) {
|
||||
row := q.db.QueryRow(ctx, getCandidateProjectRepositoryForUpdate, arg.CandidateID, arg.RepositoryKey)
|
||||
var i CandidateProjectRepository
|
||||
err := row.Scan(
|
||||
&i.CandidateID,
|
||||
&i.RepositoryKey,
|
||||
&i.State,
|
||||
&i.GithubID,
|
||||
&i.Description,
|
||||
&i.Topics,
|
||||
&i.Languages,
|
||||
&i.ReadmeExcerpt,
|
||||
&i.RepositoryEtag,
|
||||
&i.ReadmeEtag,
|
||||
&i.FailureClass,
|
||||
&i.CheckedAt,
|
||||
&i.RequestedAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getLatestRepositoryCheckRequest = `-- name: GetLatestRepositoryCheckRequest :one
|
||||
SELECT MAX(requested_at)::timestamptz AS requested_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1
|
||||
`
|
||||
|
||||
// The latest check request of a candidate, for the per-candidate limit.
|
||||
func (q *Queries) GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error) {
|
||||
row := q.db.QueryRow(ctx, getLatestRepositoryCheckRequest, candidateID)
|
||||
var requested_at pgtype.Timestamptz
|
||||
err := row.Scan(&requested_at)
|
||||
return requested_at, err
|
||||
}
|
||||
|
||||
const listCandidateProjectRepositories = `-- name: ListCandidateProjectRepositories :many
|
||||
|
||||
SELECT
|
||||
candidate_id, repository_key, state, github_id, description, topics,
|
||||
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
|
||||
checked_at, requested_at, created_at, updated_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1
|
||||
ORDER BY repository_key
|
||||
`
|
||||
|
||||
// Server checks of the GitHub repositories that candidate projects link.
|
||||
// Every statement is scoped by the candidate.
|
||||
func (q *Queries) ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateProjectRepositories, candidateID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []CandidateProjectRepository
|
||||
for rows.Next() {
|
||||
var i CandidateProjectRepository
|
||||
if err := rows.Scan(
|
||||
&i.CandidateID,
|
||||
&i.RepositoryKey,
|
||||
&i.State,
|
||||
&i.GithubID,
|
||||
&i.Description,
|
||||
&i.Topics,
|
||||
&i.Languages,
|
||||
&i.ReadmeExcerpt,
|
||||
&i.RepositoryEtag,
|
||||
&i.ReadmeEtag,
|
||||
&i.FailureClass,
|
||||
&i.CheckedAt,
|
||||
&i.RequestedAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const requestCandidateProjectRepositoryCheck = `-- name: RequestCandidateProjectRepositoryCheck :exec
|
||||
INSERT INTO candidate_project_repositories (
|
||||
candidate_id, repository_key, state, requested_at, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, 'pending', $3,
|
||||
$3, $3
|
||||
)
|
||||
ON CONFLICT (candidate_id, repository_key) DO UPDATE
|
||||
SET
|
||||
requested_at = excluded.requested_at,
|
||||
updated_at = GREATEST(candidate_project_repositories.updated_at, excluded.updated_at)
|
||||
`
|
||||
|
||||
type RequestCandidateProjectRepositoryCheckParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
RequestedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// A new repository starts pending; a known one only records the request.
|
||||
func (q *Queries) RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error {
|
||||
_, err := q.db.Exec(ctx, requestCandidateProjectRepositoryCheck, arg.CandidateID, arg.RepositoryKey, arg.RequestedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveCandidateProjectRepositoryCheck = `-- name: SaveCandidateProjectRepositoryCheck :exec
|
||||
UPDATE candidate_project_repositories
|
||||
SET
|
||||
state = $1,
|
||||
github_id = $2,
|
||||
description = $3,
|
||||
topics = $4,
|
||||
languages = $5,
|
||||
readme_excerpt = $6,
|
||||
repository_etag = $7,
|
||||
readme_etag = $8,
|
||||
failure_class = $9,
|
||||
checked_at = $10,
|
||||
updated_at = GREATEST(updated_at, $10)
|
||||
WHERE candidate_id = $11 AND repository_key = $12
|
||||
`
|
||||
|
||||
type SaveCandidateProjectRepositoryCheckParams struct {
|
||||
State string
|
||||
GithubID pgtype.Int8
|
||||
Description pgtype.Text
|
||||
Topics []string
|
||||
Languages []string
|
||||
ReadmeExcerpt pgtype.Text
|
||||
RepositoryEtag pgtype.Text
|
||||
ReadmeEtag pgtype.Text
|
||||
FailureClass pgtype.Text
|
||||
CheckedAt pgtype.Timestamptz
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
}
|
||||
|
||||
func (q *Queries) SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error {
|
||||
_, err := q.db.Exec(ctx, saveCandidateProjectRepositoryCheck,
|
||||
arg.State,
|
||||
arg.GithubID,
|
||||
arg.Description,
|
||||
arg.Topics,
|
||||
arg.Languages,
|
||||
arg.ReadmeExcerpt,
|
||||
arg.RepositoryEtag,
|
||||
arg.ReadmeEtag,
|
||||
arg.FailureClass,
|
||||
arg.CheckedAt,
|
||||
arg.CandidateID,
|
||||
arg.RepositoryKey,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -217,9 +217,19 @@ type Querier interface {
|
||||
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
|
||||
// Stored embedding vectors. A candidate keeps one set of rows for a model:
|
||||
// the job deletes every other row of the candidate and model before it
|
||||
// inserts the new set, in one transaction. A need keeps the rows of its
|
||||
// latest computed requirements snapshot the same way.
|
||||
DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error
|
||||
// Removes every vector of a subject, of any model: a closed card or a need
|
||||
// without requirements keeps no derived data.
|
||||
DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error
|
||||
// No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
|
||||
// Removes the checks of repositories that no project links any more.
|
||||
DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
@@ -314,6 +324,7 @@ type Querier interface {
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
@@ -374,6 +385,8 @@ type Querier interface {
|
||||
// resend, which issues its token with the same credentials.
|
||||
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
|
||||
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
|
||||
// The latest check request of a candidate, for the per-candidate limit.
|
||||
GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error)
|
||||
// Reads the latest root in a specialization, optionally restricted to grade.
|
||||
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
|
||||
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
|
||||
@@ -599,6 +612,7 @@ type Querier interface {
|
||||
// moves a deadline. A concurrent insert of the same key waits for the first
|
||||
// transaction and then inserts nothing, or inserts after its rollback.
|
||||
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
|
||||
InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
// The initial public history is inserted in the caller's case transaction.
|
||||
// Any unique business conflict leaves the transaction usable so the caller can
|
||||
@@ -687,6 +701,9 @@ type Querier interface {
|
||||
// have no delivery and are never listed. The candidate scopes the rows, so
|
||||
// no identifier of another candidate can appear.
|
||||
ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error)
|
||||
// The item vectors of the candidates that a search returns, at most a few
|
||||
// dozen candidates.
|
||||
ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error)
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
@@ -697,6 +714,11 @@ type Querier interface {
|
||||
// read time, and is the current name. The page continues after the
|
||||
// (occurred_at, id) position of the last event of the previous page.
|
||||
ListCandidatePrivacyEvents(ctx context.Context, arg ListCandidatePrivacyEventsParams) ([]ListCandidatePrivacyEventsRow, error)
|
||||
// Server checks of the GitHub repositories that candidate projects link.
|
||||
// Every statement is scoped by the candidate.
|
||||
ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error)
|
||||
// The whole-view vectors of the candidates of one search.
|
||||
ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error)
|
||||
// One page of the subject's ledger, newest grant first, optionally limited
|
||||
// to one state. Every record query is scoped by the subject, so a caller
|
||||
// never reads or revokes another subject's consent. The state is computed,
|
||||
@@ -721,6 +743,11 @@ type Querier interface {
|
||||
// One bounded newest-first page. Both the organization scope and the tuple
|
||||
// cursor are applied before the limit.
|
||||
ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error)
|
||||
// The vectors of a need whose texts match the given digests of the
|
||||
// requirements snapshot that the search renders.
|
||||
ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error)
|
||||
// Needs and their current requirements snapshot for the backfill.
|
||||
ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error)
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
@@ -763,13 +790,22 @@ type Querier interface {
|
||||
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
// and event history. The tuple cursor matches the composite sort key.
|
||||
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
|
||||
// Candidates with a saved profile for the backfill, in identifier order
|
||||
// after a cursor. The job of a candidate who is not published removes the
|
||||
// stored vectors, so a backfill also cleans up after a closed card.
|
||||
ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error)
|
||||
// The digests of the stored rows of a subject and model, for the job that
|
||||
// decides whether anything changed.
|
||||
ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error)
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// The projection reads only stack, declared role, experience dates, and
|
||||
// projects with the keys of their verified repositories. It deliberately
|
||||
// excludes names, contacts, salary, location, soft skills, employer names,
|
||||
// summaries, and imported excerpts; the repository address of a project stays
|
||||
// in the private input and never reaches the card. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
@@ -904,6 +940,10 @@ type Querier interface {
|
||||
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Serializes the vector jobs of one subject: a job takes this lock before it
|
||||
// reads the subject, so the job that runs last also read last and its vectors
|
||||
// describe the latest committed state. User requests never take it.
|
||||
LockSemanticSubject(ctx context.Context, lockKey int64) error
|
||||
// Serialize per-owner budget checks even before the first event exists.
|
||||
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
|
||||
// Lock and recheck one candidate's exact current publication only after the
|
||||
@@ -1080,6 +1120,8 @@ type Querier interface {
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
// A new repository starts pending; a known one only records the request.
|
||||
RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error
|
||||
// Stores the replay record of a command. A record whose retention has passed
|
||||
// is replaced, so the key is accepted as new after the retention. A live
|
||||
// record is left as it is and nothing is returned; the caller then reads it
|
||||
@@ -1109,6 +1151,7 @@ type Querier interface {
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
|
||||
SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error
|
||||
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
|
||||
SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error
|
||||
// Stores the immutable domain snapshot of a successful create command. The
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: semantic.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteSemanticVectorsOfModel = `-- name: DeleteSemanticVectorsOfModel :exec
|
||||
|
||||
DELETE FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = $1
|
||||
AND subject_id = $2
|
||||
AND model_id = $3
|
||||
AND model_revision = $4
|
||||
AND prompt_version = $5
|
||||
`
|
||||
|
||||
type DeleteSemanticVectorsOfModelParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
// Stored embedding vectors. A candidate keeps one set of rows for a model:
|
||||
// the job deletes every other row of the candidate and model before it
|
||||
// inserts the new set, in one transaction. A need keeps the rows of its
|
||||
// latest computed requirements snapshot the same way.
|
||||
func (q *Queries) DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfModel,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteSemanticVectorsOfSubject = `-- name: DeleteSemanticVectorsOfSubject :exec
|
||||
DELETE FROM semantic_vectors
|
||||
WHERE subject_kind = $1 AND subject_id = $2
|
||||
`
|
||||
|
||||
type DeleteSemanticVectorsOfSubjectParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
}
|
||||
|
||||
// Removes every vector of a subject, of any model: a closed card or a need
|
||||
// without requirements keeps no derived data.
|
||||
func (q *Queries) DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfSubject, arg.SubjectKind, arg.SubjectID)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSemanticVector = `-- name: InsertSemanticVector :exec
|
||||
INSERT INTO semantic_vectors (
|
||||
subject_kind, subject_id, candidate_id, need_id, model_id, model_revision,
|
||||
prompt_version, item_key, content_sha256, label_sha256, dimension, vector,
|
||||
computed_at
|
||||
) VALUES (
|
||||
$1, $2, $3,
|
||||
$4, $5, $6,
|
||||
$7, $8, $9,
|
||||
$10, $11, $12,
|
||||
$13
|
||||
)
|
||||
`
|
||||
|
||||
type InsertSemanticVectorParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
ComputedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSemanticVector,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.CandidateID,
|
||||
arg.NeedID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.ItemKey,
|
||||
arg.ContentSha256,
|
||||
arg.LabelSha256,
|
||||
arg.Dimension,
|
||||
arg.Vector,
|
||||
arg.ComputedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listCandidateItemVectors = `-- name: ListCandidateItemVectors :many
|
||||
SELECT candidate_id, item_key, label_sha256, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'candidate'
|
||||
AND item_key <> 'whole'
|
||||
AND model_id = $1
|
||||
AND model_revision = $2
|
||||
AND prompt_version = $3
|
||||
AND candidate_id = ANY($4::uuid [])
|
||||
ORDER BY candidate_id, item_key
|
||||
`
|
||||
|
||||
type ListCandidateItemVectorsParams struct {
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
CandidateIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type ListCandidateItemVectorsRow struct {
|
||||
CandidateID pgtype.UUID
|
||||
ItemKey string
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The item vectors of the candidates that a search returns, at most a few
|
||||
// dozen candidates.
|
||||
func (q *Queries) ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateItemVectors,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.CandidateIds,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateItemVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateItemVectorsRow
|
||||
if err := rows.Scan(
|
||||
&i.CandidateID,
|
||||
&i.ItemKey,
|
||||
&i.LabelSha256,
|
||||
&i.Dimension,
|
||||
&i.Vector,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCandidateWholeVectors = `-- name: ListCandidateWholeVectors :many
|
||||
SELECT candidate_id, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'candidate'
|
||||
AND item_key = 'whole'
|
||||
AND model_id = $1
|
||||
AND model_revision = $2
|
||||
AND prompt_version = $3
|
||||
AND candidate_id = ANY($4::uuid [])
|
||||
ORDER BY candidate_id
|
||||
`
|
||||
|
||||
type ListCandidateWholeVectorsParams struct {
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
CandidateIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type ListCandidateWholeVectorsRow struct {
|
||||
CandidateID pgtype.UUID
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The whole-view vectors of the candidates of one search.
|
||||
func (q *Queries) ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateWholeVectors,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.CandidateIds,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateWholeVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateWholeVectorsRow
|
||||
if err := rows.Scan(&i.CandidateID, &i.Dimension, &i.Vector); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listNeedVectors = `-- name: ListNeedVectors :many
|
||||
SELECT item_key, content_sha256, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'need'
|
||||
AND need_id = $1
|
||||
AND model_id = $2
|
||||
AND model_revision = $3
|
||||
AND prompt_version = $4
|
||||
AND content_sha256 = ANY($5::bytea [])
|
||||
ORDER BY item_key
|
||||
`
|
||||
|
||||
type ListNeedVectorsParams struct {
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ContentDigests [][]byte
|
||||
}
|
||||
|
||||
type ListNeedVectorsRow struct {
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The vectors of a need whose texts match the given digests of the
|
||||
// requirements snapshot that the search renders.
|
||||
func (q *Queries) ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listNeedVectors,
|
||||
arg.NeedID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.ContentDigests,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListNeedVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListNeedVectorsRow
|
||||
if err := rows.Scan(
|
||||
&i.ItemKey,
|
||||
&i.ContentSha256,
|
||||
&i.Dimension,
|
||||
&i.Vector,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listNeedsAfter = `-- name: ListNeedsAfter :many
|
||||
SELECT id, organization_id, requirements_version
|
||||
FROM organization_needs
|
||||
WHERE id > $1
|
||||
ORDER BY id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListNeedsAfterParams struct {
|
||||
AfterID pgtype.UUID
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
type ListNeedsAfterRow struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
RequirementsVersion int64
|
||||
}
|
||||
|
||||
// Needs and their current requirements snapshot for the backfill.
|
||||
func (q *Queries) ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error) {
|
||||
rows, err := q.db.Query(ctx, listNeedsAfter, arg.AfterID, arg.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListNeedsAfterRow
|
||||
for rows.Next() {
|
||||
var i ListNeedsAfterRow
|
||||
if err := rows.Scan(&i.ID, &i.OrganizationID, &i.RequirementsVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listProfileCandidatesAfter = `-- name: ListProfileCandidatesAfter :many
|
||||
SELECT profiles.user_id
|
||||
FROM candidate_profiles AS profiles
|
||||
WHERE profiles.user_id > $1
|
||||
ORDER BY profiles.user_id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListProfileCandidatesAfterParams struct {
|
||||
AfterID pgtype.UUID
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
// Candidates with a saved profile for the backfill, in identifier order
|
||||
// after a cursor. The job of a candidate who is not published removes the
|
||||
// stored vectors, so a backfill also cleans up after a closed card.
|
||||
func (q *Queries) ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, listProfileCandidatesAfter, arg.AfterID, arg.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []pgtype.UUID
|
||||
for rows.Next() {
|
||||
var user_id pgtype.UUID
|
||||
if err := rows.Scan(&user_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, user_id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listSemanticVectorDigests = `-- name: ListSemanticVectorDigests :many
|
||||
SELECT item_key, content_sha256
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = $1
|
||||
AND subject_id = $2
|
||||
AND model_id = $3
|
||||
AND model_revision = $4
|
||||
AND prompt_version = $5
|
||||
ORDER BY item_key, content_sha256
|
||||
`
|
||||
|
||||
type ListSemanticVectorDigestsParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
type ListSemanticVectorDigestsRow struct {
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
// The digests of the stored rows of a subject and model, for the job that
|
||||
// decides whether anything changed.
|
||||
func (q *Queries) ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listSemanticVectorDigests,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListSemanticVectorDigestsRow
|
||||
for rows.Next() {
|
||||
var i ListSemanticVectorDigestsRow
|
||||
if err := rows.Scan(&i.ItemKey, &i.ContentSha256); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockSemanticSubject = `-- name: LockSemanticSubject :exec
|
||||
SELECT pg_advisory_xact_lock($1::bigint)
|
||||
`
|
||||
|
||||
// Serializes the vector jobs of one subject: a job takes this lock before it
|
||||
// reads the subject, so the job that runs last also read last and its vectors
|
||||
// describe the latest committed state. User requests never take it.
|
||||
func (q *Queries) LockSemanticSubject(ctx context.Context, lockKey int64) error {
|
||||
_, err := q.db.Exec(ctx, lockSemanticSubject, lockKey)
|
||||
return err
|
||||
}
|
||||
@@ -233,6 +233,7 @@ var problemCodes = []string{
|
||||
"state_conflict", "version_conflict", "payload_too_large", "unsupported_media_type",
|
||||
"idempotency_key_reused", "precondition_required", "rate_limited", "internal",
|
||||
"not_implemented",
|
||||
"service_unavailable",
|
||||
}
|
||||
|
||||
// ObserveProblem counts one error response. A code outside the contract
|
||||
|
||||
Reference in new issue
Block a user