feat(ml): fuse two embedding models and protect the ML service with a token

This commit is contained in:
shira committed 2026-10-11 14:40:52 +03:00
1 parent bc00d6901f
commit b24e5ff906
63 files changed
+2287 -276

No files matched your search

@@ -32,6 +32,9 @@ const (
type Settings struct {
// BaseURL is the ML service origin, for example http://ml:8000.
BaseURL string
// Token is the shared bearer token of the ML service. It is a secret:
// it travels only in the Authorization header and is never logged.
Token string
// Timeout bounds one HTTP request.
Timeout time.Duration
// FailureThreshold consecutive failures open the circuit for OpenDuration.
@@ -57,13 +60,16 @@ func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
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")
}
if settings.Token == "" {
return nil, errors.New(location + " - the ML service token 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))
client, err := api.NewClient(parsed.String(), staticToken{token: settings.Token}, api.WithClient(httpClient))
if err != nil {
return nil, fmt.Errorf("%s - create client: %w", location, err)
}
@@ -130,6 +136,12 @@ func (embedder *Embedder) embedBatch(
case *api.CreateMLEmbeddingsServiceUnavailable:
embedder.breaker.failure()
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
case *api.CreateMLEmbeddingsUnauthorized:
// A wrong or missing token is a deployment mistake. The job retries
// with backoff, so the vectors follow once the operator fixes the
// token; the open circuit keeps the retries cheap meanwhile.
embedder.breaker.failure()
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the service token: %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.
@@ -167,6 +179,15 @@ func cutRunes(text string, limit int) string {
return string(runes[:limit])
}
// staticToken supplies the configured bearer token to the generated client.
type staticToken struct {
token string
}
func (source staticToken) BearerAuth(context.Context, api.OperationName) (api.BearerAuth, error) {
return api.BearerAuth{Token: source.token}, nil
}
// limitedTransport caps the bytes read from a response body.
type limitedTransport struct {
next http.RoundTripper