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

DocumentText.ts

120 lines4.6 KB

1// @effect-diagnostics nodeBuiltinImport:off -- the isolated parser process is an external runtime boundary.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeURL from "node:url";
4import * as Clock from "effect/Clock";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Schema from "effect/Schema";
10import * as Semaphore from "effect/Semaphore";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12​
13const extensions = new Set(["docx", "xlsx", "pptx", "odt", "ods", "odp", "rtf", "epub", "ipynb"]);
14​
15class DocumentTextError extends Schema.TaggedError<DocumentTextError>()("DocumentTextError", {
16 operation: Schema.Literal("extract"),
17 path: Schema.String,
18 extension: Schema.String,
19 cause: Schema.Defect(),
20}) {
21 override get message(): string {
22 return `Failed to ${this.operation} ${this.extension} document text.`;
23 }
25​
26export const resolveExtractedTextPath = Effect.fn("DocumentText.resolveExtractedTextPath")(
27 function* (path: string) {
28 const extension = path.split(".").at(-1)?.toLowerCase();
29 if (!extension || !extensions.has(extension)) return;
30 const fs = yield* FileSystem.FileSystem;
31 return yield* fs.exists(path + ".txt").pipe(
32 Effect.map((exists) => (exists ? path + ".txt" : undefined)),
33 Effect.orElseSucceed(() => undefined),
34 );
35 },
36);
37​
38export class DocumentText extends Context.Service<
39 DocumentText,
40 {
41 readonly ensure: (path: string) => Effect.Effect<string | undefined>;
42 }
43>()("t3/provider/DocumentText") {}
44​
45const make = Effect.gen(function* () {
46 const fs = yield* FileSystem.FileSystem;
47 const executable = yield* HostProcess.ExecutablePath;
48 const isExecutable = yield* HostProcess.IsExecutable;
49 const environment = yield* HostProcess.Environment;
50 const clock = yield* Clock.Clock;
51 const lock = yield* Semaphore.make(1);
52 const failed = new Map<string, number>();
53 // In a bundle import.meta.url is bin.mjs; development and tests use this source module.
54 const entry = NodeURL.fileURLToPath(
55 new URL(import.meta.url.endsWith(".ts") ? "../bin.ts" : "./bin.mjs", import.meta.url),
56 );
57 const extract = Effect.fn("DocumentText.extract")(function* (path: string, extension: string) {
58 const sidecar = `${path}.txt`;
59 if (yield* fs.exists(sidecar)) return sidecar;
60 if ((failed.get(path) ?? 0) > clock.currentTimeMillisUnsafe()) return;
61 const info = yield* fs.stat(path);
62 if (Number(info.size) > 16 * 1024 * 1024) return;
63 const content = yield* Effect.tryPromise({
64 try: (signal) =>
65 new Promise<string>((resolve, reject) => {
66 NodeChildProcess.execFile(
67 executable,
68 [...(isExecutable ? [] : [entry]), "__document-text", path, `.${extension}`],
69 {
70 signal,
71 timeout: 15_000,
72 maxBuffer: 4 * 1024 * 1024 + 1024,
73 encoding: "utf8",
74 windowsHide: true,
75 env: {
76 ...environment,
77 ELECTRON_RUN_AS_NODE: "1",
78 NODE_OPTIONS: `${environment.NODE_OPTIONS ?? ""} --max-old-space-size=192`,
79 },
80 },
81 (error, stdout) => (error ? reject(error) : resolve(stdout)),
82 );
83 }),
84 catch: (cause) => new DocumentTextError({ operation: "extract", path, extension, cause }),
85 }).pipe(
86 Effect.tapError(({ cause }) => {
87 if (failed.size >= 1024) failed.delete(failed.keys().next().value!);
88 failed.set(
89 path,
90 cause instanceof Error && "code" in cause && cause.code === 2
91 ? Infinity
92 : clock.currentTimeMillisUnsafe() + 1_000,
93 );
94 return Effect.logWarning("Document text extraction failed.", { extension });
95 }),
96 );
97 const pending = `${sidecar}.part`;
98 yield* fs
99 .writeFileString(pending, content)
100 .pipe(
101 Effect.andThen(fs.rename(pending, sidecar)),
102 Effect.ensuring(fs.remove(pending, { force: true }).pipe(Effect.ignore)),
103 Effect.uninterruptible,
104 );
105 return sidecar;
106 }, lock.withPermits(1));
107 const ensure = Effect.fn("DocumentText.ensure")(
108 function* (path: string) {
109 const extension = path.split(".").at(-1)?.toLowerCase();
110 if (!extension || !extensions.has(extension)) return;
111 const sidecar = `${path}.txt`;
112 if (yield* fs.exists(sidecar)) return sidecar;
113 return yield* extract(path, extension);
114 },
115 Effect.orElseSucceed(() => undefined),
116 );
117 return DocumentText.of({ ensure });
118});
119​
120export const layer = Layer.effect(DocumentText, make);