Skip to content

Commit

Permalink
still trying to figure out run loop of app to determine why node is b…
Browse files Browse the repository at this point in the history
…eing started when info is uninitialized
  • Loading branch information
Inalegwu committed Jun 2, 2024
1 parent 173ea7a commit 4171a90
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 156 deletions.
117 changes: 58 additions & 59 deletions src/peer/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { TypedEventEmitter } from "@src/shared/emitter";
import { globalState$, peerState$ } from "@src/shared/state";
import type { EventTypes, Message, P2PMessage } from "@src/shared/types";
import { generateRandomName } from "@src/shared/utils";
import { Socket, createServer } from "node:net";
import { v4 } from "uuid";

const emitter = new TypedEventEmitter<EventTypes>();
const connections = peerState$.connections.get();
const neighbors = peerState$.neighbors.get();
const NODE_ID = v4();
const NODE_NAME = generateRandomName();
const NODE_ID = globalState$.applicationId.get();
const NODE_NAME = globalState$.deviceName.get();
const DEVICE_TYPE = globalState$.deviceType.get();
const alreadySentMessages = peerState$.alreadySent.get();
const alreadySeenMessages = new Set();
Expand All @@ -26,12 +25,14 @@ const p2pSend = (data: P2PMessage) => {
});
}

for (const $nodeId of neighbors.keys()) {
nodeSend($nodeId, {
data: data.data,
type: data.type,
});
alreadySentMessages.add(data);
if (data.type === "broadcast") {
for (const $nodeId of neighbors.keys()) {
nodeSend($nodeId, {
data: data.data,
type: data.type,
});
alreadySentMessages.add(data);
}
}
};

Expand Down Expand Up @@ -88,7 +89,7 @@ emitter.on("message", ({ connectionId, message }) => {
deviceType,
});

emitter.emit("node-connect", { nodeId, ip, port });
emitter.emit("node-connect", { ip, port });
}

if (type === "message") {
Expand All @@ -98,82 +99,94 @@ emitter.on("message", ({ connectionId, message }) => {
console.log(`unknown node-id ${nodeId}`);
}

emitter.emit("node-message", { nodeId, data: message });
emitter.emit("node-message", { nodeId, packet: message });
}
});

emitter.on("node-connect", ({ nodeId, ip, port }) => {
emitter.on("node-connect", ({ ip, port }) => {
connnect(ip, Number(port), () => {
console.log("connection established");
});
});

emitter.on("node-disconnect", ({ nodeId }) => {
connections.delete(nodeId);
console.log(`Disconnected from ${nodeId}`);
});

emitter.on("node-message", ({ nodeId, data }) => {
if (!alreadySentMessages.has(data)) {
emitter.on("node-message", ({ nodeId, packet }) => {
if (!alreadySentMessages.has(packet)) {
broadcast(
data,
data.data.destination,
data.data.id,
data.data.origin,
data.data.ttl - 1,
packet,
packet.data.destination,
packet.data.id,
packet.data.origin,
packet.data.ttl - 1,
);
}

if (data.type === "broadcast") {
if (alreadySeenMessages.has(data.data.id)) {
if (packet.type === "broadcast") {
if (alreadySeenMessages.has(packet.data.id)) {
return;
}

alreadySeenMessages.add(data.data.id);
alreadySeenMessages.add(packet.data.id);

// this broadcast is for me
if (data.data.destination === NODE_ID) {
if (packet.data.destination === NODE_ID) {
emitter.emit("broadcast", {
data: data,
packet: packet,
nodeId: nodeId!,

Check warning on line 138 in src/peer/index.ts

View workflow job for this annotation

GitHub Actions / Lint TS (Biome)

Forbidden non-null assertion.
});
} else {
alreadySentMessages.add(data);
alreadySentMessages.add(packet);
broadcast(
data,
data.data.destination,
packet,
packet.data.destination,
v4(),
data.data.origin,
data.data.ttl - 1,
packet.data.origin,
packet.data.ttl - 1,
);
}
}

if (data.type === "dm") {
if (data.data.destination === NODE_ID) {
if (packet.type === "dm") {
if (packet.data.destination === NODE_ID) {
emitter.emit("dm", {
message: data,
origin: data.data.origin,
message: packet,
origin: packet.data.origin,
});
} else {
dm(
data,
data.data.destination,
data.data.id,
data.data.origin,
data.data.ttl - 1,
packet,
packet.data.destination,
packet.data.id,
packet.data.origin,
packet.data.ttl - 1,
);
}
}
});

emitter.on("dm", ({ origin, message }) => {
// TODO notify the user of the incoming
// file so they can accept an then stream in
console.log(origin, message);
});

emitter.on("broadcast", ({ data, nodeId }) => {
console.log(data, nodeId);
emitter.on("broadcast", ({ packet, nodeId }) => {
console.log(`Recieved a broadcast from ${nodeId} with data ${packet.data}`);
});

emitter.on("disconnect", (connectionId) => {
const nodeId = findNodeId(connectionId);

if (!nodeId) {
return;
}

console.log(`disconnecting from ${nodeId}`);

neighbors.delete(nodeId);

emitter.emit("node-disconnect", { nodeId });
});

const handleNewSocket = (socket: Socket) => {
Expand Down Expand Up @@ -202,19 +215,6 @@ const handleNewSocket = (socket: Socket) => {
});
});

emitter.on("disconnect", (connectionId) => {
const nodeId = findNodeId(connectionId);

if (!nodeId) {
return;
}

neighbors.delete(nodeId);
console.log(`disconnecting from ${nodeId}`);

emitter.emit("node-disconnect", { nodeId });
});

socket.on("data", (data) => {
try {
emitter.emit("message", {
Expand Down Expand Up @@ -250,12 +250,10 @@ const connnect = (ip: string, port: number, cb: () => void) => {
});
};

const server = createServer((socket) => handleNewSocket(socket));

export default function createP2PNode(opts: {
port: number;
}) {
console.log(`Spinning up TCP server on ${opts.port}`);
const server = createServer((socket) => handleNewSocket(socket));

return {
broadcast,
Expand All @@ -264,6 +262,7 @@ export default function createP2PNode(opts: {
off: emitter.off.bind(emitter),
connnect,
start: () => {
console.log(`Spinning up TCP server on ${opts.port}`);
server.listen(opts.port);
},
close: (cb: () => void) => {
Expand Down
27 changes: 0 additions & 27 deletions src/shared/routers/node.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,7 @@
import { globalState$ } from "@src/shared/state";
import { publicProcedure, router } from "@src/trpc";
import * as fs from "node:fs";
import { v4 } from "uuid";
import z from "zod";

export const nodeRouter = router({
startNode: publicProcedure.mutation(async ({ ctx }) => {
ctx.node.start();
}),
sendFile: publicProcedure
.input(
z.object({
files: z.string().array(),
destinationId: z.string(),
}),
)
.mutation(async ({ ctx, input }) => {
for (const file of input.files) {
const buffer = fs.readFileSync(file);

ctx.node.dm(
{
data: buffer,
type: "dm",
},
input.destinationId,
v4(),
globalState$.applicationId.get(),
10000,
);
}
}),
});
4 changes: 4 additions & 0 deletions src/shared/state/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { event } from "@legendapp/state";

export const changeDeviceNameEvent = event();
export const changeDeviceIdEvent = event();
2 changes: 1 addition & 1 deletion src/shared/state/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ configureObservablePersistence({
});

export const globalState$ = observable<GlobalState>({
colorMode: "dark",
colorMode: "light",
applicationId: null,
deviceName: null,
deviceType: "desktop",
Expand Down
1 change: 1 addition & 0 deletions src/shared/state/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./events";
export * from "./global";
5 changes: 2 additions & 3 deletions src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ export type EventTypes = {
connect: string;
disconnect: string;
"node-connect": {
nodeId: string;
ip: string;
port: string;
};
Expand All @@ -55,11 +54,11 @@ export type EventTypes = {
};
"node-message": {
nodeId: string | undefined;
data: Message;
packet: Message;
};
broadcast: {
nodeId: string;
data: Message;
packet: Message;
};
dm: {
origin: string;
Expand Down
8 changes: 1 addition & 7 deletions src/web/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { StrictMode } from "react";
import ReactDOM from "react-dom/client";
import "react-toastify/dist/ReactToastify.css";
import "virtual:uno.css";
import { globalState$ } from "../shared/state";
import "./App.css";
import { routeTree } from "./routeTree.gen";

Expand All @@ -33,12 +32,7 @@ if (!rootElement?.innerHTML) {
<StrictMode>
<t.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
<Theme
radius="medium"
accentColor="violet"
appearance={globalState$.colorMode.get()}
grayColor="gray"
>
<Theme radius="medium" accentColor="violet" grayColor="gray">
<RouterProvider router={router} />
</Theme>
</QueryClientProvider>
Expand Down
60 changes: 31 additions & 29 deletions src/web/components/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,35 +79,37 @@ export default function Layout({ children }: LayoutProps) {
</Flex>
</Flex>
{children}
<Flex className="absolute bottom-1 right-1 space-x-3 rounded-lg p-3">
<Button
variant="soft"
className="w-9 h-9 cursor-pointer rounded-full"
asChild
>
<Link to="/history">
<History size={13} />
</Link>
</Button>
<Button
variant="soft"
onClick={() => selectFiles()}
radius="full"
className=" w-9 h-9 cursor-pointer"
>
<Plus size={13} />
</Button>
<Button
variant="soft"
radius="full"
asChild
className=" w-9 h-9 cursor-pointer rounded-full"
>
<Link to="/settings">
<Settings size={13} />
</Link>
</Button>
</Flex>
{isHome && (
<Flex className="absolute bottom-1 right-1 space-x-3 rounded-lg p-3">
<Button
variant="soft"
className="w-9 h-9 cursor-pointer rounded-full"
asChild
>
<Link to="/history">
<History size={13} />
</Link>
</Button>
<Button
variant="soft"
onClick={() => selectFiles()}
radius="full"
className=" w-9 h-9 cursor-pointer"
>
<Plus size={13} />
</Button>
<Button
variant="soft"
asChild
radius="full"
className="w-9 h-9 cursor-pointer"
>
<Link to="/settings">
<Settings />
</Link>
</Button>
</Flex>
)}
</Flex>
);
}
Loading

0 comments on commit 4171a90

Please sign in to comment.