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

MediaFile.ts

122 lines4.3 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.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 }
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 }
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;
39​
40const realpathLikeFileSystem = (filePath: string) =>
41 new Promise<string>((resolve, reject) => {
42 NodeFS.realpath(filePath, (error, resolved) => (error ? reject(error) : resolve(resolved)));
43 });
44​
45/** Opens a canonical media path once. Replacements cannot change the response's source. */
46export const openMediaFile = Effect.fn("openMediaFile")(function* (
47 filePath: string,
48 identity?: { readonly device: string; readonly inode: string },
49) {
50 return yield* Effect.acquireRelease(
51 Effect.tryPromise({
52 try: async () => {
53 const before = await NodeFSP.lstat(filePath, { bigint: true });
54 if (!before.isFile() || before.ino === 0n) return null;
55 if (
56 identity &&
57 (before.dev.toString() !== identity.device || before.ino.toString() !== identity.inode)
58 ) {
59 return null;
60 }
61​
62 // Windows lacks these flags; the descriptor/path identity checks still apply.
63 const handle = await NodeFSP.open(
64 filePath,
65 NodeFS.constants.O_RDONLY |
66 (NodeFS.constants.O_NOFOLLOW ?? 0) |
67 (NodeFS.constants.O_NONBLOCK ?? 0),
68 );
69 let accepted = false;
70 try {
71 const info = await handle.stat({ bigint: true });
72 if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) return null;
73 if (
74 identity &&
75 (info.dev.toString() !== identity.device || info.ino.toString() !== identity.inode)
76 ) {
77 return null;
78 }
79 // Callers canonicalise with Effect's FileSystem.realPath, which is
80 // Node's JS realpath. fs/promises.realpath is the native binding and
81 // on Windows also expands 8.3 short names, so a path that is already
82 // canonical by the caller's rules would still look swapped here.
83 if ((await realpathLikeFileSystem(filePath)) !== filePath) return null;
84 const after = await NodeFSP.lstat(filePath, { bigint: true });
85 if (!after.isFile() || info.dev !== after.dev || info.ino !== after.ino) return null;
86 accepted = true;
87 return { handle, info } satisfies OpenMediaFile;
88 } finally {
89 if (!accepted) await handle.close();
90 }
91 },
92 catch: (cause) => new MediaFileOpenError({ path: filePath, cause }),
93 }),
94 (file) => (file ? Effect.promise(() => file.handle.close()) : Effect.void),
95 );
96});
97​
98export const statMediaFile = Effect.fn("statMediaFile")(function* (
99 filePath: string,
100 file: OpenMediaFile,
101) {
102 return yield* Effect.tryPromise({
103 try: () => file.handle.stat({ bigint: true }),
104 catch: (cause) => new MediaFileStatError({ path: filePath, cause }),
105 });
106});
107​
108export const streamMediaFile = (file: OpenMediaFile, offset: bigint, bytesToRead: bigint) => {
109 const start = Number(offset);
110 const end = Number(offset + bytesToRead - 1n);
111 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
112 return null;
113 }
114 return NodeStream.fromReadable<Uint8Array>({
115 evaluate: () =>
116 file.handle.createReadStream({
117 autoClose: false,
118 start,
119 end,
120 }),
121 });
122};