Skip to content

Send page reload message to iOS runtime #1107

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

Merged
merged 9 commits into from
Nov 12, 2015
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
5 changes: 5 additions & 0 deletions lib/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,8 @@ $injector.require("androidToolsInfo", "./android-tools-info");
$injector.require("iosUsbLiveSyncServiceLocator", "./services/usb-livesync-service");
$injector.require("androidUsbLiveSyncServiceLocator", "./services/usb-livesync-service");
$injector.require("sysInfo", "./sys-info");

$injector.require("iOSNotificationService", "./services/ios-notification-service");
$injector.require("socketProxyFactory", "./device-sockets/ios/socket-proxy-factory");
$injector.require("iOSNotification", "./device-sockets/ios/notification");
$injector.require("iOSSocketRequestExecutor", "./device-sockets/ios/socket-request-executor");
28 changes: 25 additions & 3 deletions lib/declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ interface IUsbLiveSyncService {
liveSync(platform: string): IFuture<void>;
}

interface IPlatformSpecificUsbLiveSyncService {
restartApplication(deviceAppData: Mobile.IDeviceAppData, localToDevicePaths?: Mobile.ILocalToDevicePathData[]): IFuture<void>;
beforeLiveSyncAction?(deviceAppData: Mobile.IDeviceAppData): IFuture<void>;
interface IiOSUsbLiveSyncService extends IPlatformSpecificUsbLiveSyncService {
sendPageReloadMessageToSimulator(): IFuture<void>;
}

interface IOptions extends ICommonOptions {
Expand Down Expand Up @@ -168,3 +167,26 @@ interface IAndroidToolsInfoData {
*/
targetSdkVersion: number;
}

interface ISocketProxyFactory {
createSocketProxy(factory: () => any): IFuture<any>;
}

interface IiOSNotification {
waitForDebug: string;
attachRequest: string;
appLaunching: string;
readyForAttach: string;
attachAvailabilityQuery: string;
alreadyConnected: string;
attachAvailable: string;
}

interface IiOSNotificationService {
awaitNotification(npc: Mobile.INotificationProxyClient, notification: string, timeout: number): IFuture<string>;
}

interface IiOSSocketRequestExecutor {
executeLaunchRequest(device: Mobile.IiOSDevice, timeout: number, readyForAttachTimeout: number): IFuture<void>;
executeAttachRequest(device: Mobile.IiOSDevice, timeout: number): IFuture<void>;
}
1 change: 1 addition & 0 deletions lib/definitions/platform.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ interface IPlatformService {
getLatestApplicationPackageForDevice(platformData: IPlatformData): IFuture<IApplicationPackage>;
getLatestApplicationPackageForEmulator(platformData: IPlatformData): IFuture<IApplicationPackage>;
copyLastOutput(platform: string, targetPath: string, settings: {isForDevice: boolean}): IFuture<void>;
ensurePlatformInstalled(platform: string): IFuture<void>;
}

interface IPlatformData {
Expand Down
47 changes: 47 additions & 0 deletions lib/device-sockets/ios/notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
///<reference path="../../.d.ts"/>
"use strict";

export class IOSNotification implements IiOSNotification {
Copy link

Choose a reason for hiding this comment

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

Is there a need for an interface for this class?

Copy link

Choose a reason for hiding this comment

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

This can safely be just a holder for constants, or even exported variables that can be imported via destructing.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy link

Choose a reason for hiding this comment

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

My bad, I miss the part where we use the $projectData.

private static WAIT_FOR_DEBUG_NOTIFICATION_NAME = "WaitForDebugger";
private static ATTACH_REQUEST_NOTIFICATION_NAME = "AttachRequest";
private static APP_LAUNCHING_NOTIFICATION_NAME = "AppLaunching";
private static READY_FOR_ATTACH_NOTIFICATION_NAME = "ReadyForAttach";
private static ATTACH_AVAILABILITY_QUERY_NOTIFICATION_NAME = "AttachAvailabilityQuery";
private static ALREADY_CONNECTED_NOTIFICATION_NAME = "AlreadyConnected";
private static ATTACH_AVAILABLE_NOTIFICATION_NAME = "AttachAvailable";

constructor(private $projectData: IProjectData) { }

public get waitForDebug() {
return this.formatNotification(IOSNotification.WAIT_FOR_DEBUG_NOTIFICATION_NAME);
}

public get attachRequest(): string {
return this.formatNotification(IOSNotification.ATTACH_REQUEST_NOTIFICATION_NAME);
}

public get appLaunching(): string {
return this.formatNotification(IOSNotification.APP_LAUNCHING_NOTIFICATION_NAME);
}

public get readyForAttach(): string {
return this.formatNotification(IOSNotification.READY_FOR_ATTACH_NOTIFICATION_NAME);
}

public get attachAvailabilityQuery() {
return this.formatNotification(IOSNotification.ATTACH_AVAILABILITY_QUERY_NOTIFICATION_NAME);
}

public get alreadyConnected() {
return this.formatNotification(IOSNotification.ALREADY_CONNECTED_NOTIFICATION_NAME);
}

public get attachAvailable() {
return this.formatNotification(IOSNotification.ATTACH_AVAILABLE_NOTIFICATION_NAME);
}

private formatNotification(notification: string) {
return `${this.$projectData.projectId}:NativeScript.Debug.${notification}`;
}
}
$injector.register("iOSNotification", IOSNotification);
36 changes: 36 additions & 0 deletions lib/device-sockets/ios/packet-stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
///<reference path="../../.d.ts"/>
"use strict";

import * as stream from "stream";

export class PacketStream extends stream.Transform {
private buffer: Buffer;
private offset: number;

constructor(opts?: stream.TransformOptions) {
super(opts);
}

public _transform(packet: any, encoding: string, done: Function): void {
while (packet.length > 0) {
if (!this.buffer) {
// read length
let length = packet.readInt32BE(0);
this.buffer = new Buffer(length);
this.offset = 0;
packet = packet.slice(4);
}

packet.copy(this.buffer, this.offset);
let copied = Math.min(this.buffer.length - this.offset, packet.length);
this.offset += copied;
packet = packet.slice(copied);

if (this.offset === this.buffer.length) {
this.push(this.buffer);
this.buffer = undefined;
}
}
done();
}
}
126 changes: 126 additions & 0 deletions lib/device-sockets/ios/socket-proxy-factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
///<reference path="../../.d.ts"/>
"use strict";

import { PacketStream } from "./packet-stream";
import * as net from "net";
import * as semver from "semver";
import * as ws from "ws";
import temp = require("temp");
import * as helpers from "../../common/helpers";

export class SocketProxyFactory implements ISocketProxyFactory {
constructor(private $logger: ILogger,
private $projectData: IProjectData,
private $projectDataService: IProjectDataService) { }

public createSocketProxy(factory: () => net.Socket): IFuture<any> {
return (() => {
let socketFactory = (callback: (_socket: net.Socket) => void) => helpers.connectEventually(factory, callback);

this.$projectDataService.initialize(this.$projectData.projectDir);
let frameworkVersion = this.$projectDataService.getValue("tns-ios").wait().version;
let result: any;

if(semver.gte(frameworkVersion, "1.4.0")) {
result = this.createTcpSocketProxy(socketFactory);
} else {
result = this.createWebSocketProxy(socketFactory);
}

return result;
}).future<any>()();
}

private createWebSocketProxy(socketFactory: (handler: (socket: net.Socket) => void) => void): ws.Server {
// NOTE: We will try to provide command line options to select ports, at least on the localhost.
let localPort = 8080;

this.$logger.info("\nSetting up debugger proxy...\nPress Ctrl + C to terminate, or disconnect.\n");

// NB: When the inspector frontend connects we might not have connected to the inspector backend yet.
// That's why we use the verifyClient callback of the websocket server to stall the upgrade request until we connect.
// We store the socket that connects us to the device in the upgrade request object itself and later on retrieve it
// in the connection callback.

let server = ws.createServer(<any>{
Copy link
Contributor

Choose a reason for hiding this comment

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

do you really need the cast?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, due to some bugs in .ws.d files 😿

port: localPort,
verifyClient: (info: any, callback: Function) => {
this.$logger.info("Frontend client connected.");
socketFactory((_socket: any) => {
this.$logger.info("Backend socket created.");
info.req["__deviceSocket"] = _socket;
callback(true);
});
}
});
server.on("connection", (webSocket) => {
let encoding = "utf16le";

let deviceSocket: net.Socket = (<any>webSocket.upgradeReq)["__deviceSocket"];
let packets = new PacketStream();
deviceSocket.pipe(packets);

packets.on("data", (buffer: Buffer) => {
webSocket.send(buffer.toString(encoding));
});

webSocket.on("message", (message, flags) => {
let length = Buffer.byteLength(message, encoding);
let payload = new Buffer(length + 4);
payload.writeInt32BE(length, 0);
payload.write(message, 4, length, encoding);
deviceSocket.write(payload);
});

deviceSocket.on("end", () => {
this.$logger.info("Backend socket closed!");
process.exit(0);
});

webSocket.on("close", () => {
this.$logger.info('Frontend socket closed!');
process.exit(0);
});

});

this.$logger.info("Opened localhost " + localPort);
return server;
}

private createTcpSocketProxy(socketFactory: (handler: (socket: net.Socket) => void) => void): string {
this.$logger.info("\nSetting up proxy...\nPress Ctrl + C to terminate, or disconnect.\n");

let server = net.createServer({
allowHalfOpen: true
});

server.on("connection", (frontendSocket: net.Socket) => {
this.$logger.info("Frontend client connected.");

frontendSocket.on("end", () => {
this.$logger.info('Frontend socket closed!');
process.exit(0);
});

socketFactory((backendSocket: net.Socket) => {
this.$logger.info("Backend socket created.");

backendSocket.on("end", () => {
this.$logger.info("Backend socket closed!");
process.exit(0);
});

backendSocket.pipe(frontendSocket);
frontendSocket.pipe(backendSocket);
frontendSocket.resume();
});
});

let socketFileLocation = temp.path({ suffix: ".sock" });
server.listen(socketFileLocation);

return socketFileLocation;
}
}
$injector.register("socketProxyFactory", SocketProxyFactory);
75 changes: 75 additions & 0 deletions lib/device-sockets/ios/socket-request-executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
///<reference path="../../.d.ts"/>
"use strict";

import * as helpers from "../../common/helpers";
import * as iOSProxyServices from "../../common/mobile/ios/ios-proxy-services";

export class IOSSocketRequestExecutor implements IiOSSocketRequestExecutor {
constructor(private $errors: IErrors,
private $injector: IInjector,
private $iOSNotification: IiOSNotification,
private $iOSNotificationService: IiOSNotificationService,
private $logger: ILogger,
private $projectData: IProjectData,
private $socketProxyFactory: ISocketProxyFactory) { }

public executeAttachRequest(device: Mobile.IiOSDevice, timeout: number): IFuture<void> {
return (() => {
let npc = new iOSProxyServices.NotificationProxyClient(device, this.$injector);

let [alreadyConnected, readyForAttach, attachAvailable] = [this.$iOSNotification.alreadyConnected, this.$iOSNotification.readyForAttach, this.$iOSNotification.attachAvailable]
Copy link

Choose a reason for hiding this comment

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

👍 nice destructing usage.

.map((notification) => this.$iOSNotificationService.awaitNotification(npc, notification, timeout));

npc.postNotificationAndAttachForData(this.$iOSNotification.attachAvailabilityQuery);

let receivedNotification: IFuture<string>;
try {
receivedNotification = helpers.whenAny(alreadyConnected, readyForAttach, attachAvailable).wait();
} catch (e) {
this.$errors.failWithoutHelp(`The application ${this.$projectData.projectId} does not appear to be running on ${device.deviceInfo.displayName} or is not built with debugging enabled.`);
}

switch (receivedNotification) {
case alreadyConnected:
this.$errors.failWithoutHelp("A client is already connected.");
break;
case attachAvailable:
this.executeAttachAvailable(npc, timeout).wait();
break;
case readyForAttach:
break;
}
}).future<void>()();
}

public executeLaunchRequest(device: Mobile.IiOSDevice, timeout: number, readyForAttachTimeout: number): IFuture<void> {
return (() => {
let npc = new iOSProxyServices.NotificationProxyClient(device, this.$injector);

try {
this.$iOSNotificationService.awaitNotification(npc, this.$iOSNotification.appLaunching, timeout).wait();
process.nextTick(() => {
npc.postNotificationAndAttachForData(this.$iOSNotification.waitForDebug );
npc.postNotificationAndAttachForData(this.$iOSNotification.attachRequest);
});

this.$iOSNotificationService.awaitNotification(npc, this.$iOSNotification.readyForAttach, readyForAttachTimeout).wait();
} catch(e) {
this.$logger.trace(`Timeout error: ${e}`);
this.$errors.failWithoutHelp("Timeout waiting for response from NativeScript runtime.");
}
}).future<void>()();
}

private executeAttachAvailable(npc: Mobile.INotificationProxyClient, timeout: number): IFuture<void> {
return (() => {
process.nextTick(() => npc.postNotificationAndAttachForData(this.$iOSNotification.attachRequest));
try {
this.$iOSNotificationService.awaitNotification(npc, this.$iOSNotification.readyForAttach, timeout).wait();
} catch (e) {
this.$errors.failWithoutHelp(`The application ${this.$projectData.projectId} timed out when performing the socket handshake.`);
Copy link
Contributor

Choose a reason for hiding this comment

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

This error will be shown for every thrown Error, is this expected?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes

}
}).future<void>()();
}
}
$injector.register("iOSSocketRequestExecutor", IOSSocketRequestExecutor);
Loading