var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
import { BlockstoreLevel } from './blockstore-level.js';
import { createLevelDatabase } from './level-wrapper.js';
import { exporter } from 'ipfs-unixfs-exporter';
import { importer } from 'ipfs-unixfs-importer';
import { Readable } from 'readable-stream';
// `BlockstoreLevel` doesn't support being a `Set` (i.e. it always requires a value), so use a placeholder instead.
const PLACEHOLDER_VALUE = new Uint8Array();
/**
 * A simple implementation of {@link DataStore} that works in both the browser and server-side.
 * Leverages LevelDB under the hood.
 *
 * It has the following structure (`+` represents a sublevel and `->` represents a key->value pair):
 *   'data' + <tenant> + <dataCid> -> <data>
 *   'references' + <tenant> + <dataCid> + <messageCid> -> PLACEHOLDER_VALUE
 *
 * This allows for the <data> to be shared for everything that uses the same <dataCid> while also making
 * sure that the <data> can only be deleted if there are no <messageCid> for any <tenant> still using it.
 */
export class DataStoreLevel {
    constructor(config = {}) {
        this.config = Object.assign({ blockstoreLocation: 'data/DATASTORE', createLevelDatabase }, config);
        this.blockstore = new BlockstoreLevel({
            location: this.config.blockstoreLocation,
            createLevelDatabase: this.config.createLevelDatabase,
        });
    }
    open() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.open();
        });
    }
    close() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.close();
        });
    }
    put(tenant, messageCid, dataCid, dataStream) {
        var e_1, _a;
        var _b, _c;
        return __awaiter(this, void 0, void 0, function* () {
            const blockstoreForReferenceCounting = yield this.getBlockstoreForReferenceCounting(tenant, dataCid);
            yield blockstoreForReferenceCounting.put(messageCid, PLACEHOLDER_VALUE);
            const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, dataCid);
            const asyncDataBlocks = importer([{ content: dataStream }], blockstoreForData, { cidVersion: 1 });
            // NOTE: the last block contains the root CID as well as info to derive the data size
            let dataDagRoot;
            try {
                for (var asyncDataBlocks_1 = __asyncValues(asyncDataBlocks), asyncDataBlocks_1_1; asyncDataBlocks_1_1 = yield asyncDataBlocks_1.next(), !asyncDataBlocks_1_1.done;) {
                    dataDagRoot = asyncDataBlocks_1_1.value;
                    ;
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (asyncDataBlocks_1_1 && !asyncDataBlocks_1_1.done && (_a = asyncDataBlocks_1.return)) yield _a.call(asyncDataBlocks_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return {
                dataCid: String(dataDagRoot.cid),
                dataSize: Number((_c = (_b = dataDagRoot.unixfs) === null || _b === void 0 ? void 0 : _b.fileSize()) !== null && _c !== void 0 ? _c : dataDagRoot.size)
            };
        });
    }
    get(tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const blockstoreForReferenceCounting = yield this.getBlockstoreForReferenceCounting(tenant, dataCid);
            const allowed = yield blockstoreForReferenceCounting.has(messageCid);
            if (!allowed) {
                return undefined;
            }
            const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, dataCid);
            const exists = yield blockstoreForData.has(dataCid);
            if (!exists) {
                return undefined;
            }
            // data is chunked into dag-pb unixfs blocks. re-inflate the chunks.
            const dataDagRoot = yield exporter(dataCid, blockstoreForData);
            const contentIterator = dataDagRoot.content();
            const dataStream = new Readable({
                read() {
                    return __awaiter(this, void 0, void 0, function* () {
                        const result = yield contentIterator.next();
                        if (result.done) {
                            this.push(null); // end the stream
                        }
                        else {
                            this.push(result.value);
                        }
                    });
                }
            });
            let dataSize = dataDagRoot.size;
            if (dataDagRoot.type === 'file' || dataDagRoot.type === 'directory') {
                dataSize = dataDagRoot.unixfs.fileSize();
            }
            return {
                dataCid: String(dataDagRoot.cid),
                dataSize: Number(dataSize),
                dataStream,
            };
        });
    }
    associate(tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const blockstoreForReferenceCounting = yield this.getBlockstoreForReferenceCounting(tenant, dataCid);
            const noExistingReference = yield blockstoreForReferenceCounting.isEmpty();
            if (noExistingReference) {
                return undefined;
            }
            const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, dataCid);
            const dataExists = yield blockstoreForData.has(dataCid);
            if (!dataExists) {
                return undefined;
            }
            yield blockstoreForReferenceCounting.put(messageCid, PLACEHOLDER_VALUE);
            const dataDagRoot = yield exporter(dataCid, blockstoreForData);
            let dataSize = dataDagRoot.size;
            if (dataDagRoot.type === 'file' || dataDagRoot.type === 'directory') {
                dataSize = dataDagRoot.unixfs.fileSize();
            }
            return {
                dataCid: String(dataDagRoot.cid),
                dataSize: Number(dataSize)
            };
        });
    }
    delete(tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const blockstoreForReferenceCounting = yield this.getBlockstoreForReferenceCounting(tenant, dataCid);
            yield blockstoreForReferenceCounting.delete(messageCid);
            const wasLastReference = yield blockstoreForReferenceCounting.isEmpty();
            if (!wasLastReference) {
                return;
            }
            const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, dataCid);
            yield blockstoreForData.clear();
        });
    }
    /**
     * Deletes everything in the store. Mainly used in tests.
     */
    clear() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.blockstore.clear();
        });
    }
    dump() {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            console.group('blockstore');
            yield ((_b = (_a = this.blockstore)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a));
            console.groupEnd();
        });
    }
    /**
     * Gets the blockstore used for reference counting purposes for the given `dataCid` in the given `tenant`.
     */
    getBlockstoreForReferenceCounting(tenant, dataCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const referenceCountingPartitionName = 'references';
            const blockstoreForReferenceCounting = yield this.blockstore.partition(referenceCountingPartitionName);
            const blockstoreForReferenceCountingByTenant = yield blockstoreForReferenceCounting.partition(tenant);
            const blockstoreForReferenceCountingDataCid = yield blockstoreForReferenceCountingByTenant.partition(dataCid);
            return blockstoreForReferenceCountingDataCid;
        });
    }
    /**
     * Gets the blockstore used for storing data for the given `dataCid` in the given `tenant`.
     */
    getBlockstoreForStoringData(tenant, dataCid) {
        return __awaiter(this, void 0, void 0, function* () {
            const dataPartitionName = 'data';
            const blockstoreForData = yield this.blockstore.partition(dataPartitionName);
            const blockstoreOfGivenTenant = yield blockstoreForData.partition(tenant);
            const blockstoreOfGivenDataCid = yield blockstoreOfGivenTenant.partition(dataCid);
            return blockstoreOfGivenDataCid;
        });
    }
}
//# sourceMappingURL=data-store-level.js.map