mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
fix(docsync): switches that did not switch off, a webhook nobody could authenticate, and a counter that only grew
More from the audit, each checked against the code before it was touched. The webhook obeyed neither the Documents addon nor the app_settings kill switch, so "switch document sync off" stopped the poll while every provider holding a webhook carried on driving full runs. Both are now read on arrival and again when the debounce timer fires, so a switch thrown mid-window still takes effect. Nextcloud's subscription registered its secret under `X-TREK-Docsync-Signature` while the endpoint reads `x-trek-docsync-secret`: the subscription existed, the calls arrived, and every one of them was dropped for carrying no secret the controller could find. The two names now agree, and the test pins the one the endpoint actually reads. A WebDAV create was an unconditional PUT, so a name already taken upstream was silently overwritten — two trips bound to one folder, or a `receipt.pdf` a person put there by hand, is enough. Creates now send `If-None-Match: *`. The per-item retry bookkeeping was stuck at both ends: the backoff was computed at step 1 every time, so three of the curve's four steps were unreachable, and the attempt counter only ever grew, which shelved a row that failed once a month after six months of otherwise healthy syncing. A successful pass now clears it, which is what makes the limit mean six failures in a row. Also: a manual run on an orphaned binding is refused with 409 (its credential belongs to somebody no longer on the trip, and the scheduler already refuses it, so the button was a way around that); a document deleted while a run is in flight is no longer uploaded anyway; a path-shaped WebDAV id containing `..` is rejected instead of addressing a file outside the bound folder; and Papra's multipart part header no longer takes an unescaped media type, which a CR could end early. Client: three writes in useDocSync swallowed their failure into `void` call sites, a load failure blanked the panel to "no providers available" whatever the cause, and overlapping loads let the slowest response win. Writes now report, only 403/404 blanks the panel, and a generation stamp keeps the newest answer. The dead lastRun state went with them.
This commit is contained in:
@@ -212,7 +212,7 @@ describe('useDocSync spinner', () => {
|
||||
listLinksApi.mockReturnValueOnce(gate.promise)
|
||||
seenLoading.length = 0
|
||||
|
||||
let pending!: Promise<void>
|
||||
let pending!: Promise<boolean>
|
||||
await act(async () => { pending = result.current.updateLink(1, { syncEnabled: false }) })
|
||||
expect(result.current.loading).toBe(false)
|
||||
|
||||
@@ -235,7 +235,7 @@ describe('useDocSync updateLink', () => {
|
||||
const gate = deferred<unknown>()
|
||||
updateLinkApi.mockReturnValueOnce(gate.promise)
|
||||
|
||||
let pending!: Promise<void>
|
||||
let pending!: Promise<boolean>
|
||||
await act(async () => { pending = result.current.updateLink(1, { direction: 'pull' }) })
|
||||
|
||||
expect(result.current.links[0].direction).toBe('pull')
|
||||
@@ -257,14 +257,18 @@ describe('useDocSync updateLink', () => {
|
||||
|
||||
it('FE-DOCSYNC-HOOK-011: a rejected update does not leave the optimistic value standing', async () => {
|
||||
const { result } = await mountLoaded()
|
||||
updateLinkApi.mockRejectedValueOnce(new Error('conflict'))
|
||||
updateLinkApi.mockRejectedValueOnce({ response: { data: { error: 'forbidden' } } })
|
||||
listLinksApi.mockResolvedValueOnce([link({ direction: 'both' })])
|
||||
|
||||
await act(async () => {
|
||||
await expect(result.current.updateLink(1, { syncEnabled: false })).rejects.toThrow('conflict')
|
||||
})
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.updateLink(1, { direction: 'pull' }) })
|
||||
|
||||
expect(listLinksApi).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.links[0].syncEnabled).toBe(true)
|
||||
// Reported rather than thrown: both shells call this as `void`, so a
|
||||
// rejection reached nobody. The reload puts the server's answer back and
|
||||
// the reason stays on screen.
|
||||
expect(ok).toBe(false)
|
||||
expect(result.current.links[0].direction).toBe('both')
|
||||
expect(result.current.error).toBe('forbidden')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -333,19 +337,24 @@ describe('useDocSync run and save feedback', () => {
|
||||
await act(async () => { await result.current.syncNow(1) })
|
||||
|
||||
expect(syncNowApi).toHaveBeenCalledWith(TRIP, 1, false)
|
||||
expect(result.current.lastRunFor(1)).toEqual({ pulled: 4, pushed: 2 })
|
||||
// a binding nobody ran in this session reports zeros, not someone else numbers
|
||||
expect(result.current.lastRunFor(2)).toEqual({ pulled: 0, pushed: 0 })
|
||||
// What a run moved is no longer kept: the flow bar shows standing holdings,
|
||||
// which is the question somebody opening the dialog actually has. The run's
|
||||
// own numbers were only ever on screen for the moment after pressing it.
|
||||
expect(result.current.links).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-017: a run that reports no numbers counts as nothing moved', async () => {
|
||||
syncNowApi.mockResolvedValue({ state: 'ok' })
|
||||
it('FE-DOCSYNC-HOOK-017: a refused run says so instead of vanishing into a void call', async () => {
|
||||
// syncNow is called as `void sync.syncNow(...)` from both shells, so a
|
||||
// rejection that escaped the hook reached nobody. An orphaned binding
|
||||
// answers 409 here, and the person pressing the button deserves the reason.
|
||||
syncNowApi.mockRejectedValueOnce({ response: { data: { error: 'link_orphaned' } } })
|
||||
const { result } = await mountLoaded()
|
||||
|
||||
await act(async () => { await result.current.syncNow(1, true) })
|
||||
let outcome: unknown
|
||||
await act(async () => { outcome = await result.current.syncNow(1) })
|
||||
|
||||
expect(syncNowApi).toHaveBeenCalledWith(TRIP, 1, true)
|
||||
expect(result.current.lastRunFor(1)).toEqual({ pulled: 0, pushed: 0 })
|
||||
expect(outcome).toBeNull()
|
||||
expect(result.current.error).toBe('link_orphaned')
|
||||
})
|
||||
|
||||
it('FE-DOCSYNC-HOOK-018: a refused save reports failure and surfaces the server reason', async () => {
|
||||
|
||||
@@ -92,12 +92,6 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
const [connections, setConnections] = useState<DocSyncConnection[]>([])
|
||||
const [links, setLinks] = useState<DocSyncLink[]>([])
|
||||
const [itemCounts, setItemCounts] = useState<Record<string, number>>({})
|
||||
/**
|
||||
* What the last run of each binding moved, so the flow bar can show numbers
|
||||
* on its lanes. Kept in memory rather than persisted: it describes one run,
|
||||
* and after a reload "nothing moved since you got here" is the honest answer.
|
||||
*/
|
||||
const [lastRun, setLastRun] = useState<Record<number, { pulled: number; pushed: number }>>({})
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [busy, setBusy] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -111,8 +105,21 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
*/
|
||||
const loadedOnce = useRef(false)
|
||||
|
||||
/**
|
||||
* Which load is the current one.
|
||||
*
|
||||
* Four requests go out per load and several loads overlap — every mutation
|
||||
* starts one, and so does every ping. Without a generation stamp the slowest
|
||||
* response wins, which on a binding somebody just changed means the screen
|
||||
* settles on the state from before the change.
|
||||
*/
|
||||
const generation = useRef(0)
|
||||
/** Whether the last failure came from loading rather than from a write. */
|
||||
const loadFailed = useRef(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!enabled) return
|
||||
const mine = ++generation.current
|
||||
if (!loadedOnce.current) setLoading(true)
|
||||
try {
|
||||
const [p, c, l, s] = await Promise.all([
|
||||
@@ -121,6 +128,7 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
docsyncApi.listLinks(tripId),
|
||||
docsyncApi.status(tripId),
|
||||
])
|
||||
if (mine !== generation.current) return
|
||||
setProviders(p as DocSyncProvider[])
|
||||
setConnections(c as DocSyncConnection[])
|
||||
// The status route carries the holdings; the links route does not, so the
|
||||
@@ -129,14 +137,28 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
const holdingsById = new Map((status.links ?? []).map(x => [x.id, x.holdings]))
|
||||
setLinks((l as DocSyncLink[]).map(x => ({ ...x, holdings: holdingsById.get(x.id) })))
|
||||
setItemCounts(status.items || {})
|
||||
setError(null)
|
||||
// Only a load failure is cleared here. A write that just failed reloads to
|
||||
// put the server's answer back on screen, and clearing unconditionally
|
||||
// wiped the reason it had set a moment earlier.
|
||||
setError(prev => (prev !== null && loadFailed.current ? null : prev))
|
||||
loadFailed.current = false
|
||||
loadedOnce.current = true
|
||||
} catch {
|
||||
// A failure here means the addon is off or the user lost access, both of
|
||||
// which the panel renders as "nothing to configure" rather than an alarm.
|
||||
setProviders([])
|
||||
} catch (e: unknown) {
|
||||
// A 403 or 404 really does mean "nothing to configure here" — the addon is
|
||||
// off or this person lost access — and blanking the panel is the honest
|
||||
// answer. Anything else is a failure to say so: blanking on a dropped
|
||||
// connection told the user their provider list was empty.
|
||||
if (mine !== generation.current) return
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
loadFailed.current = true
|
||||
if (status === 403 || status === 404) {
|
||||
setProviders([])
|
||||
setError(null)
|
||||
} else {
|
||||
setError(readError(e))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (mine === generation.current) setLoading(false)
|
||||
}
|
||||
}, [tripId, enabled])
|
||||
|
||||
@@ -228,20 +250,40 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
/**
|
||||
* Change one binding, optimistically.
|
||||
*
|
||||
* The reload in `finally` puts the server's answer back either way, so a
|
||||
* refused change corrects itself on screen — but it used to do that in
|
||||
* silence, with the rejection escaping into a `void` call site. The switch
|
||||
* simply flipped back and nobody said why.
|
||||
*/
|
||||
const updateLink = useCallback(async (linkId: number, patch: Record<string, unknown>) => {
|
||||
setLinks(prev => prev.map(l => (l.id === linkId ? { ...l, ...patch } as DocSyncLink : l)))
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.updateLink(tripId, linkId, patch)
|
||||
} finally {
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
// Reload first, so the optimistic value is corrected, then say why —
|
||||
// the other way round the reload cleared the message again.
|
||||
await load()
|
||||
setError(readError(e))
|
||||
return false
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
const removeLink = useCallback(async (linkId: number) => {
|
||||
setBusy('link')
|
||||
setError(null)
|
||||
try {
|
||||
await docsyncApi.deleteLink(tripId, linkId)
|
||||
await load()
|
||||
return true
|
||||
} catch (e: unknown) {
|
||||
setError(readError(e))
|
||||
return false
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
@@ -249,23 +291,26 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
|
||||
const syncNow = useCallback(async (linkId: number, full = false) => {
|
||||
setBusy(`sync-${linkId}`)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await docsyncApi.syncNow(tripId, linkId, full) as {
|
||||
state: string; pulled: number; pushed: number; conflicts: number; missing: number
|
||||
}
|
||||
setLastRun(prev => ({ ...prev, [linkId]: { pulled: res.pulled ?? 0, pushed: res.pushed ?? 0 } }))
|
||||
await load()
|
||||
return res
|
||||
} catch (e: unknown) {
|
||||
// A refused run is a thing the person asked for and did not get — an
|
||||
// orphaned binding answers 409 here — so it has to be said out loud
|
||||
// rather than escaping into the `void` at the call site. After the
|
||||
// reload, which would otherwise clear the message.
|
||||
await load()
|
||||
setError(readError(e))
|
||||
return null
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}, [tripId, load])
|
||||
|
||||
const lastRunFor = useCallback(
|
||||
(linkId: number) => lastRun[linkId] ?? { pulled: 0, pushed: 0 },
|
||||
[lastRun],
|
||||
)
|
||||
|
||||
const resolveConflict = useCallback(async (itemId: number, keep: 'trek' | 'provider' | 'both') => {
|
||||
await docsyncApi.resolve(tripId, itemId, keep)
|
||||
await load()
|
||||
@@ -281,7 +326,7 @@ export function useDocSync(tripId: number | string, enabled: boolean) {
|
||||
connectionFor, load,
|
||||
saveConnection, testConnection,
|
||||
loadScopes, createScope,
|
||||
createLink, updateLink, removeLink, syncNow, resolveConflict, lastRunFor,
|
||||
createLink, updateLink, removeLink, syncNow, resolveConflict,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user