event.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. export * as EventV2 from "./event"
  2. import { Cause, Context, Effect, Layer, Option, PubSub, Schema, Stream } from "effect"
  3. import { and, asc, eq, gt } from "drizzle-orm"
  4. import { Database } from "./database/database"
  5. import { EventSequenceTable, EventTable } from "./event/sql"
  6. import { Location } from "./location"
  7. import { externalID, type ExternalID, NonNegativeInt, withStatics } from "./schema"
  8. import { Identifier } from "./util/identifier"
  9. import { LayerNode } from "./effect/layer-node"
  10. import { isDeepStrictEqual } from "node:util"
  11. export const ID = Schema.String.check(Schema.isStartsWith("evt_")).pipe(
  12. Schema.brand("Event.ID"),
  13. withStatics((schema) => ({
  14. create: () => schema.make("evt_" + Identifier.ascending()),
  15. fromExternal: (input: ExternalID) => schema.make(externalID("evt", input)),
  16. })),
  17. )
  18. export type ID = typeof ID.Type
  19. /**
  20. * Durable aggregate continuation position for embedded replay streams.
  21. * TODO: Decide whether a future HTTP / SDK surface should expose an opaque cursor instead.
  22. */
  23. export const Cursor = NonNegativeInt.pipe(Schema.brand("EventV2.Cursor"))
  24. export type Cursor = typeof Cursor.Type
  25. export type Definition<Type extends string = string, DataSchema extends Schema.Top = Schema.Top> = {
  26. readonly type: Type
  27. readonly sync?: {
  28. readonly version: number
  29. readonly aggregate: string
  30. }
  31. readonly data: DataSchema
  32. }
  33. export type Data<D extends Definition> = Schema.Schema.Type<D["data"]>
  34. export type Payload<D extends Definition = Definition> = {
  35. readonly id: ID
  36. readonly type: D["type"]
  37. readonly data: Data<D>
  38. /** Durable aggregate order, populated while synchronized events are projected. */
  39. readonly seq?: number
  40. readonly version?: number
  41. readonly location?: Location.Ref
  42. readonly metadata?: Record<string, unknown>
  43. /** Internal replay marker for projectors that own non-replicated operational state. */
  44. readonly replay?: boolean
  45. }
  46. export type Projector<D extends Definition = Definition> = (event: Payload<D>) => Effect.Effect<void>
  47. type AnyProjector = (event: Payload) => Effect.Effect<void>
  48. export type CommitGuard = (event: Payload) => Effect.Effect<void>
  49. export type Listener = (event: Payload) => Effect.Effect<void>
  50. export type Sync = (event: Payload) => Effect.Effect<void>
  51. export type Unsubscribe = Effect.Effect<void>
  52. export type SerializedEvent = {
  53. readonly id: ID
  54. readonly type: string
  55. readonly seq: number
  56. readonly aggregateID: string
  57. readonly data: Record<string, unknown>
  58. }
  59. export type CursorEvent<E extends Payload = Payload> = {
  60. readonly cursor: Cursor
  61. readonly event: E
  62. }
  63. export class InvalidSyncEventError extends Schema.TaggedErrorClass<InvalidSyncEventError>()(
  64. "EventV2.InvalidSyncEvent",
  65. {
  66. type: Schema.String,
  67. message: Schema.String,
  68. },
  69. ) {}
  70. export function versionedType(type: string, version: number) {
  71. return `${type}.${version}`
  72. }
  73. export const registry = new Map<string, Definition>()
  74. type SyncDefinition = Definition & {
  75. readonly sync: NonNullable<Definition["sync"]>
  76. readonly encode: (data: unknown) => unknown
  77. readonly decode: (data: unknown) => unknown
  78. }
  79. const syncRegistry = new Map<string, SyncDefinition>()
  80. // Synchronized events cross a JSON boundary, so their data schemas must encode and decode without services.
  81. const syncCodec = (definition: Definition) => definition.data as Schema.Codec<unknown, unknown, never, never>
  82. export function define<const Type extends string, Fields extends Schema.Struct.Fields>(input: {
  83. readonly type: Type
  84. readonly sync?: {
  85. readonly version: number
  86. readonly aggregate: string
  87. }
  88. readonly schema: Fields
  89. }): Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> & Definition<Type, Schema.Struct<Fields>> {
  90. const Data = Schema.Struct(input.schema)
  91. const Payload = Schema.Struct({
  92. id: ID,
  93. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  94. type: Schema.Literal(input.type),
  95. version: Schema.optional(Schema.Number),
  96. location: Schema.optional(Location.Ref),
  97. data: Data,
  98. }).annotate({ identifier: input.type })
  99. const definition = Object.assign(Payload, {
  100. type: input.type,
  101. ...(input.sync === undefined ? {} : { sync: input.sync }),
  102. data: Data,
  103. })
  104. const existing = registry.get(input.type)
  105. if (input.sync === undefined || existing?.sync === undefined || input.sync.version >= existing.sync.version) {
  106. registry.set(input.type, definition)
  107. }
  108. if (input.sync)
  109. syncRegistry.set(
  110. versionedType(input.type, input.sync.version),
  111. Object.assign(definition, {
  112. encode: Schema.encodeUnknownSync(syncCodec(definition)),
  113. decode: Schema.decodeUnknownSync(syncCodec(definition)),
  114. }) as SyncDefinition,
  115. )
  116. return definition as Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> &
  117. Definition<Type, Schema.Struct<Fields>>
  118. }
  119. export function definitions() {
  120. return registry.values().toArray()
  121. }
  122. export interface PublishOptions {
  123. readonly id?: ID
  124. readonly metadata?: Record<string, unknown>
  125. readonly location?: Location.Ref
  126. /** Local operational projection committed atomically with a new synchronized event. Not replayed or serialized. */
  127. readonly commit?: (seq: number) => Effect.Effect<void>
  128. }
  129. export interface Interface {
  130. readonly publish: <D extends Definition>(
  131. definition: D,
  132. data: Data<D>,
  133. options?: PublishOptions,
  134. ) => Effect.Effect<Payload<D>>
  135. readonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>>
  136. readonly all: () => Stream.Stream<Payload>
  137. readonly aggregateEvents: (input: {
  138. readonly aggregateID: string
  139. readonly after?: Cursor
  140. }) => Stream.Stream<CursorEvent>
  141. readonly sync: (handler: Sync) => Effect.Effect<Unsubscribe>
  142. readonly listen: (listener: Listener) => Effect.Effect<Unsubscribe>
  143. readonly beforeCommit: (guard: CommitGuard) => Effect.Effect<void>
  144. readonly project: <D extends Definition>(definition: D, projector: Projector<D>) => Effect.Effect<void>
  145. readonly replay: (
  146. event: SerializedEvent,
  147. options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
  148. ) => Effect.Effect<void>
  149. readonly replayAll: (
  150. events: SerializedEvent[],
  151. options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
  152. ) => Effect.Effect<string | undefined>
  153. readonly remove: (aggregateID: string) => Effect.Effect<void>
  154. readonly claim: (aggregateID: string, ownerID: string) => Effect.Effect<void>
  155. }
  156. export class Service extends Context.Service<Service, Interface>()("@opencode/Event") {}
  157. export interface LayerOptions {
  158. readonly beforeAggregateRead?: (aggregateID: string) => Effect.Effect<void>
  159. }
  160. export const layerWith = (options?: LayerOptions) =>
  161. Layer.effect(
  162. Service,
  163. Effect.gen(function* () {
  164. const all = yield* PubSub.unbounded<Payload>()
  165. const synchronized = new Map<string, Set<PubSub.PubSub<void>>>()
  166. const typed = new Map<string, PubSub.PubSub<Payload>>()
  167. const projectors = new Map<string, AnyProjector[]>()
  168. const commitGuards = new Array<CommitGuard>()
  169. const listeners = new Array<Listener>()
  170. const syncHandlers = new Array<Sync>()
  171. const { db } = yield* Database.Service
  172. const getOrCreate = (definition: Definition) =>
  173. Effect.gen(function* () {
  174. const existing = typed.get(definition.type)
  175. if (existing) return existing
  176. const pubsub = yield* PubSub.unbounded<Payload>()
  177. typed.set(definition.type, pubsub)
  178. return pubsub
  179. })
  180. yield* Effect.addFinalizer(() =>
  181. Effect.gen(function* () {
  182. yield* PubSub.shutdown(all)
  183. yield* Effect.forEach(
  184. synchronized.values(),
  185. (pubsubs) => Effect.forEach(pubsubs, PubSub.shutdown, { discard: true }),
  186. { discard: true },
  187. )
  188. yield* Effect.forEach(typed.values(), PubSub.shutdown, { discard: true })
  189. }),
  190. )
  191. function commitSyncEvent(
  192. event: Payload,
  193. input?: {
  194. readonly seq: number
  195. readonly aggregateID: string
  196. readonly ownerID?: string
  197. readonly strictOwner?: boolean
  198. },
  199. commit?: (seq: number) => Effect.Effect<void>,
  200. ) {
  201. return Effect.gen(function* () {
  202. const definition = registry.get(event.type)
  203. const sync = definition?.sync
  204. if (sync) {
  205. if (event.version !== sync.version) {
  206. yield* Effect.die(
  207. new InvalidSyncEventError({
  208. type: event.type,
  209. message: `Expected event version ${sync.version}, got ${event.version}`,
  210. }),
  211. )
  212. }
  213. const aggregateID = (event.data as Record<string, unknown>)[sync.aggregate]
  214. if (typeof aggregateID !== "string") {
  215. yield* Effect.die(
  216. new InvalidSyncEventError({
  217. type: event.type,
  218. message: `Expected string aggregate field ${sync.aggregate}`,
  219. }),
  220. )
  221. } else {
  222. if (input && input.aggregateID !== aggregateID) {
  223. yield* Effect.die(
  224. new InvalidSyncEventError({
  225. type: event.type,
  226. message: `Aggregate mismatch: expected ${input.aggregateID}, got ${aggregateID}`,
  227. }),
  228. )
  229. }
  230. const list = projectors.get(event.type) ?? []
  231. return yield* Effect.uninterruptible(
  232. Effect.gen(function* () {
  233. const committed = yield* db
  234. .transaction(
  235. () =>
  236. Effect.gen(function* () {
  237. const row = yield* db
  238. .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id })
  239. .from(EventSequenceTable)
  240. .where(eq(EventSequenceTable.aggregate_id, aggregateID))
  241. .get()
  242. .pipe(Effect.orDie)
  243. const latest = row?.seq ?? -1
  244. const encoded = syncRegistry
  245. .get(versionedType(definition.type, sync.version))!
  246. .encode(event.data) as Record<string, unknown>
  247. if (input?.strictOwner && row?.ownerID && row.ownerID !== input.ownerID) {
  248. yield* Effect.die(
  249. new InvalidSyncEventError({
  250. type: event.type,
  251. message: `Replay owner mismatch for aggregate ${aggregateID}: expected ${row.ownerID}, got ${input.ownerID ?? "none"}`,
  252. }),
  253. )
  254. }
  255. if (input && input.seq <= latest) {
  256. const stored = yield* db
  257. .select()
  258. .from(EventTable)
  259. .where(and(eq(EventTable.aggregate_id, aggregateID), eq(EventTable.seq, input.seq)))
  260. .get()
  261. .pipe(Effect.orDie)
  262. if (
  263. stored?.id === event.id &&
  264. stored.type === versionedType(definition.type, sync.version) &&
  265. isDeepStrictEqual(stored.data, encoded)
  266. ) {
  267. if (input.ownerID && row?.ownerID == null) {
  268. yield* db
  269. .update(EventSequenceTable)
  270. .set({ owner_id: input.ownerID })
  271. .where(eq(EventSequenceTable.aggregate_id, aggregateID))
  272. .run()
  273. .pipe(Effect.orDie)
  274. }
  275. return
  276. }
  277. yield* Effect.die(
  278. new InvalidSyncEventError({
  279. type: event.type,
  280. message: `Replay diverged at aggregate ${aggregateID} sequence ${input.seq}`,
  281. }),
  282. )
  283. }
  284. if (input && row?.ownerID && row.ownerID !== input.ownerID) {
  285. return
  286. }
  287. const seq = input?.seq ?? latest + 1
  288. if (input && seq !== latest + 1) {
  289. yield* Effect.die(
  290. new InvalidSyncEventError({
  291. type: event.type,
  292. message: `Sequence mismatch for aggregate ${aggregateID}: expected ${latest + 1}, got ${seq}`,
  293. }),
  294. )
  295. }
  296. const stored = yield* db
  297. .select({ aggregateID: EventTable.aggregate_id, seq: EventTable.seq })
  298. .from(EventTable)
  299. .where(eq(EventTable.id, event.id))
  300. .get()
  301. .pipe(Effect.orDie)
  302. if (stored)
  303. yield* Effect.die(
  304. new InvalidSyncEventError({
  305. type: event.type,
  306. message: `Event ${event.id} already exists at aggregate ${stored.aggregateID} sequence ${stored.seq}`,
  307. }),
  308. )
  309. for (const guard of commitGuards) {
  310. yield* guard(event)
  311. }
  312. for (const projector of list) {
  313. yield* projector({ ...event, seq } as Payload)
  314. }
  315. if (commit) yield* commit(seq)
  316. yield* db
  317. .insert(EventSequenceTable)
  318. .values([{ aggregate_id: aggregateID, seq, owner_id: input?.ownerID }])
  319. .onConflictDoUpdate({
  320. target: EventSequenceTable.aggregate_id,
  321. set: {
  322. seq,
  323. ...(input?.ownerID && row?.ownerID == null ? { owner_id: input.ownerID } : {}),
  324. },
  325. })
  326. .run()
  327. .pipe(Effect.orDie)
  328. yield* db
  329. .insert(EventTable)
  330. .values([
  331. {
  332. id: event.id,
  333. aggregate_id: aggregateID,
  334. seq,
  335. type: versionedType(definition.type, sync.version),
  336. data: encoded,
  337. },
  338. ])
  339. .run()
  340. .pipe(Effect.orDie)
  341. return { aggregateID, seq }
  342. }),
  343. { behavior: "immediate" },
  344. )
  345. .pipe(Effect.orDie)
  346. if (committed) {
  347. yield* Effect.forEach(
  348. synchronized.get(committed.aggregateID) ?? [],
  349. (pubsub) => PubSub.publish(pubsub, undefined),
  350. { discard: true },
  351. )
  352. }
  353. return committed
  354. }),
  355. )
  356. }
  357. }
  358. })
  359. }
  360. function publishEvent<D extends Definition>(event: Payload<D>, commit?: PublishOptions["commit"]) {
  361. return Effect.gen(function* () {
  362. const durable = registry.get(event.type)?.sync !== undefined
  363. if (!durable && commit)
  364. return yield* Effect.die(
  365. new InvalidSyncEventError({
  366. type: event.type,
  367. message: "Local commit hooks require a synchronized event",
  368. }),
  369. )
  370. if (durable) {
  371. const committed = yield* commitSyncEvent(event as Payload, undefined, commit)
  372. if (committed) {
  373. event = { ...event, seq: committed.seq }
  374. yield* Effect.forEach(syncHandlers, (sync) => observe(event as Payload, "sync", sync), { discard: true })
  375. yield* notify(event as Payload, true)
  376. return event
  377. }
  378. }
  379. yield* notify(event as Payload, false)
  380. return event
  381. })
  382. }
  383. const observe = (event: Payload, kind: "sync" | "listener", observer: (event: Payload) => Effect.Effect<void>) =>
  384. Effect.suspend(() => observer(event)).pipe(
  385. Effect.catchCauseIf(
  386. (cause) => !Cause.hasInterrupts(cause),
  387. (cause) =>
  388. Effect.logError("Event observer failed", { eventID: event.id, eventType: event.type, kind, cause }),
  389. ),
  390. )
  391. function notify(event: Payload, isolateListeners: boolean) {
  392. return Effect.gen(function* () {
  393. yield* Effect.forEach(
  394. listeners,
  395. (listener) => (isolateListeners ? observe(event, "listener", listener) : listener(event)),
  396. { discard: true },
  397. )
  398. const pubsub = typed.get(event.type)
  399. if (pubsub) yield* PubSub.publish(pubsub, event)
  400. yield* PubSub.publish(all, event)
  401. })
  402. }
  403. function publish<D extends Definition>(definition: D, data: Data<D>, options?: PublishOptions) {
  404. return Effect.gen(function* () {
  405. const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
  406. const location =
  407. options?.location ??
  408. (serviceLocation
  409. ? { directory: serviceLocation.directory, workspaceID: serviceLocation.workspaceID }
  410. : undefined)
  411. return yield* publishEvent(
  412. {
  413. id: options?.id ?? ID.create(),
  414. ...(options?.metadata ? { metadata: options.metadata } : {}),
  415. type: definition.type,
  416. ...(definition.sync === undefined ? {} : { version: definition.sync.version }),
  417. ...(location ? { location } : {}),
  418. data,
  419. } as Payload<D>,
  420. options?.commit,
  421. )
  422. })
  423. }
  424. function replay(
  425. event: SerializedEvent,
  426. options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
  427. ) {
  428. return Effect.gen(function* () {
  429. const definition = syncRegistry.get(event.type)
  430. if (!definition) {
  431. yield* Effect.die(
  432. new InvalidSyncEventError({ type: event.type, message: `Unknown sync event type ${event.type}` }),
  433. )
  434. } else {
  435. const payload = {
  436. id: event.id,
  437. type: definition.type,
  438. version: definition.sync.version,
  439. data: definition.decode(event.data),
  440. replay: true,
  441. } as Payload
  442. const committed = yield* commitSyncEvent(payload, {
  443. seq: event.seq,
  444. aggregateID: event.aggregateID,
  445. ownerID: options?.ownerID,
  446. strictOwner: options?.strictOwner,
  447. })
  448. if (committed && options?.publish) {
  449. yield* notify({ ...payload, seq: committed.seq }, true)
  450. }
  451. }
  452. })
  453. }
  454. function replayAll(
  455. events: SerializedEvent[],
  456. options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
  457. ) {
  458. return Effect.gen(function* () {
  459. const source = events[0]?.aggregateID
  460. if (!source) return undefined
  461. if (events.some((event) => event.aggregateID !== source)) {
  462. yield* Effect.die(
  463. new InvalidSyncEventError({
  464. type: events[0]?.type ?? "unknown",
  465. message: "Replay events must belong to the same aggregate",
  466. }),
  467. )
  468. }
  469. const start = events[0]?.seq ?? 0
  470. for (const [index, event] of events.entries()) {
  471. const seq = start + index
  472. if (event.seq !== seq) {
  473. yield* Effect.die(
  474. new InvalidSyncEventError({
  475. type: event.type,
  476. message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`,
  477. }),
  478. )
  479. }
  480. }
  481. for (const event of events) {
  482. yield* replay(event, options)
  483. }
  484. return source
  485. })
  486. }
  487. function remove(aggregateID: string) {
  488. return db
  489. .transaction(() =>
  490. Effect.gen(function* () {
  491. yield* db.delete(EventSequenceTable).where(eq(EventSequenceTable.aggregate_id, aggregateID)).run()
  492. yield* db.delete(EventTable).where(eq(EventTable.aggregate_id, aggregateID)).run()
  493. }),
  494. )
  495. .pipe(Effect.orDie)
  496. }
  497. function claim(aggregateID: string, ownerID: string) {
  498. return db
  499. .update(EventSequenceTable)
  500. .set({ owner_id: ownerID })
  501. .where(eq(EventSequenceTable.aggregate_id, aggregateID))
  502. .run()
  503. .pipe(Effect.orDie)
  504. }
  505. const subscribe = <D extends Definition>(definition: D): Stream.Stream<Payload<D>> =>
  506. Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe(
  507. Stream.map((event) => event as Payload<D>),
  508. )
  509. const streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(all)
  510. const decodeSerializedEvent = (event: SerializedEvent): CursorEvent => {
  511. const definition = syncRegistry.get(event.type)
  512. if (!definition) {
  513. throw new InvalidSyncEventError({ type: event.type, message: `Unknown sync event type ${event.type}` })
  514. }
  515. return {
  516. cursor: Cursor.make(event.seq),
  517. event: {
  518. id: event.id,
  519. type: definition.type,
  520. version: definition.sync.version,
  521. seq: event.seq,
  522. data: definition.decode(event.data),
  523. },
  524. }
  525. }
  526. const readAfter = (aggregateID: string, after: number) =>
  527. (options?.beforeAggregateRead?.(aggregateID) ?? Effect.void).pipe(
  528. Effect.andThen(
  529. db
  530. .select()
  531. .from(EventTable)
  532. .where(and(eq(EventTable.aggregate_id, aggregateID), gt(EventTable.seq, after)))
  533. .orderBy(asc(EventTable.seq))
  534. .all(),
  535. ),
  536. Effect.orDie,
  537. Effect.map((rows) =>
  538. rows.map((event) =>
  539. decodeSerializedEvent({
  540. id: event.id,
  541. aggregateID: event.aggregate_id,
  542. seq: event.seq,
  543. type: event.type,
  544. data: event.data,
  545. }),
  546. ),
  547. ),
  548. )
  549. const subscribeSynchronized = (aggregateID: string) =>
  550. Effect.gen(function* () {
  551. const pubsub = yield* PubSub.sliding<void>(1)
  552. const subscription = yield* PubSub.subscribe(pubsub)
  553. yield* Effect.acquireRelease(
  554. Effect.sync(() => {
  555. const pubsubs = synchronized.get(aggregateID) ?? new Set()
  556. pubsubs.add(pubsub)
  557. synchronized.set(aggregateID, pubsubs)
  558. }),
  559. () =>
  560. Effect.sync(() => {
  561. const pubsubs = synchronized.get(aggregateID)
  562. pubsubs?.delete(pubsub)
  563. if (pubsubs?.size === 0) synchronized.delete(aggregateID)
  564. }).pipe(Effect.andThen(PubSub.shutdown(pubsub))),
  565. )
  566. return subscription
  567. })
  568. const streamEvents = (input: {
  569. readonly aggregateID: string
  570. readonly after?: Cursor
  571. }): Stream.Stream<CursorEvent> =>
  572. Stream.unwrap(
  573. Effect.gen(function* () {
  574. const synchronized = yield* subscribeSynchronized(input.aggregateID)
  575. let cursor = input.after ?? -1
  576. const read = Effect.suspend(() => readAfter(input.aggregateID, cursor)).pipe(
  577. Effect.tap((events) =>
  578. Effect.sync(() => {
  579. cursor = events.at(-1)?.cursor ?? cursor
  580. }),
  581. ),
  582. )
  583. const historical = yield* read
  584. const live = Stream.fromSubscription(synchronized).pipe(
  585. Stream.mapEffect(() => read),
  586. Stream.flattenIterable,
  587. )
  588. return Stream.concat(Stream.fromIterable(historical), live)
  589. }),
  590. )
  591. const listen = (listener: Listener): Effect.Effect<Unsubscribe> =>
  592. Effect.sync(() => {
  593. listeners.push(listener)
  594. return Effect.sync(() => {
  595. const index = listeners.indexOf(listener)
  596. if (index >= 0) listeners.splice(index, 1)
  597. })
  598. })
  599. const sync = (handler: Sync): Effect.Effect<Unsubscribe> =>
  600. Effect.sync(() => {
  601. syncHandlers.push(handler)
  602. return Effect.sync(() => {
  603. const index = syncHandlers.indexOf(handler)
  604. if (index >= 0) syncHandlers.splice(index, 1)
  605. })
  606. })
  607. const beforeCommit = (guard: CommitGuard): Effect.Effect<void> =>
  608. Effect.sync(() => {
  609. commitGuards.push(guard)
  610. })
  611. const project = <D extends Definition>(definition: D, projector: Projector<D>): Effect.Effect<void> =>
  612. Effect.sync(() => {
  613. const list = projectors.get(definition.type) ?? []
  614. list.push((event) => projector(event as Payload<D>))
  615. projectors.set(definition.type, list)
  616. })
  617. return Service.of({
  618. publish,
  619. subscribe,
  620. all: streamAll,
  621. aggregateEvents: streamEvents,
  622. sync,
  623. listen,
  624. beforeCommit,
  625. project,
  626. replay,
  627. replayAll,
  628. remove,
  629. claim,
  630. })
  631. }),
  632. )
  633. export const layer = layerWith()
  634. export const node = LayerNode.make(layer, [Database.node])
  635. export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer))