~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
182 lines · 5.4 KB Raw History
package opsread

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"time"

	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"sigs.k8s.io/controller-runtime/pkg/client"

	commonv1 "github.com/johnandersen777/socialweb-computer-kcp/api/common/v1alpha1"
	"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
	"github.com/johnandersen777/socialweb-computer-kcp/internal/bus"
	contract "github.com/johnandersen777/socialweb-computer-kcp/internal/contract/opsread"
)

const (
	KindBidder = "Bidder"

	KindMarketIdentity = "MarketIdentity"

	KindMarketBidder = "MarketBidder"
)

type Options struct {
	Bus *bus.Bus

	Clients func(workspace string) (client.Client, error)
}

type reader struct {
	clients func(workspace string) (client.Client, error)

	owner commonv1.ObjectRef
}

var _ contract.Objects = (*reader)(nil)

func Register(opts Options) error {
	if opts.Bus == nil {
		return errors.New("opsread: the bus is required")
	}
	if opts.Clients == nil {
		return errors.New("opsread: the workspace clients are required")
	}
	bus.Provide[contract.Objects](opts.Bus, schema.GroupKind{Group: v1alpha1.GroupName, Kind: KindBidder}, contract.CapabilityObjects,
		func(_ context.Context, to commonv1.ObjectRef, _ []string) (contract.Objects, error) {
			if strings.TrimSpace(to.Workspace) == "" || strings.TrimSpace(to.Name) == "" {
				return nil, fmt.Errorf("opsread: %s names no component", to.String())
			}
			return &reader{clients: opts.Clients, owner: to}, nil
		})
	return nil
}

func meta(o metav1.Object) contract.Meta {
	out := contract.Meta{Name: o.GetName()}
	if t := o.GetDeletionTimestamp(); t != nil && !t.IsZero() {
		out.DeletionTimestamp = t.UTC().Format(time.RFC3339)
	}
	return out
}

func vmOf(o *v1alpha1.ComputeVM) contract.VM {
	out := contract.VM{Metadata: meta(o), Status: contract.VMStatus{Phase: string(o.Status.Phase), LostReason: string(o.Status.LostReason)}}
	out.Spec.VM.Cpus = o.Spec.VM.Cpus
	out.Spec.Requester.Did = o.Spec.Requester.Did
	if o.Spec.Contract != nil {
		out.Spec.Contract = &contract.VMContract{Receipt: contract.VMReceipt{URI: o.Spec.Contract.Receipt.URI}}
	}
	return out
}

func identityStatus(in v1alpha1.MarketIdentityStatus) contract.IdentityStatus {
	out := contract.IdentityStatus{Phase: string(in.Phase)}
	if action := in.PendingAction; action != nil {
		out.PendingAction = &contract.PendingAction{Kind: string(action.Kind), Reason: action.Reason}
	}
	for _, c := range in.Conditions {
		out.Conditions = append(out.Conditions, contract.Condition{Type: c.Type, Status: string(c.Status), Reason: c.Reason})
	}
	return out
}

func (r *reader) client() (client.Client, error) {
	return r.clients(r.owner.Workspace)
}

func (r *reader) VMs(ctx context.Context) ([]contract.VM, error) {
	cl, err := r.client()
	if err != nil {
		return nil, err
	}
	list := &v1alpha1.ComputeVMList{}
	if err := cl.List(ctx, list); err != nil {
		return nil, err
	}
	out := make([]contract.VM, 0, len(list.Items))
	for i := range list.Items {
		out = append(out, vmOf(&list.Items[i]))
	}
	return out, nil
}

func found(err error) (bool, error) {
	if err == nil {
		return true, nil
	}
	if apierrors.IsNotFound(err) {
		return false, nil
	}
	return false, err
}

func (r *reader) VM(ctx context.Context, name string) (contract.VMDetail, error) {
	var out contract.VMDetail
	if !contract.ValidVMName(name) {
		return out, contract.ErrInvalid
	}
	cl, err := r.client()
	if err != nil {
		return out, err
	}
	vm := &v1alpha1.ComputeVM{}
	if ok, err := found(cl.Get(ctx, client.ObjectKey{Name: name}, vm)); err != nil {
		return out, err
	} else if ok {
		v := vmOf(vm)
		out.ComputeVM = &v
	}
	fc := &v1alpha1.FirecrackerVM{}
	if ok, err := found(cl.Get(ctx, client.ObjectKey{Name: name}, fc)); err != nil {
		return out, err
	} else if ok {
		status := contract.FirecrackerVMStatus{Phase: string(fc.Status.Phase), LostReason: string(fc.Status.LostReason)}
		if image := fc.Status.Image; image != nil {
			status.Image = &contract.VMImage{Sha256: image.Sha256, Fetched: image.Fetched}
		}
		out.FirecrackerVM = &contract.FirecrackerVM{Metadata: meta(fc), Status: status}
	}
	return out, nil
}

func (r *reader) Bidder(ctx context.Context) (contract.BidderState, error) {
	var out contract.BidderState
	cl, err := r.client()
	if err != nil {
		return out, err
	}
	bidder := &v1alpha1.Bidder{}
	if ok, err := found(cl.Get(ctx, client.ObjectKey{Name: r.owner.Name}, bidder)); err != nil {
		return out, err
	} else if !ok {
		return out, nil
	}
	out.Bidder = &contract.BidderComponent{Metadata: meta(bidder), Spec: contract.BidderSpec{Policy: bidder.Spec.Policy}}
	if id := bidder.Spec.Identity; id != nil && id.MarketIdentityRef != nil && id.MarketIdentityRef.Kind == KindMarketIdentity {
		identity := &v1alpha1.MarketIdentity{}
		if ok, err := found(cl.Get(ctx, client.ObjectKey{Name: id.MarketIdentityRef.Name}, identity)); err != nil {
			return out, err
		} else if ok {
			out.Identity = &contract.Identity{Metadata: meta(identity), Status: identityStatus(identity.Status)}
		}
	}
	for _, ref := range bidder.GetOwnerReferences() {
		if ref.Kind != KindMarketBidder {
			continue
		}
		root := &v1alpha1.MarketBidder{}
		if ok, err := found(cl.Get(ctx, client.ObjectKey{Name: ref.Name}, root)); err != nil {
			return out, err
		} else if ok {
			out.MarketBidder = &contract.MarketBidder{Metadata: meta(root),
				Status: contract.MarketBidderStatus{Phase: string(root.Status.Phase), Did: root.Status.Did}}
		}
	}
	return out, nil
}