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

assets.ts

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