"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataStoreLevel = void 0;
var blockstore_level_js_1 = require("./blockstore-level.js");
var level_wrapper_js_1 = require("./level-wrapper.js");
var ipfs_unixfs_exporter_1 = require("ipfs-unixfs-exporter");
var ipfs_unixfs_importer_1 = require("ipfs-unixfs-importer");
var readable_stream_1 = require("readable-stream");
// `BlockstoreLevel` doesn't support being a `Set` (i.e. it always requires a value), so use a placeholder instead.
var 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.
 */
var DataStoreLevel = /** @class */ (function () {
    function DataStoreLevel(config) {
        if (config === void 0) { config = {}; }
        this.config = __assign({ blockstoreLocation: 'data/DATASTORE', createLevelDatabase: level_wrapper_js_1.createLevelDatabase }, config);
        this.blockstore = new blockstore_level_js_1.BlockstoreLevel({
            location: this.config.blockstoreLocation,
            createLevelDatabase: this.config.createLevelDatabase,
        });
    }
    DataStoreLevel.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.blockstore.open()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DataStoreLevel.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.blockstore.close()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DataStoreLevel.prototype.put = function (tenant, messageCid, dataCid, dataStream) {
        var e_1, _a;
        var _b, _c;
        return __awaiter(this, void 0, void 0, function () {
            var blockstoreForReferenceCounting, blockstoreForData, asyncDataBlocks, dataDagRoot, asyncDataBlocks_1, asyncDataBlocks_1_1, e_1_1;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0: return [4 /*yield*/, this.getBlockstoreForReferenceCounting(tenant, dataCid)];
                    case 1:
                        blockstoreForReferenceCounting = _d.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.put(messageCid, PLACEHOLDER_VALUE)];
                    case 2:
                        _d.sent();
                        return [4 /*yield*/, this.getBlockstoreForStoringData(tenant, dataCid)];
                    case 3:
                        blockstoreForData = _d.sent();
                        asyncDataBlocks = (0, ipfs_unixfs_importer_1.importer)([{ content: dataStream }], blockstoreForData, { cidVersion: 1 });
                        _d.label = 4;
                    case 4:
                        _d.trys.push([4, 9, 10, 15]);
                        asyncDataBlocks_1 = __asyncValues(asyncDataBlocks);
                        _d.label = 5;
                    case 5: return [4 /*yield*/, asyncDataBlocks_1.next()];
                    case 6:
                        if (!(asyncDataBlocks_1_1 = _d.sent(), !asyncDataBlocks_1_1.done)) return [3 /*break*/, 8];
                        dataDagRoot = asyncDataBlocks_1_1.value;
                        ;
                        _d.label = 7;
                    case 7: return [3 /*break*/, 5];
                    case 8: return [3 /*break*/, 15];
                    case 9:
                        e_1_1 = _d.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 15];
                    case 10:
                        _d.trys.push([10, , 13, 14]);
                        if (!(asyncDataBlocks_1_1 && !asyncDataBlocks_1_1.done && (_a = asyncDataBlocks_1.return))) return [3 /*break*/, 12];
                        return [4 /*yield*/, _a.call(asyncDataBlocks_1)];
                    case 11:
                        _d.sent();
                        _d.label = 12;
                    case 12: return [3 /*break*/, 14];
                    case 13:
                        if (e_1) throw e_1.error;
                        return [7 /*endfinally*/];
                    case 14: return [7 /*endfinally*/];
                    case 15: return [2 /*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)
                        }];
                }
            });
        });
    };
    DataStoreLevel.prototype.get = function (tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function () {
            var blockstoreForReferenceCounting, allowed, blockstoreForData, exists, dataDagRoot, contentIterator, dataStream, dataSize;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getBlockstoreForReferenceCounting(tenant, dataCid)];
                    case 1:
                        blockstoreForReferenceCounting = _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.has(messageCid)];
                    case 2:
                        allowed = _a.sent();
                        if (!allowed) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, this.getBlockstoreForStoringData(tenant, dataCid)];
                    case 3:
                        blockstoreForData = _a.sent();
                        return [4 /*yield*/, blockstoreForData.has(dataCid)];
                    case 4:
                        exists = _a.sent();
                        if (!exists) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, (0, ipfs_unixfs_exporter_1.exporter)(dataCid, blockstoreForData)];
                    case 5:
                        dataDagRoot = _a.sent();
                        contentIterator = dataDagRoot.content();
                        dataStream = new readable_stream_1.Readable({
                            read: function () {
                                return __awaiter(this, void 0, void 0, function () {
                                    var result;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0: return [4 /*yield*/, contentIterator.next()];
                                            case 1:
                                                result = _a.sent();
                                                if (result.done) {
                                                    this.push(null); // end the stream
                                                }
                                                else {
                                                    this.push(result.value);
                                                }
                                                return [2 /*return*/];
                                        }
                                    });
                                });
                            }
                        });
                        dataSize = dataDagRoot.size;
                        if (dataDagRoot.type === 'file' || dataDagRoot.type === 'directory') {
                            dataSize = dataDagRoot.unixfs.fileSize();
                        }
                        return [2 /*return*/, {
                                dataCid: String(dataDagRoot.cid),
                                dataSize: Number(dataSize),
                                dataStream: dataStream,
                            }];
                }
            });
        });
    };
    DataStoreLevel.prototype.associate = function (tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function () {
            var blockstoreForReferenceCounting, noExistingReference, blockstoreForData, dataExists, dataDagRoot, dataSize;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getBlockstoreForReferenceCounting(tenant, dataCid)];
                    case 1:
                        blockstoreForReferenceCounting = _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.isEmpty()];
                    case 2:
                        noExistingReference = _a.sent();
                        if (noExistingReference) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, this.getBlockstoreForStoringData(tenant, dataCid)];
                    case 3:
                        blockstoreForData = _a.sent();
                        return [4 /*yield*/, blockstoreForData.has(dataCid)];
                    case 4:
                        dataExists = _a.sent();
                        if (!dataExists) {
                            return [2 /*return*/, undefined];
                        }
                        return [4 /*yield*/, blockstoreForReferenceCounting.put(messageCid, PLACEHOLDER_VALUE)];
                    case 5:
                        _a.sent();
                        return [4 /*yield*/, (0, ipfs_unixfs_exporter_1.exporter)(dataCid, blockstoreForData)];
                    case 6:
                        dataDagRoot = _a.sent();
                        dataSize = dataDagRoot.size;
                        if (dataDagRoot.type === 'file' || dataDagRoot.type === 'directory') {
                            dataSize = dataDagRoot.unixfs.fileSize();
                        }
                        return [2 /*return*/, {
                                dataCid: String(dataDagRoot.cid),
                                dataSize: Number(dataSize)
                            }];
                }
            });
        });
    };
    DataStoreLevel.prototype.delete = function (tenant, messageCid, dataCid) {
        return __awaiter(this, void 0, void 0, function () {
            var blockstoreForReferenceCounting, wasLastReference, blockstoreForData;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getBlockstoreForReferenceCounting(tenant, dataCid)];
                    case 1:
                        blockstoreForReferenceCounting = _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.delete(messageCid)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.isEmpty()];
                    case 3:
                        wasLastReference = _a.sent();
                        if (!wasLastReference) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, this.getBlockstoreForStoringData(tenant, dataCid)];
                    case 4:
                        blockstoreForData = _a.sent();
                        return [4 /*yield*/, blockstoreForData.clear()];
                    case 5:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Deletes everything in the store. Mainly used in tests.
     */
    DataStoreLevel.prototype.clear = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.blockstore.clear()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DataStoreLevel.prototype.dump = function () {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        console.group('blockstore');
                        return [4 /*yield*/, ((_b = (_a = this.blockstore)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a))];
                    case 1:
                        _c.sent();
                        console.groupEnd();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Gets the blockstore used for reference counting purposes for the given `dataCid` in the given `tenant`.
     */
    DataStoreLevel.prototype.getBlockstoreForReferenceCounting = function (tenant, dataCid) {
        return __awaiter(this, void 0, void 0, function () {
            var referenceCountingPartitionName, blockstoreForReferenceCounting, blockstoreForReferenceCountingByTenant, blockstoreForReferenceCountingDataCid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        referenceCountingPartitionName = 'references';
                        return [4 /*yield*/, this.blockstore.partition(referenceCountingPartitionName)];
                    case 1:
                        blockstoreForReferenceCounting = _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCounting.partition(tenant)];
                    case 2:
                        blockstoreForReferenceCountingByTenant = _a.sent();
                        return [4 /*yield*/, blockstoreForReferenceCountingByTenant.partition(dataCid)];
                    case 3:
                        blockstoreForReferenceCountingDataCid = _a.sent();
                        return [2 /*return*/, blockstoreForReferenceCountingDataCid];
                }
            });
        });
    };
    /**
     * Gets the blockstore used for storing data for the given `dataCid` in the given `tenant`.
     */
    DataStoreLevel.prototype.getBlockstoreForStoringData = function (tenant, dataCid) {
        return __awaiter(this, void 0, void 0, function () {
            var dataPartitionName, blockstoreForData, blockstoreOfGivenTenant, blockstoreOfGivenDataCid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        dataPartitionName = 'data';
                        return [4 /*yield*/, this.blockstore.partition(dataPartitionName)];
                    case 1:
                        blockstoreForData = _a.sent();
                        return [4 /*yield*/, blockstoreForData.partition(tenant)];
                    case 2:
                        blockstoreOfGivenTenant = _a.sent();
                        return [4 /*yield*/, blockstoreOfGivenTenant.partition(dataCid)];
                    case 3:
                        blockstoreOfGivenDataCid = _a.sent();
                        return [2 /*return*/, blockstoreOfGivenDataCid];
                }
            });
        });
    };
    return DataStoreLevel;
}());
exports.DataStoreLevel = DataStoreLevel;
//# sourceMappingURL=data-store-level.js.map