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

assets.ts

177 lines6.2 KB

1import {
2 type AssetCreateUrlResult,
3 type AssetImageDimensions,
4 AssetResource,
5 EnvironmentId,
6 WS_METHODS,
7} from "@t3tools/contracts";
8import {
9 getProjectFaviconResourceKey,
10 isProjectFaviconFallbackUrl,
11} from "@t3tools/shared/projectFavicon";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15import { AsyncResult, Atom } from "effect/unstable/reactivity";
16​
17import type { EnvironmentRegistry } from "../connection/registry.ts";
18import type { ProjectFaviconCache, ProjectFaviconTarget } from "../projectFaviconCache.ts";
19import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
20​
21const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
22const ASSET_URL_STALE_TIME_MS = 5 * 60_000;
23const ASSET_URL_IDLE_TTL_MS = 60 * 60_000;
24​
25export class InvalidAssetCollectionKeyError extends Schema.TaggedErrorClass<InvalidAssetCollectionKeyError>()(
26 "InvalidAssetCollectionKeyError",
27 {
28 key: Schema.String,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Invalid asset collection atom key: ${JSON.stringify(this.key)}.`;
34 }
36​
37const decodeAssetCollectionKey = Schema.decodeUnknownSync(
38 Schema.Tuple([EnvironmentId, Schema.Array(AssetResource)]),
39);
40​
41export function parseAssetCollectionKey(
42 key: string,
43): readonly [EnvironmentId, ReadonlyArray<AssetResource>] {
44 try {
45 return decodeAssetCollectionKey(JSON.parse(key));
46 } catch (cause) {
47 throw new InvalidAssetCollectionKeyError({ key, cause });
48 }
50​
51export function resolveAssetUrl(httpBaseUrl: string, relativeUrl: string): string | null {
52 try {
53 return new URL(relativeUrl, httpBaseUrl).toString();
54 } catch {
55 return null;
56 }
58​
59export const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
60 Atom.withLabel("asset-url:empty"),
61);
62​
63export type AssetUrlState =
64 | { readonly _tag: "Loading" }
65 | { readonly _tag: "Failure" }
66 | {
67 readonly _tag: "Success";
68 readonly url: string;
69 /** The host path the server chose to serve, when it differs from what was asked for. */
70 readonly sourcePath?: string;
71 /** Pixel size from the image header, when the server could read one. */
72 readonly imageDimensions?: AssetImageDimensions;
73 };
74​
75export function assetUrlStateFromResult(
76 result: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
77 httpBaseUrl: string | null,
78): AssetUrlState {
79 if (result._tag === "Failure") return { _tag: "Failure" };
80 if (httpBaseUrl === null || result._tag !== "Success") return { _tag: "Loading" };
81 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
82 if (url === null) return { _tag: "Failure" };
83 return {
84 _tag: "Success",
85 url,
86 ...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
87 ...(result.value.imageDimensions !== undefined
88 ? { imageDimensions: result.value.imageDimensions }
89 : {}),
90 };
92​
93export function createAssetEnvironmentAtoms<R, E>(
94 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
95) {
96 const createUrl = createEnvironmentRpcQueryAtomFamily(runtime, {
97 label: "environment-data:assets:create-url",
98 tag: WS_METHODS.assetsCreateUrl,
99 staleTimeMs: ASSET_URL_STALE_TIME_MS,
100 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
101 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
102 });
103 const createUrlsFamily = Atom.family((key: string) => {
104 const [environmentId, resources] = parseAssetCollectionKey(key);
105 return Atom.make((get) =>
106 resources.map((resource) =>
107 get(
108 createUrl({
109 environmentId,
110 input: { resource },
111 }),
112 ),
113 ),
114 ).pipe(
115 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
116 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
117 );
118 });
119​
120 return {
121 createUrl,
122 createUrls: (target: {
123 readonly environmentId: EnvironmentId;
124 readonly resources: ReadonlyArray<AssetResource>;
125 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
126 };
128​
129/**
130 * Keeps project icons visible while their environment reconnects. Each resource
131 * owns its last resolved URL, including a confirmed missing-icon response.
132 */
133export function createProjectFaviconUrlAtomFamily(input: {
134 readonly imageCache?: ProjectFaviconCache;
135 readonly createUrl: (target: {
136 readonly environmentId: EnvironmentId;
137 readonly input: { readonly resource: AssetResource };
138 }) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>;
139 readonly preparedConnection: (
140 environmentId: EnvironmentId,
141 ) => Atom.Atom<Option.Option<{ readonly httpBaseUrl: string }>>;
142}) {
143 const decodeKey = Schema.decodeUnknownSync(
144 Schema.Tuple([EnvironmentId, Schema.String, Schema.NullOr(Schema.String)]),
145 );
146 const family = Atom.family((key: string) => {
147 const [environmentId, cwd, path] = decodeKey(JSON.parse(key));
148 const resource = { _tag: "project-favicon" as const, cwd, ...(path ? { path } : {}) };
149 const request = input.createUrl({ environmentId, input: { resource } });
150 const resolvedUrl = Atom.make((get): string | null => {
151 const result = get(request);
152 const connection = get(input.preparedConnection(environmentId));
153 const state = assetUrlStateFromResult(
154 result,
155 Option.isSome(connection) ? connection.value.httpBaseUrl : null,
156 );
157 return state._tag === "Success" ? state.url : Option.getOrNull(get.self<string | null>());
158 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
159 const cache = input.imageCache;
160 if (!cache) return resolvedUrl;
161​
162 const target = { environmentId, cwd, faviconPath: path };
163 const image = Atom.make((get) => {
164 get(request);
165 const url = get(resolvedUrl);
166 return Effect.promise((signal) => cache.resolve(target, url, signal));
167 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
168​
169 return Atom.make((get): string | null => {
170 const result = get(image);
171 if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
172 return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
173 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
174 });
175 return (target: ProjectFaviconTarget) =>
176 family(getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath));