-
Notifications
You must be signed in to change notification settings - Fork 55
fix(sessions): persist queued follow-ups across restart and offline #3267
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
packages/ui/src/features/sessions/queuedMessagePersistence.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import { | ||
| sessionStore, | ||
| sessionStoreSetters, | ||
| } from "@posthog/core/sessions/sessionStore"; | ||
| import type { QueuedMessage } from "@posthog/shared"; | ||
| import { logger } from "@posthog/ui/shell/logger"; | ||
| import { queuedMessageStoreApi } from "./queuedMessageStore"; | ||
|
|
||
| /** | ||
| * Keeps the durable {@link queuedMessageStoreApi} mirror in sync with each | ||
| * session's in-memory `messageQueue`, and rehydrates persisted follow-ups back | ||
| * into a session's core queue when it (re)appears for a task. | ||
| * | ||
| * A store subscription (rather than wrapping the injected setters) is used so | ||
| * EVERY queue mutation is captured — including the several UI call sites that | ||
| * mutate `sessionStoreSetters` directly (dock remove, steer/queue toggle, | ||
| * cancel-into-editor), which a service-seam wrapper would miss. | ||
| * | ||
| * Per task the flow is: on first observation, reconcile (merge persisted into | ||
| * core, dedup by id) BEFORE mirroring, so a freshly-created empty session can't | ||
| * wipe persisted messages that haven't been seeded yet. After reconciliation, | ||
| * queue changes mirror straight through (including drains → clear). Session | ||
| * removal un-reconciles the task so a later recreation re-seeds from disk. | ||
| */ | ||
|
|
||
| const log = logger.scope("queued-messages"); | ||
|
|
||
| const reconciledTasks = new Set<string>(); | ||
| const lastQueueByTask = new Map<string, QueuedMessage[]>(); | ||
| let unsubscribe: (() => void) | null = null; | ||
|
|
||
| function reconcileTask(taskId: string): void { | ||
| void queuedMessageStoreApi | ||
| .whenHydrated() | ||
| .then(() => { | ||
| const session = sessionStoreSetters.getSessionByTaskId(taskId); | ||
| // The session vanished before hydration completed — leave the persisted | ||
| // queue intact so a later recreation can still seed from it. | ||
| if (!session) { | ||
| return; | ||
| } | ||
|
|
||
| const persisted = queuedMessageStoreApi.get(taskId); | ||
| const current = session.messageQueue; | ||
| const existingIds = new Set(current.map((m) => m.id)); | ||
| const missing = persisted.filter((m) => !existingIds.has(m.id)); | ||
|
|
||
| if (missing.length > 0) { | ||
| // Persisted follow-ups predate anything typed this session, so they | ||
| // belong at the head. The resulting store change re-enters the | ||
| // subscription (now reconciled) and mirrors the merged queue. | ||
| log.info("Rehydrating persisted queued messages", { | ||
| taskId, | ||
| count: missing.length, | ||
| }); | ||
| sessionStoreSetters.prependQueuedMessages(taskId, missing); | ||
| return; | ||
| } | ||
|
|
||
| // Nothing to seed: make the mirror match the current queue. | ||
| lastQueueByTask.set(taskId, current); | ||
| queuedMessageStoreApi.set(taskId, current); | ||
| }) | ||
| .catch((error) => { | ||
| log.warn("Failed to reconcile persisted queued messages", { | ||
| taskId, | ||
| error, | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| function handleSession(taskId: string, queue: QueuedMessage[]): void { | ||
| if (!reconciledTasks.has(taskId)) { | ||
| // Mark eagerly so repeat observations before the async reconcile finishes | ||
| // don't schedule it twice. | ||
| reconciledTasks.add(taskId); | ||
| lastQueueByTask.set(taskId, queue); | ||
| reconcileTask(taskId); | ||
| return; | ||
| } | ||
|
|
||
| if (lastQueueByTask.get(taskId) === queue) { | ||
| return; | ||
| } | ||
| lastQueueByTask.set(taskId, queue); | ||
| queuedMessageStoreApi.set(taskId, queue); | ||
| } | ||
|
|
||
| /** | ||
| * Starts mirroring the core session store into the durable queue store. Safe to | ||
| * call repeatedly; only the first call installs the subscription. | ||
| */ | ||
| export function startQueuedMessagePersistence(): void { | ||
| if (unsubscribe) { | ||
| return; | ||
| } | ||
| unsubscribe = sessionStore.subscribe((state) => { | ||
| const present = new Set<string>(); | ||
| for (const session of Object.values(state.sessions)) { | ||
| present.add(session.taskId); | ||
| handleSession(session.taskId, session.messageQueue); | ||
| } | ||
| // A removed/evicted session un-reconciles its task so a later recreation | ||
| // re-seeds from disk instead of mirroring its empty starting queue. | ||
| for (const taskId of [...reconciledTasks]) { | ||
| if (!present.has(taskId)) { | ||
| reconciledTasks.delete(taskId); | ||
| lastQueueByTask.delete(taskId); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Drops all in-memory tracking. Pairs with `queuedMessageStoreApi.clearAll()` on | ||
| * logout / project switch so tracking doesn't leak across accounts. | ||
| */ | ||
| export function resetQueuedMessagePersistenceTracking(): void { | ||
| reconciledTasks.clear(); | ||
| lastQueueByTask.clear(); | ||
| } |
53 changes: 53 additions & 0 deletions
53
packages/ui/src/features/sessions/queuedMessageStore.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import type { QueuedMessage } from "@posthog/shared"; | ||
| import { beforeEach, describe, expect, it } from "vitest"; | ||
| import { | ||
| queuedMessageStoreApi, | ||
| useQueuedMessageStore, | ||
| } from "./queuedMessageStore"; | ||
|
|
||
| function msg(id: string, queuedAt = 1): QueuedMessage { | ||
| return { id, content: `content-${id}`, queuedAt }; | ||
| } | ||
|
|
||
| describe("queuedMessageStore", () => { | ||
| beforeEach(() => { | ||
| useQueuedMessageStore.setState({ byTaskId: {} }); | ||
| }); | ||
|
|
||
| it("stores and reads a per-task queue", () => { | ||
| queuedMessageStoreApi.set("task-1", [msg("a"), msg("b")]); | ||
| expect(queuedMessageStoreApi.get("task-1").map((m) => m.id)).toEqual([ | ||
| "a", | ||
| "b", | ||
| ]); | ||
| expect(queuedMessageStoreApi.get("task-2")).toEqual([]); | ||
| }); | ||
|
|
||
| it("drops the key when the queue is emptied", () => { | ||
| queuedMessageStoreApi.set("task-1", [msg("a")]); | ||
| queuedMessageStoreApi.set("task-1", []); | ||
| expect("task-1" in useQueuedMessageStore.getState().byTaskId).toBe(false); | ||
| }); | ||
|
|
||
| it("caps a task's queue to the newest messages", () => { | ||
| const many = Array.from({ length: 25 }, (_, i) => msg(`m${i}`, i)); | ||
| queuedMessageStoreApi.set("task-1", many); | ||
| const kept = queuedMessageStoreApi.get("task-1"); | ||
| expect(kept).toHaveLength(20); | ||
| // Newest (tail) retained. | ||
| expect(kept[0].id).toBe("m5"); | ||
| expect(kept.at(-1)?.id).toBe("m24"); | ||
| }); | ||
|
|
||
| it("clears a single task and clears all", () => { | ||
| queuedMessageStoreApi.set("task-1", [msg("a")]); | ||
| queuedMessageStoreApi.set("task-2", [msg("b")]); | ||
|
|
||
| queuedMessageStoreApi.clear("task-1"); | ||
| expect(queuedMessageStoreApi.get("task-1")).toEqual([]); | ||
| expect(queuedMessageStoreApi.get("task-2").map((m) => m.id)).toEqual(["b"]); | ||
|
|
||
| queuedMessageStoreApi.clearAll(); | ||
| expect(useQueuedMessageStore.getState().byTaskId).toEqual({}); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
itblockThe
"clears a single task and clears all"test verifies bothclear(taskId)andclearAll()in sequence; a failure in the first assertion makes the second unreachable and the root cause ambiguous. Splitting these into two tests (and preferring parameterised form for the cap-boundary cases, per the project's convention) would make test failures self-describing.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!