Use threadlocal prng

This commit is contained in:
jaina heartles 2022-07-24 17:18:25 -07:00
parent a7b1361048
commit 47e157e31b
2 changed files with 12 additions and 7 deletions

View File

@ -84,14 +84,18 @@ pub const RegistrationInfo = struct {
email: ?[]const u8,
};
threadlocal var prng: std.rand.DefaultPrng = undefined;
pub fn initThreadPrng(seed: u64) void {
prng = std.rand.DefaultPrng.init(seed +% std.Thread.getCurrentId());
}
pub const ApiServer = struct {
prng: std.rand.DefaultPrng,
db: db.Database,
internal_alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator) !ApiServer {
return ApiServer{
.prng = std.rand.DefaultPrng.init(@bitCast(u64, std.time.milliTimestamp())),
.db = try db.Database.init(),
.internal_alloc = alloc,
};
@ -121,7 +125,7 @@ pub const ApiServer = struct {
}
pub fn createNoteUser(self: *ApiServer, info: NoteCreate, ctx: ApiContext) !models.Note {
const id = Uuid.randV4(self.prng.random());
const id = Uuid.randV4(prng.random());
// TODO: check for dupes
const note = models.Note{
@ -137,8 +141,8 @@ pub const ApiServer = struct {
}
pub fn register(self: *ApiServer, info: RegistrationInfo) !models.Actor {
const actor_id = Uuid.randV4(self.prng.random());
const user_id = Uuid.randV4(self.prng.random());
const actor_id = Uuid.randV4(prng.random());
const user_id = Uuid.randV4(prng.random());
// TODO: transaction?
if (try self.db.existsWhereEq(models.LocalUser, .username, info.username)) {
@ -216,7 +220,7 @@ pub const ApiServer = struct {
models.Token.HashFn.hash(&token, &hash, .{});
const db_token = models.Token{
.id = Uuid.randV4(self.prng.random()),
.id = Uuid.randV4(prng.random()),
.hash = .{ .data = hash },
.user_id = user.id,
.issued_at = DateTime.now(),
@ -242,7 +246,7 @@ pub const ApiServer = struct {
}
pub fn react(self: *ApiServer, note_id: Uuid, ctx: ApiContext) !void {
const id = Uuid.randV4(self.prng.random());
const id = Uuid.randV4(prng.random());
try self.db.insert(models.Reaction, .{ .id = id, .note_id = note_id, .reactor_id = ctx.user_context.user.actor_id.?, .created_at = DateTime.now() });
}

View File

@ -64,5 +64,6 @@ pub const RequestServer = struct {
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var srv = try RequestServer.init(gpa.allocator());
api.initThreadPrng(@bitCast(u64, std.time.milliTimestamp()));
return srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
}