Skip to content

Commit

Permalink
dumpe versionupdate deps + clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
UrielCh committed Nov 8, 2024
1 parent d010008 commit 5784ad7
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 66 deletions.
126 changes: 100 additions & 26 deletions bench/sync/pull.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,107 @@
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { spawn } from 'child_process';
import Adb from '../../src/adb';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Bench = require('bench');
import { createClient } from '../../src/adb';
import { performance, PerformanceObserver } from 'perf_hooks';

const deviceId = process.env.DEVICE_ID || '';
const deviceParams = deviceId ? ['-s', deviceId] : [];

const deviceParams = deviceId ? [ '-s', deviceId ] : [];
// Number of iterations for each benchmark
const ITERATIONS = 3;

module.exports = {
compareCount: 3,
compare: {
'pull /dev/graphics/fb0 using ADB CLI'(done: () => void) {
const proc = spawn('adb', [...deviceParams, 'pull', '/dev/graphics/fb0', '/dev/null']);
return proc.stdout.on('end', done);
},
async 'pull /dev/graphics/fb0 using client.pull()'(done: () => void) {
const client = Adb.createClient();
const stream = await client
.getDevice(deviceId)
.pull('/dev/graphics/fb0');
stream.resume();
return stream.on('end', done);
interface BenchmarkResult {
name: string;
duration: number;
opsPerSecond: number;
}

async function runBenchmark(name: string, fn: () => Promise<void>): Promise<BenchmarkResult> {
const results: number[] = [];

// Run warm-up iteration
await fn();

// Run actual benchmark iterations
for (let i = 0; i < ITERATIONS; i++) {
const start = performance.now();
await fn();
const end = performance.now();
results.push(end - start);
}

const totalDuration = results.reduce((sum, time) => sum + time, 0);
const avgDuration = totalDuration / results.length;
const opsPerSecond = 1000 / avgDuration;

return {
name,
duration: avgDuration,
opsPerSecond
};
}

async function main() {
// Setup performance observer
const obs = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
console.log(`${entry.name}: ${entry.duration}ms`);
});
});
obs.observe({ entryTypes: ['measure'], buffered: true });

const benchmarks = [
{
name: 'pull /dev/graphics/fb0 using ADB CLI',
fn: () => new Promise<void>((resolve) => {
const proc = spawn('adb', [...deviceParams, 'pull', '/dev/graphics/fb0', '/dev/null']);
proc.stdout.on('end', () => resolve());
})
},
},
};
{
name: 'pull /dev/graphics/fb0 using client.pull()',
fn: async () => {
const client = createClient();
const stream = await client
.getDevice(deviceId)
.pull('/dev/graphics/fb0');
stream.resume();
return new Promise<void>((resolve) => stream.on('end', () => resolve()));
}
}
];

console.log(`Running ${ITERATIONS} iterations for each benchmark...\n`);

const results: BenchmarkResult[] = [];
for (const benchmark of benchmarks) {
try {
const result = await runBenchmark(benchmark.name, benchmark.fn);
results.push(result);
} catch (error) {
console.error(`Error running benchmark "${benchmark.name}":`, error);
}
}

// Print results
console.log('\nResults:');
console.log('----------------------------------------');
results.forEach((result) => {
console.log(`\n${result.name}`);
console.log(` Average duration: ${result.duration.toFixed(2)}ms`);
console.log(` Operations/second: ${result.opsPerSecond.toFixed(2)}`);
});

// Determine the faster method
if (results.length === 2) {
const [first, second] = results;
const diff = Math.abs(first.opsPerSecond - second.opsPerSecond);
const faster = first.opsPerSecond > second.opsPerSecond ? first : second;
const percentage = ((diff / Math.min(first.opsPerSecond, second.opsPerSecond)) * 100).toFixed(2);

console.log('\nComparison:');
console.log(`"${faster.name}" is ${percentage}% faster`);
}
}

Bench.runMain();
// Run benchmarks
main().catch(console.error);
47 changes: 23 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@u4/adbkit",
"version": "4.1.19",
"version": "4.1.20",
"description": "A Typescript client for the Android Debug Bridge.",
"keywords": [
"adb",
Expand Down Expand Up @@ -57,38 +57,37 @@
"@u4/adbkit-monkey": "^1.0.5",
"@u4/minicap-prebuilt": "^1.0.0",
"@xmldom/xmldom": "^0.8.10",
"commander": "9.4.1",
"debug": "~4.3.4",
"get-port": "5.1.1",
"commander": "12.1.0",
"debug": "~4.3.7",
"get-port": "7.1.0",
"node-forge": "^1.3.1",
"promise-duplex": "^6.0.0",
"promise-readable": "^6.0.0",
"protobufjs": "^6.11.3",
"promise-duplex": "^8.0.0",
"promise-readable": "^8.0.1",
"protobufjs": "^7.4.0",
"xpath": "^0.0.34"
},
"devDependencies": {
"@types/debug": "^4.1.12",
"@types/mocha": "^10.0.6",
"@types/mocha": "^10.0.9",
"@types/node": "^20.11.7",
"@types/node-forge": "^1.3.11",
"@types/sinon": "^17.0.3",
"@types/sinon-chai": "^3.2.12",
"@typescript-eslint/eslint-plugin": "^6.19.1",
"@typescript-eslint/parser": "^6.19.1",
"bench": "~0.3.6",
"chai": "~4.3.7",
"@types/sinon-chai": "^4.0.0",
"@typescript-eslint/eslint-plugin": "^8.13.0",
"@typescript-eslint/parser": "^8.13.0",
"chai": "~5.1.2",
"eslint": "^8.56.0",
"mocha": "~10.2.0",
"picocolors": "^1.0.0",
"prettier": "^3.2.4",
"rimraf": "^4.4.1",
"sinon": "~15.1.0",
"sinon-chai": "~3.7.0",
"mocha": "~10.8.2",
"picocolors": "^1.1.1",
"prettier": "^3.3.3",
"rimraf": "^6.0.1",
"sinon": "~19.0.2",
"sinon-chai": "~4.0.0",
"ts-node": "^10.9.2",
"typedoc": "^0.25.7",
"typedoc-plugin-rename-defaults": "^0.7.0",
"typescript": "5.3.3",
"why-is-node-running": "^2.2.2"
"typedoc": "^0.26.11",
"typedoc-plugin-rename-defaults": "^0.7.1",
"typescript": "5.6.3",
"why-is-node-running": "^3.2.1"
},
"engines": {
"node": ">= 12.20.0"
Expand All @@ -98,6 +97,6 @@
"bin"
],
"optionalDependencies": {
"@devicefarmer/minicap-prebuilt": "^2.7.1"
"@devicefarmer/minicap-prebuilt": "^2.7.2"
}
}
3 changes: 0 additions & 3 deletions src/adb.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import Client from './adb/client';
// import { Keycode } from './adb/keycode';
// import util_ from './adb/util';
import { ClientOptions } from './models/ClientOptions';

export interface AdbOptions {
Expand Down Expand Up @@ -49,4 +47,3 @@ export function createClient(options: AdbOptions = { port: 5037 }): Client {
}
return new Client(opts);
}
// }
2 changes: 1 addition & 1 deletion src/adb/DeviceClientExtra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import DeviceClient from "./DeviceClient";
import xpath from 'xpath';
import { DOMParser } from '@xmldom/xmldom';
import { KeyCodes } from "./keycode";
import { Utils } from "..";
import { Utils } from "../index";

export default class DeviceClientExtra {
constructor(private deviceClient: DeviceClient) { }
Expand Down
7 changes: 3 additions & 4 deletions src/adb/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { Readable } from 'stream';
import Stats64 from './sync/stats64';
import Entry64 from './sync/entry64';
import Utils from './utils';
import { PromiseReadable } from "promise-readable";

const TEMP_PATH = '/data/local/tmp';
const DEFAULT_CHMOD = 0o644;
Expand Down Expand Up @@ -217,13 +216,13 @@ export default class Sync extends EventEmitter {
* @returns See `sync.push()` for details.
*/
public async pushFile(file: string, path: string, mode = DEFAULT_CHMOD): Promise<PushTransfer> {
mode || (mode = DEFAULT_CHMOD);
// mode || (mode = DEFAULT_CHMOD);
try {
const stats = await fs.promises.stat(file);
if (stats.isDirectory())
throw Error(`can not push directory "${file}" only files are supported for now.`);
} catch (e) {
throw Error(`can not read file "${file}"`);
throw Error(`can not read file "${file}" Err: ${JSON.stringify(e)}`);
}
const stream = fs.createReadStream(file);
return this.pushStream(stream, path, mode, file);
Expand Down Expand Up @@ -288,7 +287,7 @@ export default class Sync extends EventEmitter {
const readable = await Utils.waitforReadable(stream, STREAM_READ_TIMEOUT);
if (!readable)
break;
let chunk: any;
let chunk: ReturnType<Readable['read']>;
// eslint-disable-next-line no-cond-assign
while (chunk = (stream.read(DATA_MAX_LENGTH) || stream.read())) {
await this.sendCommandWithLength(Protocol.DATA, chunk.length);
Expand Down
4 changes: 2 additions & 2 deletions src/adb/sync/entry64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import Stats64 from './stats64';

export default class Entry64 extends Stats64 {
constructor(public name: string, error: number, dev: bigint, ino: bigint,
mode: bigint, nlink: bigint, uid: bigint, gid: bigint, size: bigint,
atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint) {
mode: bigint, nlink: bigint, uid: bigint, gid: bigint, size: bigint,
atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint) {
super(error, dev, ino, mode, nlink, uid, gid, size, atimeNs, mtimeNs, ctimeNs);
}

Expand Down
7 changes: 4 additions & 3 deletions src/adb/tcpusb/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ export default class Socket extends EventEmitter {
) {
super();

let base: SocketOptions;
(base = this.options).auth || (base.auth = () => Promise.resolve(true));
const base: SocketOptions = this.options;
if (!base.auth)
base.auth = () => Promise.resolve(true);
this.socket.setNoDelay(true);
this.reader = new PacketReader(this.socket)
.on('packet', this._handle.bind(this))
Expand Down Expand Up @@ -203,7 +204,7 @@ export default class Socket extends EventEmitter {
try {
await this.options.auth(key)
} catch (e) {
debug('Connection rejected by user-defined auth handler');
debug('Connection rejected by user-defined auth handler', e);
throw new Socket.AuthError('Rejected by user-defined handler');
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/adb/thirdparty/STFService/STFService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default class STFService extends EventEmitter {
try {
await fs.promises.stat(apk);
} catch (e) {
throw Error(`can not find APK bin/STFService_${version}.apk`);
throw Error(`can not find APK bin/STFService_${version}.apk Err: ${JSON.stringify(e)}`);
}
this._cachedApkPath = '';
return this.client.install(apk);
Expand Down
6 changes: 4 additions & 2 deletions src/adb/thirdparty/scrcpy/Scrcpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,17 @@ export default class Scrcpy extends EventEmitter {
errors.push(msg);
try {
this.emit('error', Error(msg));
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e: unknown) {
// emit Error but to not want to Quit Yet
}
} else {
this._setFatalError(errors.join('\n'));
break;
}
}
} catch (e) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e: unknown) {
//this.emit('error', e as Error);
//this.setError((e as Error).message);
}
Expand Down

0 comments on commit 5784ad7

Please sign in to comment.