215 lines
7.7 KiB
TypeScript
215 lines
7.7 KiB
TypeScript
import { Effect, Exit, Layer, PubSub, Scope, Context, Stream, Schema } from "effect"
|
|
import { EffectBridge } from "@/effect/bridge"
|
|
import * as Log from "@opencode-ai/core/util/log"
|
|
import { BusEvent } from "./bus-event"
|
|
import { GlobalBus } from "./global"
|
|
import { InstanceState } from "@/effect/instance-state"
|
|
import { makeRuntime } from "@/effect/run-service"
|
|
import { Identifier } from "@/id/id"
|
|
import type { InstanceContext } from "@/project/instance-context"
|
|
import { InstanceRef } from "@/effect/instance-ref"
|
|
|
|
const log = Log.create({ service: "bus" })
|
|
|
|
type BusProperties<D extends BusEvent.Definition<string, Schema.Top>> = Schema.Schema.Type<D["properties"]>
|
|
|
|
export const InstanceDisposed = BusEvent.define(
|
|
"server.instance.disposed",
|
|
Schema.Struct({
|
|
directory: Schema.String,
|
|
}),
|
|
)
|
|
|
|
type Payload<D extends BusEvent.Definition = BusEvent.Definition> = {
|
|
id: string
|
|
type: D["type"]
|
|
properties: BusProperties<D>
|
|
}
|
|
|
|
type State = {
|
|
wildcard: PubSub.PubSub<Payload>
|
|
typed: Map<string, PubSub.PubSub<Payload>>
|
|
}
|
|
|
|
export interface Interface {
|
|
readonly publish: <D extends BusEvent.Definition>(
|
|
def: D,
|
|
properties: BusProperties<D>,
|
|
options?: { id?: string },
|
|
) => Effect.Effect<void>
|
|
// subscribe / subscribeAll are eager: the underlying PubSub subscription is
|
|
// acquired in the caller's Scope at `yield*` time. Any publish after the
|
|
// yield is delivered, even if stream consumption starts later. The previous
|
|
// Stream-returning shape acquired the subscription lazily on first pull,
|
|
// opening a race window during which publishes were lost — see
|
|
// test/bus/bus-effect.test.ts RACE tests.
|
|
readonly subscribe: <D extends BusEvent.Definition>(
|
|
def: D,
|
|
) => Effect.Effect<Stream.Stream<Payload<D>>, never, Scope.Scope>
|
|
readonly subscribeAll: () => Effect.Effect<Stream.Stream<Payload>, never, Scope.Scope>
|
|
readonly subscribeCallback: <D extends BusEvent.Definition>(
|
|
def: D,
|
|
callback: (event: Payload<D>) => unknown,
|
|
) => Effect.Effect<() => void>
|
|
readonly subscribeAllCallback: (callback: (event: any) => unknown) => Effect.Effect<() => void>
|
|
}
|
|
|
|
export class Service extends Context.Service<Service, Interface>()("@opencode/Bus") {}
|
|
|
|
export const layer = Layer.effect(
|
|
Service,
|
|
Effect.gen(function* () {
|
|
const state = yield* InstanceState.make<State>(
|
|
Effect.fn("Bus.state")(function* (ctx) {
|
|
const wildcard = yield* PubSub.unbounded<Payload>()
|
|
const typed = new Map<string, PubSub.PubSub<Payload>>()
|
|
|
|
yield* Effect.addFinalizer(() =>
|
|
Effect.gen(function* () {
|
|
// Publish InstanceDisposed before shutting down so subscribers see it
|
|
yield* PubSub.publish(wildcard, {
|
|
type: InstanceDisposed.type,
|
|
id: createID(),
|
|
properties: { directory: ctx.directory },
|
|
})
|
|
yield* PubSub.shutdown(wildcard)
|
|
for (const ps of typed.values()) {
|
|
yield* PubSub.shutdown(ps)
|
|
}
|
|
}),
|
|
)
|
|
|
|
return { wildcard, typed }
|
|
}),
|
|
)
|
|
|
|
function getOrCreate<D extends BusEvent.Definition>(state: State, def: D) {
|
|
return Effect.gen(function* () {
|
|
let ps = state.typed.get(def.type)
|
|
if (!ps) {
|
|
ps = yield* PubSub.unbounded<Payload>()
|
|
state.typed.set(def.type, ps)
|
|
}
|
|
return ps as unknown as PubSub.PubSub<Payload<D>>
|
|
})
|
|
}
|
|
|
|
function publish<D extends BusEvent.Definition>(def: D, properties: BusProperties<D>, options?: { id?: string }) {
|
|
return Effect.gen(function* () {
|
|
const s = yield* InstanceState.get(state)
|
|
const payload: Payload = { id: options?.id ?? createID(), type: def.type, properties }
|
|
log.info("publishing", { type: def.type })
|
|
|
|
const ps = s.typed.get(def.type)
|
|
if (ps) yield* PubSub.publish(ps, payload)
|
|
yield* PubSub.publish(s.wildcard, payload)
|
|
|
|
const dir = yield* InstanceState.directory
|
|
const context = yield* InstanceState.context
|
|
const workspace = yield* InstanceState.workspaceID
|
|
|
|
GlobalBus.emit("event", {
|
|
directory: dir,
|
|
project: context.project.id,
|
|
workspace,
|
|
payload,
|
|
})
|
|
})
|
|
}
|
|
|
|
const subscribe = <D extends BusEvent.Definition>(
|
|
def: D,
|
|
): Effect.Effect<Stream.Stream<Payload<D>>, never, Scope.Scope> =>
|
|
Effect.gen(function* () {
|
|
log.info("subscribing", { type: def.type })
|
|
const s = yield* InstanceState.get(state)
|
|
const ps = yield* getOrCreate(s, def)
|
|
const subscription = yield* PubSub.subscribe(ps)
|
|
yield* Effect.addFinalizer(() => Effect.sync(() => log.info("unsubscribing", { type: def.type })))
|
|
return Stream.fromSubscription(subscription)
|
|
})
|
|
|
|
const subscribeAll = (): Effect.Effect<Stream.Stream<Payload>, never, Scope.Scope> =>
|
|
Effect.gen(function* () {
|
|
log.info("subscribing", { type: "*" })
|
|
const s = yield* InstanceState.get(state)
|
|
const subscription = yield* PubSub.subscribe(s.wildcard)
|
|
yield* Effect.addFinalizer(() => Effect.sync(() => log.info("unsubscribing", { type: "*" })))
|
|
return Stream.fromSubscription(subscription)
|
|
})
|
|
|
|
function on<T>(pubsub: PubSub.PubSub<T>, type: string, callback: (event: T) => unknown) {
|
|
return Effect.gen(function* () {
|
|
log.info("subscribing", { type })
|
|
const bridge = yield* EffectBridge.make()
|
|
const scope = yield* Scope.make()
|
|
const subscription = yield* Scope.provide(scope)(PubSub.subscribe(pubsub))
|
|
|
|
yield* Scope.provide(scope)(
|
|
Stream.fromSubscription(subscription).pipe(
|
|
Stream.runForEach((msg) =>
|
|
Effect.tryPromise({
|
|
try: () => Promise.resolve().then(() => callback(msg)),
|
|
catch: (cause) => {
|
|
log.error("subscriber failed", { type, cause })
|
|
},
|
|
}).pipe(Effect.ignore),
|
|
),
|
|
Effect.forkScoped,
|
|
),
|
|
)
|
|
|
|
return () => {
|
|
log.info("unsubscribing", { type })
|
|
bridge.fork(Scope.close(scope, Exit.void))
|
|
}
|
|
})
|
|
}
|
|
|
|
const subscribeCallback = Effect.fn("Bus.subscribeCallback")(function* <D extends BusEvent.Definition>(
|
|
def: D,
|
|
callback: (event: Payload<D>) => unknown,
|
|
) {
|
|
const s = yield* InstanceState.get(state)
|
|
const ps = yield* getOrCreate(s, def)
|
|
return yield* on(ps, def.type, callback)
|
|
})
|
|
|
|
const subscribeAllCallback = Effect.fn("Bus.subscribeAllCallback")(function* (callback: (event: any) => unknown) {
|
|
const s = yield* InstanceState.get(state)
|
|
return yield* on(s.wildcard, "*", callback)
|
|
})
|
|
|
|
return Service.of({ publish, subscribe, subscribeAll, subscribeCallback, subscribeAllCallback })
|
|
}),
|
|
)
|
|
|
|
export const defaultLayer = layer
|
|
|
|
const { runPromise, runSync } = makeRuntime(Service, layer)
|
|
|
|
// runSync is safe here because the subscribe chain (InstanceState.get, PubSub.subscribe,
|
|
// Scope.make, Effect.forkScoped) is entirely synchronous. If any step becomes async, this will throw.
|
|
export function createID() {
|
|
return Identifier.create("evt", "ascending")
|
|
}
|
|
|
|
export async function publish<D extends BusEvent.Definition>(
|
|
ctx: InstanceContext,
|
|
def: D,
|
|
properties: BusProperties<D>,
|
|
options?: { id?: string },
|
|
) {
|
|
return runPromise((svc) => svc.publish(def, properties, options).pipe(Effect.provideService(InstanceRef, ctx)))
|
|
}
|
|
|
|
export function subscribe<D extends BusEvent.Definition>(def: D, callback: (event: Payload<D>) => unknown) {
|
|
return runSync((svc) => svc.subscribeCallback(def, callback))
|
|
}
|
|
|
|
export function subscribeAll(callback: (event: any) => unknown) {
|
|
return runSync((svc) => svc.subscribeAllCallback(callback))
|
|
}
|
|
|
|
export * as Bus from "."
|