-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathgrpc_transport.ts
More file actions
356 lines (323 loc) · 10.6 KB
/
Copy pathgrpc_transport.ts
File metadata and controls
356 lines (323 loc) · 10.6 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import * as grpc from '@grpc/grpc-js';
import { TransportProtocolName } from '../../../core.js';
import {
A2AServiceClient,
TaskPushNotificationConfig,
GetExtendedAgentCardRequest,
ListTaskPushNotificationConfigsRequest,
SubscribeToTaskRequest,
} from '../../../grpc/pb/a2a.js';
import { Task, AgentCard, ListTaskPushNotificationConfigsResponse } from '../../../types/pb/a2a.js';
import {
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
SendMessageRequest,
StreamResponse,
SendMessageResult,
ListTasksRequest,
ListTasksResponse,
A2A_PROTOCOL_VERSION,
} from '../../../index.js';
import { RequestOptions } from '../../multitransport-client.js';
import { Transport, TransportFactory } from '../transport.js';
import { FromProto } from '../../../types/converters/from_proto.js';
import { fromGrpcError } from '../../../errors/grpc/index.js';
import { LegacyGrpcTransport } from '../../../compat/v0_3/client/transports/grpc/index.js';
import { isLegacyVersion } from '../../../version_utils.js';
import { pickMatchingInterface } from '../pick_interface.js';
const PROTOCOL_NAME: TransportProtocolName = 'GRPC';
type GrpcUnaryCall<TReq, TRes> = (
request: TReq,
metadata: grpc.Metadata,
options: Partial<grpc.CallOptions>,
callback: (error: grpc.ServiceError | null, response: TRes) => void
) => grpc.ClientUnaryCall;
type GrpcStreamCall<TReq, TRes> = (
request: TReq,
metadata?: grpc.Metadata,
options?: Partial<grpc.CallOptions>
) => grpc.ClientReadableStream<TRes>;
export interface GrpcTransportOptions {
endpoint: string;
grpcChannelCredentials?: grpc.ChannelCredentials;
grpcCallOptions?: Partial<grpc.CallOptions>;
}
export class GrpcTransport implements Transport {
private readonly grpcCallOptions?: Partial<grpc.CallOptions>;
private readonly grpcClient: A2AServiceClient;
constructor(options: GrpcTransportOptions) {
this.grpcCallOptions = options.grpcCallOptions;
this.grpcClient = new A2AServiceClient(
options.endpoint,
options.grpcChannelCredentials ?? grpc.credentials.createInsecure()
);
}
get protocolName(): string {
return PROTOCOL_NAME;
}
get protocolVersion(): string {
return A2A_PROTOCOL_VERSION;
}
async getExtendedAgentCard(
params: GetExtendedAgentCardRequest,
options?: RequestOptions
): Promise<AgentCard> {
const rpcResponse = await this._sendGrpcRequest<GetExtendedAgentCardRequest, AgentCard>(
'getExtendedAgentCard',
params,
options,
this.grpcClient.getExtendedAgentCard.bind(this.grpcClient)
);
return rpcResponse;
}
async sendMessage(
params: SendMessageRequest,
options?: RequestOptions
): Promise<SendMessageResult> {
const rpcResponse = await this._sendGrpcRequestWithConverter(
'sendMessage',
params,
options,
this.grpcClient.sendMessage.bind(this.grpcClient),
FromProto.sendMessageResult
);
return rpcResponse;
}
async *sendMessageStream(
params: SendMessageRequest,
options?: RequestOptions
): AsyncGenerator<StreamResponse, void, undefined> {
yield* this._sendGrpcStreamingRequest(
'sendStreamingMessage',
params,
options,
this.grpcClient.sendStreamingMessage.bind(this.grpcClient)
);
}
async createTaskPushNotificationConfig(
params: TaskPushNotificationConfig,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendGrpcRequest<
TaskPushNotificationConfig,
TaskPushNotificationConfig
>(
'createTaskPushNotificationConfig',
params,
options,
this.grpcClient.createTaskPushNotificationConfig.bind(this.grpcClient)
);
return rpcResponse;
}
async getTaskPushNotificationConfig(
params: GetTaskPushNotificationConfigRequest,
options?: RequestOptions
): Promise<TaskPushNotificationConfig> {
const rpcResponse = await this._sendGrpcRequest<
GetTaskPushNotificationConfigRequest,
TaskPushNotificationConfig
>(
'getTaskPushNotificationConfig',
params,
options,
this.grpcClient.getTaskPushNotificationConfig.bind(this.grpcClient)
);
return rpcResponse;
}
async listTaskPushNotificationConfig(
params: ListTaskPushNotificationConfigsRequest,
options?: RequestOptions
): Promise<ListTaskPushNotificationConfigsResponse> {
const rpcResponse = await this._sendGrpcRequest<
ListTaskPushNotificationConfigsRequest,
ListTaskPushNotificationConfigsResponse
>(
'listTaskPushNotificationConfigs',
params,
options,
this.grpcClient.listTaskPushNotificationConfigs.bind(this.grpcClient)
);
return rpcResponse;
}
async deleteTaskPushNotificationConfig(
params: DeleteTaskPushNotificationConfigRequest,
options?: RequestOptions
): Promise<void> {
await this._sendGrpcRequestWithConverter(
'deleteTaskPushNotificationConfig',
params,
options,
this.grpcClient.deleteTaskPushNotificationConfig.bind(this.grpcClient),
() => {}
);
}
async getTask(params: GetTaskRequest, options?: RequestOptions): Promise<Task> {
const rpcResponse = await this._sendGrpcRequest<GetTaskRequest, Task>(
'getTask',
params,
options,
this.grpcClient.getTask.bind(this.grpcClient)
);
return rpcResponse;
}
async cancelTask(params: CancelTaskRequest, options?: RequestOptions): Promise<Task> {
const rpcResponse = await this._sendGrpcRequest<CancelTaskRequest, Task>(
'cancelTask',
params,
options,
this.grpcClient.cancelTask.bind(this.grpcClient)
);
return rpcResponse;
}
async listTasks(params: ListTasksRequest, options?: RequestOptions): Promise<ListTasksResponse> {
const rpcResponse = await this._sendGrpcRequest<ListTasksRequest, ListTasksResponse>(
'listTasks',
params,
options,
this.grpcClient.listTasks.bind(this.grpcClient)
);
return rpcResponse;
}
async *resubscribeTask(
params: SubscribeToTaskRequest,
options?: RequestOptions
): AsyncGenerator<StreamResponse, void, undefined> {
yield* this._sendGrpcStreamingRequest(
'subscribeToTask',
params,
options,
this.grpcClient.subscribeToTask.bind(this.grpcClient)
);
}
private async _sendGrpcRequestWithConverter<TReq, TRes, TResponse>(
method: keyof A2AServiceClient,
params: TReq,
options: RequestOptions | undefined,
call: GrpcUnaryCall<TReq, TRes>,
converter: (res: TRes) => TResponse
): Promise<TResponse> {
return new Promise((resolve, reject) => {
let onAbort: (() => void) | undefined;
const clientCall = call(
params,
this._buildMetadata(options),
this.grpcCallOptions ?? {},
(error, response) => {
if (options?.signal && onAbort) {
options.signal.removeEventListener('abort', onAbort);
}
if (error) {
return reject(fromGrpcError(error, method));
}
resolve(converter(response));
}
);
if (options?.signal) {
if (options.signal.aborted) {
clientCall.cancel();
} else {
onAbort = () => clientCall.cancel();
options.signal.addEventListener('abort', onAbort);
}
}
});
}
private async _sendGrpcRequest<TReq, TRes>(
method: keyof A2AServiceClient,
params: TReq,
options: RequestOptions | undefined,
call: GrpcUnaryCall<TReq, TRes>
): Promise<TRes> {
return this._sendGrpcRequestWithConverter(method, params, options, call, (res: TRes) => res);
}
private async *_sendGrpcStreamingRequest<TReq>(
method: 'sendStreamingMessage' | 'subscribeToTask',
params: TReq,
options: RequestOptions | undefined,
call: GrpcStreamCall<TReq, StreamResponse>
): AsyncGenerator<StreamResponse, void, undefined> {
const streamResponse = call(params, this._buildMetadata(options), this.grpcCallOptions ?? {});
let onAbort: (() => void) | undefined;
if (options?.signal) {
if (options.signal.aborted) {
streamResponse.cancel();
} else {
onAbort = () => streamResponse.cancel();
options.signal.addEventListener('abort', onAbort);
}
}
try {
for await (const response of streamResponse) {
yield response;
}
} catch (error) {
if (this.isServiceError(error)) {
throw fromGrpcError(error, method);
} else {
throw new Error(`GRPC error for ${String(method)}!`, {
cause: error,
});
}
} finally {
if (options?.signal && onAbort) {
options.signal.removeEventListener('abort', onAbort);
}
streamResponse.cancel();
}
}
private isServiceError(error: unknown): error is grpc.ServiceError {
return typeof error === 'object' && error !== null && 'code' in error;
}
private _buildMetadata(options: RequestOptions | undefined): grpc.Metadata {
const metadata = new grpc.Metadata();
if (options?.serviceParameters) {
for (const [key, value] of Object.entries(options.serviceParameters)) {
metadata.set(key, value);
}
}
return metadata;
}
}
export class GrpcTransportFactoryOptions {
grpcChannelCredentials?: grpc.ChannelCredentials;
grpcCallOptions?: Partial<grpc.CallOptions>;
/**
* Enables the v0.3 protocol compatibility layer. When enabled, the
* factory inspects the matched `AgentInterface.protocolVersion`; if
* it falls in `[0.3, 1.0)`, the v0.3 `LegacyGrpcTransport` is
* instantiated instead of v1.0.
*
* Default: omitted (disabled).
*/
legacyCompat?: { enabled: boolean };
}
/**
* Factory producing a gRPC `Transport`. With
* `legacyCompat: { enabled: true }` it dispatches between the v1.0 and
* v0.3 transports based on `AgentInterface.protocolVersion`.
*/
export class GrpcTransportFactory implements TransportFactory {
constructor(private readonly options?: GrpcTransportFactoryOptions) {}
get protocolName(): string {
return PROTOCOL_NAME;
}
async create(url: string, agentCard: AgentCard): Promise<Transport> {
if (this.options?.legacyCompat?.enabled) {
const iface = pickMatchingInterface(agentCard, PROTOCOL_NAME, url);
if (iface && isLegacyVersion(iface.protocolVersion)) {
return new LegacyGrpcTransport({
endpoint: url,
grpcChannelCredentials: this.options?.grpcChannelCredentials,
grpcCallOptions: this.options?.grpcCallOptions,
});
}
}
return new GrpcTransport({
endpoint: url,
grpcChannelCredentials: this.options?.grpcChannelCredentials,
grpcCallOptions: this.options?.grpcCallOptions,
});
}
}