-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontracts.ts
More file actions
188 lines (158 loc) · 6.01 KB
/
Copy pathcontracts.ts
File metadata and controls
188 lines (158 loc) · 6.01 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
* Contract registry service.
*
* Plugins register concrete implementations for versioned capability contracts
* such as `llm.chat/v1` or `market.quote/v1`. Other plugins resolve or watch
* those contracts without needing to know plugin-to-plugin topology.
*
* This is an advanced sharing layer. Ordinary plugins should usually prefer
* plain Cordis services via `ctx.provide(...)` / `ctx.get(...)` and events.
*/
import { Context, Service } from 'cordis';
import type { GatewayContractId } from '@tradinggoose/shared';
export type ContractResolutionStrategy = 'highest-priority' | 'first-registered';
export interface ContractRegistration {
contract: GatewayContractId;
plugin: string;
implementation: unknown;
implementationId?: string;
version?: string;
priority?: number;
}
export interface ResolvedContractRegistration extends Omit<ContractRegistration, 'implementationId' | 'priority'> {
implementationId: string;
priority: number;
}
export interface ContractResolveOptions {
plugin?: string;
implementationId?: string;
strategy?: ContractResolutionStrategy;
}
export interface ContractWatchEvent {
type: 'registered' | 'unregistered';
registration: ResolvedContractRegistration;
}
type ContractWatchListener = (event: ContractWatchEvent) => void;
declare module 'cordis' {
interface Context {
contracts: ContractsService;
}
}
interface StoredContractRegistration extends ResolvedContractRegistration {
sequence: number;
}
export class ContractsService extends Service {
private registrations = new Map<GatewayContractId, Map<string, StoredContractRegistration>>();
private watchers = new Map<GatewayContractId, Set<ContractWatchListener>>();
private sequence = 0;
constructor(ctx: Context) {
super(ctx, 'contracts');
}
register(input: ContractRegistration): () => void {
const registration: StoredContractRegistration = {
...input,
implementationId: input.implementationId ?? input.plugin,
priority: input.priority ?? 0,
sequence: this.sequence++,
};
const key = this.registrationKey(registration.plugin, registration.implementationId);
const bucket = this.ensureBucket(registration.contract);
if (bucket.has(key)) {
throw new Error(
`Contract "${registration.contract}" already has an implementation registered for ${key}`,
);
}
bucket.set(key, registration);
this.emit(registration.contract, { type: 'registered', registration });
return () => {
const current = bucket.get(key);
if (!current) return;
bucket.delete(key);
if (bucket.size === 0) {
this.registrations.delete(registration.contract);
}
this.emit(registration.contract, { type: 'unregistered', registration: current });
};
}
list(contract?: GatewayContractId): ResolvedContractRegistration[] {
if (contract) {
return this.sortRegistrations([...this.ensureExistingBucket(contract).values()]);
}
return this.sortRegistrations(
[...this.registrations.values()].flatMap((bucket) => [...bucket.values()]),
);
}
listByPlugin(plugin: string): ResolvedContractRegistration[] {
return this.sortRegistrations(
[...this.registrations.values()].flatMap((bucket) =>
[...bucket.values()].filter((registration) => registration.plugin === plugin),
),
);
}
resolve(
contract: GatewayContractId,
options?: ContractResolveOptions,
): ResolvedContractRegistration | null {
const registrations = this.list(contract).filter((registration) => {
if (options?.plugin && registration.plugin !== options.plugin) return false;
if (options?.implementationId && registration.implementationId !== options.implementationId) {
return false;
}
return true;
});
if (!registrations.length) return null;
if (options?.strategy === 'first-registered') {
return registrations.reduce((best, current) =>
this.registrationSequence(best) < this.registrationSequence(current) ? best : current,
);
}
return registrations[0] ?? null;
}
watch(contract: GatewayContractId, listener: ContractWatchListener): () => void {
const listeners = this.watchers.get(contract) ?? new Set<ContractWatchListener>();
listeners.add(listener);
this.watchers.set(contract, listeners);
return () => {
const current = this.watchers.get(contract);
if (!current) return;
current.delete(listener);
if (current.size === 0) {
this.watchers.delete(contract);
}
};
}
private ensureBucket(contract: GatewayContractId): Map<string, StoredContractRegistration> {
const existing = this.registrations.get(contract);
if (existing) return existing;
const created = new Map<string, StoredContractRegistration>();
this.registrations.set(contract, created);
return created;
}
private ensureExistingBucket(contract: GatewayContractId): Map<string, StoredContractRegistration> {
return this.registrations.get(contract) ?? new Map<string, StoredContractRegistration>();
}
private emit(contract: GatewayContractId, event: ContractWatchEvent): void {
for (const listener of this.watchers.get(contract) ?? []) {
listener(event);
}
}
private registrationKey(plugin: string, implementationId: string): string {
return `${plugin}:${implementationId}`;
}
private registrationSequence(registration: ResolvedContractRegistration): number {
const bucket = this.registrations.get(registration.contract);
const stored = bucket?.get(this.registrationKey(registration.plugin, registration.implementationId));
return stored?.sequence ?? Number.MAX_SAFE_INTEGER;
}
private sortRegistrations(
registrations: StoredContractRegistration[],
): ResolvedContractRegistration[] {
return registrations
.slice()
.sort((left, right) => {
if (left.priority !== right.priority) return right.priority - left.priority;
return left.sequence - right.sequence;
})
.map(({ sequence: _sequence, ...registration }) => registration);
}
}