Open History to see the last commit
1import { AssetResource, EnvironmentId, WS_METHODS } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { Atom } from "effect/unstable/reactivity";
4
5import type { EnvironmentRegistry } from "../connection/registry.ts";
6import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
7
8const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
9const ASSET_URL_STALE_TIME_MS = 5 * 60_000;
10const ASSET_URL_IDLE_TTL_MS = 60 * 60_000;
11
12export class InvalidAssetCollectionKeyError extends Schema.TaggedErrorClass<InvalidAssetCollectionKeyError>()(
13 "InvalidAssetCollectionKeyError",
14 {
15 key: Schema.String,
16 cause: Schema.Defect(),
17 },
18) {
19 override get message(): string {
20 return `Invalid asset collection atom key: ${JSON.stringify(this.key)}.`;
21 }
22}
23
24const decodeAssetCollectionKey = Schema.decodeUnknownSync(
25 Schema.Tuple([EnvironmentId, Schema.Array(AssetResource)]),
26);
27
28export function parseAssetCollectionKey(
29 key: string,
30): readonly [EnvironmentId, ReadonlyArray<AssetResource>] {
31 try {
32 return decodeAssetCollectionKey(JSON.parse(key));
33 } catch (cause) {
34 throw new InvalidAssetCollectionKeyError({ key, cause });
35 }
36}
37
38export function resolveAssetUrl(httpBaseUrl: string, relativeUrl: string): string | null {
39 try {
40 return new URL(relativeUrl, httpBaseUrl).toString();
41 } catch {
42 return null;
43 }
44}
45
46export function createAssetEnvironmentAtoms<R, E>(
47 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
48) {
49 const createUrl = createEnvironmentRpcQueryAtomFamily(runtime, {
50 label: "environment-data:assets:create-url",
51 tag: WS_METHODS.assetsCreateUrl,
52 staleTimeMs: ASSET_URL_STALE_TIME_MS,
53 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
54 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
55 });
56 const createUrlsFamily = Atom.family((key: string) => {
57 const [environmentId, resources] = parseAssetCollectionKey(key);
58 return Atom.make((get) =>
59 resources.map((resource) =>
60 get(
61 createUrl({
62 environmentId,
63 input: { resource },
64 }),
65 ),
66 ),
67 ).pipe(
68 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
69 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
70 );
71 });
72
73 return {
74 createUrl,
75 createUrls: (target: {
76 readonly environmentId: EnvironmentId;
77 readonly resources: ReadonlyArray<AssetResource>;
78 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
79 };
80}