| 319 | } |
| 320 | |
| 321 | function handleMessage(res: typeof ProtocolResponse.Type) { |
| 322 | switch (res._tag) { |
| 323 | case "Hello": { |
| 324 | return log.registerRemote({ |
| 325 | id: res.remoteId, |
| 326 | write: (identity, entries) => |
| 327 | Effect.gen(function*() { |
| 328 | const encrypted = yield* encryption.encrypt(identity, entries) |
| 329 | const deferred = yield* Deferred.make<void>() |
| 330 | const id = pendingCounter++ |
| 331 | pending.set(id, { |
| 332 | entries, |
| 333 | deferred, |
| 334 | publicKey: identity.publicKey |
| 335 | }) |
| 336 | yield* Effect.orDie(write( |
| 337 | new WriteEntries({ |
| 338 | publicKey: identity.publicKey, |
| 339 | id, |
| 340 | iv: encrypted.iv, |
| 341 | encryptedEntries: encrypted.encryptedEntries.map((encryptedEntry, i) => ({ |
| 342 | entryId: entries[i].id, |
| 343 | encryptedEntry |
| 344 | })) |
| 345 | }) |
| 346 | )) |
| 347 | yield* Deferred.await(deferred) |
| 348 | }), |
| 349 | changes: (identity, startSequence) => |
| 350 | Effect.gen(function*() { |
| 351 | const mailbox = yield* RcMap.get(subscriptions, identity.publicKey) |
| 352 | identities.set(mailbox, identity) |
| 353 | yield* Effect.orDie(write( |
| 354 | new RequestChanges({ |
| 355 | publicKey: identity.publicKey, |
| 356 | startSequence |
| 357 | }) |
| 358 | )) |
| 359 | return mailbox |
| 360 | }) |
| 361 | }).pipe(Scope.extend(scope)) |
| 362 | } |
| 363 | case "Ack": { |
| 364 | return Effect.gen(function*() { |
| 365 | const entry = pending.get(res.id) |
| 366 | if (!entry) return |
| 367 | pending.delete(res.id) |
| 368 | const { deferred, entries, publicKey } = entry |
| 369 | const remoteEntries = res.sequenceNumbers.map((sequenceNumber, i) => { |
| 370 | const entry = entries[i] |
| 371 | return new RemoteEntry({ |
| 372 | remoteSequence: sequenceNumber, |
| 373 | entry |
| 374 | }) |
| 375 | }) |
| 376 | const mailbox = yield* RcMap.get(subscriptions, publicKey) |
| 377 | yield* mailbox.offerAll(remoteEntries) |
| 378 | yield* Deferred.done(deferred, Exit.void) |