Skip to content
Open
Changes from all 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
28 changes: 8 additions & 20 deletions src/os/persistence/PersistenceLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,17 @@ const SIGNATURE_LENGTH = 32;

export class PersistenceLayer {
/**
* Bolt Optimization: Explicitly typed as Buffer.
* Constructs output buffer using Buffer.allocUnsafe() with manual .set() and .write() copying,
* which is significantly faster (~15%) than Buffer.concat() and avoids multiple buffer allocations.
* Constructs output buffer using Buffer.alloc() to avoid uninitialized heap memory leaks.
*/
save(data: any, key: string): Buffer {
const payload = JSON.stringify(data);
const payloadBuf = Buffer.from(payload, 'utf8');

// Bolt Optimization: Allocate unsafe buffer for exact combined size to avoid Buffer.concat and intermediate payload allocations
const outBuf = Buffer.allocUnsafe(38 + payloadBuf.length);

// Copy pre-allocated header and payload
outBuf.set(HEADER_BUF, 0);
outBuf.set(payloadBuf, 38);
const payloadByteLength = Buffer.byteLength(payload, 'utf8');

// Compute and write HMAC signature directly
const hmac = crypto.createHmac('sha256',. key);
hmac.update(payloadBuf);
const hmac = crypto.createHmac('sha256', key);
hmac.update(payload, 'utf8');
const signature = hmac.digest();
outBuf.set(signature, 6);

const payloadByteLength = Buffer.byteLength(payload, 'utf8');
const out = Buffer.allocUnsafe(HEADER_LENGTH + SIGNATURE_LENGTH + payloadByteLength);
const out = Buffer.alloc(HEADER_LENGTH + SIGNATURE_LENGTH + payloadByteLength);

// Zero-copy set of pre-allocated header
out.set(HEADER_MAGIC, 0);
Expand All @@ -49,7 +37,7 @@ export class PersistenceLayer {
if (!Buffer.isBuffer(buffer)) {
throw new Error('Input must be a Buffer');
}
if (buffer.length < 38) {
if (buffer.length < HEADER_LENGTH + SIGNATURE_LENGTH) {
throw new Error('Invalid format');
}

Expand All @@ -60,8 +48,8 @@ export class PersistenceLayer {
}

// Bolt Optimization: Zero-copy subarray view instead of slice
const signature = buffer.subarray(6, 38);
const payloadSubarray = buffer.subarray(38);
const signature = buffer.subarray(HEADER_LENGTH, HEADER_LENGTH + SIGNATURE_LENGTH);
const payloadSubarray = buffer.subarray(HEADER_LENGTH + SIGNATURE_LENGTH);

const hmac = crypto.createHmac('sha256', key);
// Pass Buffer subarray directly to hmac.update() to avoid string conversion overhead
Expand Down