CPU usage optimizations

This commit is contained in:
James Babcock committed 2026-09-27 16:33:43 -07:00
1 parent 95b2ca8afa
commit 3601a998a3
17 files changed
+494 -94

No files matched your search

+52
View File
@@ -16,6 +16,58 @@ export function fetchWithUserAgent(url: string, init?: RequestInit): Promise<Res
return fetch(url, { ...init, headers: withUserAgent(init?.headers) });
}
/** The parts of a fetch() Response that fetchTextWithUserAgent provides. */
export interface TextResponse {
ok: boolean;
status: number;
text(): Promise<string>;
json<T = unknown>(): Promise<T>;
}
/**
* fetchWithUserAgent for text/JSON bodies, decoded on the Java side.
* NativeScript's fetch() polyfill reads every body as a blob, and on Android
* that copies it from the Java byte[] into JS one bridge call per byte
* (Uint8Array.from in http-request's toArrayBuffer): ~160ms of main thread
* for one Nightscout refresh. Here the body crosses once, as a string.
*/
export async function fetchTextWithUserAgent(
url: string,
init?: { method?: string; headers?: HeadersInit; body?: string },
): Promise<TextResponse> {
// Required lazily so the Node test harness can load this module (via
// fetchWithUserAgent's users) without mocking @nativescript/core. Only the
// http module: the @nativescript/core barrel would pull the UI classes
// (Frame's FragmentClass etc.) into the app workers that import this file,
// and their duplicate extends break the static binding generator.
const { request } = require("@nativescript/core/http") as typeof import("@nativescript/core/http");
const response = await request({
url,
method: init?.method ?? "GET",
headers: withUserAgent(init?.headers),
content: init?.body,
});
const status = response.statusCode;
let body: string | undefined;
const read = (): string => {
if (body === undefined) {
const content = response.content as any;
if (!content) body = "";
// HttpResponseEncoding.UTF8 is 0, so content.toString() can't ask for
// UTF-8 explicitly on Android; decode the raw ByteArrayOutputStream.
else if (global.isAndroid) body = String(content.raw.toString("UTF-8"));
else body = content.toString();
}
return body!;
};
return {
ok: status >= 200 && status < 300,
status,
text: async () => read(),
json: async () => JSON.parse(read()),
};
}
/** Copies headers into a plain record, adding our User-Agent if absent. */
export function withUserAgent(headers?: HeadersInit): Record<string, string> {
const merged: Record<string, string> = {};