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

example: chat example #55

Merged
merged 11 commits into from
Jul 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions examples/chat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist/
docs/
node_modules/
public/static
26 changes: 26 additions & 0 deletions examples/chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Topology Protocol Example

This is an example of Topology Protocol usage in a chat system where a user can create or connect to a chat room and see all the messages sent in the group chat.

## Specifics

Messages are be represented as strings in the format (timestamp, content, senderId). Chat is a class which extends TopologyObject and has Gset\<string> as an attribute to store the list of messages.

## How to run locally

After cloning the repository, run the following commands:

```bash
cd TopologyExample
yarn install
yarn dev
```

Debugging is made easier by setting the mode in `webpack.config.js` to "development":

```js
module.exports = {
mode: "development",
...
}
```
34 changes: 34 additions & 0 deletions examples/chat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "topology-example",
"version": "1.0.0",
"description": "Topology Protocol Chat Exmaple",
"main": "src/index.ts",
"repository": "https://github.com/JanLewDev/TopologyExample.git",
"author": "Jan Lewandowski",
"license": "MIT",
"dependencies": {
"@topology-foundation/crdt": "0.0.22",
"@topology-foundation/network": "0.0.22",
"@topology-foundation/node": "0.0.22",
"@topology-foundation/object": "0.0.22",
"crypto-browserify": "^3.12.0",
"process": "^0.11.10",
"stream-browserify": "^3.0.0",
"ts-node": "^10.9.2",
"vm-browserify": "^1.1.2"
},
"devDependencies": {
"@types/node": "^20.11.16",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.74.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
},
"scripts": {
"build": "webpack",
"clean": "rm -rf dist/ node_modules/",
"dev": "webpack serve",
"start": "ts-node ./src/index.ts"
}
}
41 changes: 41 additions & 0 deletions examples/chat/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Topology - Chat</title>
</head>
<body>
<div>
<h1>Topology Protocol - Chat</h1>
<p>Current peer ID <span id="peerId"></span></p>
<p>Connected to <span id="chatId"></span></p>
<p>peers: <span id="peers"></span></p>
<p>discovery_peers: <span id="discoveryPeers"></span></p>
<p>object_peers: <span id="objectPeers"></span></p>

<input id="roomInput" type="text" placeholder="Room ID" />
<button id="joinRoom">Join Room</button>
<button id="createRoom">Create Room</button>
</div>

<div
id="chat"
style="
overflow-y: scroll;
min-height: 200px;
max-height: 600px;
width: 100%;
"
>
<!-- Messages will appear here -->
</div>

<div style="margin-bottom: 10px">
<input id="messageInput" type="text" placeholder="Message" />
<button id="sendMessage">Send</button>
</div>

<script src="./static/bundle/script.js"></script>
</body>
</html>
30 changes: 30 additions & 0 deletions examples/chat/src/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { toString as uint8ArrayToString } from "uint8arrays/to-string";
import { IChat } from "./objects/chat";

export const handleChatMessages = (chat: IChat, e: any) => {
if (e.detail.msg.topic === "topology::discovery") return;
const input = uint8ArrayToString(e.detail.msg.data);
const message = JSON.parse(input);
switch (message["type"]) {
case "object_update": {
const fn = uint8ArrayToString(new Uint8Array(message["data"]));
handleObjectUpdate(chat, fn);
break;
}
default: {
break;
}
}
};

function handleObjectUpdate(chat: IChat, fn: string) {
// In this case we only have addMessage
// `addMessage(${timestamp}, ${message}, ${node.getPeerId()})`
let args = fn.replace("addMessage(", "").replace(")", "").split(", ");
console.log("Received message: ", args);
try {
chat.addMessage(args[0], args[1], args[2]);
} catch (e) {
console.error(e);
}
}
116 changes: 116 additions & 0 deletions examples/chat/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { TopologyNode } from "@topology-foundation/node";
import { Chat, IChat } from "./objects/chat";
import { handleChatMessages } from "./handlers";

const node = new TopologyNode();
// CRO = Conflict-free Replicated Object
let chatCRO: IChat;
let peers: string[] = [];
let discoveryPeers: string[] = [];
let objectPeers: string[] = [];

const render = () => {
const element_peerId = <HTMLDivElement>document.getElementById("peerId");
element_peerId.innerHTML = node.networkNode.peerId;

const element_peers = <HTMLDivElement>document.getElementById("peers");
element_peers.innerHTML = "[" + peers.join(", ") + "]";

const element_discoveryPeers = <HTMLDivElement>document.getElementById("discoveryPeers");
element_discoveryPeers.innerHTML = "[" + discoveryPeers.join(", ") + "]";

const element_objectPeers = <HTMLDivElement>document.getElementById("objectPeers");
element_objectPeers.innerHTML = "[" + objectPeers.join(", ") + "]";

if(!chatCRO) return;
const chat = chatCRO.getMessages();
const element_chat = <HTMLDivElement>document.getElementById("chat");
element_chat.innerHTML = "";

if(chat.set().size == 0){
const div = document.createElement("div");
div.innerHTML = "No messages yet";
div.style.padding = "10px";
element_chat.appendChild(div);
return;
}
Array.from(chat.set()).sort().forEach((message: string) => {
const div = document.createElement("div");
div.innerHTML = message;
div.style.padding = "10px";
element_chat.appendChild(div);
});

}

async function sendMessage(message: string) {
let timestamp: string = Date.now().toString();
if(!chatCRO) {
console.error("Chat CRO not initialized");
alert("Please create or join a chat room first");
return;
}
console.log("Sending message: ", `(${timestamp}, ${message}, ${node.networkNode.peerId})`);
chatCRO.addMessage(timestamp, message, node.networkNode.peerId);

node.updateObject(chatCRO, `addMessage(${timestamp}, ${message}, ${node.networkNode.peerId})`);
render();
}

async function main() {
await node.start();
render();

node.addCustomGroupMessageHandler((e) => {
handleChatMessages(chatCRO, e);
peers = node.networkNode.getAllPeers();
discoveryPeers = node.networkNode.getGroupPeers("topology::discovery");
if(chatCRO) objectPeers = node.networkNode.getGroupPeers(chatCRO.getObjectId());
render();
});

let button_create = <HTMLButtonElement>document.getElementById("createRoom");
button_create.addEventListener("click", () => {
chatCRO = new Chat(node.networkNode.peerId);
node.createObject(chatCRO);
(<HTMLButtonElement>document.getElementById("chatId")).innerHTML = chatCRO.getObjectId();
render();
});

let button_connect = <HTMLButtonElement>document.getElementById("joinRoom");
button_connect.addEventListener("click", async () => {
let input: HTMLInputElement = <HTMLInputElement>document.getElementById("roomInput");
let objectId = input.value;
input.value = "";
if(!objectId){
alert("Please enter a room id");
return;
}
try {
await node.subscribeObject(objectId, true);

let object: any = node.getObject(objectId);

chatCRO = Object.assign(new Chat(node.networkNode.peerId), object);
(<HTMLButtonElement>document.getElementById("chatId")).innerHTML = objectId;
render();
} catch (e) {
console.error("Error while connecting to the CRO ", objectId, e);
}
});

let button_send = <HTMLButtonElement>document.getElementById("sendMessage");
button_send.addEventListener("click", async () => {
let input: HTMLInputElement = <HTMLInputElement>document.getElementById("messageInput");
let message: string = input.value;
input.value = "";
if(!message){
console.error("Tried sending an empty message");
alert("Please enter a message");
return;
}
await sendMessage(message);
});
}

main();
32 changes: 32 additions & 0 deletions examples/chat/src/objects/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { TopologyObject } from "@topology-foundation/object";
import { GSet } from "@topology-foundation/crdt";

export interface IChat extends TopologyObject {
chat: GSet<string>;
addMessage(timestamp: string, message: string, node_id: string): void;
getMessages(): GSet<string>;
merge(other: Chat): void;
}

export class Chat extends TopologyObject implements IChat {
// store messages as strings in the format (timestamp, message, peerId)
chat: GSet<string>;

constructor(peerId: string) {
super(peerId);
this.chat = new GSet<string>(new Set<string>());
}

addMessage(timestamp: string, message: string, node_id: string): void {
this.chat.add(`(${timestamp}, ${message}, ${node_id})`);
}

getMessages(): GSet<string> {
return this.chat;
}

merge(other: Chat): void {
this.chat.merge(other.chat);
}

}
14 changes: 14 additions & 0 deletions examples/chat/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es6",
"module": "ESNEXT",
"rootDir": ".",
"strict": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
63 changes: 63 additions & 0 deletions examples/chat/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const path = require("path");
const webpack = require("webpack");
const fs = require("fs");

module.exports = {
mode: "development",
entry: path.resolve(__dirname, "./src/index.ts"),
devServer: {
allowedHosts: "all",
client: {
overlay: false,
},
static: {
directory: path.join(__dirname, "public"),
},
compress: true,
hot: true,
port: 3000,
},
module: {
rules: [
{
test: /\.ts?$/,
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.m?js$/,
resolve: {
fullySpecified: false,
},
},
],
},
resolve: {
extensions: [".ts", ".js"],
fallback: {
crypto: require.resolve("crypto-browserify"),
dgram: false,
os: false,
net: false,
path: false,
"process/browser": require.resolve("process/browser"),
stream: require.resolve("stream-browserify"),
vm: require.resolve("vm-browserify"),
},
},
output: {
filename: "script.js",
path: path.resolve(__dirname, "public", "static", "bundle"),
publicPath: "/static/bundle/",
},
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000,
},
plugins: [
new webpack.ProvidePlugin({
process: "process/browser",
}),
],
};
Loading