Skip to content

Commit

Permalink
Decouple oss module from pro module
Browse files Browse the repository at this point in the history
  • Loading branch information
sudharsan-selvaraj committed Apr 13, 2024
1 parent 449f48e commit 422e41e
Show file tree
Hide file tree
Showing 13 changed files with 128 additions and 117 deletions.
37 changes: 0 additions & 37 deletions src/WebsocketHandler.ts

This file was deleted.

12 changes: 0 additions & 12 deletions src/app/routers/grid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,6 @@ import { DeviceFarmManager } from '../../device-managers';
import Container from 'typedi';
import { IPluginArgs } from '../../interfaces/IPluginArgs';
import { IDevice } from '../../interfaces/IDevice';
import {
closeSession,
createDriverSession,
installAndroidStreamingApp,
installApk,
installIOSAppOnRealDevice
} from '../../modules/device-control/DeviceHelper';
import path from 'path';
import multer from 'multer';

Expand Down Expand Up @@ -280,11 +273,6 @@ function register(router: Router, pluginArgs: IPluginArgs) {
router.get('/node/status', nodeAdbStatusOnThisHost);
router.get('/node/:host/status', _.curry(nodeAdbStatusOnOtherHost)(pluginArgs.bindHostOrIp));

router.post('/installAndroidStreamingApp', installAndroidStreamingApp);
router.post('/installApk', installApk);
router.post('/installiOSWDA', installIOSAppOnRealDevice);
router.post('/appiumSession', createDriverSession);
router.post('/closeSession', closeSession);
//router.post('/upload', uploadFile);
router.post('/upload', upload.single('file'), function (req: any, res) {
console.log('storage location is ', req.hostname + '/' + req.file.path);
Expand Down
10 changes: 5 additions & 5 deletions src/data-service/device-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import log from '../logger';
import { setUtilizationTime } from '../device-utils';
import semver from 'semver';
import debugLog from '../debugLog';
import { setDeviceState, setDeviceStateWhenUnplugged } from '../modules/device-control/DeviceHelper';
// import { setDeviceState, setDeviceStateWhenUnplugged } from '../modules/device-control/DeviceHelper';

export async function removeDevice(devices: { udid: string; host: string }[]) {
for await (const device of devices) {
Expand All @@ -15,7 +15,7 @@ export async function removeDevice(devices: { udid: string; host: string }[]) {
.find({ udid: device.udid, host: { $contains: device.host } })
.remove();
}
await setDeviceStateWhenUnplugged();
//await setDeviceStateWhenUnplugged();
}

export async function addNewDevice(devices: IDevice[], host?: string): Promise<IDevice[]> {
Expand Down Expand Up @@ -66,9 +66,9 @@ export async function addNewDevice(devices: IDevice[], host?: string): Promise<I
log.debug(`Added ${result.length} new devices to local database`);

debugLog(`Added devices: ${JSON.stringify(result)}`);
for (const iDevice of result) {
await setDeviceState(iDevice);
}
// for (const iDevice of result) {
// await setDeviceState(iDevice);
// }
debugLog(`All devices: ${JSON.stringify((await ADTDatabase.DeviceModel).chain().find().data())}`);

return result;
Expand Down
19 changes: 19 additions & 0 deletions src/events/after-session-deleted-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IAfterSessionDeletedEventOptions } from '../interfaces/IDeviceFarmSession';
import { Event } from '../notifier/event';
import { EventListener } from '../notifier/event-listener';
import { EventConsumer } from '../types/event';

export class AfterSessionDeletedEvent extends Event<IAfterSessionDeletedEventOptions> {
private static readonly EVENT_NAME: string = 'after-session-deleted';

constructor(options: IAfterSessionDeletedEventOptions) {
super(AfterSessionDeletedEvent.EVENT_NAME, options);
}

static listener(handler: EventConsumer<IAfterSessionDeletedEventOptions>) {
return new EventListener<IAfterSessionDeletedEventOptions>(
AfterSessionDeletedEvent.EVENT_NAME,
handler,
);
}
}
19 changes: 19 additions & 0 deletions src/events/before-session-create-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IBeforeSessionCreateEventOptions } from '../interfaces/IDeviceFarmSession';
import { Event } from '../notifier/event';
import { EventListener } from '../notifier/event-listener';
import { EventConsumer } from '../types/event';

export class BeforeSessionCreatedEvent extends Event<IBeforeSessionCreateEventOptions> {
private static readonly EVENT_NAME: string = 'before-session-create';

constructor(session: IBeforeSessionCreateEventOptions) {
super(BeforeSessionCreatedEvent.EVENT_NAME, session);
}

static listener(handler: EventConsumer<IBeforeSessionCreateEventOptions>) {
return new EventListener<IBeforeSessionCreateEventOptions>(
BeforeSessionCreatedEvent.EVENT_NAME,
handler,
);
}
}
15 changes: 15 additions & 0 deletions src/events/unexpected-server-shutdown-event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Event } from '../notifier/event';
import { EventListener } from '../notifier/event-listener';
import { EventConsumer } from '../types/event';

export class UnexpectedServerShutdownEvent extends Event<null> {
private static readonly EVENT_NAME: string = 'unexpected-server-shutdown-event';

constructor() {
super(UnexpectedServerShutdownEvent.EVENT_NAME, null);
}

static listener(handler: EventConsumer<null>) {
return new EventListener<null>(UnexpectedServerShutdownEvent.EVENT_NAME, handler);
}
}
3 changes: 3 additions & 0 deletions src/fake-module-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { IPluginArgs } from './interfaces/IPluginArgs';
import { EventBus } from './notifier/event-bus';
import { Config } from './types/Config';
import { ServerArgs } from '@appium/types';
import ADB from 'appium-adb';

export class FakeModuleLoader implements IExternalModuleLoader {
async onPluginLoaded(
serverArgs: ServerArgs,
pluginArgs: IPluginArgs,
httpServer: any,
config: Config,
bus: EventBus,
adb: ADB,
) {
//no action
}
Expand Down
10 changes: 10 additions & 0 deletions src/interfaces/IDeviceFarmSession.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import ADB from 'appium-adb';
import { IDevice } from './IDevice';
import SessionType from '../enums/SessionType';

export type IDeviceFarmSessionOptions = {
sessionId: string;
Expand All @@ -10,3 +11,12 @@ export type IDeviceFarmSessionOptions = {
driver: any;
adb: ADB;
};

export type IBeforeSessionCreateEventOptions = {
device: IDevice;
sessionType: SessionType;
};

export type IAfterSessionDeletedEventOptions = {
sessionId: string;
};
3 changes: 3 additions & 0 deletions src/interfaces/IExternalModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { EventBus } from '../notifier/event-bus';
import { Config } from '../types/Config';
import http from 'http';
import { ServerArgs, ServerConfig } from '@appium/types';
import ADB from 'appium-adb';

export type ExpressMiddleware = (request: Request, response: Response, next: NextFunction) => void;

Expand All @@ -12,7 +13,9 @@ export interface IExternalModuleLoader {
serverArgs: ServerArgs,
pluginArgs: IPluginArgs,
config: Config,
httpServer: any,
bus: EventBus,
adb: ADB,
): Promise<void>;

getMiddleWares(): ExpressMiddleware[];
Expand Down
2 changes: 1 addition & 1 deletion src/modules
69 changes: 26 additions & 43 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,11 @@ import { SessionCreatedEvent } from './events/session-created-event';
import debugLog from './debugLog';
import http from 'http';
import * as https from 'https';
import { installStreamingApp } from './modules/device-control/androidStreaming';
import {
registerAndroidWebSocketHandlers,
registerIOSWebSocketHandlers,
waitForWebsocketToBeDeregister,
} from './WebsocketHandler';
import { downloadAndroidStreamAPK, streamAndroid } from './modules/device-control/DeviceHelper';
import { DEVICE_CONNECTIONS_FACTORY } from 'appium-xcuitest-driver/build/lib/device-connections-factory';
import { BeforeSessionCreatedEvent } from './events/before-session-create-event';
import SessionType from './enums/SessionType';
import { UnexpectedServerShutdownEvent } from './events/unexpected-server-shutdown-event';
import { AfterSessionDeletedEvent } from './events/after-session-deleted-event';

const commandsQueueGuard = new AsyncLock();
const DEVICE_MANAGER_LOCK_NAME = 'DeviceManager';
Expand Down Expand Up @@ -125,16 +122,15 @@ class DevicePlugin extends BasePlugin {
deviceFilter,
)} onUnexpectedShutdown from server`,
);
await waitForWebsocketToBeDeregister(this.pluginArgs, DevicePlugin.httpServer);

await DevicePlugin.registerWebSocket(this.pluginArgs);
await EventBus.fire(new UnexpectedServerShutdownEvent());
}
public static async updateServer(
expressApp: any,
httpServer: any,
cliArgs: ServerArgs,
): Promise<void> {
DevicePlugin.httpServer = httpServer;

// cliArgs are here is not pluginArgs yet as it contains the whole CLI argument for Appium! Different case for our plugin constructor
log.debug(`📱 Update server with CLI Args: ${JSON.stringify(cliArgs)}`);
externalModule = await loadExternalModules();
Expand All @@ -149,7 +145,17 @@ class DevicePlugin extends BasePlugin {
} else {
pluginArgs = Object.assign({}, DefaultPluginArgs);
}
externalModule.onPluginLoaded(cliArgs, pluginArgs, pluginConfig, EventBus);
if (pluginArgs.platform.toLowerCase() === 'android') {
DevicePlugin.adbInstance = ADB.createADB({});
}
externalModule.onPluginLoaded(
cliArgs,
pluginArgs,
httpServer,
pluginConfig,
EventBus,
DevicePlugin.adbInstance,
);
DevicePlugin.NODE_ID = uuidv4();
log.info('Cli Args: ' + JSON.stringify(cliArgs));

Expand All @@ -159,7 +165,6 @@ class DevicePlugin extends BasePlugin {
if (pluginArgs.bindHostOrIp === undefined) {
pluginArgs.bindHostOrIp = ip.address();
}
await DevicePlugin.registerWebSocket(pluginArgs);
log.debug(`📱 Update server with Plugin Args: ${JSON.stringify(pluginArgs)}`);
await initializeStorage();
(await ADTDatabase.DeviceModel).removeDataOnly();
Expand Down Expand Up @@ -263,19 +268,6 @@ class DevicePlugin extends BasePlugin {
);
}

static async registerWebSocket(pluginArgs: IPluginArgs) {
if (pluginArgs.platform.toLowerCase() === 'android') {
DevicePlugin.adbInstance = await ADB.createADB({});
await registerAndroidWebSocketHandlers(DevicePlugin.httpServer, DevicePlugin.adbInstance);
} else if (pluginArgs.platform.toLowerCase() === 'ios') {
await registerIOSWebSocketHandlers(DevicePlugin.httpServer);
} else {
DevicePlugin.adbInstance = await ADB.createADB({});
await registerAndroidWebSocketHandlers(DevicePlugin.httpServer, DevicePlugin.adbInstance);
await registerIOSWebSocketHandlers(DevicePlugin.httpServer);
}
}

private static setIncludeSimulatorState(pluginArgs: IPluginArgs, deviceTypes: string) {
if (hasCloudArgument(pluginArgs)) {
deviceTypes = 'real';
Expand Down Expand Up @@ -342,18 +334,14 @@ class DevicePlugin extends BasePlugin {
debugLog(`📱${pendingSessionId} --- Forwarded session response: ${JSON.stringify(session)}`);
} else {
log.debug('📱 Creating session on the same node');
if (
this.pluginArgs.platform.toLowerCase() === 'android' &&
this.pluginArgs.liveStreaming &&
!this.pluginArgs.cloud
) {
log.info('📱 Live streaming argument is set to true, preparing device for live streaming');
const destination = await downloadAndroidStreamAPK();
const adbClient = await ADB.createADB({});
await installStreamingApp(adbClient, device.udid);
log.info(`Installed ${destination} on device ${device.udid}`);
await streamAndroid(adbClient, { udid: device.udid, state: 'device' }, device.systemPort);
}
const sessionType = device.cloud
? SessionType.CLOUD
: device.nodeId !== DevicePlugin.NODE_ID
? SessionType.REMOTE
: SessionType.LOCAL;

await EventBus.fire(new BeforeSessionCreatedEvent({ device, sessionType: sessionType }));

session = await next();
if (caps.alwaysMatch['df:portForward'] !== undefined && device.realDevice) {
log.info(`📱 Forwarding ios port to real device ${device.udid} for manual interaction`);
Expand Down Expand Up @@ -577,12 +565,7 @@ class DevicePlugin extends BasePlugin {
await unblockDeviceMatchingFilter({ session_id: sessionId });
log.info(`📱 Unblocking the device that is blocked for session ${sessionId}`);
const res = await next();
try {
await waitForWebsocketToBeDeregister(this.pluginArgs, DevicePlugin.httpServer);
await DevicePlugin.registerWebSocket(this.pluginArgs);
} catch (err) {
log.info('Socket server not removed within 5000ms. So not registering again');
}
await EventBus.fire(new AfterSessionDeletedEvent({ sessionId: sessionId }));
return res;
}
}
Expand Down
18 changes: 13 additions & 5 deletions web/src/api-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,26 @@ export default class DeviceFarmApiService {
}

public static androidStreamingAppInstalled(udid: string, systemPort: number) {
return apiClient.makePOSTRequest('/installAndroidStreamingApp', {}, { udid, systemPort });
return apiClient.makePOSTRequest(
'/dashboard/installAndroidStreamingApp',
{},
{ udid, systemPort },
);
}

public static createSession(udid: string, systemPort: number) {
return apiClient.makePOSTRequest(
'/appiumSession',
'/dashboard/appiumSession',
{},
{ udid, systemPort, origin: window.location.origin },
);
}
public static installWDAOnDevice(udid: string) {
return apiClient.makePOSTRequest('/installiOSWDA', {}, { udid });
return apiClient.makePOSTRequest('/dashboard/installiOSWDA', {}, { udid });
}

public static installApk(udid: string, apkPath: string) {
return apiClient.makePOSTRequest('/installApk', {}, { udid, apkPath });
return apiClient.makePOSTRequest('/dashboard/installApk', {}, { udid, apkPath });
}
public static getPendingSessionsCount() {
return apiClient.makeGETRequest('/queue/length', {});
Expand Down Expand Up @@ -52,7 +56,11 @@ export default class DeviceFarmApiService {
}

public static closeSession(udid: string) {
return apiClient.makePOSTRequest('/closeSession', {}, { udid, origin: window.location.origin });
return apiClient.makePOSTRequest(
'/dashboard/closeSession',
{},
{ udid, origin: window.location.origin },
);
}

public static async getDeviceLogs(sessionId: string) {
Expand Down
Loading

0 comments on commit 422e41e

Please sign in to comment.