@naturalcycles/nodejs-lib 15.147.0 → 15.148.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fs/json2env.js +4 -12
- package/dist/glob/index.js +1 -0
- package/dist/security/hash.util.d.ts +3 -4
- package/dist/stream/cloudStorageStream.d.ts +22 -0
- package/dist/stream/cloudStorageStream.js +80 -0
- package/dist/stream/ndjson/createReadStreamAsNDJson.d.ts +4 -0
- package/dist/stream/ndjson/createReadStreamAsNDJson.js +15 -6
- package/dist/stream/pipeline.d.ts +27 -0
- package/dist/stream/pipeline.js +50 -6
- package/dist/stream/readable/createReadable.js +5 -0
- package/dist/stream/transform/transformThrottleByRSS.js +1 -2
- package/package.json +11 -2
- package/src/fs/json2env.ts +4 -12
- package/src/glob/index.ts +1 -0
- package/src/security/hash.util.ts +3 -7
- package/src/stream/cloudStorageStream.ts +133 -0
- package/src/stream/ndjson/createReadStreamAsNDJson.ts +17 -7
- package/src/stream/pipeline.ts +57 -6
- package/src/stream/readable/createReadable.ts +6 -0
- package/src/stream/transform/transformThrottleByRSS.ts +1 -2
- package/src/stream/transform/worker/workerClassProxy.js +3 -2
- package/src/validation/ajv/jsonSchemaBuilder.util.ts +1 -1
package/dist/fs/json2env.js
CHANGED
|
@@ -98,12 +98,8 @@ export function objectToShellExport(obj, prefix = '') {
|
|
|
98
98
|
if (!Object.keys(obj).length)
|
|
99
99
|
return '';
|
|
100
100
|
return (Object.entries(obj)
|
|
101
|
-
.
|
|
102
|
-
|
|
103
|
-
return `export ${prefix}${k}="${v}"`;
|
|
104
|
-
}
|
|
105
|
-
})
|
|
106
|
-
.filter(Boolean)
|
|
101
|
+
.filter(([_k, v]) => v !== undefined && v !== null)
|
|
102
|
+
.map(([k, v]) => `export ${prefix}${k}="${v}"`)
|
|
107
103
|
.join('\n') + '\n'); // trailing \n is important
|
|
108
104
|
}
|
|
109
105
|
/**
|
|
@@ -126,11 +122,7 @@ export function objectToGithubActionsEnv(obj, prefix = '') {
|
|
|
126
122
|
if (!Object.keys(obj).length)
|
|
127
123
|
return '';
|
|
128
124
|
return (Object.entries(obj)
|
|
129
|
-
.
|
|
130
|
-
|
|
131
|
-
return `${prefix}${k}=${v}`;
|
|
132
|
-
}
|
|
133
|
-
})
|
|
134
|
-
.filter(Boolean)
|
|
125
|
+
.filter(([_k, v]) => v !== undefined && v !== null)
|
|
126
|
+
.map(([k, v]) => `${prefix}${k}=${v}`)
|
|
135
127
|
.join('\n') + '\n'); // trailing \n is important
|
|
136
128
|
}
|
package/dist/glob/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { BinaryToTextEncoding } from 'node:crypto';
|
|
2
1
|
import type { Base64String, Base64UrlString } from '@naturalcycles/js-lib/types';
|
|
3
|
-
export declare function md5(s: string | Uint8Array, outputEncoding?:
|
|
2
|
+
export declare function md5(s: string | Uint8Array, outputEncoding?: BufferEncoding): string;
|
|
4
3
|
export declare function md5AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer>;
|
|
5
|
-
export declare function sha256(s: string | Uint8Array, outputEncoding?:
|
|
4
|
+
export declare function sha256(s: string | Uint8Array, outputEncoding?: BufferEncoding): string;
|
|
6
5
|
export declare function sha256AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer>;
|
|
7
|
-
export declare function hash(s: string | Uint8Array, algorithm: string, outputEncoding?:
|
|
6
|
+
export declare function hash(s: string | Uint8Array, algorithm: string, outputEncoding?: BufferEncoding): string;
|
|
8
7
|
export declare function hashAsBuffer(s: string | Uint8Array, algorithm: string): Buffer<ArrayBuffer>;
|
|
9
8
|
export declare function base64(s: string | Uint8Array): Base64String;
|
|
10
9
|
export declare function base64Url(s: string | Uint8Array): Base64UrlString;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ReadableTyped, WritableTyped } from './stream.model.js';
|
|
2
|
+
/**
|
|
3
|
+
* Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
4
|
+
*
|
|
5
|
+
* The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
|
|
6
|
+
* afterwards. It is the same approach as in `createReadableFromAsync`.
|
|
7
|
+
*
|
|
8
|
+
* The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
9
|
+
* which is an optional peer dependency.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createCloudStorageReadStream(url: string): ReadableTyped<Uint8Array>;
|
|
12
|
+
/**
|
|
13
|
+
* Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
14
|
+
*
|
|
15
|
+
* The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
16
|
+
* which is an optional peer dependency.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createCloudStorageWriteStream(url: string): Promise<WritableTyped<Uint8Array>>;
|
|
19
|
+
/**
|
|
20
|
+
* Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isCloudStorageUrl(path: string): boolean;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { PassThrough } from 'node:stream';
|
|
2
|
+
import { _assert } from '@naturalcycles/js-lib/error/assert.js';
|
|
3
|
+
import { _noop } from '@naturalcycles/js-lib/types';
|
|
4
|
+
const CLOUD_STORAGE_URL_PREFIX = 'gs://';
|
|
5
|
+
const CLOUD_STORAGE_LIB = '@naturalcycles/cloud-storage-lib';
|
|
6
|
+
/**
|
|
7
|
+
* Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
8
|
+
*
|
|
9
|
+
* The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
|
|
10
|
+
* afterwards. It is the same approach as in `createReadableFromAsync`.
|
|
11
|
+
*
|
|
12
|
+
* The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
13
|
+
* which is an optional peer dependency.
|
|
14
|
+
*/
|
|
15
|
+
export function createCloudStorageReadStream(url) {
|
|
16
|
+
const { bucketName, filePath } = parseCloudStorageUrl(url);
|
|
17
|
+
const readable = new PassThrough();
|
|
18
|
+
// The read can fail before any consumer is attached, and an 'error' event without a listener
|
|
19
|
+
// crashes the process. With this listener the error is kept in the stream instead,
|
|
20
|
+
// and the consumer gets it when it attaches.
|
|
21
|
+
readable.on('error', _noop);
|
|
22
|
+
void getDefaultCloudStorage()
|
|
23
|
+
.then(async (storage) => {
|
|
24
|
+
await storage.getFileReadStream(bucketName, filePath).to(readable);
|
|
25
|
+
})
|
|
26
|
+
// If `readable` is already destroyed (e.g. the consumer stopped early) - this `destroy` does nothing
|
|
27
|
+
.catch(err => readable.destroy(err));
|
|
28
|
+
return readable;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
32
|
+
*
|
|
33
|
+
* The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
34
|
+
* which is an optional peer dependency.
|
|
35
|
+
*/
|
|
36
|
+
export async function createCloudStorageWriteStream(url) {
|
|
37
|
+
const { bucketName, filePath } = parseCloudStorageUrl(url);
|
|
38
|
+
const storage = await getDefaultCloudStorage();
|
|
39
|
+
return storage.getFileWriteStream(bucketName, filePath);
|
|
40
|
+
}
|
|
41
|
+
function parseCloudStorageUrl(url) {
|
|
42
|
+
_assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${url}`);
|
|
43
|
+
const [bucketName, ...pathParts] = url.slice(CLOUD_STORAGE_URL_PREFIX.length).split('/');
|
|
44
|
+
const filePath = pathParts.join('/');
|
|
45
|
+
_assert(bucketName && filePath, `Cloud Storage url should look like gs://bucket/path/to/file but got: ${url}`);
|
|
46
|
+
return { bucketName, filePath };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
|
|
50
|
+
*/
|
|
51
|
+
export function isCloudStorageUrl(path) {
|
|
52
|
+
return path.startsWith(CLOUD_STORAGE_URL_PREFIX);
|
|
53
|
+
}
|
|
54
|
+
async function getDefaultCloudStorage() {
|
|
55
|
+
const lib = await importCloudStorageLib();
|
|
56
|
+
return await lib.getDefaultCloudStorage();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* cloud-storage-lib is an optional peer dependency, so it is imported lazily,
|
|
60
|
+
* only when a `gs://` url is actually used.
|
|
61
|
+
*/
|
|
62
|
+
async function importCloudStorageLib() {
|
|
63
|
+
try {
|
|
64
|
+
// The package name is passed as a variable, so that TypeScript does not resolve this import,
|
|
65
|
+
// see the comment at CloudStorageLib
|
|
66
|
+
return await import(CLOUD_STORAGE_LIB);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
const { code, message } = err;
|
|
70
|
+
// The message names the missing package in quotes. If it names another package -
|
|
71
|
+
// cloud-storage-lib is installed, and one of its own imports is missing.
|
|
72
|
+
if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`))
|
|
73
|
+
throw err;
|
|
74
|
+
throw new Error([
|
|
75
|
+
`Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
|
|
76
|
+
'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
|
|
77
|
+
`Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
|
|
78
|
+
].join('\n'), { cause: err });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -12,5 +12,9 @@ import type { ReadableTyped } from '../stream.model.js';
|
|
|
12
12
|
To add a Limit or Offset: just add .take() or .drop(), example:
|
|
13
13
|
|
|
14
14
|
createReadStreamAsNDJson().take(100)
|
|
15
|
+
|
|
16
|
+
inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorage`.
|
|
17
|
+
A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
|
|
18
|
+
Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
|
|
15
19
|
*/
|
|
16
20
|
export declare function createReadStreamAsNDJson<ROW = any>(inputPath: string): ReadableTyped<ROW>;
|
|
@@ -2,6 +2,7 @@ import { pipeline } from 'node:stream';
|
|
|
2
2
|
import { createUnzip, createZstdDecompress } from 'node:zlib';
|
|
3
3
|
import { _noop } from '@naturalcycles/js-lib/types';
|
|
4
4
|
import { fs2 } from '../../fs/fs2.js';
|
|
5
|
+
import { createCloudStorageReadStream, isCloudStorageUrl } from '../cloudStorageStream.js';
|
|
5
6
|
import { transformSplitOnNewline } from '../transform/transformSplit.js';
|
|
6
7
|
import { transformJsonParse } from './transformJsonParse.js';
|
|
7
8
|
/**
|
|
@@ -17,14 +18,13 @@ import { transformJsonParse } from './transformJsonParse.js';
|
|
|
17
18
|
To add a Limit or Offset: just add .take() or .drop(), example:
|
|
18
19
|
|
|
19
20
|
createReadStreamAsNDJson().take(100)
|
|
21
|
+
|
|
22
|
+
inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorage`.
|
|
23
|
+
A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
|
|
24
|
+
Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
|
|
20
25
|
*/
|
|
21
26
|
export function createReadStreamAsNDJson(inputPath) {
|
|
22
|
-
|
|
23
|
-
const streams = [
|
|
24
|
-
fs2.createReadStream(inputPath, {
|
|
25
|
-
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
26
|
-
}),
|
|
27
|
-
];
|
|
27
|
+
const streams = [createFileReadStream(inputPath)];
|
|
28
28
|
if (inputPath.endsWith('.gz')) {
|
|
29
29
|
streams.push(createUnzip({
|
|
30
30
|
chunkSize: 256 * 1024, // 64KB: speedup from ~3200 to 3800 rps! 256KB: +6-8% more on ~9KB rows, neutral on ~180B rows
|
|
@@ -47,3 +47,12 @@ export function createReadStreamAsNDJson(inputPath) {
|
|
|
47
47
|
// ~5000 vs ~4000 rps !!!". Measured again on Node 24, it's the opposite: Readable.map costs ~1µs per row in promise machinery,
|
|
48
48
|
// transformJsonParse() is 1.5x (consumed via pipeline) to 1.75x (consumed via for-await) faster on ~180B rows.
|
|
49
49
|
}
|
|
50
|
+
function createFileReadStream(inputPath) {
|
|
51
|
+
// A Cloud Storage file is not checked for existence upfront: if it is missing - the stream fails
|
|
52
|
+
if (isCloudStorageUrl(inputPath))
|
|
53
|
+
return createCloudStorageReadStream(inputPath);
|
|
54
|
+
fs2.requireFileToExist(inputPath);
|
|
55
|
+
return fs2.createReadStream(inputPath, {
|
|
56
|
+
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -32,8 +32,24 @@ export declare class Pipeline<T = unknown> {
|
|
|
32
32
|
*/
|
|
33
33
|
static fromArray<T>(input: readonly T[]): Pipeline<T>;
|
|
34
34
|
static fromIterable<T>(input: Iterable<T> | AsyncIterable<T>): Pipeline<T>;
|
|
35
|
+
/**
|
|
36
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
37
|
+
* see `fromCloudStorage`.
|
|
38
|
+
*/
|
|
35
39
|
static fromNDJsonFile<T>(sourceFilePath: string): Pipeline<T>;
|
|
40
|
+
/**
|
|
41
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
42
|
+
* see `fromCloudStorage`.
|
|
43
|
+
*/
|
|
36
44
|
static fromFile(sourceFilePath: string): Pipeline<Uint8Array>;
|
|
45
|
+
/**
|
|
46
|
+
* Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
|
|
47
|
+
*
|
|
48
|
+
* Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
|
|
49
|
+
* Its default storage is used (see `getDefaultCloudStorage` there):
|
|
50
|
+
* it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
|
|
51
|
+
*/
|
|
52
|
+
static fromCloudStorage(url: string): Pipeline<Uint8Array>;
|
|
37
53
|
/**
|
|
38
54
|
* Limits the source Readable, but using `.take(limit)` on it.
|
|
39
55
|
* This is THE preferred way of limiting the source.
|
|
@@ -98,6 +114,10 @@ export declare class Pipeline<T = unknown> {
|
|
|
98
114
|
opt?: ZstdOptions): Pipeline<Uint8Array>;
|
|
99
115
|
zstdDecompress(this: Pipeline<Uint8Array>, opt?: ZstdOptions): Pipeline<Uint8Array>;
|
|
100
116
|
toArray(opt?: TransformOptions): Promise<T[]>;
|
|
117
|
+
/**
|
|
118
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
119
|
+
* see `fromCloudStorage` for the requirements.
|
|
120
|
+
*/
|
|
101
121
|
toFile(outputFilePath: string): Promise<void>;
|
|
102
122
|
/**
|
|
103
123
|
* level corresponds to zstd compression level (if filename ends with .zst),
|
|
@@ -105,6 +125,9 @@ export declare class Pipeline<T = unknown> {
|
|
|
105
125
|
* Default levels are:
|
|
106
126
|
* gzip: 6
|
|
107
127
|
* zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
|
|
128
|
+
*
|
|
129
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
130
|
+
* see `fromCloudStorage` for the requirements.
|
|
108
131
|
*/
|
|
109
132
|
toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void>;
|
|
110
133
|
to(destination: WritableTyped<T>): Promise<void>;
|
|
@@ -112,4 +135,8 @@ export declare class Pipeline<T = unknown> {
|
|
|
112
135
|
forEachSync(fn: AbortableMapper<T, void>, opt?: TransformMapSyncOptions<T, void> & TransformLogProgressOptions<T>): Promise<void>;
|
|
113
136
|
run(): Promise<void>;
|
|
114
137
|
private isGracefullyAborted;
|
|
138
|
+
/**
|
|
139
|
+
* Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
|
|
140
|
+
*/
|
|
141
|
+
private createFileWriteStream;
|
|
115
142
|
}
|
package/dist/stream/pipeline.js
CHANGED
|
@@ -5,6 +5,7 @@ import { createAbortableSignal } from '@naturalcycles/js-lib';
|
|
|
5
5
|
import { _passthroughPredicate } from '@naturalcycles/js-lib/types';
|
|
6
6
|
import { fs2 } from '../fs/fs2.js';
|
|
7
7
|
import { zip2 } from '../zip/zip2.js';
|
|
8
|
+
import { createCloudStorageReadStream, createCloudStorageWriteStream, isCloudStorageUrl, } from './cloudStorageStream.js';
|
|
8
9
|
import { createReadStreamAsNDJson } from './ndjson/createReadStreamAsNDJson.js';
|
|
9
10
|
import { transformJsonParse } from './ndjson/transformJsonParse.js';
|
|
10
11
|
import { transformToNDJson } from './ndjson/transformToNDJson.js';
|
|
@@ -62,6 +63,10 @@ export class Pipeline {
|
|
|
62
63
|
static fromIterable(input) {
|
|
63
64
|
return new Pipeline(Readable.from(input));
|
|
64
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
68
|
+
* see `fromCloudStorage`.
|
|
69
|
+
*/
|
|
65
70
|
static fromNDJsonFile(sourceFilePath) {
|
|
66
71
|
// Important that createReadStreamAsNDJson function is used
|
|
67
72
|
// (and not Pipeline set of individual transforms),
|
|
@@ -70,11 +75,27 @@ export class Pipeline {
|
|
|
70
75
|
// e.g like Pipeline.fromNDJsonFile().limitSource(limit)
|
|
71
76
|
return new Pipeline(createReadStreamAsNDJson(sourceFilePath));
|
|
72
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
80
|
+
* see `fromCloudStorage`.
|
|
81
|
+
*/
|
|
73
82
|
static fromFile(sourceFilePath) {
|
|
83
|
+
if (isCloudStorageUrl(sourceFilePath))
|
|
84
|
+
return Pipeline.fromCloudStorage(sourceFilePath);
|
|
74
85
|
return new Pipeline(fs2.createReadStream(sourceFilePath, {
|
|
75
86
|
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
76
87
|
}), false);
|
|
77
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
|
|
91
|
+
*
|
|
92
|
+
* Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
|
|
93
|
+
* Its default storage is used (see `getDefaultCloudStorage` there):
|
|
94
|
+
* it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
|
|
95
|
+
*/
|
|
96
|
+
static fromCloudStorage(url) {
|
|
97
|
+
return new Pipeline(createCloudStorageReadStream(url), false);
|
|
98
|
+
}
|
|
78
99
|
/**
|
|
79
100
|
* Limits the source Readable, but using `.take(limit)` on it.
|
|
80
101
|
* This is THE preferred way of limiting the source.
|
|
@@ -272,9 +293,12 @@ export class Pipeline {
|
|
|
272
293
|
await this.run();
|
|
273
294
|
return arr;
|
|
274
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
298
|
+
* see `fromCloudStorage` for the requirements.
|
|
299
|
+
*/
|
|
275
300
|
async toFile(outputFilePath) {
|
|
276
|
-
|
|
277
|
-
this.destination = fs2.createWriteStream(outputFilePath);
|
|
301
|
+
this.destination = await this.createFileWriteStream(outputFilePath);
|
|
278
302
|
await this.run();
|
|
279
303
|
}
|
|
280
304
|
/**
|
|
@@ -283,9 +307,11 @@ export class Pipeline {
|
|
|
283
307
|
* Default levels are:
|
|
284
308
|
* gzip: 6
|
|
285
309
|
* zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
|
|
310
|
+
*
|
|
311
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
312
|
+
* see `fromCloudStorage` for the requirements.
|
|
286
313
|
*/
|
|
287
314
|
async toNDJsonFile(outputFilePath, level) {
|
|
288
|
-
fs2.ensureFile(outputFilePath);
|
|
289
315
|
this.transforms.push(transformToNDJson());
|
|
290
316
|
if (outputFilePath.endsWith('.gz')) {
|
|
291
317
|
this.transforms.push(createGzip({
|
|
@@ -296,9 +322,7 @@ export class Pipeline {
|
|
|
296
322
|
else if (outputFilePath.endsWith('.zst')) {
|
|
297
323
|
this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)));
|
|
298
324
|
}
|
|
299
|
-
this.destination =
|
|
300
|
-
// highWaterMark: 64 * 1024, // no observed speedup
|
|
301
|
-
});
|
|
325
|
+
this.destination = await this.createFileWriteStream(outputFilePath);
|
|
302
326
|
await this.run();
|
|
303
327
|
}
|
|
304
328
|
async to(destination) {
|
|
@@ -353,4 +377,24 @@ export class Pipeline {
|
|
|
353
377
|
const { aborted, reason } = this.abortableSignal;
|
|
354
378
|
return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT;
|
|
355
379
|
}
|
|
380
|
+
/**
|
|
381
|
+
* Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
|
|
382
|
+
*/
|
|
383
|
+
async createFileWriteStream(outputFilePath) {
|
|
384
|
+
try {
|
|
385
|
+
if (isCloudStorageUrl(outputFilePath)) {
|
|
386
|
+
return await createCloudStorageWriteStream(outputFilePath);
|
|
387
|
+
}
|
|
388
|
+
fs2.ensureFile(outputFilePath);
|
|
389
|
+
return fs2.createWriteStream(outputFilePath, {
|
|
390
|
+
// highWaterMark: 64 * 1024, // no observed speedup
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
// The pipeline does not run, so nothing else closes the source, which can hold an open file
|
|
395
|
+
// or connection. It is destroyed without the error: nothing listens to its 'error' event here.
|
|
396
|
+
this.source.destroy();
|
|
397
|
+
throw err;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
356
400
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Readable, Transform } from 'node:stream';
|
|
2
|
+
import { _noop } from '@naturalcycles/js-lib/types';
|
|
2
3
|
/**
|
|
3
4
|
* Convenience function to create a Readable that can be pushed into (similar to RxJS Subject).
|
|
4
5
|
* Push `null` to it to complete (similar to RxJS `.complete()`).
|
|
@@ -43,6 +44,10 @@ export function createReadableFromAsync(fn) {
|
|
|
43
44
|
cb(null, chunk);
|
|
44
45
|
},
|
|
45
46
|
});
|
|
47
|
+
// `fn` or the source Readable can fail before any consumer is attached, and an 'error' event
|
|
48
|
+
// without a listener crashes the process. With this listener the error is kept in the stream instead,
|
|
49
|
+
// and the consumer gets it when it attaches.
|
|
50
|
+
transform.on('error', _noop);
|
|
46
51
|
void fn()
|
|
47
52
|
.then(readable => {
|
|
48
53
|
readable.on('error', err => transform.destroy(err)).pipe(transform);
|
|
@@ -71,15 +71,14 @@ export function transformThrottleByRSS(opt) {
|
|
|
71
71
|
clearTimeout(rssCheckTimer);
|
|
72
72
|
if (onPollTimeout === 'throw') {
|
|
73
73
|
lock.reject(new Error(`transformThrottleByRSS pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB`));
|
|
74
|
-
lock = undefined;
|
|
75
74
|
}
|
|
76
75
|
else {
|
|
77
76
|
// open-the-floodgates
|
|
78
77
|
logger.error(`${localTime.now().toPretty()} transformThrottleByRSS: pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB — DISABLING THROTTLE`);
|
|
79
78
|
disabled = true;
|
|
80
79
|
lock.resolve();
|
|
81
|
-
lock = undefined;
|
|
82
80
|
}
|
|
81
|
+
lock = undefined;
|
|
83
82
|
}
|
|
84
83
|
else {
|
|
85
84
|
logger.log(`${localTime.now().toPretty()} transformThrottleByRSS still paused: RSS ${_mb(rss)} > ${maxRSS} MB, rechecking in ${_ms(pollInterval)}`);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@naturalcycles/nodejs-lib",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "15.
|
|
4
|
+
"version": "15.148.0",
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"@naturalcycles/js-lib": "^15",
|
|
7
7
|
"@standard-schema/spec": "^1",
|
|
@@ -13,8 +13,17 @@
|
|
|
13
13
|
"tslib": "^2",
|
|
14
14
|
"yaml": "^2"
|
|
15
15
|
},
|
|
16
|
+
"peerDependencies": {
|
|
17
|
+
"@naturalcycles/cloud-storage-lib": "^2"
|
|
18
|
+
},
|
|
19
|
+
"peerDependenciesMeta": {
|
|
20
|
+
"@naturalcycles/cloud-storage-lib": {
|
|
21
|
+
"optional": true
|
|
22
|
+
}
|
|
23
|
+
},
|
|
16
24
|
"devDependencies": {
|
|
17
|
-
"@naturalcycles/
|
|
25
|
+
"@naturalcycles/cloud-storage-lib": "2.19.0",
|
|
26
|
+
"@naturalcycles/dev-lib": "0.0.0",
|
|
18
27
|
"typescript": "^7"
|
|
19
28
|
},
|
|
20
29
|
"exports": {
|
package/src/fs/json2env.ts
CHANGED
|
@@ -147,12 +147,8 @@ export function objectToShellExport(obj: AnyObject, prefix = ''): string {
|
|
|
147
147
|
|
|
148
148
|
return (
|
|
149
149
|
Object.entries(obj)
|
|
150
|
-
.
|
|
151
|
-
|
|
152
|
-
return `export ${prefix}${k}="${v}"`
|
|
153
|
-
}
|
|
154
|
-
})
|
|
155
|
-
.filter(Boolean)
|
|
150
|
+
.filter(([_k, v]) => v !== undefined && v !== null)
|
|
151
|
+
.map(([k, v]) => `export ${prefix}${k}="${v}"`)
|
|
156
152
|
.join('\n') + '\n'
|
|
157
153
|
) // trailing \n is important
|
|
158
154
|
}
|
|
@@ -178,12 +174,8 @@ export function objectToGithubActionsEnv(obj: AnyObject, prefix = ''): string {
|
|
|
178
174
|
|
|
179
175
|
return (
|
|
180
176
|
Object.entries(obj)
|
|
181
|
-
.
|
|
182
|
-
|
|
183
|
-
return `${prefix}${k}=${v}`
|
|
184
|
-
}
|
|
185
|
-
})
|
|
186
|
-
.filter(Boolean)
|
|
177
|
+
.filter(([_k, v]) => v !== undefined && v !== null)
|
|
178
|
+
.map(([k, v]) => `${prefix}${k}=${v}`)
|
|
187
179
|
.join('\n') + '\n'
|
|
188
180
|
) // trailing \n is important
|
|
189
181
|
}
|
package/src/glob/index.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import type { BinaryToTextEncoding } from 'node:crypto'
|
|
2
1
|
import { hash as cryptoHash } from 'node:crypto'
|
|
3
2
|
import type { Base64String, Base64UrlString } from '@naturalcycles/js-lib/types'
|
|
4
3
|
|
|
5
|
-
export function md5(s: string | Uint8Array, outputEncoding:
|
|
4
|
+
export function md5(s: string | Uint8Array, outputEncoding: BufferEncoding = 'hex'): string {
|
|
6
5
|
return hash(s, 'md5', outputEncoding)
|
|
7
6
|
}
|
|
8
7
|
|
|
@@ -10,10 +9,7 @@ export function md5AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer> {
|
|
|
10
9
|
return hashAsBuffer(s, 'md5')
|
|
11
10
|
}
|
|
12
11
|
|
|
13
|
-
export function sha256(
|
|
14
|
-
s: string | Uint8Array,
|
|
15
|
-
outputEncoding: BinaryToTextEncoding = 'hex',
|
|
16
|
-
): string {
|
|
12
|
+
export function sha256(s: string | Uint8Array, outputEncoding: BufferEncoding = 'hex'): string {
|
|
17
13
|
return hash(s, 'sha256', outputEncoding)
|
|
18
14
|
}
|
|
19
15
|
|
|
@@ -24,7 +20,7 @@ export function sha256AsBuffer(s: string | Uint8Array): Buffer<ArrayBuffer> {
|
|
|
24
20
|
export function hash(
|
|
25
21
|
s: string | Uint8Array,
|
|
26
22
|
algorithm: string,
|
|
27
|
-
outputEncoding:
|
|
23
|
+
outputEncoding: BufferEncoding = 'hex',
|
|
28
24
|
): string {
|
|
29
25
|
return cryptoHash(algorithm, s, outputEncoding)
|
|
30
26
|
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { PassThrough } from 'node:stream'
|
|
2
|
+
import type { Writable } from 'node:stream'
|
|
3
|
+
import { _assert } from '@naturalcycles/js-lib/error/assert.js'
|
|
4
|
+
import { _noop } from '@naturalcycles/js-lib/types'
|
|
5
|
+
import type { ReadableTyped, WritableTyped } from './stream.model.js'
|
|
6
|
+
|
|
7
|
+
const CLOUD_STORAGE_URL_PREFIX = 'gs://'
|
|
8
|
+
const CLOUD_STORAGE_LIB = '@naturalcycles/cloud-storage-lib'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Returns a binary Readable (objectMode=false) of the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
12
|
+
*
|
|
13
|
+
* The Readable is returned immediately, while the storage is loaded asynchronously and piped into it
|
|
14
|
+
* afterwards. It is the same approach as in `createReadableFromAsync`.
|
|
15
|
+
*
|
|
16
|
+
* The file is read from the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
17
|
+
* which is an optional peer dependency.
|
|
18
|
+
*/
|
|
19
|
+
export function createCloudStorageReadStream(url: string): ReadableTyped<Uint8Array> {
|
|
20
|
+
const { bucketName, filePath } = parseCloudStorageUrl(url)
|
|
21
|
+
const readable = new PassThrough()
|
|
22
|
+
|
|
23
|
+
// The read can fail before any consumer is attached, and an 'error' event without a listener
|
|
24
|
+
// crashes the process. With this listener the error is kept in the stream instead,
|
|
25
|
+
// and the consumer gets it when it attaches.
|
|
26
|
+
readable.on('error', _noop)
|
|
27
|
+
|
|
28
|
+
void getDefaultCloudStorage()
|
|
29
|
+
.then(async storage => {
|
|
30
|
+
await storage.getFileReadStream(bucketName, filePath).to(readable)
|
|
31
|
+
})
|
|
32
|
+
// If `readable` is already destroyed (e.g. the consumer stopped early) - this `destroy` does nothing
|
|
33
|
+
.catch(err => readable.destroy(err))
|
|
34
|
+
|
|
35
|
+
return readable
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns a binary Writable (objectMode=false) for the Cloud Storage file at `gs://bucket/path/to/file`.
|
|
40
|
+
*
|
|
41
|
+
* The file is written to the default storage of `@naturalcycles/cloud-storage-lib`,
|
|
42
|
+
* which is an optional peer dependency.
|
|
43
|
+
*/
|
|
44
|
+
export async function createCloudStorageWriteStream(
|
|
45
|
+
url: string,
|
|
46
|
+
): Promise<WritableTyped<Uint8Array>> {
|
|
47
|
+
const { bucketName, filePath } = parseCloudStorageUrl(url)
|
|
48
|
+
const storage = await getDefaultCloudStorage()
|
|
49
|
+
return storage.getFileWriteStream(bucketName, filePath)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseCloudStorageUrl(url: string): CloudStorageUrl {
|
|
53
|
+
_assert(isCloudStorageUrl(url), `Cloud Storage url should start with gs:// but got: ${url}`)
|
|
54
|
+
|
|
55
|
+
const [bucketName, ...pathParts] = url.slice(CLOUD_STORAGE_URL_PREFIX.length).split('/')
|
|
56
|
+
const filePath = pathParts.join('/')
|
|
57
|
+
|
|
58
|
+
_assert(
|
|
59
|
+
bucketName && filePath,
|
|
60
|
+
`Cloud Storage url should look like gs://bucket/path/to/file but got: ${url}`,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
return { bucketName, filePath }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Returns true for a Cloud Storage url: `gs://bucket/path/to/file`.
|
|
68
|
+
*/
|
|
69
|
+
export function isCloudStorageUrl(path: string): boolean {
|
|
70
|
+
return path.startsWith(CLOUD_STORAGE_URL_PREFIX)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function getDefaultCloudStorage(): Promise<DefaultCloudStorage> {
|
|
74
|
+
const lib = await importCloudStorageLib()
|
|
75
|
+
return await lib.getDefaultCloudStorage()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* cloud-storage-lib is an optional peer dependency, so it is imported lazily,
|
|
80
|
+
* only when a `gs://` url is actually used.
|
|
81
|
+
*/
|
|
82
|
+
async function importCloudStorageLib(): Promise<CloudStorageLib> {
|
|
83
|
+
try {
|
|
84
|
+
// The package name is passed as a variable, so that TypeScript does not resolve this import,
|
|
85
|
+
// see the comment at CloudStorageLib
|
|
86
|
+
return await import(CLOUD_STORAGE_LIB)
|
|
87
|
+
} catch (err) {
|
|
88
|
+
const { code, message } = err as NodeJS.ErrnoException
|
|
89
|
+
// The message names the missing package in quotes. If it names another package -
|
|
90
|
+
// cloud-storage-lib is installed, and one of its own imports is missing.
|
|
91
|
+
if (code !== 'ERR_MODULE_NOT_FOUND' || !message.includes(`'${CLOUD_STORAGE_LIB}'`)) throw err
|
|
92
|
+
|
|
93
|
+
throw new Error(
|
|
94
|
+
[
|
|
95
|
+
`Reading from and writing to gs:// urls requires ${CLOUD_STORAGE_LIB}.`,
|
|
96
|
+
'It is an optional peer dependency of @naturalcycles/nodejs-lib, and it is not installed.',
|
|
97
|
+
`Install it with: pnpm add ${CLOUD_STORAGE_LIB}`,
|
|
98
|
+
].join('\n'),
|
|
99
|
+
{ cause: err },
|
|
100
|
+
)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface CloudStorageUrl {
|
|
105
|
+
bucketName: string
|
|
106
|
+
filePath: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The part of `@naturalcycles/cloud-storage-lib` that is used here.
|
|
111
|
+
*
|
|
112
|
+
* It is declared here, and not imported from there, because cloud-storage-lib depends on nodejs-lib.
|
|
113
|
+
* Its types resolve to the `dist` folder of nodejs-lib, which would then be both an input and the output
|
|
114
|
+
* of the nodejs-lib build: "Cannot write file ... because it would overwrite input file".
|
|
115
|
+
*/
|
|
116
|
+
interface CloudStorageLib {
|
|
117
|
+
getDefaultCloudStorage: () => Promise<DefaultCloudStorage>
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The part of `CommonStorage` that is used here.
|
|
122
|
+
*/
|
|
123
|
+
interface DefaultCloudStorage {
|
|
124
|
+
/**
|
|
125
|
+
* Returns a `Pipeline<Uint8Array>`.
|
|
126
|
+
*/
|
|
127
|
+
getFileReadStream: (bucketName: string, filePath: string) => PipelineTo
|
|
128
|
+
getFileWriteStream: (bucketName: string, filePath: string) => WritableTyped<Uint8Array>
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
interface PipelineTo {
|
|
132
|
+
to: (destination: Writable) => Promise<void>
|
|
133
|
+
}
|
|
@@ -3,6 +3,7 @@ import { pipeline } from 'node:stream'
|
|
|
3
3
|
import { createUnzip, createZstdDecompress } from 'node:zlib'
|
|
4
4
|
import { _noop } from '@naturalcycles/js-lib/types'
|
|
5
5
|
import { fs2 } from '../../fs/fs2.js'
|
|
6
|
+
import { createCloudStorageReadStream, isCloudStorageUrl } from '../cloudStorageStream.js'
|
|
6
7
|
import type { ReadableTyped } from '../stream.model.js'
|
|
7
8
|
import { transformSplitOnNewline } from '../transform/transformSplit.js'
|
|
8
9
|
import { transformJsonParse } from './transformJsonParse.js'
|
|
@@ -20,16 +21,14 @@ import { transformJsonParse } from './transformJsonParse.js'
|
|
|
20
21
|
To add a Limit or Offset: just add .take() or .drop(), example:
|
|
21
22
|
|
|
22
23
|
createReadStreamAsNDJson().take(100)
|
|
24
|
+
|
|
25
|
+
inputPath can also be a Cloud Storage url (`gs://bucket/path/to/file`), see `Pipeline.fromCloudStorage`.
|
|
26
|
+
A Cloud Storage file with `Content-Encoding: gzip` metadata is already decompressed by the storage client.
|
|
27
|
+
Such a file should not have a `.gz` name, otherwise it is decompressed twice, which fails.
|
|
23
28
|
*/
|
|
24
29
|
|
|
25
30
|
export function createReadStreamAsNDJson<ROW = any>(inputPath: string): ReadableTyped<ROW> {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const streams: Readable[] = [
|
|
29
|
-
fs2.createReadStream(inputPath, {
|
|
30
|
-
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
31
|
-
}),
|
|
32
|
-
]
|
|
31
|
+
const streams: Readable[] = [createFileReadStream(inputPath)]
|
|
33
32
|
|
|
34
33
|
if (inputPath.endsWith('.gz')) {
|
|
35
34
|
streams.push(
|
|
@@ -59,3 +58,14 @@ export function createReadStreamAsNDJson<ROW = any>(inputPath: string): Readable
|
|
|
59
58
|
// ~5000 vs ~4000 rps !!!". Measured again on Node 24, it's the opposite: Readable.map costs ~1µs per row in promise machinery,
|
|
60
59
|
// transformJsonParse() is 1.5x (consumed via pipeline) to 1.75x (consumed via for-await) faster on ~180B rows.
|
|
61
60
|
}
|
|
61
|
+
|
|
62
|
+
function createFileReadStream(inputPath: string): Readable {
|
|
63
|
+
// A Cloud Storage file is not checked for existence upfront: if it is missing - the stream fails
|
|
64
|
+
if (isCloudStorageUrl(inputPath)) return createCloudStorageReadStream(inputPath)
|
|
65
|
+
|
|
66
|
+
fs2.requireFileToExist(inputPath)
|
|
67
|
+
|
|
68
|
+
return fs2.createReadStream(inputPath, {
|
|
69
|
+
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
70
|
+
})
|
|
71
|
+
}
|
package/src/stream/pipeline.ts
CHANGED
|
@@ -22,6 +22,11 @@ import type {
|
|
|
22
22
|
} from '@naturalcycles/js-lib/types'
|
|
23
23
|
import { fs2 } from '../fs/fs2.js'
|
|
24
24
|
import { zip2 } from '../zip/zip2.js'
|
|
25
|
+
import {
|
|
26
|
+
createCloudStorageReadStream,
|
|
27
|
+
createCloudStorageWriteStream,
|
|
28
|
+
isCloudStorageUrl,
|
|
29
|
+
} from './cloudStorageStream.js'
|
|
25
30
|
import { createReadStreamAsNDJson } from './ndjson/createReadStreamAsNDJson.js'
|
|
26
31
|
import { transformJsonParse } from './ndjson/transformJsonParse.js'
|
|
27
32
|
import { transformToNDJson } from './ndjson/transformToNDJson.js'
|
|
@@ -101,6 +106,10 @@ export class Pipeline<T = unknown> {
|
|
|
101
106
|
return new Pipeline(Readable.from(input))
|
|
102
107
|
}
|
|
103
108
|
|
|
109
|
+
/**
|
|
110
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
111
|
+
* see `fromCloudStorage`.
|
|
112
|
+
*/
|
|
104
113
|
static fromNDJsonFile<T>(sourceFilePath: string): Pipeline<T> {
|
|
105
114
|
// Important that createReadStreamAsNDJson function is used
|
|
106
115
|
// (and not Pipeline set of individual transforms),
|
|
@@ -110,7 +119,13 @@ export class Pipeline<T = unknown> {
|
|
|
110
119
|
return new Pipeline<T>(createReadStreamAsNDJson(sourceFilePath))
|
|
111
120
|
}
|
|
112
121
|
|
|
122
|
+
/**
|
|
123
|
+
* sourceFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
124
|
+
* see `fromCloudStorage`.
|
|
125
|
+
*/
|
|
113
126
|
static fromFile(sourceFilePath: string): Pipeline<Uint8Array> {
|
|
127
|
+
if (isCloudStorageUrl(sourceFilePath)) return Pipeline.fromCloudStorage(sourceFilePath)
|
|
128
|
+
|
|
114
129
|
return new Pipeline(
|
|
115
130
|
fs2.createReadStream(sourceFilePath, {
|
|
116
131
|
highWaterMark: 256 * 1024, // 64KB had no observed speedup over the default; 256KB is +6-12% end-to-end on ~9KB rows, neutral on ~180B rows, 1MB brings nothing more
|
|
@@ -119,6 +134,17 @@ export class Pipeline<T = unknown> {
|
|
|
119
134
|
)
|
|
120
135
|
}
|
|
121
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Reads the Cloud Storage file at the given url (`gs://bucket/path/to/file`) as a binary stream.
|
|
139
|
+
*
|
|
140
|
+
* Requires `@naturalcycles/cloud-storage-lib` to be installed, it is an optional peer dependency.
|
|
141
|
+
* Its default storage is used (see `getDefaultCloudStorage` there):
|
|
142
|
+
* it authenticates with Application Default Credentials, and it is in-memory when APP_ENV=test.
|
|
143
|
+
*/
|
|
144
|
+
static fromCloudStorage(url: string): Pipeline<Uint8Array> {
|
|
145
|
+
return new Pipeline(createCloudStorageReadStream(url), false)
|
|
146
|
+
}
|
|
147
|
+
|
|
122
148
|
/**
|
|
123
149
|
* Limits the source Readable, but using `.take(limit)` on it.
|
|
124
150
|
* This is THE preferred way of limiting the source.
|
|
@@ -374,9 +400,12 @@ export class Pipeline<T = unknown> {
|
|
|
374
400
|
return arr
|
|
375
401
|
}
|
|
376
402
|
|
|
403
|
+
/**
|
|
404
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
405
|
+
* see `fromCloudStorage` for the requirements.
|
|
406
|
+
*/
|
|
377
407
|
async toFile(outputFilePath: string): Promise<void> {
|
|
378
|
-
|
|
379
|
-
this.destination = fs2.createWriteStream(outputFilePath)
|
|
408
|
+
this.destination = await this.createFileWriteStream(outputFilePath)
|
|
380
409
|
await this.run()
|
|
381
410
|
}
|
|
382
411
|
|
|
@@ -386,9 +415,11 @@ export class Pipeline<T = unknown> {
|
|
|
386
415
|
* Default levels are:
|
|
387
416
|
* gzip: 6
|
|
388
417
|
* zlib: 3 (optimized for throughput, not size, may be larger than gzip at its default level)
|
|
418
|
+
*
|
|
419
|
+
* outputFilePath can be a local file path, or a Cloud Storage url (`gs://bucket/path/to/file`),
|
|
420
|
+
* see `fromCloudStorage` for the requirements.
|
|
389
421
|
*/
|
|
390
422
|
async toNDJsonFile(outputFilePath: string, level?: Integer): Promise<void> {
|
|
391
|
-
fs2.ensureFile(outputFilePath)
|
|
392
423
|
this.transforms.push(transformToNDJson())
|
|
393
424
|
if (outputFilePath.endsWith('.gz')) {
|
|
394
425
|
this.transforms.push(
|
|
@@ -400,9 +431,7 @@ export class Pipeline<T = unknown> {
|
|
|
400
431
|
} else if (outputFilePath.endsWith('.zst')) {
|
|
401
432
|
this.transforms.push(createZstdCompress(zip2.zstdLevelToOptions(level)))
|
|
402
433
|
}
|
|
403
|
-
this.destination =
|
|
404
|
-
// highWaterMark: 64 * 1024, // no observed speedup
|
|
405
|
-
})
|
|
434
|
+
this.destination = await this.createFileWriteStream(outputFilePath)
|
|
406
435
|
await this.run()
|
|
407
436
|
}
|
|
408
437
|
|
|
@@ -472,4 +501,26 @@ export class Pipeline<T = unknown> {
|
|
|
472
501
|
const { aborted, reason } = this.abortableSignal
|
|
473
502
|
return aborted && reason instanceof Error && reason.message === PIPELINE_GRACEFUL_ABORT
|
|
474
503
|
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Returns a Writable for a local file, or for a Cloud Storage file if outputFilePath is a `gs://` url.
|
|
507
|
+
*/
|
|
508
|
+
private async createFileWriteStream(outputFilePath: string): Promise<NodeJS.WritableStream> {
|
|
509
|
+
try {
|
|
510
|
+
if (isCloudStorageUrl(outputFilePath)) {
|
|
511
|
+
return await createCloudStorageWriteStream(outputFilePath)
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
fs2.ensureFile(outputFilePath)
|
|
515
|
+
|
|
516
|
+
return fs2.createWriteStream(outputFilePath, {
|
|
517
|
+
// highWaterMark: 64 * 1024, // no observed speedup
|
|
518
|
+
})
|
|
519
|
+
} catch (err) {
|
|
520
|
+
// The pipeline does not run, so nothing else closes the source, which can hold an open file
|
|
521
|
+
// or connection. It is destroyed without the error: nothing listens to its 'error' event here.
|
|
522
|
+
this.source.destroy()
|
|
523
|
+
throw err
|
|
524
|
+
}
|
|
525
|
+
}
|
|
475
526
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Readable, Transform } from 'node:stream'
|
|
2
2
|
import type { ReadableOptions } from 'node:stream'
|
|
3
|
+
import { _noop } from '@naturalcycles/js-lib/types'
|
|
3
4
|
import type { ReadableTyped } from '../stream.model.js'
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -56,6 +57,11 @@ export function createReadableFromAsync<T>(fn: () => Promise<ReadableTyped<T>>):
|
|
|
56
57
|
},
|
|
57
58
|
})
|
|
58
59
|
|
|
60
|
+
// `fn` or the source Readable can fail before any consumer is attached, and an 'error' event
|
|
61
|
+
// without a listener crashes the process. With this listener the error is kept in the stream instead,
|
|
62
|
+
// and the consumer gets it when it attaches.
|
|
63
|
+
transform.on('error', _noop)
|
|
64
|
+
|
|
59
65
|
void fn()
|
|
60
66
|
.then(readable => {
|
|
61
67
|
readable.on('error', err => transform.destroy(err)).pipe(transform)
|
|
@@ -130,7 +130,6 @@ export function transformThrottleByRSS<T>(
|
|
|
130
130
|
`transformThrottleByRSS pollTimeout of ${_ms(pollTimeout)} reached, RSS ${_mb(rss)} still > ${maxRSS} MB`,
|
|
131
131
|
),
|
|
132
132
|
)
|
|
133
|
-
lock = undefined
|
|
134
133
|
} else {
|
|
135
134
|
// open-the-floodgates
|
|
136
135
|
logger.error(
|
|
@@ -138,8 +137,8 @@ export function transformThrottleByRSS<T>(
|
|
|
138
137
|
)
|
|
139
138
|
disabled = true
|
|
140
139
|
lock!.resolve()
|
|
141
|
-
lock = undefined
|
|
142
140
|
}
|
|
141
|
+
lock = undefined
|
|
143
142
|
} else {
|
|
144
143
|
logger.log(
|
|
145
144
|
`${localTime.now().toPretty()} transformThrottleByRSS still paused: RSS ${_mb(rss)} > ${maxRSS} MB, rechecking in ${_ms(pollInterval)}`,
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// oxlint-disable-next-line no-restricted-globals -- the worker entry stays dependency-free
|
|
2
|
-
const started = Date.now()
|
|
3
1
|
import { inspect } from 'node:util'
|
|
4
2
|
import { workerData, parentPort } from 'node:worker_threads'
|
|
5
3
|
|
|
4
|
+
// oxlint-disable-next-line no-restricted-globals -- the worker entry stays dependency-free
|
|
5
|
+
const started = Date.now()
|
|
6
|
+
|
|
6
7
|
const { workerFile, workerIndex, logEvery = 1000, metric = 'worker', silent } = workerData || {}
|
|
7
8
|
|
|
8
9
|
// The worker entry stays dependency-free, so no `_assert` here
|
|
@@ -75,7 +75,7 @@ export function mergeJsonSchemaObjects<T1 extends AnyObject, T2 extends AnyObjec
|
|
|
75
75
|
|
|
76
76
|
// Merge `required`
|
|
77
77
|
s1.required.push(...s2.required)
|
|
78
|
-
s1.required = _uniq(s1.required).sort()
|
|
78
|
+
s1.required = _uniq(s1.required as string[]).sort()
|
|
79
79
|
|
|
80
80
|
// `additionalProperties` remains the same, unless s2 is a string map (schema-valued)
|
|
81
81
|
if (typeof s2.additionalProperties === 'object') {
|