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 MediaFileStatError extends Schema.TaggedErrorClass<MediaFileStatError>()(
23 "MediaFileStatError",
24 {
25 path: Schema.String,
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Failed to read metadata for media file '${this.path}'.`;
31 }
32}
33
34/** Holds the file identity and descriptor for one HTTP request, never a copy of its bytes. */
35export interface OpenMediaFile {
36 readonly handle: NodeFSP.FileHandle;
37 readonly info: NodeFS.BigIntStats;
38}
39
40/** Opens a canonical media path once. Replacements cannot change the response's source. */
41export const openMediaFile = Effect.fn("openMediaFile")(function* (
42 filePath: string,
43 identity?: { readonly device: string; readonly inode: string },
44) {
45 return yield* Effect.acquireRelease(
46 Effect.tryPromise({
47 try: async () => {
48 const before = await NodeFSP.lstat(filePath, { bigint: true });
49 if (!before.isFile() || before.ino === 0n) return null;
50 if (
51 identity &&
52 (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
53 ) {
54 return null;
55 }
56
57 // Windows lacks these flags; the descriptor/path identity checks still apply.
58 const handle = await NodeFSP.open(
59 filePath,
60 NodeFS.constants.O_RDONLY |
61 (NodeFS.constants.O_NOFOLLOW ?? 0) |
62 (NodeFS.constants.O_NONBLOCK ?? 0),
63 );
64 let accepted = false;
65 try {
66 const info = await handle.stat({ bigint: true });
67 if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
68 if (
69 identity &&
70 (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
71 ) {
72 return null;
73 }
74 if ((await NodeFSP.realpath(filePath)) !== filePath) return null;
75 const after = await NodeFSP.lstat(filePath, { bigint: true });
76 if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
77 accepted = true;
78 return { handle, info } satisfies OpenMediaFile;
79 } finally {
80 if (!accepted) await handle.close();
81 }
82 },
83 catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
84 }),
85 (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
86 );
87});
88
89export const statMediaFile = Effect.fn("statMediaFile")(function* (
90 filePath: string,
91 file: OpenMediaFile,
92) {
93 return yield* Effect.tryPromise({
94 try: () => file.handle.stat({ bigint: true }),
95 catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
96 });
97});
98
99export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
100 const start = Number(offset);
101 const end = Number(offset + bytesToRead - 1n);
102 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
103 return null;
104 }
105 return NodeStream.fromReadable<Uint8Array>({
106 evaluate: () =>
107 file.handle.createReadStream({
108 autoClose: false,
109 start,
110 end,
111 }),
112 });
113};