Skip to content
Open
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
104 changes: 104 additions & 0 deletions cli/src/commands/proposal/commands/status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb';
import type { Proposal } from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import { Command } from 'commander';
import pc from 'picocolors';
import { BaseCommandOptions } from '../../../core/types/types.js';
import { getProposalsByFederatedGraph } from '../utils.js';

type FindProposalResult = { success: true; proposal: Proposal } | { success: false; details: string };

const findProposal = async (
client: BaseCommandOptions['client'],
{
name,
federatedGraphName,
namespace,
}: {
name: string;
federatedGraphName: string;
namespace?: string;
},
): Promise<FindProposalResult> => {
const resp = await getProposalsByFederatedGraph({
client,
federatedGraphName,
namespace,
proposalName: name,
limit: 1,
offset: 0,
});

if (resp.response?.code !== EnumStatusCode.OK) {
return {
success: false,
details: resp.response?.details || `Failed to fetch proposal '${name}'.`,
};
}

const proposal = resp.proposals.find((item) => item.name === name);
if (proposal) {
return { success: true, proposal };
}

return {
success: false,
details: `Proposal '${name}' not found.`,
};
};

export default (opts: BaseCommandOptions) => {
const command = new Command('status');
command.description('Checks the status of an existing proposal for a federated graph.');
command.argument('<name>', 'The name of the proposal to check.');
command.requiredOption(
'-f, --federation-graph <federatedGraphName>',
'The name of the federated graph this proposal is for.',
);
command.option('-n, --namespace [string]', 'The namespace of the federated graph.', 'default');
command.option('-j, --json', 'Prints to the console in json format instead of text.');

command.action(async (name, options) => {
let result: FindProposalResult;

try {
result = await findProposal(opts.client, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't add try/catch block here even if agent tells you to. I'll try and document when this is required or not.
We don't really catch exceptions for code that calls RPC because that would make the codebase a bit tangled. Instead the CLI application has a top-level error handling in cli/src/index.ts that we use for catching unexpected errors.

But in most cases, network failures are handled by checking resp.response?.code !== EnumStatusCode.OK. The functions such as findProposal are then wrappers around RPC code and they model a result object with success property.

name,
federatedGraphName: options.federationGraph,
namespace: options.namespace,
});
} catch (error) {
result = {
success: false,
details: error instanceof Error ? error.message : 'An unknown error occurred.',
};
}

if (!result.success) {
if (options.json) {
console.log(
JSON.stringify({
status: 'error',
details: result.details,
}),
);
} else {
console.error(pc.red(result.details));
}
process.exitCode = 1;
return;
}

if (options.json) {
console.log(
JSON.stringify({
status: result.proposal.state,
}),
);
return;
}

console.log(`Proposal '${name}' status is ${result.proposal.state}.`);
});

return command;
};
2 changes: 2 additions & 0 deletions cli/src/commands/proposal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { Command } from 'commander';
import { BaseCommandOptions } from '../../core/types/types.js';
import { checkAuth } from '../auth/utils.js';
import CreateProposalCommand from './commands/create.js';
import StatusProposalCommand from './commands/status.js';
import UpdateProposalCommand from './commands/update.js';

export default (opts: BaseCommandOptions) => {
const command = new Command('proposal');
command.description('Provides commands for creating and maintaining proposals for a federated graph');
command.addCommand(CreateProposalCommand(opts));
command.addCommand(UpdateProposalCommand(opts));
command.addCommand(StatusProposalCommand(opts));

command.hook('preAction', async (thisCmd) => {
await checkAuth();
Expand Down
37 changes: 37 additions & 0 deletions cli/src/commands/proposal/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,43 @@ import { resolve } from 'pathe';
import { LabelSchema } from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import type { Label } from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import { splitLabel } from '@wundergraph/cosmo-shared';
import type { Client } from '../../core/client/client.js';
import { getBaseHeaders } from '../../core/config.js';

export const getProposalsByFederatedGraph = ({
Comment thread
comatory marked this conversation as resolved.
client,
federatedGraphName,
namespace,
proposalName,
startDate,
endDate,
limit,
offset,
}: {
client: Client;
federatedGraphName: string;
namespace?: string;
proposalName?: string;
startDate?: string;
endDate?: string;
limit?: number;
offset?: number;
}) => {
return client.platform.getProposalsByFederatedGraph(
{
federatedGraphName,
namespace,
proposalName,
startDate,
endDate,
limit,
offset,
},
{
headers: getBaseHeaders(),
},
);
};

// Define interfaces for parsing parameters
interface SubgraphParams {
Expand Down
150 changes: 150 additions & 0 deletions cli/test/proposal-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { type MessageInitShape } from '@bufbuild/protobuf';
import { createClient, createRouterTransport } from '@connectrpc/connect';
import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb';
import {
type GetProposalsByFederatedGraphRequest,
GetProposalsByFederatedGraphResponseSchema,
PlatformService,
} from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, test, vi, type MockInstance } from 'vitest';
import StatusProposalCommand from '../src/commands/proposal/commands/status.js';
import { Client } from '../src/core/client/client.js';

type GetProposalsResponse = MessageInitShape<typeof GetProposalsByFederatedGraphResponseSchema>;

function createMockTransport(
response: GetProposalsResponse,
onGetProposals?: (req: GetProposalsByFederatedGraphRequest) => void,
) {
return createRouterTransport(({ service }) => {
service(PlatformService, {
getProposalsByFederatedGraph: (req) => {
onGetProposals?.(req);
return response;
},
});
});
}

async function runStatus(
response: GetProposalsResponse,
args: string[] = [],
onGetProposals?: (req: GetProposalsByFederatedGraphRequest) => void,
): Promise<void> {
const client: Client = {
platform: createClient(PlatformService, createMockTransport(response, onGetProposals)),
};
const program = new Command();
program.exitOverride();
program.addCommand(StatusProposalCommand({ client }));
await program.parseAsync(['status', 'my-proposal', '--federation-graph', 'my-graph', ...args], { from: 'user' });
}

describe('proposal status', () => {
let logSpy: MockInstance<typeof console.log>;
let errorSpy: MockInstance<typeof console.error>;

beforeEach(() => {
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
process.exitCode = undefined;
vi.restoreAllMocks();
});

test('prints the proposal status as text', async () => {
let request: GetProposalsByFederatedGraphRequest | undefined;

await runStatus(
{
response: { code: EnumStatusCode.OK },
proposals: [{ name: 'my-proposal', state: 'DRAFT' }],
totalCount: 1,
},
['--namespace', 'production'],
(req) => {
request = req;
},
);

expect(request).toMatchObject({
federatedGraphName: 'my-graph',
namespace: 'production',
proposalName: 'my-proposal',
limit: 1,
offset: 0,
});
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Proposal 'my-proposal' status is DRAFT."));
expect(errorSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
});

test('prints the proposal status as json', async () => {
await runStatus(
{
response: { code: EnumStatusCode.OK },
proposals: [{ name: 'my-proposal', state: 'APPROVED' }],
totalCount: 1,
},
['--json'],
);

expect(logSpy).toHaveBeenCalledWith(JSON.stringify({ status: 'APPROVED' }));
expect(errorSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
});

test('uses the default namespace when none is specified', async () => {
let request: GetProposalsByFederatedGraphRequest | undefined;

await runStatus(
{
response: { code: EnumStatusCode.OK },
proposals: [{ name: 'my-proposal', state: 'DRAFT' }],
totalCount: 1,
},
[],
(req) => {
request = req;
},
);

expect(request?.namespace).toBe('default');
});

test('prints a json error and sets a non-zero exit code when the proposal is not found', async () => {
await runStatus(
{
response: { code: EnumStatusCode.OK },
proposals: [],
totalCount: 0,
},
['--json'],
);

expect(JSON.parse(String(logSpy.mock.calls[0][0]))).toEqual({
status: 'error',
details: "Proposal 'my-proposal' not found.",
});
expect(errorSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});

test('prints the control-plane error and sets a non-zero exit code', async () => {
await runStatus({
response: {
code: EnumStatusCode.ERR_NOT_FOUND,
details: 'Federated graph my-graph not found',
},
proposals: [],
totalCount: 0,
});

expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Federated graph my-graph not found'));
expect(logSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
});
15 changes: 13 additions & 2 deletions connect-go/gen/proto/wg/cosmo/platform/v1/platform.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion connect/src/wg/cosmo/platform/v1/platform_pb.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export function getProposalsByFederatedGraph(

const { proposals } = await proposalRepo.ByFederatedGraphId({
federatedGraphId: federatedGraph.id,
proposalName: req.proposalName,
startDate: dateRange.start,
endDate: dateRange.end,
limit: req.limit,
Expand All @@ -114,6 +115,7 @@ export function getProposalsByFederatedGraph(

const totalCount = await proposalRepo.countByFederatedGraphId({
federatedGraphId: federatedGraph.id,
proposalName: req.proposalName,
startDate: dateRange.start,
endDate: dateRange.end,
});
Expand Down
Loading
Loading