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