recorder.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { Effect, Scope, SynchronizedRef } from "effect"
  2. import type * as CassetteService from "./cassette.js"
  3. import type { CassetteNotFoundError } from "./cassette.js"
  4. import type { Interaction } from "./schema.js"
  5. const isCI = () => {
  6. const value = process.env.CI
  7. return value !== undefined && value !== "" && value !== "false" && value !== "0"
  8. }
  9. export const resolveAutoMode = (
  10. cassette: CassetteService.Interface,
  11. name: string,
  12. ): Effect.Effect<"record" | "replay" | "passthrough"> =>
  13. Effect.gen(function* () {
  14. if (isCI()) return "replay"
  15. return (yield* cassette.exists(name)) ? "replay" : "record"
  16. })
  17. export interface ReplayState<T> {
  18. readonly claim: <E>(
  19. validate: (interaction: T | undefined, index: number, interactions: ReadonlyArray<T>) => Effect.Effect<void, E>,
  20. ) => Effect.Effect<{ readonly interaction: T; readonly index: number }, CassetteNotFoundError | E>
  21. }
  22. export const makeReplayState = <T>(
  23. cassette: CassetteService.Interface,
  24. name: string,
  25. project: (interactions: ReadonlyArray<Interaction>) => ReadonlyArray<T>,
  26. ): Effect.Effect<ReplayState<T>, never, Scope.Scope> =>
  27. Effect.gen(function* () {
  28. const load = yield* Effect.cached(cassette.read(name).pipe(Effect.map(project)))
  29. const position = yield* SynchronizedRef.make(0)
  30. yield* Effect.addFinalizer(() =>
  31. Effect.gen(function* () {
  32. const used = yield* SynchronizedRef.get(position)
  33. if (used === 0) return yield* Effect.void
  34. const interactions = yield* load.pipe(Effect.orDie)
  35. if (used < interactions.length)
  36. return yield* Effect.die(
  37. new Error(`Unused recorded interactions in ${name}: used ${used} of ${interactions.length}`),
  38. )
  39. return yield* Effect.void
  40. }),
  41. )
  42. return {
  43. claim: (validate) =>
  44. Effect.flatMap(load, (interactions) =>
  45. SynchronizedRef.modifyEffect(position, (index) =>
  46. Effect.gen(function* () {
  47. const interaction = interactions[index]
  48. yield* validate(interaction, index, interactions)
  49. if (interaction === undefined)
  50. return yield* Effect.die("Replay validation accepted a missing interaction")
  51. return [{ interaction, index }, index + 1] as const
  52. }),
  53. ),
  54. ),
  55. }
  56. })