Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9932 fix(collab): re-check access on live connections and keep mixed issue updates atomic (#11282)

Bohan Jiang7eeb7e984f29
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
index 1d0df9b6db..f764f1aa0e 100644
--- a/apps/collab/src/collab.test.ts
+++ b/apps/collab/src/collab.test.ts
@@ -606,3 +606,110 @@ describe("issue descriptions", () => {
expect(result.status).toBe(404);
});
});
+
+describe("access after joining", () => {
+ let access: ReturnType<typeof createCollabServer>;
+ let accessUrl = "";
+
+ beforeAll(async () => {
+ access = createCollabServer(
+ { port: 0, secret: SECRET, apiUrl, cdnDomain: "", storeDebounceMs: 100, storeMaxDebounceMs: 400 },
+ codec,
+ silent,
+ { refreshLeadMs: 1500, revalidateGraceMs: 300, sweepMs: 50 },
+ );
+ await access.server.listen(0);
+ accessUrl = `ws://127.0.0.1:${access.server.address.port}`;
+ });
+
+ afterAll(async () => {
+ await access.server.destroy();
+ });
+
+ /** Joins with a ticket expiring in `ttl` seconds; later tickets come from
+ * `next`, which may refuse by throwing. */
+ async function join(actor: Actor, ttl: number, next: () => string) {
+ let calls = 0;
+ const reasons: string[] = [];
+ const provider = new HocuspocusProvider({
+ url: accessUrl,
+ name: NAME,
+ document: new Y.Doc(),
+ token: () => {
+ calls += 1;
+ if (calls > 1) return next();
+ return signTicket(
+ { document: NAME, workspaceId: "ws", actor, readOnly: false, expiresAt: Math.floor(Date.now() / 1000) + ttl },
+ SECRET,
+ );
+ },
+ onClose: ({ event }) => reasons.push(event.reason),
+ });
+ providers.push(provider);
+ await waitFor(() => provider.isSynced);
+ return { provider, reasons, calls: () => calls };
+ }
+
+ const connections = () => access.server.hocuspocus.documents.get(NAME)?.getConnectionsCount() ?? 0;
+
+ it("renews a connection's ticket before it expires", async () => {
+ resetDoc("Hello");
+ const a = await join(ada, 2, () => ticket(ada));
+ await waitFor(() => a.calls() >= 2);
+ // Past the first ticket's expiry, the connection is still in.
+ await new Promise((resolve) => setTimeout(resolve, 2200));
+ expect(a.reasons).toEqual([]);
+ expect(connections()).toBe(1);
+ });
+
+ it("closes a connection that shows no fresh ticket by the time its ticket expires", async () => {
+ resetDoc("Hello");
+ const a = await join(ada, 2, () => {
+ throw new Error("access revoked");
+ });
+ await waitFor(() => a.reasons.includes("reauthenticate"), 4000);
+ expect(connections()).toBe(0);
+ });
+
+ it("refuses a fresh ticket issued to someone else", async () => {
+ resetDoc("Hello");
+ const a = await join(ada, 2, () => ticket(bob));
+ await waitFor(() => a.reasons.includes("reauthenticate"));
+ expect(connections()).toBe(0);
+ });
+
+ it("revalidates only the connections a revocation names", async () => {
+ resetDoc("Hello");
+ let allowed = true;
+ const a = await join(ada, 60, () => {
+ if (!allowed) throw new Error("access revoked");
+ return ticket(ada);
+ });
+ const b = await join(bob, 60, () => ticket(bob));
+ const revalidate = (body: unknown) =>
+ fetch(`http://127.0.0.1:${access.server.address.port}/internal/revalidate`, {
+ method: "POST",
+ headers: { "X-Collab-Secret": SECRET, "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ // Still allowed in: a fresh ticket keeps the connection.
+ const kept = await revalidate({ workspace_id: "ws", actor: { type: "member", id: ada.id } });
+ expect(await kept.json()).toEqual({ asked: 1 });
+ await waitFor(() => a.calls() >= 2);
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ expect(a.reasons).toEqual([]);
+
+ // Revoked: no ticket comes, and the connection is closed after the grace
+ // period. Others in the doc are untouched.
+ allowed = false;
+ await revalidate({ workspace_id: "ws", actor: { type: "member", id: ada.id } });
+ await waitFor(() => a.reasons.includes("reauthenticate"));
+ expect(b.reasons).toEqual([]);
+ expect(b.calls()).toBe(1);
+ expect(connections()).toBe(1);
+
+ expect((await revalidate({ workspace_id: "other" })).status).toBe(200);
+ expect((await revalidate({})).status).toBe(400);
+ });
+});
diff --git a/apps/collab/src/server.ts b/apps/collab/src/server.ts
index 8483c01d64..75a3f24d5c 100644
--- a/apps/collab/src/server.ts
+++ b/apps/collab/src/server.ts
@@ -1,8 +1,8 @@
import { timingSafeEqual } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
-import { isTransactionOrigin, Server } from "@hocuspocus/server";
+import { type Connection, isTransactionOrigin, Server } from "@hocuspocus/server";
import type { DocumentCodec } from "@multica/views/editor/schema/codec";
-import { CollabApi } from "./api";
+import { CollabApi, type DocumentType } from "./api";
import type { CollabConfig } from "./config";
import {
DocumentStore,
@@ -20,8 +20,51 @@ export interface ConnectionContext {
workspaceId: string;
/** The document epoch this client's local copy came from, if it has one. */
epoch?: string;
+ /** When the last ticket this connection showed expires, in ms. */
+ expiresAt: number;
+ /** Set once the connection is asked for a fresh ticket: when it is closed
+ * unless one arrives. */
+ dueBy?: number;
}
+/** Close reason for a connection that did not show a fresh ticket in time.
+ * The client joins again with a new one, which the API only mints for
+ * someone still allowed in. */
+export const REAUTHENTICATE_REASON = "reauthenticate";
+const REAUTHENTICATE_CLOSE_CODE = 4401;
+
+/** A connection stays only as long as its ticket: tickets are minted after
+ * the API checks access, so asking for fresh ones is how a connection keeps
+ * proving it. */
+export interface AccessTiming {
+ /** How long before its ticket expires a connection is asked for a new one. */
+ refreshLeadMs: number;
+ /** How long a connection asked to revalidate has to show a new ticket. */
+ revalidateGraceMs: number;
+ /** How often connections are checked. */
+ sweepMs: number;
+}
+
+export const DEFAULT_ACCESS_TIMING: AccessTiming = {
+ refreshLeadMs: 60_000,
+ revalidateGraceMs: 15_000,
+ sweepMs: 5_000,
+};
+
+/** Who must show a fresh ticket after the API revoked some access. */
+export interface RevalidateRequest {
+ workspace_id: string;
+ /** Only this person's or agent's connections. */
+ actor?: Pick<Actor, "type" | "id">;
+ /** Only connections to this document. */
+ document?: string;
+ /** Only connections to documents of this type. */
+ type?: DocumentType;
+}
+
+const reauthenticate = (message: string) =>
+ Object.assign(new Error(message), { code: REAUTHENTICATE_CLOSE_CODE, reason: REAUTHENTICATE_REASON });
+
export interface Logger {
info(msg: string, fields?: Record<string, unknown>): void;
warn(msg: string, fields?: Record<string, unknown>): void;
@@ -40,7 +83,12 @@ function parseToken(token: string): { ticket: string; epoch?: string } {
return { ticket: parsed.ticket, epoch: typeof parsed.epoch === "string" ? parsed.epoch : undefined };
}
-export function createCollabServer(config: CollabConfig, codec: DocumentCodec, log: Logger) {
+export function createCollabServer(
+ config: CollabConfig,
+ codec: DocumentCodec,
+ log: Logger,
+ timing: AccessTiming = DEFAULT_ACCESS_TIMING,
+) {
const api = new CollabApi(config.apiUrl, config.secret);
const store = new DocumentStore(api, codec, log);
@@ -59,7 +107,30 @@ export function createCollabServer(config: CollabConfig, codec: DocumentCodec, l
if (verified.document !== documentName) throw new Error("ticket is for another document");
if (!parseDocumentName(documentName)) throw new Error("unknown document");
if (verified.readOnly) connectionConfig.readOnly = true;
- return { actor: verified.actor, workspaceId: verified.workspaceId, epoch };
+ return { actor: verified.actor, workspaceId: verified.workspaceId, epoch, expiresAt: verified.expiresAt * 1000 };
+ },
+
+ // A fresh ticket the client sent when asked (see checkAccess). Thrown
+ // errors close the connection with their code and reason.
+ async onTokenSync({ token, documentName, connection }) {
+ const context = connection.context as ConnectionContext;
+ let verified;
+ try {
+ verified = verifyTicket(parseToken(token).ticket, config.secret);
+ } catch (error) {
+ throw reauthenticate(String(error));
+ }
+ if (
+ verified.document !== documentName ||
+ verified.workspaceId !== context.workspaceId ||
+ verified.actor.type !== context.actor.type ||
+ verified.actor.id !== context.actor.id
+ ) {
+ throw reauthenticate("ticket is for another connection");
+ }
+ if (verified.readOnly) connection.readOnly = true;
+ context.expiresAt = verified.expiresAt * 1000;
+ context.dueBy = undefined;
},
async onLoadDocument({ documentName }) {
@@ -89,6 +160,10 @@ export function createCollabServer(config: CollabConfig, codec: DocumentCodec, l
store.forget(documentName);
},
+ async onDestroy() {
+ clearInterval(sweep);
+ },
+
async onRequest({ request, response }) {
if (await handleRequest(request, response)) {
// Rejecting with a falsy value stops Hocuspocus's default response.
@@ -98,6 +173,54 @@ export function createCollabServer(config: CollabConfig, codec: DocumentCodec, l
});
store.hocuspocus = server.hocuspocus;
+ function* connections(): Generator<[string, Connection<ConnectionContext>]> {
+ for (const [name, document] of server.hocuspocus.documents) {
+ for (const connection of document.getConnections()) yield [name, connection as Connection<ConnectionContext>];
+ }
+ }
+
+ /** Asks a connection for a fresh ticket, closing it at `dueBy` without one. */
+ function requestTicket(connection: Connection<ConnectionContext>, dueBy: number) {
+ const context = connection.context;
+ context.dueBy = Math.min(context.dueBy ?? Infinity, dueBy);
+ connection.requestToken();
+ }
+
+ /** Closes connections past their ticket or revalidation deadline, and asks
+ * those whose ticket is about to expire for a new one. */
+ function checkAccess(now = Date.now()) {
+ for (const [name, connection] of connections()) {
+ const context = connection.context;
+ if (!context?.expiresAt) continue;
+ if (now >= Math.min(context.expiresAt, context.dueBy ?? Infinity)) {
+ log.info("connection access expired", { name, actor: `${context.actor.type}:${context.actor.id}` });
+ connection.close({ code: REAUTHENTICATE_CLOSE_CODE, reason: REAUTHENTICATE_REASON });
+ } else if (context.dueBy === undefined && context.expiresAt - now <= timing.refreshLeadMs) {
+ requestTicket(connection, context.expiresAt);
+ }
+ }
+ }
+ const sweep = setInterval(() => checkAccess(), timing.sweepMs);
+ sweep.unref();
+
+ /** The API revoked some access: everyone it may affect must show a fresh
+ * ticket within the grace period or be disconnected. Those still allowed
+ * in get one without noticing. */
+ function revalidate(req: RevalidateRequest): number {
+ const dueBy = Date.now() + timing.revalidateGraceMs;
+ let asked = 0;
+ for (const [name, connection] of connections()) {
+ const context = connection.context;
+ if (!context?.expiresAt || context.workspaceId !== req.workspace_id) continue;
+ if (req.actor && (context.actor.type !== req.actor.type || context.actor.id !== req.actor.id)) continue;
+ if (req.document && name !== req.document) continue;
+ if (req.type && parseDocumentName(name)?.type !== req.type) continue;
+ requestTicket(connection, dueBy);
+ asked++;
+ }
+ return asked;
+ }
+
const authorized = (request: IncomingMessage) => {
const given = Buffer.from(String(request.headers["x-collab-secret"] ?? ""));
const expected = Buffer.from(config.secret);
@@ -110,6 +233,22 @@ export function createCollabServer(config: CollabConfig, codec: DocumentCodec, l
send(response, 200, { ok: true, documents: server.hocuspocus.getDocumentsCount() });
return true;
}
+ if (url.pathname === "/internal/revalidate") {
+ if (request.method !== "POST") return send(response, 405, { error: "method not allowed" });
+ if (!authorized(request)) return send(response, 401, { error: "unauthorized" });
+ let body: RevalidateRequest;
+ try {
+ body = (await readJson(request)) as RevalidateRequest;
+ } catch {
+ return send(response, 400, { error: "invalid body" });
+ }
+ if (typeof body?.workspace_id !== "string" || !body.workspace_id) {
+ return send(response, 400, { error: "workspace_id is required" });
+ }
+ const asked = revalidate(body);
+ log.info("revalidating connections", { ...body, asked });
+ return send(response, 200, { asked });
+ }
const match = /^\/internal\/documents\/([^/]+)\/(write|edit|flush)$/.exec(url.pathname);
if (!match) return false;
if (request.method !== "POST") return send(response, 405, { error: "method not allowed" });
@@ -130,7 +269,7 @@ export function createCollabServer(config: CollabConfig, codec: DocumentCodec, l
}
}
- return { server, store };
+ return { server, store, checkAccess, revalidate };
}
function sendResult(response: ServerResponse, result: WriteResult): boolean {
diff --git a/packages/views/docs/components/doc-live-session.test.ts b/packages/views/docs/components/doc-live-session.test.ts
index 717e350052..7ab6d41197 100644
--- a/packages/views/docs/components/doc-live-session.test.ts
+++ b/packages/views/docs/components/doc-live-session.test.ts
@@ -11,6 +11,8 @@ const { apiMock, providers, sockets } = vi.hoisted(() => ({
onClose: (e: { event: { reason: string } }) => void;
};
destroyed: boolean;
+ tokensSent: number;
+ syncs: number;
awareness: { local: unknown; states: Map<number, unknown>; emit: () => void };
}>,
sockets: [] as Array<{ destroyed: boolean }>,
@@ -56,7 +58,15 @@ vi.mock("@hocuspocus/provider", () => {
constructor(public config: (typeof providers)[number]["config"]) {
providers.push(this);
}
+ tokensSent = 0;
+ syncs = 0;
attach() {}
+ async sendToken() {
+ this.tokensSent++;
+ }
+ startSync() {
+ this.syncs++;
+ }
destroy() {
this.destroyed = true;
}
@@ -301,6 +311,31 @@ describe("doc sessions", () => {
releaseDocSession(b, { discard: true });
});
+ it("joins again with a fresh ticket when the server asks it to reauthenticate", async () => {
+ vi.useFakeTimers();
+ const { url, docId } = ids();
+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);
+ const provider = providers.at(-1)!;
+ provider.config.onSynced({ state: true });
+
+ apiMock.createDocCollabTicket.mockRejectedValueOnce(new Error("offline"));
+ provider.config.onClose({ event: { reason: "reauthenticate" } });
+ // Unsynced until it is back in, so a page waiting too long goes solo.
+ expect(session.getState().synced).toBe(false);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(provider.tokensSent).toBe(0);
+
+ // The next try, later, gets a ticket and joins with it, keeping the doc.
+ apiMock.createDocCollabTicket.mockResolvedValueOnce(ticket(docId, { token: "fresh" }));
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect([provider.tokensSent, provider.syncs]).toEqual([1, 1]);
+ expect(JSON.parse(await provider.config.token()).ticket).toBe("fresh");
+ expect(providers).toHaveLength(1);
+ provider.config.onSynced({ state: true });
+ expect(session.getState().synced).toBe(true);
+ releaseDocSession(session, { discard: true });
+ });
+
it("ends a reset session once its page lets go, and starts the next one fresh", () => {
const { url, docId } = ids();
const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);
diff --git a/packages/views/docs/components/doc-live-session.ts b/packages/views/docs/components/doc-live-session.ts
index 865ceb6722..31d0190087 100644
--- a/packages/views/docs/components/doc-live-session.ts
+++ b/packages/views/docs/components/doc-live-session.ts
@@ -192,6 +192,13 @@ export function warmSocket(url: string) {
// ---- Sessions ------------------------------------------------------------------
+/** The collaboration server closes a connection with this reason when it did
+ * not show a fresh ticket in time (apps/collab REAUTHENTICATE_REASON). */
+const REAUTHENTICATE_REASON = "reauthenticate";
+/** Backoff for joining again after such a close. */
+const REJOIN_BASE_MS = 1_000;
+const REJOIN_MAX_MS = 30_000;
+
/** How long a session stays connected after its page closes. */
const SESSION_KEEP_MS = 60_000;
/** Sessions kept for pages that are closed; the oldest goes first. */
@@ -224,6 +231,8 @@ export class DocSession {
private keep: ReturnType<typeof setTimeout> | null = null;
private ticket: LiveTicket | null;
private destroyed = false;
+ private rejoins = 0;
+ private rejoinTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
readonly key: string,
@@ -265,11 +274,19 @@ export class DocSession {
return JSON.stringify({ ticket: ticket.token, epoch: typeof epoch === "string" ? epoch : undefined });
},
onSynced: ({ state }) => {
- if (state) this.update({ synced: true, ready: true });
+ if (!state) return;
+ this.rejoins = 0;
+ this.update({ synced: true, ready: true });
},
onStatus: ({ status }) => this.update({ connected: status === WebSocketStatus.Connected }),
onClose: ({ event }) => {
if (event.reason === "document-reset") this.update({ reset: true });
+ else if (event.reason === REAUTHENTICATE_REASON) {
+ // Unsynced until it is back in: a page that waits too long carries
+ // what was typed into solo editing (useDocCollab).
+ this.update({ synced: false });
+ this.rejoin();
+ }
},
});
this.provider.attach();
@@ -281,6 +298,29 @@ export class DocSession {
getState = (): DocSessionState => this.state;
+ /** Joins again over the open socket, as on a reconnect, keeping what was
+ * typed meanwhile. The API refuses a ticket to someone who lost access, so
+ * they stay out until the page gives up on the session. */
+ private rejoin() {
+ if (this.destroyed || this.rejoinTimer) return;
+ const delay = Math.min(REJOIN_MAX_MS, REJOIN_BASE_MS * 2 ** this.rejoins);
+ this.rejoins++;
+ this.rejoinTimer = setTimeout(async () => {
+ this.rejoinTimer = null;
+ let ticket: DocCollabTicket;
+ try {
+ ticket = await requestTicket(this.kind, this.docId);
+ } catch {
+ this.rejoin();
+ return;
+ }
+ if (this.destroyed || !ticket.enabled) return;
+ this.ticket = ticket;
+ await this.provider.sendToken();
+ if (!this.destroyed) this.provider.startSync();
+ }, delay);
+ }
+
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
@@ -366,6 +406,7 @@ export class DocSession {
if (this.destroyed) return;
this.destroyed = true;
if (this.keep) clearTimeout(this.keep);
+ if (this.rejoinTimer) clearTimeout(this.rejoinTimer);
this.provider.awareness?.off("change", this.updateCollaborators);
this.provider.destroy();
this.ydoc.destroy();
diff --git a/server/cmd/server/collab_listeners.go b/server/cmd/server/collab_listeners.go
new file mode 100644
index 0000000000..62eec3b633
--- /dev/null
+++ b/server/cmd/server/collab_listeners.go
@@ -0,0 +1,89 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+const collabRevalidateTimeout = 5 * time.Second
+
+// collabRevalidator is the part of *collab.Client the listeners use.
+type collabRevalidator interface {
+ Revalidate(ctx context.Context, req collab.RevalidateRequest) error
+}
+
+// registerCollabListeners makes live editors prove their access again when an
+// event may have revoked it. A ticket only checks access when an editor
+// joins; asking the affected connections for fresh tickets disconnects
+// whoever the API no longer lets in, and the rest do not notice. Connections
+// renew their tickets before they expire anyway, so a missed event delays
+// a revocation by at most a ticket's lifetime.
+func registerCollabListeners(bus *events.Bus, client collabRevalidator) {
+ revalidate := func(req collab.RevalidateRequest) {
+ if req.WorkspaceID == "" {
+ return
+ }
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), collabRevalidateTimeout)
+ defer cancel()
+ if err := client.Revalidate(ctx, req); err != nil {
+ slog.Warn("collab revalidate failed", "workspace_id", req.WorkspaceID, "document", req.Document, "error", err)
+ }
+ }()
+ }
+ member := func(workspaceID, userID string) {
+ if userID == "" {
+ return
+ }
+ revalidate(collab.RevalidateRequest{WorkspaceID: workspaceID, Actor: &collab.Actor{Type: "member", ID: userID}})
+ }
+
+ // Removed from the workspace, or a role change such as becoming a guest,
+ // who may not edit live at all.
+ bus.Subscribe(protocol.EventMemberRemoved, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ userID, _ := payload["user_id"].(string)
+ member(e.WorkspaceID, userID)
+ })
+ bus.Subscribe(protocol.EventMemberUpdated, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ switch m := payload["member"].(type) {
+ case handler.MemberWithUserResponse:
+ member(e.WorkspaceID, m.UserID)
+ case map[string]any:
+ userID, _ := m["user_id"].(string)
+ member(e.WorkspaceID, userID)
+ }
+ })
+
+ // A project's visibility or members decide who sees its issues. Docs do
+ // not depend on projects.
+ for _, eventType := range []string{protocol.EventProjectUpdated, protocol.EventProjectMembersChanged, protocol.EventProjectDeleted} {
+ bus.Subscribe(eventType, func(e events.Event) {
+ revalidate(collab.RevalidateRequest{WorkspaceID: e.WorkspaceID, Type: "issue"})
+ })
+ }
+
+ // An issue moved to another project may be hidden from some of its editors.
+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ if changed, _ := payload["project_changed"].(bool); !changed {
+ return
+ }
+ issue, ok := payload["issue"].(handler.IssueResponse)
+ if !ok {
+ return
+ }
+ revalidate(collab.RevalidateRequest{WorkspaceID: e.WorkspaceID, Document: collab.IssueDocumentName(issue.ID)})
+ })
+
+ bus.Subscribe(protocol.EventWorkspaceDeleted, func(e events.Event) {
+ revalidate(collab.RevalidateRequest{WorkspaceID: e.WorkspaceID})
+ })
+}
diff --git a/server/cmd/server/collab_listeners_test.go b/server/cmd/server/collab_listeners_test.go
new file mode 100644
index 0000000000..b0aacfbec8
--- /dev/null
+++ b/server/cmd/server/collab_listeners_test.go
@@ -0,0 +1,68 @@
+package main
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type fakeRevalidator chan collab.RevalidateRequest
+
+func (f fakeRevalidator) Revalidate(_ context.Context, req collab.RevalidateRequest) error {
+ f <- req
+ return nil
+}
+
+func TestCollabListenersRevalidateOnRevocation(t *testing.T) {
+ bus := events.New()
+ got := make(fakeRevalidator, 8)
+ registerCollabListeners(bus, got)
+ next := func() collab.RevalidateRequest {
+ t.Helper()
+ select {
+ case req := <-got:
+ return req
+ case <-time.After(2 * time.Second):
+ t.Fatal("no revalidation")
+ return collab.RevalidateRequest{}
+ }
+ }
+ none := func() {
+ t.Helper()
+ select {
+ case req := <-got:
+ t.Fatalf("unexpected revalidation: %+v", req)
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+ publish := func(eventType string, payload any) {
+ bus.Publish(events.Event{Type: eventType, WorkspaceID: "ws-1", ActorType: "member", ActorID: "admin", Payload: payload})
+ }
+
+ publish(protocol.EventMemberRemoved, map[string]any{"user_id": "u-1", "workspace_id": "ws-1"})
+ if req := next(); req.WorkspaceID != "ws-1" || req.Actor == nil || req.Actor.Type != "member" || req.Actor.ID != "u-1" {
+ t.Fatalf("member removed: %+v", req)
+ }
+
+ publish(protocol.EventMemberUpdated, map[string]any{"member": handler.MemberWithUserResponse{UserID: "u-2", Role: "guest"}})
+ if req := next(); req.Actor == nil || req.Actor.ID != "u-2" {
+ t.Fatalf("member updated: %+v", req)
+ }
+
+ publish(protocol.EventProjectMembersChanged, map[string]any{"project_id": "p-1"})
+ if req := next(); req.WorkspaceID != "ws-1" || req.Type != "issue" || req.Actor != nil {
+ t.Fatalf("project members changed: %+v", req)
+ }
+
+ publish(protocol.EventIssueUpdated, map[string]any{"issue": handler.IssueResponse{ID: "i-1"}, "project_changed": false})
+ none()
+ publish(protocol.EventIssueUpdated, map[string]any{"issue": handler.IssueResponse{ID: "i-1"}, "project_changed": true})
+ if req := next(); req.Document != collab.IssueDocumentName("i-1") {
+ t.Fatalf("issue moved: %+v", req)
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index fd9e8eaa98..e304e41a44 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -490,6 +490,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Error("live doc editing disabled", "error", err)
}
h.Collab = collabClient
+ if collabClient != nil {
+ registerCollabListeners(bus, collabClient)
+ }
h.ThemeStore = themeStoreFromEnv()
h.TaskService.FeatureFlags = opts.FeatureFlags
h.TaskService.Metrics = opts.BusinessMetrics
diff --git a/server/internal/collab/client.go b/server/internal/collab/client.go
index 337aa9915e..27bd5f94cc 100644
--- a/server/internal/collab/client.go
+++ b/server/internal/collab/client.go
@@ -97,6 +97,8 @@ type Result struct {
Merged bool `json:"merged"`
Conflicts []MergeConflict `json:"conflicts,omitempty"`
Failure *EditFailure `json:"failure,omitempty"`
+ // Loaded: a flushed document is open in the service.
+ Loaded bool `json:"loaded,omitempty"`
}
// Write, Edit and Flush address a live document by its service name:
@@ -110,10 +112,50 @@ func (c *Client) Edit(ctx context.Context, document string, req EditRequest) (Re
}
// Flush persists pending editor changes of a loaded document, so a read sees
-// what people have typed. Documents nobody has open return immediately.
-func (c *Client) Flush(ctx context.Context, document string) error {
- _, err := c.call(ctx, document, "flush", struct{}{})
- return err
+// what people have typed. Documents nobody has open return immediately;
+// loaded reports whether it was open.
+func (c *Client) Flush(ctx context.Context, document string) (loaded bool, err error) {
+ result, err := c.call(ctx, document, "flush", struct{}{})
+ return result.Loaded, err
+}
+
+// RevalidateRequest names the editors a revocation may affect. WorkspaceID
+// is required; the other fields narrow it down.
+type RevalidateRequest struct {
+ WorkspaceID string `json:"workspace_id"`
+ // Actor limits it to one person's or agent's connections; Name is unused.
+ Actor *Actor `json:"actor,omitempty"`
+ // Document limits it to one document (DocumentName, IssueDocumentName).
+ Document string `json:"document,omitempty"`
+ // Type limits it to documents of a type: "doc" or "issue".
+ Type string `json:"type,omitempty"`
+}
+
+// Revalidate asks the editors connected under req for fresh tickets, which
+// the API mints only for those still allowed in; the rest are disconnected.
+// Call it after revoking access to a workspace, project or issue.
+func (c *Client) Revalidate(ctx context.Context, req RevalidateRequest) error {
+ raw, err := json.Marshal(req)
+ if err != nil {
+ return err
+ }
+ endpoint := c.baseURL.JoinPath("internal", "revalidate")
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set(SecretHeader, c.secret)
+ resp, err := c.http.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("%w: %v", ErrUnavailable, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
+ return fmt.Errorf("revalidate returned %d: %s", resp.StatusCode, strings.TrimSpace(string(data)))
+ }
+ return nil
}
func (c *Client) call(ctx context.Context, document, op string, body any) (Result, error) {
diff --git a/server/internal/collab/collab_test.go b/server/internal/collab/collab_test.go
index 24ec2b1a13..5f7b465a83 100644
--- a/server/internal/collab/collab_test.go
+++ b/server/internal/collab/collab_test.go
@@ -118,7 +118,41 @@ func TestClientMapsServiceResponses(t *testing.T) {
}
srv.Close()
- if err = client.Flush(ctx, DocumentName("abc")); !errors.Is(err, ErrUnavailable) {
+ if _, err = client.Flush(ctx, DocumentName("abc")); !errors.Is(err, ErrUnavailable) {
+ t.Fatalf("unreachable err = %v, want ErrUnavailable", err)
+ }
+}
+
+func TestRevalidate(t *testing.T) {
+ var gotPath, gotSecret string
+ var got RevalidateRequest
+ status := http.StatusOK
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotSecret = r.URL.Path, r.Header.Get(SecretHeader)
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(`{"asked":1}`))
+ }))
+ defer srv.Close()
+ client, err := NewClient(srv.URL, "s3cret")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ req := RevalidateRequest{WorkspaceID: "ws-1", Actor: &Actor{Type: "member", ID: "u-1"}}
+ if err := client.Revalidate(ctx, req); err != nil {
+ t.Fatal(err)
+ }
+ if gotPath != "/internal/revalidate" || gotSecret != "s3cret" || got.WorkspaceID != "ws-1" || got.Actor == nil || got.Actor.ID != "u-1" {
+ t.Fatalf("request = %s %q %+v", gotPath, gotSecret, got)
+ }
+
+ status = http.StatusBadRequest
+ if err := client.Revalidate(ctx, req); err == nil {
+ t.Fatal("a refused revalidate must return an error")
+ }
+ srv.Close()
+ if err := client.Revalidate(ctx, req); !errors.Is(err, ErrUnavailable) {
t.Fatalf("unreachable err = %v, want ErrUnavailable", err)
}
}
diff --git a/server/internal/handler/doc_collab.go b/server/internal/handler/doc_collab.go
index fad02098b4..1dad2df5bf 100644
--- a/server/internal/handler/doc_collab.go
+++ b/server/internal/handler/doc_collab.go
@@ -156,7 +156,7 @@ func (h *Handler) flushDocCollab(ctx context.Context, docID pgtype.UUID) {
}
ctx, cancel := context.WithTimeout(ctx, docCollabFlushTimeout)
defer cancel()
- if err := h.Collab.Flush(ctx, collab.DocumentName(uuidToString(docID))); err != nil {
+ if _, err := h.Collab.Flush(ctx, collab.DocumentName(uuidToString(docID))); err != nil {
slog.Warn("doc collab flush failed", "doc_id", uuidToString(docID), "error", err)
}
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index c6046701d2..a05e84d269 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -4254,30 +4254,29 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
return
}
- // With live editing on, the description goes through its live session,
- // merged into what people are typing; the other fields follow as usual.
- // Everything above has been validated, so nothing is refused after it.
- // A write pinned to expected_revision stays a direct compare-and-swap of
- // the whole issue; the live session folds it in on its next save.
- if client := h.issueCollab(r.Context()); req.Description != nil && req.ExpectedRevision == nil && client != nil {
+ // With live editing on, a write of the description alone goes through its
+ // live session, merged into what people are typing. One that changes other
+ // fields too, or is pinned to expected_revision, commits as a single
+ // transaction below, so a field refused there never leaves the description
+ // changed; the live session takes the new description afterwards.
+ liveClient := h.issueCollab(r.Context())
+ if liveClient != nil && req.Description != nil && req.ExpectedRevision == nil && issueUpdateOnlyDescription(rawFields) {
writerType, writerID := h.resolveActor(r, userID, workspaceID)
- handled, ok := h.updateIssueDescriptionViaCollab(w, r, client, prevIssue, req, writerType, writerID)
+ handled, ok := h.updateIssueDescriptionViaCollab(w, r, liveClient, prevIssue, req, writerType, writerID)
if !ok {
return
}
if handled {
- if issueUpdateOnlyDescription(rawFields) {
- updated, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: prevIssue.ID, WorkspaceID: prevIssue.WorkspaceID})
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to load issue")
- return
- }
- h.writeIssueForCaller(w, r, updated)
+ updated, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: prevIssue.ID, WorkspaceID: prevIssue.WorkspaceID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
return
}
- req.Description, req.DescriptionBase, req.DescriptionBaseRevision = nil, nil, nil
- params.Description = pgtype.Text{}
+ h.writeIssueForCaller(w, r, updated)
+ return
}
+ // The service is unreachable; there is no session to tell.
+ liveClient = nil
}
// The agent this write hands the issue to gets the change as its own run,
@@ -4326,6 +4325,9 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
// Determine actor identity: agent (via X-Agent-ID header) or member.
actorType, actorID := h.resolveActor(r, userID, workspaceID)
h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
+ if liveClient != nil && issue.Description != prevIssue.Description {
+ h.syncIssueDescriptionCollab(r, liveClient, prevIssue, issue, actorType, actorID)
+ }
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
resp := issueToResponse(issue, prefix)
diff --git a/server/internal/handler/issue_description_collab.go b/server/internal/handler/issue_description_collab.go
index 7753e0e897..c54b12c5de 100644
--- a/server/internal/handler/issue_description_collab.go
+++ b/server/internal/handler/issue_description_collab.go
@@ -146,7 +146,7 @@ func (h *Handler) flushIssueDescriptionCollab(r *http.Request, issue db.Issue) d
}
ctx, cancel := context.WithTimeout(r.Context(), docCollabFlushTimeout)
defer cancel()
- if err := client.Flush(ctx, collab.IssueDocumentName(uuidToString(issue.ID))); err != nil {
+ if _, err := client.Flush(ctx, collab.IssueDocumentName(uuidToString(issue.ID))); err != nil {
slog.Warn("issue description collab flush failed", "issue_id", uuidToString(issue.ID), "error", err)
return issue
}
@@ -321,6 +321,31 @@ func (h *Handler) updateIssueDescriptionViaCollab(w http.ResponseWriter, r *http
return true, true
}
+// syncIssueDescriptionCollab hands a description written directly, past the
+// live session, to that session if anyone has it open, so editors see it now
+// instead of on their next save. It is merged into what they typed since.
+// Best effort: a session that misses it still folds it in when it next saves.
+func (h *Handler) syncIssueDescriptionCollab(r *http.Request, client *collab.Client, prev, issue db.Issue, actorType, actorID string) {
+ ctx, cancel := context.WithTimeout(r.Context(), docCollabFlushTimeout)
+ defer cancel()
+ document := collab.IssueDocumentName(uuidToString(issue.ID))
+ loaded, err := client.Flush(ctx, document)
+ if err == nil && loaded {
+ write := collab.WriteRequest{
+ Actor: h.collabActor(ctx, actorType, actorID),
+ BaseContent: &prev.Description.String,
+ Content: &issue.Description.String,
+ }
+ if task := h.wakeupSourceTaskID(r); task.Valid {
+ write.TaskID = uuidToString(task)
+ }
+ _, err = client.Write(ctx, document, write)
+ }
+ if err != nil {
+ slog.Warn("issue description collab sync failed", "issue_id", uuidToString(issue.ID), "error", err)
+ }
+}
+
// issueUpdateOnlyDescription reports whether an UpdateIssue body changes
// nothing but the description.
func issueUpdateOnlyDescription(raw map[string]json.RawMessage) bool {
diff --git a/server/internal/handler/issue_description_collab_test.go b/server/internal/handler/issue_description_collab_test.go
index 0acf0faf26..4d7e21ed9c 100644
--- a/server/internal/handler/issue_description_collab_test.go
+++ b/server/internal/handler/issue_description_collab_test.go
@@ -189,13 +189,13 @@ func TestUpdateIssueDescriptionGoesThroughTheLiveSession(t *testing.T) {
var updated IssueResponse
putIssueForTest(t, id, map[string]any{
- "description": "Mine", "description_base_revision": *start.DescriptionRevision, "status": "in_progress",
+ "description": "Mine", "description_base_revision": *start.DescriptionRevision,
}).Want(http.StatusOK).JSON(&updated)
if got.BaseContent == nil || *got.BaseContent != "Base" || got.Actor.ID != testUserID {
t.Fatalf("write must carry the description at its base revision: %+v", got)
}
- if updated.Description == nil || *updated.Description != "Mine" || updated.Status != "in_progress" {
- t.Fatalf("description and status must both land: %+v", updated)
+ if updated.Description == nil || *updated.Description != "Mine" {
+ t.Fatalf("description must land: %+v", updated)
}
mu.Lock()
@@ -222,6 +222,89 @@ func TestUpdateIssueDescriptionGoesThroughTheLiveSession(t *testing.T) {
}
}
+// An update that changes the description and other fields commits as one
+// transaction, so a field refused there cannot leave the description changed.
+// The live session takes the result afterwards.
+func TestUpdateIssueDescriptionWithOtherFieldsIsOneTransaction(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withFeatureFlag(t, testHandler, featureflags.IssueDescriptionLive, true)
+ id := dbfx.Issue(t, "mixed", testutil.Cols{"description": "Base"})
+ document := "issue:" + id
+
+ var mu sync.Mutex
+ var calls []string
+ var synced []collab.WriteRequest
+ loaded := false
+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ calls = append(calls, r.URL.Path)
+ switch r.URL.Path {
+ case "/internal/documents/" + document + "/flush":
+ if loaded {
+ _, _ = w.Write([]byte(`{"loaded":true,"revision":1}`))
+ } else {
+ _, _ = w.Write([]byte(`{"loaded":false}`))
+ }
+ case "/internal/documents/" + document + "/write":
+ var req collab.WriteRequest
+ _ = json.NewDecoder(r.Body).Decode(&req)
+ synced = append(synced, req)
+ _, _ = w.Write([]byte(`{"status":"ok","revision":1,"content":"","title":"","merged":false}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer service.Close()
+ useCollab(t, service.URL)
+ reset := func() {
+ mu.Lock()
+ defer mu.Unlock()
+ calls, synced = nil, nil
+ }
+
+ // An older client renames the issue from a title someone has since
+ // changed: the title conflicts, and the description must stay as it was.
+ putIssueForTest(t, id, map[string]any{"title": "Renamed elsewhere"}).Want(http.StatusOK)
+ reset()
+ putIssueForTest(t, id, map[string]any{
+ "title": "Mine", "title_base": "mixed", "description": "Mine", "description_base": "Base",
+ }).Want(http.StatusConflict)
+ if current := getIssueForTest(t, id); current.Description == nil || *current.Description != "Base" || current.Title != "Renamed elsewhere" {
+ t.Fatalf("a refused update must change nothing: %+v", current)
+ }
+ mu.Lock()
+ if len(calls) != 0 {
+ t.Fatalf("a refused update must not reach the live session: %v", calls)
+ }
+ mu.Unlock()
+
+ // Nobody has the description open: both fields land, nothing to sync.
+ var updated IssueResponse
+ putIssueForTest(t, id, map[string]any{"description": "Second", "status": "in_progress"}).Want(http.StatusOK).JSON(&updated)
+ if updated.Description == nil || *updated.Description != "Second" || updated.Status != "in_progress" {
+ t.Fatalf("description and status must both land: %+v", updated)
+ }
+ mu.Lock()
+ if len(synced) != 0 {
+ t.Fatalf("an unopened description must not be loaded to sync it: %v", calls)
+ }
+ loaded = true
+ mu.Unlock()
+
+ // Someone has it open: the session takes the new description, merged
+ // from the one the transaction replaced.
+ putIssueForTest(t, id, map[string]any{"description": "Third", "priority": "high"}).Want(http.StatusOK)
+ mu.Lock()
+ defer mu.Unlock()
+ if len(synced) != 1 || synced[0].BaseContent == nil || *synced[0].BaseContent != "Second" ||
+ synced[0].Content == nil || *synced[0].Content != "Third" || synced[0].Actor.ID != testUserID {
+ t.Fatalf("the open session must take the committed description: %+v", synced)
+ }
+}
+
func TestUpdateIssueDescriptionMergesFromTheFirstRevision(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")