Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assets.ts

114 lines3.4 KB

1import {
2 type AssetCreateUrlResult,
3 AssetResource,
4 EnvironmentId,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8import { AsyncResult, Atom } from "effect/unstable/reactivity";
9​
10import type { EnvironmentRegistry } from "../connection/registry.ts";
11import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
12​
13const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
14const ASSET_URL_STALE_TIME_MS = 5 * 60_000;
15const ASSET_URL_IDLE_TTL_MS = 60 * 60_000;
16​
17export class InvalidAssetCollectionKeyError extends Schema.TaggedErrorClass<InvalidAssetCollectionKeyError>()(
18 "InvalidAssetCollectionKeyError",
19 {
20 key: Schema.String,
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Invalid asset collection atom key: ${JSON.stringify(this.key)}.`;
26 }
28​
29const decodeAssetCollectionKey = Schema.decodeUnknownSync(
30 Schema.Tuple([EnvironmentId, Schema.Array(AssetResource)]),
31);
32​
33export function parseAssetCollectionKey(
34 key: string,
35): readonly [EnvironmentId, ReadonlyArray<AssetResource>] {
36 try {
37 return decodeAssetCollectionKey(JSON.parse(key));
38 } catch (cause) {
39 throw new InvalidAssetCollectionKeyError({ key, cause });
40 }
42​
43export function resolveAssetUrl(httpBaseUrl: string, relativeUrl: string): string | null {
44 try {
45 return new URL(relativeUrl, httpBaseUrl).toString();
46 } catch {
47 return null;
48 }
50​
51export const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
52 Atom.withLabel("asset-url:empty"),
53);
54​
55export type AssetUrlState =
56 | { readonly _tag: "Loading" }
57 | { readonly _tag: "Failure" }
58 | {
59 readonly _tag: "Success";
60 readonly url: string;
61 /** The host path the server chose to serve, when it differs from what was asked for. */
62 readonly sourcePath?: string;
63 };
64​
65export function assetUrlStateFromResult(
66 result: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
67 httpBaseUrl: string | null,
68): AssetUrlState {
69 if (result._tag === "Failure") return { _tag: "Failure" };
70 if (httpBaseUrl === null || result._tag !== "Success") return { _tag: "Loading" };
71 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
72 if (url === null) return { _tag: "Failure" };
73 return {
74 _tag: "Success",
75 url,
76 ...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
77 };
79​
80export function createAssetEnvironmentAtoms<R, E>(
81 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
82) {
83 const createUrl = createEnvironmentRpcQueryAtomFamily(runtime, {
84 label: "environment-data:assets:create-url",
85 tag: WS_METHODS.assetsCreateUrl,
86 staleTimeMs: ASSET_URL_STALE_TIME_MS,
87 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
88 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
89 });
90 const createUrlsFamily = Atom.family((key: string) => {
91 const [environmentId, resources] = parseAssetCollectionKey(key);
92 return Atom.make((get) =>
93 resources.map((resource) =>
94 get(
95 createUrl({
96 environmentId,
97 input: { resource },
98 }),
99 ),
100 ),
101 ).pipe(
102 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
103 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
104 );
105 });
106​
107 return {
108 createUrl,
109 createUrls: (target: {
110 readonly environmentId: EnvironmentId;
111 readonly resources: ReadonlyArray<AssetResource>;
112 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
113 };