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

johnandersen777.bsky.social/socialweb-computer-console

console.socialweb.computer: kcp, kubectl and ssh compiled to wasm in a browser tab with a terminal; a kcp fork

0
0
main
519 lines · 20.6 KB Raw History
// Package statusfeed watches the socialweb CRs in the browser kcp and pushes a
// compact state snapshot to the page. It replaces the page's kubectl pollers:
// the page only needs current phases and endpoints, not a generic watch API.
package statusfeed

import (
	"context"
	"encoding/json"
	"errors"
	"sort"
	"strings"
	"sync"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/dynamic/dynamicinformer"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"

	exposurev1alpha1 "github.com/johnandersen777/socialweb-computer-kcp/api/exposure/v1alpha1"
	policyv1alpha1 "github.com/johnandersen777/socialweb-computer-kcp/api/policy/v1alpha1"
	"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
)

const debounce = 100 * time.Millisecond

var crdGVR = schema.GroupVersionResource{Group: "apiextensions.k8s.io", Version: "v1", Resource: "customresourcedefinitions"}

// PendingAction is the subset of MarketIdentity.status.pendingAction the page
// needs to open the authorization popup.
type PendingAction struct {
	Kind      string `json:"kind,omitempty"`
	URL       string `json:"url,omitempty"`
	ExpiresAt string `json:"expiresAt,omitempty"`
	// Reason says why a signInAgain is offered (ScopeUpgrade: the session
	// works, but lacks scopes the page now asks for).
	Reason string `json:"reason,omitempty"`
	// MissingScopes names the scope tokens a ScopeUpgrade would add.
	MissingScopes []string `json:"missingScopes,omitempty"`
}

// Resource is one watched object reduced to status fields.
type Resource struct {
	Name     string         `json:"name"`
	Phase    string         `json:"phase,omitempty"`
	Message  string         `json:"message,omitempty"`
	Ready    bool           `json:"ready,omitempty"`
	DID      string         `json:"did,omitempty"`
	Handle   string         `json:"handle,omitempty"`
	Address  string         `json:"address,omitempty"`
	Endpoint string         `json:"endpoint,omitempty"`
	Pending  *PendingAction `json:"pendingAction,omitempty"`
	// Fenced is the PolicyEngine's Fenced condition status (plan 0037).
	Fenced string `json:"fenced,omitempty"`
}

// Contract is the compute-contract projection rendered by the page.
type Contract struct {
	Name      string `json:"name"`
	Phase     string `json:"phase,omitempty"`
	Message   string `json:"message,omitempty"`
	ChosenDID string `json:"chosenDid,omitempty"`
	Bids      int    `json:"bids,omitempty"`
	// Agent is spec.agent being set (plan 0035): the page offers its Agent button.
	Agent bool `json:"agent,omitempty"`
	// GuestTools and FromGuest are spec.guestTools and
	// spec.association.fromGuest: the page's Start R2 button (plan 0036 A7).
	GuestTools []string `json:"guestTools,omitempty"`
	FromGuest  bool     `json:"fromGuest,omitempty"`
	// Step is status.execution.step (e.g. releasingGuestRequester while the
	// A8 cascade waits for the guest requester); AtircRevokes is
	// status.atircRevokes (Pending|Done|Abandoned), run before Released.
	Step         string `json:"step,omitempty"`
	AtircRevokes string `json:"atircRevokes,omitempty"`
	// The parts of the requester's guestMayRun (runner.go), which r128
	// 388ccee6 uses to re-release a Failed contract for a newer stamp:
	// ReceiptOk is status.contract.receipt set with receiptOk true,
	// Terminated is status.contract.termination set, ReleaseOk is
	// status.contract.release.ok (the bidder acknowledged the release).
	ReceiptOk  bool `json:"receiptOk,omitempty"`
	Terminated bool `json:"terminated,omitempty"`
	ReleaseOk  bool `json:"releaseOk,omitempty"`
	// R2Release is status.contract.r2Release: the A8 cascade's guest answer
	// (phase Requested|Released|Failed|TimedOut; ok is omitted when false).
	R2Release *R2Release `json:"r2Release,omitempty"`
	// AtircToken is the requester's AtircTokenMinted condition (socialweb
	// r130): absent until the first mint after the verified receipt, True
	// with reason Leased|Unleased|Present, False with MintFailed (retrying)
	// or GaveUp and the error in the message.
	AtircToken *Condition `json:"atircToken,omitempty"`

	SecretsFetchedAt string `json:"secretsFetchedAt,omitempty"`
	Release          bool   `json:"release,omitempty"`
	// ReleaseRequestedAt is spec.releaseRequestedAt (computecontracts 30):
	// the page sets it with spec.release on every Release.
	ReleaseRequestedAt string `json:"releaseRequestedAt,omitempty"`
	// ReleaseAnsweredAt is status.release.requestedAt: the request the
	// release outcome answers (current only when equal to ReleaseRequestedAt).
	ReleaseAnsweredAt string `json:"releaseAnsweredAt,omitempty"`
	// ReleaseFailed is the ReleaseFailed condition being True: a newer
	// releaseRequestedAt restarts that release.
	ReleaseFailed bool `json:"releaseFailed,omitempty"`
	// ReleaseFailedReason is that condition's reason (ReleaseBound: the
	// requester gave up at its release bound; DestroyFailed).
	ReleaseFailedReason string    `json:"releaseFailedReason,omitempty"`
	Networks            []Network `json:"networks,omitempty"`
	// HostKeys are status.contract.hostKeys as authorized_keys lines, the
	// pins for the page's WebRTC SSH client.
	HostKeys []string `json:"hostKeys,omitempty"`
	// Association is status.association.uri, the contract-scoped
	// market.association the requester wrote (plan 0036 P1).
	Association string `json:"association,omitempty"`
	// AssociationMessage is status.associationMessage: why an association
	// was not written (plan 0036 A5).
	AssociationMessage string `json:"associationMessage,omitempty"`
	// GuestRequester is status.contract.guestRequester: the DID the guest's
	// socialweb-computer (R2) reported and whether the requester verified it.
	GuestRequester *GuestRequester `json:"guestRequester,omitempty"`
}

// R2Release is the guest requester's answer to guest.r2Release; the phase
// decides (OK is nil unless true).
type R2Release struct {
	Phase       string `json:"phase,omitempty"`
	OK          *bool  `json:"ok,omitempty"`
	Message     string `json:"message,omitempty"`
	RequestedAt string `json:"requestedAt,omitempty"`
	AnsweredAt  string `json:"answeredAt,omitempty"`
}

// Condition is one status condition's status, reason and message.
type Condition struct {
	Status  string `json:"status"`
	Reason  string `json:"reason,omitempty"`
	Message string `json:"message,omitempty"`
}

// GuestRequester is the R2 guest's reported requester DID.
type GuestRequester struct {
	DID     string `json:"did"`
	State   string `json:"state,omitempty"`
	Message string `json:"message,omitempty"`
}

// Network is one tagged guest address from status.contract.networks (plan
// 0032), e.g. the opentunnel URL of a tunnel; kind webrtc (plan 0034) makes
// the address the guest agent's DTLS fingerprint.
type Network struct {
	Tag     string `json:"tag"`
	Kind    string `json:"kind,omitempty"`
	Address string `json:"address"`
}

// ContractEvent is a plan 0034 guest event: a publicKey or a sealed
// signalWebRTC. Only public material: keys and age ciphertext.
type ContractEvent struct {
	Name       string `json:"name"`
	Contract   string `json:"contract"`
	Direction  string `json:"direction,omitempty"`
	NSID       string `json:"nsid"`
	Kind       string `json:"kind,omitempty"`
	Tag        string `json:"tag,omitempty"`
	Key        string `json:"key,omitempty"`
	Ciphertext string `json:"ciphertext,omitempty"`
	Phase      string `json:"phase,omitempty"`
	Message    string `json:"message,omitempty"`
	CreatedAt  string `json:"createdAt,omitempty"`
}

// State is a full, idempotent UI snapshot.
type State struct {
	Seq             int64           `json:"seq"`
	TS              int64           `json:"ts,omitempty"`
	MarketRequester *Resource       `json:"marketRequester,omitempty"`
	MarketIdentity  *Resource       `json:"marketIdentity,omitempty"`
	Requester       *Resource       `json:"requester,omitempty"`
	Exposures       []Resource      `json:"exposures,omitempty"`
	Contracts       []Contract      `json:"contracts,omitempty"`
	ContractEvents  []ContractEvent `json:"contractEvents,omitempty"`
	PolicyEngine    *Resource       `json:"policyEngine,omitempty"`
	CRDs            []string        `json:"crds,omitempty"`
}

// Feed watches all browser-relevant resources and calls Publish with each
// changed snapshot. It is safe for concurrent use.
type Feed struct {
	client dynamic.Interface

	informers map[schema.GroupVersionResource]cache.SharedIndexInformer

	mu      sync.Mutex
	timer   *time.Timer
	last    string
	seq     int64
	publish func([]byte)
	started bool
}

// Start begins the informers and waits for their initial cache sync. publish is
// called from a timer goroutine and must not block.
func Start(ctx context.Context, cfg *rest.Config, publish func([]byte)) error {
	if cfg == nil {
		return errors.New("statusfeed: a rest config is required")
	}
	if publish == nil {
		return errors.New("statusfeed: a publish function is required")
	}
	base := rest.CopyConfig(cfg)
	base.Host = strings.TrimSuffix(base.Host, "/") + "/clusters/root"
	client, err := dynamic.NewForConfig(base)
	if err != nil {
		return err
	}
	f := &Feed{client: client, publish: publish, informers: map[schema.GroupVersionResource]cache.SharedIndexInformer{}}
	factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(client, 0, metav1.NamespaceAll, nil)
	watch := func(gvr schema.GroupVersionResource) error {
		informer := factory.ForResource(gvr).Informer()
		_, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
			AddFunc:    func(any) { f.changed() },
			UpdateFunc: func(any, any) { f.changed() },
			DeleteFunc: func(any) { f.changed() },
		})
		if err != nil {
			return err
		}
		f.mu.Lock()
		f.informers[gvr] = informer
		f.mu.Unlock()
		return nil
	}
	for _, gvr := range []schema.GroupVersionResource{
		v1alpha1.MarketRequesterGVR,
		v1alpha1.MarketIdentityGVR,
		v1alpha1.RequesterGVR,
		v1alpha1.ComputeContractGVR,
		exposurev1alpha1.ExposureGVR,
		crdGVR,
	} {
		if err := watch(gvr); err != nil {
			return err
		}
	}
	factory.Start(ctx.Done())
	factory.WaitForCacheSync(ctx.Done())
	// ContractEvent (and PolicyEngine) is newer than some served manifests: it starts after the
	// initial sync and is never waited on, so a kcp without the API still
	// boots; its reflector lists again with backoff until the API appears.
	if err := watch(v1alpha1.ContractEventGVR); err != nil {
		return err
	}
	if err := watch(policyv1alpha1.PolicyEngineGVR); err != nil {
		return err
	}
	factory.Start(ctx.Done())
	f.changed()
	return nil
}

func (f *Feed) changed() {
	f.mu.Lock()
	defer f.mu.Unlock()
	if f.timer == nil {
		f.timer = time.AfterFunc(debounce, f.flush)
		return
	}
	f.timer.Reset(debounce)
}

func (f *Feed) flush() {
	state := f.build()
	state.Seq, state.TS = 0, 0
	raw, err := json.Marshal(state)
	if err != nil {
		return
	}
	f.mu.Lock()
	if string(raw) == f.last {
		f.mu.Unlock()
		return
	}
	f.last = string(raw)
	f.seq++
	state.Seq, state.TS = f.seq, time.Now().UnixMilli()
	f.mu.Unlock()
	if out, err := json.Marshal(state); err == nil {
		f.publish(out)
	}
}

func (f *Feed) objects(gvr schema.GroupVersionResource) []*unstructured.Unstructured {
	f.mu.Lock()
	informer, ok := f.informers[gvr]
	f.mu.Unlock()
	if !ok || informer.GetStore() == nil {
		return nil
	}
	items := informer.GetStore().List()
	out := make([]*unstructured.Unstructured, 0, len(items))
	for _, item := range items {
		if u, ok := item.(*unstructured.Unstructured); ok {
			out = append(out, u)
		}
	}
	return out
}

func (f *Feed) build() State {
	var state State
	// The page's own objects by name: root can hold other MarketIdentities
	// (session owners); none called requester reads as Pending.
	state.MarketRequester = named(f.objects(v1alpha1.MarketRequesterGVR), "app", requesterResource)
	state.MarketIdentity = named(f.objects(v1alpha1.MarketIdentityGVR), "requester", identityResource)
	state.Requester = first(f.objects(v1alpha1.RequesterGVR), requesterResource)
	for _, u := range f.objects(exposurev1alpha1.ExposureGVR) {
		state.Exposures = append(state.Exposures, *requesterResource(u))
	}
	sort.Slice(state.Exposures, func(i, j int) bool { return state.Exposures[i].Name < state.Exposures[j].Name })
	for _, u := range f.objects(v1alpha1.ComputeContractGVR) {
		state.Contracts = append(state.Contracts, contract(u))
	}
	sort.Slice(state.Contracts, func(i, j int) bool { return state.Contracts[i].Name < state.Contracts[j].Name })
	for _, u := range f.objects(v1alpha1.ContractEventGVR) {
		state.ContractEvents = append(state.ContractEvents, contractEvent(u))
	}
	sort.Slice(state.ContractEvents, func(i, j int) bool { return state.ContractEvents[i].Name < state.ContractEvents[j].Name })
	state.PolicyEngine = first(f.objects(policyv1alpha1.PolicyEngineGVR), policyEngine)
	for _, u := range f.objects(crdGVR) {
		state.CRDs = append(state.CRDs, u.GetName())
	}
	sort.Strings(state.CRDs)
	return state
}

// named is the item called name, or nil: never another object in its
// place (root also holds session-owner MarketIdentities of other DIDs, which
// the panel must not show as the page's own; review page-rc134 F5).
func named(items []*unstructured.Unstructured, name string, conv func(*unstructured.Unstructured) *Resource) *Resource {
	for _, u := range items {
		if u.GetName() == name {
			return conv(u)
		}
	}
	return nil
}

func first(items []*unstructured.Unstructured, conv func(*unstructured.Unstructured) *Resource) *Resource {
	if len(items) == 0 {
		return nil
	}
	sort.Slice(items, func(i, j int) bool { return items[i].GetName() < items[j].GetName() })
	return conv(items[0])
}

func requesterResource(u *unstructured.Unstructured) *Resource {
	r := &Resource{Name: u.GetName()}
	r.Phase, _, _ = unstructured.NestedString(u.Object, "status", "phase")
	r.Message, _, _ = unstructured.NestedString(u.Object, "status", "message")
	r.Ready, _, _ = unstructured.NestedBool(u.Object, "status", "ready")
	r.DID, _, _ = unstructured.NestedString(u.Object, "status", "did")
	r.Handle, _, _ = unstructured.NestedString(u.Object, "status", "handle")
	r.Address, _, _ = unstructured.NestedString(u.Object, "status", "address")
	r.Endpoint, _, _ = unstructured.NestedString(u.Object, "status", "endpoint")
	if action, ok, _ := unstructured.NestedMap(u.Object, "status", "pendingAction"); ok {
		r.Pending = &PendingAction{}
		r.Pending.Kind, _, _ = unstructured.NestedString(action, "kind")
		r.Pending.URL, _, _ = unstructured.NestedString(action, "url")
		r.Pending.ExpiresAt, _, _ = unstructured.NestedString(action, "expiresAt")
		r.Pending.Reason, _, _ = unstructured.NestedString(action, "reason")
		r.Pending.MissingScopes, _, _ = unstructured.NestedStringSlice(action, "missingScopes")
	}
	return r
}

func contract(u *unstructured.Unstructured) Contract {
	c := Contract{Name: u.GetName()}
	c.Phase, _, _ = unstructured.NestedString(u.Object, "status", "phase")
	c.Message, _, _ = unstructured.NestedString(u.Object, "status", "message")
	c.ChosenDID, _, _ = unstructured.NestedString(u.Object, "status", "chosen", "did")
	if bids, ok, _ := unstructured.NestedSlice(u.Object, "status", "bids"); ok {
		c.Bids = len(bids)
	}
	c.SecretsFetchedAt, _, _ = unstructured.NestedString(u.Object, "status", "secretsFetchedAt")
	c.Association, _, _ = unstructured.NestedString(u.Object, "status", "association", "uri")
	c.AssociationMessage, _, _ = unstructured.NestedString(u.Object, "status", "associationMessage")
	if gr, ok, _ := unstructured.NestedMap(u.Object, "status", "contract", "guestRequester"); ok {
		did, _ := gr["did"].(string)
		state, _ := gr["state"].(string)
		message, _ := gr["message"].(string)
		if did != "" {
			c.GuestRequester = &GuestRequester{DID: did, State: state, Message: message}
		}
	}
	c.Release, _, _ = unstructured.NestedBool(u.Object, "spec", "release")
	c.ReleaseRequestedAt, _, _ = unstructured.NestedString(u.Object, "spec", "releaseRequestedAt")
	c.ReleaseAnsweredAt, _, _ = unstructured.NestedString(u.Object, "status", "release", "requestedAt")
	conditions, _, _ := unstructured.NestedSlice(u.Object, "status", "conditions")
	for _, raw := range conditions {
		cond, _ := raw.(map[string]any)
		if cond["type"] == "ReleaseFailed" && cond["status"] == "True" {
			c.ReleaseFailed = true
			c.ReleaseFailedReason, _ = cond["reason"].(string)
		}
		if cond["type"] == "AtircTokenMinted" {
			t := &Condition{}
			t.Status, _ = cond["status"].(string)
			t.Reason, _ = cond["reason"].(string)
			t.Message, _ = cond["message"].(string)
			c.AtircToken = t
		}
	}
	_, c.Agent, _ = unstructured.NestedMap(u.Object, "spec", "agent")
	c.GuestTools, _, _ = unstructured.NestedStringSlice(u.Object, "spec", "guestTools")
	c.FromGuest, _, _ = unstructured.NestedBool(u.Object, "spec", "association", "fromGuest")
	c.Step, _, _ = unstructured.NestedString(u.Object, "status", "execution", "step")
	c.AtircRevokes, _, _ = unstructured.NestedString(u.Object, "status", "atircRevokes")
	c.ReceiptOk, c.Terminated, c.ReleaseOk = guestParts(u)
	if rel, ok, _ := unstructured.NestedMap(u.Object, "status", "contract", "r2Release"); ok {
		r := &R2Release{}
		r.Phase, _ = rel["phase"].(string)
		r.Message, _ = rel["message"].(string)
		r.RequestedAt, _ = rel["requestedAt"].(string)
		r.AnsweredAt, _ = rel["answeredAt"].(string)
		if answer, ok := rel["ok"].(bool); ok {
			r.OK = &answer
		}
		c.R2Release = r
	}
	networks, _, _ := unstructured.NestedSlice(u.Object, "status", "contract", "networks")
	for _, raw := range networks {
		n, _ := raw.(map[string]any)
		tag, _ := n["tag"].(string)
		kind, _ := n["kind"].(string)
		address, _ := n["address"].(string)
		if tag != "" && address != "" {
			c.Networks = append(c.Networks, Network{Tag: tag, Kind: kind, Address: address})
		}
	}
	keys, _, _ := unstructured.NestedSlice(u.Object, "status", "contract", "hostKeys", "keys")
	for _, raw := range keys {
		k, _ := raw.(map[string]any)
		typ, _ := k["type"].(string)
		pub, _ := k["publicKey"].(string)
		if typ != "" && pub != "" {
			c.HostKeys = append(c.HostKeys, typ+" "+pub)
		}
	}
	return c
}

func contractEvent(u *unstructured.Unstructured) ContractEvent {
	e := ContractEvent{Name: u.GetName(), CreatedAt: u.GetCreationTimestamp().UTC().Format(time.RFC3339)}
	e.Contract, _, _ = unstructured.NestedString(u.Object, "spec", "contractRef", "name")
	e.Direction, _, _ = unstructured.NestedString(u.Object, "spec", "direction")
	e.NSID, _, _ = unstructured.NestedString(u.Object, "spec", "nsid")
	e.Kind, _, _ = unstructured.NestedString(u.Object, "spec", "kind")
	e.Tag, _, _ = unstructured.NestedString(u.Object, "spec", "tag")
	e.Key, _, _ = unstructured.NestedString(u.Object, "spec", "key")
	e.Phase, _, _ = unstructured.NestedString(u.Object, "status", "phase")
	e.Message, _, _ = unstructured.NestedString(u.Object, "status", "message")
	// Only inbound ciphertext is for the page; outbound ones are its own.
	if e.Direction == "inbound" {
		e.Ciphertext, _, _ = unstructured.NestedString(u.Object, "spec", "ciphertext")
	}
	return e
}

// identityResource is requesterResource plus the identity-only status fields.
func identityResource(u *unstructured.Unstructured) *Resource {
	r := requesterResource(u)
	if r.DID == "" {
		r.DID, _, _ = unstructured.NestedString(u.Object, "status", "did")
	}
	if r.Handle == "" {
		r.Handle, _, _ = unstructured.NestedString(u.Object, "status", "handle")
	}
	return r
}

// policyEngine reports phase, ready and the Fenced condition; the message is
// the Fenced reason and probe facts, else why the engine is not Ready.
func policyEngine(u *unstructured.Unstructured) *Resource {
	r := &Resource{Name: u.GetName()}
	r.Phase, _, _ = unstructured.NestedString(u.Object, "status", "phase")
	r.Ready, _, _ = unstructured.NestedBool(u.Object, "status", "ready")
	conditions, _, _ := unstructured.NestedSlice(u.Object, "status", "conditions")
	notReady := ""
	for _, raw := range conditions {
		c, _ := raw.(map[string]any)
		typ, _ := c["type"].(string)
		status, _ := c["status"].(string)
		reason, _ := c["reason"].(string)
		message, _ := c["message"].(string)
		switch {
		case typ == policyv1alpha1.PolicyEngineConditionFenced:
			r.Fenced, r.Message = status, reason+": "+message
		case typ == "Ready" && status != "True":
			notReady = reason + ": " + message
		}
	}
	if r.Message == "" {
		r.Message = notReady
	}
	return r
}

// guestParts reads the requester's guestMayRun inputs from the unstructured
// status.contract: an ok receipt (receipt set, receiptOk true), a
// termination, and a release answer with ok true.
func guestParts(u *unstructured.Unstructured) (receiptOK, terminated, releaseOK bool) {
	if _, ok, _ := unstructured.NestedMap(u.Object, "status", "contract", "receipt"); ok {
		receiptOK, _, _ = unstructured.NestedBool(u.Object, "status", "contract", "receiptOk")
	}
	_, terminated, _ = unstructured.NestedFieldNoCopy(u.Object, "status", "contract", "termination")
	releaseOK, _, _ = unstructured.NestedBool(u.Object, "status", "contract", "release", "ok")
	return receiptOK, terminated, releaseOK
}