wind

package
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

🌀 Wind

Wind is an async data fetching, caching, and state management library for Kitex inspired by React Query. It simplifies async state management (IsLoading, IsFetching, IsError), automates request deduping, cancels outstanding fetchers when components unmount, and provides an ergonomic mutation API with built-in query invalidation.

✨ Features

  • 🌀 Declarative Queries: Fetch async data easily inside functional components with wind.Use.
  • 📦 Thread-Safe Caching: Cache query results with strict K comparable keys for zero-reflection map lookups.
  • 🏎️ Request Deduping: If multiple components mount simultaneously and request the same key, only a single background request is dispatched.
  • 🛑 Automatic Unmount Cancellation: Instantly cancels the fetcher's context.Context when the number of subscribing components for a key drops to zero.
  • ⚡ Cache Invalidation: Force active queries to refetch in the background via Client.InvalidateQueries.
  • 🪓 Ergonomic Mutations: Execute mutations with state tracking (IsPending, Error) and context-based invalidation callbacks.
  • 🔗 Bounded Async: Leverages the promise package and the engine's background worker pool for all async operations, ensuring thread safety and main-thread callback routing.

🚀 Getting Started

1. Setup the Client Provider

Before starting the engine, mount your views inside wind.Provider. Keep one client for the lifetime of the app:

package main

import (
	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/extras/wind"
)

func mount(app *kite.Engine, view kitex.Node) {
	client := wind.NewClient()
	app.OnStop(client.Close)

	root := kitex.CreateRoot(app)
	root.Render(wind.Provider(wind.ProviderProps{Client: client}, view))
}
2. Fetch Data with wind.Use

Use the query hook by passing a comparable cache key and a plain Go fetch function:

type PodKey struct {
	Namespace string
	PodName   string
}

type PodInfo struct {
	Status string
	CPU    string
}

var PodViewer = kitex.FC("PodViewer", func(props PodKey) kitex.Node {
	// res holds Data, IsLoading, IsFetching, IsError, Error, and Refetch()
	res := wind.Use(props,
		func(ctx context.Context, key PodKey) (PodInfo, error) {
			return fetchPodDetails(ctx, key.Namespace, key.PodName)
		},
	)

	if res.IsLoading {
		return kitex.Text("Loading pod details...")
	}
	if res.IsError {
		return kitex.Text("Error: " + res.Error.Error())
	}

	return kitex.Box.Style(
		style.S().Padding(1),
		kitex.Span.Style(style.S().Bold(true), kitex.Text("Status: " + res.Data.Status)),
		kitex.Text("CPU Usage: " + res.Data.CPU),
		kitex.Button(kitex.ButtonProps{
			OnClick: func(e *event.MouseEvent) { res.Refetch() },
		}, kitex.Text("Manual Refresh")),
	)
})
3. Mutate and Invalidate with wind.UseMutation

Mutate remote data and invalidate cached queries to trigger automated background refetches:

type DeletePodVariables struct {
	Namespace string
	PodName   string
}

var DeletePodButton = kitex.FC("DeletePodButton", func(props PodKey) kitex.Node {
	mutation := wind.UseMutation(
		func(ctx context.Context, vars DeletePodVariables) (string, error) {
			return apiDeletePod(ctx, vars.Namespace, vars.PodName)
		},
		wind.MutationOptions[DeletePodVariables, string]{
			OnSuccess: func(result string, vars DeletePodVariables, ctx wind.MutationContext) {
				// Invalidate the query key to auto-trigger a background refetch
				ctx.Client.InvalidateQueries(PodKey{
					Namespace: vars.Namespace,
					PodName:   vars.PodName,
				})
			},
		},
	)

	text := "Delete Pod"
	if mutation.IsPending {
		text = "Deleting..."
	}

	return kitex.Button(kitex.ButtonProps{
		OnClick: func(e *event.MouseEvent) {
			mutation.Mutate(DeletePodVariables{
				Namespace: props.Namespace,
				PodName:   props.PodName,
			})
		},
	}, kitex.Text(text))
})
4. Optimistically mark a cached pod as deleting

Use the previous value as this option's rollback. Refresh the affected namespace after either outcome:

opts := wind.MutationOptions[PodKey, string]{
	OnMutate: func(k PodKey, ctx wind.MutationContext) (any, error) {
		prev, ok := wind.GetQueryData[PodKey, PodInfo](ctx.Client, k)
		if !ok {
			return nil, nil
		}
		next := prev
		next.Status = "Deleting"
		wind.SetQueryData(ctx.Client, k, next)
		return prev, nil
	},
	OnError: func(_ error, k PodKey, ctx wind.MutationContext) {
		if prev, ok := ctx.Rollback.(PodInfo); ok {
			wind.SetQueryData(ctx.Client, k, prev)
		}
	},
	OnSettled: func(_ string, _ error, k PodKey, ctx wind.MutationContext) {
		wind.InvalidateQueriesOf(ctx.Client, func(other PodKey) bool {
			return other.Namespace == k.Namespace
		})
	},
}

InvalidateQueriesOf skips other key types. For mixed keys, use client.InvalidateQueriesWhere(func(k any) bool { return k == "pods" || k == podKey }). Use CancelQueriesOf or CancelQueriesWhere with the same predicates to stop requests instead of refreshing them.

🛠 API Reference

Caching Client & Imperative Cache Helpers
  • NewClient() *Client: Instantiates a thread-safe cache store.
  • GetQueryData[K comparable, T any](client *Client, key K) (T, bool): Reads cached data for key if present, populated, and assignable to T without creating a cache entry on a miss.
  • SetQueryData[K comparable, T any](client *Client, key K, data T): Seeds or replaces cached data for key, arming the GC timer when unsubscribed and coalescing subscriber notifications on the main thread.
  • UpdateQueryData[K comparable, T any](client *Client, key K, updater func(prev T, exists bool) T): Atomically reads and updates cached data under the entry lock (ideal for optimistic updates and concurrent mutations) and coalesces subscriber notifications.
  • Client.InvalidateQueries(key any): Invalidates matching queries. Subscribed components immediately begin background refetches.
  • Client.CancelQueries(key any): Cancels in-flight queries and streams matching key (exact, prefix, or predicate), stops pending throttle timers, clears IsFetching, and notifies subscribers.
  • Client.InvalidateQueriesWhere(match func(any) bool): Invalidates cached entries whose keys satisfy match.
  • InvalidateQueriesOf[K comparable](client *Client, match func(K) bool): Invalidates matching entries, passing only keys assignable to K to the predicate.
  • Client.CancelQueriesWhere(match func(any) bool): Cancels in-flight queries and streams whose keys satisfy match.
  • CancelQueriesOf[K comparable](client *Client, match func(K) bool): Cancels matching work, passing only keys assignable to K to the predicate.
  • Client.Close(): Idempotently cancels all active queries, streams, and client-bound mutations, stops pending GC/throttle timers, clears the cache, and waits for background work to drain.
Options & Helpers
  • Optional[T] (Some, None): Zero-allocation wrapper used for optional configuration fields (Options.Enabled, Stream.Enabled, Stream.Throttle) so leaving a field unset preserves its default (Enabled defaults to true, Throttle defaults to 16ms).
  • Latest[T](_ T, next T) T: Convenience reducer for Stream.Reduce that replaces previous state with the latest event.
Hooks

Wind runs query and mutation functions on the background scheduler. Pass the supplied context to the underlying request: it links Wind's cancellation to scheduler shutdown. Panics surface as errors through the normal result path.

  • Use[K comparable, T any](key K, fetcher func(context.Context, K) (T, error), opts ...Options) Result[T]:
    • Options.Enabled (Optional[bool]): Defaults to true; set to wind.Some(false) to disable automatic fetching on mount.
    • Options.StaleTime: Max age before the cache entry is considered stale and re-fetched on mount/dependency change.
    • Options.KeepPreviousData: Show the previous key's data while a new key loads. IsPlaceholderData distinguishes that value; IsLoading is false. An error on the new key ends the placeholder.
    • Options.RefetchInterval: A positive interval polls while enabled and mounted. Busy ticks are skipped. Closing the client stops polling.
    • Options.Retry: Additional attempts after returned errors (default zero); panics are never retried. RetryDelay(attempt) overrides the cancellable exponential delay (1 second up to 30 seconds). Attempts start at zero; nonpositive delays retry immediately.
  • PrefetchQuery(client, key, fetcher, opts...): Warm missing or stale data without mounting a hook. Shares in-flight work with Use, honors StaleTime and retry settings, and expires unused entries after GcTime. Pass a positive StaleTime to Use to reuse fresh data without a background refresh.
  • UseStream[K comparable, E, S any](key K, spec Stream[E, S]) StreamResult[S]:
    • Subscribes to a declarative streaming query via promise.Spawn (scheduler-managed lifecycle outside the bounded worker pool) and exposes Status ("connecting", "open", "closed", "error"). Stopping the engine scheduler or calling Client.Close() cancels active streams.
    • Stream[E, S].Initial: Seeds state S before the first Fetch or Source emission.
    • Stream[E, S].Fetch: Optional snapshot loader executed on connect/reconnect before Source opens. If Fetch fails, Source is not invoked.
    • Stream[E, S].Source: State-aware func(ctx context.Context, state S) iter.Seq2[E, error] stream producer receiving the current state (seeded from Initial, cached RefetchAppend state, or Fetch) so cursors like LastEventID can be forwarded across reconnects.
    • Stream[E, S].Reduce: Folds every yielded event E into accumulated state S synchronously so throttled UI updates never drop events (when nil and E is assignable to S, events replace state directly).
    • Stream[E, S].Enabled (Optional[bool]): Defaults to true; toggling Some(true) -> Some(false) cancels when no other enabled consumer remains, and Some(false) -> Some(true) reconnects.
    • Stream[E, S].Throttle (Optional[time.Duration]): Defaults to 16ms; values <= 0 disable timer throttling and coalesce via microtasks.
    • Stream[E, S].RefetchMode: RefetchReplace (default, keeps cached data visible until first event), RefetchReset (resets to Initial immediately), or RefetchAppend (folds onto existing cached data).
  • UseMutation[V, R any](mutationFn func(context.Context, V) (R, error), opts ...MutationOptions[V, R]) MutationResult[V]:
    • State fields: IsPending, IsError, Error.
    • Mutate(vars V): Triggers mutation function.
    • OnMutate(variables V, ctx MutationContext) (rollback any, err error): Runs synchronously before scheduling mutationFn, for example to apply an optimistic update. Returning an error skips the mutation and any remaining options.
    • MutationContext.Rollback: The value returned by the same option's OnMutate, passed to its later callbacks. Use it in OnError to undo an optimistic update; Wind does not roll back automatically.
    • OnSuccess(result R, variables V, ctx MutationContext): Fires when mutationFn succeeds.
    • OnError(err error, variables V, ctx MutationContext): Fires when mutationFn returns an error or panics, or when OnMutate aborts with an error. Panics recovered from mutationFn are reported as errors.
    • OnSettled(result R, err error, variables V, ctx MutationContext): Runs after the same option's OnSuccess or OnError, including on preparation errors for options up to and including the one that aborted.
    • Unmounting cancels all outstanding mutation contexts and suppresses later callbacks. This is cooperative cancellation, not a rollback of server-side changes. A retained Mutate function does not start work after unmount.

Documentation

Overview

Package wind implements an asynchronous data fetching and caching library for Kitex applications, inspired by React Query.

It provides automated cache management, request deduping, background updates, and cache invalidation.

Cache Architecture

Cache state is managed by the Client. The Client maintains a thread-safe map of query keys. When a component initiates a query using Use, it retrieves the client instance from the context Provider. If the query does not exist in the cache, or is considered stale, the scheduler runs the fetcher on a background worker. Callers can also read, seed, and atomically update cached values imperatively via GetQueryData, SetQueryData, and UpdateQueryData, or cancel in-flight queries and streams via Client.CancelQueries. Call Client.Close on shutdown to cancel active queries and streams, stop pending timers, and wait for background goroutines to finish.

PrefetchQuery warms a missing or stale key without subscribing. Use joins an in-flight prefetch or reads its result immediately. StaleTime determines freshness; unused prefetched entries expire after Client.GcTime.

KeepPreviousData displays the last real result while a new key loads. IsPlaceholderData identifies it; errors are never hidden by a placeholder. RefetchInterval polls enabled, mounted hooks without queuing busy ticks. Retry counts additional attempts on errors, not panics. RetryDelay receives a zero-based retry index; the default backoff doubles from 1s up to 30s. Cancellation interrupts backoff, and Client.Close also stops polling.

Streaming & Accumulation

UseStream subscribes to declarative streams configured by Stream[E, S] on dedicated goroutines outside the bounded promise worker pool so long-lived streams never starve short-lived queries. A Stream can optionally load an initial snapshot via Fetch before opening a state-aware Source iter.Seq2[E, error] iterator (which receives the current state so cursors such as LastEventID can be forwarded across connects and reconnects). Incoming events are folded into state S via Reduce (or Latest when replacing state directly) before UI notification throttling, ensuring rapid event bursts are never dropped. Stream supports Optional[bool] Enabled, Optional[time.Duration] Throttle, and RefetchMode (RefetchReplace, RefetchReset, RefetchAppend).

Request Deduping

If multiple components mount simultaneously with the exact same cache key, they subscribe to the same cache entry. Only a single fetcher goroutine is fired. Once the fetch completes, all subscribed components are notified and re-render with the fetched data.

Comparable Keys

The Use hook enforces a comparable constraint on cache keys (K comparable). This enables zero-reflection, fast O(1) map lookups, while internally storing keys under type-erased "any" values in the Client.

Mutations and Invalidation

OnMutate runs synchronously before the request. Its return value is private to that option and mutation call. OnSettled follows OnSuccess or OnError. For example, optimistically rename a cached title and refresh list views:

opts := wind.MutationOptions[string, int]{
	OnMutate: func(v string, ctx wind.MutationContext) (any, error) {
		old, ok := wind.GetQueryData[string, string](ctx.Client, "title")
		if ok {
			wind.SetQueryData(ctx.Client, "title", v)
			return old, nil
		}
		return nil, nil
	},
	OnError: func(_ error, _ string, ctx wind.MutationContext) {
		if old, ok := ctx.Rollback.(string); ok {
			wind.SetQueryData(ctx.Client, "title", old)
		}
	},
	OnSettled: func(_ int, _ error, _ string, ctx wind.MutationContext) {
		wind.InvalidateQueriesOf(ctx.Client, func(k ListKey) bool {
			return k.Filter == "open"
		})
	},
}

For mixed key types, use Client.InvalidateQueriesWhere with a func(any) bool. Both predicate forms run outside the cache lock and may read cached data.

Unmounting cancels the contexts of outstanding mutations and suppresses later callbacks. Use and UseMutation take plain func(context.Context, K) (T, error) functions. Wind runs them on the background scheduler and links their context to scheduler shutdown. Pass that context to the underlying request.

Index

Constants

This section is empty.

Variables

View Source
var ErrClientClosed = errors.New("wind: client is closed")

ErrClientClosed is returned by PerformDevToolsAction when the target client has already been closed.

View Source
var ErrQueryNotFound = errors.New("wind: query not found")

ErrQueryNotFound is returned by PerformDevToolsAction when no cache entry matches the requested key ID.

Functions

func CancelQueriesOf

func CancelQueriesOf[K comparable](c *Client, match func(K) bool)

func GetQueryData

func GetQueryData[K comparable, T any](client *Client, key K) (T, bool)

GetQueryData reads the cached value for key if it exists, has data, and is assignable to T. It never creates a new cache entry on a miss.

func InvalidateQueriesOf

func InvalidateQueriesOf[K comparable](c *Client, match func(K) bool)

func Latest

func Latest[T any](_ T, next T) T

Latest is a convenience reducer that replaces previous state with the latest event.

func PrefetchQuery

func PrefetchQuery[K comparable, T any](
	client *Client,
	key K,
	fetcher func(context.Context, K) (T, error),
	opts ...Options,
)

func Provider

func Provider(props ProviderProps, children ...kitex.Node) kitex.Node

Provider makes the Client available to the component tree.

func SetQueryData

func SetQueryData[K comparable, T any](client *Client, key K, data T)

SetQueryData writes data directly into the cache entry for key and notifies active subscribers with coalescing.

func UpdateQueryData

func UpdateQueryData[K comparable, T any](client *Client, key K, updater func(prev T, exists bool) T)

UpdateQueryData atomically reads the current cached value for key, computes the next value via updater while holding the entry lock, stores it, and notifies active subscribers with coalescing.

Types

type Client

type Client struct {
	GcTime time.Duration
	// contains filtered or unexported fields
}

func NewClient

func NewClient() *Client

func UseClient

func UseClient() *Client

UseClient extracts the client from the context.

func (*Client) CancelQueries

func (c *Client) CancelQueries(key any)

CancelQueries cancels in-flight queries and streams matching the search key/predicate.

func (*Client) CancelQueriesWhere

func (c *Client) CancelQueriesWhere(match func(key any) bool)

func (*Client) Close

func (c *Client) Close()

Close cancels all active queries and streams, stops pending timers, clears the cache, and waits for all background operations started by the client to finish. Close is safe to call multiple times.

func (*Client) InvalidateQueries

func (c *Client) InvalidateQueries(key any)

InvalidateQueries invalidates all queries matching the search key/predicate.

func (*Client) InvalidateQueriesWhere

func (c *Client) InvalidateQueriesWhere(match func(key any) bool)

func (*Client) PerformDevToolsAction

func (c *Client) PerformDevToolsAction(action string, keyID string) error

PerformDevToolsAction executes a DevTools control action ("invalidate", "refetch", "cancel", or "remove") against the cache entry whose formatted key ID matches keyID.

func (*Client) SnapshotQueries

func (c *Client) SnapshotQueries() []QuerySnapshot

SnapshotQueries returns a deterministic, thread-safe snapshot of all active cache entries sorted by Key.

type MutationContext

type MutationContext struct {
	Client   *Client
	Rollback any
}

type MutationOptions

type MutationOptions[V any, R any] struct {
	OnMutate  func(V, MutationContext) (rollback any, err error)
	OnSuccess func(R, V, MutationContext)
	OnError   func(error, V, MutationContext)
	OnSettled func(R, error, V, MutationContext)
}

type MutationResult

type MutationResult[V any] struct {
	IsPending bool
	IsError   bool
	Error     error
	Mutate    func(V)
}

func UseMutation

func UseMutation[V any, R any](
	mutationFn func(context.Context, V) (R, error),
	opts ...MutationOptions[V, R],
) MutationResult[V]

UseMutation tracks mutations for the mounted component. Unmounting cancels their context and suppresses subsequent success and error callbacks. The mutation function must honor that context to stop its underlying work.

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional wraps a value of type T to distinguish an explicitly set value (including the zero value) from an unset option.

func None

func None[T any]() Optional[T]

None returns an unset Optional.

func Some

func Some[T any](v T) Optional[T]

Some returns an Optional with v explicitly set.

func (Optional[T]) Get

func (o Optional[T]) Get() (T, bool)

Get returns the stored value and a boolean reporting whether it was set.

func (Optional[T]) IsSet

func (o Optional[T]) IsSet() bool

IsSet reports whether a value has been explicitly set.

func (Optional[T]) UnwrapOr

func (o Optional[T]) UnwrapOr(fallback T) T

UnwrapOr returns the stored value if set, otherwise fallback.

func (Optional[T]) Value

func (o Optional[T]) Value() T

Value returns the stored value, or the zero value of T if unset.

type Options

type Options struct {
	Enabled          Optional[bool]
	StaleTime        time.Duration
	KeepPreviousData bool
	RefetchInterval  time.Duration
	Retry            int
	RetryDelay       func(attempt int) time.Duration
}

type ProviderProps

type ProviderProps struct {
	Client *Client
}

type QuerySnapshot

type QuerySnapshot struct {
	ID          string `json:"id"`
	Key         string `json:"key"`
	Status      string `json:"status"` // "loading", "success", "error"
	IsFetching  bool   `json:"isFetching"`
	HasData     bool   `json:"hasData"`
	Data        any    `json:"data,omitempty"`
	Error       string `json:"error,omitempty"`
	Subscribers int    `json:"subscribers"`
	Version     uint64 `json:"version"`
	UpdatedAt   string `json:"updatedAt,omitempty"`
}

QuerySnapshot is a JSON-serializable snapshot of a cached query or stream entry.

type RefetchMode

type RefetchMode uint8

RefetchMode controls how cached stream state is treated when reconnecting.

const (
	// RefetchReplace keeps cached Data visible while reconnecting, folds incoming
	// events into a fresh initial state, and swaps Data on the first yielded event.
	RefetchReplace RefetchMode = iota
	// RefetchReset clears cached Data back to initial immediately upon reconnect
	// and transitions status back to loading/connecting until the first event.
	RefetchReset
	// RefetchAppend folds incoming events on reconnect onto the existing cached Data
	// (if present, otherwise starting from initial).
	RefetchAppend
)

type Result

type Result[T any] struct {
	Data              T
	IsLoading         bool
	IsFetching        bool
	IsError           bool
	IsPlaceholderData bool
	Error             error
	Refetch           func()
}

func Use

func Use[K comparable, T any](
	key K,
	fetcher func(context.Context, K) (T, error),
	opts ...Options,
) Result[T]

type Stream

type Stream[E, S any] struct {
	// Initial seeds the state before the first Fetch or Source emission.
	Initial S
	// Fetch optionally loads an authoritative snapshot on connect and reconnect
	// before Source begins streaming deltas.
	Fetch func(ctx context.Context) (S, error)
	// Source opens the event stream, receiving the current state (seeded from
	// Initial, cached RefetchAppend state, or Fetch) so cursors like LastEventID
	// can be forwarded on connect/reconnect.
	Source func(ctx context.Context, state S) iter.Seq2[E, error]
	// Reduce folds each incoming event into the accumulated state. When nil and E
	// is assignable to S, incoming events replace the state directly.
	Reduce func(state S, event E) S
	// Enabled controls whether the stream connects (defaults to true when unset).
	Enabled Optional[bool]
	// Throttle bounds UI notification frequency (defaults to 16ms when unset; <= 0 coalesces via microtask).
	Throttle Optional[time.Duration]
	// RefetchMode controls how cached state behaves across reconnects.
	RefetchMode RefetchMode
}

Stream configures a declarative streaming query for UseStream.

type StreamResult

type StreamResult[T any] struct {
	Result[T]
	Status string
}

func UseStream

func UseStream[K comparable, E, S any](key K, spec Stream[E, S]) StreamResult[S]

UseStream subscribes to a declarative stream configured by spec, optionally loading an initial snapshot via Fetch, opening a state-aware Source iterator, and folding incoming events with Reduce.

Directories

Path Synopsis
Package winddt provides the DevTools integration bridge for wind async queries and streams.
Package winddt provides the DevTools integration bridge for wind async queries and streams.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL