Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Namui New http wrapping #932

Merged
merged 1 commit into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
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
64 changes: 45 additions & 19 deletions namui/namui-cli/webCode/src/RingBufferWriter.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,49 @@
export type StrictArrayBuffer = ArrayBuffer & { buffer?: undefined };

export type RingBufferInput =
| ["u8", number]
| ["u16", number]
| ["u32", number]
| ["bytes", ArrayBuffer];

export type RingBufferInputs = RingBufferInput[];

export class RingBufferWriter {
private writerIndex = 0;
private isWriting = false;
private queue: RingBufferInputs[] = [];
public constructor(
private readonly wasmMemory: ArrayBuffer,
private readonly bufferPtr: number,
private readonly bufferLen: number,
private readonly writtenBuffer: SharedArrayBuffer,
) {}

public async write(
...tuples: (
| ["u8", number]
| ["u16", number]
| ["u32", number]
| ["bytes", ArrayBuffer]
)[]
) {
const totalByteLength = tuples.reduce((a, b) => {
/**
* It's FIFO.
*/
public write(...inputs: RingBufferInputs) {
this.queue.push(inputs);
if (this.isWriting) {
return;
}
this.runQueueLoop();
}

private async runQueueLoop() {
this.isWriting = true;
try {
while (this.queue.length) {
const inputs = this.queue.shift()!;
await this.writeInputOneByOne(inputs);
}
} finally {
this.isWriting = false;
}
}

private async writeInputOneByOne(inputs: RingBufferInputs) {
const totalByteLength = inputs.reduce((a, b) => {
switch (b[0]) {
case "u8":
return a + 1;
Expand All @@ -38,16 +64,16 @@ export class RingBufferWriter {

await this.waitForBufferAvailable(totalByteLength);

for (const tuple of tuples) {
this.writeTuple(tuple);
for (const input of inputs) {
this.writeInput(input);
}

Atomics.add(new Uint32Array(this.writtenBuffer), 0, totalByteLength);
Atomics.notify(new Int32Array(this.writtenBuffer), 0);
}

writeTuple(
tuple:
private writeInput(
input:
| ["u8", number]
| ["u16", number]
| ["u32", number]
Expand All @@ -57,23 +83,23 @@ export class RingBufferWriter {
this.writerIndex = 0;
}

const type = tuple[0];
const type = input[0];
let value: StrictArrayBuffer;
switch (type) {
case "u8": {
value = new Uint8Array([tuple[1]]).buffer;
value = new Uint8Array([input[1]]).buffer;
break;
}
case "u16": {
value = new Uint16Array([tuple[1]]).buffer;
value = new Uint16Array([input[1]]).buffer;
break;
}
case "u32": {
value = new Uint32Array([tuple[1]]).buffer;
value = new Uint32Array([input[1]]).buffer;
break;
}
case "bytes": {
value = tuple[1];
value = input[1];
break;
}
default: {
Expand All @@ -100,7 +126,7 @@ export class RingBufferWriter {

this.writerIndex = left;
}
async waitForBufferAvailable(byteLength: number) {
private async waitForBufferAvailable(byteLength: number) {
while (true) {
const written = Atomics.load(
new Uint32Array(this.writtenBuffer),
Expand Down
63 changes: 63 additions & 0 deletions namui/namui-cli/webCode/src/bufferPool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { sendMessageToMainThread } from "./interWorkerProtocol";
import { NewEventSystemHandleOnMainThread } from "./newEventSystem";

export type PooledBuffer = {
ptr: number;
view: Uint8Array;
};

export function bufferPoolImports({ memory }: { memory: WebAssembly.Memory }) {
return {
_buffer_pool_new_buffer: (ptr: number, len: number) => {
if (!(memory.buffer instanceof SharedArrayBuffer)) {
throw new Error("memory.buffer must be SharedArrayBuffer");
}

sendMessageToMainThread({
type: "buffer-pool-new-buffer",
ptr,
len,
});
},
};
}

export class BufferPoolHandleOnMainThread {
readonly bufferPool: PooledBuffer[] = [];
readonly bufferWaiters: Array<(buffer: PooledBuffer) => void> = [];

constructor(
private readonly newEventSystemHandle: NewEventSystemHandleOnMainThread,
) {
for (let i = 0; i < 128; i++) {
this.requestBuffer();
}
}

public pushBuffer(buffer: PooledBuffer) {
const waiter = this.bufferWaiters.shift();
if (waiter) {
return waiter(buffer);
}
this.bufferPool.push(buffer);
}

public async getBuffer(): Promise<PooledBuffer> {
this.requestBuffer();

const buffer = this.bufferPool.pop();
if (buffer) {
return buffer;
}

return await new Promise<PooledBuffer>((resolve) => {
this.bufferWaiters.push(resolve);
});
}

private requestBuffer() {
this.newEventSystemHandle.sendEvent({
type: "buffer-pool/request-buffer",
});
}
}
Loading
Loading