Last active
January 12, 2025 09:42
-
-
Save boseabhishek/2e52e23c5f291a11d8ef36dc4bcf89cc to your computer and use it in GitHub Desktop.
sync server + am-repo ws n/w adapter (using deno)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NetworkAdapter } from "@automerge/automerge-repo"; | |
import { PeerMetadata, Message } from "@automerge/automerge-repo"; | |
import { PeerId } from "@automerge/automerge-repo"; | |
export class FooWSNetworkAdapter extends NetworkAdapter { | |
sockets: Map<PeerId, WebSocket> = new Map(); | |
#ready = false; | |
#readyResolver?: () => void; | |
#readyPromise: Promise<void> = new Promise<void>((resolve) => { | |
this.#readyResolver = resolve; | |
}); | |
isReady() { | |
return this.#ready; | |
} | |
whenReady() { | |
return this.#readyPromise; | |
} | |
#forceReady() { | |
if (!this.#ready) { | |
this.#ready = true; | |
this.#readyResolver?.(); | |
} | |
} | |
constructor( | |
private socket: WebSocket, | |
) { | |
super() | |
} | |
override connect(peerId: PeerId, peerMetadata?: PeerMetadata): void { | |
this.peerId = peerId | |
this.peerMetadata = peerMetadata | |
this.socket.onclose = () => { | |
console.log("ws connection closed"); | |
}; | |
this.socket.onopen = () => { | |
console.log("received open"); | |
this.socket.onmessage = (msg) => { | |
console.log("received msg:", msg.data); | |
}; | |
}; | |
} | |
override send(message: Message): void { | |
throw new Error("Method not implemented."); | |
} | |
override disconnect(): void { | |
throw new Error("Method not implemented."); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sync-server impl to host our repo | |
import { serve } from "https://deno.land/[email protected]/http/server.ts"; | |
import { FooWSNetworkAdapter } from "./FooWSNetworkAdapter.ts"; | |
import {PeerId, Repo} from "@automerge/automerge-repo" | |
const handler = async (req: Request): Promise<Response> => { | |
const { socket, response } = Deno.upgradeWebSocket(req); | |
const config = { | |
network: [new FooWSNetworkAdapter(socket)], | |
// storage: new DummyStorageAdapter(), | |
peerId: `whatever-000` as PeerId, | |
sharePolicy: async () => false, | |
} | |
const repo = new Repo(config) | |
return response; | |
}; | |
console.log("Our very own Sync Server started @ws://localhost:8080"); | |
serve(handler, { port: 8080 }); | |
// deno run --allow-net sync-server.ts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use a Go WS client to talk to the above sync-server (WS).