Files
xen-orchestra/packages/vhd-lib/createVhdDirectoryFromStream.js
2022-06-18 11:12:30 +02:00

62 lines
1.7 KiB
JavaScript

'use strict'
const { parseVhdStream } = require('./parseVhdStream.js')
const { VhdDirectory } = require('./Vhd/VhdDirectory.js')
const { Disposable } = require('promise-toolbox')
const { asyncEach } = require('@vates/async-each')
const buildVhd = Disposable.wrap(async function* (
handler,
path,
inputStream,
{ concurrency, compression, encryption }
) {
const vhd = yield VhdDirectory.create(handler, path, { compression, encryption })
await asyncEach(
parseVhdStream(inputStream),
async function (item) {
switch (item.type) {
case 'footer':
vhd.footer = item.footer
break
case 'header':
vhd.header = item.header
break
case 'parentLocator':
await vhd.writeParentLocator({ ...item, data: item.buffer })
break
case 'block':
await vhd.writeEntireBlock(item)
break
case 'bat':
// it exists but I don't care
break
default:
throw new Error(`unhandled type of block generated by parser : ${item.type} while generating ${path}`)
}
},
{
concurrency,
}
)
await Promise.all([vhd.writeFooter(), vhd.writeHeader(), vhd.writeBlockAllocationTable()])
})
exports.createVhdDirectoryFromStream = async function createVhdDirectoryFromStream(
handler,
path,
inputStream,
{ validator, concurrency = 16, compression, encryption } = {}
) {
try {
await buildVhd(handler, path, inputStream, { concurrency, compression, encryption })
if (validator !== undefined) {
await validator.call(this, path)
}
} catch (error) {
// cleanup on error
await handler.rmtree(path)
throw error
}
}