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

assets.ts

239 lines9.0 KB

1import {
2 type AssetCreateUrlInput,
3 type AssetCreateUrlResult,
4 type AssetImageDimensions,
5 AssetResource,
6 EnvironmentId,
7 type ProjectCloneSnapshot,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import { mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
11import { isWindowsAbsolutePath } from "@t3tools/shared/path";
12import {
13 getProjectFaviconResourceKey,
14 isProjectFaviconFallbackUrl,
15} from "@t3tools/shared/projectFavicon";
16import * as Effect from "effect/Effect";
17import * as Option from "effect/Option";
18import * as Result from "effect/Result";
19import * as Schema from "effect/Schema";
20import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
21​
22import * as EnvironmentRegistry from "../connection/registry.ts";
23import * as EnvironmentSupervisor from "../connection/supervisor.ts";
24import { request } from "../rpc/client.ts";
25import type { ProjectFaviconCache, ProjectFaviconTarget } from "../projectFaviconCache.ts";
26import { createEnvironmentQueryAtomFamily } from "./runtime.ts";
27​
28const ASSET_URL_REFRESH_INTERVAL_MS = 30 * 60_000;
29const ASSET_URL_STALE_TIME_MS = 5 * 60_000;
30const ASSET_URL_IDLE_TTL_MS = 60 * 60_000;
31​
32export class InvalidAssetCollectionKeyError extends Schema.TaggedError<InvalidAssetCollectionKeyError>()(
33 "InvalidAssetCollectionKeyError",
34 {
35 key: Schema.String,
36 cause: Schema.Defect(),
37 },
38) {
39 override get message(): string {
40 return `Invalid asset collection atom key: ${JSON.stringify(this.key)}.`;
41 }
43​
44const decodeAssetCollectionKey = Schema.decodeUnknownSync(
45 Schema.Tuple([EnvironmentId, Schema.Array(AssetResource)]),
46);
47​
48export function parseAssetCollectionKey(
49 key: string,
50): readonly [EnvironmentId, ReadonlyArray<AssetResource>] {
51 try {
52 return decodeAssetCollectionKey(JSON.parse(key));
53 } catch (cause) {
54 throw new InvalidAssetCollectionKeyError({ key, cause });
55 }
57​
58export function resolveAssetUrl(httpBaseUrl: string, relativeUrl: string): string | null {
59 try {
60 return new URL(relativeUrl, httpBaseUrl).toString();
61 } catch {
62 return null;
63 }
65​
66export const EMPTY_ASSET_URL_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
67 Atom.withLabel("asset-url:empty"),
68);
69​
70export type AssetUrlState =
71 | { readonly _tag: "Loading" }
72 | { readonly _tag: "Failure" }
73 | {
74 readonly _tag: "Success";
75 readonly url: string;
76 /** The host path the server chose to serve, when it differs from what was asked for. */
77 readonly sourcePath?: string;
78 /** Pixel size from the image header, when the server could read one. */
79 readonly imageDimensions?: AssetImageDimensions;
80 };
81​
82export function assetUrlStateFromResult(
83 result: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
84 httpBaseUrl: string | null,
85): AssetUrlState {
86 if (result._tag === "Failure") return { _tag: "Failure" };
87 if (httpBaseUrl === null || result._tag !== "Success") return { _tag: "Loading" };
88 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
89 if (url === null) return { _tag: "Failure" };
90 return {
91 _tag: "Success",
92 url,
93 ...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
94 ...(result.value.imageDimensions !== undefined
95 ? { imageDimensions: result.value.imageDimensions }
96 : {}),
97 };
99​
100export function createAssetEnvironmentAtoms<R, E>(
101 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
102 localMediaEnvironment?: Atom.Atom<{
103 readonly environmentId: EnvironmentId;
104 readonly httpBaseUrl: string;
105 } | null>,
106) {
107 const execute = Effect.fn("assets.createUrl")(function* (input: AssetCreateUrlInput) {
108 const result = yield* request(WS_METHODS.assetsCreateUrl, input).pipe(Effect.result);
109 if (Result.isSuccess(result)) return result.success;
110 const error = result.failure;
111 const resource = input.resource;
112 const local = localMediaEnvironment
113 ? (yield* AtomRegistry.AtomRegistry).get(localMediaEnvironment)
114 : null;
115 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
116 if (
117 !local ||
118 local.environmentId === supervisor.target.environmentId ||
119 !(
120 error._tag === "AssetWorkspaceAssetNotFoundError" ||
121 error._tag === "AssetWorkspaceAssetInspectionError" ||
122 error._tag === "AssetWorkspaceContextNotFoundError"
123 ) ||
124 resource._tag !== "media-file" ||
125 !(resource.path.startsWith("/") || isWindowsAbsolutePath(resource.path)) ||
126 mediaMimeTypeFromExtension(resource.path.slice(resource.path.lastIndexOf("."))) === null
127 )
128 return yield* error;
129 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
130 const asset = yield* registry.run(
131 local.environmentId,
132 request(WS_METHODS.assetsCreateUrl, input),
133 );
134 // Callers resolve against the thread's server, so preserve the local server's origin.
135 return { ...asset, relativeUrl: new URL(asset.relativeUrl, local.httpBaseUrl).href };
136 });
137 const createUrl = createEnvironmentQueryAtomFamily(runtime, {
138 label: "environment-data:assets:create-url",
139 execute,
140 staleTimeMs: ASSET_URL_STALE_TIME_MS,
141 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
142 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
143 refreshTrigger: ({ input }) =>
144 input.resource._tag === "media-file" ? localMediaEnvironment : undefined,
145 });
146 const createUrlsFamily = Atom.family((key: string) => {
147 const [environmentId, resources] = parseAssetCollectionKey(key);
148 return Atom.make((get) =>
149 resources.map((resource) =>
150 get(
151 createUrl({
152 environmentId,
153 input: { resource },
154 }),
155 ),
156 ),
157 ).pipe(
158 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
159 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
160 );
161 });
162​
163 return {
164 createUrl,
165 createUrls: (target: {
166 readonly environmentId: EnvironmentId;
167 readonly resources: ReadonlyArray<AssetResource>;
168 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
169 };
171​
172/**
173 * Keeps project icons visible while their environment reconnects. Each resource
174 * owns its last resolved URL, including a confirmed missing-icon response.
175 */
176export function createProjectFaviconUrlAtomFamily(input: {
177 readonly imageCache?: ProjectFaviconCache;
178 readonly createUrl: (target: {
179 readonly environmentId: EnvironmentId;
180 readonly input: { readonly resource: AssetResource };
181 }) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>;
182 readonly preparedConnection: (
183 environmentId: EnvironmentId,
184 ) => Atom.Atom<Option.Option<{ readonly httpBaseUrl: string }>>;
185 /** The environment's tracked clones, empty when it reports none. */
186 readonly projectClones?: (
187 environmentId: EnvironmentId,
188 ) => Atom.Atom<ReadonlyArray<ProjectCloneSnapshot>>;
189}) {
190 const decodeKey = Schema.decodeUnknownSync(
191 Schema.Tuple([EnvironmentId, Schema.String, Schema.NullOr(Schema.String)]),
192 );
193 const projectClones = input.projectClones;
194 const family = Atom.family((key: string) => {
195 const [environmentId, cwd, path] = decodeKey(JSON.parse(key));
196 const resource = { _tag: "project-favicon" as const, cwd, ...(path ? { path } : {}) };
197 const query = input.createUrl({ environmentId, input: { resource } });
198 // A cloned project exists before its files do, and the server reports its
199 // icon missing until the clone lands. Ask again whenever the clone's phase
200 // changes: the first list a client sees may already say done.
201 const request = projectClones
202 ? query.pipe(
203 Atom.makeRefreshOnSignal(
204 Atom.make(
205 (get) =>
206 get(projectClones(environmentId)).find((clone) => clone.destinationPath === cwd)
207 ?.phase ?? null,
208 ),
209 ),
210 )
211 : query;
212 const resolvedUrl = Atom.make((get): string | null => {
213 const result = get(request);
214 const connection = get(input.preparedConnection(environmentId));
215 const state = assetUrlStateFromResult(
216 result,
217 Option.isSome(connection) ? connection.value.httpBaseUrl : null,
218 );
219 return state._tag === "Success" ? state.url : Option.getOrNull(get.self<string | null>());
220 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
221 const cache = input.imageCache;
222 if (!cache) return resolvedUrl;
223​
224 const target = { environmentId, cwd, faviconPath: path };
225 const image = Atom.make((get) => {
226 get(request);
227 const url = get(resolvedUrl);
228 return Effect.promise((signal) => cache.resolve(target, url, signal));
229 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
230​
231 return Atom.make((get): string | null => {
232 const result = get(image);
233 if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
234 return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
235 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
236 });
237 return (target: ProjectFaviconTarget) =>
238 family(getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath));