Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changes/feat-tracker-manifest-fake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Added

- **`trackerManifestContract`, `trackerManifestFixture` and `trackerManifestFake` in `@wirecat/cli-core/tracker/testing`
run `trackerSourceContract` over a tracker source built from a manifest**, with no code for the service: a CLI made
from `wirecat.config.ts` (linear-cli first) checks its tracker in one line,
`for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)`. The fake is
cli-base's strict `graphqlFake` with three rows of each kind behind it, written where the map reads them and linked
across kinds, paged by the Relay cursor, read for changes by the since, archived rows hidden unless asked for. The
fixture brings the held ids, a dead cursor and the faults `skewed`, `change`, `archive` and `remove`
([TRACKER.md](../docs/dev/TRACKER.md#the-contract-kit)).
33 changes: 33 additions & 0 deletions docs/dev/TRACKER.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,36 @@ result.
read again, `ids()` covering the full list, a dead cursor answering reset, a clock off by ten minutes either way, an
archived row still listed, a deleted row leaving `ids()`, a list cut after its first page, and a spent budget ending a
call that pages inside. `fakeTrackerSource` and `exampleTrackerRows` are an in-memory tracker for tests.

A source built from a manifest runs the contract with no code for the service, as a CLI made from `wirecat.config.ts`
does in its generated test:

```ts
for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)
```

- `trackerManifestFake(manifest, { api, definitions })` is cli-base's strict `graphqlFake` with a tracker behind it:
three rows of each kind, sampled within every selection the kind's calls send. The values the map reads are written
where it reads them: ids `issue-1`, a fixed seeded time, a state type from `STATE_TYPES`, an enum's own value. A
field that points at another kind (`state.id`, `assignee.id`, `labels.nodes` with `each`) holds that kind's first
row.
- It answers each call within its selection, two rows a page by the operation's cursor. A change read keeps the rows
whose `updatedAt` is at or after the value at its `"{since}"` (after it, for `gt`), oldest first. An operation that
takes `includeArchived` hides archived rows unless the call sets it.
- The only filter it applies is that since, and it must sit at `<the map's updatedAt path>.gte` or `.gt` inside
`filter`. Every call is refused when the since sits elsewhere (`createdAt.gte`, `updatedAt.lt`), when a list or id
call sends a `filter` (sync would mark the rows it leaves out deleted), and when a change call's `filter` holds
anything beside the since. Any other variable the fake cannot interpret, such as users' `includeDisabled: true`,
is trusted: it only picks which call of the manifest is answered, and the fake answers as if the tracker applied it.
- A call whose fixed variables match no call of the manifest, a cursor the fake never gave and an unreadable since are
refused and listed in `fake.refusals`, beside `graphqlFake`'s own (an unknown variable, a field the type lacks).
`touch`, `archive` and `remove` change a row on the tracker's side. Building the fake fails for a kind with
`changes` whose `updatedAt` the map does not read from a path.
- `trackerManifestFixture` adds the source over it, the ids it holds per kind (`held`), a dead cursor (`"not a
time"`, which the source answers with `reset` itself, without a call: the case checks the source, never the fake or
the tracker's own refusal of a stale cursor), and the faults
on the issue kind, else the last kind with `changes`: `skewed` and `change`, `archive` when the map reads
`archivedAt`, and `remove`. `trackerManifestContract` runs `trackerSourceContract` over it and fails a case whose
calls the fake refused, with the refusals as its message.
- It answers GraphQL operations paged by a cursor only. `self` is not part of the contract, so the fake leaves its call
to `graphqlFake`'s sample.
218 changes: 218 additions & 0 deletions src/testing/tracker-graphql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import type { ManifestOperation, SchemaNode } from "@wirecat/cli-base/codegen"
import type { ServiceApiManifest } from "../cli/service-api-manifest.js"
import type { TrackerKind } from "../domain/tracker.js"
import type { TrackerManifest } from "../tracker/manifest/manifest.js"

export const URL = "https://api.example-tracker.test/graphql"
export const KEY = "lin_api_fake"

const text: SchemaNode = { type: "string", nullable: true }
const ref = (name: string, nullable = true): SchemaNode => ({
type: "ref",
ref: name,
...(nullable ? { nullable } : {}),
})
const object = (properties: Record<string, SchemaNode>): SchemaNode => ({ type: "object", properties, required: [] })
const times = { createdAt: text, updatedAt: text, archivedAt: text }
const node = (properties: Record<string, SchemaNode>) => object({ id: { type: "string" }, ...times, ...properties })
const connection = (of: string) =>
object({ nodes: { type: "array", items: ref(of, false) }, pageInfo: ref("PageInfo", false) })

export const definitions: Record<string, SchemaNode> = {
PageInfo: object({ hasNextPage: { type: "boolean" }, endCursor: text }),
ListRequest: {
type: "object",
properties: {
first: { type: "integer", nullable: true },
after: text,
includeArchived: { type: "boolean", nullable: true },
orderBy: { type: "string", enum: ["createdAt", "updatedAt"], nullable: true },
filter: {
type: "object",
properties: {},
required: [],
additionalProperties: { type: "unknown" },
nullable: true,
},
},
required: [],
},
Team: node({ name: text, key: text }),
User: node({ name: text, email: text, active: { type: "boolean", nullable: true } }),
WorkflowState: node({ name: text, type: text, position: { type: "number", nullable: true }, team: ref("Team") }),
IssueLabel: node({ name: text, team: ref("Team") }),
ProjectStatus: object({ type: { type: "string", enum: ["backlog", "planned", "started", "completed"] } }),
Project: node({
name: text,
description: text,
state: text,
status: ref("ProjectStatus", false),
lead: ref("User"),
teams: ref("TeamConnection", false),
targetDate: text,
url: text,
}),
Issue: node({
identifier: text,
title: text,
description: text,
state: ref("WorkflowState"),
team: ref("Team"),
project: ref("Project"),
assignee: ref("User"),
creator: ref("User"),
labels: ref("IssueLabelConnection", false),
parent: ref("Issue"),
priority: { type: "number", nullable: true },
dueDate: text,
completedAt: text,
canceledAt: text,
url: text,
}),
Comment: node({ body: text, issue: ref("Issue"), user: ref("User"), url: text }),
}
for (const name of ["Team", "User", "WorkflowState", "IssueLabel", "Project", "Issue", "Comment"])
definitions[`${name}Connection`] = connection(name)

export const FIELDS: Record<TrackerKind, [field: string, type: string]> = {
team: ["teams", "Team"],
user: ["users", "User"],
state: ["workflowStates", "WorkflowState"],
label: ["issueLabels", "IssueLabel"],
project: ["projects", "Project"],
issue: ["issues", "Issue"],
comment: ["comments", "Comment"],
}

const listOperation = (field: string, type: string): ManifestOperation => ({
id: field,
command: field.toLowerCase(),
binding: {
kind: "graphql",
operation: "query",
field,
variables: {
first: "Int",
after: "String",
filter: `${type}Filter`,
includeArchived: "Boolean",
orderBy: "PaginationOrderBy",
},
selection: "nodes { id } pageInfo { hasNextPage endCursor }",
},
effect: "read",
tags: ["query"],
parameters: ["first", "after", "filter", "includeArchived", "orderBy"].map((name) => ({
name,
in: "body" as const,
required: false,
schema: (definitions.ListRequest as { properties: Record<string, SchemaNode> }).properties[name] as SchemaNode,
})),
request: { required: false, confidence: "contract", schema: "ListRequest" },
response: { confidence: "contract", schema: `${type}Connection` },
pagination: {
style: "cursor",
cursor: { in: "body", name: "after" },
next: "pageInfo.endCursor",
items: "nodes",
hasMore: "pageInfo.hasNextPage",
limit: { in: "body", name: "first" },
},
})

export const api: ServiceApiManifest = {
servers: [{ url: URL }],
securitySchemes: { key: { type: "apiKey", in: "header", name: "Authorization" } },
security: [{ key: [] }],
operations: [
...Object.values(FIELDS).map(([field, type]) => listOperation(field, type)),
{
id: "viewer",
command: "viewer",
binding: { kind: "graphql", operation: "query", field: "viewer", variables: {}, selection: "id" },
effect: "read",
tags: ["query"],
parameters: [],
response: { confidence: "contract", schema: "User" },
},
],
}

export const PAGE_INFO = "pageInfo { hasNextPage endCursor }"
const TIMES = "id createdAt updatedAt archivedAt"
const SELECTIONS: Record<TrackerKind, string> = {
team: `nodes { ${TIMES} name key } ${PAGE_INFO}`,
user: `nodes { ${TIMES} name email active } ${PAGE_INFO}`,
state: `nodes { ${TIMES} name type position team { id } } ${PAGE_INFO}`,
label: `nodes { ${TIMES} name team { id } } ${PAGE_INFO}`,
project: `nodes { ${TIMES} name description state lead { id } teams { nodes { id } } targetDate url } ${PAGE_INFO}`,
issue:
`nodes { ${TIMES} identifier title description state { id } team { id } project { id } assignee { id } ` +
`creator { id } labels { nodes { id } } parent { id } priority dueDate completedAt canceledAt url } ${PAGE_INFO}`,
comment: `nodes { ${TIMES} body issue { id } user { id } url } ${PAGE_INFO}`,
}
const TIME_MAP = { externalId: "id", createdAt: "createdAt", updatedAt: "updatedAt", archivedAt: "archivedAt" }
// A literal after `key:` reads as a permission key to src/cli/permission-keys.test.ts.
const TEAM_KEY = "key"
const ISSUE_KEY = "identifier"
const MAPS: { [K in TrackerKind]: Record<string, unknown> } = {
team: { ...TIME_MAP, name: "name", key: TEAM_KEY },
user: { ...TIME_MAP, name: "name", email: "email", active: "active" },
state: { ...TIME_MAP, name: "name", type: "type", position: "position", team: "team.id" },
label: { ...TIME_MAP, name: "name", team: "team.id" },
project: {
...TIME_MAP,
name: "name",
description: "description",
status: "state",
lead: "lead.id",
teams: { each: "teams.nodes", value: "id" },
targetDate: "targetDate",
url: "url",
},
issue: {
...TIME_MAP,
key: ISSUE_KEY,
title: "title",
description: "description",
state: "state.id",
team: "team.id",
project: "project.id",
assignee: "assignee.id",
creator: "creator.id",
labels: { each: "labels.nodes", id: "id" },
parent: "parent.id",
priority: "priority",
dueDate: "dueDate",
completedAt: "completedAt",
canceledAt: "canceledAt",
url: "url",
},
comment: { ...TIME_MAP, body: "body", issue: "issue.id", author: "user.id", url: "url" },
}

export const ALL = { first: 50, includeArchived: true }
export const MANIFEST = {
provider: "example-tracker",
kinds: ["team", "user", "state", "label", "project", "issue", "comment"],
entities: Object.fromEntries(
(Object.keys(FIELDS) as TrackerKind[]).map((kind) => {
const [operation] = FIELDS[kind]
return [
kind,
{
list: { operation, variables: ALL, selection: SELECTIONS[kind] },
changes: {
operation,
variables: { ...ALL, orderBy: "updatedAt", filter: { updatedAt: { gte: "{since}" } } },
selection: SELECTIONS[kind],
since: "iso",
},
ids: { operation, variables: ALL, selection: `nodes { id } ${PAGE_INFO}` },
map: MAPS[kind],
},
]
}),
),
self: { call: { operation: "viewer" }, path: "id" },
} as unknown as TrackerManifest
2 changes: 1 addition & 1 deletion src/tracker/manifest/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ const selects = (tree: Selection, steps: readonly string[]): boolean => {
}

/** The selection of one row: under the operation's `items` (a connection's `nodes`) or the call's own. */
const rowSelection = (tree: Selection, items: string | undefined): Selection | undefined => {
export const rowSelection = (tree: Selection, items: string | undefined): Selection | undefined => {
let inside: Selection | true | undefined = tree
for (const step of items?.split(".") ?? []) inside = inside === true ? undefined : inside?.[step]
return inside === true ? undefined : inside
Expand Down
Loading
Loading