Skip to content

Commit

Permalink
feat: Add browser React panrpc demo, prefix all demo CLIs
Browse files Browse the repository at this point in the history
  • Loading branch information
pojntfx committed Feb 13, 2024
1 parent 680b664 commit a270037
Show file tree
Hide file tree
Showing 37 changed files with 258 additions and 7 deletions.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
node_modules
dist
.parcel-cache
coverage
typedoc
out
4 changes: 2 additions & 2 deletions docs/generate-bench-rps.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ cd go

echo "language,data_type,runs" >../out/rps-${SERIALIZER}.csv
for data_type in "${DATA_TYPES[@]}"; do
export RESULTS=$(go run ./cmd/panrpc-example-tcp-rps-client/ --addr localhost:1337 --data-type ${data_type} --serializer ${SERIALIZER})
export RESULTS=$(go run ./cmd/panrpc-example-tcp-rps-client-cli/ --addr localhost:1337 --data-type ${data_type} --serializer ${SERIALIZER})

IFS=$'\n'
for result in ${RESULTS}; do
Expand All @@ -19,7 +19,7 @@ done

cd ../ts
for data_type in "${DATA_TYPES[@]}"; do
export RESULTS=$(ADDR=localhost:1338 DATA_TYPE=${data_type} tsx ./bin/panrpc-example-tcp-rps-client.ts)
export RESULTS=$(ADDR=localhost:1338 DATA_TYPE=${data_type} tsx ./bin/panrpc-example-tcp-rps-client-cli.ts)

IFS=$'\n'
for result in ${RESULTS}; do
Expand Down
4 changes: 2 additions & 2 deletions docs/generate-bench-throughput.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ cd go

echo "language,throughput" >../out/throughput-${SERIALIZER}.csv

export RESULTS=$(go run ./cmd/panrpc-example-tcp-throughput-client/ --addr localhost:1337 --serializer ${SERIALIZER})
export RESULTS=$(go run ./cmd/panrpc-example-tcp-throughput-client-cli/ --addr localhost:1337 --serializer ${SERIALIZER})

IFS=$'\n'
for result in ${RESULTS}; do
Expand All @@ -16,7 +16,7 @@ done

cd ../ts

export RESULTS=$(ADDR=localhost:1338 tsx ./bin/panrpc-example-tcp-throughput-client.ts)
export RESULTS=$(ADDR=localhost:1338 tsx ./bin/panrpc-example-tcp-throughput-client-cli.ts)

IFS=$'\n'
for result in ${RESULTS}; do
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion ts/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "eslint-plugin-prettier"],
"ignorePatterns": ["node_modules", "typedoc", "dist"],
"ignorePatterns": ["node_modules", "typedoc", "dist", "bin/*-web"],
"rules": {
"prettier/prettier": "error",
"import/export": "off",
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 3 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
3 changes: 3 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.next
next-env.d.ts
17 changes: 17 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Metadata } from "next";

export const metadata: Metadata = {
title: "panrpc WebSocket Client Example (Web)",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
173 changes: 173 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"use client";

import { JSONParser } from "@streamparser/json-whatwg";
import { ILocalContext, IRemoteContext, Registry } from "panrpc";
import { env } from "process";
import { useEffect, useState } from "react";
import useAsyncEffect from "use-async";

class Local {
// eslint-disable-next-line class-methods-use-this
async Println(ctx: ILocalContext, msg: string) {
console.log("Printing message", msg, "for remote with ID", ctx.remoteID);

console.log(msg);
}
}

class Remote {
// eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
async Increment(ctx: IRemoteContext, delta: number): Promise<number> {
return 0;
}
}

const addr = env.ADDR || "127.0.0.1:1337";

export default function Home() {
const [clients, setClients] = useState(0);
useEffect(() => console.log(clients, "clients connected"), [clients]);

const [registry] = useState(
new Registry(
new Local(),
new Remote(),

{
onClientConnect: () => setClients((v) => v + 1),
onClientDisconnect: () => setClients((v) => v - 1),
}
)
);

useAsyncEffect(async () => {
const socket = new WebSocket(`ws://${addr}`);

socket.addEventListener("error", (e) => {
console.error("Disconnected with error:", e);
});

await new Promise<void>((res, rej) => {
socket.addEventListener("open", () => res());
socket.addEventListener("error", rej);
});

const encoder = new WritableStream({
write(chunk) {
socket.send(JSON.stringify(chunk));
},
});

const parser = new JSONParser({
paths: ["$"],
separator: "",
});
const parserWriter = parser.writable.getWriter();
const parserReader = parser.readable.getReader();
const decoder = new ReadableStream({
start(controller) {
parserReader
.read()
.then(async function process({ done, value }) {
if (done) {
controller.close();

return;
}

controller.enqueue(value?.value);

parserReader
.read()
.then(process)
.catch((e) => controller.error(e));
})
.catch((e) => controller.error(e));
},
});
socket.addEventListener("message", (m) =>
parserWriter.write(m.data as string)
);
socket.addEventListener("close", () => {
parserReader.cancel();
parserWriter.abort();
});

registry.linkStream(
encoder,
decoder,

(v) => v,
(v) => v
);

console.log("Connected to", addr);

return () => socket.close();
}, []);

const [log, setLog] = useState<string[]>([]);

return clients > 0 ? (
<main>
<h1>panrpc WebSocket Client Example (Web)</h1>

<section>
<h2>Actions</h2>

<button
onClick={() =>
registry.forRemotes(async (remoteID, remote) => {
setLog((v) => [
...v,
"Calling functions for remote with ID " + remoteID,
]);

try {
const res = await remote.Increment(undefined, 1);

setLog((v) => [...v, `${res}`]);
} catch (e) {
console.error(`Got error for Increment func: ${e}`);
}
})
}
>
Increment remote counter by one
</button>
<button
onClick={() =>
registry.forRemotes(async (remoteID, remote) => {
setLog((v) => [
...v,
"Calling functions for remote with ID " + remoteID,
]);

try {
const res = await remote.Increment(undefined, -1);

setLog((v) => [...v, `${res}`]);
} catch (e) {
console.error(`Got error for Increment func: ${e}`);
}
})
}
>
Decrement remote counter by one
</button>
</section>

<section>
<h2>Log</h2>

<textarea
style={{ width: "100%" }}
rows={20}
value={log.join("\n")}
></textarea>
</section>
</main>
) : (
"Connecting ..."
);
}
Binary file not shown.
4 changes: 4 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;
27 changes: 27 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@pojntfx/panrpc-example-websocket-client-web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.1.0"
},
"dependencies": {
"@streamparser/json-whatwg": "^0.0.20",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"use-async": "^1.1.0",
"panrpc": "file:../.."
}
}
26 changes: 26 additions & 0 deletions ts/bin/panrpc-example-websocket-client-web/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
File renamed without changes.

0 comments on commit a270037

Please sign in to comment.