Skip to content

Commit

Permalink
lazy init buffer pool
Browse files Browse the repository at this point in the history
  • Loading branch information
kane50613 committed Mar 4, 2024
1 parent fb29357 commit e4b36db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "redis-on-workers",
"version": "0.2.8",
"version": "0.2.9q",
"description": "Connect to your Redis server using cloudflare:sockets",
"scripts": {
"build": "tsup",
Expand Down
32 changes: 19 additions & 13 deletions src/create-parser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CreateParserOptions } from "./type";

let bufferPool = new Uint8Array(32 * 1024);
let bufferPool: Uint8Array | undefined;
let bufferOffset = 0;
let interval: NodeJS.Timeout | undefined;
let counter = 0;
Expand Down Expand Up @@ -214,7 +214,7 @@ function parseArrayChunks(parser: ParserContext) {
}

function decreaseBufferPool() {
if (bufferPool.length > 50 * 1024) {
if (bufferPool && bufferPool.length > 50 * 1024) {
if (counter === 1 || notDecreased > counter * 2) {
const minSliceLen = Math.floor(bufferPool.length / 10);
const sliceLength =
Expand All @@ -235,18 +235,22 @@ function decreaseBufferPool() {
}

function resizeBuffer(length: number) {
if (bufferPool.length < length + bufferOffset) {
const multiplier = length > 1024 * 1024 * 75 ? 2 : 3;
if (bufferOffset > 1024 * 1024 * 111) {
bufferOffset = 1024 * 1024 * 50;
}
if (bufferPool && bufferPool.length >= length + bufferOffset) {
return;
}

bufferPool = new Uint8Array(length * multiplier + bufferOffset);
bufferOffset = 0;
counter++;
if (interval === null) {
interval = setInterval(decreaseBufferPool, 50);
}
const multiplier = length > 1024 * 1024 * 75 ? 2 : 3;

if (bufferOffset > 1024 * 1024 * 111) {
bufferOffset = 1024 * 1024 * 50;
}

bufferPool = new Uint8Array(length * multiplier + bufferOffset);
bufferOffset = 0;
counter++;

if (interval === null) {
interval = setInterval(decreaseBufferPool, 50);
}
}

Expand All @@ -272,6 +276,8 @@ function concatBulkBuffer(parser: ParserContext) {
resizeBuffer(length);
const start = bufferOffset;

if (!bufferPool) throw new Error("Buffer pool is null");

bufferPool.set(list[0].subarray(oldOffset), start);

bufferOffset += list[0].length - oldOffset;
Expand Down

0 comments on commit e4b36db

Please sign in to comment.