Skip to content

Commit

Permalink
but what if i rewrote it a fourth time
Browse files Browse the repository at this point in the history
persistent log for events, with collapse on next open
  • Loading branch information
cysabi committed Mar 30, 2024
1 parent 166de2a commit b7dfbf6
Show file tree
Hide file tree
Showing 7 changed files with 210 additions and 37 deletions.
Binary file modified buncg.state
Binary file not shown.
Binary file modified buncg.state-lock
Binary file not shown.
178 changes: 178 additions & 0 deletions consume/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions consume/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"preview": "bunx --bun vite preview"
},
"dependencies": {
"msgpackr": "^1.10.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"zustand": "^4.5.2"
Expand Down
25 changes: 18 additions & 7 deletions consume/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { pack, unpack } from "msgpackr";

type Emit = {
type: "emit";
id: string;
patches: Array<
{ path?: undefined; value: any } | { path: string[]; value?: any }
>;
};

export class Client {
ws: WebSocket;
listeners: { [id: string]: (state: unknown) => void };
[any: string]: any;

constructor(url = `ws://${location.host}`) {
this.ws = new WebSocket(url);
constructor() {
this.ws = new WebSocket(`ws://${location.host}`);
this.listeners = {};

this.ws.binaryType = "arraybuffer";
this.ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
const data = unpack(event.data);

switch (data.type) {
case "emit":
Expand All @@ -17,8 +27,9 @@ export class Client {
});
}

handleEmit(data: { type: "emit"; id: string; state: unknown }) {
this.listeners[data.id](data.state);
handleEmit(data: Emit) {
// has own state,
this.listeners[data.id](data);
}

act(action: string, payload: any) {
Expand All @@ -45,6 +56,6 @@ export class Client {
resolve();
}
});
this.ws.send(JSON.stringify(obj));
this.ws.send(pack(obj));
}
}
4 changes: 0 additions & 4 deletions consume/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ const App = () => {
const flavorText = cg.useState((s: any) => s.flavorText);
const name = cg.useState((s: any) => s.scoreboard[0].name);

cg.ws.addEventListener("message", (event) => {
setLog([...log, "Received message: " + event.data]);
});

return (
<div className="flex flex-col w-full max-w-6xl mx-auto p-2 gap-2" id="feed">
<div className="flex gap-2">
Expand Down
39 changes: 13 additions & 26 deletions lib/buncg.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ServerWebSocket, WebSocketHandler } from "bun";
import { open } from "lmdb";
import { Encoder } from "msgpackr";
import { pack, unpack } from "msgpackr";
import Immutable from "immutable";

type Input<S> = {
Expand Down Expand Up @@ -46,31 +46,17 @@ export type Emit = {

export default class BunCG<S extends {}> {
#filepath = "buncg.state";
#structs = {
$: Symbol.for("$structs"),
} as {
$: symbol;
get: () => any[];
set: (s: any[0]) => void;
};
#structs = Symbol.for("$structs");
_db;
_encoder;
_state: Immutable.FromJS<S>;
_actions;
_websocket: WebSocketHandler;
_watchers: Watcher[];

constructor(input: Input<S>) {
this._db = open(this.#filepath, {
sharedStructuresKey: this.#structs.$,
});
this.#structs.get = () => this._db.get(this.#structs.$) || [];
this.#structs.set = (s) => this._db.putSync(this.#structs.$, s);
this._encoder = new Encoder({
getStructures: this.#structs.get,
saveStructures: this.#structs.set,
sharedStructuresKey: this.#structs,
});

this._state = Immutable.fromJS(input.state).withMutations((draft) => {
this._db.getRange({ start: 0 }).forEach(({ value }) =>
value.forEach((patch: PatchPathed) => {
Expand All @@ -87,9 +73,10 @@ export default class BunCG<S extends {}> {
});
this._actions = input.actions;
this._websocket = {
message: (ws, msg: string) => {
console.log(`ws ~ message ~ ${msg}`);
const data: Message = JSON.parse(msg);
message: (ws, msg: Buffer) => {
const data: Message = unpack(msg);

console.log(`ws ~ message ~ ${data}`);

switch (data.type) {
case "action":
Expand Down Expand Up @@ -205,15 +192,15 @@ export default class BunCG<S extends {}> {
}

_eventsEmit(...events: Emit[]) {
events.forEach(({ ws, id, patches }) => {
events.forEach(({ ws, id, patches }) =>
ws.send(
this._encoder.encode({
pack({
type: "emit",
id,
patches,
})
);
});
)
);
}

_persistAppend(value: Patch[]) {
Expand All @@ -227,9 +214,9 @@ export default class BunCG<S extends {}> {

_persistCollapse() {
this._db.transactionSync(() => {
const structs = this.#structs.get();
const structs = this._db.get(this.#structs) || [];
this._db.clearSync();
this.#structs.set(structs);
this._db.putSync(this.#structs, structs);
this._db.putSync(0, [{ value: this._state }]);
});
}
Expand Down

0 comments on commit b7dfbf6

Please sign in to comment.