Query unstable
A keyed data cache. Each query is a class service with a name, argument and
result Schemas, and a freshness duration. The cache keeps one entry per query
and arguments, shares in-flight fetches, refetches stale entries on demand,
and collects unused entries. A stream query, made with StreamService,
follows a Stream instead of fetching.
Attach a fetcher with toLayer: it builds once per Layer build and captures
its dependencies, so get requires only the query and cache. Fake it in
tests with GetUser.toLayer(fn).
Plain Effect code provides the cache with Query.layer(). Every time-based
rule runs on the Clock, so TestClock drives it, and
effect/ui/testing/TestQuery is the harness for tests.
Server dehydration omits entries whose args, success or error Schema holds
a Schema.Redacted, even when the current value contains no secret. The
client fetches omitted entries instead of hydrating them. Ordinary entries
still dehydrate and hydrate through their JSON codecs.
Example Defining a query and sharing its fetch
import { Effect, Layer, Schema } from "effect"import { Query } from "effect/ui"
let requests = 0
class GetUser extends Query.Service<GetUser>()("users/GetUser", { args: { id: Schema.String }, success: Schema.Struct({ id: Schema.String, name: Schema.String }), error: Schema.Never, staleTime: "30 seconds"}) { static readonly layer = this.toLayer(({ id }) => Effect.sync(() => ({ id, name: `User ${++requests}` })) )}
const program = Effect.gen(function*() { // Two callers at once share one fetch, and the second call is served from the cache. const [a, b] = yield* Effect.all([GetUser.get({ id: "1" }), GetUser.get({ id: "1" })], { concurrency: "unbounded" }) const c = yield* GetUser.get({ id: "1" }) return [a.name, b.name, c.name, requests]}).pipe(Effect.provide(Layer.merge(GetUser.layer, Query.layer())))
await Effect.runPromise(program) // => ["User 1", "User 1", "User 1", 1]Constructors
InfiniteService
unstableDefines an infinite query: a query that holds every page of an accumulating list in one entry, and loads more of them on request.
When to use
Use when a new page appends to what the screen shows, such as an infinite
feed or a "load more" button, on a cursor API or an offset one. When a new
page replaces the old one, use an ordinary query with the page in its args,
even on a cursor API: h.queries keeps the old page until the new one loads.
Details
pageis the Schema of one page. The entry's value is the page array.itemslists a page's items andkeyidentifies each item. Both are required. Items are deduplicated bykey, keeping the first occurrence, including when an offset API shifts items between pages.cursoris the Schema of a cursor, andnextderives the cursor of the page afterlastPagefrom the server's pages,Nonewhen the list has ended. It must be pure. The cursor is never stored.- Attach the fetcher with
toLayer; it takes(args, cursor), withNonefor the first page. - The other options are a query's.
staleTimecounts from the end of the last load that started at the first page: loading more changes no timestamp.
One entry holds every page of one list, and one load runs per list. A refetch loads the pages again from the first one, in sequence, as many as the list holds, and swaps them in at the end; a list that got shorter ends early. An invalidation, a patch and the close of the build that loads restart it from the first page, keeping the pages to reach. A visibility, connectivity or interval refetch that arrives while a page is being appended runs once that page is in.
A failed load more keeps the held pages and sets an error that a view
reads as More's Failed. A refetch that fails on a page the list
holds is a Failure with the held pages as its previous Success; one that
fails on the page past them swaps the pages it loaded in, and sets that
error. Nothing retries.
Gotchas
- Write
itemsbeforekey. TypeScript infers the item type from the first of the two it reads, so withkeyfirst an item isunknown. - A refetch of a list of 30 pages is 30 requests, one after the other.
- Every infinite query with the same arguments shares its page count, which
only goes up until
resetor the entry is collected. - The server renders the first page only, so the page size is the one lever on how much of a list a server render shows.
- Every page a list field holds is saved in
history.stateon each navigation.$.resetdrops the pages after the first, and is the way to keep that small. - For replacement pagination with an ordinary query, reset the cursor when a filter changes, or the new filter opens at the old cursor.
Signature
declare const InfiniteService: <Self>() => <Name extends string, Args extends NoServices | { [x: string]: NoServices;} = {}, PageSchema extends NoServices = never, Item = unknown, CursorSchema extends NoServices = never, Error extends NoServices = Never>(name: Name, options: NoInfer<Given<"args", Args, {}> & Given<"error", Error, Never>> & { readonly args?: Args; readonly cursor: CursorSchema; readonly error?: Error; readonly idleTimeToLive?: Input; readonly items: (page: PageSchema["Type"]) => readonly Array<Item>; readonly key: (item: NoInfer<Item>) => string; readonly next: (lastPage: PageSchema["Type"], allPages: readonly [PageSchema["Type"], PageSchema["Type"]]) => Option<CursorSchema["Type"]>; readonly page: PageSchema; readonly persist?: boolean; readonly reactivityKeys?: (args: ArgsSchema<Args>["Type"]) => readonly Array<unknown> | ReadonlyRecord<string, readonly Array<unknown>>; readonly refetchInterval?: RefetchInterval<ArgsSchema<Args>["Type"], readonly Array<PageSchema["Type"]>, Error["Type"]>; readonly staleTime: Input; readonly tags?: readonly Array<Tag>;}) => InfiniteService<Self, Name, ArgsSchema<Args>, PageSchema, Item, CursorSchema, Error>Example A list of messages
import { Effect, Layer, Option, Schema } from "effect"import { Query } from "effect/ui"
const Page = Schema.Struct({ messages: Schema.Array(Schema.Struct({ id: Schema.String, text: Schema.String })), next: Schema.NullOr(Schema.Number)})
class ListMessages extends Query.InfiniteService<ListMessages>()("chat/ListMessages", { args: { room: Schema.String }, page: Page, items: (page) => page.messages, key: (message) => message.id, error: Schema.Never, cursor: Schema.Number, next: (lastPage) => Option.fromNullishOr(lastPage.next), staleTime: "30 seconds"}) { static readonly layer = this.toLayer(({ room }, cursor) => { const from = Option.getOrElse(cursor, () => 0) return Effect.succeed({ messages: [{ id: `${room}-${from}`, text: `message ${from}` }], next: from < 2 ? from + 1 : null }) })}
const program = Effect.gen(function*() { yield* ListMessages.get({ room: "a" }) const { pages, hasMore } = yield* ListMessages.loadMore({ room: "a" }) return [ListMessages.items(pages).map((message) => message.text), hasMore]}).pipe(Effect.provide(Layer.merge(ListMessages.layer, Query.layer())))
await Effect.runPromise(program) // => [["message 0", "message 1"], true]makeSignal
unstableCreates a SettableSignal with an initial value of true unless specified.
When to use
Use to provide Visibility or Connectivity from a host source that only
pushes changes, such as a network listener. A source with a synchronous
read can implement Signal directly instead.
Details
getreturns the last value set, even without subscribers.- Listeners run in subscription order.
- Changes made inside a listener are queued and delivered in order after the current change.
- Unsubscribing before a listener's turn skips that call. A listener added during delivery only receives changes made after it subscribes.
Gotchas
A listener that throws doesn't stop the others, and set returns
normally. The error is rethrown in a microtask.
Signature
declare const makeSignal: (initial?: boolean) => SettableSignalExample Providing connectivity from a network listener
import { Effect, Layer } from "effect"import { Query } from "effect/ui"
declare const Network: { addListener(f: (state: { isConnected: boolean }) => void): { remove(): void }}
const ConnectivityLive = Layer.effect( Query.Connectivity, Effect.gen(function*() { const signal = Query.makeSignal(true) yield* Effect.acquireRelease( Effect.sync(() => Network.addListener((state) => signal.set(state.isConnected))), (subscription) => Effect.sync(() => subscription.remove()) ) return signal }))Defines a query service class. Attach its fetcher with toLayer.
When to use
Use when data is loaded by its arguments and shared: every caller of the same query with the same arguments sees one entry and one fetch.
Details
argsis a fields record or any Schema, none when omitted. The cache derives an entry's key from the encoded arguments.successis required.errordefaults toSchema.Never.staleTimeis required. Zero means always stale and"Infinity"means never stale by age. A stale entry is still served at once; it refetches when its first watcher arrives, ongetorprefetch, on a host edge, on its interval, or when it's invalidated.idleTimeToLiveis how long an entry nothing watches stays in the cache. It overrides the cache's default of 5 minutes.refetchIntervalpolls an entry while it's watched.tagslists the invalidation tags the query belongs to.persistsaves the query's Successes and restores them after a reload, stale, when the app providesQueryPersistence.layerKvs. Without that Layer it does nothing.reactivityKeysmaps arguments toReactivity.KeysInputso each live entry invalidates on matching publications whenReactivity.Reactivityis in context. Pick eitherreactivityKeysor Commandinvalidatesper query.
toLayer takes a fetcher function or an Effect that builds one once per
Layer build. Retries go inside the fetcher (Effect.retry); the cache never
retries. The Layer captures the fetcher's requirements when it's built,
except Query.Cache, which each fetch gets from its own cache, so a
fetcher can get another query's server value. When the fetch's context
also holds a service, such as one provided to a mount, the fetch's wins.
Gotchas
- The definition throws on a negative
staleTimeoridleTimeToLive, and on a constantrefetchIntervalthat is zero, negative or a bare number under 1000. - Calling a query throws when its arguments don't encode, or encode to something JSON can't carry.
{ id }and{ id, page: 1 }are two entries, even when a default makes them one request.- An optional field of the
argsstruct that isundefinedis the same as a missing one:{ id, page: undefined }and{ id }are one entry. The property is dropped before theargsSchema checks or encodes the arguments. - Only the fields of the
argsstruct itself are covered. What a field holds reaches the Schema as it was passed: a nested struct, a union, a class, a record, a tuple, anOptionor a collection. So do arguments that are not a struct, such as aSchema.Classor a union. - Everywhere else the Schema's encoding decides. The default JSON encoding
of a type that allows both
undefinedandnullencodes both asnull. So for a nestedpage: Schema.optional(Schema.NullOr(Schema.Number)),{ filter: { page: undefined } }and{ filter: { page: null } }are one entry, and the later call gets the data of the earlier one.{ filter: {} }is another entry. The same goes for a required key, a record's value and a tuple's element of such a type. - Other Schemas differ.
Schema.Anypasses values through, so anundefinedproperty is the same as a missing one. An encoding that distinguishesundefinedfromnullgives them separate entries; use one when the fetcher treats them differently. - The property's type decides whether
undefinedis allowed, so aSchema.optionalKey(Schema.Number)property rejects it. A type made withSchema.declareis not asked: underSchema.optionalKeyitsundefinedis left to the Schema. Anundefinedthat the Schema's own encoding produces is left to the Schema too. - Only a property the arguments hold as their own plain data is dropped. One they inherit, or one behind a getter, is left to the Schema.
- The arguments are never changed. When a property is dropped, the Schema gets a copy without it.
- The fetcher gets the arguments of the call that created the entry, so it can see either form.
Signature
declare const Service: <Self>() => <Name extends string, Args extends NoServices | { [x: string]: NoServices;} = {}, Success extends NoServices = never, Error extends NoServices = Never>(name: Name, options: NoInfer<Given<"args", Args, {}> & Given<"error", Error, Never>> & { readonly args?: Args; readonly error?: Error; readonly idleTimeToLive?: Input; readonly persist?: boolean; readonly reactivityKeys?: (args: ArgsSchema<Args>["Type"]) => readonly Array<unknown> | ReadonlyRecord<string, readonly Array<unknown>>; readonly refetchInterval?: RefetchInterval<ArgsSchema<Args>["Type"], Success["Type"], Error["Type"]>; readonly staleTime: Input; readonly success: Success; readonly tags?: readonly Array<Tag>;}) => Service<Self, Name, ArgsSchema<Args>, Success, Error>Example A query that captures a service
import { Context, Effect, Layer, Schema } from "effect"import { Query } from "effect/ui"
class UsersApi extends Context.Service<UsersApi, { readonly name: (id: string) => Effect.Effect<string>}>()("UsersApi") {}
class GetUserName extends Query.Service<GetUserName>()("users/GetUserName", { args: { id: Schema.String }, success: Schema.String, error: Schema.Never, staleTime: "1 minute"}) { static readonly layer = this.toLayer(Effect.gen(function*() { const api = yield* UsersApi return ({ id }) => api.name(id) }))}
const layer = GetUserName.layer.pipe( Layer.provide(Layer.succeed(UsersApi, { name: (id) => Effect.succeed(`user-${id}`) })), Layer.merge(Query.layer()))
await Effect.runPromise(GetUserName.get({ id: "1" }).pipe(Effect.provide(layer))) // => "user-1"StreamService
unstableDefines a stream query: a query whose entry follows a Stream, such as a
sync engine's subscription. Attach the stream function with toLayer.
When to use
Use when the server pushes changes to the data: every watcher of the same query with the same arguments shares one entry and one open stream.
Details
- The options are a query's, without
staleTimeandrefetchInterval. - The stream opens where a fetch would start: on the first watcher,
getorprefetchof an entry with no open stream. The entry isInitial, or its last value, withwaitinguntil the first element, which settles it as a fetch result does. Each later element is stored, or a chunk's last. - Watchers see changes, as for any query: an element equal to the stored value is stored but not emitted.
- An entry is fresh while its stream is open, and stale otherwise.
- The stream stays open while the entry exists: it closes when the entry
is collected,
idleTimeToLiveafter it was last watched or asked for. invalidatecloses the stream, waits for its cleanup, and a watched entry opens a new one.reactivityKeyshas the same effect as callinginvalidate(args)when a matching key is published. Use it for changes the stream can't observe (such as a session or filter change); to rerun a read on publication instead, returnreactivity.stream(keys, read)without declaringreactivityKeys.- A typed failure is stored over the last value and closes the stream. It reopens when the entry is requested again.
- Completion keeps the last value. The stream reopens when the entry is requested again, or immediately if the entry is watched and has a patch.
- A stream that ends before its first element is a defect.
- A server render stores the first element and closes the stream. The client opens it once the fetch-free window closes.
- A stream that reads
Other.changes(args)follows that entry's server value. Agetin aServicefetcher reads it once.
Gotchas
- Under the default
idleTimeToLiveof 5 minutes, a subscription stays open 5 minutes after its last watcher leaves. - A run that only patches an entry with an open stream doesn't reopen it:
failure drops the patch; success holds it until the next element. That
element can predate the write or describe another row. To keep the write
visible, record the written row and its version, then overlay it on older
rows in the stream function until the stream catches up. Clear these
records if the source resets its versions. See the keyed-row recipe in
LLMS.md, including its same-row queue. For a source that can't observe the write, list the entry ininvalidatesto reopen the stream. - An element that already holds the change can arrive while the patch is live, so write idempotent patches, such as setting a title rather than adding to a count.
- Two stream queries that follow each other never settle.
Stream.fromEffectcompletes after one element, so the entry goes stale at once. In a test that wants a live entry, follow it withStream.never.
Signature
declare const StreamService: <Self>() => <Name extends string, Args extends NoServices | { [x: string]: NoServices;} = {}, Success extends NoServices = never, Error extends NoServices = Never>(name: Name, options: NoInfer<Given<"args", Args, {}> & Given<"error", Error, Never>> & { readonly args?: Args; readonly error?: Error; readonly idleTimeToLive?: Input; readonly persist?: boolean; readonly reactivityKeys?: (args: ArgsSchema<Args>["Type"]) => readonly Array<unknown> | ReadonlyRecord<string, readonly Array<unknown>>; readonly refetchInterval?: undefined; readonly staleTime?: undefined; readonly success: Success; readonly tags?: readonly Array<Tag>;}) => StreamService<Self, Name, ArgsSchema<Args>, Success, Error>Example A note that follows its edits
import { Effect, Layer, Queue, Schema, Stream } from "effect"import { Query } from "effect/ui"
const Note = Schema.Struct({ id: Schema.String, title: Schema.String })
const program = Effect.gen(function*() { const edits = yield* Queue.unbounded<typeof Note.Type>()
class GetNote extends Query.StreamService<GetNote>()("notes/GetNote", { args: { id: Schema.String }, success: Note }) {}
const layer = Layer.merge( GetNote.toLayer(() => Stream.fromQueue(edits)), Query.layer() )
return yield* Effect.gen(function*() { yield* Queue.offer(edits, { id: "1", title: "Draft" }) const first = yield* GetNote.get({ id: "1" }) yield* Queue.offer(edits, { id: "1", title: "Final" }) yield* Effect.yieldNow // The stream is still open, so this is served from the cache. const latest = yield* GetNote.get({ id: "1" }) return [first.title, latest.title] }).pipe(Effect.provide(layer))})
await Effect.runPromise(program) // => ["Draft", "Final"]Declares an invalidation tag, to list in a query's tags.
When to use
Use to invalidate several queries together, such as everything that shows a user, without naming each query where the invalidation happens.
Signature
declare const Tag: (name: string) => TagLayers
Provides a query cache for Effect code or, through Component.provide, a
component subtree.
Details
idleTimeToLive is how long an entry stays once nothing watches it, 5
minutes by default; a query can override it. The cache takes Visibility,
Connectivity, Problems, Clock, and optional Reactivity.Reactivity
from where the Layer is built, and is disposed with the Layer's Scope:
fetches in flight are interrupted, and the close waits for their cleanup.
Through Component.provide, the cache serves the component and its descendants
unless a nested provider supplies another cache. Its lifetime and sharing
follow the Layer build, as described in Component.provide. A keyed provide
creates a new, empty cache when its key changes. During server rendering,
queries use the request's cache.
Gotchas
Throws on a negative idleTimeToLive.
Signature
declare function layer(options?: { readonly idleTimeToLive?: Input;}): Layer<Cache>Models
One entry of a query, as an invalidation target. Built by a query's entry.
Signature
interface EntryTarget<R extends Query.Any = Query.Any> { readonly _tag: "Entry"; readonly args: Args<R>; readonly query: R;}An infinite query: a query whose entry holds every page loaded so far, as an
array. Its result is the page array, so peek, changes and get
return the pages, and a patch maps them one page at a time.
Signature
interface InfiniteQuery<in out Args, in out Page, in out Item, in out E> extends Query<Args, ReadonlyArray<Page>, E> { readonly "~effect/ui/Query/Infinite": Variance<Page, Item>;}An infinite query class, as returned by InfiniteService.
Details
It's a Context.Service whose value is the query's fetcher, which takes
the arguments and the cursor of the page to load, None for the first.
The fetcher returns one page; get returns the page array. It has the
statics of a query, except set, and adds loadMore, reset and items.
Signature
interface InfiniteService<in out Self, in out Name extends string, in out Args extends Schema.Top, in out Page extends Schema.Top, in out Item, in out Cursor extends Schema.Top, in out Error extends Schema.Top> extends ServiceClass<Self, Name, (args: Args["Type"], cursor: Option.Option<Cursor["Type"]>) => Effect.Effect<Page["Type"], Error["Type"], Cache>>, InfiniteQuery<Args["Type"], Page["Type"], Item, Error["Type"]> { constructor(_: never); readonly args: Args; readonly error: Error; readonly success: $Array<Page>; changes(args: Args["Type"]): Stream<AsyncResult<readonly Array<Page["Type"]>, Error["Type"]>, never, Cache | Self>; entry(args: Args["Type"]): EntryTarget<InfiniteQuery<Args["Type"], Page["Type"], Item, Error["Type"]>>; get(args: Args["Type"]): Effect<readonly Array<Page["Type"]>, Error["Type"], Cache | Self>; invalidate(args?: Args["Type"]): Effect<void, never, Cache>; items(pages: readonly Array<Page["Type"]>): readonly Array<Item>; loadMore(args: Args["Type"]): Effect<LoadedMore<Page["Type"]>, Error["Type"], Cache | Self>; patch(args: Args["Type"], f: (page: Page["Type"], index: number) => Page["Type"]): Patch<InfiniteQuery<Args["Type"], Page["Type"], Item, Error["Type"]>>; patchAll(f: (page: Page["Type"], args: Args["Type"], index: number) => Page["Type"]): Patch<InfiniteQuery<Args["Type"], Page["Type"], Item, Error["Type"]>>; peek(args: Args["Type"]): Effect<AsyncResult<readonly Array<Page["Type"]>, Error["Type"]>, never, Cache>; prefetch(args: Args["Type"]): Effect<void, never, Cache | Self>; reset(args: Args["Type"]): Effect<void, never, Cache>; toLayer<LE = never, LR = never, R = never>(build: (args: Args["Type"], cursor: Option<Cursor["Type"]>) => Effect<Page["Type"], Error["Type"], R> | Effect<(args: Args["Type"], cursor: Option<Cursor["Type"]>) => Effect<Page["Type"], Error["Type"], R>, LE, LR>): Layer<Self, LE, Exclude<LR, Scope> | Exclude<R, Cache>>;}What an infinite query's loadMore resolves with: every page held once the
load ended, and whether there is a next one.
Signature
interface LoadedMore<Page> { readonly hasMore: boolean; readonly pages: readonly Array<Page>;}Whether a list holds more pages to load, as a view sees it.
Details
End: the definition'snextreturnedNonefor the last page.Available: there is a next page, and nothing is loading it.Loading: a load more is running or waiting its turn, such as behind a refetch of the held pages or a live patch.Failed: the last load more failed witherror. The held pages stay. The next load more, or the next refetch from page 1, clears it, and so does the last watcher leaving.
Signature
type More<E> = { readonly _tag: "End";} | { readonly _tag: "Available";} | { readonly _tag: "Loading";} | { readonly _tag: "Failed"; readonly error: E;}An optimistic patch, built by a query's patch or patchAll. It is a
pure function from a server value to the value to show.
Details
A patch is live while its run is queued or running: nothing fetches the entry, and its watchers see the patched value. After the run succeeds the patch is held until the entry settles, a write is stored, or its open stream sends an element. A failure, an interrupt or a defect drops it at once.
Signature
type Patch<R extends Query.Any = Query.Any> = { readonly _tag: "Patch"; readonly args: Query.Args<R>; readonly patch: (value: Query.Success<R>) => Query.Success<R>; readonly query: R;} | { readonly _tag: "PatchAll"; readonly patch: (value: Query.Success<R>, args: Query.Args<R>) => Query.Success<R>; readonly query: R;}What every query has in common: its name, and the types of its arguments, its result and its error.
Signature
interface Query<in out Args, in out A, in out E> { readonly "~effect/ui/Query": Variance<Args, A, E>;}How often a watched entry refetches: a duration, or a function of the last
settled result and the arguments that returns one, or undefined to stop.
Details
The function form is called once per settle with the result the fetcher
produced, a Success or a Failure. A duration under one second has to be
spelt as a Duration string such as "500 millis": a bare number under 1000
is rejected, since refetchInterval: 5 is a 5 ms poll written by mistake.
Signature
type RefetchInterval<Args, A, E> = Duration.Input | (result: AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>, args: Args) => Duration.Input | undefinedA query class, as returned by Service.
Details
A Context.Service holding the query's fetcher. Attach one with toLayer;
static methods look up the cache and require the query when they may fetch.
Signature
interface Service<in out Self, in out Name extends string, in out Args extends Schema.Top, in out Success extends Schema.Top, in out Error extends Schema.Top> extends ServiceClass<Self, Name, (args: Args["Type"]) => Effect.Effect<Success["Type"], Error["Type"], Cache>>, Query<Args["Type"], Success["Type"], Error["Type"]> { constructor(_: never); readonly args: Args; readonly error: Error; readonly success: Success; changes(args: Args["Type"]): Stream<AsyncResult<Success["Type"], Error["Type"]>, never, Cache | Self>; entry(args: Args["Type"]): EntryTarget<Query<Args["Type"], Success["Type"], Error["Type"]>>; get(args: Args["Type"]): Effect<Success["Type"], Error["Type"], Cache | Self>; invalidate(args?: Args["Type"]): Effect<void, never, Cache>; patch(args: Args["Type"], f: (value: Success["Type"]) => Success["Type"]): Patch<Query<Args["Type"], Success["Type"], Error["Type"]>>; patchAll(f: (value: Success["Type"], args: Args["Type"]) => Success["Type"]): Patch<Query<Args["Type"], Success["Type"], Error["Type"]>>; peek(args: Args["Type"]): Effect<AsyncResult<Success["Type"], Error["Type"]>, never, Cache>; prefetch(args: Args["Type"]): Effect<void, never, Cache | Self>; set(args: Args["Type"], value: Success["Type"]): Write<Query<Args["Type"], Success["Type"], Error["Type"]>>; toLayer<LE = never, LR = never, R = never>(build: (args: Args["Type"]) => Effect<Success["Type"], Error["Type"], R> | Effect<(args: Args["Type"]) => Effect<Success["Type"], Error["Type"], R>, LE, LR>): Layer<Self, LE, Exclude<LR, Scope> | Exclude<R, Cache>>;}A Signal whose value can be changed with set.
Signature
interface SettableSignal extends Signal { readonly set: (value: boolean) => void;}A boolean a host reports, with a synchronous getter and a listener. It is state, not a pulse: the cache reads the level as well as its edges.
Signature
interface Signal { readonly get: () => boolean; readonly subscribe: (listener: (value: boolean) => void) => () => void;}A stream query class, as returned by StreamService.
Details
It's a Context.Service whose value is the query's stream function. It
has the statics of a query except set, since the stream is the entry's
only writer.
Signature
interface StreamService<in out Self, in out Name extends string, in out Args extends Schema.Top, in out Success extends Schema.Top, in out Error extends Schema.Top> extends ServiceClass<Self, Name, (args: Args["Type"]) => Stream.Stream<Success["Type"], Error["Type"], Cache>>, Query<Args["Type"], Success["Type"], Error["Type"]> { constructor(_: never); readonly args: Args; readonly error: Error; readonly success: Success; changes(args: Args["Type"]): Stream<AsyncResult<Success["Type"], Error["Type"]>, never, Cache | Self>; entry(args: Args["Type"]): EntryTarget<Query<Args["Type"], Success["Type"], Error["Type"]>>; get(args: Args["Type"]): Effect<Success["Type"], Error["Type"], Cache | Self>; invalidate(args?: Args["Type"]): Effect<void, never, Cache>; patch(args: Args["Type"], f: (value: Success["Type"]) => Success["Type"]): Patch<Query<Args["Type"], Success["Type"], Error["Type"]>>; patchAll(f: (value: Success["Type"], args: Args["Type"]) => Success["Type"]): Patch<Query<Args["Type"], Success["Type"], Error["Type"]>>; peek(args: Args["Type"]): Effect<AsyncResult<Success["Type"], Error["Type"]>, never, Cache>; prefetch(args: Args["Type"]): Effect<void, never, Cache | Self>; toLayer<LE = never, LR = never, R = never>(build: (args: Args["Type"]) => Stream<Success["Type"], Error["Type"], R> | Effect<(args: Args["Type"]) => Stream<Success["Type"], Error["Type"], R>, LE, LR>): Layer<Self, LE, Exclude<LR, Scope> | Exclude<R, Cache>>;}A declared invalidation tag. A tag is a plain name, so two
Query.Tag("users") calls are one tag.
Signature
interface Tag { readonly _tag: "Tag"; readonly name: string;}What a run invalidates: a whole query, one entry or a tag.
Signature
type Target = Query.Any | EntryTarget | TagWhat started a fetch. Every fetch records exactly one, and the fetcher never sees it.
Details
watch: an entry's watcher count went from zero to one over a cold or stale entry. A watcher that joins others never refetches.getandprefetch: the call found a cold or stale entry with no fetch in flight. Agetthat calls the fetcher for its callers alone, storing nothing, recordsgettoo.visibilityandconnectivity: the host signal went from false to true, and a watched entry was stale or its interval had elapsed.interval: a watched entry'srefetchIntervalfired.invalidation: an invalidation hit a watched entry.loadMore: an infinite query'sloadMore.reset: an infinite query'sresethit a watched list.
It is also the trigger attribute of the fetch's span.
Signature
type Trigger = "watch" | "get" | "prefetch" | "visibility" | "connectivity" | "interval" | "invalidation" | "loadMore" | "reset"A write of a run's result into one entry, built by a query's set. A
Command's writes is the only place one is used.
Signature
interface Write<R extends Query.Any = Query.Any> { readonly _tag: "Set"; readonly args: Args<R>; readonly query: R; readonly value: Success<R>;}Other
Problems
DuplicateKeyInPage
unstableA page of a list holds two items with one key. The first survives in
items. A duplicate across two pages is left out without a report.
Signature
declare class DuplicateKeyInPage extends Readonly<{ readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "DuplicateKeyInPage";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly query: string; });}DuplicateName
unstableA second query was defined under a name already in the cache. The first definition wins: it pins the Schemas, the stale and idle times, the interval and the tags.
Signature
declare class DuplicateName extends Readonly<{ readonly message: string; readonly query: string;}> & { readonly _tag: "DuplicateName";} & Pipeable { constructor(args: { readonly message: string; readonly query: string; });}EncodeFailed
unstableAn entry failed to encode when the server cache was serialised. It is left out, and the client fetches it.
Signature
declare class EncodeFailed extends Readonly<{ readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "EncodeFailed";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly query: string; });}FetchRestarted
unstableOne entry's fetch was restarted 10 times in a row with no settle between. Nothing changes; it's reported once per streak.
Signature
declare class FetchRestarted extends Readonly<{ readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "FetchRestarted";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly query: string; });}HydrationDecodeFailed
unstableA hydrated entry's arguments or value failed to decode when its query
registered. The entry is cold. logKey is there only when the arguments
decoded.
Signature
declare class HydrationDecodeFailed extends Readonly<{ readonly logKey: string | undefined; readonly message: string; readonly part: "value" | "args"; readonly query: string;}> & { readonly _tag: "HydrationDecodeFailed";} & Pipeable { constructor(args: { readonly logKey: string | undefined; readonly message: string; readonly part: "value" | "args"; readonly query: string; });}HydrationMalformed
unstableThe serialised cache the client hydrates from isn't the expected shape. It is ignored whole.
Signature
declare class HydrationMalformed extends Readonly<{ readonly message: string;}> & { readonly _tag: "HydrationMalformed";} & Pipeable { constructor(args: { readonly message: string; });}IntervalInvalid
unstableA function-form refetchInterval returned zero, a negative, or a bare
number under 1000. The entry has no interval until its next settle.
Signature
declare class IntervalInvalid extends Readonly<{ readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "IntervalInvalid";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly query: string; });}IntervalThrew
unstableA function-form refetchInterval threw. The entry has no interval until
its next settle. error is what was thrown.
Signature
declare class IntervalThrew extends Readonly<{ readonly error: unknown; readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "IntervalThrew";} & Pipeable { constructor(args: { readonly error: unknown; readonly logKey: string; readonly message: string; readonly query: string; });}InvalidateIgnored
unstableA query's own invalidate was called on a per-request server cache, where
an entry settles once. Nothing changes.
Signature
declare class InvalidateIgnored extends Readonly<{ readonly message: string; readonly query: string | undefined;}> & { readonly _tag: "InvalidateIgnored";} & Pipeable { constructor(args: { readonly message: string; readonly query: string | undefined; });}PageRepeated
unstableA list's walk got a page again: next returned a cursor that encodes
equal to one the walk already used. Nothing changes; it's reported once per
walk.
Signature
declare class PageRepeated extends Readonly<{ readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "PageRepeated";} & Pipeable { constructor(args: { readonly logKey: string; readonly message: string; readonly query: string; });}PatchInvalid
unstableA patch made a value the query's success Schema rejects, the first time it
was applied. The value is used as is.
Signature
declare class PatchInvalid extends Readonly<{ readonly command: string; readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "PatchInvalid";} & Pipeable { constructor(args: { readonly command: string; readonly logKey: string; readonly message: string; readonly query: string; });}PatchMutated
unstableA patch changed the server value it was given, the first time it was applied. A patch must return a new value.
Details
The cache encodes the server value with the query's success Schema before
a run's patches are first applied and after, and compares snapshots of the
two encodings with Equal.equals. The check sees everything the Schema
encodes. Where the Schema passes a value through as it is, as Schema.Any
does, it sees the value's own data properties, and not:
- inside a value that implements
Equal; - state that only a getter reaches, such as a private field or a
WeakMap.
The check runs no getter and no Equal or Hash method of the value,
and finds an Equal value by the presence of its key. A patch that reads
a getter which memoizes into the value's own data is reported, since the
stored value changed. A Proxy has its getPrototypeOf, has,
ownKeys and getOwnPropertyDescriptor traps called, never get or
set, and one whose traps answer differently each time can be reported on
a patch that changed nothing. If a mutation goes unreported,
give the query a success Schema that encodes the value. A value the Schema
can't encode is not checked.
Signature
declare class PatchMutated extends Readonly<{ readonly command: string; readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "PatchMutated";} & Pipeable { constructor(args: { readonly command: string; readonly logKey: string; readonly message: string; readonly query: string; });}Diagnostic problems reported by the cache without changing its behavior.
Details
A problem names its query and the entry's log key, which is the entry's key
built with every Schema.Redacted argument redacted. It never carries a
value or the key itself.
Signature
type Problem = DuplicateName | IntervalThrew | IntervalInvalid | FetchRestarted | PageRepeated | DuplicateKeyInPage | PatchInvalid | PatchMutated | UncoveredWrite | InvalidateIgnored | EncodeFailed | HydrationMalformed | HydrationDecodeFailed | ReactivityMissingReactivityMissing
unstableA query declared reactivityKeys in a cache built without
Reactivity.Reactivity. Reported once per query; nothing registers.
Signature
declare class ReactivityMissing extends Readonly<{ readonly message: string; readonly query: string;}> & { readonly _tag: "ReactivityMissing";} & Pipeable { constructor(args: { readonly message: string; readonly query: string; });}UncoveredWrite
unstableA run wrote an entry that existed when it started and that neither its
invalidates nor a patch covers. The write applies.
Signature
declare class UncoveredWrite extends Readonly<{ readonly command: string; readonly logKey: string; readonly message: string; readonly query: string;}> & { readonly _tag: "UncoveredWrite";} & Pipeable { constructor(args: { readonly command: string; readonly logKey: string; readonly message: string; readonly query: string; });}References
Connectivity
unstableWhether the host is online. Defaults to always true, so servers and CLIs provide nothing.
Details
When it goes from false to true, and Visibility is true as well, the cache
refetches every watched entry that is stale or whose interval elapsed
meanwhile. While it's false, intervals don't fire. Being offline never
blocks a fetch: the fetcher fails, and the reconnect refetches. The cache
reads it once, when it's built. A custom host can provide it with
makeSignal.
Signature
declare const Connectivity: Context.Reference<Signal>Where the cache reports problems: a synchronous function, called with each
one. The default is console.warn(problem.message).
When to use
Use to send problems somewhere else, such as a Logger, by providing a
function that forks Effect.logWarning.
Details
Every check runs in every build. The cache reads the sink once, when it's built, and swallows anything the sink throws.
Signature
declare const Problems: Context.Reference<(problem: Problem.Any) => void>Visibility
unstableWhether the host is visible, such as a browser tab in the foreground. Defaults to always true, so servers and CLIs provide nothing.
Details
When it goes from false to true, and Connectivity is true as well, the
cache refetches every watched entry that is stale or whose interval elapsed
meanwhile. While it's false, intervals don't fire. The cache reads it once,
when it's built. A custom host can provide it with makeSignal.
Signature
declare const Visibility: Context.Reference<Signal>Services
Type IDs
InfiniteTypeId
unstableIdentifies an infinite query: a class made by InfiniteService.
Signature
declare const InfiniteTypeId: InfiniteTypeIdIdentifies an infinite query: a class made by InfiniteService.
Signature
type InfiniteTypeId = "~effect/ui/Query/Infinite"Identifies a query: a class made by Service.
Signature
declare const TypeId: TypeIdIdentifies a query: a class made by Service.
Signature
type TypeId = "~effect/ui/Query"Utils
applyPatches
unstableApplies, in order, every patch that targets the entry of read at args
to value, and leaves the others out.
When to use
Use to test a Command's optimistic patches without a cache. It is the
function the cache itself calls.
Signature
declare function applyPatches<R extends Any>(patches: readonly Array<Patch<Any>>, query: R, args: Args<R>, value: Success<R>): Success<R>Example Testing a patch
import { Schema } from "effect"import { Query } from "effect/ui"
class GetCount extends Query.Service<GetCount>()("counts/GetCount", { args: { id: Schema.String }, success: Schema.Number, error: Schema.Never, staleTime: "1 minute"}) {}
const patches = [GetCount.patch({ id: "a" }, (n) => n + 1)]Query.applyPatches(patches, GetCount, { id: "a" }, 1) // => 2Query.applyPatches(patches, GetCount, { id: "b" }, 1) // => 1invalidatesEntry
unstableWhether a run with these invalidates and optimistic declarations
invalidates the entry of read at args: a declared target hits it, or
a patch targets it.
When to use
Use to test a Command's declarations without a cache, using the same
predicate as the cache and get inside a run.
Details
A write stored fresh is left out of its run's invalidation. This predicate doesn't know about writes: it answers before they are subtracted.
Signature
declare function invalidatesEntry<R extends Any>(run: { readonly invalidates: readonly Array<Target>; readonly optimistic?: readonly Array<Patch<Any>>;}, query: R, args: Args<R>): booleanExample Testing a Command's targets
import { Schema } from "effect"import { Query } from "effect/ui"
const Users = Query.Tag("users")
class GetUser extends Query.Service<GetUser>()("users/GetUser", { args: { id: Schema.String }, success: Schema.String, error: Schema.Never, staleTime: "1 minute", tags: [Users]}) {}
Query.invalidatesEntry({ invalidates: [Users] }, GetUser, { id: "1" }) // => trueQuery.invalidatesEntry({ invalidates: [GetUser.entry({ id: "1" })] }, GetUser, { id: "2" }) // => false