mirror of
https://github.com/Zakkaus/doona.git
synced 2026-12-06 00:00:57 +00:00
fix(policies): stage interruption in the edit draft
Keep interruption and the other draft fields in one source write against the original digest, so a live PATCH cannot advance the draft past an external edit. Preserve immediate PATCHes in view mode.
This commit is contained in:
1 parent
7aaa8ff21c
commit
db7dccbf6c
7 files changed
+106
-69
No files matched your search
@@ -85,8 +85,8 @@ test('releasing a collapsed automatic group clears overrides on both networks',
|
||||
expect([selection.tcp?.source, selection.udp?.source]).not.toContain('override');
|
||||
});
|
||||
|
||||
test('toggling interruption keeps unsaved filters and permits the next save', async ({page}) => {
|
||||
const {api} = await mockBackend(page);
|
||||
test('toggling interruption stages it with unsaved filters in one conditional source write', async ({page}) => {
|
||||
const {api, requests} = await mockBackend(page);
|
||||
await page.goto('/#/policies');
|
||||
await moreAction(page.getByRole('region', {name: 'proxy', exact: true}), 'Edit group');
|
||||
const dialog = page.getByRole('dialog', {name: 'Edit group proxy'});
|
||||
@@ -94,6 +94,9 @@ test('toggling interruption keeps unsaved filters and permits the next save', as
|
||||
await dialog.getByRole('textbox', {name: 'Filter 1'}).fill('name(hk-01, sg-01)');
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await expect(dialog.getByRole('switch')).toBeChecked();
|
||||
expect(requests.filter(request => request.method() === 'PATCH')).toHaveLength(0);
|
||||
expect((await api.group('proxy')).config.interrupt_connections).toBe(false);
|
||||
const origin = (await api.config()).sources.find(source => source.kind === 'main')!;
|
||||
const apply = dialog.getByRole('button', {name: 'Apply', exact: true});
|
||||
await expect(apply).toBeEnabled();
|
||||
await apply.click();
|
||||
@@ -101,6 +104,9 @@ test('toggling interruption keeps unsaved filters and permits the next save', as
|
||||
const saved = (await api.config()).sources.find(source => source.kind === 'main')!.content!;
|
||||
expect(saved).toContain('filter: name(hk-01, sg-01)');
|
||||
expect((await api.group('proxy')).config.interrupt_connections).toBe(true);
|
||||
const writes = requests.filter(request => request.method() === 'PUT' && new URL(request.url()).pathname.includes('/config/sources/'));
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0].headers()['if-match']).toBe(`"${origin.content_sha256}"`);
|
||||
});
|
||||
|
||||
for (const when of ['before', 'after'])
|
||||
@@ -114,14 +120,7 @@ for (const when of ['before', 'after'])
|
||||
await api.replaceConfigSource(main.id, '# external edit\n' + main.content, `"${main.content_sha256}"`);
|
||||
await expect.poll(async () => (await api.config()).sources.find(source => source.kind === 'main')!.content).toContain('# external edit');
|
||||
};
|
||||
if (when === 'before') {
|
||||
await external();
|
||||
const refreshed = page.waitForResponse(response => response.request().method() === 'GET' && new URL(response.url()).pathname.endsWith('/groups/proxy'));
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await refreshed;
|
||||
await expect(dialog.getByRole('switch')).not.toBeChecked();
|
||||
await expect(dialog.getByRole('switch')).toBeEnabled();
|
||||
}
|
||||
if (when === 'before') await external();
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await expect(dialog.getByRole('switch')).toBeChecked();
|
||||
const apply = dialog.getByRole('button', {name: 'Apply', exact: true});
|
||||
@@ -182,28 +181,55 @@ test('an automatic group sums itself up, opens on a press and still takes a pinn
|
||||
]);
|
||||
});
|
||||
|
||||
test('the edit dialog shows the running configuration and the interrupt switch, which writes to the group', async ({page}) => {
|
||||
const {requests} = await mockBackend(page);
|
||||
await page.setViewportSize({width: 1440, height: 1000});
|
||||
test('cancelling an interrupt-only draft leaves the source and live group unchanged', async ({page}) => {
|
||||
const {api, requests} = await mockBackend(page);
|
||||
await page.goto('/#/policies');
|
||||
const card = page.getByRole('region', {name: 'proxy', exact: true});
|
||||
// Nothing of the configuration stays on the card.
|
||||
await expect(card.getByRole('switch')).toHaveCount(0);
|
||||
await expect(card.getByRole('button', {name: 'Configuration', exact: true})).toHaveCount(0);
|
||||
await moreAction(card, 'Edit group');
|
||||
const dialog = page.getByRole('dialog', {name: 'Edit group proxy'});
|
||||
await expect(dialog.getByRole('heading', {name: 'Running configuration'})).toBeVisible();
|
||||
await expect(dialog.getByText('Check interval', {exact: true})).toBeVisible();
|
||||
const origin = (await api.config()).sources.find(source => source.kind === 'main')!;
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await expect(dialog.getByRole('switch')).toBeChecked();
|
||||
await dialog.getByRole('button', {name: 'Cancel', exact: true}).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(requests.filter(request => ['PATCH', 'PUT'].includes(request.method()))).toHaveLength(0);
|
||||
expect((await api.config()).sources.find(source => source.id === origin.id)!.content_sha256).toBe(origin.content_sha256);
|
||||
expect((await api.group('proxy')).config.interrupt_connections).toBe(false);
|
||||
await moreAction(card, 'Edit group');
|
||||
await expect(dialog.getByRole('switch')).not.toBeChecked();
|
||||
});
|
||||
|
||||
test('the view dialog patches interruption live and refetches after a PATCH 412', async ({page}) => {
|
||||
const {api, capabilities, requests} = await mockBackend(page);
|
||||
capabilities.resources.config.writable = false;
|
||||
await page.goto('/#/policies');
|
||||
await moreAction(page.getByRole('region', {name: 'proxy', exact: true}), 'View configuration');
|
||||
const dialog = page.getByRole('dialog', {name: 'proxy configuration'});
|
||||
const toggle = dialog.getByRole('switch', {name: 'Interrupt existing connections on switch'});
|
||||
await expect(toggle).not.toBeChecked();
|
||||
const main = (await api.config()).sources.find(source => source.kind === 'main')!;
|
||||
await api.replaceConfigSource(main.id, '# external edit\n' + main.content, `"${main.content_sha256}"`);
|
||||
await expect.poll(async () => (await api.config()).sources.find(source => source.kind === 'main')!.content).toContain('# external edit');
|
||||
let patchRejected = false;
|
||||
const rejected = page.waitForResponse(response => {
|
||||
if (response.request().method() !== 'PATCH' || response.status() !== 412) return false;
|
||||
patchRejected = true;
|
||||
return true;
|
||||
});
|
||||
const refreshed = page.waitForResponse(
|
||||
response => patchRejected && response.request().method() === 'GET' && new URL(response.url()).pathname.endsWith('/groups/proxy')
|
||||
);
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await expect(page.locator('.rp-toast.positive').filter({hasText: 'proxy'})).toBeVisible();
|
||||
await rejected;
|
||||
await refreshed;
|
||||
await expect(toggle).not.toBeChecked();
|
||||
await expect(toggle).toBeEnabled();
|
||||
const saved = page.waitForResponse(response => response.request().method() === 'PATCH' && response.status() === 202);
|
||||
await dialog.getByText('Interrupt existing connections on switch', {exact: true}).click();
|
||||
await saved;
|
||||
await expect(toggle).toBeChecked();
|
||||
const patches = requests.filter(request => request.method() === 'PATCH');
|
||||
expect(patches.map(request => [new URL(request.url()).pathname, request.postDataJSON()])).toEqual([
|
||||
['/api/v1/groups/proxy/config', expect.arrayContaining([expect.objectContaining({path: '/config/interrupt_connections', value: true})])]
|
||||
]);
|
||||
// The switch writes at once; cancelling the dialog leaves the file alone.
|
||||
await dialog.getByRole('button', {name: 'Cancel', exact: true}).click();
|
||||
expect((await api.group('proxy')).config.interrupt_connections).toBe(true);
|
||||
expect(requests.filter(request => request.method() === 'PUT')).toHaveLength(0);
|
||||
});
|
||||
@@ -81,6 +81,23 @@ describe('group entries', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('round-trips interruption and edits it without moving comments or other fields', () => {
|
||||
const source = "group {\n g {\n policy: select\n interrupt_connections: 'true' # keep\n check_url: x\n }\n}\n";
|
||||
const unchanged = {filters: [], policy: 'select'};
|
||||
expect(readGroupEntries(source)[0]).toMatchObject({interrupt: "'true'"});
|
||||
expect(writeGroupEntry(source, 'g', unchanged)).toBe(source);
|
||||
expect(writeGroupEntry(source, 'g', {...unchanged, interrupt: 'false'})).toBe(source.replace("'true'", 'false'));
|
||||
expect(writeGroupEntry(source, 'g', {...unchanged, interrupt: null})).toBe(source.replace("interrupt_connections: 'true'", ''));
|
||||
const absent = 'group {\n g {\n policy: select\n check_url: x\n }\n}\n';
|
||||
const added = writeGroupEntry(absent, 'g', {...unchanged, interrupt: 'true'});
|
||||
expect(added).toBe(absent.replace(' check_url:', ' interrupt_connections: true\n check_url:'));
|
||||
expect(writeGroupEntry(added, 'g', {...unchanged, interrupt: null})).toBe(absent);
|
||||
expect(writeGroupEntry('group { g { policy: select interrupt_connections: true } }', 'g', {...unchanged, interrupt: 'false'})).toContain(
|
||||
' policy: select\n interrupt_connections: false\n'
|
||||
);
|
||||
expect(writeGroupEntry('', 'g', {...unchanged, interrupt: 'true'})).toContain('interrupt_connections: true');
|
||||
});
|
||||
|
||||
it('writes a name back as it was written while it names the same value', () => {
|
||||
expect(nameText('hk', "'hk'")).toBe("'hk'");
|
||||
expect(nameText('jp 01', "'hk'")).toBe("'jp 01'");
|
||||
|
||||
+11
-8
@@ -10,6 +10,7 @@ export type GroupEntry = {
|
||||
// `default` and `final` as written, quotes included, or null when the entry sets none.
|
||||
default: string | null;
|
||||
final: string | null;
|
||||
interrupt: string | null;
|
||||
from: number;
|
||||
to: number;
|
||||
};
|
||||
@@ -30,6 +31,7 @@ export function readGroupEntries(text: string): GroupEntry[] {
|
||||
policy: last('policy'),
|
||||
default: last('default'),
|
||||
final: last('final'),
|
||||
interrupt: last('interrupt_connections'),
|
||||
from: entry.line,
|
||||
to: entry.endLine
|
||||
};
|
||||
@@ -45,9 +47,8 @@ export function groupNameProblem(name: string, taken: ReadonlySet<string>): 'inv
|
||||
return !isBareName(name) ? 'invalid' : taken.has(name) ? 'taken' : null;
|
||||
}
|
||||
|
||||
// What writeGroupEntry sets. `default` and `final` are written as given, quotes included; undefined leaves the line
|
||||
// alone and null removes it.
|
||||
export type GroupEntryUpdate = {filters: string[]; policy: string | null; default?: string | null; final?: string | null};
|
||||
// Optional fields are written as given; undefined leaves the line alone and null removes it.
|
||||
export type GroupEntryUpdate = {filters: string[]; policy: string | null; default?: string | null; final?: string | null; interrupt?: string | null};
|
||||
export function writeGroupEntry(text: string, name: string, next: GroupEntryUpdate): string {
|
||||
const {blocks, tokens} = scanConfig(text);
|
||||
const sections = blocks.filter(block => block.name === 'group');
|
||||
@@ -77,6 +78,7 @@ export function writeGroupEntry(text: string, name: string, next: GroupEntryUpda
|
||||
...(next.policy ? [`${indent}${indent}policy: ${next.policy}`] : []),
|
||||
...(next.default ? [`${indent}${indent}default: ${next.default}`] : []),
|
||||
...(next.final ? [`${indent}${indent}final: ${next.final}`] : []),
|
||||
...(next.interrupt ? [`${indent}${indent}interrupt_connections: ${next.interrupt}`] : []),
|
||||
`${indent}}`
|
||||
].join('\n');
|
||||
if (block) {
|
||||
@@ -87,9 +89,10 @@ export function writeGroupEntry(text: string, name: string, next: GroupEntryUpda
|
||||
return `${text.replace(/\n+$/, '')}\n\ngroup {\n${body}\n}\n`;
|
||||
}
|
||||
|
||||
// Changes the filter, policy, default and final fields where they stand, so comments and other fields keep their place.
|
||||
// Changes fields where they stand, so comments and other fields keep their place.
|
||||
// A new line goes after the last line of its own key or of a key listed before it, in the order a group is written.
|
||||
const singleKeys = ['policy', 'default', 'final'] as const;
|
||||
const singleKeys = ['policy', 'default', 'final', 'interrupt'] as const;
|
||||
const fieldName = (key: (typeof singleKeys)[number]) => (key === 'interrupt' ? 'interrupt_connections' : key);
|
||||
function rewriteFields(text: string, entry: TextBlock, fields: TextField[], inner: string, next: GroupEntryUpdate): string {
|
||||
const filters = fields.filter(field => field.name === 'filter');
|
||||
const edits: Array<{from: number; to: number; text: string}> = [];
|
||||
@@ -115,7 +118,7 @@ function rewriteFields(text: string, entry: TextBlock, fields: TextField[], inne
|
||||
singleKeys.forEach((key, i) => {
|
||||
const value = next[key];
|
||||
if (value === undefined) return;
|
||||
const own = fields.filter(field => field.name === key);
|
||||
const own = fields.filter(field => field.name === fieldName(key));
|
||||
own.slice(0, -1).forEach(remove);
|
||||
if (own.length) {
|
||||
if (value) replace(own.at(-1)!, value);
|
||||
@@ -124,8 +127,8 @@ function rewriteFields(text: string, entry: TextBlock, fields: TextField[], inne
|
||||
}
|
||||
if (!value) return;
|
||||
if (key === 'policy') return add(filterAt, `${inner}policy: ${value}\n`);
|
||||
const before = fields.filter(field => field.name === 'filter' || singleKeys.slice(0, i).includes(field.name as (typeof singleKeys)[number])).at(-1);
|
||||
add(before ? lineEnd(before.to) : lineEnd(entry.open), `${inner}${key}: ${value}\n`);
|
||||
const before = fields.filter(field => field.name === 'filter' || singleKeys.slice(0, i).some(key => field.name === fieldName(key))).at(-1);
|
||||
add(before ? lineEnd(before.to) : lineEnd(entry.open), `${inner}${fieldName(key)}: ${value}\n`);
|
||||
});
|
||||
for (const [at, lines] of added) edits.push({from: at, to: at, text: lines});
|
||||
return edits.sort((a, b) => b.from - a.from || b.to - a.to).reduce((out, edit) => out.slice(0, edit.from) + edit.text + out.slice(edit.to), text);
|
||||
|
||||
@@ -122,7 +122,6 @@ function PolicyDetail(props: PolicyGroupInput & {kind: 'manual' | 'auto'}) {
|
||||
]}
|
||||
/>
|
||||
);
|
||||
// Whether the group runs automatically or on a pinned member; an automatic group shows it only while pinned.
|
||||
const pin = g?.pinned && (
|
||||
<Light small tone="neutral">
|
||||
{t('policy.overridden')}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {useState} from 'react';
|
||||
import {getApi} from '../../api';
|
||||
import {useT} from '../../i18n';
|
||||
import {nameText, writeGroupEntry} from '../../dae/groups';
|
||||
import {unquote} from '../../dae/text';
|
||||
import {editProblem, type MainSourceEdit} from '../../store/mainSource';
|
||||
import type {ConfigSource, Group} from '../../api/model';
|
||||
import {toast} from '../../ui/ui';
|
||||
@@ -56,7 +56,8 @@ export type PolicyEditView = {
|
||||
setPolicy: (value: string) => void;
|
||||
add: () => void;
|
||||
save: (close: () => void) => void;
|
||||
refreshOrigin: (write: () => Promise<boolean | undefined>) => Promise<boolean | undefined>;
|
||||
interrupt: boolean | null | undefined;
|
||||
setInterrupt: (value: boolean) => void;
|
||||
};
|
||||
// Where the group is declared, and whether that source's text is complete and the configuration read.
|
||||
export type PolicyDeclaration = {owner: GroupOwner | undefined; complete: boolean | undefined; loaded: boolean; error: Error | null};
|
||||
@@ -76,6 +77,7 @@ type Draft = {
|
||||
filters: string[];
|
||||
default: string | null;
|
||||
final: string | null;
|
||||
interrupt: string | null;
|
||||
};
|
||||
// Edits the group in the source that declares it; `source` carries the write and whether the backend takes one.
|
||||
export function usePolicyEdit(name: string, source: MainSourceEdit, declaration: PolicyDeclaration, context: RouteContext): PolicyEditView {
|
||||
@@ -86,15 +88,15 @@ export function usePolicyEdit(name: string, source: MainSourceEdit, declaration:
|
||||
const blocked = editBlocked(owner, declaration, t);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [viewing, setViewing] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const busy = source.busy || refreshing;
|
||||
const busy = source.busy;
|
||||
const routes = routeFields(context.g, draft?.policy ?? null);
|
||||
const session = useDialogSession();
|
||||
const [problem, setProblem] = useState<PolicyEditView['problem']>(null);
|
||||
const refuse = (text: string) => setProblem(prev => ({id: (prev?.id ?? 0) + 1, text}));
|
||||
const guard = useDraftGuard(
|
||||
!!draft &&
|
||||
(draft.policy !== entry?.policy ||
|
||||
(draft.interrupt !== entry?.interrupt ||
|
||||
draft.policy !== entry?.policy ||
|
||||
JSON.stringify(draft.filters) !== JSON.stringify(entry?.filters) ||
|
||||
routes.some(id => draft[routeKeys[id]] !== routeValue(entry?.[routeKeys[id]] ?? null))),
|
||||
() => {
|
||||
@@ -115,7 +117,7 @@ export function usePolicyEdit(name: string, source: MainSourceEdit, declaration:
|
||||
const origin = draft.refused ? (declared?.origin ?? draft.origin) : draft.origin;
|
||||
void source
|
||||
.apply(text => {
|
||||
const update = {filters, policy: draft.policy};
|
||||
const update = {filters, policy: draft.policy, interrupt: draft.interrupt};
|
||||
// A field the dialog does not offer, such as the default member under an automatic policy, is left as the file
|
||||
// has it.
|
||||
for (const id of routes) Object.assign(update, {[routeKeys[id]]: nameText(draft[routeKeys[id]], written[routeKeys[id]])});
|
||||
@@ -188,7 +190,8 @@ export function usePolicyEdit(name: string, source: MainSourceEdit, declaration:
|
||||
policy: declared.entry.policy,
|
||||
filters: declared.entry.filters,
|
||||
default: routeValue(declared.entry.default),
|
||||
final: routeValue(declared.entry.final)
|
||||
final: routeValue(declared.entry.final),
|
||||
interrupt: declared.entry.interrupt
|
||||
});
|
||||
},
|
||||
view: () => {
|
||||
@@ -206,26 +209,7 @@ export function usePolicyEdit(name: string, source: MainSourceEdit, declaration:
|
||||
setPolicy: policy => edit(prev => ({...prev, policy})),
|
||||
add: () => edit(prev => ({...prev, filters: [...prev.filters, '']})),
|
||||
save,
|
||||
refreshOrigin: async write => {
|
||||
if (!draft) return write();
|
||||
const current = session.start();
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const api = getApi();
|
||||
const before = await api.config().catch(() => null);
|
||||
const saved = await write();
|
||||
if (saved) {
|
||||
const after = await api.config().catch(() => null);
|
||||
const origin = after?.sources.find(item => item.id === draft.origin.id);
|
||||
// A pre-existing external edit still requires a refusal; only our own write advances the draft's base.
|
||||
if (current() && origin && before?.sources.find(item => item.id === draft.origin.id)?.content_sha256 === draft.origin.content_sha256)
|
||||
setDraft(prev => (prev && prev.origin === draft.origin ? {...prev, origin} : prev));
|
||||
source.retry();
|
||||
}
|
||||
return saved;
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}
|
||||
interrupt: draft ? (draft.interrupt === null ? null : unquote(draft.interrupt) === 'true') : undefined,
|
||||
setInterrupt: value => edit(prev => ({...prev, interrupt: value ? 'true' : prev.interrupt === null ? null : 'false'}))
|
||||
};
|
||||
}
|
||||
@@ -100,12 +100,15 @@ export function usePolicyGroup(input: PolicyGroupInput) {
|
||||
: t('policy.noneSelected');
|
||||
toast('positive', t('policy.backToAutomatic', {name: g.name, member}));
|
||||
});
|
||||
const interrupt = (value: boolean) =>
|
||||
void declared
|
||||
.refreshOrigin(() => control.setInterrupt(value))
|
||||
.then(saved => {
|
||||
if (saved && g) toast('positive', t('policy.updated', {name: g.name}));
|
||||
});
|
||||
const interrupt = (value: boolean) => {
|
||||
if (declared.editing) {
|
||||
declared.setInterrupt(value);
|
||||
return;
|
||||
}
|
||||
void control.setInterrupt(value).then(saved => {
|
||||
if (saved && g) toast('positive', t('policy.updated', {name: g.name}));
|
||||
});
|
||||
};
|
||||
const select =
|
||||
card && (card.selectable || card.overridable)
|
||||
? (memberId: string) => {
|
||||
@@ -139,14 +142,19 @@ export function usePolicyGroup(input: PolicyGroupInput) {
|
||||
expanded,
|
||||
setExpanded,
|
||||
// What the dialog shows beside the declaration, and alone when it opens read-only: the group's configuration as
|
||||
// the backend reports it, and the interrupt switch, which writes to the group directly rather than to the file.
|
||||
// the backend reports it. The interrupt switch edits the draft when present, otherwise the live group.
|
||||
details: card
|
||||
? {
|
||||
fields: card.fields,
|
||||
heading: edit.editing ? t('policy.liveConfig') : null,
|
||||
reason: edit.editing ? null : (edit.tip ?? null),
|
||||
interrupt: card.interruptable
|
||||
? {selected: card.interrupt, unset: card.interruptUnset, isDisabled: !!control.busy || edit.busy, change: interrupt}
|
||||
? {
|
||||
selected: edit.editing ? edit.interrupt === true : card.interrupt,
|
||||
unset: edit.editing ? edit.interrupt === null : card.interruptUnset,
|
||||
isDisabled: !!control.busy || edit.busy,
|
||||
change: interrupt
|
||||
}
|
||||
: null
|
||||
}
|
||||
: null,
|
||||
|
||||
@@ -338,7 +338,7 @@ it('finds the one source that declares each group, and none when two entries do'
|
||||
|
||||
it('says why a group cannot be edited in the source that declares it', () => {
|
||||
const origin = {id: 'extra', path: '/etc/honk/extra.dae', writable: true} as ConfigSource;
|
||||
const owner = {entry: {name: 'media', written: 'media', filters: [], policy: null, default: null, final: null, from: 1, to: 1}, origin};
|
||||
const owner = {entry: {name: 'media', written: 'media', filters: [], policy: null, default: null, final: null, interrupt: null, from: 1, to: 1}, origin};
|
||||
const state = {loaded: true, complete: true, error: null};
|
||||
expect(editBlocked(owner, state, t)).toBeNull();
|
||||
expect(editBlocked(owner, {...state, error: new LocalError('ui.groupNotLoaded')}, t)).toBe(t('ui.groupNotLoaded'));
|
||||
|
||||
Reference in new issue
Block a user