8000 replicache/src/replicache.test.ts at main · hmmhmmhm/replicache · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
2785 lines (2362 loc) · 63.7 KB

replicache.test.ts

File metadata and controls

2785 lines (2362 loc) · 63.7 KB
import {ReplicacheTest, httpStatusUnauthorized} from './replicache.js';
import type {MutatorDefs} from './replicache.js';
import type {ReplicacheOptions} from './replicache.js';
import {Replicache, TransactionClosedError} from './mod.js';
import type {ReadTransaction, WriteTransaction} from './mod.js';
import type {JSONValue} from './json.js';
import {assert, expect} from '@esm-bundle/chai';
import * as sinon from 'sinon';
import type {SinonSpy} from 'sinon';
// fetch-mock has invalid d.ts file so we removed that on npm install.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import fetchMock from 'fetch-mock/esm/client.js';
import {Invoke, RPC} from './repm-invoker.js';
import type {ScanOptions} from './scan-options.js';
import {SinonFakeTimers, useFakeTimers} from 'sinon';
import {asyncIterableToArray} from './async-iterable-to-array.js';
import {
closeAllReps,
deletaAllDatabases,
reps,
dbsToDrop,
} from './test-util.js';
import {sleep} from './sleep.js';
let clock: SinonFakeTimers;
setup(function () {
clock = useFakeTimers(0);
});
teardown(function () {
clock.restore();
});
async function tickAFewTimes(n = 10, time = 10) {
for (let i = 0; i < n; i++) {
await clock.tickAsync(time);
}
}
async function tickUntil(f: () => boolean, msPerTest = 10) {
while (!f()) {
await clock.tickAsync(msPerTest);
}
}
fetchMock.config.overwriteRoutes = true;
const {fail} = assert;
let overrideUseMemstore = false;
// eslint-disable-next-line @typescript-eslint/ban-types
async function replicacheForTesting<MD extends MutatorDefs = {}>(
name: string,
{
pullURL = 'https://pull.com/?name=' + name,
pushDelay = 60_000, // Large to prevent interfering
pushURL = 'https://push.com/?name=' + name,
useMemstore = overrideUseMemstore,
...rest
}: ReplicacheOptions<MD> = {},
): Promise<ReplicacheTest<MD>> {
dbsToDrop.add(name);
const rep = new ReplicacheTest<MD>({
pullURL,
pushDelay,
pushURL,
name,
useMemstore,
wasmModule: new URL(
'./wasm/debug/replicache_client_bg.wasm',
import.meta.url,
).href,
...rest,
});
reps.add(rep);
// Wait for open to be done.
await rep.clientID;
fetchMock.post(pullURL, {lastMutationID: 0, patch: []});
fetchMock.post(pushURL, 'ok');
await tickAFewTimes();
return rep;
}
async function addData(tx: WriteTransaction, data: {[key: string]: JSONValue}) {
for (const [key, value] of Object.entries(data)) {
await tx.put(key, value);
}
}
const emptyHash = '';
function spyInvoke(
rep: Replicache,
): SinonSpy<Parameters<Invoke>, ReturnType<Invoke>> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return sinon.spy(rep, '_invoke');
}
teardown(async () => {
fetchMock.restore();
sinon.restore();
await closeAllReps();
deletaAllDatabases();
});
async function expectPromiseToReject(p: unknown): Promise<Chai.Assertion> {
let e;
try {
await p;
} catch (ex) {
e = ex;
}
return expect(e);
}
async function expectAsyncFuncToThrow(f: () => unknown, c: unknown) {
(await expectPromiseToReject(f())).to.be.instanceof(c);
}
function testWithBothStores(name: string, func: () => Promise<void>) {
for (const useMemstore of [false, true]) {
test(`${name} {useMemstore: ${useMemstore}}`, async () => {
try {
overrideUseMemstore = useMemstore;
await func();
} finally {
overrideUseMemstore = false;
}
});
}
}
testWithBothStores('get, has, scan on empty db', async () => {
const rep = await replicacheForTesting('test2');
async function t(tx: ReadTransaction) {
expect(await tx.get('key')).to.equal(undefined);
expect(await tx.has('key')).to.be.false;
const scanItems = await asyncIterableToArray(tx.scan());
expect(scanItems).to.have.length(0);
}
await t(rep);
});
testWithBothStores('put, get, has, del inside tx', async () => {
const rep = await replicacheForTesting('test3', {
mutators: {
testMut: async (
tx: WriteTransaction,
args: {key: string; value: JSONValue},
) => {
const key = args['key'];
const value = args['value'];
await tx.put(key, value);
expect(await tx.has(key)).to.equal(true);
const v = await tx.get(key);
expect(v).to.deep.equal(value);
expect(await tx.del(key)).to.equal(true);
expect(await tx.has(key)).to.be.false;
},
},
});
const {testMut} = rep.mutate;
for (const [key, value] of Object.entries({
a: true,
b: false,
c: null,
d: 'string',
e: 12,
f: {},
g: [],
h: {h1: true},
i: [0, 1],
})) {
await testMut({key, value: value as JSONValue});
}
});
async function testScanResult<K, V>(
rep: Replicache,
options: ScanOptions | undefined,
entries: [K, V][],
) {
await rep.query(async tx => {
expect(
await asyncIterableToArray(tx.scan(options).entries()),
).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options))).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options).values())).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await asyncIterableToArray(tx.scan(options).keys())).to.deep.equal(
entries.map(([k]) => k),
);
});
await rep.query(async tx => {
expect(await tx.scanAll(options)).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await tx.scan(options).toArray()).to.deep.equal(
entries.map(([, v]) => v),
);
});
// scan().xxx().toArray()
await rep.query(async tx => {
expect(await tx.scan(options).entries().toArray()).to.deep.equal(entries);
});
await rep.query(async tx => {
expect(await tx.scan(options).values().toArray()).to.deep.equal(
entries.map(([, v]) => v),
);
});
await rep.query(async tx => {
expect(await tx.scan(options).keys().toArray()).to.deep.equal(
entries.map(([k]) => k),
);
});
}
testWithBothStores('scan', async () => {
const rep = await replicacheForTesting('test4', {
mutators: {
addData,
},
});
const add = rep.mutate.addData;
await add({
'a/0': 0,
'a/1': 1,
'a/2': 2,
'a/3': 3,
'a/4': 4,
'b/0': 5,
'b/1': 6,
'b/2': 7,
'c/0': 8,
});
await testScanResult(rep, undefined, [
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
['b/0', 5],
['b/1', 6],
['b/2', 7],
['c/0', 8],
]);
await testScanResult(rep, {prefix: 'a'}, [
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
]);
await testScanResult(rep, {prefix: 'b'}, [
['b/0', 5],
['b/1', 6],
['b/2', 7],
]);
await testScanResult(rep, {prefix: 'c/'}, [['c/0', 8]]);
await testScanResult(
rep,
{
start: {key: 'b/1', exclusive: false},
},
[
['b/1', 6],
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
start: {key: 'b/1'},
},
[
['b/1', 6],
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
start: {key: 'b/1', exclusive: true},
},
[
['b/2', 7],
['c/0', 8],
],
);
await testScanResult(
rep,
{
limit: 3,
},
[
['a/0', 0],
['a/1', 1],
['a/2', 2],
],
);
await testScanResult(
rep,
{
limit: 10,
prefix: 'a/',
},
[
['a/0', 0],
['a/1', 1],
['a/2', 2],
['a/3', 3],
['a/4', 4],
],
);
await testScanResult(
rep,
{
limit: 1,
prefix: 'b/',
},
[['b/0', 5]],
);
});
testWithBothStores('subscribe', async () => {
const log: [string, JSONValue][] = [];
const rep = await replicacheForTesting('subscribe', {
mutators: {
addData,
},
});
let queryCallCount = 0;
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
return await tx.scan({prefix: 'a/'}).entries().toArray();
},
{
onData: (values: Iterable<[string, JSONValue]>) => {
for (const entry of values) {
log.push(entry);
}
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
const add = rep.mutate.addData;
await add({'a/0': 0});
expect(log).to.deep.equal([['a/0', 0]]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
// Put with same value should not invoke the subscription.
log.length = 0;
await add({'a/0': 0});
expect(log).to.deep.equal([]);
expect(queryCallCount).to.equal(2);
log.length = 0;
await add({'a/1': 1});
expect(log).to.deep.equal([
['a/0', 0],
['a/1', 1],
]);
expect(queryCallCount).to.equal(3);
log.length = 0;
log.length = 0;
await add({'a/1': 11});
expect(log).to.deep.equal([
['a/0', 0],
['a/1', 11],
]);
expect(queryCallCount).to.equal(4);
log.length = 0;
cancel();
await add({'a/1': 12});
await Promise.resolve();
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(4);
});
testWithBothStores('subscribe with index', async () => {
const log: [[string, string], JSONValue][] = [];
const rep = await replicacheForTesting('subscribe-with-index', {
mutators: {
addData,
},
});
await rep.createIndex({
name: 'i1',
jsonPointer: '/id',
keyPrefix: 'a',
});
let queryCallCount = 0;
let >
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
return await tx.scan({indexName: 'i1'}).entries().toArray();
},
{
onData: (values: Iterable<[[string, string], JSONValue]>) => {
onDataCallCount++;
for (const entry of values) {
log.push(entry);
}
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
expect(onDataCallCount).to.equal(0);
await rep.mutate.addData({
a1: {id: 'a-1', x: 1},
a2: {id: 'a-2', x: 2},
b: {id: 'bx'},
});
expect(log).to.deep.equal([
[
['a-1', 'a1'],
{
id: 'a-1',
x: 1,
},
],
[
['a-2', 'a2'],
{
id: 'a-2',
x: 2,
},
],
]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(2);
log.length = 0;
await rep.mutate.addData({a3: {id: 'a-3', x: 3}});
expect(queryCallCount).to.equal(3);
expect(onDataCallCount).to.equal(3);
expect(log).to.deep.equal([
[
['a-1', 'a1'],
{
id: 'a-1',
x: 1,
},
],
[
['a-2', 'a2'],
{
id: 'a-2',
x: 2,
},
],
[
['a-3', 'a3'],
{
id: 'a-3',
x: 3,
},
],
]);
await rep.dropIndex('i1');
expect(queryCallCount).to.equal(4);
expect(onDataCallCount).to.equal(3); // scan({indexName: 'i1'}) fails since we do not have that index any more.
log.length = 0;
await rep.createIndex({
name: 'i1',
jsonPointer: '/id',
});
expect(queryCallCount).to.equal(5);
expect(onDataCallCount).to.equal(4);
expect(log).to.deep.equal([
[
['a-1', 'a1'],
{
id: 'a-1',
x: 1,
},
],
[
['a-2', 'a2'],
{
id: 'a-2',
x: 2,
},
],
[
['a-3', 'a3'],
{
id: 'a-3',
x: 3,
},
],
[
['bx', 'b'],
{
id: 'bx',
},
],
]);
cancel();
});
testWithBothStores('subscribe with index and start', async () => {
const log: [[string, string], JSONValue][] = [];
const rep = await replicacheForTesting('subscribe-with-index-and-start', {
mutators: {
addData,
},
});
await rep.createIndex({
name: 'i1',
jsonPointer: '/id',
});
let queryCallCount = 0;
let >
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
return await tx
.scan({indexName: 'i1', start: {key: 'a-2'}})
.entries()
.toArray();
},
{
onData: (values: Iterable<[[string, string], JSONValue]>) => {
onDataCallCount++;
for (const entry of values) {
log.push(entry);
}
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
expect(onDataCallCount).to.equal(0);
await rep.mutate.addData({
a1: {id: 'a-1', x: 1},
a2: {id: 'a-2', x: 2},
b: {id: 'bx'},
});
expect(log).to.deep.equal([
[
['a-2', 'a2'],
{
id: 'a-2',
x: 2,
},
],
[
['bx', 'b'],
{
id: 'bx',
},
],
]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(2);
log.length = 0;
await rep.mutate.addData({
b: {id: 'bx2'},
});
expect(log).to.deep.equal([
[
['a-2', 'a2'],
{
id: 'a-2',
x: 2,
},
],
[
['bx2', 'b'],
{
id: 'bx2',
},
],
]);
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
// Adding a entry that does not match the index... no id property
await rep.mutate.addData({
c: {noid: 'c-3'},
});
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
// Changing a entry before the start key
await rep.mutate.addData({
a1: {id: 'a-1', x: 2},
});
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
// Changing a entry to the same value
await rep.mutate.addData({
a2: {id: 'a-2', x: 2},
});
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
cancel();
});
testWithBothStores('subscribe with index and prefix', async () => {
const log: [[string, string], JSONValue][] = [];
const rep = await replicacheForTesting('subscribe-with-index-and-prefix', {
mutators: {
addData,
},
});
await rep.createIndex({
name: 'i1',
jsonPointer: '/id',
});
let queryCallCount = 0;
let >
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
return await tx.scan({indexName: 'i1', prefix: 'b'}).entries().toArray();
},
{
onData: (values: Iterable<[[string, string], JSONValue]>) => {
onDataCallCount++;
for (const entry of values) {
log.push(entry);
}
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
expect(onDataCallCount).to.equal(0);
await rep.mutate.addData({
a1: {id: 'a-1', x: 1},
a2: {id: 'a-2', x: 2},
b: {id: 'bx'},
});
expect(log).to.deep.equal([
[
['bx', 'b'],
{
id: 'bx',
},
],
]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(2);
log.length = 0;
await rep.mutate.addData({
b: {id: 'bx2'},
});
expect(log).to.deep.equal([
[
['bx2', 'b'],
{
id: 'bx2',
},
],
]);
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
// Adding a entry that does not match the index... no id property
await rep.mutate.addData({
c: {noid: 'c-3'},
});
expect(queryCallCount).to.equal(3); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(3);
// Changing a entry but still matching prefix
await rep.mutate.addData({
b: {id: 'bx3', x: 3},
});
expect(queryCallCount).to.equal(4);
expect(onDataCallCount).to.equal(4);
// Changing a entry to the same value
await rep.mutate.addData({
b: {id: 'bx3', x: 3},
});
expect(queryCallCount).to.equal(4); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(4);
cancel();
});
testWithBothStores('subscribe with isEmpty and prefix', async () => {
const log: boolean[] = [];
const rep = await replicacheForTesting('subscribe-with-is-empty', {
mutators: {
addData,
del: (tx, k: string) => tx.del(k),
},
});
let queryCallCount = 0;
let >
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
return await tx.isEmpty();
},
{
onData: (empty: boolean) => {
onDataCallCount++;
log.push(empty);
},
},
);
expect(log).to.deep.equal([]);
expect(queryCallCount).to.equal(0);
expect(onDataCallCount).to.equal(0);
await tickAFewTimes();
expect(log).to.deep.equal([true]);
expect(queryCallCount).to.equal(1);
expect(onDataCallCount).to.equal(1);
await rep.mutate.addData({
a: 1,
});
expect(log).to.deep.equal([true, false]);
expect(queryCallCount).to.equal(2);
expect(onDataCallCount).to.equal(2);
await rep.mutate.addData({
b: 2,
});
expect(log).to.deep.equal([true, false]);
expect(queryCallCount).to.equal(3);
expect(onDataCallCount).to.equal(2);
await rep.mutate.del('a');
expect(log).to.deep.equal([true, false]);
expect(queryCallCount).to.equal(4);
expect(onDataCallCount).to.equal(2);
await rep.mutate.del('b');
expect(log).to.deep.equal([true, false, true]);
expect(queryCallCount).to.equal(5);
expect(onDataCallCount).to.equal(3);
cancel();
});
testWithBothStores('subscribe change keys', async () => {
const log: JSONValue[][] = [];
const rep = await replicacheForTesting('subscribe-change-keys', {
mutators: {
addData,
},
});
let queryCallCount = 0;
let >
const cancel = rep.subscribe(
async (tx: ReadTransaction) => {
queryCallCount++;
const a = await tx.get('a');
const rv = [a ?? 'no-a'];
if (a === 1) {
rv.push((await tx.get('b')) ?? 'no b');
}
return rv;
},
{
onData: (values: JSONValue[]) => {
onDataCallCount++;
log.push(values);
},
},
);
expect(log).to.have.length(0);
expect(queryCallCount).to.equal(0);
expect(onDataCallCount).to.equal(0);
await rep.mutate.addData({
a: 0,
});
expect(log).to.deep.equal([['no-a'], [0]]);
expect(queryCallCount).to.equal(2); // One for initial subscribe and one for the add.
expect(onDataCallCount).to.equal(2);
await rep.mutate.addData({
b: 2,
});
expect(queryCallCount).to.equal(2);
expect(onDataCallCount).to.equal(2);
log.length = 0;
await rep.mutate.addData({
a: 1,
});
expect(queryCallCount).to.equal(3);
expect(onDataCallCount).to.equal(3);
expect(log).to.deep.equal([[1, 2]]);
log.length = 0;
await rep.mutate.addData({
b: 3,
});
expect(queryCallCount).to.equal(4);
expect(onDataCallCount).to.equal(4);
expect(log).to.deep.equal([[1, 3]]);
log.length = 0;
await rep.mutate.addData({
a: 4,
});
expect(queryCallCount).to.equal(5);
expect(onDataCallCount).to.equal(5);
expect(log).to.deep.equal([[4]]);
await rep.mutate.addData({
b: 5,
});
expect(queryCallCount).to.equal(5);
expect(onDataCallCount).to.equal(5);
cancel();
});
testWithBothStores('subscribe close', async () => {
const rep = await replicacheForTesting('subscribe-close', {
mutators: {addData},
});
const log: (JSONValue | undefined)[] = [];
const cancel = rep.subscribe((tx: ReadTransaction) => tx.get('k'), {
onData: value => log.push(value),
onDone: () => (done = true),
});
expect(log).to.have.length(0);
const add = rep.mutate.addData;
await add({k: 0});
await Promise.resolve();
expect(log).to.deep.equal([undefined, 0]);
let done = false;
await rep.close();
expect(done).to.equal(true);
cancel();
});
testWithBothStores('name', async () => {
const repA = await replicacheForTesting('a', {mutators: {addData}});
const repB = await replicacheForTesting('b', {mutators: {addData}});
const addA = repA.mutate.addData;
const addB = repB.mutate.addData;
await addA({key: 'A'});
await addB({key: 'B'});
expect(await repA.get('key')).to.equal('A');
expect(await repB.get('key')).to.equal('B');
await repA.close();
await repB.close();
indexedDB.deleteDatabase('a');
indexedDB.deleteDatabase('b');
});
testWithBothStores('register with error', async () => {
const rep = await replicacheForTesting('regerr', {
mutators: {
err: async (_: WriteTransaction, args: number) => {
throw args;
},
},
});
const doErr = rep.mutate.err;
try {
await doErr(42);
fail('Should have thrown');
} catch (ex) {
expect(ex).to.equal(42);
}
});
testWithBothStores('subscribe with error', async () => {
const rep = await replicacheForTesting('suberr', {mutators: {addData}});
const add = rep.mutate.addData;
let gottenValue = 0;
let error;
const cancel = rep.subscribe(
async tx => {
const v = await tx.get('k');
if (v !== undefined && v !== null) {
throw v;
}
return null;
},
{
onData: () => {
gottenValue++;
},
onError: e => {
error = e;
},
},
);
await Promise.resolve();
expect(error).to.equal(undefined);
expect(gottenValue).to.equal(0);
await add({k: 'throw'});
expect(gottenValue).to.equal(1);
0