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

assets.ts

120 lines3.7 KB

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