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