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

assets.ts

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