Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
9 changes: 4 additions & 5 deletions bindings/napi/BeaconStateView.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ const pubkey = @import("./pubkeys.zig");
const js_types = @import("./js_types.zig");
const sszValueToNapiValue = @import("./to_napi_value.zig").sszValueToNapiValue;
const numberSliceToNapiValue = @import("./to_napi_value.zig").numberSliceToNapiValue;
const napi_io = @import("./io.zig");

/// Allocator used for all BeaconStateView instances.
var gpa: std.heap.DebugAllocator(.{}) = .init;
Expand Down Expand Up @@ -72,7 +71,7 @@ pub const js_meta = js.class(.{ .properties = .{
} });

cached_state: ?*CachedBeaconState = null,
pool_rc: ?*pool.PoolRc = null,
pool_rc: @TypeOf(pool.state.pool_rc) = null,
const BeaconStateView = @This();

pub fn init() BeaconStateView {
Expand Down Expand Up @@ -1037,7 +1036,7 @@ pub fn createMultiProof(self: *const BeaconStateView, descriptor: js.Uint8Array)
pub fn computeUnrealizedCheckpoints(self: *const BeaconStateView) !js_types.UnrealizedCheckpoints {
const env = js.env();
const cached_state = try self.requireState();
const result = try st.computeUnrealizedCheckpoints(allocator, napi_io.get(), cached_state);
const result = try st.computeUnrealizedCheckpoints(allocator, js.io(), cached_state);

const obj = try env.createObject();
try obj.setNamedProperty(
Expand Down Expand Up @@ -1280,7 +1279,7 @@ pub fn processSlots(self: *const BeaconStateView, slot_arg: js.Number, options:
allocator.destroy(post_state);
}

try st.processSlots(allocator, napi_io.get(), post_state, slot_value, .{});
try st.processSlots(allocator, js.io(), post_state, slot_value, .{});
return .{
.cached_state = post_state,
.pool_rc = pool.state.poolRc().ref(),
Expand Down Expand Up @@ -1309,7 +1308,7 @@ pub fn stateTransition(self: *const BeaconStateView, signed_block_bytes: js.Uint
const signed_block = try AnySignedBeaconBlock.deserialize(allocator, .full, fork_seq, bytes);
defer signed_block.deinit(allocator);

const post_state = try st.stateTransition(allocator, napi_io.get(), cached_state, signed_block, opts);
const post_state = try st.stateTransition(allocator, js.io(), cached_state, signed_block, opts);
return .{
.cached_state = post_state,
.pool_rc = pool.state.poolRc().ref(),
Expand Down
53 changes: 29 additions & 24 deletions bindings/napi/blst.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const zapi = @import("zapi:zapi");
const js = zapi.js;
const napi = zapi.napi;
const bls = @import("bls");
const napi_io = @import("./io.zig");

const NativePublicKey = bls.PublicKey;
const NativeSignature = bls.Signature;
Expand All @@ -39,25 +38,31 @@ const BATCH_VERIFY_SIZE = 32;
/// Initialized lazily on first use, torn down via `deinitThreadPool`.
var thread_pool: ?*ThreadPool = null;

pub fn initThreadPool(n_workers: u16) !void {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We could have kept the function as it is by using following signature.

pub fn initThreadPool(n_workers: js.Number) !void

But then it would have been expose to JS surface, which we don't want, as it's an internal life cycle function only used at root with the number of cpu count.

if (thread_pool != null) return error.PoolExists;
thread_pool = try ThreadPool.init(std.heap.page_allocator, napi_io.get(), .{ .n_workers = n_workers });
}
/// Native-only thread pool lifecycle, reached from `root.zig` through the
/// pub `lifecycle` var so it is not part of the JS module surface.
const Lifecycle = struct {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This pattern is safety hatch for above mentioned problem. Now we can access the lifecycle functions in zig but not in the js surface.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this seems reasonable and cleaner than #483 , but thinking about future modules we expose, might get confusing with mixed use in the same file, but this might be overthinking, we can reconsider again when/if we encounter this issue because the blast radius here is not big

nit: is LifeCycle a good name though, seems like blst.lifecycle... is not immediately obvious

pub fn initThreadPool(_: *Lifecycle, n_workers: u16) !void {
if (thread_pool != null) return error.PoolExists;
thread_pool = try ThreadPool.init(std.heap.page_allocator, js.io(), .{ .n_workers = n_workers });
}

/// Closes the `ThreadPool` used for blst operations.
///
/// Note: this can invalidate any inflight verification requests. Consumer is responsible
/// for the lifecycle of their program and should only call this when all work is done.
///
/// This note is however application dependent. For the use case of lodestar,
/// it's likely that this would not be called at all.
/// Same goes for any other long-lived processes.
pub fn deinitThreadPool() void {
if (thread_pool) |p| {
p.deinit(napi_io.get());
thread_pool = null;
/// Closes the `ThreadPool` used for blst operations.
///
/// Note: this can invalidate any inflight verification requests. Consumer is responsible
/// for the lifecycle of their program and should only call this when all work is done.
///
/// This note is however application dependent. For the use case of lodestar,
/// it's likely that this would not be called at all.
/// Same goes for any other long-lived processes.
pub fn deinitThreadPool(_: *Lifecycle) void {
if (thread_pool) |p| {
p.deinit(js.io());
thread_pool = null;
}
}
}
};

pub var lifecycle: Lifecycle = .{};

var gpa: std.heap.DebugAllocator(.{}) = .init;
const allocator = if (builtin.mode == .Debug)
Expand Down Expand Up @@ -375,7 +380,7 @@ pub fn aggregateVerify(msgs: js.Array, pks: js.Array, sig: Signature, pks_valida

const pool = thread_pool orelse return error.ThreadPoolNotInitialized;
const result = pool.aggregateVerify(
napi_io.get(),
js.io(),
&sig.raw,
try boolOrDefault(sig_groupcheck, false),
msg_bufs,
Expand Down Expand Up @@ -473,7 +478,7 @@ pub fn verifyMultipleAggregateSignatures(sets: js.Array, pks_validate: ?js.Boole
};

var seed_bytes: [8]u8 = undefined;
const io = napi_io.get();
const io = js.io();
io.random(&seed_bytes);
var prng = std.Random.DefaultPrng.init(std.mem.readInt(u64, &seed_bytes, .little));
const rand = prng.random();
Expand Down Expand Up @@ -503,7 +508,7 @@ pub fn verifyMultipleAggregateSignatures(sets: js.Array, pks_validate: ?js.Boole

const pool = thread_pool orelse return error.ThreadPoolNotInitialized;
const result = pool.verifyMultipleAggregateSignatures(
napi_io.get(),
js.io(),
n_elems,
msgs,
DST,
Expand Down Expand Up @@ -613,7 +618,7 @@ pub fn aggregateWithRandomness(sets: js.Array) !js.Value {
var sig_ptrs: [MAX_AGGREGATE_PER_JOB]*const NativeSignature = undefined;

var seed_bytes: [8]u8 = undefined;
const io = napi_io.get();
const io = js.io();
io.random(&seed_bytes);
var prng = std.Random.DefaultPrng.init(std.mem.readInt(u64, &seed_bytes, .little));
const rand = prng.random();
Expand Down Expand Up @@ -720,7 +725,7 @@ fn asyncAggRand_execute(_: napi.Env, data: *AsyncAggRandData) void {
return;
};
pool.aggregateWithRandomness(
napi_io.get(),
js.io(),
data.pk_ptrs[0..data.n],
data.sig_ptrs[0..data.n],
data.randomness[0 .. data.n * 32],
Expand Down Expand Up @@ -816,7 +821,7 @@ pub fn asyncAggregateWithRandomness(sets: js.Array) !js.Value {
data.err = null;
data.deferred = undefined;
data.work = undefined;
napi_io.get().random(data.randomness[0 .. n * 32]);
js.io().random(data.randomness[0 .. n * 32]);

for (0..n) |i| {
const set = (try sets.get(@intCast(i))).toValue();
Expand Down
4 changes: 2 additions & 2 deletions bindings/napi/config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const Preset = @import("preset").Preset;

const max_blob_schedule_entries = 16;

pub const State = struct {
const State = struct {
config: BeaconConfig = undefined,
initialized: bool = false,
config_name: [64]u8 = undefined,
Expand Down Expand Up @@ -71,7 +71,7 @@ pub fn set(object: js.Value, genesis_root: js.Uint8Array) !void {
state.initialized = true;
}

pub fn chainConfigFromObject(env: napi.Env, obj: napi.Value) !ChainConfig {
fn chainConfigFromObject(env: napi.Env, obj: napi.Value) !ChainConfig {
var chain_config: ChainConfig = undefined;

inline for (std.meta.fields(ChainConfig)) |field| {
Expand Down
48 changes: 0 additions & 48 deletions bindings/napi/io.zig

This file was deleted.

3 changes: 1 addition & 2 deletions bindings/napi/metrics.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const std = @import("std");
const builtin = @import("builtin");
const js = @import("zapi:zapi").js;
const state_transition = @import("state_transition");
const napi_io = @import("./io.zig");

var gpa: std.heap.DebugAllocator(.{}) = .init;
const allocator = if (builtin.mode == .Debug)
Expand All @@ -15,7 +14,7 @@ var initialized: bool = false;
/// JS: metrics.init() → void
pub fn init() !void {
if (initialized) return;
try state_transition.metrics.init(allocator, napi_io.get(), .{});
try state_transition.metrics.init(allocator, js.io(), .{});
initialized = true;
}

Expand Down
4 changes: 2 additions & 2 deletions bindings/napi/pool.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ const allocator = std.heap.page_allocator;

const default_pool_size: u32 = 0;

pub const PoolRc = RefCount(Node.Pool);
const PoolRc = RefCount(Node.Pool);

/// Pool is wrapped in `RefCount` so binding objects holding pool refs at
/// process exit keep the pool alive until their JS finalizer runs. NAPI
/// env cleanup hook fires before module-level JS holders are finalized,
/// so an unconditional `pool.deinit()` there would free memory that
/// `pool.unref()` calls in those finalizers still need.
pub const State = struct {
const State = struct {
pool_rc: ?*PoolRc = null,

pub fn init(self: *State) !void {
Expand Down
7 changes: 3 additions & 4 deletions bindings/napi/pubkeys.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const bls = @import("bls");
const blst_bindings = @import("./blst.zig");
const PubkeyIndexMap = @import("state_transition").PubkeyIndexMap;
const Index2PubkeyCache = @import("state_transition").Index2PubkeyCache;
const napi_io = @import("./io.zig");

/// Uses page allocator for internal allocations.
/// It's recommended to never reallocate the pubkey2index after initialization.
Expand All @@ -13,7 +12,7 @@ const allocator = std.heap.page_allocator;
const default_initial_capacity: u32 = 0;
const max_stack_aggregate_pubkeys = 512;

pub const State = struct {
const State = struct {
pubkey2index: PubkeyIndexMap = undefined,
index2pubkey: Index2PubkeyCache = undefined,
initialized: bool = false,
Expand Down Expand Up @@ -81,7 +80,7 @@ fn pubkey2indexWrittenSize() usize {
pub fn save(file_path: js.String) !void {
var file_path_buf: [1024]u8 = undefined;
const path = try file_path.toSlice(&file_path_buf);
const io = napi_io.get();
const io = js.io();
const file = try std.Io.Dir.createFile(.cwd(), io, path, .{});
defer file.close(io);

Expand Down Expand Up @@ -110,7 +109,7 @@ pub fn save(file_path: js.String) !void {
pub fn load(file_path: js.String) !void {
var file_path_buf: [1024]u8 = undefined;
const path = try file_path.toSlice(&file_path_buf);
const io = napi_io.get();
const io = js.io();
const file = try std.Io.Dir.openFile(.cwd(), io, path, .{});
defer file.close(io);

Expand Down
11 changes: 3 additions & 8 deletions bindings/napi/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,13 @@ pub const blst = @import("./blst.zig");
pub const pubkeys = @import("./pubkeys.zig");

const options = @import("bls_options");
const napi_io = @import("./io.zig");

var gpa: std.heap.DebugAllocator(.{}) = .init;
const allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_allocator;

fn init(old_ref_count: u32) !void {
if (old_ref_count == 0) {
// First environment — initialize shared state in your threadpool init.
try napi_io.init();
errdefer napi_io.deinit();

var cpu_count: u64 = options.thread_count;
if (options.thread_count == 0) {
cpu_count = @max(try detectCpuCount(), 2) - 1;
Expand All @@ -31,7 +27,7 @@ fn init(old_ref_count: u32) !void {
}

const n_workers = @min(cpu_count, @import("bls").ThreadPool.MAX_WORKERS);
try blst.initThreadPool(@intCast(n_workers));
try blst.lifecycle.initThreadPool(@intCast(n_workers));
try pool.state.init();
try pubkeys.state.init();
config.state.init();
Expand All @@ -42,7 +38,7 @@ fn init(old_ref_count: u32) !void {
/// not prevent the module from loading: warn and fall back to the affinity
/// count (what `std.Thread.getCpuCount()` reports).
fn detectCpuCount() !usize {
return @import("cpu_count").getNumCpus(allocator, napi_io.get()) catch |err| {
return @import("cpu_count").getNumCpus(allocator, js.io()) catch |err| {
std.debug.print(
"Warning: cgroup CPU detection failed ({s}), using affinity count\n",
.{@errorName(err)},
Expand All @@ -54,12 +50,11 @@ fn detectCpuCount() !usize {
fn cleanup(new_ref_count: u32) void {
if (new_ref_count == 0) {
// Last environment — tear down shared state.
blst.deinitThreadPool();
blst.lifecycle.deinitThreadPool();
config.state.deinit();
pubkeys.state.deinit();
pool.state.deinit();
metrics.deinit();
napi_io.deinit();
}
}

Expand Down
4 changes: 2 additions & 2 deletions build.zig.zon
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@
.hash = "zig_yaml-0.1.0-C1161kFWAwDxjKAFmklKwWVDvz2mmq0Q__bDhGGjeyd3",
},
.zapi = .{
.url = "https://github.com/ChainSafe/zapi/archive/refs/tags/zapi-v2.2.0.tar.gz",
.hash = "zapi-2.2.0-rIqzUXBaBADUsvvvB2N5kOBdLEO0rGPhowTqmIXe3qVh",
.url = "https://github.com/ChainSafe/zapi/archive/refs/tags/zapi-v3.0.0.tar.gz",
.hash = "zapi-3.0.0-rIqzUQJsBAB4NLcumPdgG1fXtWjLnkTixzr6xsX5XAVO",
},
.zbench = .{
.url = "git+https://github.com/hendriknielaender/zBench#b2b89c475e3ef1bb2bd71255c80478a82d3e0ca8",
Expand Down
Loading