Open History to see the last commit
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/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 }
42}
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 }
56}
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 }
64}
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 /** When the signed URL stops working, in epoch milliseconds. */
77 readonly expiresAt: number;
78 /** The host path the server chose to serve, when it differs from what was asked for. */
79 readonly sourcePath?: string;
80 /** Pixel size from the image header, when the server could read one. */
81 readonly imageDimensions?: AssetImageDimensions;
82 };
83
84export function assetUrlStateFromResult(
85 result: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
86 httpBaseUrl: string | null,
87): AssetUrlState {
88 if (result._tag === "Failure") return { _tag: "Failure" };
89 if (httpBaseUrl === null || result._tag !== "Success") return { _tag: "Loading" };
90 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
91 if (url === null) return { _tag: "Failure" };
92 return {
93 _tag: "Success",
94 url,
95 expiresAt: result.value.expiresAt,
96 ...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
97 ...(result.value.imageDimensions !== undefined
98 ? { imageDimensions: result.value.imageDimensions }
99 : {}),
100 };
101}
102
103export function createAssetEnvironmentAtoms<R, E>(
104 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
105 localMediaEnvironment?: Atom.Atom<{
106 readonly environmentId: EnvironmentId;
107 readonly httpBaseUrl: string;
108 } | null>,
109) {
110 const execute = Effect.fn("assets.createUrl")(function* (input: AssetCreateUrlInput) {
111 const result = yield* request(WS_METHODS.assetsCreateUrl, input).pipe(Effect.result);
112 if (Result.isSuccess(result)) return result.success;
113 const error = result.failure;
114 const resource = input.resource;
115 const local = localMediaEnvironment
116 ? (yield* AtomRegistry.AtomRegistry).get(localMediaEnvironment)
117 : null;
118 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
119 if (
120 !local ||
121 local.environmentId === supervisor.target.environmentId ||
122 !(
123 error._tag === "AssetWorkspaceAssetNotFoundError" ||
124 error._tag === "AssetWorkspaceAssetInspectionError" ||
125 error._tag === "AssetWorkspaceContextNotFoundError"
126 ) ||
127 resource._tag !== "media-file" ||
128 !(resource.path.startsWith("/") || isWindowsAbsolutePath(resource.path)) ||
129 mediaMimeTypeFromExtension(resource.path.slice(resource.path.lastIndexOf("."))) === null
130 )
131 return yield* error;
132 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
133 const asset = yield* registry.run(
134 local.environmentId,
135 request(WS_METHODS.assetsCreateUrl, input),
136 );
137 // Callers resolve against the thread's server, so preserve the local server's origin.
138 return { ...asset, relativeUrl: new URL(asset.relativeUrl, local.httpBaseUrl).href };
139 });
140 const createUrl = createEnvironmentQueryAtomFamily(runtime, {
141 label: "environment-data:assets:create-url",
142 execute,
143 staleTimeMs: ASSET_URL_STALE_TIME_MS,
144 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
145 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
146 refreshTrigger: ({ input }) =>
147 input.resource._tag === "media-file" ? localMediaEnvironment : undefined,
148 });
149 const createUrlsFamily = Atom.family((key: string) => {
150 const [environmentId, resources] = parseAssetCollectionKey(key);
151 return Atom.make((get) =>
152 resources.map((resource) =>
153 get(
154 createUrl({
155 environmentId,
156 input: { resource },
157 }),
158 ),
159 ),
160 ).pipe(
161 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
162 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
163 );
164 });
165
166 return {
167 createUrl,
168 createUrls: (target: {
169 readonly environmentId: EnvironmentId;
170 readonly resources: ReadonlyArray<AssetResource>;
171 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
172 };
173}
174
175/**
176 * Keeps project icons visible while their environment reconnects. Each resource
177 * owns its last resolved URL, including a confirmed missing-icon response.
178 */
179export function createProjectFaviconUrlAtomFamily(input: {
180 readonly imageCache?: ProjectFaviconCache;
181 readonly createUrl: (target: {
182 readonly environmentId: EnvironmentId;
183 readonly input: { readonly resource: AssetResource };
184 }) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>;
185 readonly preparedConnection: (
186 environmentId: EnvironmentId,
187 ) => Atom.Atom<Option.Option<{ readonly httpBaseUrl: string }>>;
188 /** The environment's tracked clones, empty when it reports none. */
189 readonly projectClones?: (
190 environmentId: EnvironmentId,
191 ) => Atom.Atom<ReadonlyArray<ProjectCloneSnapshot>>;
192}) {
193 const decodeKey = Schema.decodeUnknownSync(
194 Schema.Tuple([EnvironmentId, Schema.String, Schema.NullOr(Schema.String)]),
195 );
196 const projectClones = input.projectClones;
197 const family = Atom.family((key: string) => {
198 const [environmentId, cwd, path] = decodeKey(JSON.parse(key));
199 const resource = { _tag: "project-favicon" as const, cwd, ...(path ? { path } : {}) };
200 const query = input.createUrl({ environmentId, input: { resource } });
201 // A cloned project exists before its files do, and the server reports its
202 // icon missing until the clone lands. Ask again whenever the clone's phase
203 // changes: the first list a client sees may already say done.
204 const request = projectClones
205 ? query.pipe(
206 Atom.makeRefreshOnSignal(
207 Atom.make(
208 (get) =>
209 get(projectClones(environmentId)).find((clone) => clone.destinationPath === cwd)
210 ?.phase ?? null,
211 ),
212 ),
213 )
214 : query;
215 const resolvedUrl = Atom.make((get): string | null => {
216 const result = get(request);
217 const connection = get(input.preparedConnection(environmentId));
218 const state = assetUrlStateFromResult(
219 result,
220 Option.isSome(connection) ? connection.value.httpBaseUrl : null,
221 );
222 return state._tag === "Success" ? state.url : Option.getOrNull(get.self<string | null>());
223 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
224 const cache = input.imageCache;
225 if (!cache) return resolvedUrl;
226
227 const target = { environmentId, cwd, faviconPath: path };
228 const image = Atom.make((get) => {
229 get(request);
230 const url = get(resolvedUrl);
231 return Effect.promise((signal) => cache.resolve(target, url, signal));
232 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
233
234 return Atom.make((get): string | null => {
235 const result = get(image);
236 if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
237 return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
238 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
239 });
240 return (target: ProjectFaviconTarget) =>
241 family(getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath));
242}