diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md index 4280222bf..6d1f51bd9 100644 --- a/desktop/AGENTS.md +++ b/desktop/AGENTS.md @@ -116,6 +116,10 @@ Adding or changing a Tauri command touches these layers in order: `crates/test-http-api/tests/parity.rs`, with the reason 5. `src/` — call via `invoke("command_name", args)`, import types from `@bindings` +6. `src/lib/writes.ts` — a command that writes either names the cache keys it + affects in `writtenKeys` and `mappedWrites`, or is listed in `outsideCache` + in `tests/unit/writeCoverage.test.ts` with the reason; that test fails until + you do. Reads go in `outsideCache` too ### Tests for a feature @@ -146,6 +150,24 @@ Paginated list views (issues, patches, notifications) go through a domain `Service` backed by the SQLite adapter instead of the ports; new lists over large data sets should do the same. +## Data and reactivity + +Read `docs/adr/0005-reactivity.md` first. In short: + +- Route loaders read cached data with `load(...)` from `@app/lib/cobQueries`, + and views read the same keys with `createQuery`, so that both share it. Keys + come from `@radicle-gui/core/keys` +- Data a view keeps itself, such as a paginated list, refreshes with + `onInvalidate`. Its loader calls `markLoading` on the same key before it + reads, so that an update during the load isn't lost +- The backend forwards the node's ref updates and the changes other processes + make to the node's databases, and `src/lib/startup.svelte.ts` invalidates the + keys they affect. `invoke()` invalidates the keys of the user's own writes + from `src/lib/writes.ts`, since the node doesn't announce every write +- New data must not move what the user is looking at: keep scroll position, + selection and drafts, and pin what the user is reading with `pinned` when + replacing it would disturb them + ## Boards Read `docs/adr/0005-boards.md` before working on boards. diff --git a/desktop/src/lib/invoke.ts b/desktop/src/lib/invoke.ts index 2a8536884..7e590baf5 100644 --- a/desktop/src/lib/invoke.ts +++ b/desktop/src/lib/invoke.ts @@ -15,7 +15,6 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import type { RepoSummary } from "@bindings/repo/RepoSummary"; import type { TreePath } from "@bindings/repo/TreePath"; -import { keys } from "@radicle-gui/core/keys"; import { cached } from "@radicle-gui/ui/lib/cached"; import * as tauri from "@tauri-apps/api/core"; @@ -23,33 +22,23 @@ import { labs } from "@app/lib/labs"; import { projectsOf } from "@app/lib/projects"; import { queryClient } from "@app/lib/query"; import type { RepoListScope } from "@app/lib/repoListScope"; - -// Commands that change a repository's info: its issue and patch counts, and -// whether it is seeded. The node doesn't announce the user's own writes when -// announcing is off, so the cache learns of them here. -const countWrites = new Set([ - "create_issue", - "edit_issue", - "delete_issue", - "edit_patch", - "delete_patch", - "rebuild_issue_cache", - "rebuild_patch_cache", - "seed", - "unseed", -]); +import { writtenKeys } from "@app/lib/writes"; export async function invoke( cmd: string, args?: tauri.InvokeArgs, options?: tauri.InvokeOptions, ): Promise { - const result = await invokeCommand(cmd, args, options); - const rid = (args as { rid?: unknown } | undefined)?.rid; - if (countWrites.has(cmd) && typeof rid === "string") { - void queryClient.invalidateQueries({ queryKey: keys.repoInfo(rid) }); + let result: T | undefined; + try { + result = await invokeCommand(cmd, args, options); + return result; + } finally { + // Also after a failure: a command can fail after writing part of a change. + for (const queryKey of writtenKeys(cmd, args, result)) { + void queryClient.invalidateQueries({ queryKey }); + } } - return result; } async function invokeCommand( diff --git a/desktop/src/lib/writes.ts b/desktop/src/lib/writes.ts new file mode 100644 index 000000000..d3cf7bf98 --- /dev/null +++ b/desktop/src/lib/writes.ts @@ -0,0 +1,86 @@ +import type { Key } from "@radicle-gui/core/keys"; + +import { keys } from "@radicle-gui/core/keys"; +import { affectedKeys, cobTypes } from "@radicle-gui/core/refUpdates"; + +const { issue: ISSUE, patch: PATCH } = cobTypes; + +interface WriteArgs { + rid?: unknown; + cobId?: unknown; + new?: { id?: unknown }; + args?: { rid?: unknown }; +} + +// Write commands whose effect on the cache is mapped below. Other writes change +// data the cache doesn't hold. +export const mappedWrites = [ + "create_issue", + "edit_issue", + "delete_issue", + "create_issue_comment", + "edit_patch", + "delete_patch", + "create_patch_comment", + "create_patch_review", + "rebuild_issue_cache", + "rebuild_patch_cache", + "seed", + "unseed", + "clean", +]; + +// The keys a command's write affects, so that the user's own changes show +// whether or not the node announces them: it doesn't with announcing off, for +// reviews, or while it is stopped. Views that apply pinned state still wait +// for their own refetch. +export function writtenKeys( + cmd: string, + args: unknown, + result: unknown, +): Key[] { + const { rid, cobId, new: created, args: nested } = (args ?? {}) as WriteArgs; + const cob = (type: string, id: unknown) => + typeof rid === "string" && typeof id === "string" + ? affectedKeys({ rid, refs: [`refs/cobs/${type}/${id}`] }) + : []; + + switch (cmd) { + case "create_issue": + return cob(ISSUE, (result as { id?: unknown } | undefined)?.id); + case "edit_issue": + case "delete_issue": + return cob(ISSUE, cobId); + case "create_issue_comment": + return cob(ISSUE, created?.id); + case "edit_patch": + case "delete_patch": + return cob(PATCH, cobId); + case "create_patch_comment": + return cob(PATCH, created?.id); + // A review names its revision, not its patch, so every patch of the + // repository is refetched while shown. + case "create_patch_review": + return typeof nested?.rid === "string" + ? [keys.patchDetails(nested.rid), keys.patches(nested.rid)] + : []; + case "rebuild_issue_cache": + return typeof rid === "string" + ? [keys.issues(rid), keys.repoInfo(rid)] + : []; + case "rebuild_patch_cache": + return typeof rid === "string" + ? [keys.patches(rid), keys.repoInfo(rid)] + : []; + // The repository info says whether it is seeded, and the repository list + // shows the seeded ones. + case "seed": + case "unseed": + return typeof rid === "string" ? [keys.repoInfo(rid), keys.repos()] : []; + // Cleaning removes other peers' refs, which can change anything shown. + case "clean": + return typeof rid === "string" ? [keys.repo(rid), keys.repos()] : []; + default: + return []; + } +} diff --git a/desktop/src/views/repo/Issue.svelte b/desktop/src/views/repo/Issue.svelte index d04b2cebd..060923e65 100644 --- a/desktop/src/views/repo/Issue.svelte +++ b/desktop/src/views/repo/Issue.svelte @@ -109,13 +109,18 @@ const activityItems = $derived(issueTimeline(issue, activity)); - // After the user's own changes, refetch and show them right away. - async function reload() { - await queryClient.invalidateQueries({ - queryKey: query.queryKey, - refetchType: "all", - }); - description.apply(); + // After the user's own changes, refetch and show them right away. Only a + // change to the description itself shows its latest edit, so that acting on + // the rest of the issue doesn't swap the text the user is reading. + async function reload(commentId?: string) { + // Joins the refetch `invoke()` started after the write, if any. + await queryClient.invalidateQueries( + { queryKey: query.queryKey, refetchType: "all" }, + { cancelRefetch: false }, + ); + if (commentId !== undefined && commentId === issue.body?.id) { + description.apply(); + } } async function createComment( @@ -152,7 +157,7 @@ } catch (error) { console.error("Issue comment editing failed: ", error); } finally { - await reload(); + await reload(id); } } @@ -218,11 +223,12 @@ } catch (error) { console.error("Editing reactions failed", error); } finally { - await reload(); + await reload(commentId); } } async function deleteIssue() { + deleting = true; try { await invoke("delete_issue", { rid: repo.rid, diff --git a/desktop/src/views/repo/Patch.svelte b/desktop/src/views/repo/Patch.svelte index c9ddb95cf..5eac8e424 100644 --- a/desktop/src/views/repo/Patch.svelte +++ b/desktop/src/views/repo/Patch.svelte @@ -113,9 +113,11 @@ : loadedRevisions, ); - // Deleted elsewhere while shown, so there is nothing left to show. + // Deleted elsewhere while shown, so there is nothing left to show. Deleting + // it here navigates by itself. + let deleting = false; $effect(() => { - if (detail.current.data?.patch === null) { + if (detail.current.data && !detail.current.data.patch && !deleting) { void router.push({ resource: "repo.patches", rid: repo.rid, status }); } }); @@ -528,10 +530,11 @@ // After the user's own changes, refetch and show them right away. async function loadPatch() { - await queryClient.invalidateQueries({ - queryKey: query.queryKey, - refetchType: "all", - }); + // Joins the refetch `invoke()` started after the write, if any. + await queryClient.invalidateQueries( + { queryKey: query.queryKey, refetchType: "all" }, + { cancelRefetch: false }, + ); } // A draft review belongs to a single revision, mirroring the protocol's @@ -607,19 +610,22 @@ }); async function deletePatch() { + deleting = true; try { await invoke("delete_patch", { rid: repo.rid, cobId: patch.id, opts: { announce: $nodeRunning && $announce }, }); - void router.push({ + await router.push({ resource: "repo.patches", rid: repo.rid, status: patch.state.status, }); } catch (error) { console.error("Deleting patch failed", error); + } finally { + deleting = false; } } diff --git a/desktop/tests/e2e/repo/issue.spec.ts b/desktop/tests/e2e/repo/issue.spec.ts index 074aa6c76..d46f68007 100644 --- a/desktop/tests/e2e/repo/issue.spec.ts +++ b/desktop/tests/e2e/repo/issue.spec.ts @@ -92,13 +92,15 @@ test("create issue with only a title", async ({ page }) => { const save = page.getByRole("button", { name: /^Save/ }); await expect(save).toBeDisabled(); - await page.getByPlaceholder("Title").fill("An issue without a description"); + // Not a prefix of another test's title in the same repository, whose issue + // the list may show too. + await page.getByPlaceholder("Title").fill("A title-only issue"); await expect(save).toBeEnabled(); await save.click(); await expect(page).toHaveURL(/\/issues\/[0-9a-f]{40}/); await expect( - page.getByRole("button", { name: "An issue without a description" }), + page.getByRole("button", { name: "A title-only issue" }), ).toBeVisible(); }); diff --git a/desktop/tests/e2e/repo/patchEditing.spec.ts b/desktop/tests/e2e/repo/patchEditing.spec.ts index 7073ba519..6e02e33e1 100644 --- a/desktop/tests/e2e/repo/patchEditing.spec.ts +++ b/desktop/tests/e2e/repo/patchEditing.spec.ts @@ -4,6 +4,7 @@ import type { RadiclePeer } from "@tests/support/peerManager.js"; import { createProject } from "@tests/support/collaboration.js"; import { expect, + goto, reload, test, waitForCommand, @@ -98,7 +99,7 @@ test("the title and description can be edited", async ({ page, peer }) => { }); await expect(title).toBeVisible(); - await page.goto(`/repos/${rid}/patches/${patchId}?view=changes`); + await goto(page, `/repos/${rid}/patches/${patchId}?view=changes`); await page.getByText("Readers skim").hover(); await page.getByTitle("Edit description").click(); const editor = page.getByRole("textbox", { name: "textarea-comment" }); diff --git a/desktop/tests/unit/invoke.test.ts b/desktop/tests/unit/invoke.test.ts new file mode 100644 index 000000000..c4d1392c7 --- /dev/null +++ b/desktop/tests/unit/invoke.test.ts @@ -0,0 +1,54 @@ +import { keys } from "@radicle-gui/core/keys"; +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { invoke } from "@app/lib/invoke"; +import { queryClient } from "@app/lib/query"; + +vi.mock("@app/lib/query", async () => { + const { createQueryClient } = + await import("@radicle-gui/ui/lib/query.svelte"); + return { queryClient: createQueryClient() }; +}); + +const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries"); + +const rid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5"; +const id = "d87dcfe8c2b3200e78b128d9b959cfdf7063fefe"; + +afterEach(() => { + vi.unstubAllGlobals(); + invalidateQueries.mockClear(); +}); + +describe("invoke", () => { + test("a write refetches what it changed", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(new Response("null", { status: 200 })), + ); + await invoke("edit_issue", { rid, cobId: id }); + expect(invalidateQueries).toHaveBeenCalledWith({ + queryKey: keys.issue(rid, id), + }); + }); + + // A command can fail after writing part of a change. + test("a failed write still refetches what it may have changed", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("down"))); + await expect(invoke("edit_issue", { rid, cobId: id })).rejects.toThrow( + "down", + ); + expect(invalidateQueries).toHaveBeenCalledWith({ + queryKey: keys.issue(rid, id), + }); + }); + + test("a read refetches nothing", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(new Response("null", { status: 200 })), + ); + await invoke("issue_by_id", { rid, id }); + expect(invalidateQueries).not.toHaveBeenCalled(); + }); +}); diff --git a/desktop/tests/unit/writeCoverage.test.ts b/desktop/tests/unit/writeCoverage.test.ts new file mode 100644 index 000000000..c65e374aa --- /dev/null +++ b/desktop/tests/unit/writeCoverage.test.ts @@ -0,0 +1,251 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, expect, test } from "vitest"; + +import { mappedWrites, writtenKeys } from "@app/lib/writes"; + +// Commands that read, or write data the query cache doesn't hold. A new +// command has to be added here or to `mappedWrites`, so that a write which +// changes cached data can't be forgotten. +const outsideCache = [ + // Reads + "activity_by_issue", + "activity_by_patch", + "actor", + "actor_profile_history", + "actors_of_key", + "alias", + "artifact_binaries", + "artifact_node_running", + "artifact_node_status", + "board_links", + "check_radicle_cli", + "closed_actor_revisions", + "comment_threads_by_issue_id", + "compute_artifact_cid", + "config", + "decode_enrollment", + "diff_stats", + "get_commit_diff", + "get_diff", + "get_diff_text", + "get_embed", + "git_info", + "identity_by_repo", + "issue_by_id", + "joinable_actor", + "list_boards", + "list_canonical_tags", + "list_commits", + "list_issues", + "list_jobs", + "list_notifications", + "list_patches", + "list_releases", + "list_repo_commits", + "list_repo_refs", + "list_repos", + "list_repos_summary", + "notification_count", + "patch_by_id", + "release_by_id", + "release_counts", + "repo_blob", + "repo_blob_bytes", + "repo_by_id", + "repo_commit", + "repo_commit_count", + "repo_commits_by_prefix", + "repo_count", + "repo_readme", + "repo_split_tree_path", + "repo_tree", + "revisions_by_patch", + "search_aliases", + "seeded_artifacts", + "seeded_not_replicated", + "version", + // App and node state + "authenticate", + "init", + "pick_artifact_directory", + "pick_artifact_files", + "startup", + // Actor writes, after which the profile page reloads itself. A join code + // only changes the actor once another device approves it. + "approve_actor_revision", + "approve_enrollment", + "cancel_leave", + "create_actor", + "join_actor", + "leave_actor", + "reject_actor_revision", + "remove_actor_key", + "retire_actor", + "update_actor_profile", + "withdraw_actor_revision", + // Writes outside the cache: boards, releases, artifacts, embeds, files and + // notifications, which their views reload themselves. + "add_artifact_location", + "attest_artifact", + "clear_notifications", + "create_board", + "create_or_open_release", + "delete_release", + "download_artifact", + "redact_artifact", + "register_artifact", + "remove_artifact_location", + "remove_artifact_metadata", + "rename_board", + "save_diff_to_disk", + "save_embed_by_bytes", + "save_embed_by_path", + "save_embed_to_disk", + "seed_artifact", + "set_artifact_metadata", + "set_board_columns", + "unseed_artifact", + "update_board", +]; + +function backendCommands(): string[] { + const source = readFileSync( + join(__dirname, "../../crates/radicle-tauri/src/lib.rs"), + "utf8", + ); + const handler = source.match(/generate_handler!\[([\s\S]*?)\]\s*\)/); + if (!handler) throw new Error("No command handler found"); + return handler[1] + .replace(/\/\/.*$/gm, "") + .replace(/#\[[^\]]*\]/g, "") + .split(",") + .map(path => path.trim().split("::").pop() ?? "") + .filter(name => name !== ""); +} + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const path = join(dir, entry.name); + if (entry.isDirectory()) return sourceFiles(path); + return /\.(ts|svelte)$/.test(entry.name) ? [path] : []; + }); +} + +// The object literal starting at `start`, which is a `{`. +function objectAt(source: string, start: number): string { + let depth = 0; + for (let i = start; i < source.length; i++) { + if (source[i] === "{") depth++; + if (source[i] === "}" && --depth === 0) return source.slice(start, i + 1); + } + throw new Error("Unbalanced braces"); +} + +// The names of an object literal's own properties, with nested literals as +// objects of their own. +function shapeOf(literal: string): Record { + const shape: Record = {}; + const body = literal.slice(1, -1); + let depth = 0; + let start = 0; + const parts: string[] = []; + for (let i = 0; i < body.length; i++) { + if ("{[(".includes(body[i])) depth++; + if ("}])".includes(body[i])) depth--; + if (body[i] === "," && depth === 0) { + parts.push(body.slice(start, i)); + start = i + 1; + } + } + parts.push(body.slice(start)); + for (const part of parts) { + const match = part.trim().match(/^(\w+)\s*(?::\s*([\s\S]*))?$/); + if (!match) continue; + const value = match[2]?.trim(); + shape[match[1]] = value?.startsWith("{") + ? shapeOf(objectAt(value, 0)) + : "x"; + } + return shape; +} + +// Fills every property with an id, so that only the names matter. +function withIds(shape: Record): Record { + return Object.fromEntries( + Object.entries(shape).map(([name, value]) => [ + name, + typeof value === "object" && value !== null + ? withIds(value as Record) + : "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5", + ]), + ); +} + +// Each call of a mapped write in the app, with the shape of its arguments +// where they are written out in the call or in a variable of the same file. +function writeCalls(): { cmd: string; where: string; args: unknown }[] { + const calls = []; + for (const file of sourceFiles(join(__dirname, "../../src"))) { + const source = readFileSync(file, "utf8"); + const call = /invoke(?:<[^>]*>)?\(\s*"(\w+)"\s*,\s*(\{|\w+)/g; + for (const match of source.matchAll(call)) { + const [, cmd, arg] = match; + if (!mappedWrites.includes(cmd)) continue; + let literal: string | undefined; + if (arg === "{") { + literal = objectAt(source, match.index + match[0].length - 1); + } else { + const declared = source.lastIndexOf(`const ${arg} = {`, match.index); + if (declared >= 0) { + literal = objectAt(source, source.indexOf("{", declared)); + } + } + if (literal === undefined) continue; + calls.push({ + cmd, + where: `${file.split("/src/")[1]}`, + args: withIds(shapeOf(literal)), + }); + } + } + return calls; +} + +describe("write commands", () => { + const commands = backendCommands(); + + test("every backend command is classified once", () => { + const classified = [...mappedWrites, ...outsideCache]; + expect(new Set(classified).size).toBe(classified.length); + expect(commands.filter(cmd => !classified.includes(cmd))).toEqual([]); + }); + + test("every classified command exists", () => { + expect( + [...mappedWrites, ...outsideCache].filter(cmd => !commands.includes(cmd)), + ).toEqual([]); + }); + + test("every mapped write affects some keys", () => { + const rid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5"; + const id = "d87dcfe8c2b3200e78b128d9b959cfdf7063fefe"; + const args = { rid, cobId: id, new: { id }, args: { rid } }; + expect( + mappedWrites.filter(cmd => writtenKeys(cmd, args, { id }).length === 0), + ).toEqual([]); + }); + + test("every call of a mapped write names what it changes", () => { + const calls = writeCalls(); + expect(calls.length).toBeGreaterThan(10); + expect( + calls + .filter( + ({ cmd, args }) => writtenKeys(cmd, args, { id: "x" }).length === 0, + ) + .map(({ cmd, where }) => `${cmd} in ${where}`), + ).toEqual([]); + }); +}); diff --git a/desktop/tests/unit/writes.test.ts b/desktop/tests/unit/writes.test.ts new file mode 100644 index 000000000..5af67bc71 --- /dev/null +++ b/desktop/tests/unit/writes.test.ts @@ -0,0 +1,67 @@ +import { keys } from "@radicle-gui/core/keys"; +import { describe, expect, test } from "vitest"; + +import { writtenKeys } from "@app/lib/writes"; + +const rid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5"; +const id = "d87dcfe8c2b3200e78b128d9b959cfdf7063fefe"; + +describe("writtenKeys", () => { + test("an issue edit affects the issue, its list and the counts", () => { + expect(writtenKeys("edit_issue", { rid, cobId: id }, null)).toEqual([ + keys.issue(rid, id), + keys.issues(rid), + keys.repoInfo(rid), + ]); + }); + + test("a new issue is named by the command's result", () => { + expect(writtenKeys("create_issue", { rid }, { id })).toEqual([ + keys.issue(rid, id), + keys.issues(rid), + keys.repoInfo(rid), + ]); + }); + + test("a patch comment affects the patch it was made on", () => { + expect( + writtenKeys("create_patch_comment", { rid, new: { id } }, null), + ).toEqual([keys.patch(rid, id), keys.patches(rid), keys.repoInfo(rid)]); + }); + + test("a review refetches the repository's patches, which names none", () => { + const written = writtenKeys( + "create_patch_review", + { args: { rid, revision: id } }, + id, + ); + expect(written).toEqual([keys.patchDetails(rid), keys.patches(rid)]); + // A prefix, so it covers whichever patch the review is on. + expect(keys.patch(rid, id).slice(0, keys.patchDetails(rid).length)).toEqual( + [...keys.patchDetails(rid)], + ); + }); + + test("seeding changes the repository info and list, cleaning anything", () => { + expect(writtenKeys("seed", { rid }, null)).toEqual([ + keys.repoInfo(rid), + keys.repos(), + ]); + expect(writtenKeys("unseed", { rid }, null)).toEqual([ + keys.repoInfo(rid), + keys.repos(), + ]); + expect(writtenKeys("clean", { rid }, null)).toEqual([ + keys.repo(rid), + keys.repos(), + ]); + }); + + test("a failed issue creation names no issue", () => { + expect(writtenKeys("create_issue", { rid }, undefined)).toEqual([]); + }); + + test("reads affect nothing", () => { + expect(writtenKeys("issue_by_id", { rid, id }, null)).toEqual([]); + }); +}); diff --git a/shared/core/src/keys.ts b/shared/core/src/keys.ts index d6587a087..cc8a9d14e 100644 --- a/shared/core/src/keys.ts +++ b/shared/core/src/keys.ts @@ -35,6 +35,7 @@ export const keys = { patchList: (rid: string, status: string) => ["repo", rid, "patches", status] as const, patch: (rid: string, id: string) => ["repo", rid, "patch", id] as const, + patchDetails: (rid: string) => ["repo", rid, "patch"] as const, releases: (rid: string) => ["repo", rid, "releases"] as const, boards: (rid: string) => ["repo", rid, "boards"] as const, jobs: (rid: string) => ["repo", rid, "jobs"] as const, diff --git a/shared/core/src/refUpdates.ts b/shared/core/src/refUpdates.ts index 6d1110fa2..076b9cb60 100644 --- a/shared/core/src/refUpdates.ts +++ b/shared/core/src/refUpdates.ts @@ -9,12 +9,22 @@ export interface RefUpdate { refs?: string[]; } -const ISSUE = "xyz.radicle.issue"; -const PATCH = "xyz.radicle.patch"; -const JOB = "xyz.radworks.job"; -// Releases are artifact COBs. -const RELEASE = "dev.radicle.artifact"; -const BOARD = "works.monadic.board"; +// The type names of the COBs whose data has keys of its own. +export const cobTypes = { + issue: "xyz.radicle.issue", + patch: "xyz.radicle.patch", + job: "xyz.radworks.job", + // Releases are artifact COBs. + release: "dev.radicle.artifact", + board: "works.monadic.board", +} as const; +const { + issue: ISSUE, + patch: PATCH, + job: JOB, + release: RELEASE, + board: BOARD, +} = cobTypes; export function affectedKeys({ rid, refs }: RefUpdate): Key[] { if (refs === undefined) { diff --git a/shared/core/tests/refUpdates.test.ts b/shared/core/tests/refUpdates.test.ts index 9609beb5c..0afcc64ba 100644 --- a/shared/core/tests/refUpdates.test.ts +++ b/shared/core/tests/refUpdates.test.ts @@ -68,4 +68,22 @@ describe("affectedKeys", () => { }), ).toEqual([keys.repo(rid)]); }); + + test("signed refs alone affect nothing", () => { + expect( + affectedKeys({ + rid, + refs: [`refs/namespaces/${nid}/refs/rad/sigrefs`], + }), + ).toEqual([]); + }); + + test("an unknown COB type affects the whole repository", () => { + expect( + affectedKeys({ + rid, + refs: [`refs/namespaces/${nid}/refs/cobs/org.example.thing/${issue}`], + }), + ).toEqual([keys.repo(rid)]); + }); });