0
0
package bidder
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/market"
"github.com/johnandersen777/socialweb-computer-kcp/internal/guestimage"
"github.com/johnandersen777/socialweb-computer-kcp/internal/guestseed"
"github.com/johnandersen777/socialweb-computer-kcp/internal/identlink"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/memsize"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/atproto"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/trust"
)
// The kinds of a decline the bidder answers submitRfp with (docs/protocol/market.md): the requester waits for capacity only
// while some bidder declined for DeclineCapacity or did not answer; when every bidder it asked declined for another reason
// nobody can serve the request and it fails at once with the reasons.
const (
DeclineCapacity = "capacity"
DeclineUnservable = "unservable"
)
// Decline is why a bidder will not bid on an RFP, found when submitRfp arrives (the same checks the bid decision runs).
type Decline struct {
Kind string
Reason string
}
func (d Decline) Error() string { return d.Kind + ": " + d.Reason }
var ErrKindUnsupported = fmt.Errorf("bidder: the RFP asks for a compute kind this bidder does not serve")
func (b *Bidder) servesKind(kind string) bool {
served := b.cfg.ComputeKinds
if len(served) == 0 {
served = []string{string(v1alpha1.ComputeKindVM)}
}
if kind == "" {
kind = string(v1alpha1.ComputeKindVM)
}
if !slices.Contains(served, kind) {
return false
}
if kind == string(v1alpha1.ComputeKindDeno) && (b.cfg.Sandbox == nil || !b.cfg.Sandbox.Available()) {
return false
}
return true
}
func (b *Bidder) rfpKind(ctx context.Context, rfpURI, rfpCID string) (string, error) {
resolved, err := b.records.Resolve(ctx, market.RecordRef{URI: rfpURI, CID: rfpCID})
if err != nil {
return "", fmt.Errorf("bidder: resolving the RFP payload kind: %w", err)
}
rfp, err := market.ParseRFP(resolved.Value)
if err != nil {
return "", nil
}
payload, err := b.records.Resolve(ctx, market.RecordRef{URI: rfp.Payload.URI, CID: rfp.Payload.CID})
if err != nil {
return "", fmt.Errorf("bidder: resolving the RFP payload: %w", err)
}
kind, _ := payload.Value["kind"].(string)
return kind, nil
}
func (b *Bidder) inboxServesKind(ctx context.Context, rfpURI, rfpCID string) (string, bool) {
kind, err := b.rfpKind(ctx, rfpURI, rfpCID)
if err != nil {
b.log.Warn("reading the compute kind of an inbox RFP failed; it is dropped", "rfp", rfpURI, "err", err.Error())
return kind, false
}
return kind, b.servesKind(kind)
}
func payloadRefusal(kind string) string {
if kind == DeclineCapacity {
return "PayloadUnavailable"
}
return "PayloadUnservable"
}
func declinedRefusal(kind string) string {
if kind == DeclineCapacity {
return "DeclinedCapacity"
}
return "DeclinedUnservable"
}
// payloadDecline is the check of the RFP's compute.vm payload with the kind of a refusal (DeclineCapacity or
// DeclineUnservable); nil when the bidder would take it.
func (b *Bidder) payloadDecline(ctx context.Context, rfp *market.RFP, room bool) (*Decline, error) {
payload, err := b.records.Resolve(ctx, market.RecordRef{URI: rfp.Payload.URI, CID: rfp.Payload.CID})
if err != nil {
return nil, fmt.Errorf("bidder: resolving the RFP payload: %w", err)
}
record, err := parseVMRecord(payload.Value)
if err != nil {
return &Decline{Kind: DeclineUnservable, Reason: err.Error()}, nil
}
if at, err := market.ParseTime(record.ExpiresAt); err == nil && !at.After(b.now()) {
return &Decline{Kind: DeclineUnservable, Reason: fmt.Sprintf("bidder: the RFP payload's expiresAt %s has passed", record.ExpiresAt)}, nil
}
if msg := b.imageErr.Load(); msg != nil && record.Kind != string(v1alpha1.ComputeKindDeno) && record.Image == nil {
// the pinned image is verified in the background (at start, again every ImageRetry): a bidder that has just rolled is full of
// requests it cannot take yet, not one that can never take them
return &Decline{Kind: DeclineCapacity, Reason: "bidder: the bidder's pinned guest image does not verify yet: " + *msg}, nil
}
refused, kind := b.capacityVerdict(record, room)
if refused != "" && kind == DeclineUnservable {
return &Decline{Kind: kind, Reason: refused}, nil
}
// a refused image outranks a full bidder: a request no bidder can ever take must not wait for the room of one that is full now
if image, imageKind := b.imageVerdict(ctx, record); image != "" {
return &Decline{Kind: imageKind, Reason: image}, nil
}
if refused != "" {
return &Decline{Kind: kind, Reason: refused}, nil
}
return nil, nil
}
func (b *Bidder) imageRefused(ctx context.Context, record vmRecord) string {
reason, _ := b.imageVerdict(ctx, record)
return reason
}
// imageVerdict is why this bidder will not boot the requested image, with the kind: DeclineUnservable for a refusal that no waiting
// changes (a manifest that hashes to another value, is malformed, is for another target, has an oversized marker, a disk overflow, a
// non-public address), DeclineCapacity when the manifest could not be fetched now (the network, a timeout, a 408, 429 or 5xx).
func (b *Bidder) imageVerdict(ctx context.Context, record vmRecord) (string, string) {
if record.Image == nil {
return "", ""
}
pin, err := guestimage.PinFor(b.cfg.ImageTarget)
if err != nil {
return err.Error(), DeclineUnservable
}
diskMiB, err := memsize.ParseMiB(record.Disk)
if err != nil {
return err.Error(), DeclineUnservable
}
m, _, err := guestimage.FetchManifest(ctx, guestimage.PublicClient(), *record.Image)
if err == nil {
err = m.CheckFor(pin, int64(diskMiB)<<20)
}
switch {
case err == nil:
return "", ""
case errors.Is(err, guestimage.ErrRequestedUnavailable) || ctx.Err() != nil:
return err.Error(), DeclineCapacity
}
return err.Error(), DeclineUnservable
}
func (b *Bidder) guestToolsRefused(ctx context.Context, rfp *market.RFP) (string, error) {
payload, err := b.records.Resolve(ctx, market.RecordRef{URI: rfp.Payload.URI, CID: rfp.Payload.CID})
if err != nil {
return "", fmt.Errorf("bidder: resolving the RFP payload for its guest tools: %w", err)
}
userData, _ := payload.Value["user_data"].(string)
needs := guestseed.GuestBinariesNeeded(userData)
if len(needs.Tools) == 0 {
return "", nil
}
if err := needs.ToolsErr(); err != nil {
return err.Error(), nil
}
if _, err := guestseed.GuestBinaryPins(b.cfg.GuestDownloads, needs.Tools); err != nil {
return err.Error(), nil
}
return "", nil
}
type Operators interface {
Walk(ctx context.Context, did string, assoc trust.Association) (identlink.Result, error)
PinnedRecord(ctx context.Context, ref atproto.StrongRef) (map[string]any, string, error)
ContractHeld(ctx context.Context, contract atproto.StrongRef, authorities []string) (bool, error)
Record(ctx context.Context, repo, collection, rkey string) (map[string]any, error)
}
func (b *Bidder) netRefused(ctx context.Context, rfp *market.RFP, requester string) (string, error) {
payload, err := b.records.Resolve(ctx, market.RecordRef{URI: rfp.Payload.URI, CID: rfp.Payload.CID})
if err != nil {
return "", fmt.Errorf("bidder: resolving the RFP payload for its net: %w", err)
}
if net, _ := payload.Value["net"].(bool); !net {
return "", nil
}
if kind, _ := payload.Value["kind"].(string); kind != string(v1alpha1.ComputeKindDeno) {
return "net is a computeKind deno option", nil
}
return b.ownerOnly(ctx, requester)
}
func (b *Bidder) ownerOnly(ctx context.Context, requester string) (string, error) {
if requester == b.cfg.DID {
return "", nil
}
if b.operators == nil {
return "the bidder cannot check its owner, so it runs no networked sandbox", nil
}
self, err := b.operators.Walk(ctx, b.cfg.DID, trust.Association{})
if err != nil {
return "", err
}
if slices.Contains(self.Roots, requester) {
return "", nil
}
theirs, err := b.operators.Walk(ctx, requester, trust.Association{})
if err != nil {
return "", err
}
if slices.ContainsFunc(self.Roots, func(root string) bool { return slices.Contains(theirs.Roots, root) }) {
return "", nil
}
owner := strings.Join(self.Roots, ", ")
return "a networked sandbox runs only for the bidder's owner " + owner, nil
}