@sphereon/ssi-sdk.data-store
Version:
139 lines • 7.94 kB
JavaScript
;
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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MachineStateStore = void 0;
const debug_1 = __importDefault(require("debug"));
const typeorm_1 = require("typeorm");
const MachineStateInfoEntity_1 = require("../entities/machineState/MachineStateInfoEntity");
const IAbstractMachineStateStore_1 = require("./IAbstractMachineStateStore");
const debug = (0, debug_1.default)('sphereon:ssi-sdk:machine-state:store');
/**
* Represents a data store for managing machine states.
*/
class MachineStateStore extends IAbstractMachineStateStore_1.IAbstractMachineStateStore {
constructor(dbConnection) {
super();
this._dbConnection = dbConnection;
}
persistMachineState(state) {
return __awaiter(this, void 0, void 0, function* () {
const connection = yield this._dbConnection;
const { machineName, instanceId, tenantId } = state;
debug(`Executing persistMachineState for machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}...`);
const entity = MachineStateStore.machineStateInfoEntityFrom(state);
const existing = yield connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).findOne({
where: {
instanceId: state.instanceId,
},
});
if (existing && existing.updatedCount > state.updatedCount) {
const error = `Updating machine state with an older version is not allowed. Machine ${existing.machineName}, last count: ${existing.updatedCount}, new count: ${existing.updatedCount}, last updated: ${existing.updatedAt}, current: ${new Date()}, instance: ${existing.instanceId}`;
console.log(error);
return Promise.reject(new Error(error));
}
// No need for a transaction. This is a single entity. We don't want to be surprised by an isolation level hiding the state from others
const result = yield connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).save(entity, { transaction: false });
debug(`Done persistMachineState machine ${machineName}, instance ${instanceId}, tenantId: ${tenantId}`);
return MachineStateStore.machineInfoFrom(result);
});
}
findActiveMachineStates(args) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const { tenantId, machineName, instanceId } = args;
const connection = yield this._dbConnection;
debug(`Executing findActiveMachineStates query with machineName: ${machineName}, tenantId: ${tenantId}`);
const queryBuilder = connection
.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity)
.createQueryBuilder('state')
.where('state.completedAt IS NULL')
.andWhere(new typeorm_1.Brackets((qb) => {
qb.where('state.expiresAt IS NULL').orWhere('state.expiresAt > :now', { now: new Date() });
}));
if (instanceId) {
queryBuilder.andWhere('state.instanceId = :instanceId', { instanceId });
}
if (tenantId) {
queryBuilder.andWhere('state.tenantId = :tenantId', { tenantId });
}
if (machineName) {
queryBuilder.andWhere('state.machineName = :machineName', { machineName });
}
return ((_a = (yield queryBuilder
.orderBy('state.updatedAt', 'DESC')
.getMany()
.then((entities) => entities.map(MachineStateStore.machineInfoFrom)))) !== null && _a !== void 0 ? _a : []);
});
}
findMachineStates(args) {
return __awaiter(this, void 0, void 0, function* () {
const connection = yield this._dbConnection;
debug('findMachineStates', args);
const result = yield connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).find(Object.assign(Object.assign({}, ((args === null || args === void 0 ? void 0 : args.filter) && { where: args === null || args === void 0 ? void 0 : args.filter })), { transaction: false }));
return result.map((event) => MachineStateStore.machineInfoFrom(event));
});
}
getMachineState(args) {
return __awaiter(this, void 0, void 0, function* () {
const connection = yield this._dbConnection;
debug('getMachineState', args);
return connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).findOneOrFail({ where: { instanceId: args.instanceId } });
});
}
deleteMachineState(args) {
return __awaiter(this, void 0, void 0, function* () {
debug(`Executing deleteMachineState query with id: ${args.instanceId}`);
if (!args.instanceId) {
throw new Error('No instanceId parameter is provided.');
}
try {
const connection = yield this._dbConnection;
const result = yield connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).delete(args.instanceId);
return result.affected != null && result.affected > 0;
}
catch (error) {
debug(`Error deleting state: ${error}`);
return false;
}
});
}
deleteExpiredMachineStates(args) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const { machineName, tenantId, deleteDoneStates } = args;
debug(`Executing deleteExpiredMachineStates query with params: ${JSON.stringify(args)}`);
try {
const connection = yield this._dbConnection;
const deleteCriteria = Object.assign(Object.assign(Object.assign(Object.assign({}, (machineName && { machineName })), (tenantId && { tenantId })), (!deleteDoneStates && { expiresAt: (0, typeorm_1.LessThan)(new Date()) })), (deleteDoneStates && { completedAt: (0, typeorm_1.Not)((0, typeorm_1.IsNull)()) }));
const result = yield connection.getRepository(MachineStateInfoEntity_1.MachineStateInfoEntity).delete(deleteCriteria);
return (_a = result.affected) !== null && _a !== void 0 ? _a : 0;
}
catch (error) {
debug(`Error deleting machine info: ${error}`);
return Promise.reject(new Error(`Error deleting expired machine states for machine type ${machineName}`));
}
});
}
}
exports.MachineStateStore = MachineStateStore;
MachineStateStore.machineInfoFrom = (machineStateInfoEntity) => {
// We are making sure no entity function get copied
return JSON.parse(JSON.stringify(machineStateInfoEntity));
};
MachineStateStore.machineStateInfoEntityFrom = (machineStateInfo) => {
const entity = new MachineStateInfoEntity_1.MachineStateInfoEntity();
Object.assign(entity, machineStateInfo);
return entity;
};
//# sourceMappingURL=MachineStateStore.js.map