import { EventKey, LocalSnapshot, Timestamp } from '@actyx/sdk' import { last, partition } from 'fp-ts/lib/Array' import { none, Option, some, map as mapO, getOrElse as getOrElseO, alt as altO, filter as filterO, } from 'fp-ts/lib/Option' import { pipe } from 'fp-ts/lib/function' import { gt } from 'fp-ts/lib/Ord' import log from '../loggers' import { SnapshotScheduler } from './snapshotScheduler' import { CachingReducer, PendingSnapshot, SerializedStateSnap, SimpleReducer } from './types' const eventKeyGreater = gt(EventKey.ord) // Wrap a normal, very simple Reducer into one that caches intermediate states // and schedules persistence as local snapshots. export const cachingReducer = ( simpleReducer: SimpleReducer, snapshotScheduler: SnapshotScheduler, storeSnapshot: (toStore: PendingSnapshot) => Promise, deserializeState: undefined | ((jsonState: unknown) => S), ): CachingReducer => { const deserialize = deserializeState ? (s: string): S => deserializeState(JSON.parse(s)) : (s: string): S => JSON.parse(s) as S const deserializeSnapshot = (snap: SerializedStateSnap): LocalSnapshot => { const snapState = deserialize(snap.state) return { ...snap, state: snapState } } const serialize = (original: LocalSnapshot): SerializedStateSnap => ({ ...original, state: JSON.stringify(original.state), }) const queue = snapshotQueue() // Chain of snapshot storage promises let storeSnapshotsPromise: Promise = Promise.resolve() let toStore: { [tag: string]: PendingSnapshot } | null = null const sendToStore = (snap: PendingSnapshot) => { if (toStore !== null) { toStore[snap.tag] = snap } else { toStore = { [snap.tag]: snap } storeSnapshotsPromise = storeSnapshotsPromise .then(async () => { while (toStore !== null) { for (const tag of Object.keys(toStore)) { const snap = toStore[tag] delete toStore[tag] await storeSnapshot(snap) } if (Object.keys(toStore).length === 0) { toStore = null } } }) .catch(log.pond.warn) } } const snapshotEligible = (latest: Timestamp) => (snapBase: PendingSnapshot) => snapshotScheduler.isEligibleForStorage(snapBase, { timestamp: latest }) let latestStateSerialized: Option = none const appendEvents: CachingReducer['appendEvents'] = (events) => { // FIXME: Arguments are a bit questionable, but we can’t change the scheduler yet, otherwise the FES-based tests start failing. const statesToStore = snapshotScheduler.getSnapshotLevels( pipe( latestStateSerialized, mapO((x) => x.cycle), getOrElseO(() => 0), ), // FIXME: We only put payload in here for chaos.spec.ts hacky custom scheduling events.map((x) => ({ timestamp: x.meta.timestampMicros, payload: x.payload })), 0, ) let fromIdx = 0 for (const toStore of statesToStore) { const headState = simpleReducer.appendEvents(events, fromIdx, toStore.i) fromIdx = toStore.i + 1 queue.addPending({ snap: serialize(headState), tag: toStore.tag, timestamp: events[toStore.i].meta.timestampMicros, }) } const latestState = simpleReducer.appendEvents(events, fromIdx, events.length - 1) const snapshotsToPersist = events.length > 0 ? queue.getSnapshotsToStore( snapshotEligible(events[events.length - 1].meta.timestampMicros), ) : [] for (const snap of snapshotsToPersist) { sendToStore(snap) } // Make another copy so that downstream doesn’t mutate what’s in the SimpleReducer const latestStateSer = serialize(latestState) latestStateSerialized = some(latestStateSer) return deserializeSnapshot(latestStateSer) } const setState = (snap: SerializedStateSnap) => { // Time travel to the past: All newer cached states are invalid queue.invalidateLaterThan(snap.eventKey) latestStateSerialized = some(snap) simpleReducer.setState(deserializeSnapshot(snap)) } return { appendEvents, awaitPendingPersistence: () => storeSnapshotsPromise, latestKnownValidState: (lowestInvalidating) => pipe( latestStateSerialized, filterO(isSnapshotValid(lowestInvalidating)), altO(() => pipe( queue.latestValid(lowestInvalidating), mapO((x) => x.snap), ), ), ), setState, } } const isSnapshotValid = (lowestInvalidating: EventKey) => (snap: SerializedStateSnap): boolean => eventKeyGreater(lowestInvalidating, snap.eventKey) type SnapshotQueue = { // Add a pending snapshot addPending: (snap: PendingSnapshot) => void // Evict all cached states based on events after the cutoff. invalidateLaterThan: (cutOff: EventKey) => void // Pop all snapshots from the queue which should be stored now, according to the given predicate getSnapshotsToStore: ( storeNow: (snapshot: PendingSnapshot) => boolean, ) => ReadonlyArray // Try to find the latest still valid snapshot according to the given arguments. // Only calling this function does not evict anything latestValid: (lowestInvalidating: EventKey) => Option } const snapshotQueue = (): SnapshotQueue => { let queue: PendingSnapshot[] = [] const addPending = (snap: PendingSnapshot) => { queue.push(snap) } const invalidateLaterThan = (cutOff: EventKey) => { queue = queue.filter((entry) => eventKeyGreater(cutOff, entry.snap.eventKey)) } const getSnapshotsToStore = ( storeNow: (snapshot: PendingSnapshot) => boolean, ): ReadonlyArray => { const seperated = partition(storeNow)(queue) queue = seperated.left return seperated.right } const latestValid = (lowestInvalidating: EventKey): Option => { return last(queue.filter(({ snap }) => isSnapshotValid(lowestInvalidating)(snap))) } return { addPending, invalidateLaterThan, latestValid, getSnapshotsToStore, } }