import { DbWorker } from './workers/DbWorker.js';
import { DECODER, readInt32 } from '@saulx/utils';
import native from '../native.js';
export class IoWorker extends DbWorker {
    constructor(address, db) {
        const onExit = (_code) => {
            this.db.ioWorker = new IoWorker(address, db);
        };
        super(address, db, onExit, 'io_worker.js');
    }
    handleMsg(_buf) {
    }
    cb = (resolve) => {
        this.db.activeReaders++;
        this.resolvers.push((r) => {
            this.db.activeReaders--;
            resolve(r);
            //this.db.onQueryEnd()
        });
    };
    /**
     * Save given blocks and return errors and hashes in an array.
     * @returns [[4 bytes err], [16 bytes hash]][] with the same length as blocks.
     */
    async saveBlocks(blocks) {
        const job = {
            type: 'save',
            blocks,
        };
        this.channel.postMessage(job);
        const resBufP = new Promise(this.cb);
        resBufP.then(() => this.db.onQueryEnd());
        return resBufP;
    }
    async loadBlock(filepath) {
        const job = {
            type: 'load',
            filepath,
        };
        const resBuf = await this.call(job);
        if (resBuf.length) {
            throw new Error(DECODER.decode(resBuf));
        }
    }
    /**
     * Save a block and discard it from memory "atomically".
     * Note that this worker doesn't give any protection from other threads
     * accessing the block concurrently, and it must be coordinated in the
     * main thread.
     */
    async unloadBlock(filepath, typeId, start) {
        const job = {
            type: 'unload',
            filepath,
            typeId,
            start,
        };
        const resBuf = await this.call(job);
        const err = readInt32(resBuf, 0);
        if (err) {
            throw new Error(native.selvaStrerror(err));
        }
        // Note that this shares the original buffer which may not be 100% optimal,
        // as the first 4 bytes are no longer needed.
        return new Uint8Array(resBuf.buffer, 4);
    }
}
//# sourceMappingURL=IoWorker.js.map