event.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import { Context, Effect, Layer, Option, PubSub, Schema, Stream } from "effect"
  2. import { Location } from "./location"
  3. import { withStatics } from "./schema"
  4. import { Identifier } from "./util/identifier"
  5. export const ID = Schema.String.pipe(
  6. Schema.brand("Event.ID"),
  7. withStatics((schema) => ({ create: () => schema.make("evt_" + Identifier.ascending()) })),
  8. )
  9. export type ID = typeof ID.Type
  10. export type Definition<Type extends string = string, DataSchema extends Schema.Top = Schema.Top> = {
  11. readonly type: Type
  12. readonly version?: number
  13. readonly aggregate?: string
  14. readonly data: DataSchema
  15. }
  16. export type Data<D extends Definition> = Schema.Schema.Type<D["data"]>
  17. export type Payload<D extends Definition = Definition> = {
  18. readonly id: ID
  19. readonly type: D["type"]
  20. readonly data: Data<D>
  21. readonly version?: number
  22. readonly location?: Location.Ref
  23. readonly metadata?: Record<string, unknown>
  24. }
  25. export type Sync = (event: Payload) => Effect.Effect<void>
  26. export const registry = new Map<string, Definition>()
  27. export function define<const Type extends string, Fields extends Schema.Struct.Fields>(input: {
  28. readonly type: Type
  29. readonly version?: number
  30. readonly aggregate?: string
  31. readonly schema: Fields
  32. }): Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> & Definition<Type, Schema.Struct<Fields>> {
  33. const Data = Schema.Struct(input.schema)
  34. const Payload = Schema.Struct({
  35. id: ID,
  36. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  37. type: Schema.Literal(input.type),
  38. version: Schema.optional(Schema.Number),
  39. location: Schema.optional(Location.Ref),
  40. data: Data,
  41. }).annotate({ identifier: input.type })
  42. const definition = Object.assign(Payload, {
  43. type: input.type,
  44. ...(input.version === undefined ? {} : { version: input.version }),
  45. ...(input.aggregate === undefined ? {} : { aggregate: input.aggregate }),
  46. data: Data,
  47. })
  48. registry.set(input.type, definition)
  49. return definition as Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> &
  50. Definition<Type, Schema.Struct<Fields>>
  51. }
  52. export function definitions() {
  53. return registry.values().toArray()
  54. }
  55. export interface PublishOptions {
  56. readonly id?: ID
  57. readonly metadata?: Record<string, unknown>
  58. }
  59. export type Unsubscribe = Effect.Effect<void>
  60. export interface Interface {
  61. readonly publish: <D extends Definition>(
  62. definition: D,
  63. data: Data<D>,
  64. options?: PublishOptions,
  65. ) => Effect.Effect<Payload<D>>
  66. readonly publishEvent: <D extends Definition>(event: Payload<D>) => Effect.Effect<Payload<D>>
  67. readonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>>
  68. readonly all: () => Stream.Stream<Payload>
  69. readonly sync: (handler: Sync) => Effect.Effect<Unsubscribe>
  70. }
  71. export class Service extends Context.Service<Service, Interface>()("@opencode/Event") {}
  72. export const layer = Layer.effect(
  73. Service,
  74. Effect.gen(function* () {
  75. const all = yield* PubSub.unbounded<Payload>()
  76. const typed = new Map<string, PubSub.PubSub<Payload>>()
  77. const syncHandlers = new Array<Sync>()
  78. const getOrCreate = (definition: Definition) =>
  79. Effect.gen(function* () {
  80. const existing = typed.get(definition.type)
  81. if (existing) return existing
  82. const pubsub = yield* PubSub.unbounded<Payload>()
  83. typed.set(definition.type, pubsub)
  84. return pubsub
  85. })
  86. yield* Effect.addFinalizer(() =>
  87. Effect.gen(function* () {
  88. yield* PubSub.shutdown(all)
  89. yield* Effect.forEach(typed.values(), PubSub.shutdown, { discard: true })
  90. }),
  91. )
  92. function publishEvent<D extends Definition>(event: Payload<D>) {
  93. return Effect.gen(function* () {
  94. for (const sync of syncHandlers) {
  95. yield* sync(event as Payload)
  96. }
  97. const pubsub = typed.get(event.type)
  98. if (pubsub) yield* PubSub.publish(pubsub, event as Payload)
  99. yield* PubSub.publish(all, event as Payload)
  100. return event
  101. })
  102. }
  103. function publish<D extends Definition>(definition: D, data: Data<D>, options?: PublishOptions) {
  104. return Effect.gen(function* () {
  105. const location = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
  106. const event = {
  107. id: options?.id ?? ID.create(),
  108. ...(options?.metadata ? { metadata: options.metadata } : {}),
  109. type: definition.type,
  110. ...(definition.version === undefined ? {} : { version: definition.version }),
  111. ...(location ? { location } : {}),
  112. data,
  113. } as Payload<D>
  114. return yield* publishEvent(event)
  115. })
  116. }
  117. const subscribe = <D extends Definition>(definition: D): Stream.Stream<Payload<D>> =>
  118. Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe(
  119. Stream.map((event) => event as Payload<D>),
  120. )
  121. const streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(all)
  122. const sync = (handler: Sync): Effect.Effect<Unsubscribe> =>
  123. Effect.sync(() => {
  124. syncHandlers.push(handler)
  125. return Effect.sync(() => {
  126. const index = syncHandlers.indexOf(handler)
  127. if (index >= 0) syncHandlers.splice(index, 1)
  128. })
  129. })
  130. return Service.of({ publish, publishEvent, subscribe, all: streamAll, sync })
  131. }),
  132. )
  133. export const defaultLayer = layer
  134. export * as EventV2 from "./event"