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