Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/Syndica/sig into 19/cicd-go…
Browse files Browse the repository at this point in the history
…ssip
  • Loading branch information
0xNineteen committed Jun 10, 2024
2 parents 4802d63 + 12d9939 commit 75126c2
Show file tree
Hide file tree
Showing 49 changed files with 2,611 additions and 630 deletions.
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub fn build(b: *Build) void {
});
b.installArtifact(unit_tests);
unit_tests.root_module.addImport("base58-zig", base58_module);
unit_tests.root_module.addImport("curl", curl_mod);
unit_tests.root_module.addImport("httpz", httpz_mod);
unit_tests.root_module.addImport("zig-network", zig_network_module);
unit_tests.root_module.addImport("zstd", zstd_mod);
Expand Down
123 changes: 53 additions & 70 deletions remove_unused.py
Original file line number Diff line number Diff line change
@@ -1,85 +1,68 @@
# parse arg of file name
# parse arg of file name
import sys
import os
import re

if len(sys.argv) != 2:
print("Usage: python remove_unused.py <dir name>")
sys.exit()

zig_files = []
dirs = [sys.argv[1]]
while 1:
while 1:
d = dirs.pop()
files = os.listdir(d)
for file in files:
for file in files:
full_path = os.path.join(d, file)
if os.path.isdir(full_path):
if os.path.isdir(full_path):
dirs.append(full_path)
else:
# if file ends in .zig
if file.endswith('.zig'):
else:
# if file ends in .zig
if file.endswith(".zig"):
zig_files.append(full_path)

if len(dirs) == 0:
break

total_removes = 0
n_remove_iter = 0
n_removes = 1
while n_removes > 0:
n_removes = 0
print(f"iteration: {n_remove_iter}, lines removed: {n_removes}")
n_remove_iter += 1

for filename in zig_files:
print(filename)

# open and read lines of file
with open(filename, 'r') as f:
full_lines = f.readlines()

# parse the value {VAR} name in 'const {VAR} = @import ...'
import_var_names = []
for (i, line) in enumerate(full_lines):
if not (line.startswith('const') or line.startswith('pub const')):
continue

if '@import' not in line:
continue

start_index = line.index("const ")
end_index = line.index(" = ")
var_name = line[start_index + 6:end_index]
import_var_names.append((var_name, i))

unused_vars = import_var_names.copy()
for i, line in enumerate(full_lines):

for var, line_num in import_var_names:
if (var in line) and (i != line_num):
if (var, line_num) in unused_vars:
unused_vars.remove((var, line_num))

new_lines = []
lines_to_remove = [i for (_, i) in unused_vars]
n_removes += len(lines_to_remove)
total_removes += len(lines_to_remove)

for (i, line) in enumerate(full_lines):
if i in lines_to_remove:
continue
new_lines.append(line)

if (len(lines_to_remove) > 0):
print(filename)
print(unused_vars)

# write
with open(filename, 'w') as f:
f.writelines(new_lines)

print("total iterations: ", n_remove_iter)
print("total lines removed: ", total_removes)

if (total_removes > 0):
exit(1)
if len(dirs) == 0:
break

import_line_regex = re.compile(
r'const ([a-zA-Z0-9_]+) = (@import\("[a-zA-Z0-9_]+"\))?[a-zA-Z0-9_.]*;'
)

total_num_lines_removed = 0
lines_removed_this_time = 999 # get past 1st while check

while lines_removed_this_time > 0:
lines_removed_this_time = 0
for path in zig_files:
with open(path) as f:
orig_file = f.read()
orig_lines = orig_file.split("\n")
if orig_lines[-1] == "":
orig_lines = orig_lines[0:-1]
imported_names = []
for line_num, line in enumerate(orig_lines):
match = import_line_regex.match(line)
if match:
imported_names.append((match.groups()[0], line_num))
lines_to_drop = set()
num_lines_to_remove = 0
for name, line in imported_names:
match = re.findall(f"[^a-zA-Z0-9_.]{name}[^a-zA-Z0-9_]", orig_file)
assert len(match) > 0
if len(match) == 1:
lines_to_drop.add(line)
num_lines_to_remove += 1
with open(path, "w") as f:
f.writelines(
f"{line}\n"
for i, line in enumerate(orig_lines)
if i not in lines_to_drop
)
lines_to_drop
print(path, num_lines_to_remove)
total_num_lines_removed += num_lines_to_remove
lines_removed_this_time += num_lines_to_remove
print("removed this iteration:", lines_removed_this_time)
print()

print("total lines removed:", total_num_lines_removed)
26 changes: 23 additions & 3 deletions src/accountsdb/accounts_file.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,27 @@ const Pubkey = @import("../core/pubkey.zig").Pubkey;

const AccountFileInfo = @import("snapshots.zig").AccountFileInfo;

pub const FileId = u32;
/// Simple strictly-typed alias for an integer, used to represent a file ID.
pub const FileId = enum(u32) {
_,

pub inline fn fromInt(int: u32) FileId {
return @enumFromInt(int);
}

pub inline fn toInt(file_id: FileId) u32 {
return @intFromEnum(file_id);
}

pub fn format(
_: FileId,
comptime _: []const u8,
_: std.fmt.FormatOptions,
_: anytype,
) !void {
@compileError("Should not print " ++ @typeName(FileId) ++ " directly");
}
};

// an account thats stored in an AccountFile
pub const AccountInFile = struct {
Expand All @@ -25,14 +45,14 @@ pub const AccountInFile = struct {
len: usize = 0,

/// info about the account stored
pub const StorageInfo = struct {
pub const StorageInfo = extern struct {
write_version_obsolete: u64,
data_len: u64,
pubkey: Pubkey,
};

/// on-chain account info about the account
pub const AccountInfo = struct {
pub const AccountInfo = extern struct {
lamports: u64,
rent_epoch: Epoch,
owner: Pubkey,
Expand Down
6 changes: 3 additions & 3 deletions src/accountsdb/db.zig
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,8 @@ pub const AccountsDB = struct {
std.debug.panic("failed to *sanitize* AccountsFile: {d}.{d}: {s}\n", .{ accounts_file.slot, accounts_file.id, @errorName(err) });
};

const file_id_u32: u32 = @intCast(accounts_file_id);
file_map.putAssumeCapacityNoClobber(file_id_u32, accounts_file);
const file_id = FileId.fromInt(@intCast(accounts_file_id));
file_map.putAssumeCapacityNoClobber(file_id, accounts_file);

if (print_progress and progress_timer.read() > DB_PROGRESS_UPDATES_NS) {
printTimeEstimate(
Expand Down Expand Up @@ -984,7 +984,7 @@ pub const AccountsDB = struct {
var refs = try ArrayList(AccountRef).initCapacity(reference_allocator, n_accounts);

try self.account_index.validateAccountFile(account_file, bin_counts, &refs);
try self.storage.file_map.put(@as(u32, @intCast(account_file.id)), account_file.*);
try self.storage.file_map.put(FileId.fromInt(@intCast(account_file.id)), account_file.*);
const refs_ptr = try self.account_index.addMemoryBlock(refs);

// allocate enough memory here
Expand Down
5 changes: 3 additions & 2 deletions src/accountsdb/index.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const Hash = @import("../core/hash.zig").Hash;
const Slot = @import("../core/time.zig").Slot;
const Pubkey = @import("../core/pubkey.zig").Pubkey;
const AccountFile = @import("accounts_file.zig").AccountFile;
const FileId = @import("accounts_file.zig").FileId;

/// reference to an account (either in a file or cache)
pub const AccountRef = struct {
Expand All @@ -16,7 +17,7 @@ pub const AccountRef = struct {

pub const AccountLocation = union(enum(u8)) {
File: struct {
file_id: u32,
file_id: FileId,
offset: usize,
},
Cache: struct {
Expand Down Expand Up @@ -190,7 +191,7 @@ pub const AccountIndex = struct {
.slot = accounts_file.slot,
.location = .{
.File = .{
.file_id = @as(u32, @intCast(accounts_file.id)),
.file_id = FileId.fromInt(@intCast(accounts_file.id)),
.offset = offset,
},
},
Expand Down
22 changes: 22 additions & 0 deletions src/accountsdb/lib.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub const accounts_file = @import("accounts_file.zig");
pub const bank = @import("bank.zig");
pub const db = @import("db.zig");
pub const download = @import("download.zig");
pub const genesis_config = @import("genesis_config.zig");
pub const index = @import("index.zig");
pub const snapshots = @import("snapshots.zig");
pub const sysvars = @import("sysvars.zig");

pub const AccountsDB = db.AccountsDB;
pub const AccountsDBConfig = db.AccountsDBConfig;
pub const AllSnapshotFields = snapshots.AllSnapshotFields;
pub const Bank = bank.Bank;
pub const GenesisConfig = genesis_config.GenesisConfig;
pub const SnapshotFieldsAndPaths = snapshots.SnapshotFieldsAndPaths;
pub const SnapshotFiles = snapshots.SnapshotFiles;
pub const StatusCache = snapshots.StatusCache;

pub const downloadSnapshotsFromGossip = download.downloadSnapshotsFromGossip;
pub const parallelUnpackZstdTarBall = snapshots.parallelUnpackZstdTarBall;

pub const ACCOUNT_INDEX_BINS = db.ACCOUNT_INDEX_BINS;
11 changes: 10 additions & 1 deletion src/accountsdb/snapshots.zig
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,16 @@ pub const AccountFileInfo = struct {
id: usize,
length: usize, // amount of bytes used

pub fn validate(self: *const AccountFileInfo, file_size: usize) !void {
pub const ValidateError = error{
IdOverflow,
FileSizeTooSmall,
FileSizeTooLarge,
OffsetOutOfBounds,
};
pub fn validate(self: *const AccountFileInfo, file_size: usize) ValidateError!void {
if (self.id > std.math.maxInt(u32)) {
return error.IdOverflow;
}
if (file_size == 0) {
return error.FileSizeTooSmall;
} else if (file_size > @as(usize, MAXIMUM_ACCOUNT_FILE_SIZE)) {
Expand Down
43 changes: 25 additions & 18 deletions src/bincode/bincode.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ const testing = std.testing;

const bincode = @This();

pub const config = struct {
// TODO move these files to the bincode folder
pub const arraylist = @import("../utils/arraylist.zig");
pub const shortvec = @import("../utils/shortvec.zig");
pub const varint = @import("../utils/varint.zig");
};

pub const Params = struct {
pub const legacy: Params = .{
.endian = .little,
Expand Down Expand Up @@ -110,24 +117,24 @@ pub fn read(allocator: std.mem.Allocator, comptime U: type, reader: anytype, par
} else {
inline for (info.fields) |field| {
if (field.is_comptime) continue;
if (getFieldConfig(T, field)) |config| {
if (shouldUseDefaultValue(field, config)) |default_value| {
if (getFieldConfig(T, field)) |field_config| {
if (shouldUseDefaultValue(field, field_config)) |default_value| {
@field(data, field.name) = @as(*const field.type, @ptrCast(@alignCast(default_value))).*;
continue;
}

if (config.deserializer) |deser_fcn| {
if (field_config.deserializer) |deser_fcn| {
@field(data, field.name) = try deser_fcn(allocator, reader, params);
continue;
}

if (config.default_on_eof) {
if (field_config.default_on_eof) {
const field_type = field.type;
@field(data, field.name) = bincode.read(allocator, field_type, reader, params) catch |err| blk: {
if (err == error.EndOfStream) {
if (field.default_value) |default_value| {
break :blk @as(*const field_type, @ptrCast(@alignCast(default_value))).*;
} else if (config.default_fn) |default_fcn| {
} else if (field_config.default_fn) |default_fcn| {
break :blk default_fcn(allocator);
} else {
return error.MissingFieldDefaultValue;
Expand Down Expand Up @@ -346,8 +353,8 @@ pub fn free(allocator: std.mem.Allocator, value: anytype) void {
}
val.deinit();
} else inline for (info.fields) |field| {
if (getFieldConfig(T, field)) |config| {
if (config.free) |free_fcn| {
if (getFieldConfig(T, field)) |field_config| {
if (field_config.free) |free_fcn| {
var field_value = @field(value, field.name);
switch (@typeInfo(field.type)) {
.Pointer => |*field_info| {
Expand Down Expand Up @@ -412,8 +419,8 @@ pub fn write(writer: anytype, data: anytype, params: bincode.Params) !void {
.Type, .Void, .NoReturn, .Undefined, .Null, .Fn, .Opaque, .Frame, .AnyFrame => return,
.Bool => return writer.writeByte(@intFromBool(data)),
.Enum => |_| {
if (getConfig(T)) |config| {
if (config.serializer) |serialize_fcn| {
if (getConfig(T)) |type_config| {
if (type_config.serializer) |serialize_fcn| {
return serialize_fcn(writer, data, params);
}
}
Expand Down Expand Up @@ -449,10 +456,10 @@ pub fn write(writer: anytype, data: anytype, params: bincode.Params) !void {
inline for (info.fields) |field| {
if (field.is_comptime) continue;

if (getFieldConfig(T, field)) |config| {
if (config.skip) {
if (getFieldConfig(T, field)) |field_config| {
if (field_config.skip) {
continue;
} else if (config.serializer) |ser_fcn| {
} else if (field_config.serializer) |ser_fcn| {
try ser_fcn(writer, @field(data, field.name), params);
continue;
}
Expand Down Expand Up @@ -592,23 +599,23 @@ pub fn FieldConfig(comptime T: type) type {
pub fn getConfig(comptime struct_type: type) ?FieldConfig(struct_type) {
const bincode_field = "!bincode-config";
if (@hasDecl(struct_type, bincode_field)) {
const config = @field(struct_type, bincode_field);
return config;
const type_config = @field(struct_type, bincode_field);
return type_config;
}
return null;
}

pub fn getFieldConfig(comptime struct_type: type, comptime field: std.builtin.Type.StructField) ?FieldConfig(field.type) {
const bincode_field = "!bincode-config:" ++ field.name;
if (@hasDecl(struct_type, bincode_field)) {
const config = @field(struct_type, bincode_field);
return config;
const field_config = @field(struct_type, bincode_field);
return field_config;
}
return null;
}

pub inline fn shouldUseDefaultValue(comptime field: std.builtin.Type.StructField, comptime config: FieldConfig(field.type)) ?*const anyopaque {
if (config.skip) {
pub inline fn shouldUseDefaultValue(comptime field: std.builtin.Type.StructField, comptime field_config: FieldConfig(field.type)) ?*const anyopaque {
if (field_config.skip) {
if (field.default_value == null) {
const field_type_name = @typeName(field.type);
@compileError("┓\n|\n|--> Invalid config: cannot skip field '" ++ field_type_name ++ "." ++ field.name ++ "' deserialization if no default value set\n\n");
Expand Down
6 changes: 6 additions & 0 deletions src/bloom/lib.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub const bit_set = @import("bit_set.zig");
pub const bit_vec = @import("bit_vec.zig");
pub const bitvec = @import("bitvec.zig");
pub const bloom = @import("bloom.zig");

pub const Bloom = bloom.Bloom;
Loading

0 comments on commit 75126c2

Please sign in to comment.