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

NodeFileSystem.ts

675 lines18.8 KB

1/**
2 * Shared Node-compatible implementation of Effect's `FileSystem` service.
3 *
4 * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a
5 * `FileSystem` layer for Effect programs running on Node-compatible runtimes.
6 * Platform packages use it to provide file and directory I/O, permissions,
7 * links, metadata, temporary files and directories, and file watching through
8 * the shared `FileSystem` service.
9 *
10 * **Mental model**
11 *
12 * {@link layer} installs a process-backed `FileSystem` service. Each operation
13 * delegates to the corresponding Node filesystem API, then maps Node failures
14 * into `PlatformError` values and invalid arguments into `BadArgument` failures.
15 * Paths keep Node's normal behavior: relative paths resolve from the current
16 * working directory and platform path rules still apply.
17 *
18 * **Common tasks**
19 *
20 * Provide {@link layer} at the Node runtime boundary, then depend on the
21 * `FileSystem` service from application code. Use the service for ordinary
22 * reads and writes, directory management, metadata inspection, links, temporary
23 * resources, and file watching without importing Node's `fs` APIs directly.
24 *
25 * **Gotchas**
26 *
27 * Open files are scoped resources with tracked read and write positions; append
28 * mode lets the operating system choose the write offset. File watching follows
29 * `node:fs.watch` semantics unless a custom watch backend is supplied, so
30 * recursive support, event coalescing, and reported paths vary by runtime and
31 * platform.
32 *
33 * @since 4.0.0
34 */
35import * as Cause from "effect/Cause"
36import * as Effect from "effect/Effect"
37import { effectify } from "effect/Effect"
38import * as FileSystem from "effect/FileSystem"
39import { pipe } from "effect/Function"
40import * as Layer from "effect/Layer"
41import * as Option from "effect/Option"
42import * as Error from "effect/PlatformError"
43import * as Queue from "effect/Queue"
44import * as Stream from "effect/Stream"
45import * as Crypto from "node:crypto"
46import * as NFS from "node:fs"
47import * as OS from "node:os"
48import * as Path from "node:path"
49import { handleErrnoException } from "./internal/utils.ts"
50​
51const handleBadArgument = (method: string) => (err: unknown) =>
52 Error.badArgument({
53 module: "FileSystem",
54 method,
55 description: (err as Error).message ?? String(err)
56 })
57​
58// == access
59​
60const access = ((): FileSystem.FileSystem["access"] => {
61 const nodeAccess = effectify(
62 NFS.access,
63 handleErrnoException("FileSystem", "access"),
64 handleBadArgument("access")
65 )
66 return (path, options) => {
67 let mode = NFS.constants.F_OK
68 if (options?.readable) {
69 mode |= NFS.constants.R_OK
70 }
71 if (options?.writable) {
72 mode |= NFS.constants.W_OK
73 }
74 return nodeAccess(path, mode)
75 }
76})()
77​
78// == copy
79​
80const copy = ((): FileSystem.FileSystem["copy"] => {
81 const nodeCp = effectify(
82 NFS.cp,
83 handleErrnoException("FileSystem", "copy"),
84 handleBadArgument("copy")
85 )
86 return (fromPath, toPath, options) =>
87 nodeCp(fromPath, toPath, {
88 force: options?.overwrite ?? false,
89 preserveTimestamps: options?.preserveTimestamps ?? false,
90 recursive: true
91 })
92})()
93​
94// == copyFile
95​
96const copyFile = (() => {
97 const nodeCopyFile = effectify(
98 NFS.copyFile,
99 handleErrnoException("FileSystem", "copyFile"),
100 handleBadArgument("copyFile")
101 )
102 return (fromPath: string, toPath: string) => nodeCopyFile(fromPath, toPath)
103})()
104​
105// == chmod
106​
107const chmod = (() => {
108 const nodeChmod = effectify(
109 NFS.chmod,
110 handleErrnoException("FileSystem", "chmod"),
111 handleBadArgument("chmod")
112 )
113 return (path: string, mode: number) => nodeChmod(path, mode)
114})()
115​
116// == chown
117​
118const chown = (() => {
119 const nodeChown = effectify(
120 NFS.chown,
121 handleErrnoException("FileSystem", "chown"),
122 handleBadArgument("chown")
123 )
124 return (path: string, uid: number, gid: number) => nodeChown(path, uid, gid)
125})()
126​
127// == link
128​
129const link = (() => {
130 const nodeLink = effectify(
131 NFS.link,
132 handleErrnoException("FileSystem", "link"),
133 handleBadArgument("link")
134 )
135 return (existingPath: string, newPath: string) => nodeLink(existingPath, newPath)
136})()
137​
138// == makeDirectory
139​
140const makeDirectory = ((): FileSystem.FileSystem["makeDirectory"] => {
141 const nodeMkdir = effectify(
142 NFS.mkdir,
143 handleErrnoException("FileSystem", "makeDirectory"),
144 handleBadArgument("makeDirectory")
145 )
146 return (path, options) =>
147 nodeMkdir(path, {
148 recursive: options?.recursive ?? false,
149 mode: options?.mode
150 })
151})()
152​
153// == makeTempDirectory
154​
155const makeTempDirectoryFactory = (method: string): FileSystem.FileSystem["makeTempDirectory"] => {
156 const nodeMkdtemp = effectify(
157 NFS.mkdtemp,
158 handleErrnoException("FileSystem", method),
159 handleBadArgument(method)
160 )
161 return (options) =>
162 Effect.suspend(() => {
163 const prefix = options?.prefix ?? ""
164 const directory = typeof options?.directory === "string"
165 ? Path.join(options.directory, ".")
166 : OS.tmpdir()
167​
168 return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + "/")
169 })
171const makeTempDirectory = makeTempDirectoryFactory("makeTempDirectory")
172​
173// == remove
174​
175const removeFactory = (method: string): FileSystem.FileSystem["remove"] => {
176 const nodeRm = effectify(
177 NFS.rm,
178 handleErrnoException("FileSystem", method),
179 handleBadArgument(method)
180 )
181 return (path, options) =>
182 nodeRm(
183 path,
184 { recursive: options?.recursive ?? false, force: options?.force ?? false }
185 )
187const remove = removeFactory("remove")
188​
189// == makeTempDirectoryScoped
190​
191const makeTempDirectoryScoped = ((): FileSystem.FileSystem["makeTempDirectoryScoped"] => {
192 const makeDirectory = makeTempDirectoryFactory("makeTempDirectoryScoped")
193 const removeDirectory = removeFactory("makeTempDirectoryScoped")
194 return (options) =>
195 Effect.acquireRelease(
196 makeDirectory(options),
197 (directory) => Effect.orDie(removeDirectory(directory, { recursive: true }))
198 )
199})()
200​
201// == open
202​
203const openFactory = (method: string): FileSystem.FileSystem["open"] => {
204 const nodeOpen = effectify(
205 NFS.open,
206 handleErrnoException("FileSystem", method),
207 handleBadArgument(method)
208 )
209 const nodeClose = effectify(
210 NFS.close,
211 handleErrnoException("FileSystem", method),
212 handleBadArgument(method)
213 )
214​
215 return (path, options) =>
216 pipe(
217 Effect.acquireRelease(
218 nodeOpen(path, options?.flag ?? "r", options?.mode),
219 (fd) => Effect.orDie(nodeClose(fd))
220 ),
221 Effect.map((fd) => makeFile(FileSystem.FileDescriptor(fd), options?.flag?.startsWith("a") ?? false))
222 )
224const open = openFactory("open")
225​
226const makeFile = (() => {
227 const nodeReadFactory = (method: string) =>
228 effectify(
229 NFS.read,
230 handleErrnoException("FileSystem", method),
231 handleBadArgument(method)
232 )
233 const nodeRead = nodeReadFactory("read")
234 const nodeReadAlloc = nodeReadFactory("readAlloc")
235 const nodeStat = effectify(
236 NFS.fstat,
237 handleErrnoException("FileSystem", "stat"),
238 handleBadArgument("stat")
239 )
240 const nodeTruncate = effectify(
241 NFS.ftruncate,
242 handleErrnoException("FileSystem", "truncate"),
243 handleBadArgument("truncate")
244 )
245​
246 const nodeSync = effectify(
247 NFS.fsync,
248 handleErrnoException("FileSystem", "sync"),
249 handleBadArgument("sync")
250 )
251​
252 const nodeWriteFactory = (method: string) =>
253 effectify(
254 NFS.write,
255 handleErrnoException("FileSystem", method),
256 handleBadArgument(method)
257 )
258 const nodeWrite = nodeWriteFactory("write")
259 const nodeWriteAll = nodeWriteFactory("writeAll")
260​
261 class FileImpl implements FileSystem.File {
262 readonly [FileSystem.FileTypeId]: typeof FileSystem.FileTypeId
263 readonly fd: FileSystem.File.Descriptor
264 private readonly append: boolean
265​
266 private position: bigint = BigInt(0)
267​
268 constructor(
269 fd: FileSystem.File.Descriptor,
270 append: boolean
271 ) {
272 this[FileSystem.FileTypeId] = FileSystem.FileTypeId
273 this.fd = fd
274 this.append = append
275 }
276​
277 get stat() {
278 return Effect.map(nodeStat(this.fd), makeFileInfo)
279 }
280​
281 get sync() {
282 return nodeSync(this.fd)
283 }
284​
285 seek(offset: FileSystem.SizeInput, from: FileSystem.SeekMode) {
286 const offsetSize = FileSystem.Size(offset)
287 return Effect.sync(() => {
288 if (from === "start") {
289 this.position = offsetSize
290 } else if (from === "current") {
291 this.position = this.position + offsetSize
292 }
293​
294 return this.position
295 })
296 }
297​
298 read(buffer: Uint8Array) {
299 return Effect.suspend(() => {
300 const position = this.position
301 return Effect.map(
302 nodeRead(this.fd, { buffer, position }),
303 (bytesRead) => {
304 const sizeRead = FileSystem.Size(bytesRead)
305 this.position = position + sizeRead
306 return sizeRead
307 }
308 )
309 })
310 }
311​
312 readAlloc(size: FileSystem.SizeInput) {
313 const sizeNumber = Number(size)
314 return Effect.suspend(() => {
315 const buffer = Buffer.allocUnsafeSlow(sizeNumber)
316 const position = this.position
317 return Effect.map(
318 nodeReadAlloc(this.fd, { buffer, position }),
319 (bytesRead): Option.Option<Buffer> => {
320 if (bytesRead === 0) {
321 return Option.none()
322 }
323​
324 this.position = position + BigInt(bytesRead)
325 if (bytesRead === sizeNumber) {
326 return Option.some(buffer)
327 }
328​
329 const dst = Buffer.allocUnsafeSlow(bytesRead)
330 buffer.copy(dst, 0, 0, bytesRead)
331 return Option.some(dst)
332 }
333 )
334 })
335 }
336​
337 truncate(length?: FileSystem.SizeInput) {
338 return Effect.map(nodeTruncate(this.fd, length ? Number(length) : undefined), () => {
339 if (!this.append) {
340 const len = BigInt(length ?? 0)
341 if (this.position > len) {
342 this.position = len
343 }
344 }
345 })
346 }
347​
348 write(buffer: Uint8Array) {
349 return Effect.suspend(() => {
350 const position = this.position
351 return Effect.map(
352 nodeWrite(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)),
353 (bytesWritten) => {
354 const sizeWritten = FileSystem.Size(bytesWritten)
355 if (!this.append) {
356 this.position = position + sizeWritten
357 }
358 return sizeWritten
359 }
360 )
361 })
362 }
363​
364 private writeAllChunk(buffer: Uint8Array): Effect.Effect<void, Error.PlatformError> {
365 return Effect.suspend(() => {
366 const position = this.position
367 return Effect.flatMap(
368 nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(position)),
369 (bytesWritten) => {
370 if (bytesWritten === 0) {
371 return Effect.fail(
372 Error.systemError({
373 module: "FileSystem",
374 method: "writeAll",
375 _tag: "WriteZero",
376 pathOrDescriptor: this.fd,
377 description: "write returned 0 bytes written"
378 })
379 )
380 }
381​
382 if (!this.append) {
383 this.position = position + BigInt(bytesWritten)
384 }
385​
386 return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void
387 }
388 )
389 })
390 }
391​
392 writeAll(buffer: Uint8Array) {
393 return this.writeAllChunk(buffer)
394 }
395 }
396​
397 return (fd: FileSystem.File.Descriptor, append: boolean): FileSystem.File => new FileImpl(fd, append)
398})()
399​
400// == makeTempFile
401​
402const makeTempFileFactory = (method: string): FileSystem.FileSystem["makeTempFile"] => {
403 const makeDirectory = makeTempDirectoryFactory(method)
404 return Effect.fnUntraced(function*(options) {
405 const directory = yield* makeDirectory(options)
406 const random = Crypto.randomBytes(6).toString("hex")
407 const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random)
408 yield* writeFile(name, new Uint8Array(0))
409 return name
410 })
412const makeTempFile = makeTempFileFactory("makeTempFile")
413​
414// == makeTempFileScoped
415​
416const makeTempFileScoped = ((): FileSystem.FileSystem["makeTempFileScoped"] => {
417 const makeFile = makeTempFileFactory("makeTempFileScoped")
418 const removeDirectory = removeFactory("makeTempFileScoped")
419 return (options) =>
420 Effect.acquireRelease(
421 makeFile(options),
422 (file) => Effect.orDie(removeDirectory(Path.dirname(file), { recursive: true }))
423 )
424})()
425​
426// == readDirectory
427​
428const readDirectory: FileSystem.FileSystem["readDirectory"] = (path, options) =>
429 Effect.tryPromise({
430 try: () => NFS.promises.readdir(path, options),
431 catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err as any, [path])
432 })
433​
434// == readFile
435​
436const readFile = (path: string) =>
437 Effect.callback<Uint8Array, Error.PlatformError>((resume, signal) => {
438 try {
439 NFS.readFile(path, { signal }, (err, data) => {
440 if (err) {
441 resume(Effect.fail(handleErrnoException("FileSystem", "readFile")(err, [path])))
442 } else {
443 resume(Effect.succeed(data))
444 }
445 })
446 } catch (err) {
447 resume(Effect.fail(handleBadArgument("readFile")(err)))
448 }
449 })
450​
451// == readLink
452​
453const readLink = (() => {
454 const nodeReadLink = effectify(
455 NFS.readlink,
456 handleErrnoException("FileSystem", "readLink"),
457 handleBadArgument("readLink")
458 )
459 return (path: string) => nodeReadLink(path)
460})()
461​
462// == realPath
463​
464const realPath = (() => {
465 const nodeRealPath = effectify(
466 NFS.realpath,
467 handleErrnoException("FileSystem", "realPath"),
468 handleBadArgument("realPath")
469 )
470 return (path: string) => nodeRealPath(path)
471})()
472​
473// == rename
474​
475const rename = (() => {
476 const nodeRename = effectify(
477 NFS.rename,
478 handleErrnoException("FileSystem", "rename"),
479 handleBadArgument("rename")
480 )
481 return (oldPath: string, newPath: string) => nodeRename(oldPath, newPath)
482})()
483​
484// == stat
485​
486const makeFileInfo = (stat: NFS.Stats): FileSystem.File.Info => ({
487 type: stat.isFile() ?
488 "File" :
489 stat.isDirectory() ?
490 "Directory" :
491 stat.isSymbolicLink() ?
492 "SymbolicLink" :
493 stat.isBlockDevice() ?
494 "BlockDevice" :
495 stat.isCharacterDevice() ?
496 "CharacterDevice" :
497 stat.isFIFO() ?
498 "FIFO" :
499 stat.isSocket() ?
500 "Socket" :
501 "Unknown",
502 mtime: Option.fromNullishOr(stat.mtime),
503 atime: Option.fromNullishOr(stat.atime),
504 birthtime: Option.fromNullishOr(stat.birthtime),
505 dev: stat.dev,
506 rdev: Option.fromNullishOr(stat.rdev),
507 ino: Option.fromNullishOr(stat.ino),
508 mode: stat.mode,
509 nlink: Option.fromNullishOr(stat.nlink),
510 uid: Option.fromNullishOr(stat.uid),
511 gid: Option.fromNullishOr(stat.gid),
512 size: FileSystem.Size(stat.size),
513 blksize: stat.blksize !== undefined ? Option.some(FileSystem.Size(stat.blksize)) : Option.none(),
514 blocks: Option.fromNullishOr(stat.blocks)
515})
516const stat = (() => {
517 const nodeStat = effectify(
518 NFS.stat,
519 handleErrnoException("FileSystem", "stat"),
520 handleBadArgument("stat")
521 )
522 return (path: string) => Effect.map(nodeStat(path), makeFileInfo)
523})()
524​
525// == symlink
526​
527const symlink = (() => {
528 const nodeSymlink = effectify(
529 NFS.symlink,
530 handleErrnoException("FileSystem", "symlink"),
531 handleBadArgument("symlink")
532 )
533 return (target: string, path: string) => nodeSymlink(target, path)
534})()
535​
536// == truncate
537​
538const truncate = (() => {
539 const nodeTruncate = effectify(
540 NFS.truncate,
541 handleErrnoException("FileSystem", "truncate"),
542 handleBadArgument("truncate")
543 )
544 return (path: string, length?: FileSystem.SizeInput) =>
545 nodeTruncate(path, length !== undefined ? Number(length) : undefined)
546})()
547​
548// == utimes
549​
550const utimes = (() => {
551 const nodeUtimes = effectify(
552 NFS.utimes,
553 handleErrnoException("FileSystem", "utime"),
554 handleBadArgument("utime")
555 )
556 return (path: string, atime: number | Date, mtime: number | Date) => nodeUtimes(path, atime, mtime)
557})()
558​
559// == watch
560​
561const watchNode = (path: string) =>
562 Stream.callback<FileSystem.WatchEvent, Error.PlatformError>((queue) =>
563 Effect.acquireRelease(
564 Effect.sync(() => {
565 const watcher = NFS.watch(path, {
566 recursive: true
567 }, (event, path) => {
568 if (!path) return
569 switch (event) {
570 case "rename": {
571 Effect.runFork(Effect.matchEffect(stat(path), {
572 onSuccess: (_) => Queue.offer(queue, { _tag: "Create", path }),
573 onFailure: (_) => Queue.offer(queue, { _tag: "Remove", path })
574 }))
575 return
576 }
577 case "change": {
578 Queue.offerUnsafe(queue, { _tag: "Update", path })
579 return
580 }
581 }
582 })
583 watcher.on("error", (error) => {
584 Queue.failCauseUnsafe(
585 queue,
586 Cause.fail(
587 Error.systemError({
588 module: "FileSystem",
589 _tag: "Unknown",
590 method: "watch",
591 pathOrDescriptor: path,
592 cause: error
593 })
594 )
595 )
596 })
597 watcher.on("close", () => {
598 Queue.endUnsafe(queue)
599 })
600 return watcher
601 }),
602 (watcher) => Effect.sync(() => watcher.close())
603 )
604 )
605​
606const watch = (backend: Option.Option<FileSystem.WatchBackend["Service"]>, path: string) =>
607 stat(path).pipe(
608 Effect.map((stat) =>
609 backend.pipe(
610 Option.flatMap((_) => _.register(path, stat)),
611 Option.getOrElse(() => watchNode(path))
612 )
613 ),
614 Stream.unwrap
615 )
616​
617// == writeFile
618​
619const writeFile: FileSystem.FileSystem["writeFile"] = (path, data, options) =>
620 Effect.callback<void, Error.PlatformError>((resume, signal) => {
621 try {
622 NFS.writeFile(path, data, {
623 signal,
624 flag: options?.flag,
625 mode: options?.mode
626 }, (err) => {
627 if (err) {
628 resume(Effect.fail(handleErrnoException("FileSystem", "writeFile")(err, [path])))
629 } else {
630 resume(Effect.void)
631 }
632 })
633 } catch (err) {
634 resume(Effect.fail(handleBadArgument("writeFile")(err)))
635 }
636 })
637​
638const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend), (backend) =>
639 FileSystem.make({
640 access,
641 chmod,
642 chown,
643 copy,
644 copyFile,
645 link,
646 makeDirectory,
647 makeTempDirectory,
648 makeTempDirectoryScoped,
649 makeTempFile,
650 makeTempFileScoped,
651 open,
652 readDirectory,
653 readFile,
654 readLink,
655 realPath,
656 remove,
657 rename,
658 stat,
659 symlink,
660 truncate,
661 utimes,
662 watch(path) {
663 return watch(backend, path)
664 },
665 writeFile
666 }))
667​
668/**
669 * Provides the `FileSystem` service backed by Node filesystem APIs, including
670 * file operations, directory operations, links, metadata, and file watching.
671 *
672 * @category layers
673 * @since 4.0.0
674 */
675export const layer: Layer.Layer<FileSystem.FileSystem> = Layer.effect(FileSystem.FileSystem)(makeFileSystem)