mirror of
https://github.com/block/buzz.git
synced 2026-11-25 10:42:26 +00:00
Fixes the bug where running a dev build with stale localStorage would
publish outdated channel sections, sort preferences, starred channels,
and muted channels to the relay, clobbering the DMG installation's live
state.
## Root cause
All four sidebar-preference sync managers (`channelSectionsSync`,
`channelSortSync`, `channelStarsSync`, `channelMutesSync`) collapsed
five distinct fetch outcomes — no event, timeout, error, auth-race empty
result, decrypt/parse failure — into a single `null`. Each hook's boot
effect treated `null` as "no remote exists" and seed-published whatever
was in localStorage, stamped at `max(now, lastRemoteCreatedAt+1)` with
`lastRemoteCreatedAt` reset to 0 on every boot. A dev build with stale
localStorage therefore re-signed old state as newer, and the DMG's live
subscription applied it.
## Two guards
**1. Tri-state fetch result** (`found | absent | failed`) — decrypt
failure on an existing event reports `failed` and records
`event.created_at`, so seed-publish is blocked even when the payload is
unreadable.
**2. Persisted head watermark** (`sidebarSyncWatermark.ts`) — keyed
`{blobType, pubkey, normalizedRelayUrl}`, written to localStorage on
every observed remote event (before decrypt on all paths: initial fetch,
live subscription, `fetchOwnBlobBeforePublish`), hydrated at
construction. Any session that has ever seen a remote blob skips
seed-publish on the next boot even when the fetch returns empty. Relay
URLs are normalised via `shared/lib/normalizeRelayUrl` (also used by
profile storage) so the same relay written two ways never produces two
keys.
**Bootstrap owns the seed.** Each manager exposes
`bootstrap(localStore)` that fetches, records the raw head, and
delegates the decision to the single `runBootstrap` policy: hold on
`failed` or `absent + prior watermark`, seed on genuine first-sync
(`absent + zero watermark + non-empty local`), `apply-remote` when a
blob was found. Hooks only act on `apply-remote`; they cannot publish
during bootstrap. First-time sync is unchanged: successful EOSE with no
event, zero watermark, and non-empty local state still seeds.
## LWW baseline preservation
`fetchOwnBlobBeforePublish` for sections/sort snapshots the watermark
before `recordRemoteHead` advances it, then compares the fetched event
against the snapshot — advancing first would make `remote.createdAt >
lastRemoteCreatedAt` always false and silently kill the whole-blob LWW
merge. Stars/mutes merge per-entry via `mergeStores`, so no snapshot is
needed there.
## Relay lifecycle
All four hooks require a defined `relayUrl` (plumbed from
`communitiesHook.activeCommunity?.relayUrl` in `AppShell.tsx`); while it
is undefined no manager is constructed and no boot/live/reconnect effect
binds. All effects depend on `[pubkey, relayUrl]`, so community switches
tear down and rebind. `destroy()` cancels pending publishes without
flushing — flushing would race community switching and could publish
relay A's state to relay B via the shared `relayClient` singleton.
Pending debounce-window edits are intentionally dropped: stars/mutes
entries survive via per-entry merge on the next publish; a dropped
sections/sort edit is lost because bootstrap whole-blob-replaces from
remote on return.
Known trade-off: a first boot with the relay unreachable holds (never
seeds) until the user's next explicit edit — preferred over risking a
stale seed-publish.
## Files
- `sidebarSyncWatermark.ts` — watermark persistence + `runBootstrap`
policy (tri-state `FetchResult`, `readWatermark`, `advanceWatermark`)
- `shared/lib/normalizeRelayUrl.ts` — relay-URL normalisation shared by
watermark keys and profile storage
- `channelSectionsSync.ts`, `channelSortSync.ts`, `channelStarsSync.ts`,
`channelMutesSync.ts` — tri-state fetch, pre-decrypt `recordRemoteHead`
on all paths, sections/sort watermark snapshot for LWW, `bootstrap()`,
cancel-without-flush `destroy()`
- `useChannelSections.ts`, `useChannelSortPreference.ts`,
`useChannelStars.ts`, `useChannelMutes.ts` — act on `bootstrap()`
results, gate on `relayUrl`, `[pubkey, relayUrl]` deps on all effects
- `AppShell.tsx` — passes `activeCommunity?.relayUrl` to
`useChannelMutes` and `useChannelStars`
- `sidebarSyncTestHelpers.mjs` — shared fake-window/localStorage/Tauri
mocks for the four manager suites
- Test suites — mutation-sensitive coverage: `failed→hold`,
`absent+watermark→hold`, first-sync seeds, undecryptable head recorded
on all paths, relay-A/B watermark isolation, watermark restart
round-trip, sections/sort LWW baseline
---------
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
171 lines
5.3 KiB
TypeScript
171 lines
5.3 KiB
TypeScript
import { normalizeRelayUrl } from "@/shared/lib/normalizeRelayUrl";
|
|
|
|
const STORAGE_KEY_PREFIX = "buzz-channel-sections.v1";
|
|
|
|
export type ChannelSection = {
|
|
id: string;
|
|
name: string;
|
|
icon?: string;
|
|
order: number;
|
|
};
|
|
|
|
export type ChannelSectionStore = {
|
|
version: 1;
|
|
sections: ChannelSection[];
|
|
assignments: Record<string, string>;
|
|
};
|
|
|
|
export const DEFAULT_STORE: ChannelSectionStore = Object.freeze({
|
|
version: 1,
|
|
sections: [],
|
|
assignments: {},
|
|
});
|
|
|
|
/**
|
|
* Returns the localStorage key for channel sections.
|
|
*
|
|
* When `relayUrl` is provided the key is scoped to that relay (normalized via
|
|
* the same `normalizeRelayUrl` used by all relay-scoped local stores) so
|
|
* sections from different communities/relays don't bleed across each other.
|
|
* When omitted the legacy pubkey-only key is returned (used only during
|
|
* one-time migration in `readChannelSectionsStore`).
|
|
*/
|
|
export function storageKey(pubkey: string, relayUrl?: string): string {
|
|
if (!relayUrl) return `${STORAGE_KEY_PREFIX}:${pubkey}`;
|
|
const normalized = normalizeRelayUrl(relayUrl);
|
|
// Encode the normalized relay so it can't contain the `:` delimiter.
|
|
return `${STORAGE_KEY_PREFIX}:${pubkey}:${encodeURIComponent(normalized)}`;
|
|
}
|
|
|
|
export function stripOrphanedAssignments(
|
|
store: ChannelSectionStore,
|
|
): ChannelSectionStore {
|
|
const sectionIds = new Set(store.sections.map((s) => s.id));
|
|
const cleaned = Object.fromEntries(
|
|
Object.entries(store.assignments).filter(([, sid]) => sectionIds.has(sid)),
|
|
);
|
|
if (Object.keys(cleaned).length === Object.keys(store.assignments).length)
|
|
return store;
|
|
return { ...store, assignments: cleaned };
|
|
}
|
|
|
|
export function parseChannelSectionPayload(
|
|
json: unknown,
|
|
): ChannelSectionStore | null {
|
|
if (typeof json !== "object" || json === null) return null;
|
|
const obj = json as Record<string, unknown>;
|
|
const sections: ChannelSection[] = Array.isArray(obj.sections)
|
|
? obj.sections.flatMap((entry: unknown): ChannelSection[] => {
|
|
if (typeof entry !== "object" || entry === null) return [];
|
|
const section = entry as Record<string, unknown>;
|
|
if (
|
|
typeof section.id !== "string" ||
|
|
typeof section.name !== "string" ||
|
|
typeof section.order !== "number"
|
|
) {
|
|
return [];
|
|
}
|
|
const icon =
|
|
typeof section.icon === "string" && section.icon.trim().length > 0
|
|
? section.icon.trim()
|
|
: undefined;
|
|
return [
|
|
{
|
|
id: section.id,
|
|
name: section.name,
|
|
...(icon ? { icon } : {}),
|
|
order: section.order,
|
|
},
|
|
];
|
|
})
|
|
: [];
|
|
const assignments: Record<string, string> =
|
|
typeof obj.assignments === "object" &&
|
|
obj.assignments !== null &&
|
|
!Array.isArray(obj.assignments)
|
|
? Object.fromEntries(
|
|
Object.entries(obj.assignments as Record<string, unknown>).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
),
|
|
)
|
|
: {};
|
|
return stripOrphanedAssignments({ version: 1, sections, assignments });
|
|
}
|
|
|
|
function parseRaw(raw: string | null): ChannelSectionStore | null {
|
|
if (!raw) return null;
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (typeof parsed !== "object" || parsed === null || parsed.version !== 1) {
|
|
return null;
|
|
}
|
|
return parseChannelSectionPayload(parsed);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Read the section store for `pubkey` scoped to `relayUrl`.
|
|
*
|
|
* On first access for a scoped key, migrates any existing data from the
|
|
* legacy pubkey-only key so users don't lose their sections on upgrade.
|
|
* After a successful migration write the legacy key is deleted, making
|
|
* this a globally one-time operation — subsequent empty scoped-key reads
|
|
* (i.e. a different relay) won't see legacy data and won't trigger
|
|
* cross-relay contamination via the seed-publish path.
|
|
*/
|
|
export function readChannelSectionsStore(
|
|
pubkey: string,
|
|
relayUrl?: string,
|
|
): ChannelSectionStore {
|
|
try {
|
|
const key = storageKey(pubkey, relayUrl);
|
|
const raw = window.localStorage.getItem(key);
|
|
|
|
// Scoped key already has data — use it directly.
|
|
if (raw !== null) {
|
|
return parseRaw(raw) ?? DEFAULT_STORE;
|
|
}
|
|
|
|
// No scoped data yet. If we were given a relay scope, attempt a
|
|
// one-time migration from the legacy pubkey-only key.
|
|
if (relayUrl) {
|
|
const legacyKey = storageKey(pubkey);
|
|
const legacyRaw = window.localStorage.getItem(legacyKey);
|
|
const migrated = parseRaw(legacyRaw);
|
|
if (migrated && migrated.sections.length > 0) {
|
|
// Persist under the scoped key and remove the legacy key so this
|
|
// migration cannot fire again for any other relay scope.
|
|
try {
|
|
window.localStorage.setItem(key, JSON.stringify(migrated));
|
|
window.localStorage.removeItem(legacyKey);
|
|
} catch {
|
|
// Ignore write failures — we still return the migrated value.
|
|
}
|
|
return migrated;
|
|
}
|
|
}
|
|
|
|
return DEFAULT_STORE;
|
|
} catch {
|
|
return DEFAULT_STORE;
|
|
}
|
|
}
|
|
|
|
export function writeChannelSectionsStore(
|
|
pubkey: string,
|
|
store: ChannelSectionStore,
|
|
relayUrl?: string,
|
|
): boolean {
|
|
try {
|
|
window.localStorage.setItem(
|
|
storageKey(pubkey, relayUrl),
|
|
JSON.stringify(store),
|
|
);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|