/* * Actyx Pond: A TypeScript framework for writing distributed apps * deployed on peer-to-peer networks, without any servers. * * Copyright (C) 2020 Actyx AG */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { ActyxEvent, EventFns, Metadata, Milliseconds, Offset, OffsetMap, StateWithProvenance, StreamId, Timestamp, Where, } from '@actyx/sdk' import { lt } from 'fp-ts/lib/Ord' import { Map } from 'immutable' import { Observable, Subject, Subscription as RxSubscription, from, of } from '../node_modules/rxjs' import { catchError, tap, filter, map, take, concatMap, mergeScan, reduce, startWith, } from '../node_modules/rxjs/operators' import log from './loggers' import { PondStateTracker } from './pond-state' import { Fish, FishId } from './types' import { lookup } from './util' // I is an intermediate value that is consumed by the specialized command handling logic. // Pond V1 has Async vs. SyncCommandResult, while V2 has Payload+Tags. export type CommandFn = (state: S) => I export type FishJar = Readonly<{ // enqueue the commands for processing enqueueCommand: (command: C, onComplete: () => void, onError: (err: any) => void) => void // public "state" publicSubject: Observable

dispose: () => void dump: () => string }> type CommandInput = Readonly<{ type: 'command' command: CommandFn onComplete: () => void onError: (err: any) => void }> export type CommandPipeline = Readonly<{ // Subject where new commands must be pushed subject: Subject> // Subscription to the running pipeline (cancel to destroy pipeline) subscription: RxSubscription }> type CommandScanState = Readonly<{ waitFor: Record }> const hasAllOffsets = (offsets: Record, waitFor: Record) => { for (const [stream, offsetToWaitFor] of Object.entries(waitFor)) { const latestSeen = lookup(offsets, stream) if (latestSeen === undefined || offsetToWaitFor > latestSeen) { return false } } return true } const commandPipeline = ( pondStateTracker: PondStateTracker, semantics: string, name: string, handler: (input: I) => Promise, stateSubject: Observable>, eventFilter: (t: Metadata) => boolean, ): CommandPipeline => { const commandIn: Subject> = new Subject() // Command handling pipeline. After each command, if it emitted any events that we are subscribed to, // the handling of the following command is delayed until upstream (event aggregation) has seen and // integrated the event into our state. // In this way, we arrive at our core command guarantee: Every command sees all local effects of all // preceding commands. const cmdScanAcc = ( current: CommandScanState, input: CommandInput, ): Observable => { const { command, onComplete, onError } = input const pondStateTrackerCommandProcessingToken = pondStateTracker.commandProcessingStarted( semantics, name, ) const unblock = () => { pondStateTracker.commandProcessingFinished(pondStateTrackerCommandProcessingToken) } const result = stateSubject.pipe( filter((stateWithProvenance) => { const pass = hasAllOffsets(stateWithProvenance.offsets, current.waitFor) if (!pass) { log.pond.debug( semantics, '/', name, ' waiting for', JSON.stringify(current.waitFor), '; currently at:', JSON.stringify(stateWithProvenance.offsets), ) } return pass }), map((sp) => sp.state), take(1), concatMap((s) => { const onCommandResult = command(s) const stored = from(handler(onCommandResult)) return stored.pipe( concatMap((envelopes) => { if (envelopes.length === 0) { return of({ ...current }) } // We only care about events we ourselves are actually subscribed to. const filtered = envelopes.filter(eventFilter) if (filtered.length === 0) { return of({ ...current }) } // We must wait for all of our generated events to be applied to the state, // before we may apply the next command. // The events may be in different streams. const finalOffsets: Record = {} for (const env of envelopes) { // Since envelopes are returned in ascending order, we will // just overwrite the same entry again and again with higher number // in case the events all go into the same stream. finalOffsets[env.stream] = env.offset } return of({ waitFor: finalOffsets }) }), ) }), ) return result.pipe( catchError((x) => { unblock() onError(x) return of(current) }), tap(() => { unblock() onComplete() }), ) } const subscription = commandIn.pipe(mergeScan(cmdScanAcc, { waitFor: {} }, 1)).subscribe() return { subject: commandIn, subscription, } } const getEventsForwardChunked = ( fns: EventFns, subscriptionSet: Where, present: OffsetMap, ): Observable => new Observable((o) => fns.queryKnownRangeChunked( { upperBound: present, query: subscriptionSet, }, 500, (chunk) => o.next(chunk.events), () => o.complete(), ), ) type StartedFish = { fish: Fish startedFrom: ActyxEvent } export type StartedFishMap = Map> const observeAll = (eventStore: EventFns, _pondStateTracker: PondStateTracker) => ( firstEvents: Where, makeFish: (seed: ESeed) => Fish | undefined, expireAfterSeed?: Milliseconds, ): Observable> => { const fish$ = from(eventStore.present()).pipe( concatMap((present) => { const persisted = getEventsForwardChunked(eventStore, firstEvents, present) // This step is only so that we don’t emit outdated collection while receiving chunks of old events const initialFishs: Observable>> = persisted.pipe( reduce((acc: Record>, chunk) => { for (const evt of chunk) { const fish = makeFish(evt.payload as ESeed) if (fish !== undefined) { acc[FishId.canonical(fish.fishId)] = { fish, startedFrom: evt } } } return acc }, {}), ) return initialFishs.pipe( concatMap( observeAllStartWithInitial(eventStore, makeFish, firstEvents, present, expireAfterSeed), ), ) }), ) return fish$ } const earlier = lt(ActyxEvent.ord) const mkPrune = (timeout?: Milliseconds) => { if (!timeout) return (cur: Map>) => cur const timeoutMicros = Milliseconds.toTimestamp(timeout) return (cur: Map>) => { const now = Timestamp.now() return cur.filter((started) => started.startedFrom.meta.timestampMicros + timeoutMicros > now) } } const observeAllStartWithInitial = ( eventStore: EventFns, makeFish: (seed: ESeed) => Fish | undefined, subscriptionSet: Where, present: OffsetMap, expireAfterSeed?: Milliseconds, ) => (init: Record>) => { // Switch to immutable representation so as to not screw over downstream consumers let immutableFishSet = Map(init) const liveEvents = new Observable((o) => eventStore.subscribeChunked( { lowerBound: present, query: subscriptionSet, }, { // Buffer slightly to improve performance maxChunkTimeMs: 20, }, (chunk) => o.next(chunk.events), ), ) const prune = mkPrune(expireAfterSeed) const updates = liveEvents.pipe( concatMap((chunk) => { const oldSize = immutableFishSet.size for (const evt of chunk) { const fish = makeFish(evt.payload as ESeed) if (fish === undefined) { continue } const newEntry = { fish, startedFrom: evt } // Latest writer wins. This is only relevant for expiry -- the Fish ought to be the same, and the Pond will have it cached. immutableFishSet = immutableFishSet.update(FishId.canonical(fish.fishId), (existing) => !existing || earlier(existing.startedFrom, evt) ? newEntry : existing, ) } const newSize = immutableFishSet.size const newFishAppeared = newSize > oldSize immutableFishSet = prune(immutableFishSet) const oldFishPruned = immutableFishSet.size < newSize if (newFishAppeared || oldFishPruned) { return [immutableFishSet] } return [] }), ) return updates.pipe(startWith(Map(init))) } export const FishJar = { commandPipeline, observeAll, }