-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.ts
285 lines (242 loc) · 8.33 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { randomBytes } from "crypto";
import { read, open, closeSync, unlinkSync, write, close, unlink } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { Readable, ReadableOptions, Writable, WritableOptions } from "stream";
import { EventEmitter } from "events";
export class ReadAfterDestroyedError extends Error {}
export class ReadAfterReleasedError extends Error {}
export interface ReadStreamOptions {
highWaterMark?: ReadableOptions["highWaterMark"];
encoding?: ReadableOptions["encoding"];
}
// Use a “proxy” event emitter configured to have an infinite maximum number of
// listeners to prevent Node.js max listeners exceeded warnings if many
// `fs-capacitor` `ReadStream` instances are created at the same time. See:
// https://github.com/mike-marcacci/fs-capacitor/issues/30
const processExitProxy = new EventEmitter();
processExitProxy.setMaxListeners(Infinity);
process.once("exit", () => processExitProxy.emit("exit"));
export class ReadStream extends Readable {
private _pos: number = 0;
private _writeStream: WriteStream;
constructor(writeStream: WriteStream, options?: ReadStreamOptions) {
super({
highWaterMark: options?.highWaterMark,
encoding: options?.encoding,
autoDestroy: true,
});
this._writeStream = writeStream;
}
_read(n: number): void {
if (this.destroyed) return;
if (typeof this._writeStream["_fd"] !== "number") {
this._writeStream.once("ready", () => this._read(n));
return;
}
// Using `allocUnsafe` here is OK because we return a slice the length of
// `bytesRead`, and discard the rest. This prevents node from having to zero
// out the entire allocation first.
const buf = Buffer.allocUnsafe(n);
read(this._writeStream["_fd"], buf, 0, n, this._pos, (error, bytesRead) => {
if (error) this.destroy(error);
// Push any read bytes into the local stream buffer.
if (bytesRead) {
this._pos += bytesRead;
this.push(buf.slice(0, bytesRead));
return;
}
// If there were no more bytes to read and the write stream is finished,
// then this stream has reached the end.
if (
(
this._writeStream as any as {
_writableState: { finished: boolean };
}
)._writableState.finished
) {
// Check if we have consumed the whole file up to where
// the write stream has written before ending the stream
if (this._pos < (this._writeStream as any as { _pos: number })._pos)
this._read(n);
else this.push(null);
return;
}
// Otherwise, wait for the write stream to add more data or finish.
const retry = (): void => {
this._writeStream.off("finish", retry);
this._writeStream.off("write", retry);
this._read(n);
};
this._writeStream.on("finish", retry);
this._writeStream.on("write", retry);
});
}
}
export interface WriteStreamOptions {
highWaterMark?: WritableOptions["highWaterMark"];
defaultEncoding?: WritableOptions["defaultEncoding"];
tmpdir?: () => string;
}
export class WriteStream extends Writable {
private _fd: null | number = null;
private _path: null | string = null;
private _pos: number = 0;
private _readStreams: Set<ReadStream> = new Set();
private _released: boolean = false;
constructor(options?: WriteStreamOptions) {
super({
highWaterMark: options?.highWaterMark,
defaultEncoding: options?.defaultEncoding,
autoDestroy: false,
});
// Generate a random filename.
randomBytes(16, (error, buffer) => {
if (error) {
this.destroy(error);
return;
}
this._path = join(
(options?.tmpdir ?? tmpdir)(),
`capacitor-${buffer.toString("hex")}.tmp`
);
// Create a file in the OS's temporary files directory.
open(this._path, "wx+", 0o600, (error, fd) => {
if (error) {
this.destroy(error);
return;
}
// Cleanup when the process exits or is killed.
processExitProxy.once("exit", this._cleanupSync);
this._fd = fd;
this.emit("ready");
});
});
}
_cleanup = (callback: (error: null | Error) => void): void => {
const fd = this._fd;
const path = this._path;
if (typeof fd !== "number" || typeof path !== "string") {
callback(null);
return;
}
// Close the file descriptor.
close(fd, (closeError) => {
// An error here probably means the fd was already closed, but we can
// still try to unlink the file.
unlink(path, (unlinkError) => {
// If we are unable to unlink the file, the operating system will
// clean up on next restart, since we use store thes in `os.tmpdir()`
this._fd = null;
// We avoid removing this until now in case an exit occurs while
// asyncronously cleaning up.
processExitProxy.off("exit", this._cleanupSync);
callback(unlinkError ?? closeError);
});
});
};
_cleanupSync = (): void => {
processExitProxy.off("exit", this._cleanupSync);
if (typeof this._fd === "number")
try {
closeSync(this._fd);
} catch (error) {
// An error here probably means the fd was already closed, but we can
// still try to unlink the file.
}
try {
if (this._path !== null) {
unlinkSync(this._path);
}
} catch (error) {
// If we are unable to unlink the file, the operating system will clean
// up on next restart, since we use store thes in `os.tmpdir()`
}
};
_final(callback: (error?: null | Error) => any): void {
if (typeof this._fd !== "number") {
this.once("ready", () => this._final(callback));
return;
}
callback();
}
_write(
chunk: Buffer,
encoding: string,
callback: (error?: null | Error) => any
): void {
if (typeof this._fd !== "number") {
this.once("ready", () => this._write(chunk, encoding, callback));
return;
}
write(this._fd, chunk, 0, chunk.length, this._pos, (error) => {
if (error) {
callback(error);
return;
}
// It's safe to increment `this._pos` after flushing to the filesystem
// because node streams ensure that only one `_write()` is active at a
// time. If this assumption is broken, the behavior of this library is
// undefined, regardless of where this is incremented. Relocating this
// to increment syncronously would result in correct file contents, but
// the out-of-order writes would still open the potential for read streams
// to scan positions that have not yet been written.
this._pos += chunk.length;
this.emit("write");
callback();
});
}
release(): void {
this._released = true;
if (this._readStreams.size === 0) this.destroy();
}
_destroy(
error: undefined | null | Error,
callback: (error?: null | Error) => any
): void {
// Destroy all attached read streams.
for (const readStream of this._readStreams) {
readStream.destroy(error || undefined);
}
// This capacitor is fully initialized.
if (typeof this._fd === "number" && typeof this._path === "string") {
this._cleanup((cleanupError) => callback(cleanupError ?? error));
return;
}
// This capacitor has not yet finished initialization; if initialization
// does complete, immediately clean up after.
this.once("ready", () => {
this._cleanup((cleanupError) => {
if (cleanupError) {
this.emit("error", cleanupError);
}
});
});
callback(error);
}
createReadStream(options?: ReadStreamOptions): ReadStream {
if (this.destroyed)
throw new ReadAfterDestroyedError(
"A ReadStream cannot be created from a destroyed WriteStream."
);
if (this._released)
throw new ReadAfterReleasedError(
"A ReadStream cannot be created from a released WriteStream."
);
const readStream = new ReadStream(this, options);
this._readStreams.add(readStream);
readStream.once("close", (): void => {
this._readStreams.delete(readStream);
if (this._released && this._readStreams.size === 0) {
this.destroy();
}
});
return readStream;
}
}
export default {
WriteStream,
ReadStream,
ReadAfterDestroyedError,
ReadAfterReleasedError,
};