| 63 | yield* Effect.fork(write(new Hello({ remoteId }))) |
| 64 | |
| 65 | function handleRequest(request: typeof ProtocolRequest.Type) { |
| 66 | switch (request._tag) { |
| 67 | case "Ping": { |
| 68 | return write(new Pong({ id: request.id })) |
| 69 | } |
| 70 | case "WriteEntries": { |
| 71 | if (request.encryptedEntries.length === 0) { |
| 72 | return write( |
| 73 | new Ack({ |
| 74 | id: request.id, |
| 75 | sequenceNumbers: [] |
| 76 | }) |
| 77 | ) |
| 78 | } |
| 79 | return Effect.gen(function*() { |
| 80 | const entries = request.encryptedEntries.map(({ encryptedEntry, entryId }) => |
| 81 | new PersistedEntry({ |
| 82 | entryId, |
| 83 | iv: request.iv, |
| 84 | encryptedEntry |
| 85 | }) |
| 86 | ) |
| 87 | const encrypted = yield* storage.write(request.publicKey, entries) |
| 88 | latestSequence = encrypted[encrypted.length - 1].sequence |
| 89 | return yield* write( |
| 90 | new Ack({ |
| 91 | id: request.id, |
| 92 | sequenceNumbers: encrypted.map((e) => e.sequence) |
| 93 | }) |
| 94 | ) |
| 95 | }) |
| 96 | } |
| 97 | case "RequestChanges": { |
| 98 | return Effect.gen(function*() { |
| 99 | const changes = yield* storage.changes(request.publicKey, request.startSequence) |
| 100 | return yield* changes.takeAll.pipe( |
| 101 | Effect.flatMap(function([entries]) { |
| 102 | const latestEntries: Array<EncryptedRemoteEntry> = [] |
| 103 | for (const entry of entries) { |
| 104 | if (entry.sequence <= latestSequence) continue |
| 105 | latestEntries.push(entry) |
| 106 | latestSequence = entry.sequence |
| 107 | } |
| 108 | if (latestEntries.length === 0) return Effect.void |
| 109 | return write( |
| 110 | new Changes({ |
| 111 | publicKey: request.publicKey, |
| 112 | entries: Chunk.toReadonlyArray(entries) |
| 113 | }) |
| 114 | ) |
| 115 | }), |
| 116 | Effect.forever |
| 117 | ) |
| 118 | }).pipe( |
| 119 | Effect.scoped, |
| 120 | FiberMap.run(subscriptions, request.publicKey) |
| 121 | ) |
| 122 | } |