Skip to content

Commit

Permalink
Make node:v8 getHeapStatistics more plausible (#12139)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarred-Sumner authored Jun 25, 2024
1 parent 9f2533e commit d5e3ea0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 13 deletions.
44 changes: 32 additions & 12 deletions src/js/node/v8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,44 @@ function cachedDataVersionTag() {
function getHeapSnapshot() {
notimpl("getHeapSnapshot");
}

let totalmem_ = -1;

function totalmem() {
if (totalmem_ === -1) {
totalmem_ = require("node:os").totalmem();
}
return totalmem_;
}

function getHeapStatistics() {
const stats = jsc.heapStats();
// this is not very correct
const memory = jsc.memoryUsage();

// These numbers need to be plausible, even if incorrect
// From npm's codebase:
//
// > static #heapLimit = Math.floor(getHeapStatistics().heap_size_limit)
//
return {
total_heap_size: stats.heapCapacity,
total_heap_size_executable: 0,
total_physical_size: stats.heapSize,
total_available_size: Infinity,
total_heap_size: stats.heapSize,
total_heap_size_executable: stats.heapSize >> 1,
total_physical_size: memory.peak,
total_available_size: totalmem() - stats.heapSize,
used_heap_size: stats.heapSize,
heap_size_limit: Infinity,
heap_size_limit: Math.min(memory.peak * 10, totalmem()),
malloced_memory: stats.heapSize,
peak_malloced_memory: Infinity,
peak_malloced_memory: memory.peak,

// -- Copied from Node:
does_zap_garbage: 0,
number_of_native_contexts: Infinity,
number_of_detached_contexts: Infinity,
total_global_handles_size: Infinity,
used_global_handles_size: Infinity,
external_memory: Infinity,
number_of_native_contexts: 1,
number_of_detached_contexts: 0,
total_global_handles_size: 8192,
used_global_handles_size: 2208,
// ---- End of copied from Node

external_memory: stats.extraMemorySize,
};
}
function getHeapSpaceStatistics() {
Expand Down
17 changes: 16 additions & 1 deletion test/js/node/stubs.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect, test } from "bun:test";
import { describe, expect, test } from "bun:test";

const weirdInternalSpecifiers = [
"_http_agent",
Expand Down Expand Up @@ -98,3 +98,18 @@ test("you can import bun:test", async () => {
const bunTest1 = await import("bun:test" + String(""));
const bunTest2 = require("bun:test" + String(""));
});

describe("v8.getHeapStatistics", () => {
const stats = require("v8").getHeapStatistics();

for (let key in stats) {
test(key, () => {
if (key === "does_zap_garbage" || key === "number_of_detached_contexts") {
expect(stats[key]).toBe(0);
return;
}
expect(stats[key]).toBeNumber();
expect(stats[key]).toBePositive();
});
}
});

0 comments on commit d5e3ea0

Please sign in to comment.