@configurator/ravendb
Version:
RavenDB client for Node.js
91 lines • 3.34 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HiloIdGenerator = void 0;
const DateUtil_1 = require("../../Utility/DateUtil");
const HiloReturnCommand_1 = require("./Commands/HiloReturnCommand");
const NextHiloCommand_1 = require("./Commands/NextHiloCommand");
const HiloRangeValue_1 = require("./HiloRangeValue");
const Lazy_1 = require("../Lazy");
class HiloIdGenerator {
constructor(tag, store, dbName, identityPartsSeparator) {
this._prefix = null;
this._lastBatchSize = 0;
this._serverTag = null;
this._store = store;
this._tag = tag;
this._dbName = dbName;
this._identityPartsSeparator = identityPartsSeparator;
this._lastRangeAt = DateUtil_1.DateUtil.zeroDate();
this._range = new HiloRangeValue_1.HiloRangeValue(1, 0, null);
}
_getDocumentIdFromId(nextId) {
return this._prefix + nextId + "-" + this._serverTag;
}
async generateDocumentId(entity) {
const nextId = await this.getNextId();
return this._getDocumentIdFromId(nextId.id);
}
async getNextId() {
while (true) {
const current = this._nextRangeTask;
const range = this._range;
const id = range.increment();
if (id <= range.maxId) {
return {
id,
serverTag: range.serverTag
};
}
try {
await current.getValue();
if (range !== this._range) {
continue;
}
}
catch (e) {
}
const maybeNextTask = new Lazy_1.Lazy(() => this._getNextRange());
let changed = false;
if (this._nextRangeTask === current) {
changed = true;
this._nextRangeTask = maybeNextTask;
}
if (changed) {
await maybeNextTask.getValue();
continue;
}
try {
await this._nextRangeTask.getValue();
}
catch (e) {
}
}
}
async nextId() {
const result = await this.getNextId();
return result.id;
}
async _getNextRange() {
const hiloCmd = new NextHiloCommand_1.NextHiloCommand(this._tag, this._lastBatchSize, this._lastRangeAt, this._identityPartsSeparator, this._range.maxId, this._store.conventions);
await this._store.getRequestExecutor(this._dbName).execute(hiloCmd);
const result = hiloCmd.result;
this._prefix = result.prefix;
this._lastBatchSize = result.lastSize;
this._serverTag = result.serverTag || null;
this._lastRangeAt = result.lastRangeAt;
this._range = new HiloRangeValue_1.HiloRangeValue(result.low, result.high, result.serverTag);
}
returnUnusedRange() {
const range = this._range;
const executor = this._store.getRequestExecutor(this._dbName);
return executor.execute(new HiloReturnCommand_1.HiloReturnCommand(this._tag, range.current, range.maxId));
}
get range() {
return this._range;
}
set range(value) {
this._range = value;
}
}
exports.HiloIdGenerator = HiloIdGenerator;
//# sourceMappingURL=HiloIdGenerator.js.map