Open History to see the last commit
1import { useMessages } from "gt-react";
2import { useAtomValue } from "@effect/atom-react";
3import {
4 type AssetUrlState,
5 assetUrlStateFromResult,
6 blockedAssetUrlState,
7 EMPTY_ASSET_URL_ATOM,
8} from "@t3tools/client-runtime/state/assets";
9import { AssetResource, type AssetCreateUrlResult, EnvironmentId } from "@t3tools/contracts";
10import * as Schema from "effect/Schema";
11import { AsyncResult, Atom } from "effect/reactivity";
12
13import { assetEnvironment } from "~/state/assets";
14import { useFilesystemReadAccess } from "~/state/filesystem";
15import { usePreparedConnection } from "~/state/session";
16
17type AssetUrlTarget = {
18 readonly environmentId: EnvironmentId;
19 readonly input: { readonly resource: AssetResource };
20};
21
22const decodeAssetUrlKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, AssetResource]));
23
24/**
25 * Asset URLs for documents that cannot report a failed load, such as frames. A
26 * cached URL with `minLifeMs` left is reused; one closer to expiry is re-minted.
27 * A node mints at most once, so a skewed client clock cannot mint on every update.
28 */
29export function makeLongLivedAssetUrlFamily(
30 createUrl: (
31 target: AssetUrlTarget,
32 ) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>,
33 options: { readonly minLifeMs: number; readonly now?: () => number },
34) {
35 const now = options.now ?? Date.now;
36 const family = Atom.family((key: string) => {
37 const [environmentId, resource] = decodeAssetUrlKey(JSON.parse(key));
38 const query = createUrl({ environmentId, input: { resource } });
39 return Atom.transform(
40 query,
41 (get) => {
42 let minting = false;
43 const settle = (
44 value: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
45 ): AsyncResult.AsyncResult<AssetCreateUrlResult, unknown> => {
46 if (value._tag !== "Success") return value;
47 const lasts = value.value.expiresAt - now() > options.minLifeMs;
48 // An expiring URL must not be handed out while its successor mints,
49 // whichever reader started the mint.
50 if (value.waiting) return lasts ? value : AsyncResult.initial(true);
51 if (minting || lasts) return value;
52 minting = true;
53 get.refresh(query);
54 return AsyncResult.initial(true);
55 };
56 get.subscribe(query, (value) => get.setSelf(settle(value)));
57 return settle(get.once(query));
58 },
59 { initialValueTarget: query },
60 // Each mount gets its own node, so a later mount may mint again.
61 ).pipe(Atom.setIdleTTL(0));
62 });
63 return (target: AssetUrlTarget) =>
64 family(JSON.stringify([target.environmentId, target.input.resource]));
65}
66
67const longLivedAssetUrl = makeLongLivedAssetUrlFamily(assetEnvironment.createUrl, {
68 minLifeMs: 5 * 60_000,
69});
70
71/** Pass a null environment once the URL is adopted, so later mints do not re-render. */
72export function useLongLivedAssetUrl(
73 environmentId: EnvironmentId | null,
74 resource: AssetResource,
75): AssetUrlState {
76 const blocked = blockedAssetUrlState(
77 resource,
78 useFilesystemReadAccess(environmentId, useMessages()),
79 );
80 const preparedConnection = usePreparedConnection(environmentId);
81 const result = useAtomValue(
82 blocked !== null || environmentId === null
83 ? EMPTY_ASSET_URL_ATOM
84 : longLivedAssetUrl({ environmentId, input: { resource } }),
85 );
86 if (blocked !== null) return blocked;
87 return assetUrlStateFromResult(
88 result,
89 preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null,
90 );
91}