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 ¶
- Variables
- func CancelQueriesOf[K comparable](c *Client, match func(K) bool)
- func GetQueryData[K comparable, T any](client *Client, key K) (T, bool)
- func InvalidateQueriesOf[K comparable](c *Client, match func(K) bool)
- func Latest[T any](_ T, next T) T
- func PrefetchQuery[K comparable, T any](client *Client, key K, fetcher func(context.Context, K) (T, error), ...)
- func Provider(props ProviderProps, children ...kitex.Node) kitex.Node
- func SetQueryData[K comparable, T any](client *Client, key K, data T)
- func UpdateQueryData[K comparable, T any](client *Client, key K, updater func(prev T, exists bool) T)
- type Client
- func (c *Client) CancelQueries(key any)
- func (c *Client) CancelQueriesWhere(match func(key any) bool)
- func (c *Client) Close()
- func (c *Client) InvalidateQueries(key any)
- func (c *Client) InvalidateQueriesWhere(match func(key any) bool)
- func (c *Client) PerformDevToolsAction(action string, keyID string) error
- func (c *Client) SnapshotQueries() []QuerySnapshot
- type MutationContext
- type MutationOptions
- type MutationResult
- type Optional
- type Options
- type ProviderProps
- type QuerySnapshot
- type RefetchMode
- type Result
- type Stream
- type StreamResult
Constants ¶
This section is empty.
Variables ¶
var ErrClientClosed = errors.New("wind: client is closed")
ErrClientClosed is returned by PerformDevToolsAction when the target client has already been closed.
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 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 ¶
func (*Client) CancelQueries ¶
CancelQueries cancels in-flight queries and streams matching the search key/predicate.
func (*Client) CancelQueriesWhere ¶
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 ¶
InvalidateQueries invalidates all queries matching the search key/predicate.
func (*Client) InvalidateQueriesWhere ¶
func (*Client) PerformDevToolsAction ¶
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 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 ¶
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.
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 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 ¶
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.