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

MediaFile.ts

144 lines5.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - FileSystem does not expose no-follow
2// or non-blocking open flags, and the response must keep the validated descriptor.
3import * as NodeFS from "node:fs";
4import * as NodeFSP from "node:fs/promises";
5​
6import * as NodeStream from "@effect/platform-node/NodeStream";
7import * as Effect from "effect/Effect";
8import * as Schema from "effect/Schema";
9​
10class MediaFileOpenError extends Schema.TaggedError<MediaFileOpenError>()("MediaFileOpenError", {
11 path: Schema.String,
12 cause: Schema.Defect(),
13}) {
14 override get message(): string {
15 return `Failed to open media file '${this.path}'.`;
16 }
18​
19class MediaFileReadError extends Schema.TaggedError<MediaFileReadError>()("MediaFileReadError", {
20 path: Schema.String,
21 cause: Schema.Defect(),
22}) {
23 override get message(): string {
24 return `Failed to read media file '${this.path}'.`;
25 }
27​
28class MediaFileStatError extends Schema.TaggedError<MediaFileStatError>()("MediaFileStatError", {
29 path: Schema.String,
30 cause: Schema.Defect(),
31}) {
32 override get message(): string {
33 return `Failed to read metadata for media file '${this.path}'.`;
34 }
36​
37export interface OpenMediaFile {
38 readonly handle: NodeFSP.FileHandle;
39 readonly info: NodeFS.BigIntStats;
41​
42const realpathLikeFileSystem = (filePath: string) =>
43 new Promise<string>((resolve, reject) => {
44 NodeFS.realpath(filePath, (error, resolved) => (error ? reject(error) : resolve(resolved)));
45 });
46​
47/** Null when the path cannot be resolved. */
48export const realPathWithoutNativeResolver = (filePath: string) =>
49 Effect.promise(() => realpathLikeFileSystem(filePath).catch(() => null));
50​
51export const openMediaFile = Effect.fn("openMediaFile")(function* (
52 filePath: string,
53 identity?: { readonly device: string; readonly inode: string },
54) {
55 return yield* Effect.acquireRelease(
56 Effect.tryPromise({
57 try: async () => {
58 const before = await NodeFSP.lstat(filePath, { bigint: true });
59 if (!before.isFile() || before.ino === 0n) return null;
60 if (
61 identity &&
62 (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
63 ) {
64 return null;
65 }
66​
67 // Windows lacks these flags; the descriptor/path identity checks still apply.
68 const handle = await NodeFSP.open(
69 filePath,
70 NodeFS.constants.O_RDONLY |
71 (NodeFS.constants.O_NOFOLLOW ?? 0) |
72 (NodeFS.constants.O_NONBLOCK ?? 0),
73 );
74 let accepted = false;
75 try {
76 const info = await handle.stat({ bigint: true });
77 if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
78 if (
79 identity &&
80 (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
81 ) {
82 return null;
83 }
84 // Match FileSystem.realPath's JS behavior; native realpath expands Windows 8.3 names too.
85 if ((await realpathLikeFileSystem(filePath)) !== filePath) return null;
86 const after = await NodeFSP.lstat(filePath, { bigint: true });
87 if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
88 accepted = true;
89 return { handle, info } satisfies OpenMediaFile;
90 } finally {
91 if (!accepted) await handle.close();
92 }
93 },
94 catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
95 }),
96 (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
97 );
98});
99​
100/** Identity, size and nanosecond times, so it moves whenever the file is edited or replaced. */
101export const mediaFileRevision = (info: NodeFS.BigIntStats) =>
102 `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
103​
104/** Follows links, as serving the path does. Null when nothing can be read there. */
105export const readFileRevision = (filePath: string) =>
106 Effect.promise(() =>
107 NodeFSP.stat(filePath, { bigint: true }).then(mediaFileRevision, () => null),
108 );
109​
110export const readMediaFileHeader = (filePath: string, file: OpenMediaFile, byteCount: number) =>
111 Effect.tryPromise({
112 try: async () => {
113 const buffer = new Uint8Array(byteCount);
114 const { bytesRead } = await file.handle.read(buffer, 0, byteCount, 0);
115 return buffer.subarray(0, bytesRead);
116 },
117 catch: (cause) => new MediaFileReadError({ path: filePath, cause }),
118 });
119​
120export const statMediaFile = Effect.fn("statMediaFile")(function* (
121 filePath: string,
122 file: OpenMediaFile,
123) {
124 return yield* Effect.tryPromise({
125 try: () => file.handle.stat({ bigint: true }),
126 catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
127 });
128});
129​
130export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
131 const start = Number(offset);
132 const end = Number(offset + bytesToRead - 1n);
133 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
134 return null;
135 }
136 return NodeStream.fromReadable<Uint8Array>({
137 evaluate: () =>
138 file.handle.createReadStream({
139 autoClose: false,
140 start,
141 end,
142 }),
143 });
144};