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
18 changes: 17 additions & 1 deletion static/packages/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ const logOperations = operations.filter(operation =>
console.log(logOperations.map(({ functionName, method, path }) => ({ functionName, method, path })));
```

Each `ApiOperation` records the actual exported `functionName`, original OpenAPI `operationId`, method, path (relative to `API_BASE_PATH`), summary, description, tags, path parameter names, query metadata, explicit deprecation flag, `experimental` flag, `idempotent` flag, and `routing` declaration. `ApiQueryParameter` includes the name, required flag, description, type, and declared enum values (item values for arrays). Operation parameters override inherited path parameters.
Each `ApiOperation` records the actual exported `functionName`, original OpenAPI `operationId`, method, path (relative to `API_BASE_PATH`), summary, description, tags, path parameter names, query metadata, explicit deprecation flag, `experimental` flag, `idempotent` flag, `routing` declaration, and `projectScope` declaration when Sentry has one. `ApiQueryParameter` includes the name, required flag, description, type, and declared enum values (item values for arrays). Operation parameters override inherited path parameters.

`experimental` is `true` when Sentry marks the operation with the `x-sentry-experimental` OpenAPI extension, which it sets for endpoints under active development that may change. Their SDK docs also start with an **Experimental:** note. To find or reject experimental operations, for example in a lint rule or build check:

Expand Down Expand Up @@ -185,6 +185,22 @@ The path may include `API_BASE_PATH`, an origin or a query string, and a missing

`idempotent` tells retrying clients whether resending an identical request after a timeout or 5xx response is safe. It is always `true` for `GET`, `HEAD`, `OPTIONS`, and `TRACE`. Other methods are `true` only when Sentry marks the operation with the `x-sentry-idempotent` OpenAPI extension; `false` means not known to be idempotent, not known to be unsafe.

`projectScope` copies Sentry's `x-sentry-project-scope` declaration, which says how a request names the projects whose data it returns or changes. Clients that limit a caller to some projects read it instead of keeping their own endpoint list. `ApiProjectScope` is one of:

- `path`: the path names the project.
- `filter`: an organization endpoint that takes the `project` query parameter (numeric project IDs) and returns or changes only those projects' data.
- `org-metadata`: a read-only organization endpoint whose response holds no project's telemetry, such as settings, members, or integrations. Only on `GET`.
- `response:<pointer>`: a `GET` that looks something up by ID alone. The numeric ID of the project it belongs to is at `<pointer>` in the response body. `<pointer>` is an RFC 6901 JSON pointer in which a `*` segment matches every element of an array, such as `response:/projects/*/id`.

An operation without a declaration has no `projectScope`, which means it is not known to respect a project limit. The build fails on any other value, and on `org-metadata` or `response:` for a method other than `GET`:

```ts
import { matchOperation, type ApiProjectScope } from "@sentry/api/operations";

const scope: ApiProjectScope | undefined = matchOperation("GET", "/api/0/projects/acme/backend/")?.operation.projectScope;
scope; // "path"
```

The catalog is generated from the same schema and SDK output as each release. Consumers own search, grouping, ranking, and command aliases; the catalog does not fetch a live schema or infer undocumented API behavior.

### API reference data
Expand Down
29 changes: 29 additions & 0 deletions static/packages/api/lib/operation-catalog.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,34 @@ function routing(key, operation, pathParameters) {
return { silo, organizationParameter };
}

const PROJECT_SCOPES = new Set(["path", "filter", "org-metadata"]);
const RESPONSE_SCOPE = "response:";
// RFC 6901: "/"-separated segments, with "~" only in the escapes "~0" and "~1". A "*" segment needs no special case.
const JSON_POINTER = /^(\/([^/~]|~[01])*)+$/;

/**
* Copy Sentry's `x-sentry-project-scope` declaration, rejecting values that Sentry's
* schema build would also reject. An operation without one gets no `projectScope`.
*/
function projectScope(key, method, operation) {
const declared = operation["x-sentry-project-scope"];
if (declared === undefined) return {};
const invalid = reason => new Error(`${key} declares an unsupported x-sentry-project-scope ${JSON.stringify(declared)}: ${reason}`);
if (typeof declared !== "string") throw invalid("the value must be a string");
if (declared.startsWith(RESPONSE_SCOPE)) {
if (method !== "get") throw invalid("response: is only for GET");
if (!JSON_POINTER.test(declared.slice(RESPONSE_SCOPE.length))) {
throw invalid("response: must be followed by a JSON pointer such as /project/id");
}
return { projectScope: declared };
}
if (!PROJECT_SCOPES.has(declared)) {
throw invalid('the value must be "path", "filter", "org-metadata", or "response:<JSON pointer>"');
}
if (declared === "org-metadata" && method !== "get") throw invalid("org-metadata is only for GET");
return { projectScope: declared };
}

/** Operation-level parameters replace path-level parameters with the same name/in. */
function queryParameters(pathItem, operation) {
const parameters = new Map();
Expand Down Expand Up @@ -79,6 +107,7 @@ export function extractOperations(spec, sdkSource) {
// Other methods count only when Sentry marks them; PUT/DELETE handlers are not all idempotent.
idempotent: SAFE_METHODS.has(method) || operation["x-sentry-idempotent"] === true,
routing: routing(key, operation, pathParameters),
...projectScope(key, method, operation),
});
}
}
Expand Down
20 changes: 20 additions & 0 deletions static/packages/api/lib/operation-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@ export type ApiOperationRouting = {
readonly organizationParameter?: string;
};

/**
* How an operation's request names the projects whose data it returns or changes, from
* Sentry's `x-sentry-project-scope` OpenAPI extension:
* - `path`: the path names the project.
* - `filter`: an organization endpoint that takes the `project` query parameter (numeric
* project IDs) and returns or changes only those projects' data.
* - `org-metadata`: a read-only organization endpoint whose response holds no project's
* telemetry, such as settings, members, or integrations.
* - `response:<pointer>`: a GET that looks something up by ID alone. The numeric ID of
* the project it belongs to is at `<pointer>` in the response body, such as
* `response:/project/id`. `<pointer>` is an RFC 6901 JSON pointer in which a `*`
* segment matches every element of an array.
*/
export type ApiProjectScope = "path" | "filter" | "org-metadata" | `response:${string}`;

/** An operation shipped by this SDK version, without consumer-specific policy. */
export type ApiOperation = {
/** Actual exported SDK function name, after name normalization. */
Expand Down Expand Up @@ -59,4 +74,9 @@ export type ApiOperation = {
readonly idempotent: boolean;
/** Where Sentry declares the operation available. */
readonly routing: ApiOperationRouting;
/**
* How the request names the projects it reads or changes. Absent when Sentry has no
* declaration, which means the operation is not known to respect a project limit.
*/
readonly projectScope?: ApiProjectScope;
};
2 changes: 1 addition & 1 deletion static/packages/api/scripts/generate-operations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function emit({ sourceSpec }) {
])),
match,
),
f.createExportDeclaration(undefined, true, named(["ApiOperation", "ApiOperationRouting", "ApiQueryParameter"]), types),
f.createExportDeclaration(undefined, true, named(["ApiOperation", "ApiOperationRouting", "ApiProjectScope", "ApiQueryParameter"]), types),
f.createExportDeclaration(undefined, false, named(["API_BASE_PATH"]), f.createStringLiteral("./api-base-path.gen.ts")),
f.createExportDeclaration(undefined, false, named(["createOperationMatcher"]), match),
f.createExportDeclaration(undefined, true, named(["ApiOperationMatch", "ApiOperationMatcher", "ApiOperationTemplate"]), match),
Expand Down
7 changes: 6 additions & 1 deletion static/packages/api/test/operation-types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Public discovery types are readonly, including nested parameter metadata. */
import { operations, type ApiOperation, type ApiQueryParameter } from "@sentry/api/operations";
import { operations, type ApiOperation, type ApiProjectScope, type ApiQueryParameter } from "@sentry/api/operations";

const operation: ApiOperation | undefined = operations[0];
const parameter: ApiQueryParameter | undefined = operation?.queryParameters[0];
Expand All @@ -15,4 +15,9 @@ if (operation) {
}
// @ts-expect-error Enum values must not be changed by consumers.
parameter?.enum?.push("added");
const scope: ApiProjectScope | undefined = operation?.projectScope;
// @ts-expect-error Only Sentry's declared project scopes are values.
const unknownScope: ApiProjectScope = "project";
void value;
void scope;
void unknownScope;
43 changes: 43 additions & 0 deletions static/packages/api/test/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,49 @@ describe("operation discovery", () => {
.toThrow("organizationParameter organization_slug, which is not in its path");
});

test("copies Sentry's project scope declarations and rejects malformed ones", async () => {
const response = { responses: { "200": { description: "OK" } } };
const scoped = (operationId: string, scope: unknown) => ({ operationId, ...response, "x-sentry-project-scope": scope });
const spec = (scope: unknown, method = "get") => ({
...fixture(),
paths: {
...fixture().paths,
"/project/": { get: scoped("retrieveProject", "path") },
"/issues/": { put: scoped("updateIssues", "filter") },
"/members/": { get: scoped("listMembers", "org-metadata") },
"/short-ids/": { get: scoped("resolveShortId", "response:/projects/*/id") },
"/escaped/": { get: scoped("readEscaped", "response:/a~0b/~1c") },
"/thing/": { [method]: scoped("thing", scope) },
},
});
const get = await generate(spec("response:/project/id"));
expect(Object.fromEntries(get.catalog.map(operation => [operation.functionName, operation.projectScope]))).toEqual({
listMembers: "org-metadata",
listOrganizationEvents: undefined,
readEscaped: "response:/a~0b/~1c",
resolveShortId: "response:/projects/*/id",
retrieveProject: "path",
thing: "response:/project/id",
updateIssues: "filter",
});
expect(get.catalog.find(operation => operation.path === eventsPath)).not.toHaveProperty("projectScope");
for (const pointer of ["", "project/id", "/project/~2", "/project~"]) {
expect(() => extractOperations(spec(`response:${pointer}`), get.source)).toThrow(
`GET /thing/ declares an unsupported x-sentry-project-scope "response:${pointer}": response: must be followed by a JSON pointer such as /project/id`,
);
}

const put = await generate(spec("filter", "put"));
expect(put.catalog.find(operation => operation.path === "/thing/")?.projectScope).toBe("filter");
const error = "PUT /thing/ declares an unsupported x-sentry-project-scope";
expect(() => extractOperations(spec("org-metadata", "put"), put.source)).toThrow(`${error} "org-metadata": org-metadata is only for GET`);
expect(() => extractOperations(spec("response:/project/id", "put"), put.source))
.toThrow(`${error} "response:/project/id": response: is only for GET`);
expect(() => extractOperations(spec("project", "put"), put.source))
.toThrow(`${error} "project": the value must be "path", "filter", "org-metadata", or "response:<JSON pointer>"`);
expect(() => extractOperations(spec(["filter"], "put"), put.source)).toThrow(`${error} ["filter"]: the value must be a string`);
});

test("ships the released routing declarations", () => {
expect(operations.find(operation => operation.functionName === "listOrganizationProjects")?.routing)
.toEqual({ silo: "cell", organizationParameter: "organization_id_or_slug" });
Expand Down
Loading