Implement android traced_consumer socket comunication
Thanks to adb_socket_controller, we will be able to connect to the
perfetto socket in the android device, and exchange messages directly.
In this way will be possible to have complete tracing control from
the perfetto UI, using typescript.
bug: 139536756
Change-Id: I622cf9a65bf0ce2b5eb17de059ba648d9217017b
diff --git a/ui/BUILD.gn b/ui/BUILD.gn
index 5c0a988..c53171b 100644
--- a/ui/BUILD.gn
+++ b/ui/BUILD.gn
@@ -201,6 +201,7 @@
inputs += [
"../protos/perfetto/config/perfetto_config.proto",
"../protos/perfetto/ipc/consumer_port.proto",
+ "../protos/perfetto/ipc/wire_protocol.proto",
]
outputs = [
"$ui_gen_dir/protos.js",
diff --git a/ui/src/base/string_utils.ts b/ui/src/base/string_utils.ts
index 0ad7dd3..efe8fb0 100644
--- a/ui/src/base/string_utils.ts
+++ b/ui/src/base/string_utils.ts
@@ -16,6 +16,10 @@
return btoa(uint8ArrayToString(buffer));
}
+// This function will not handle correctly buffers with a large number of
+// elements due to a js limitation on the number of arguments of a function.
+// The apply will in fact do a call like
+// 'String.fromCharCode(buffer[0],buffer[1],...)'.
export function uint8ArrayToString(buffer: Uint8Array): string {
return String.fromCharCode.apply(null, Array.from(buffer));
}
diff --git a/ui/src/chrome_extension/chrome_tracing_controller.ts b/ui/src/chrome_extension/chrome_tracing_controller.ts
index d46f6b7..93b5f01 100644
--- a/ui/src/chrome_extension/chrome_tracing_controller.ts
+++ b/ui/src/chrome_extension/chrome_tracing_controller.ts
@@ -28,7 +28,9 @@
import {DevToolsSocket} from './devtools_socket';
-const CHUNK_SIZE: number = 1024 * 1024 * 64;
+// The chunk size should be large enough to support reasonable batching of data,
+// but small enough not to cause stack overflows in uint8ArrayToString().
+const CHUNK_SIZE: number = 1024 * 1024 * 16; // 16Mb
export class ChromeTracingController extends RpcConsumerPort {
private streamHandle: string|undefined = undefined;
@@ -126,12 +128,12 @@
if (res === undefined) return;
const chunk = res.base64Encoded ? atob(res.data) : res.data;
- // TODO(nicomazz): remove the conversion to unknown when we stream each
- // chunk to the trace processor.
+ // The 'as {} as UInt8Array' is done because we can't send ArrayBuffers
+ // trough a chrome.runtime.Port. The conversion from string to ArrayBuffer
+ // takes place on the other side of the port.
const response: ReadBuffersResponse = {
type: 'ReadBuffersResponse',
- slices:
- [{data: chunk as unknown as Uint8Array, lastSliceForPacket: res.eof}]
+ slices: [{data: chunk as {} as Uint8Array, lastSliceForPacket: res.eof}]
};
this.sendMessage(response);
if (res.eof) return;
diff --git a/ui/src/controller/adb.ts b/ui/src/controller/adb.ts
index 6ba9515..8a81428 100644
--- a/ui/src/controller/adb.ts
+++ b/ui/src/controller/adb.ts
@@ -75,6 +75,11 @@
}
async connect(device: USBDevice): Promise<void> {
+ if (this.state === AdbState.CONNECTED && this.dev === device) {
+ this.onConnected();
+ this.onConnected = () => {};
+ return;
+ }
this.dev = device;
this.useChecksum = true;
this.key = await AdbOverWebUsb.initKey();
@@ -243,6 +248,10 @@
return this.openStream('shell:' + cmd);
}
+ socket(path: string): Promise<AdbStream> {
+ return this.openStream('localfilesystem:' + path);
+ }
+
openStream(svc: string): Promise<AdbStream> {
const stream = new AdbStreamImpl(this, ++this.lastStreamId);
this.streams.set(stream.localStreamId, stream);
diff --git a/ui/src/controller/adb_interfaces.ts b/ui/src/controller/adb_interfaces.ts
index 2f22a2f..9cc3aa4 100644
--- a/ui/src/controller/adb_interfaces.ts
+++ b/ui/src/controller/adb_interfaces.ts
@@ -16,11 +16,16 @@
export interface Adb {
connect(device: USBDevice): Promise<void>;
disconnect(): Promise<void>;
+ // Executes a shell command non-interactively.
shell(cmd: string): Promise<AdbStream>;
+ // Waits until the shell get closed, and returns all the output.
shellOutputAsString(cmd: string): Promise<string>;
+ // Opens a connection to a UNIX socket.
+ socket(path: string): Promise<AdbStream>;
}
export interface AdbStream {
+ write(msg: string|Uint8Array): Promise<void>;
onMessage(message: AdbMsg): void;
onData: (str: string, raw: Uint8Array) => void;
close(): void;
@@ -45,6 +50,10 @@
shellOutputAsString(_: string): Promise<string> {
return Promise.resolve('');
}
+
+ socket(_: string): Promise<AdbStream> {
+ return Promise.resolve(new MockAdbStream());
+ }
}
export class MockAdbStream implements AdbStream {
@@ -53,6 +62,9 @@
onClose = () => {};
onMessage = (_: AdbMsg) => {};
close() {}
+ write(_: string|Uint8Array): Promise<void> {
+ return Promise.resolve();
+ }
}
export declare type CmdType =
diff --git a/ui/src/controller/adb_record_controller.ts b/ui/src/controller/adb_record_controller.ts
index 990053d..922b28e 100644
--- a/ui/src/controller/adb_record_controller.ts
+++ b/ui/src/controller/adb_record_controller.ts
@@ -38,8 +38,8 @@
private device: USBDevice|undefined = undefined;
private recordShell?: AdbStream;
- constructor(adb: Adb, consumerPortListener: Consumer) {
- super(consumerPortListener);
+ constructor(adb: Adb, consumer: Consumer) {
+ super(consumer);
this.adb = adb;
}
diff --git a/ui/src/controller/adb_socket_controller.ts b/ui/src/controller/adb_socket_controller.ts
new file mode 100644
index 0000000..88d6ddc
--- /dev/null
+++ b/ui/src/controller/adb_socket_controller.ts
@@ -0,0 +1,337 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import * as protobuf from 'protobufjs/minimal';
+import {perfetto} from '../gen/protos';
+import {Adb, AdbStream} from './adb_interfaces';
+import {
+ isReadBuffersResponse,
+ ReadBuffersResponse
+} from './consumer_port_types';
+import {globals} from './globals';
+import {Consumer, RpcConsumerPort} from './record_controller_interfaces';
+
+enum State {
+ DISCONNECTED,
+ BINDING_IN_PROGRESS,
+ BOUND,
+}
+
+// See wire_protocol.proto for more details.
+const WIRE_PROTOCOL_HEADER_SIZE = 4;
+const MAX_IPC_BUFFER_SIZE = 128 * 1024;
+
+const PROTO_LEN_DELIMITED_WIRE_TYPE = 2;
+const TRACE_PACKET_PROTO_ID = 1;
+const TRACE_PACKET_PROTO_TAG =
+ (TRACE_PACKET_PROTO_ID << 3) | PROTO_LEN_DELIMITED_WIRE_TYPE;
+
+declare type Frame = perfetto.ipc.Frame;
+declare type IMethodInfo = perfetto.ipc.Frame.BindServiceReply.IMethodInfo;
+declare type ISlice = perfetto.protos.ReadBuffersResponse.ISlice;
+
+export class AdbSocketConsumerPort extends RpcConsumerPort {
+ private state = State.DISCONNECTED;
+ private adb: Adb;
+ private socket?: AdbStream;
+ private device: USBDevice|undefined = undefined;
+ // Wire protocol request ID. After each request it is increased. It is needed
+ // to keep track of the type of request, and parse the response correctly.
+ private requestId = 1;
+
+ // Buffers received wire protocol data.
+ private incomingBuffer = new Uint8Array(MAX_IPC_BUFFER_SIZE);
+ private incomingBufferLen = 0;
+ private frameToParseLen = 0;
+
+ private availableMethods: IMethodInfo[] = [];
+ private serviceId = -1;
+
+ private resolveBindingPromise!: VoidFunction;
+ private requestMethods = new Map<number, string>();
+
+ // Needed for ReadBufferResponse: all the trace packets are split into
+ // several slices. |partialPacket| is the buffer for them. Once we receive a
+ // slice with the flag |lastSliceForPacket|, a new packet is created.
+ private partialPacket: ISlice[] = [];
+ // Accumulates trace packets into a proto trace file..
+ private traceProtoWriter = protobuf.Writer.create();
+
+ constructor(adb: Adb, consumer: Consumer) {
+ super(consumer);
+ this.adb = adb;
+ }
+
+ async handleCommand(method: string, params: Uint8Array) {
+ if (this.state === State.BINDING_IN_PROGRESS) return;
+ if (this.state === State.DISCONNECTED) {
+ this.state = State.BINDING_IN_PROGRESS;
+ this.device = await this.findDevice();
+ if (!this.device) {
+ this.sendErrorMessage(`Device with serial ${
+ globals.state.serialAndroidDeviceConnected} not found.`);
+ return;
+ }
+ await this.adb.connect(this.device);
+ await this.listenForMessages();
+ await this.bind();
+ this.traceProtoWriter = protobuf.Writer.create();
+ this.state = State.BOUND;
+ }
+
+ console.assert(this.state === State.BOUND);
+ this.invoke(method, params);
+ }
+
+ invoke(method: string, argsProto: Uint8Array) {
+ const requestId = this.requestId++;
+ const methodId = this.findMethodId(method);
+ if (methodId === undefined) {
+ this.sendErrorMessage('Calling unsupported method on target.');
+ console.error(`Method ${method} not supported by the target`);
+ return;
+ }
+ const frame = new perfetto.ipc.Frame({
+ requestId,
+ msgInvokeMethod: new perfetto.ipc.Frame.InvokeMethod(
+ {serviceId: this.serviceId, methodId, argsProto})
+ });
+ this.requestMethods.set(requestId, method);
+ this.sendFrame(frame);
+ }
+
+ async sendFrame(frame: Frame) {
+ console.assert(this.socket !== undefined);
+ if (!this.socket) return;
+ const frameProto: Uint8Array = perfetto.ipc.Frame.encode(frame).finish();
+ const frameLen = frameProto.length;
+ const buf = new Uint8Array(WIRE_PROTOCOL_HEADER_SIZE + frameLen);
+ const dv = new DataView(buf.buffer);
+ dv.setUint32(0, frameProto.length, /* littleEndian */ true);
+ for (let i = 0; i < frameLen; i++) {
+ dv.setUint8(WIRE_PROTOCOL_HEADER_SIZE + i, frameProto[i]);
+ }
+ await this.socket.write(buf);
+ }
+
+ async listenForMessages() {
+ this.socket = await this.adb.socket('/dev/socket/traced_consumer');
+ this.socket.onData = (_str, newData) => this.handleReceivedData(newData);
+ this.socket.onClose = () => this.state = State.DISCONNECTED;
+ }
+
+ private parseMessageSize(buffer: Uint8Array) {
+ const dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.length);
+ return dv.getUint32(0, true);
+ }
+
+ private parseMessage(frameBuffer: Uint8Array) {
+ const frame = perfetto.ipc.Frame.decode(frameBuffer);
+ this.handleIncomingFrame(frame);
+ }
+
+ private incompleteSizeHeader() {
+ if (!this.frameToParseLen) {
+ console.assert(this.incomingBufferLen < WIRE_PROTOCOL_HEADER_SIZE);
+ return true;
+ }
+ return false;
+ }
+
+ private canCompleteSizeHeader(newData: Uint8Array) {
+ return newData.length + this.incomingBufferLen > WIRE_PROTOCOL_HEADER_SIZE;
+ }
+
+ private canParseFullMessage(newData: Uint8Array) {
+ return this.frameToParseLen &&
+ this.incomingBufferLen + newData.length >= this.frameToParseLen;
+ }
+
+ private appendToIncomingBuffer(array: Uint8Array) {
+ this.incomingBuffer.set(array, this.incomingBufferLen);
+ this.incomingBufferLen += array.length;
+ }
+
+ handleReceivedData(newData: Uint8Array) {
+ if (this.incompleteSizeHeader() && this.canCompleteSizeHeader(newData)) {
+ const newDataBytesToRead =
+ WIRE_PROTOCOL_HEADER_SIZE - this.incomingBufferLen;
+ // Add to the incoming buffer the remaining bytes to arrive at
+ // WIRE_PROTOCOL_HEADER_SIZE
+ this.appendToIncomingBuffer(newData.subarray(0, newDataBytesToRead));
+ newData = newData.subarray(newDataBytesToRead);
+
+ this.frameToParseLen = this.parseMessageSize(this.incomingBuffer);
+ this.incomingBufferLen = 0;
+ }
+
+ // Parse all complete messages in incomingBuffer and newData.
+ while (this.canParseFullMessage(newData)) {
+ // All the message is in the newData buffer.
+ if (this.incomingBufferLen === 0) {
+ this.parseMessage(newData.subarray(0, this.frameToParseLen));
+ newData = newData.subarray(this.frameToParseLen);
+ } else { // We need to complete the local buffer.
+ // Read the remaining part of this message.
+ const bytesToCompleteMessage =
+ this.frameToParseLen - this.incomingBufferLen;
+ this.appendToIncomingBuffer(
+ newData.subarray(0, bytesToCompleteMessage));
+ this.parseMessage(
+ this.incomingBuffer.subarray(0, this.frameToParseLen));
+ this.incomingBufferLen = 0;
+ // Remove the data just parsed.
+ newData = newData.subarray(bytesToCompleteMessage);
+ }
+ this.frameToParseLen = 0;
+ if (!this.canCompleteSizeHeader(newData)) break;
+
+ this.frameToParseLen =
+ this.parseMessageSize(newData.subarray(0, WIRE_PROTOCOL_HEADER_SIZE));
+ newData = newData.subarray(WIRE_PROTOCOL_HEADER_SIZE);
+ }
+ // Buffer the remaining data (part of the next header + message).
+ this.appendToIncomingBuffer(newData);
+ }
+
+ decodeResponse(
+ requestId: number, responseProto: Uint8Array, hasMore = false) {
+ const method = this.requestMethods.get(requestId);
+ if (!method) {
+ console.error(`Unknown request id: ${requestId}`);
+ this.sendErrorMessage(`Wire protocol error.`);
+ return;
+ }
+ const decoder = decoders.get(method);
+ if (decoder === undefined) {
+ console.error(`Unable to decode method: ${method}`);
+ return;
+ }
+ const decodedResponse = decoder(responseProto);
+ const response = {type: `${method}Response`, ...decodedResponse};
+
+ // TODO(nicomazz): Fix this.
+ // We assemble all the trace and then send it back to the main controller.
+ // This is a temporary solution, that will be changed in a following CL,
+ // because now both the chrome consumer port and the other adb consumer port
+ // send back the entire trace, while the correct behavior should be to send
+ // back the slices, that are assembled by the main record controller.
+ if (isReadBuffersResponse(response)) {
+ if (response.slices) this.handleSlices(response.slices);
+ if (!hasMore) this.sendReadBufferResponse();
+ return;
+ }
+ this.sendMessage(response);
+ }
+
+ handleSlices(slices: ISlice[]) {
+ for (const slice of slices) {
+ this.partialPacket.push(slice);
+ if (slice.lastSliceForPacket) {
+ const tracePacket = this.generateTracePacket(this.partialPacket);
+ this.traceProtoWriter.uint32(TRACE_PACKET_PROTO_TAG);
+ this.traceProtoWriter.bytes(tracePacket);
+ this.partialPacket = [];
+ }
+ }
+ }
+
+ generateTracePacket(slices: ISlice[]): Uint8Array {
+ let bufferSize = 0;
+ for (const slice of slices) bufferSize += slice.data!.length;
+ const fullBuffer = new Uint8Array(bufferSize);
+ let written = 0;
+ for (const slice of slices) {
+ const data = slice.data!;
+ fullBuffer.set(data, written);
+ written += data.length;
+ }
+ return fullBuffer;
+ }
+
+ sendReadBufferResponse() {
+ const readBufferResponse: ReadBuffersResponse = {
+ type: 'ReadBuffersResponse',
+ slices: [{data: this.traceProtoWriter.finish(), lastSliceForPacket: true}]
+ };
+
+ this.sendMessage(readBufferResponse);
+ }
+
+ bind() {
+ console.assert(this.socket !== undefined);
+ const requestId = this.requestId++;
+ const frame = new perfetto.ipc.Frame({
+ requestId,
+ msgBindService:
+ new perfetto.ipc.Frame.BindService({serviceName: 'ConsumerPort'})
+ });
+ return new Promise((resolve, _) => {
+ this.resolveBindingPromise = resolve;
+ this.sendFrame(frame);
+ });
+ }
+
+ findMethodId(method: string): number|undefined {
+ const methodObject = this.availableMethods.find((m) => m.name === method);
+ if (methodObject && methodObject.id) return methodObject.id;
+ return undefined;
+ }
+
+ async findDevice() {
+ if (!globals.state.androidDeviceConnected) return undefined;
+ const targetSerial = globals.state.androidDeviceConnected.serial;
+ const devices = await navigator.usb.getDevices();
+ return devices.find(d => d.serialNumber === targetSerial);
+ }
+
+ handleIncomingFrame(frame: perfetto.ipc.Frame) {
+ const requestId = frame.requestId as number;
+ switch (frame.msg) {
+ case 'msgBindServiceReply': {
+ const msgBindServiceReply = frame.msgBindServiceReply;
+ if (msgBindServiceReply && msgBindServiceReply.methods &&
+ msgBindServiceReply.serviceId) {
+ console.assert(msgBindServiceReply.success);
+ this.availableMethods = msgBindServiceReply.methods;
+ this.serviceId = msgBindServiceReply.serviceId;
+ this.resolveBindingPromise();
+ this.resolveBindingPromise = () => {};
+ }
+ return;
+ }
+ case 'msgInvokeMethodReply': {
+ const msgInvokeMethodReply = frame.msgInvokeMethodReply;
+ if (msgInvokeMethodReply && msgInvokeMethodReply.replyProto) {
+ console.assert(msgInvokeMethodReply.success);
+ this.decodeResponse(
+ requestId,
+ msgInvokeMethodReply.replyProto,
+ msgInvokeMethodReply.hasMore === true);
+ }
+ return;
+ }
+ default:
+ console.error(`not recognized frame message: ${frame.msg}`);
+ }
+ }
+}
+
+const decoders =
+ new Map<string, Function>()
+ .set('EnableTracing', perfetto.protos.EnableTracingResponse.decode)
+ .set('FreeBuffers', perfetto.protos.FreeBuffersResponse.decode)
+ .set('ReadBuffers', perfetto.protos.ReadBuffersResponse.decode)
+ .set('DisableTracing', perfetto.protos.DisableTracingResponse.decode)
+ .set('GetTraceStats', perfetto.protos.GetTraceStatsResponse.decode);
\ No newline at end of file
diff --git a/ui/src/controller/chrome_proxy_record_controller.ts b/ui/src/controller/chrome_proxy_record_controller.ts
index c2ce289..54a4f29 100644
--- a/ui/src/controller/chrome_proxy_record_controller.ts
+++ b/ui/src/controller/chrome_proxy_record_controller.ts
@@ -12,9 +12,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-import {uint8ArrayToString} from '../base/string_utils';
+import {stringToUint8Array, uint8ArrayToString} from '../base/string_utils';
-import {ConsumerPortResponse, Typed} from './consumer_port_types';
+import {
+ ConsumerPortResponse,
+ isConsumerPortResponse,
+ isReadBuffersResponse,
+ Typed
+} from './consumer_port_types';
import {Consumer, RpcConsumerPort} from './record_controller_interfaces';
export interface ChromeExtensionError extends Typed {
@@ -43,8 +48,8 @@
export class ChromeExtensionConsumerPort extends RpcConsumerPort {
private extensionPort: MessagePort;
- constructor(extensionPort: MessagePort, consumerPortListener: Consumer) {
- super(consumerPortListener);
+ constructor(extensionPort: MessagePort, consumer: Consumer) {
+ super(consumer);
this.extensionPort = extensionPort;
this.extensionPort.onmessage = this.onExtensionMessage.bind(this);
}
@@ -52,11 +57,23 @@
onExtensionMessage(message: {data: ChromeExtensionMessage}) {
if (isError(message.data)) {
this.sendErrorMessage(message.data.error);
- } else if (isStatus(message.data)) {
- this.sendStatus(message.data.status);
- } else {
- this.sendMessage(message.data);
+ return;
}
+ if (isStatus(message.data)) {
+ this.sendStatus(message.data.status);
+ return;
+ }
+
+ console.assert(isConsumerPortResponse(message.data));
+ // In this else branch message.data will be a ConsumerPortResponse.
+ if (isReadBuffersResponse(message.data) && message.data.slices) {
+ // This is needed because we can't send an ArrayBuffer through a
+ // chrome.runtime.port. A string is sent instead, and here converted to
+ // an ArrayBuffer.
+ const slice = message.data.slices[0].data as unknown as string;
+ message.data.slices[0].data = stringToUint8Array(slice);
+ }
+ this.sendMessage(message.data);
}
handleCommand(method: string, requestData: Uint8Array): void {
diff --git a/ui/src/controller/consumer_port_types.ts b/ui/src/controller/consumer_port_types.ts
index bb3c4ea..8a249d4 100644
--- a/ui/src/controller/consumer_port_types.ts
+++ b/ui/src/controller/consumer_port_types.ts
@@ -28,6 +28,12 @@
export type ConsumerPortResponse =
EnableTracingResponse|ReadBuffersResponse|GetTraceStatsResponse;
+export function isConsumerPortResponse(obj: Typed):
+ obj is ConsumerPortResponse {
+ return isReadBuffersResponse(obj) || isEnableTracingResponse(obj) ||
+ isGetTraceStatsResponse(obj);
+}
+
export function isReadBuffersResponse(obj: Typed): obj is ReadBuffersResponse {
return obj.type === 'ReadBuffersResponse';
}
diff --git a/ui/src/controller/record_controller.ts b/ui/src/controller/record_controller.ts
index 670f984..879fb1c 100644
--- a/ui/src/controller/record_controller.ts
+++ b/ui/src/controller/record_controller.ts
@@ -12,10 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-import {ungzip} from 'pako';
import {Message, Method, rpc, RPCImplCallback} from 'protobufjs';
-import {stringToUint8Array, uint8ArrayToBase64} from '../base/string_utils';
+import {
+ uint8ArrayToBase64,
+} from '../base/string_utils';
import {Actions} from '../common/actions';
import {
AndroidLogConfig,
@@ -42,6 +43,7 @@
import {AdbOverWebUsb} from './adb';
import {AdbConsumerPort} from './adb_record_controller';
+import {AdbSocketConsumerPort} from './adb_socket_controller';
import {ChromeExtensionConsumerPort} from './chrome_proxy_record_controller';
import {
ConsumerPortResponse,
@@ -448,7 +450,7 @@
private extensionPort: MessagePort;
private recordingInProgress = false;
private consumerPort: ConsumerPort;
- private traceBuffer = '';
+ private traceBuffer: Uint8Array[] = [];
private bufferUpdateInterval: ReturnType<typeof setTimeout>|undefined;
// We have a different controller for each targetOS. The correct one will be
@@ -519,10 +521,10 @@
onConsumerPortResponse(data: ConsumerPortResponse) {
if (data === undefined) return;
if (isReadBuffersResponse(data)) {
- if (!data.slices) return;
+ if (!data.slices || data.slices.length === 0) return;
// TODO(nicomazz): handle this as intended by consumer_port.proto.
- this.traceBuffer += data.slices[0].data;
- // TODO(nicomazz): Stream the chunks directly in the trace processor.
+ console.assert(data.slices.length === 1);
+ if (data.slices[0].data) this.traceBuffer.push(data.slices[0].data);
if (data.slices[0].lastSliceForPacket) this.onTraceComplete();
} else if (isEnableTracingResponse(data)) {
this.readBuffers();
@@ -539,16 +541,24 @@
onTraceComplete() {
this.consumerPort.freeBuffers({});
globals.dispatch(Actions.setRecordingStatus({status: undefined}));
- if (globals.state.recordingCancelled) {
- globals.dispatch(
- Actions.setLastRecordingError({error: 'Recording cancelled.'}));
- return;
- }
- const trace = ungzip(stringToUint8Array(this.traceBuffer));
+ const trace = this.generateTrace();
globals.dispatch(Actions.openTraceFromBuffer({buffer: trace.buffer}));
- this.traceBuffer = '';
+ this.traceBuffer = [];
}
+ // TODO(nicomazz): stream each chunk into the trace processor, instead of
+ // creating a big long trace.
+ generateTrace() {
+ let traceLen = 0;
+ for (const chunk of this.traceBuffer) traceLen += chunk.length;
+ const completeTrace = new Uint8Array(traceLen);
+ let written = 0;
+ for (const chunk of this.traceBuffer) {
+ completeTrace.set(chunk, written);
+ written += chunk.length;
+ }
+ return completeTrace;
+ }
getBufferUsagePercentage(data: GetTraceStatsResponse): number {
if (!data.traceStats || !data.traceStats.bufferStats) return 0.0;
@@ -580,7 +590,7 @@
// - Android device target: WebUSB is used to communicate using the adb
// protocol. Actually, there is no full consumer_port implementation, but
// only the support to start tracing and fetch the file.
- getTargetController(target: TargetOs): RpcConsumerPort {
+ async getTargetController(target: TargetOs): Promise<RpcConsumerPort> {
let controller = this.controllers.get(target);
if (controller) return controller;
@@ -588,8 +598,12 @@
controller = new ChromeExtensionConsumerPort(this.extensionPort, this);
} else if (isAndroidTarget(target)) {
// TODO(nicomazz): create the correct controller also based on the
- // selected android device.
- controller = new AdbConsumerPort(new AdbOverWebUsb(), this);
+ // selected android device. TargetOS may be changed from a single char to
+ // something else.
+ const socketAccess = await this.hasSocketAccess();
+ controller = socketAccess ?
+ new AdbSocketConsumerPort(new AdbOverWebUsb(), this) :
+ new AdbConsumerPort(new AdbOverWebUsb(), this);
}
if (!controller) throw Error(`Unknown target: ${target}`);
@@ -598,11 +612,16 @@
return controller;
}
- private rpcImpl(
+ private hasSocketAccess() {
+ // TODO(nicomazz): implement proper logic
+ return Promise.resolve(false);
+ }
+
+ private async rpcImpl(
method: RPCImplMethod, requestData: Uint8Array,
_callback: RPCImplCallback) {
try {
- this.getTargetController(this.app.state.recordConfig.targetOS)
+ (await this.getTargetController(this.app.state.recordConfig.targetOS))
.handleCommand(method.name, requestData);
} catch (e) {
console.error(`error invoking ${method}: ${e.message}`);