feat(ml): fuse two embedding models and protect the ML service with a token
This commit is contained in:
1 parent
bc00d6901f
commit
b24e5ff906
63 files changed
+2287
-276
No files matched your search
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@@ -29,13 +30,16 @@ func trimTrailingSlashes(u *url.URL) {
|
||||
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.
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||
// bearer token. 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
|
||||
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||
// the same state. A request without a valid token answers 401, 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
|
||||
@@ -57,11 +61,12 @@ type Invoker interface {
|
||||
// Client implements OAS client.
|
||||
type Client struct {
|
||||
serverURL *url.URL
|
||||
sec SecuritySource
|
||||
baseClient
|
||||
}
|
||||
|
||||
// NewClient initializes new Client defined by OAS.
|
||||
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
||||
func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) {
|
||||
u, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -74,6 +79,7 @@ func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
||||
}
|
||||
return &Client{
|
||||
serverURL: u,
|
||||
sec: sec,
|
||||
baseClient: c,
|
||||
}, nil
|
||||
}
|
||||
@@ -95,13 +101,16 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
|
||||
|
||||
// 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.
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||
// bearer token. 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
|
||||
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||
// the same state. A request without a valid token answers 401, 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
|
||||
@@ -160,6 +169,39 @@ func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingR
|
||||
return res, errors.Wrap(err, "encode request")
|
||||
}
|
||||
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
stage = "Security:BearerAuth"
|
||||
switch err := c.securityBearerAuth(ctx, CreateMLEmbeddingsOperation, r); {
|
||||
case err == nil: // if NO error
|
||||
satisfied[0] |= 1 << 0
|
||||
case errors.Is(err, ogenerrors.ErrSkipClientSecurity):
|
||||
// Skip this security.
|
||||
default:
|
||||
return res, errors.Wrap(err, "security \"BearerAuth\"")
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied
|
||||
}
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
|
||||
@@ -106,6 +106,53 @@ func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddin
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 401:
|
||||
// Code 401.
|
||||
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 &CreateMLEmbeddingsUnauthorized{
|
||||
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"))
|
||||
|
||||
@@ -12,6 +12,31 @@ func (s *ProblemStatusCode) Error() string {
|
||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||
}
|
||||
|
||||
type BearerAuth struct {
|
||||
Token string
|
||||
Roles []string
|
||||
}
|
||||
|
||||
// GetToken returns the value of Token.
|
||||
func (s *BearerAuth) GetToken() string {
|
||||
return s.Token
|
||||
}
|
||||
|
||||
// GetRoles returns the value of Roles.
|
||||
func (s *BearerAuth) GetRoles() []string {
|
||||
return s.Roles
|
||||
}
|
||||
|
||||
// SetToken sets the value of Token.
|
||||
func (s *BearerAuth) SetToken(val string) {
|
||||
s.Token = val
|
||||
}
|
||||
|
||||
// SetRoles sets the value of Roles.
|
||||
func (s *BearerAuth) SetRoles(val []string) {
|
||||
s.Roles = val
|
||||
}
|
||||
|
||||
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
||||
@@ -24,6 +49,10 @@ type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsUnauthorized ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsUnauthorized) 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.
|
||||
//
|
||||
@@ -143,13 +172,14 @@ func (s *EmbeddingModel) SetPromptVersion(val string) {
|
||||
|
||||
// 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.
|
||||
// configured size, and returned in request order. The same texts in the same request on the same
|
||||
// installation, device, precision, 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`.
|
||||
// the service, the first one it is configured with. 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"`
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
)
|
||||
|
||||
// SecuritySource is provider of security values (tokens, passwords, etc.).
|
||||
type SecuritySource interface {
|
||||
// BearerAuth provides bearerAuth security value.
|
||||
// Shared random service token sent as `Authorization: Bearer <token>`. The service compares it in
|
||||
// constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user
|
||||
// tokens.
|
||||
BearerAuth(ctx context.Context, operationName OperationName) (BearerAuth, error)
|
||||
}
|
||||
|
||||
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||
var operationRolesBearerAuth = map[string][]string{
|
||||
CreateMLEmbeddingsOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||
//
|
||||
// This is useful for authorization scenarios where you need to know which roles
|
||||
// are required for an operation.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
|
||||
//
|
||||
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||
func GetRolesForBearerAuth(operation string) []string {
|
||||
roles, ok := operationRolesBearerAuth[operation]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent external modification
|
||||
result := make([]string, len(roles))
|
||||
copy(result, roles)
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error {
|
||||
t, err := s.sec.BearerAuth(ctx, operationName)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "security source \"BearerAuth\"")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+t.Token)
|
||||
return nil
|
||||
}
|
||||
@@ -33,6 +33,14 @@ func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsUnauthorized) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingInputKind) Validate() error {
|
||||
switch s {
|
||||
case "query":
|
||||
|
||||
Reference in new issue
Block a user