summaryrefslogtreecommitdiffhomepage
path: root/packages/kernel/src/bus/bus.ts
blob: 03d692e481da73a64347e539ed91a850101072ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import type { Logger } from "../contracts/extension.js";
import type {
	EventHandler,
	EventHookDescriptor,
	FilterDescriptor,
	FilterHandler,
	ServiceHandle,
} from "../contracts/hooks.js";
import {
	applyFilterChain,
	dispatchEventAsync,
	dispatchEventSync,
	type FilterEntry,
	sortFilters,
} from "./pure.js";

export interface Bus {
	readonly on: <T>(hook: EventHookDescriptor<T>, handler: EventHandler<T>) => () => void;
	readonly emit: <T>(hook: EventHookDescriptor<T>, payload: T) => void;
	readonly emitAsync: <T>(
		hook: EventHookDescriptor<T>,
		payload: T,
		timeoutMs?: number,
	) => Promise<void>;
	readonly addFilter: <T>(
		hook: FilterDescriptor<T>,
		fn: FilterHandler<T>,
		opts?: { readonly priority?: number },
	) => () => void;
	readonly applyFilters: <T>(
		hook: FilterDescriptor<T>,
		value: T,
		opts?: { readonly failClosed?: boolean },
	) => Promise<T>;
	readonly provideService: <T>(handle: ServiceHandle<T>, impl: T) => void;
	readonly getService: <T>(handle: ServiceHandle<T>) => T;
}

interface StoredFilterEntry {
	readonly fn: unknown;
	readonly priority: number;
	readonly order: number;
}

export function createBus(logger: Logger): Bus {
	const eventHandlers = new Map<string, Set<unknown>>();
	const filterEntries = new Map<string, StoredFilterEntry[]>();
	const services = new Map<string, unknown>();
	let filterOrderCounter = 0;

	return {
		on<T>(hook: EventHookDescriptor<T>, handler: EventHandler<T>): () => void {
			let set = eventHandlers.get(hook.id);
			if (set === undefined) {
				set = new Set();
				eventHandlers.set(hook.id, set);
			}
			const stored: unknown = handler;
			set.add(stored);
			return () => {
				const current = eventHandlers.get(hook.id);
				if (current !== undefined) current.delete(stored);
			};
		},

		emit<T>(hook: EventHookDescriptor<T>, payload: T): void {
			const set = eventHandlers.get(hook.id);
			if (set === undefined || set.size === 0) return;
			const handlers = [...set] as Array<EventHandler<T>>;
			dispatchEventSync(handlers, payload, logger, hook.id);
		},

		async emitAsync<T>(
			hook: EventHookDescriptor<T>,
			payload: T,
			timeoutMs?: number,
		): Promise<void> {
			const set = eventHandlers.get(hook.id);
			if (set === undefined || set.size === 0) return;
			const handlers = [...set] as Array<EventHandler<T>>;
			await dispatchEventAsync(handlers, payload, logger, hook.id, timeoutMs);
		},

		addFilter<T>(
			hook: FilterDescriptor<T>,
			fn: FilterHandler<T>,
			opts?: { readonly priority?: number },
		): () => void {
			let entries = filterEntries.get(hook.id);
			if (entries === undefined) {
				entries = [];
				filterEntries.set(hook.id, entries);
			}
			const entry: StoredFilterEntry = {
				fn,
				priority: opts?.priority ?? 0,
				order: filterOrderCounter++,
			};
			entries.push(entry);
			return () => {
				const current = filterEntries.get(hook.id);
				if (current === undefined) return;
				const idx = current.indexOf(entry);
				if (idx !== -1) current.splice(idx, 1);
			};
		},

		async applyFilters<T>(
			hook: FilterDescriptor<T>,
			value: T,
			opts?: { readonly failClosed?: boolean },
		): Promise<T> {
			const entries = filterEntries.get(hook.id);
			if (entries === undefined || entries.length === 0) return value;
			const sorted = sortFilters(entries as ReadonlyArray<FilterEntry<T>>);
			const fns = sorted.map((e) => e.fn) as Array<FilterHandler<T>>;
			return applyFilterChain(fns, value, logger, hook.id, opts?.failClosed ?? false);
		},

		provideService<T>(handle: ServiceHandle<T>, impl: T): void {
			if (services.has(handle.id)) {
				throw new Error(
					`Service "${handle.id}" is already provided. Only one provider per handle is allowed.`,
				);
			}
			services.set(handle.id, impl);
		},

		getService<T>(handle: ServiceHandle<T>): T {
			const impl = services.get(handle.id);
			if (impl === undefined) {
				throw new Error(
					`Service "${handle.id}" has no provider. Call provideService before getService.`,
				);
			}
			return impl as T;
		},
	};
}