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

assets.ts

280 lines10.4 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/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 | {
73 readonly _tag: "Failure";
74 /** Set when the session lacks `filesystem:read`; the file itself may be fine. */
75 readonly reason?: "missing-file-access";
76 }
77 | {
78 readonly _tag: "Success";
79 readonly url: string;
80 /** When the signed URL stops working, in epoch milliseconds. */
81 readonly expiresAt: number;
82 /** The host path the server chose to serve, when it differs from what was asked for. */
83 readonly sourcePath?: string;
84 /** Pixel size from the image header, when the server could read one. */
85 readonly imageDimensions?: AssetImageDimensions;
86 };
87​
88/** Shown in place of a host file the session lacks `filesystem:read` for. */
89export const MISSING_FILE_ACCESS_MESSAGE =
90 "This connection cannot read host files. Pair again with a new link to view it.";
91​
92/**
93 * The state for a host file this session cannot read yet, or null when the client
94 * should ask the host. The host requires `filesystem:read` for these resources, so
95 * clients skip the request. A connected session without the scope gets its own
96 * reason, so the UI can say to pair again instead of implying the file is gone.
97 */
98export function blockedAssetUrlState(
99 resource: AssetResource | null,
100 fileAccess: {
101 readonly canReadFiles: boolean;
102 readonly isPending: boolean;
103 readonly error: string | null;
104 },
105): AssetUrlState | null {
106 if (
107 resource === null ||
108 fileAccess.canReadFiles ||
109 (resource._tag !== "workspace-file" &&
110 resource._tag !== "media-file" &&
111 resource._tag !== "draft-workspace-file")
112 ) {
113 return null;
114 }
115 if (fileAccess.isPending) return { _tag: "Loading" };
116 // An error means the session check itself failed, such as when offline.
117 return fileAccess.error === null
118 ? { _tag: "Failure", reason: "missing-file-access" }
119 : { _tag: "Failure" };
121​
122export function assetUrlStateFromResult(
123 result: AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>,
124 httpBaseUrl: string | null,
125): AssetUrlState {
126 if (result._tag === "Failure") return { _tag: "Failure" };
127 if (httpBaseUrl === null || result._tag !== "Success") return { _tag: "Loading" };
128 const url = resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
129 if (url === null) return { _tag: "Failure" };
130 return {
131 _tag: "Success",
132 url,
133 expiresAt: result.value.expiresAt,
134 ...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
135 ...(result.value.imageDimensions !== undefined
136 ? { imageDimensions: result.value.imageDimensions }
137 : {}),
138 };
140​
141export function createAssetEnvironmentAtoms<R, E>(
142 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
143 localMediaEnvironment?: Atom.Atom<{
144 readonly environmentId: EnvironmentId;
145 readonly httpBaseUrl: string;
146 } | null>,
147) {
148 const execute = Effect.fn("assets.createUrl")(function* (input: AssetCreateUrlInput) {
149 const result = yield* request(WS_METHODS.assetsCreateUrl, input).pipe(Effect.result);
150 if (Result.isSuccess(result)) return result.success;
151 const error = result.failure;
152 const resource = input.resource;
153 const local = localMediaEnvironment
154 ? (yield* AtomRegistry.AtomRegistry).get(localMediaEnvironment)
155 : null;
156 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
157 if (
158 !local ||
159 local.environmentId === supervisor.target.environmentId ||
160 !(
161 error._tag === "AssetWorkspaceAssetNotFoundError" ||
162 error._tag === "AssetWorkspaceAssetInspectionError" ||
163 error._tag === "AssetWorkspaceContextNotFoundError"
164 ) ||
165 resource._tag !== "media-file" ||
166 !(resource.path.startsWith("/") || isWindowsAbsolutePath(resource.path)) ||
167 mediaMimeTypeFromExtension(resource.path.slice(resource.path.lastIndexOf("."))) === null
168 )
169 return yield* error;
170 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
171 const asset = yield* registry.run(
172 local.environmentId,
173 request(WS_METHODS.assetsCreateUrl, input),
174 );
175 // Callers resolve against the thread's server, so preserve the local server's origin.
176 return { ...asset, relativeUrl: new URL(asset.relativeUrl, local.httpBaseUrl).href };
177 });
178 const createUrl = createEnvironmentQueryAtomFamily(runtime, {
179 label: "environment-data:assets:create-url",
180 execute,
181 staleTimeMs: ASSET_URL_STALE_TIME_MS,
182 idleTtlMs: ASSET_URL_IDLE_TTL_MS,
183 refreshIntervalMs: ASSET_URL_REFRESH_INTERVAL_MS,
184 refreshTrigger: ({ input }) =>
185 input.resource._tag === "media-file" ? localMediaEnvironment : undefined,
186 });
187 const createUrlsFamily = Atom.family((key: string) => {
188 const [environmentId, resources] = parseAssetCollectionKey(key);
189 return Atom.make((get) =>
190 resources.map((resource) =>
191 get(
192 createUrl({
193 environmentId,
194 input: { resource },
195 }),
196 ),
197 ),
198 ).pipe(
199 Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS),
200 Atom.withLabel(`environment-data:assets:create-urls:${key}`),
201 );
202 });
203​
204 return {
205 createUrl,
206 createUrls: (target: {
207 readonly environmentId: EnvironmentId;
208 readonly resources: ReadonlyArray<AssetResource>;
209 }) => createUrlsFamily(JSON.stringify([target.environmentId, target.resources])),
210 };
212​
213/**
214 * Keeps project icons visible while their environment reconnects. Each resource
215 * owns its last resolved URL, including a confirmed missing-icon response.
216 */
217export function createProjectFaviconUrlAtomFamily(input: {
218 readonly imageCache?: ProjectFaviconCache;
219 readonly createUrl: (target: {
220 readonly environmentId: EnvironmentId;
221 readonly input: { readonly resource: AssetResource };
222 }) => Atom.Atom<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>;
223 readonly preparedConnection: (
224 environmentId: EnvironmentId,
225 ) => Atom.Atom<Option.Option<{ readonly httpBaseUrl: string }>>;
226 /** The environment's tracked clones, empty when it reports none. */
227 readonly projectClones?: (
228 environmentId: EnvironmentId,
229 ) => Atom.Atom<ReadonlyArray<ProjectCloneSnapshot>>;
230}) {
231 const decodeKey = Schema.decodeUnknownSync(
232 Schema.Tuple([EnvironmentId, Schema.String, Schema.NullOr(Schema.String)]),
233 );
234 const projectClones = input.projectClones;
235 const family = Atom.family((key: string) => {
236 const [environmentId, cwd, path] = decodeKey(JSON.parse(key));
237 const resource = { _tag: "project-favicon" as const, cwd, ...(path ? { path } : {}) };
238 const query = input.createUrl({ environmentId, input: { resource } });
239 // A cloned project exists before its files do, and the server reports its
240 // icon missing until the clone lands. Ask again whenever the clone's phase
241 // changes: the first list a client sees may already say done.
242 const request = projectClones
243 ? query.pipe(
244 Atom.makeRefreshOnSignal(
245 Atom.make(
246 (get) =>
247 get(projectClones(environmentId)).find((clone) => clone.destinationPath === cwd)
248 ?.phase ?? null,
249 ),
250 ),
251 )
252 : query;
253 const resolvedUrl = Atom.make((get): string | null => {
254 const result = get(request);
255 const connection = get(input.preparedConnection(environmentId));
256 const state = assetUrlStateFromResult(
257 result,
258 Option.isSome(connection) ? connection.value.httpBaseUrl : null,
259 );
260 return state._tag === "Success" ? state.url : Option.getOrNull(get.self<string | null>());
261 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
262 const cache = input.imageCache;
263 if (!cache) return resolvedUrl;
264​
265 const target = { environmentId, cwd, faviconPath: path };
266 const image = Atom.make((get) => {
267 get(request);
268 const url = get(resolvedUrl);
269 return Effect.promise((signal) => cache.resolve(target, url, signal));
270 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
271​
272 return Atom.make((get): string | null => {
273 const result = get(image);
274 if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
275 return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
276 }).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
277 });
278 return (target: ProjectFaviconTarget) =>
279 family(getProjectFaviconResourceKey(target.environmentId, target.cwd, target.faviconPath));