import { BrowserStream } from "@effect/platform-browser" import * as AsyncData from "@typed/async-data" import { type Cause, Effect, Fiber, identity, Option, Queue, Ref, type Scope, Stream, SubscriptionRef } from "effect" import type * as QueryClient from "./QueryClient.js" import * as QueryProgress from "./QueryProgress.js" import { QueryState } from "./internal/index.js" export interface QueryRunner { readonly queryKey: Stream.Stream readonly latestKeyValueRef: SubscriptionRef.SubscriptionRef> readonly stateRef: SubscriptionRef.SubscriptionRef> readonly fiberRef: SubscriptionRef.SubscriptionRef | AsyncData.Failure, Cause.NoSuchElementException >>> readonly interrupt: Effect.Effect readonly forkInterrupt: Effect.Effect> readonly forkFetch: (keyValue: K) => Effect.Effect | AsyncData.Failure>, state: Stream.Stream>, ]> readonly forkRefresh: Effect.Effect | AsyncData.Failure, Cause.NoSuchElementException>, state: Stream.Stream>, ]> } export const Tag = (id: Id) => < Self, K extends readonly unknown[], A, E = never >() => Effect.Tag(id)>() export interface MakeProps { readonly QueryClient: QueryClient.GenericTagClass readonly key: Stream.Stream readonly query: (key: K) => Effect.Effect } export const make = ( { QueryClient, key, query, }: MakeProps ): Effect.Effect< QueryRunner>, never, R | QueryClient.TagClassShape > => Effect.gen(function*() { const context = yield* Effect.context>() const latestKeyValueRef = yield* SubscriptionRef.make(Option.none()) const stateRef = yield* SubscriptionRef.make(AsyncData.noData>()) const fiberRef = yield* SubscriptionRef.make(Option.none | AsyncData.Failure>, Cause.NoSuchElementException >>()) const queryStateTag = QueryState.makeTag>() const interrupt = Effect.flatMap(fiberRef, Option.match({ onSome: fiber => Ref.set(fiberRef, Option.none()).pipe( Effect.andThen(Fiber.interrupt(fiber)) ), onNone: () => Effect.void, })) const forkInterrupt = Effect.flatMap(fiberRef, Option.match({ onSome: fiber => Ref.set(fiberRef, Option.none()).pipe( Effect.andThen(Fiber.interrupt(fiber).pipe( Effect.asVoid, Effect.forkDaemon, )) ), onNone: () => Effect.forkDaemon(Effect.void), })) const run = (keyValue: K) => Effect.all([QueryClient, queryStateTag]).pipe( Effect.flatMap(([client, state]) => Ref.set(latestKeyValueRef, Option.some(keyValue)).pipe( Effect.andThen(query(keyValue)), client.errorHandler.handle, Effect.matchCauseEffect({ onSuccess: v => Effect.tap(Effect.succeed(AsyncData.success(v)), state.set), onFailure: c => Effect.tap(Effect.succeed(AsyncData.failure(c)), state.set), }), )), Effect.provide(context), Effect.provide(QueryProgress.QueryProgress.Default), ) const forkFetch = (keyValue: K) => Queue.unbounded>>().pipe( Effect.flatMap(stateQueue => queryStateTag.pipe( Effect.flatMap(state => interrupt.pipe( Effect.andThen( Effect.addFinalizer(() => Effect.andThen( Ref.set(fiberRef, Option.none()), Queue.shutdown(stateQueue), )).pipe( Effect.andThen(state.set(AsyncData.loading())), Effect.andThen(run(keyValue)), Effect.scoped, Effect.forkDaemon, ) ), Effect.tap(fiber => Ref.set(fiberRef, Option.some(fiber))), Effect.map(fiber => [fiber, Stream.fromQueue(stateQueue)] as const), )), Effect.provide(QueryState.layer( queryStateTag, stateRef, value => Effect.andThen( Queue.offer(stateQueue, value), Ref.set(stateRef, value), ), )), )) ) const setInitialRefreshState = Effect.flatMap(queryStateTag, state => state.update(previous => { if (AsyncData.isSuccess(previous) || AsyncData.isFailure(previous)) return AsyncData.refreshing(previous) if (AsyncData.isRefreshing(previous)) return AsyncData.refreshing(previous.previous) return AsyncData.loading() })) const forkRefresh = Queue.unbounded>>().pipe( Effect.flatMap(stateQueue => interrupt.pipe( Effect.andThen( Effect.addFinalizer(() => Effect.andThen( Ref.set(fiberRef, Option.none()), Queue.shutdown(stateQueue), )).pipe( Effect.andThen(setInitialRefreshState), Effect.andThen(latestKeyValueRef.pipe( Effect.flatMap(identity), Effect.flatMap(run), )), Effect.scoped, Effect.forkDaemon, ) ), Effect.tap(fiber => Ref.set(fiberRef, Option.some(fiber))), Effect.map(fiber => [fiber, Stream.fromQueue(stateQueue)] as const), Effect.provide(QueryState.layer( queryStateTag, stateRef, value => Effect.andThen( Queue.offer(stateQueue, value), Ref.set(stateRef, value), ), )), )) ) return { queryKey: key, latestKeyValueRef, stateRef, fiberRef, interrupt, forkInterrupt, forkFetch, forkRefresh, } }) export interface RunOptions { readonly refreshOnWindowFocus?: boolean } export const run = ( self: QueryRunner, options?: RunOptions, ): Effect.Effect => Effect.gen(function*() { if (typeof window !== "undefined" && (options?.refreshOnWindowFocus ?? true)) yield* Effect.forkScoped( Stream.runForEach(BrowserStream.fromEventListenerWindow("focus"), () => self.forkRefresh) ) yield* Effect.addFinalizer(() => self.interrupt) yield* Stream.runForEach(Stream.changes(self.queryKey), latestKey => self.forkFetch(latestKey)) })