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

socialweb.computer/socialweb-computer-kcp

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

1 collaborator
0
0
241 lines · 7.8 KB Raw History
package requester

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"sync"
	"time"

	"filippo.io/age"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	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/atproto/cloudinit"
	"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/market"
	"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/tunnel"
	"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/netretry"
)

const guestWebRTCEventPrefix = "requester-webrtc-"

type guestWebRTCOffer struct {
	SDP string `json:"sdp"`

	ReplyTo string `json:"replyTo"`

	ID string `json:"id"`

	Session string `json:"session"`

	Peer string `json:"peer"`
}

func GuestWebRTCEventName(contract string) string {
	name := guestWebRTCEventPrefix + contract
	if len(name) > 253 {
		return name[:253]
	}
	return name
}

func guestRequesterKey(event v1alpha1.ContractEvent) bool {
	return event.Spec.Direction == v1alpha1.ContractEventInbound && event.Spec.NSID == market.ComputeEventsGuestPublicKeyNSID &&
		event.Spec.Tag == cloudinit.GuestRequesterTag && event.Status.Record != nil
}

func guestRequesterAnswer(event v1alpha1.ContractEvent) bool {
	return event.Spec.Direction == v1alpha1.ContractEventInbound && event.Spec.NSID == market.ComputeEventsGuestSignalWebRTCNSID &&
		event.Spec.Tag == cloudinit.GuestRequesterTag && event.Spec.Kind == market.GuestSignalKindAnswer && event.Status.Record != nil
}

func guestRequesterSignal(event v1alpha1.ContractEvent) bool {
	return event.Spec.Direction == v1alpha1.ContractEventOutbound && event.Spec.NSID == market.ComputeEventsGuestSignalWebRTCNSID &&
		event.Spec.Tag == cloudinit.GuestRequesterTag
}

func (q *Requester) guestWebRTC() bool {
	return q.deps.GuestIngress != nil && q.cfg.InboundXRPC()
}

func (q *Requester) latestGuestKey(contract v1alpha1.ComputeContract, tag string) (v1alpha1.ContractEvent, bool) {
	keys := q.contractEvents.Filter(func(e v1alpha1.ContractEvent) bool {
		return e.Spec.Direction == v1alpha1.ContractEventInbound && e.Spec.NSID == market.ComputeEventsGuestPublicKeyNSID && e.Spec.Tag == tag &&
			e.Status.Record != nil && e.Spec.ContractRef.Name == contract.Name && e.DeletionTimestamp == nil &&
			(contract.UID == "" || len(e.OwnerReferences) == 0 || ownedBy(e, contract))
	})
	var latest v1alpha1.ContractEvent
	found := false
	for _, e := range keys {
		if !found || latest.CreationTimestamp.Before(&e.CreationTimestamp) ||
			(latest.CreationTimestamp.Equal(&e.CreationTimestamp) && e.Name > latest.Name) {
			latest, found = e, true
		}
	}
	return latest, found
}

type guestRTCState struct {
	mu sync.Mutex

	identity *age.X25519Identity

	answered map[string]bool

	failures int

	notBefore time.Time
}

func (q *Requester) guestRTCOf(contract string, create bool) *guestRTCState {
	q.guestRTCMu.Lock()
	defer q.guestRTCMu.Unlock()
	st := q.guestRTC[contract]
	if st == nil && create {
		if q.guestRTC == nil {
			q.guestRTC = map[string]*guestRTCState{}
		}
		st = &guestRTCState{}
		q.guestRTC[contract] = st
	}
	return st
}

func (q *Requester) forgetGuestWebRTC(contract string) {
	q.guestRTCMu.Lock()
	delete(q.guestRTC, contract)
	q.guestRTCMu.Unlock()
}

func (q *Requester) offerGuestWebRTC(ctx context.Context, contract v1alpha1.ComputeContract) error {
	return q.offerGuestWebRTCWhen(ctx, contract, false)
}

func (q *Requester) offerGuestWebRTCWhen(ctx context.Context, contract v1alpha1.ComputeContract, due bool) error {
	if !q.guestWebRTC() || contract.Spec.SecretsRef == nil || q.deps.ContractEvents == nil || contract.DeletionTimestamp != nil || q.releasing(contract) {
		return nil
	}
	key, ok := q.latestGuestKey(contract, cloudinit.GuestRequesterTag)
	if !ok {
		return nil
	}
	name := GuestWebRTCEventName(contract.Name)
	st := q.guestRTCOf(contract.Name, true)
	st.mu.Lock()
	defer st.mu.Unlock()
	if !due && time.Now().Before(st.notBefore) {
		return nil
	}
	if existing, known := q.contractEvents.Get(name); known && existing.Spec.RecipientRef != nil && existing.Spec.RecipientRef.Name == key.Name && st.identity != nil {
		return nil
	}
	recipient, err := age.ParseX25519Recipient(strings.TrimSpace(key.Spec.Key))
	if err != nil {
		return fmt.Errorf("requester: the guest's requester key %s is not an age X25519 recipient: %w", key.Name, err)
	}
	offer, err := q.deps.GuestIngress.Offer(ctx, q.repoDID, contract.Name)
	if err != nil {
		return fmt.Errorf("requester: the guest WebRTC offer: %w", err)
	}
	identity, err := age.GenerateX25519Identity()
	if err != nil {
		return err
	}
	plaintext, err := json.Marshal(guestWebRTCOffer{SDP: offer.SDP, ReplyTo: identity.Recipient().String(), ID: offer.ID, Session: offer.Session, Peer: offer.Peer})
	if err != nil {
		return err
	}
	ciphertext, err := sealTo(recipient, plaintext)
	if err != nil {
		return fmt.Errorf("requester: sealing the guest WebRTC offer: %w", err)
	}
	event := v1alpha1.ContractEvent{
		ObjectMeta: metav1.ObjectMeta{Name: name, OwnerReferences: []metav1.OwnerReference{contractOwnerReference(contract)}},
		Spec: v1alpha1.ContractEventSpec{
			ContractRef:  commonv1.LocalObjectRef{Name: contract.Name},
			Direction:    v1alpha1.ContractEventOutbound,
			NSID:         market.ComputeEventsGuestSignalWebRTCNSID,
			Kind:         market.GuestSignalKindOffer,
			Tag:          cloudinit.GuestRequesterTag,
			Ciphertext:   ciphertext,
			RecipientRef: &commonv1.LocalObjectRef{Name: key.Name},
		},
	}
	if err := q.deps.ContractEvents.ApplyContractEvent(ctx, event); err != nil {
		return err
	}
	st.identity = identity
	st.answered = map[string]bool{}
	q.log.Info("requester_guest_webrtc_offered", "contract", contract.Name, "contractEvent", name, "recipient", key.Name, "session", offer.Session)
	return nil
}

func (q *Requester) acceptGuestWebRTC(ctx context.Context, event v1alpha1.ContractEvent) error {
	if !q.guestWebRTC() {
		return nil
	}
	name := event.Spec.ContractRef.Name
	st := q.guestRTCOf(name, false)
	if st == nil {
		return nil
	}
	failures := q.applyGuestAnswer(ctx, st, event)
	if failures == 0 {
		return nil
	}
	q.reofferGuestWebRTC(context.WithoutCancel(ctx), name, st, failures)
	return nil
}

func (q *Requester) reofferGuestWebRTC(ctx context.Context, name string, st *guestRTCState, failures int) {
	delay := netretry.Delay(failures)
	st.mu.Lock()
	st.notBefore = time.Now().Add(delay)
	st.mu.Unlock()
	time.AfterFunc(delay, func() {
		if q.stopping() || q.guestRTCOf(name, false) != st {
			return
		}
		contract, ok := q.contracts.Get(name)
		if !ok {
			return
		}
		if err := q.offerGuestWebRTCWhen(ctx, contract, true); err != nil {
			q.log.Warn("requester_guest_webrtc_offer_failed", "contract", name, "err", err.Error(), "next", netretry.Delay(failures+1).String())
			q.reofferGuestWebRTC(ctx, name, st, failures+1)
		}
	})
}

func (q *Requester) applyGuestAnswer(ctx context.Context, st *guestRTCState, event v1alpha1.ContractEvent) int {
	st.mu.Lock()
	defer st.mu.Unlock()
	if st.identity == nil {
		return 0
	}
	plaintext, err := openSealed(st.identity, event.Spec.Ciphertext)
	if err != nil {
		return 0
	}
	var answer tunnel.Answer
	if err := json.Unmarshal(plaintext, &answer); err != nil {
		q.log.Warn("requester_guest_webrtc_answer_refused", "contract", event.Spec.ContractRef.Name, "err", err.Error())
		return 0
	}
	if st.answered[answer.Session] {
		return 0
	}
	if err := q.deps.GuestIngress.Accept(ctx, answer); err != nil {
		st.identity = nil
		st.failures++
		q.log.Warn("requester_guest_webrtc_answer_refused", "contract", event.Spec.ContractRef.Name, "session", answer.Session, "err", err.Error(),
			"next", "a new offer in "+netretry.Delay(st.failures).String())
		return st.failures
	}
	st.answered[answer.Session] = true
	st.failures = 0
	q.log.Info("requester_guest_webrtc_answered", "contract", event.Spec.ContractRef.Name, "session", answer.Session)
	return 0
}