feat: implementing ActionRegistry service to register distributed actions

Signed-off-by: benjdlambert <ben@blam.sh>
This commit is contained in:
benjdlambert
2025-05-26 18:27:24 +02:00
parent 872c5a5e18
commit 04592af953
11 changed files with 667 additions and 2 deletions
+6 -1
View File
@@ -20,6 +20,7 @@
"license": "Apache-2.0",
"exports": {
".": "./src/index.ts",
"./actionsRegistry": "./src/entrypoints/actionsRegistry/index.ts",
"./auditor": "./src/entrypoints/auditor/index.ts",
"./auth": "./src/entrypoints/auth/index.ts",
"./cache": "./src/entrypoints/cache/index.ts",
@@ -45,6 +46,9 @@
"types": "src/index.ts",
"typesVersions": {
"*": {
"actionsRegistry": [
"src/entrypoints/actionsRegistry/index.ts"
],
"auditor": [
"src/entrypoints/auditor/index.ts"
],
@@ -188,7 +192,8 @@
"winston-transport": "^4.5.0",
"yauzl": "^3.0.0",
"yn": "^4.0.0",
"zod": "^3.22.4"
"zod": "^3.22.4",
"zod-to-json-schema": "^3.20.4"
},
"devDependencies": {
"@aws-sdk/util-stream-node": "^3.350.0",
@@ -35,8 +35,10 @@ import { schedulerServiceFactory } from '@backstage/backend-defaults/scheduler';
import { urlReaderServiceFactory } from '@backstage/backend-defaults/urlReader';
import { userInfoServiceFactory } from '@backstage/backend-defaults/userInfo';
import { eventsServiceFactory } from '@backstage/plugin-events-node';
import { actionsRegistryServiceFactory } from './entrypoints/actionsRegistry';
export const defaultServiceFactories = [
actionsRegistryServiceFactory,
auditorServiceFactory,
authServiceFactory,
cacheServiceFactory,
@@ -0,0 +1,128 @@
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ActionsRegistryAction,
HttpAuthService,
LoggerService,
} from '@backstage/backend-plugin-api';
import PromiseRouter from 'express-promise-router';
import { Router, json } from 'express';
import { z, ZodType } from 'zod';
import zodToJsonSchema from 'zod-to-json-schema';
import { InputError, NotFoundError } from '@backstage/errors';
export class PluginActionsRegistry {
private constructor(
private readonly actions: Map<
string,
ActionsRegistryAction<ZodType, ZodType>
>,
private readonly router: Router,
private readonly logger: LoggerService,
private readonly httpAuth: HttpAuthService,
) {
this.bindRoutes();
}
static create({
httpAuth,
logger,
}: {
httpAuth: HttpAuthService;
logger: LoggerService;
}): PluginActionsRegistry {
return new PluginActionsRegistry(
new Map(),
PromiseRouter(),
logger,
httpAuth,
);
}
getRouter(): Router {
return this.router;
}
register<TInputSchema extends ZodType, TOutputSchema extends ZodType>(
options: ActionsRegistryAction<TInputSchema, TOutputSchema>,
): void {
this.actions.set(options.id, options as ActionsRegistryAction<any, any>);
}
private bindRoutes() {
this.router.use(json());
this.router.get('/.backstage/v1/actions', (_, res) => {
return res.json({
actions: Array.from(this.actions.entries()).map(([_id, action]) => ({
...action,
schema: {
input: action.schema?.input
? zodToJsonSchema(action.schema.input)
: zodToJsonSchema(z.any()),
output: action.schema?.output
? zodToJsonSchema(action.schema.output)
: zodToJsonSchema(z.any()),
},
})),
});
});
this.router.post(
'/.backstage/v1/actions/:actionId/invoke',
async (req, res) => {
const action = this.actions.get(req.params.actionId);
if (!action) {
throw new NotFoundError(`Action "${req.params.actionId}" not found`);
}
const input = action.schema?.input
? action.schema.input.safeParse(req.body)
: ({ success: true, data: undefined } as const);
if (!input.success) {
throw new InputError(
`Invalid input to action "${req.params.actionId}"`,
input.error,
);
}
const credentials = await this.httpAuth.credentials(req);
const result = await action.action({
input: input.data,
credentials,
logger: this.logger,
});
const output = action.schema?.output
? action.schema.output.safeParse(result)
: ({ success: true, data: result } as const);
if (!output.success) {
throw new InputError(
`Invalid output from action "${req.params.actionId}"`,
output.error,
);
}
return res.json({ response: output.data });
},
);
}
}
@@ -0,0 +1,367 @@
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
coreServices,
createBackendPlugin,
} from '@backstage/backend-plugin-api';
import {
mockCredentials,
mockServices,
startTestBackend,
} from '@backstage/backend-test-utils';
import { httpRouterServiceFactory } from '../httpRouter';
import request from 'supertest';
import { actionsRegistryServiceFactory } from './actionsRegistryServiceFactory';
describe('actionsRegistryServiceFactory', () => {
const defaultServices = [
actionsRegistryServiceFactory,
httpRouterServiceFactory,
mockServices.httpAuth.factory({
defaultCredentials: mockCredentials.user(),
}),
];
describe('typescript tests', () => {
it('should properly infer the input types', () => {
createBackendPlugin({
pluginId: 'my-plugin',
register(reg) {
reg.registerInit({
deps: {
actionsRegistry: coreServices.actionsRegistry,
},
async init({ actionsRegistry }) {
actionsRegistry.register({
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: z =>
z.object({
test: z.string(),
}),
output: z =>
z.object({
ok: z.boolean(),
}),
},
action: async ({ input: { test } }) => {
// @ts-expect-error - test is not a boolean
const _t: boolean = test;
return { ok: true };
},
});
},
});
},
});
expect(true).toBe(true);
});
it('should properly infer the output types', () => {
createBackendPlugin({
pluginId: 'my-plugin',
register(reg) {
reg.registerInit({
deps: {
actionsRegistry: coreServices.actionsRegistry,
},
async init({ actionsRegistry }) {
actionsRegistry.register({
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: z =>
z.object({
test: z.string(),
}),
output: z =>
z.object({
ok: z.boolean(),
}),
},
// @ts-expect-error - ok is not a boolean
action: async () => {
return { ok: 'bo' };
},
});
},
});
},
});
expect(true).toBe(true);
});
});
describe('/.backstage/v1/actions', () => {
it('should allow registering of actions', async () => {
const pluginSubject = createBackendPlugin({
pluginId: 'my-plugin',
register(reg) {
reg.registerInit({
deps: {
actionsRegistry: coreServices.actionsRegistry,
},
async init({ actionsRegistry }) {
actionsRegistry.register({
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: z =>
z.object({
name: z.string(),
}),
output: z =>
z.object({
ok: z.boolean(),
}),
},
action: async () => ({ ok: true }),
});
},
});
},
});
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
const { body, status } = await request(server).get(
'/api/my-plugin/.backstage/v1/actions',
);
expect(status).toBe(200);
expect(body).toMatchObject({
actions: [
{
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: {
type: 'object',
properties: {
name: {
type: 'string',
},
},
},
output: {
type: 'object',
properties: {
ok: {
type: 'boolean',
},
},
},
},
},
],
});
});
it('should allow registering of actions with no schema', async () => {
const pluginSubject = createBackendPlugin({
pluginId: 'my-plugin',
register(reg) {
reg.registerInit({
deps: {
actionsRegistry: coreServices.actionsRegistry,
},
async init({ actionsRegistry }) {
actionsRegistry.register({
name: 'test',
title: 'Test',
description: 'Test',
action: async () => ({ ok: true }),
});
},
});
},
});
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
const { body, status } = await request(server).get(
'/api/my-plugin/.backstage/v1/actions',
);
expect(status).toBe(200);
expect(body).toMatchObject({
actions: [
{
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: {},
output: {},
},
},
],
});
});
});
describe('/.backstage/v1/actions/:actionId/invoke', () => {
const mockAction = jest.fn();
beforeEach(() => {
mockAction.mockResolvedValue({ ok: true });
});
const pluginSubject = createBackendPlugin({
pluginId: 'my-plugin',
register(reg) {
reg.registerInit({
deps: {
actionsRegistry: coreServices.actionsRegistry,
},
async init({ actionsRegistry }) {
actionsRegistry.register({
name: 'test',
title: 'Test',
description: 'Test',
schema: {
input: z =>
z.object({
name: z.string(),
}),
output: z =>
z.object({
ok: z.boolean(),
}),
},
action: mockAction,
});
},
});
},
});
it('should throw an error if the action is not found', async () => {
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
const { body, status } = await request(server).post(
'/api/my-plugin/.backstage/v1/actions/test/invoke',
);
expect(status).toBe(404);
expect(body).toMatchObject({
error: {
message: 'Action "test" not found',
},
});
});
it('should throw an error if the action input does not match the schema', async () => {
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
const { body, status } = await request(server)
.post('/api/my-plugin/.backstage/v1/actions/my-plugin:test/invoke')
.send({
name: 123,
});
expect(status).toBe(400);
expect(body).toMatchObject({
error: {
message: expect.stringMatching(
'Invalid input to action "my-plugin:test"',
),
},
});
});
it('should call the action with the input', async () => {
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
await request(server)
.post('/api/my-plugin/.backstage/v1/actions/my-plugin:test/invoke')
.send({
name: 'test',
});
expect(mockAction).toHaveBeenCalledWith({
input: {
name: 'test',
},
credentials: {
$$type: '@backstage/BackstageCredentials',
principal: {
type: 'user',
userEntityRef: 'user:default/mock',
},
},
logger: expect.anything(),
});
});
it('should validate the output of the action if provided', async () => {
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
mockAction.mockResolvedValue({ ok: 'blob' });
const { body, status } = await request(server)
.post('/api/my-plugin/.backstage/v1/actions/my-plugin:test/invoke')
.send({
name: 'test',
});
expect(status).toBe(400);
expect(body).toMatchObject({
error: {
message: expect.stringMatching(
'Invalid output from action "my-plugin:test"',
),
},
});
});
it('should return the output of the action', async () => {
const { server } = await startTestBackend({
features: [pluginSubject, ...defaultServices],
});
const { body, status } = await request(server)
.post('/api/my-plugin/.backstage/v1/actions/my-plugin:test/invoke')
.send({
name: 'test',
});
expect(status).toBe(200);
expect(body).toMatchObject({ response: { ok: true } });
});
});
});
@@ -0,0 +1,57 @@
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ActionsRegistryActionOptions,
coreServices,
createServiceFactory,
} from '@backstage/backend-plugin-api';
import { PluginActionsRegistry } from './PluginActionsRegistry';
import { z, ZodType } from 'zod';
export const actionsRegistryServiceFactory = createServiceFactory({
service: coreServices.actionsRegistry,
deps: {
metadata: coreServices.pluginMetadata,
httpRouter: coreServices.httpRouter,
httpAuth: coreServices.httpAuth,
logger: coreServices.logger,
},
factory: ({ metadata, httpRouter, httpAuth, logger }) => {
const pluginActionsRegistry = PluginActionsRegistry.create({
httpAuth,
logger,
});
httpRouter.use(pluginActionsRegistry.getRouter());
return {
async register<
TInputSchema extends ZodType,
TOutputSchema extends ZodType,
>(options: ActionsRegistryActionOptions<TInputSchema, TOutputSchema>) {
pluginActionsRegistry.register({
...options,
id: `${metadata.getId()}:${options.name}`,
schema: {
input: options.schema?.input?.(z),
output: options.schema?.output?.(z),
},
});
},
};
},
});
@@ -0,0 +1,16 @@
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { actionsRegistryServiceFactory } from './actionsRegistryServiceFactory';
+2 -1
View File
@@ -63,7 +63,8 @@
"@types/express": "^4.17.6",
"@types/luxon": "^3.0.0",
"knex": "^3.0.0",
"luxon": "^3.0.0"
"luxon": "^3.0.0",
"zod": "^3.22.4"
},
"devDependencies": {
"@backstage/backend-test-utils": "workspace:^",
@@ -0,0 +1,66 @@
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { z, ZodType } from 'zod';
import { LoggerService } from './LoggerService';
import { BackstageCredentials } from './AuthService';
export type ActionsRegistryActionContext<TInputSchema extends ZodType> = {
input: z.infer<TInputSchema>;
logger: LoggerService;
credentials: BackstageCredentials;
};
// todo: opaque type?
export type ActionsRegistryAction<
TInputSchema extends ZodType,
TOutputSchema extends ZodType,
> = {
id: string;
name: string;
title: string;
description: string;
// todo: what about additional metadata?
schema?: {
input?: TInputSchema;
output?: TOutputSchema;
};
action: (
context: ActionsRegistryActionContext<TInputSchema>,
) => Promise<TOutputSchema extends ZodType ? z.infer<TOutputSchema> : void>;
};
export type ActionsRegistryActionOptions<
TInputSchema extends ZodType,
TOutputSchema extends ZodType,
> = {
name: string;
title: string;
description: string;
// todo: what about additional metadata?
schema?: {
input?: (zod: typeof z) => TInputSchema;
output?: (zod: typeof z) => TOutputSchema;
};
action: (
context: ActionsRegistryActionContext<TInputSchema>,
) => Promise<TOutputSchema extends ZodType ? z.infer<TOutputSchema> : void>;
};
export interface ActionsRegistryService {
register<TInputSchema extends ZodType, TOutputSchema extends ZodType>(
options: ActionsRegistryActionOptions<TInputSchema, TOutputSchema>,
): void;
}
@@ -35,6 +35,21 @@ export namespace coreServices {
id: 'core.auth',
});
/**
* Service for registering and managing actions.
*
* See {@link ActionsRegistryService}
* and {@link https://backstage.io/docs/backend-system/core-services/actions-registry | the service docs}
* for more information.
*
* @public
*/
export const actionsRegistry = createServiceRef<
import('./ActionsRegistryService').ActionsRegistryService
>({
id: 'core.actionsRegistry',
});
/**
* Authenticated user information retrieval.
*
@@ -14,6 +14,12 @@
* limitations under the License.
*/
export type {
ActionsRegistryService,
ActionsRegistryActionOptions,
ActionsRegistryActionContext,
ActionsRegistryAction,
} from './ActionsRegistryService';
export type {
AuditorService,
AuditorServiceCreateEventOptions,
+2
View File
@@ -3636,6 +3636,7 @@ __metadata:
yauzl: "npm:^3.0.0"
yn: "npm:^4.0.0"
zod: "npm:^3.22.4"
zod-to-json-schema: "npm:^3.20.4"
peerDependencies:
"@google-cloud/cloud-sql-connector": ^1.4.0
peerDependenciesMeta:
@@ -3738,6 +3739,7 @@ __metadata:
"@types/luxon": "npm:^3.0.0"
knex: "npm:^3.0.0"
luxon: "npm:^3.0.0"
zod: "npm:^3.22.4"
languageName: unknown
linkType: soft