Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add step to enable PHPMyAdmin in the phpmyadmin command #1665

Merged
merged 4 commits into from
Jan 25, 2024
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
48 changes: 40 additions & 8 deletions __tests__/commands/phpmyadmin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { PhpMyAdminCommand } from '../../src/commands/phpmyadmin';
import API from '../../src/lib/api';
import { CommandTracker } from '../../src/lib/tracker';

const mutationMock = jest.fn( async () => {
const generatePMAAccessMutationMock = jest.fn( async () => {
return Promise.resolve( {
data: {
generatePHPMyAdminAccess: {
Expand All @@ -21,10 +21,37 @@ const mutationMock = jest.fn( async () => {
} );
} );

const enablePMAMutationMock = jest.fn( async () => {
return Promise.resolve( {
data: {
enablePHPMyAdmin: {
success: true,
},
},
} );
} );

const pmaEnabledQueryMockTrue = jest.fn( async () => {
return Promise.resolve( {
data: {
app: {
environments: [
{
phpMyAdminStatus: {
status: 'enabled',
},
},
],
},
},
} );
} );

jest.mock( '../../src/lib/api' );
jest.mocked( API ).mockImplementation( () => {
return Promise.resolve( {
mutate: mutationMock,
mutate: generatePMAAccessMutationMock,
query: pmaEnabledQueryMockTrue,
} as any );
} );

Expand All @@ -42,20 +69,25 @@ describe( 'commands/PhpMyAdminCommand', () => {
openUrl.mockReset();
} );

it( 'should generate a URL by calling the right mutation', async () => {
it( 'should open the generated URL in browser', async () => {
await cmd.run();
expect( mutationMock ).toHaveBeenCalledWith( {
expect( pmaEnabledQueryMockTrue ).toHaveBeenCalledWith( {
query: expect.anything(),
variables: {
appId: 123,
envId: 456,
},
fetchPolicy: 'network-only',
} );
expect( enablePMAMutationMock ).not.toHaveBeenCalled();
expect( generatePMAAccessMutationMock ).toHaveBeenCalledWith( {
mutation: expect.anything(),
variables: {
input: {
environmentId: 456,
},
},
} );
} );

it( 'should open the generated URL in browser', async () => {
await cmd.run();
expect( openUrl ).toHaveBeenCalledWith( 'http://test-url.com' );
} );
} );
Expand Down
140 changes: 132 additions & 8 deletions src/commands/phpmyadmin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/**
* External dependencies
*/
import {
ApolloClient,
ApolloQueryResult,
FetchResult,
NormalizedCacheObject,
} from '@apollo/client';
import chalk from 'chalk';
import { GraphQLFormattedError } from 'graphql';
import { DocumentNode, GraphQLFormattedError } from 'graphql';
import gql from 'graphql-tag';

/**
Expand All @@ -14,9 +20,11 @@ import API, {
enableGlobalGraphQLErrorHandling,
} from '../lib/api';
import * as exit from '../lib/cli/exit';
import { ProgressTracker } from '../lib/cli/progress';
import { CommandTracker } from '../lib/tracker';
import { pollUntil } from '../lib/utils';

export const GENERATE_PHP_MY_ADMIN_URL_MUTATION = gql`
export const GENERATE_PHP_MY_ADMIN_URL_MUTATION: DocumentNode = gql`
mutation GeneratePhpMyAdminAccess($input: GeneratePhpMyAdminAccessInput) {
generatePHPMyAdminAccess(input: $input) {
expiresAt
Expand All @@ -25,12 +33,33 @@ export const GENERATE_PHP_MY_ADMIN_URL_MUTATION = gql`
}
`;

export const GET_PHP_MY_ADMIN_STATUS_QUERY: DocumentNode = gql`
query PhpMyAdminStatus($appId: Int!, $envId: Int!) {
app(id: $appId) {
environments(id: $envId) {
phpMyAdminStatus {
status
}
}
}
}
`;

export const ENABLE_PHP_MY_ADMIN_MUTATION: DocumentNode = gql`
mutation EnablePhpMyAdmin($input: EnablePhpMyAdminInput) {
enablePHPMyAdmin(input: $input) {
success
}
}
`;

async function generatePhpMyAdminAccess( envId: number ): Promise< string > {
// Disable global error handling so that we can handle errors ourselves
disableGlobalGraphQLErrorHandling();

const api = await API();
const resp = await api.mutate( {
const api: ApolloClient< NormalizedCacheObject > = await API();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const resp: FetchResult< any, Record< string, any >, Record< string, any > > = await api.mutate( {
mutation: GENERATE_PHP_MY_ADMIN_URL_MUTATION,
variables: {
input: {
Expand All @@ -46,46 +75,139 @@ async function generatePhpMyAdminAccess( envId: number ): Promise< string > {
return resp?.data?.generatePHPMyAdminAccess?.url as string;
}

async function enablePhpMyAdmin( envId: number ): Promise< string > {
// Disable global error handling so that we can handle errors ourselves
disableGlobalGraphQLErrorHandling();

const api: ApolloClient< NormalizedCacheObject > = await API();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const resp: FetchResult< any, Record< string, any >, Record< string, any > > = await api.mutate( {
mutation: ENABLE_PHP_MY_ADMIN_MUTATION,
variables: {
input: {
environmentId: envId,
},
},
} );

// Re-enable global error handling
enableGlobalGraphQLErrorHandling();

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return resp?.data?.generatePHPMyAdminAccess?.url as string;
}

async function getPhpMyAdminStatus( appId: number, envId: number ): Promise< string > {
// Disable global error handling so that we can handle errors ourselves
disableGlobalGraphQLErrorHandling();

const api: ApolloClient< NormalizedCacheObject > = await API();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const resp: ApolloQueryResult< any > = await api.query( {
query: GET_PHP_MY_ADMIN_STATUS_QUERY,
variables: { appId, envId },
fetchPolicy: 'network-only',
} );

// Re-enable global error handling
enableGlobalGraphQLErrorHandling();

// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return resp?.data?.app?.environments?.[ 0 ]?.phpMyAdminStatus?.status as string;
}

export class PhpMyAdminCommand {
app: App;
env: AppEnvironment;
silent?: boolean;
track: CommandTracker;
steps = {
ENABLE: 'enable',
GENERATE: 'generate',
};
private progressTracker: ProgressTracker;

constructor( app: App, env: AppEnvironment, trackerFn: CommandTracker = async () => {} ) {
this.app = app;
this.env = env;
this.track = trackerFn;
this.progressTracker = new ProgressTracker( [
{ id: this.steps.ENABLE, name: 'Enabling PHPMyAdmin for this site' },
{ id: this.steps.GENERATE, name: 'Generating access link' },
] );
}

log( msg: string ) {
log( msg: string ): void {
if ( this.silent ) {
return;
}
console.log( msg );
}

async openUrl( url: string ) {
stopProgressTracker(): void {
this.progressTracker.print();
this.progressTracker.stopPrinting();
}

async openUrl( url: string ): Promise< void > {
const { default: open } = await import( 'open' );
void open( url, { wait: false } );
}

async run( silent = false ) {
async getStatus(): Promise< string > {
try {
return await getPhpMyAdminStatus( this.app.id as number, this.env.id as number );
} catch ( err ) {
exit.withError(
'Failed to get PhpMyAdmin status. Please try again. If the problem persists, please contact support.'
);
}
}

async maybeEnablePhpMyAdmin(): Promise< void > {
const status = await this.getStatus();
if ( ! [ 'running', 'enabled' ].includes( status ) ) {
await enablePhpMyAdmin( this.env.id as number );
await pollUntil( this.getStatus.bind( this ), 1000, ( sts: string ) => sts === 'running' );

// Additional 30s for LB routing to be updated
await new Promise( resolve => setTimeout( resolve, 30000 ) );
}
}

async run( silent = false ): Promise< void > {
this.silent = silent;

if ( ! this.app.id ) {
exit.withError( 'No app was specified' );
}

if ( ! this.env.id ) {
exit.withError( 'No environment was specified' );
}

const message =
'Note: PHPMyAdmin sessions are read-only. If you run a query that writes to DB, it will fail.';
console.log( chalk.yellow( message ) );
this.log( 'Generating PhpMyAdmin URL...' );

this.progressTracker.startPrinting();
try {
this.progressTracker.stepRunning( this.steps.ENABLE );
await this.maybeEnablePhpMyAdmin();
this.progressTracker.stepSuccess( this.steps.ENABLE );
} catch ( err ) {
this.progressTracker.stepFailed( this.steps.ENABLE );
exit.withError( 'Failed to enable PhpMyAdmin' );
}

let url;
try {
this.progressTracker.stepRunning( this.steps.GENERATE );
url = await generatePhpMyAdminAccess( this.env.id );
this.progressTracker.stepSuccess( this.steps.GENERATE );
} catch ( err ) {
this.progressTracker.stepFailed( this.steps.GENERATE );
const error = err as Error & {
graphQLErrors?: GraphQLFormattedError[];
};
Expand All @@ -96,7 +218,9 @@ export class PhpMyAdminCommand {
} );
exit.withError( `Failed to generate PhpMyAdmin URL: ${ error.message }` );
}

void this.openUrl( url );
this.stopProgressTracker();
this.log( 'PhpMyAdmin is opened in your default browser.' );
}
}