Skip to content

Commit

Permalink
Refactor app initialize method call (#688)
Browse files Browse the repository at this point in the history
  • Loading branch information
d-gubert authored Dec 21, 2023
1 parent 0d8d413 commit 213d6b1
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 31 deletions.
2 changes: 1 addition & 1 deletion deno-runtime/handlers/app/construct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function wrapAppCode(code: string): (require: (module: string) => unknown) => Pr
) as (require: (module: string) => unknown) => Promise<Record<string, unknown>>;
}

export async function handlInitializeApp(params: unknown): Promise<boolean> {
export default async function handleConstructApp(params: unknown): Promise<boolean> {
if (!Array.isArray(params)) {
throw new Error('Invalid params', { cause: 'invalid_param_type' });
}
Expand Down
24 changes: 14 additions & 10 deletions deno-runtime/handlers/app/handler.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { Defined, JsonRpcError } from "jsonrpc-lite";
import { handlInitializeApp } from "./construct.ts";
import { Defined, JsonRpcError } from 'jsonrpc-lite';
import handleConstructApp from './construct.ts';
import handleInitialize from './initialize.ts';

export default async function handleApp(method: string, params: unknown): Promise<Defined | JsonRpcError> {
const [, appMethod] = method.split(':');

let result: Defined;

try {
if (appMethod === 'construct') {
result = await handlInitializeApp(params);
} else {
result = null;
switch (appMethod) {
case 'construct':
return await handleConstructApp(params);
case 'initialize':
return await handleInitialize();
default:
throw new JsonRpcError('Method not found', -32601);
}
} catch (e: unknown) {
if (!(e instanceof Error)) {
Expand All @@ -21,8 +23,10 @@ export default async function handleApp(method: string, params: unknown): Promis
return JsonRpcError.invalidParams(null);
}

if ((e.cause as string)?.includes('invalid_app')) {
return JsonRpcError.internalError({ message: 'App unavailable' });
}

return new JsonRpcError(e.message, -32000, e);
}

return result;
}
18 changes: 18 additions & 0 deletions deno-runtime/handlers/app/initialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { App } from '@rocket.chat/apps-engine/definition/App.ts';

import { AppObjectRegistry } from '../../AppObjectRegistry.ts';
import { AppAccessorsInstance } from '../../lib/accessors/mod.ts';

export default async function handleInitialize(): Promise<boolean> {
const app = AppObjectRegistry.get<App>('app');

if (typeof app?.initialize !== 'function') {
throw new Error('App must contain an initialize function', {
cause: 'invalid_app',
});
}

await app.initialize(AppAccessorsInstance.getConfigurationExtend(), AppAccessorsInstance.getEnvironmentRead());

return true;
}
4 changes: 2 additions & 2 deletions deno-runtime/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import handleApp from './handlers/app/handler.ts';

AppObjectRegistry.set('MESSAGE_SEPARATOR', Deno.args.at(-1));

async function handleRequest({ type, payload }: Messenger.JsonRpcRequest): Promise<void> {
async function requestRouter({ type, payload }: Messenger.JsonRpcRequest): Promise<void> {
// We're not handling notifications at the moment
if (type === 'notification') {
return Messenger.sendInvalidRequestError();
Expand Down Expand Up @@ -99,7 +99,7 @@ async function main() {
}

if (Messenger.isRequest(JSONRPCMessage)) {
await handleRequest(JSONRPCMessage);
await requestRouter(JSONRPCMessage);
}

if (Messenger.isResponse(JSONRPCMessage)) {
Expand Down
4 changes: 1 addition & 3 deletions src/server/AppManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -914,14 +914,12 @@ export class AppManager {

private async initializeApp(storageItem: IAppStorageItem, app: ProxiedApp, saveToDb = true, silenceStatus = false): Promise<boolean> {
let result: boolean;
const configExtend = this.getAccessorManager().getConfigurationExtend(storageItem.id);
const envRead = this.getAccessorManager().getEnvironmentRead(storageItem.id);

try {
await app.validateLicense();
await app.validateInstallation();

await app.call(AppMethod.INITIALIZE, configExtend, envRead);
await app.call(AppMethod.INITIALIZE);
await app.setStatus(AppStatus.INITIALIZED, silenceStatus);

result = true;
Expand Down
16 changes: 1 addition & 15 deletions src/server/ProxiedApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,7 @@ export class ProxiedApp implements IApp {
}

public async call(method: `${AppMethod}`, ...args: Array<any>): Promise<any> {
const logger = this.setupLogger(method);

try {
const result = await this.appRuntime.sendRequest({ method, params: args });

logger.debug('Result:', result);

return result;
} catch (e) {
logger.error('Error:', e);

throw e;
} finally {
await this.manager.getLogStorage().storeEntries(AppConsole.toStorageEntry(this.getID(), logger));
}
return this.appRuntime.sendRequest({ method: `app:${method}`, params: args });
}

public getStatus(): AppStatus {
Expand Down

0 comments on commit 213d6b1

Please sign in to comment.