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