"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); }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventLogLevel = void 0;
var ulid_1 = require("ulid");
var level_wrapper_js_1 = require("../store/level-wrapper.js");
var WATERMARKS_SUBLEVEL_NAME = 'watermarks';
var CIDS_SUBLEVEL_NAME = 'cids';
var EventLogLevel = /** @class */ (function () {
    function EventLogLevel(config) {
        this.config = __assign({ location: 'data/EVENTLOG', createLevelDatabase: level_wrapper_js_1.createLevelDatabase }, config);
        this.db = new level_wrapper_js_1.LevelWrapper(__assign(__assign({}, this.config), { valueEncoding: 'utf8' }));
        this.ulid = (0, ulid_1.monotonicFactory)();
    }
    EventLogLevel.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.open()];
            });
        });
    };
    EventLogLevel.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.close()];
            });
        });
    };
    EventLogLevel.prototype.clear = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.clear()];
            });
        });
    };
    EventLogLevel.prototype.append = function (tenant, messageCid) {
        return __awaiter(this, void 0, void 0, function () {
            var tenantEventLog, watermarkLog, cidLog, watermark;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.db.partition(tenant)];
                    case 1:
                        tenantEventLog = _a.sent();
                        return [4 /*yield*/, tenantEventLog.partition(WATERMARKS_SUBLEVEL_NAME)];
                    case 2:
                        watermarkLog = _a.sent();
                        return [4 /*yield*/, tenantEventLog.partition(CIDS_SUBLEVEL_NAME)];
                    case 3:
                        cidLog = _a.sent();
                        watermark = this.ulid();
                        return [4 /*yield*/, watermarkLog.put(watermark, messageCid)];
                    case 4:
                        _a.sent();
                        return [4 /*yield*/, cidLog.put(messageCid, watermark)];
                    case 5:
                        _a.sent();
                        return [2 /*return*/, watermark];
                }
            });
        });
    };
    EventLogLevel.prototype.getEvents = function (tenant, options) {
        var e_1, _a;
        return __awaiter(this, void 0, void 0, function () {
            var tenantEventLog, watermarkLog, events, _b, _c, _d, key, value, event_1, e_1_1;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0: return [4 /*yield*/, this.db.partition(tenant)];
                    case 1:
                        tenantEventLog = _e.sent();
                        return [4 /*yield*/, tenantEventLog.partition(WATERMARKS_SUBLEVEL_NAME)];
                    case 2:
                        watermarkLog = _e.sent();
                        events = [];
                        _e.label = 3;
                    case 3:
                        _e.trys.push([3, 8, 9, 14]);
                        _b = __asyncValues(watermarkLog.iterator(options));
                        _e.label = 4;
                    case 4: return [4 /*yield*/, _b.next()];
                    case 5:
                        if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 7];
                        _d = __read(_c.value, 2), key = _d[0], value = _d[1];
                        event_1 = { watermark: key, messageCid: value };
                        events.push(event_1);
                        _e.label = 6;
                    case 6: return [3 /*break*/, 4];
                    case 7: return [3 /*break*/, 14];
                    case 8:
                        e_1_1 = _e.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 14];
                    case 9:
                        _e.trys.push([9, , 12, 13]);
                        if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 11];
                        return [4 /*yield*/, _a.call(_b)];
                    case 10:
                        _e.sent();
                        _e.label = 11;
                    case 11: return [3 /*break*/, 13];
                    case 12:
                        if (e_1) throw e_1.error;
                        return [7 /*endfinally*/];
                    case 13: return [7 /*endfinally*/];
                    case 14: return [2 /*return*/, events];
                }
            });
        });
    };
    EventLogLevel.prototype.deleteEventsByCid = function (tenant, cids) {
        return __awaiter(this, void 0, void 0, function () {
            var tenantEventLog, cidLog, ops, promises, cids_1, cids_1_1, cid, promise, numEventsDeleted, watermarks, watermarks_1, watermarks_1_1, watermark, watermarkLog;
            var e_2, _a, e_3, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (cids.length === 0) {
                            return [2 /*return*/, 0];
                        }
                        return [4 /*yield*/, this.db.partition(tenant)];
                    case 1:
                        tenantEventLog = _c.sent();
                        return [4 /*yield*/, tenantEventLog.partition(CIDS_SUBLEVEL_NAME)];
                    case 2:
                        cidLog = _c.sent();
                        ops = [];
                        promises = [];
                        try {
                            for (cids_1 = __values(cids), cids_1_1 = cids_1.next(); !cids_1_1.done; cids_1_1 = cids_1.next()) {
                                cid = cids_1_1.value;
                                ops.push({ type: 'del', key: cid });
                                promise = cidLog.get(cid).catch(function (e) { return e; });
                                promises.push(promise);
                            }
                        }
                        catch (e_2_1) { e_2 = { error: e_2_1 }; }
                        finally {
                            try {
                                if (cids_1_1 && !cids_1_1.done && (_a = cids_1.return)) _a.call(cids_1);
                            }
                            finally { if (e_2) throw e_2.error; }
                        }
                        return [4 /*yield*/, cidLog.batch(ops)];
                    case 3:
                        _c.sent();
                        ops = [];
                        numEventsDeleted = 0;
                        return [4 /*yield*/, Promise.all(promises)];
                    case 4:
                        watermarks = _c.sent();
                        try {
                            for (watermarks_1 = __values(watermarks), watermarks_1_1 = watermarks_1.next(); !watermarks_1_1.done; watermarks_1_1 = watermarks_1.next()) {
                                watermark = watermarks_1_1.value;
                                if (watermark) {
                                    ops.push({ type: 'del', key: watermark });
                                    numEventsDeleted += 1;
                                }
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (watermarks_1_1 && !watermarks_1_1.done && (_b = watermarks_1.return)) _b.call(watermarks_1);
                            }
                            finally { if (e_3) throw e_3.error; }
                        }
                        return [4 /*yield*/, tenantEventLog.partition('watermarks')];
                    case 5:
                        watermarkLog = _c.sent();
                        return [4 /*yield*/, watermarkLog.batch(ops)];
                    case 6:
                        _c.sent();
                        return [2 /*return*/, numEventsDeleted];
                }
            });
        });
    };
    EventLogLevel.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('db');
                        return [4 /*yield*/, ((_b = (_a = this.db)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a))];
                    case 1:
                        _c.sent();
                        console.groupEnd();
                        return [2 /*return*/];
                }
            });
        });
    };
    return EventLogLevel;
}());
exports.EventLogLevel = EventLogLevel;
//# sourceMappingURL=event-log-level.js.map