You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Hydro/hydro/model/system.js

52 lines
1.4 KiB
JavaScript

5 years ago
const db = require('../service/db.js');
const coll = db.collection('system');
async function get(_id) {
5 years ago
const doc = await coll.findOne({ _id });
if (doc) return doc.value;
5 years ago
return null;
}
async function update(_id, update, config) {
await coll.findOneAndUpdate({ _id }, update, config);
5 years ago
return get(_id);
}
/**
* Increments the user counter.
* @returns {number} Integer value after increment.
*/
5 years ago
function incUserCounter() {
return update('userCounter', { $inc: { value: 1 } }, { upsert: true });
}
/**
* Increments the problem ID counter.
* @returns {number} Integer value before increment.
*/
5 years ago
function incPidCounter() {
return update('userCounter', { $inc: { value: 1 } }, { upsert: true });
}
async function acquireLock(name) {
5 years ago
const value = Math.floor(Math.random() * 0xFFFFFFFF);
try {
5 years ago
await coll.updateOne({ _id: `lock_${name}`, value: 0 }, { $set: { value } }, { upsert: true });
} catch (e) { return null; }
return value;
}
async function releaseLock(name, value) {
5 years ago
const result = await coll.updateOne({ _id: `lock_${name}`, value }, { $set: { value: 0 } });
return !!result.matchedCount;
}
async function releaseLockAnyway(name) {
5 years ago
await coll.updateOne({ _id: `lock_${name}` }, { $set: { value: 0 } });
return true;
}
module.exports = {
get,
update,
incPidCounter,
incUserCounter,
acquireLock,
releaseLock,
5 years ago
releaseLockAnyway,
};