|
| 1 | +import { createReadStream, createWriteStream, promises as fs } from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import readline from 'node:readline/promises'; |
| 4 | +import stream from 'node:stream/promises'; |
| 5 | + |
| 6 | +import { driver, EJSON, type mongodb, PARALLEL_DIRECTORY } from '../../driver.mjs'; |
| 7 | + |
| 8 | +export const taskSize = 565; |
| 9 | + |
| 10 | +let temporaryDirectory: string; |
| 11 | +let collection: mongodb.Collection; |
| 12 | + |
| 13 | +export async function beforeEach() { |
| 14 | + await driver.drop(); |
| 15 | + await driver.create(); |
| 16 | + |
| 17 | + temporaryDirectory = path.resolve(PARALLEL_DIRECTORY, 'downloads'); |
| 18 | + await fs.rm(temporaryDirectory, { recursive: true, force: true }); |
| 19 | + await fs.mkdir(temporaryDirectory); |
| 20 | + |
| 21 | + collection = driver.client.db(driver.DB_NAME).collection(driver.COLLECTION_NAME); |
| 22 | + |
| 23 | + const directory = path.resolve(PARALLEL_DIRECTORY, 'ldjson_multi'); |
| 24 | + |
| 25 | + const files = await fs.readdir(directory); |
| 26 | + const uploads = files.map(async file => { |
| 27 | + const fileStream = createReadStream(path.resolve(directory, file)); |
| 28 | + const lineReader = readline.createInterface({ |
| 29 | + input: fileStream |
| 30 | + }); |
| 31 | + |
| 32 | + const operations = []; |
| 33 | + |
| 34 | + for await (const line of lineReader) { |
| 35 | + operations.push({ |
| 36 | + insertOne: { |
| 37 | + document: JSON.parse(line) |
| 38 | + } |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + fileStream.close(); |
| 43 | + lineReader.close(); |
| 44 | + |
| 45 | + return await collection.bulkWrite(operations); |
| 46 | + }); |
| 47 | + |
| 48 | + await Promise.all(uploads); |
| 49 | +} |
| 50 | + |
| 51 | +export async function run() { |
| 52 | + const skips = Array.from({ length: 100 }, (_, index) => index * 5000); |
| 53 | + |
| 54 | + const promises = skips.map(async skip => { |
| 55 | + const documentCursor = collection.find({}, { skip, limit: 5000 }); |
| 56 | + documentCursor.map(doc => EJSON.stringify(doc)); |
| 57 | + const outputStream = createWriteStream(path.resolve(temporaryDirectory, `tmp-${skip}.txt`)); |
| 58 | + return stream.pipeline(documentCursor.stream(), outputStream); |
| 59 | + }); |
| 60 | + |
| 61 | + await Promise.all(promises); |
| 62 | +} |
| 63 | + |
| 64 | +export async function afterEach() { |
| 65 | + await fs.rm(temporaryDirectory, { recursive: true, force: true }); |
| 66 | +} |
| 67 | + |
| 68 | +export async function after() { |
| 69 | + await driver.drop(); |
| 70 | + await driver.close(); |
| 71 | +} |
0 commit comments