Skip to content

Commit e37384b

Browse files
committed
Keep imported rules in the order they were exported in
Rules apply oldest first, and two with the same createdAt are ordered by their random ids. An import creates its rules within one millisecond, so they could come out in either order (CI caught it in overridesFile.test). A rule made in the same millisecond as another of its workspace now goes one past the newest instead.
1 parent 93b1d4d commit e37384b

4 files changed

Lines changed: 30 additions & 7 deletions

File tree

‎docs/SPEC.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ A version 1 `session.json` (one page and its tabs) becomes the first workspace,
348348
rules: (CreateRuleInput & { enabled })[] } // no ids or times: the importing store sets them
349349
```
350350

351-
An import reads a file of at most 200 MB with `overridesFileSchema` (`src/shared/overrides`): the format, a `version` this build reads (a newer one is refused, with a word to update), at most 500 overrides. It then checks each entry as the app's own input: an override's shapes with `exportedOverrideSchema` (a known kind, an http(s) source URL, a usable matcher, a SHA-256 or null), then what a response override matches and answers as the store does (`responseFieldsOf`); a rule with `ruleInputSchema`. An entry that fails is left out and counted. So is one the workspace already has, which keeps its own: an override answering the same requests (kind, matcher and, for a response override, method and GraphQL operation), or a rule doing the same (`sameRuleInput`). The rest are created in order, turned off when they were off, and `overrides-changed` and `rules-changed` follow, even when a later one fails (a full workspace refuses a rule). The renderer says what was added and left out, and reloads the page if that setting is on.
351+
An import reads a file of at most 200 MB with `overridesFileSchema` (`src/shared/overrides`): the format, a `version` this build reads (a newer one is refused, with a word to update), at most 500 overrides. It then checks each entry as the app's own input: an override's shapes with `exportedOverrideSchema` (a known kind, an http(s) source URL, a usable matcher, a SHA-256 or null), then what a response override matches and answers as the store does (`responseFieldsOf`); a rule with `ruleInputSchema`. An entry that fails is left out and counted. So is one the workspace already has, which keeps its own: an override answering the same requests (kind, matcher and, for a response override, method and GraphQL operation), or a rule doing the same (`sameRuleInput`). The rest are created in order, turned off when they were off (a rule made in the same millisecond as another of its workspace goes past the newest, so rules, which apply oldest first, keep the order they were made in), and `overrides-changed` and `rules-changed` follow, even when a later one fails (a full workspace refuses a rule). The renderer says what was added and left out, and reloads the page if that setting is on.
352352

353353
**Rules on disk.** `RuleStore` writes a change to disk before it reaches memory (and so the engine); a failed write leaves the rules as they were. Entries this build can't read (a newer version's action or request type, a hand edit) are neither listed nor applied, and are written back as they were. A `rules.json` that isn't JSON of the right shape is moved to `rules.json.broken` and the app starts with no rules; one that can't be read, or moved aside, is left alone and every change is refused, so it is never written over. Either way the window says so once it opens.
354354

‎src/main/store/RuleStore/addRule.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@ import type { CreateRuleInput } from '../../../shared/types';
33
import type { RuleState, StoredRule } from '../types';
44
import { newRuleId } from './newRuleId';
55

6-
/** Adds an enabled rule to `workspaceId` in `state`; refused once the workspace holds MAX_RULES. */
6+
/**
7+
* Adds an enabled rule to `workspaceId` in `state`, never in the same millisecond as another of its
8+
* rules; refused once the workspace holds MAX_RULES.
9+
*/
710
export function addRule(state: RuleState, workspaceId: string, input: CreateRuleInput): StoredRule {
8-
if ([...state.rules.values()].filter((r) => r.workspaceId === workspaceId).length >= MAX_RULES) {
9-
throw new Error(`A workspace holds at most ${MAX_RULES} rules`);
10-
}
11+
const own = [...state.rules.values()].filter((r) => r.workspaceId === workspaceId);
12+
if (own.length >= MAX_RULES) throw new Error(`A workspace holds at most ${MAX_RULES} rules`);
1113
const id = newRuleId(state);
12-
const now = Date.now();
14+
// Two rules made in one millisecond (an import) would tie, and a tie goes by id, at random: the later one goes
15+
// past the newest instead, so rules, which apply oldest first, keep the order they were made in.
16+
const clock = Date.now();
17+
const now = own.some((r) => r.createdAt === clock) ? Math.max(...own.map((r) => r.createdAt)) + 1 : clock;
1318
const rule: StoredRule = { workspaceId, id, ...input, enabled: true, createdAt: now, updatedAt: now };
1419
state.rules.set(id, rule);
1520
return rule;

‎test/unit/overridesFile.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
66
import { tmpdir } from 'node:os';
77
import { join } from 'node:path';
8-
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
8+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
99
import { buildOverridesFile, importOverrides, importRules, overridesFileName, readOverridesFile } from '../../src/main/overridesFile';
1010
import { OverrideStore } from '../../src/main/store/OverrideStore';
1111
import { RuleStore } from '../../src/main/store/RuleStore';
@@ -47,6 +47,7 @@ beforeEach(async () => {
4747
});
4848

4949
afterEach(async () => {
50+
vi.restoreAllMocks();
5051
await rm(dir, { recursive: true, force: true });
5152
});
5253

@@ -97,6 +98,8 @@ describe('import', () => {
9798
store.setWorkspace('ws2');
9899
rules.setWorkspace('ws2');
99100

101+
// All in one millisecond, as a fast import is: the rules still apply in the order they were exported in.
102+
vi.spyOn(Date, 'now').mockReturnValue(5_000);
100103
expect(await importFile(file)).toEqual({ overrides: 3, rules: 2, present: 0, unreadable: 0 });
101104
const [first, second, third] = store.list();
102105
expect(first).toMatchObject({ kind: 'Script', content: 'mine();', enabled: true, originalHash: HASH });

‎test/unit/ruleStore.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,21 @@ describe('RuleStore', () => {
190190
expect((await readIndex()).rules).toEqual([{ ...rule, enabled: false, updatedAt: expect.any(Number) }, added, unknownAction, unknownType, malformed, duplicate]);
191191
});
192192

193+
it('keeps the order rules were made in, even within one millisecond', async () => {
194+
const store = await open();
195+
vi.spyOn(Date, 'now').mockReturnValue(1_000);
196+
// Ids that would sort the other way round (queued one at a time: each write's temp file takes random bytes too).
197+
queuedIds.push('ffffffff');
198+
const first = await store.create(block('https://a.com/first.js'));
199+
queuedIds.push('00000000');
200+
const second = await store.create(removeCsp);
201+
expect(second.createdAt).toBeGreaterThan(first.createdAt);
202+
expect(store.forRenderer().map((r) => r.id)).toEqual(['ffffffff', '00000000']);
203+
// Another workspace's rules don't push its times on.
204+
store.setWorkspace('bbbbbbbb');
205+
expect((await store.create(block())).createdAt).toBe(1_000);
206+
});
207+
193208
it('gives new rules ids that no rule and no unreadable entry has', async () => {
194209
const store = await open();
195210
queuedIds.push('00000001');

0 commit comments

Comments
 (0)