优化数据库读写
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createStateCache } from '../src/database/state-cache.mjs';
|
||||
|
||||
let loads = 0;
|
||||
let release;
|
||||
const gate = new Promise(resolve => { release = resolve; });
|
||||
const coalesced = createStateCache({
|
||||
maxAgeMs: 30000,
|
||||
async load() {
|
||||
loads += 1;
|
||||
await gate;
|
||||
return { load: loads };
|
||||
}
|
||||
});
|
||||
const firstPending = coalesced.read();
|
||||
const secondPending = coalesced.read();
|
||||
release();
|
||||
const [first, second] = await Promise.all([firstPending, secondPending]);
|
||||
assert.equal(loads, 1, '并发冷读取应合并为一次全量加载');
|
||||
assert.strictEqual(first, second, '并发读取应共享同一份快照');
|
||||
assert.strictEqual(await coalesced.read(), first, '有效期内应直接复用内存快照');
|
||||
|
||||
coalesced.invalidate();
|
||||
const afterInvalidation = await coalesced.read();
|
||||
assert.equal(loads, 2, '应用写入失效后应重新加载');
|
||||
assert.notStrictEqual(afterInvalidation, first, '失效后不得继续返回旧快照');
|
||||
|
||||
let version = 1;
|
||||
let versionLoads = 0;
|
||||
const versioned = createStateCache({
|
||||
version: () => version,
|
||||
load: () => ({ load: ++versionLoads })
|
||||
});
|
||||
const versionOne = await versioned.read();
|
||||
assert.strictEqual(await versioned.read(), versionOne, '数据库版本未变化时应复用快照');
|
||||
version += 1;
|
||||
const versionTwo = await versioned.read();
|
||||
assert.equal(versionLoads, 2, '外部数据库版本变化后应重新加载');
|
||||
assert.notStrictEqual(versionTwo, versionOne, '外部写入后不得返回旧快照');
|
||||
|
||||
console.log('State cache tests passed');
|
||||
Reference in New Issue
Block a user