RPC services refactoring

This commit is contained in:
Julien Valverdé
2024-07-11 22:47:55 +02:00
parent 320ccb5bc5
commit d9df1e15ae
6 changed files with 33 additions and 69 deletions

View File

@@ -6,7 +6,7 @@ import { TRPCContextCreator } from "../trpc/TRPCContextCreator"
import { RPCRouter } from "./RPCRouter"
export module RPCServerRoute {
export module RPCRoute {
export const Live = Layer.effectDiscard(Effect.gen(function*() {
const app = yield* ExpressApp

View File

@@ -0,0 +1,22 @@
import { applyWSSHandler } from "@trpc/server/adapters/ws"
import { Effect, Layer } from "effect"
import { WebSocketServer } from "../http/WebSocketServer"
import { TRPCContextCreator } from "../trpc/TRPCContextCreator"
import { RPCRouter } from "./RPCRouter"
export module RPCWebSocketHandler {
export const Live = Layer.effectDiscard(Effect.acquireRelease(
Effect.gen(function*() {
return applyWSSHandler({
wss: yield* WebSocketServer,
router: yield* RPCRouter,
createContext: yield* TRPCContextCreator,
})
}),
handler => Effect.sync(() =>
handler.broadcastReconnectNotification()
),
))
}

View File

@@ -1,44 +0,0 @@
import { applyWSSHandler } from "@trpc/server/adapters/ws"
import { Context, Effect, Layer, Runtime } from "effect"
import ws from "ws"
import { ExpressHTTPServer } from "../http/ExpressHTTPServer"
import { TRPCContextCreator } from "../trpc/TRPCContextCreator"
import { RPCRouter } from "./RPCRouter"
export class RPCWebSocketServer extends Context.Tag("RPCWebSocketServer")<RPCWebSocketServer, {
wss: ws.Server
handler: ReturnType<typeof applyWSSHandler>
}>() {}
export module RPCWebSocketServer {
export const Live = Layer.effect(RPCWebSocketServer, Effect.acquireRelease(
Effect.gen(function*() {
const runSync = yield* Effect.runtime().pipe(
Effect.map(Runtime.runSync)
)
// Extract this to its own service?
const wss = new ws.WebSocketServer({ server: yield* ExpressHTTPServer }, () =>
runSync(Effect.logInfo(`WebSocket RPC server started`))
)
const handler = applyWSSHandler({
wss,
router: yield* RPCRouter,
createContext: yield* TRPCContextCreator,
})
return { wss, handler }
}),
({ wss, handler }) => Effect.gen(function*() {
yield* Effect.logInfo(`WebSocket server is closing. Waiting for existing connections to end...`)
handler.broadcastReconnectNotification()
yield* Effect.async(resume => {
wss.close(() => resume(Effect.logInfo(`WebSocket server closed`)))
})
}),
))
}