Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/live-query-interrupted-discovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@effect-app/vue": patch
---

Stop buffering live-query writes forever when a live fetch is interrupted while waiting for the invalidation source to be ready.
16 changes: 9 additions & 7 deletions packages/vue/src/atomQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import * as Stream from "effect/Stream"
import type * as Tracer from "effect/Tracer"
import { clearQueryReadDependencies, getQueryReadDependencies, type QueryInvalidationMode, registerQueryInvalidationMode, setQueryReadDependencies } from "./dependencyMetadata.ts"
import { reportRuntimeError } from "./lib.ts"
import { beginLiveQueryFetch, endLiveQueryFetch, type LiveQueryOptions, registerLiveQuery } from "./liveQueryInvalidation.ts"
import { acquireLiveQueryFetch, endLiveQueryFetch, type LiveQueryOptions, liveQueryReady, registerLiveQuery } from "./liveQueryInvalidation.ts"
import { atomsToRefetch, observeQueryAtom } from "./queryLifetime.ts"

/** All non-empty prefixes of a key, longest last. `[a,b,c]` -> `[[a],[a,b],[a,b,c]]`. */
Expand Down Expand Up @@ -503,14 +503,16 @@ export const buildQueryFamily = <I, A, E>(
setQueryReadDependencies(fullKey, lastReads)
return result
})
let liveFetch = false
const effect = Effect
.gen(function*() {
liveFetch = yield* Effect.promise(() => beginLiveQueryFetch(fullKey))
return yield* recordReads.pipe(Effect.retry({ times: 5, while: isRetryable }))
})
.acquireUseRelease(
Effect.sync(() => acquireLiveQueryFetch(fullKey)),
(live) =>
(live ? Effect.promise(liveQueryReady) : Effect.void).pipe(
Effect.andThen(recordReads.pipe(Effect.retry({ times: 5, while: isRetryable })))
),
(live) => Effect.sync(() => endLiveQueryFetch(live))
)
.pipe(
Effect.ensuring(Effect.sync(() => endLiveQueryFetch(liveFetch))),
Effect.tapCauseIf(Cause.hasDies, (cause) => reportRuntimeError(cause)),
// On exit, the compute is no longer in-flight. An interrupt (subscriber lost interest / a
// superseding refresh) may leave the result at `waiting`; with `inFlight` back at 0 that
Expand Down
13 changes: 11 additions & 2 deletions packages/vue/src/liveQueryInvalidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,20 @@ export const registerLiveQuery = (
}
}

export const beginLiveQueryFetch = async (key: ReadonlyArray<unknown>) => {
/** Synchronously marks a live fetch as discovering; pair with `endLiveQueryFetch` even if interrupted. */
export const acquireLiveQueryFetch = (key: ReadonlyArray<unknown>) => {
if (!entries.has(Hash.hash(key)) || source === undefined) return false
discovering++
return true
}

export const liveQueryReady = () => source?.ready() ?? Promise.resolve()

/** @deprecated Interruptible between acquire and ready; use `acquireLiveQueryFetch` + `liveQueryReady`. */
export const beginLiveQueryFetch = async (key: ReadonlyArray<unknown>) => {
if (!acquireLiveQueryFetch(key)) return false
try {
await source.ready()
await liveQueryReady()
return true
} catch (error) {
discovering--
Expand Down
46 changes: 43 additions & 3 deletions packages/vue/test/liveQueryInvalidation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime"
import { afterEach, describe, expect, it, vi } from "vitest"
import { awaitAtomResult, buildQueryFamily, invalidateAndAwait, invalidateSoft, makeAtomClientRuntime, withQueryOptions } from "../src/atomQuery.js"
import { getQueryInvalidationMode } from "../src/dependencyMetadata.js"
import { beginLiveQueryFetch, configureLiveQueryInvalidation, endLiveQueryFetch, registerLiveQuery } from "../src/liveQueryInvalidation.js"
import { acquireLiveQueryFetch, configureLiveQueryInvalidation, endLiveQueryFetch, liveQueryReady, registerLiveQuery } from "../src/liveQueryInvalidation.js"

const repo = DataDependencies.repo("Inventory", ["item-1"])
const otherId = DataDependencies.repo("Inventory", ["item-2"])
Expand Down Expand Up @@ -166,16 +166,56 @@ describe("live query invalidation", () => {
let reads = DataDependencies.empty()
cleanups.push(registerLiveQuery(key, () => reads, {}))

const starting = beginLiveQueryFetch(key)
const wasLive = acquireLiveQueryFetch(key)
const starting = liveQueryReady()
receive(new Set([repo]))
open()
const wasLive = await starting
await starting
reads = new Set([repo])
endLiveQueryFetch(wasLive)

expect(invalidations).toEqual([[key]])
})

it("dispatches writes after an observed live query is interrupted while awaiting readiness", async () => {
const dependency = DataDependencies.repo("LiveOrders")
const mrt = ManagedRuntime.make(Layer.empty)
const rt = makeAtomClientRuntime(() => Layer.empty, mrt.memoMap)
const invalidations: Array<ReadonlyArray<ReadonlyArray<unknown>>> = []
let receive = (_writes: DataDependencies.DataDependencies) => {}
let readyCalled = () => {}
const readyRequested = new Promise<void>((resolve) => readyCalled = resolve)
configureLiveQueryInvalidation({
ready: () => {
readyCalled()
return new Promise<void>(() => {})
},
subscribe: (onWrites) => {
receive = onWrites
return () => {}
},
invalidate: (keys) => invalidations.push(keys)
})
const query = { id: "LiveOrders.Pending", handler: () => DataDependencies.read(dependency) }
const base = buildQueryFamily(rt, query)(undefined)
const atom = withQueryOptions(base, { live: true, revalidateOnFocus: false }, [...makeQueryKey(query), undefined])
try {
const unmount = defaultRegistry.mount(atom)
await readyRequested
unmount()
defaultRegistry.reset()
await new Promise((resolve) => setTimeout(resolve, 0))

const key = ["$LiveOrders", "Other", undefined]
cleanups.push(registerLiveQuery(key, () => new Set([dependency]), {}))
receive(new Set([dependency]))
expect(invalidations).toEqual([[key]])
} finally {
defaultRegistry.reset()
await mrt.dispose()
}
})

it("coalesces matching writes using the query's maximum delay", () => {
vi.useFakeTimers()
const invalidations: Array<ReadonlyArray<ReadonlyArray<unknown>>> = []
Expand Down
Loading