MCPcopy Create free account
hub / github.com/Effect-TS/effect / withRunClient

Function withRunClient

packages/effect/src/unstable/rpc/Utils.ts:68–120  ·  view source on GitHub ↗
(
  f: (
    write: (clientId: number, response: FromServerEncoded) => Effect.Effect<void>,
    clientIds: ReadonlySet<number>
  ) => Effect.Effect<Omit<Protocol["Service"], "run">, EX, RX>
)

Source from the content-addressed store, hash-verified

66 * @since 4.0.0
67 */
68export const withRunClient = <EX, RX>(
69 f: (
70 write: (clientId: number, response: FromServerEncoded) => Effect.Effect<void>,
71 clientIds: ReadonlySet<number>
72 ) => Effect.Effect<Omit<Protocol["Service"], "run">, EX, RX>
73): Effect.Effect<Protocol["Service"], EX, RX> =>
74 Effect.suspend(() => {
75 const clientIds = new Set<number>()
76 const clientBuffers = new Map<number, Array<[FromServerEncoded, Context.Context<never>]>>()
77 const clientWrites = new Map<number, (data: FromServerEncoded) => Effect.Effect<void>>()
78 let write = (clientId: number, data: FromServerEncoded): Effect.Effect<void> =>
79 Effect.contextWith((context) => {
80 let buffer = clientBuffers.get(clientId)
81 if (!buffer) {
82 buffer = []
83 clientBuffers.set(clientId, buffer)
84 }
85 buffer.push([data, context])
86 return Effect.void
87 })
88 return Effect.map(
89 f((clientId, data) => {
90 const clientWrite = clientWrites.get(clientId)
91 if (clientWrite) {
92 return clientWrite(data)
93 }
94 return write(clientId, data)
95 }, clientIds),
96 (a) => ({
97 ...a,
98 run(clientId, f) {
99 return Effect.gen(function*() {
100 clientIds.add(clientId)
101 clientWrites.set(clientId, f)
102
103 const buffer = clientBuffers.get(clientId)
104 if (buffer) {
105 clientBuffers.delete(clientId)
106 for (const [args, context] of buffer) {
107 yield* Effect.provideContext(Effect.suspend(() => f(args)), context)
108 }
109 }
110
111 return yield* Effect.onExit(Effect.never, () => {
112 clientIds.delete(clientId)
113 clientWrites.delete(clientId)
114 return Effect.void
115 })
116 })
117 }
118 } satisfies Protocol["Service"])
119 )
120 })

Callers

nothing calls this directly

Calls 4

writeFunction · 0.70
getMethod · 0.65
fFunction · 0.50
mapMethod · 0.45

Tested by

no test coverage detected