Open History to see the last commit
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.TaggedErrorClass<MediaFileOpenError>()(
11 "MediaFileOpenError",
12 {
13 path: Schema.String,
14 cause: Schema.Defect(),
15 },
16) {
17 override get message(): string {
18 return `Failed to open media file '${this.path}'.`;
19 }
20}
21
22class MediaFileReadError extends Schema.TaggedErrorClass<MediaFileReadError>()(
23 "MediaFileReadError",
24 {
25 path: Schema.String,
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Failed to read media file '${this.path}'.`;
31 }
32}
33
34class MediaFileStatError extends Schema.TaggedErrorClass<MediaFileStatError>()(
35 "MediaFileStatError",
36 {
37 path: Schema.String,
38 cause: Schema.Defect(),
39 },
40) {
41 override get message(): string {
42 return `Failed to read metadata for media file '${this.path}'.`;
43 }
44}
45
46/** Holds the file identity and descriptor for one HTTP request, never a copy of its bytes. */
47export interface OpenMediaFile {
48 readonly handle: NodeFSP.FileHandle;
49 readonly info: NodeFS.BigIntStats;
50}
51
52const realpathLikeFileSystem = (filePath: string) =>
53 new Promise<string>((resolve, reject) => {
54 NodeFS.realpath(filePath, (error, resolved) => (error ? reject(error) : resolve(resolved)));
55 });
56
57/** Opens a canonical media path once. Replacements cannot change the response's source. */
58export const openMediaFile = Effect.fn("openMediaFile")(function* (
59 filePath: string,
60 identity?: { readonly device: string; readonly inode: string },
61) {
62 return yield* Effect.acquireRelease(
63 Effect.tryPromise({
64 try: async () => {
65 const before = await NodeFSP.lstat(filePath, { bigint: true });
66 if (!before.isFile() || before.ino === 0n) return null;
67 if (
68 identity &&
69 (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
70 ) {
71 return null;
72 }
73
74 // Windows lacks these flags; the descriptor/path identity checks still apply.
75 const handle = await NodeFSP.open(
76 filePath,
77 NodeFS.constants.O_RDONLY |
78 (NodeFS.constants.O_NOFOLLOW ?? 0) |
79 (NodeFS.constants.O_NONBLOCK ?? 0),
80 );
81 let accepted = false;
82 try {
83 const info = await handle.stat({ bigint: true });
84 if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
85 if (
86 identity &&
87 (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
88 ) {
89 return null;
90 }
91 // Callers canonicalise with Effect's FileSystem.realPath, which is
92 // Node's JS realpath. fs/promises.realpath is the native binding and
93 // on Windows also expands 8.3 short names, so a path that is already
94 // canonical by the caller's rules would still look swapped here.
95 if ((await realpathLikeFileSystem(filePath)) !== filePath) return null;
96 const after = await NodeFSP.lstat(filePath, { bigint: true });
97 if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
98 accepted = true;
99 return { handle, info } satisfies OpenMediaFile;
100 } finally {
101 if (!accepted) await handle.close();
102 }
103 },
104 catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
105 }),
106 (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
107 );
108});
109
110/** Reads the leading bytes of an already-validated media file, never past the end. */
111export const readMediaFileHeader = (filePath: string, file: OpenMediaFile, byteCount: number) =>
112 Effect.tryPromise({
113 try: async () => {
114 const buffer = new Uint8Array(byteCount);
115 const { bytesRead } = await file.handle.read(buffer, 0, byteCount, 0);
116 return buffer.subarray(0, bytesRead);
117 },
118 catch: (cause) => new MediaFileReadError({ path: filePath, cause }),
119 });
120
121export const statMediaFile = Effect.fn("statMediaFile")(function* (
122 filePath: string,
123 file: OpenMediaFile,
124) {
125 return yield* Effect.tryPromise({
126 try: () => file.handle.stat({ bigint: true }),
127 catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
128 });
129});
130
131export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
132 const start = Number(offset);
133 const end = Number(offset + bytesToRead - 1n);
134 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
135 return null;
136 }
137 return NodeStream.fromReadable<Uint8Array>({
138 evaluate: () =>
139 file.handle.createReadStream({
140 autoClose: false,
141 start,
142 end,
143 }),
144 });
145};