-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.ts
More file actions
311 lines (288 loc) · 10.1 KB
/
Copy pathdata.ts
File metadata and controls
311 lines (288 loc) · 10.1 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
import {
isJsonObject,
type JsonValue,
} from '@datafe-open/markdown-chart';
import {
createLegacySandboxErrorClassifier,
type LegacySandboxFailureKind,
type LegacySandboxFile,
type LegacySandboxTransport,
} from '@datafe-open/markdown-chart-echarts';
interface ListArtifactsResult {
readonly NextToken?: unknown;
readonly Artifacts?: unknown;
}
interface ArtifactMetaResult {
readonly ArtifactContent?: unknown;
}
export interface ChatBILegacySandboxTransportOptions {
readonly fetch?: typeof globalThis.fetch;
readonly listEndpoint?: string;
readonly metaEndpoint?: string;
/** Maximum UTF-8 bytes read from one same-origin proxy response. */
readonly maxResponseBytes?: number;
}
const DEFAULT_LIST_ENDPOINT = '/api/dataworks/list-agent-session-artifacts';
const DEFAULT_META_ENDPOINT = '/api/dataworks/get-agent-session-artifact-meta';
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
const MAX_ARTIFACT_PAGES = 100;
let jsonRpcId = 0;
class OpenApiTransportError extends Error {
readonly kind: LegacySandboxFailureKind | undefined;
readonly status: number | undefined;
constructor(
message: string,
options?: {
readonly cause?: unknown;
readonly kind?: LegacySandboxFailureKind;
readonly status?: number;
},
) {
super(message, options && 'cause' in options ? { cause: options.cause } : undefined);
this.name = 'OpenApiTransportError';
this.kind = options?.kind;
this.status = options?.status;
}
}
function failure(
kind: LegacySandboxFailureKind,
message: string,
cause?: unknown,
): OpenApiTransportError {
return new OpenApiTransportError(message, {
kind,
...(cause === undefined ? {} : { cause }),
});
}
function httpFailure(status: number, message: string): OpenApiTransportError {
return new OpenApiTransportError(message, { status });
}
function requiredText(value: string, label: string): string {
const normalized = value.trim();
if (!normalized) throw failure('fatal', `${label} is required`);
return normalized;
}
function positiveSafeInteger(value: number, label: string): number {
if (!Number.isSafeInteger(value) || value <= 0) {
throw failure('fatal', `${label} must be a positive safe integer`);
}
return value;
}
function isAbortError(error: unknown): boolean {
return error instanceof Error && error.name === 'AbortError';
}
function errorDetail(value: unknown): string | undefined {
if (!isJsonObject(value)) return undefined;
const code = typeof value.Code === 'string' ? value.Code : undefined;
const message = typeof value.Message === 'string' ? value.Message : undefined;
return [code, message].filter(Boolean).join(': ') || undefined;
}
async function readResponseText(
response: Response,
operation: string,
maxResponseBytes: number,
): Promise<string> {
const contentLength = response.headers.get('Content-Length');
if (contentLength !== null) {
const declaredBytes = Number(contentLength);
if (Number.isFinite(declaredBytes) && declaredBytes > maxResponseBytes) {
throw failure('fatal', `${operation} exceeds the ${maxResponseBytes} byte response limit`);
}
}
if (!response.body) {
const body = await response.text();
if (new TextEncoder().encode(body).byteLength > maxResponseBytes) {
throw failure('fatal', `${operation} exceeds the ${maxResponseBytes} byte response limit`);
}
return body;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let body = '';
let receivedBytes = 0;
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) {
body += decoder.decode();
return body;
}
receivedBytes += chunk.value.byteLength;
if (receivedBytes > maxResponseBytes) {
await reader.cancel();
throw failure('fatal', `${operation} exceeds the ${maxResponseBytes} byte response limit`);
}
body += decoder.decode(chunk.value, { stream: true });
}
} finally {
reader.releaseLock();
}
}
async function postJsonRpc<Result>(
fetcher: typeof globalThis.fetch,
endpoint: string,
params: Record<string, JsonValue>,
signal: AbortSignal,
operation: string,
maxResponseBytes: number,
): Promise<Result> {
jsonRpcId += 1;
let response: Response;
try {
response = await fetcher(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Jsonrpc: '2.0', Id: String(jsonRpcId), Params: params }),
signal,
});
} catch (cause) {
if (signal.aborted) throw signal.reason ?? cause;
if (isAbortError(cause)) throw cause;
throw failure('retryable', `${operation} could not reach the OpenAPI proxy`, cause);
}
let text: string;
try {
text = await readResponseText(response, operation, maxResponseBytes);
} catch (cause) {
if (signal.aborted) throw signal.reason ?? cause;
if (isAbortError(cause) || cause instanceof OpenApiTransportError) throw cause;
throw failure('retryable', `${operation} could not read the OpenAPI proxy response`, cause);
}
if (!response.ok) {
let parsedError: unknown;
try {
parsedError = JSON.parse(text) as unknown;
} catch {
parsedError = undefined;
}
const detail = errorDetail(parsedError);
throw httpFailure(
response.status,
`${operation} failed with HTTP ${response.status}${detail ? `: ${detail}` : ''}`,
);
}
let parsed: unknown;
try {
parsed = JSON.parse(text) as unknown;
} catch (cause) {
throw failure('fatal', `${operation} returned invalid JSON`, cause);
}
if (!isJsonObject(parsed)) {
throw failure('fatal', `${operation} returned an invalid JSON-RPC envelope`);
}
if (parsed.Code !== undefined || parsed.Message !== undefined) {
throw failure('fatal', `${operation} failed: ${errorDetail(parsed) ?? 'OpenAPI error'}`);
}
const jsonRpcResponse = parsed.JsonRpcResponse;
if (!isJsonObject(jsonRpcResponse)) {
throw failure('fatal', `${operation} returned an invalid JSON-RPC envelope`);
}
if (jsonRpcResponse.Error !== undefined && jsonRpcResponse.Error !== null) {
throw failure(
'fatal',
`${operation} failed: ${errorDetail(jsonRpcResponse.Error) ?? 'JSON-RPC error'}`,
);
}
if (!Object.prototype.hasOwnProperty.call(jsonRpcResponse, 'Result')) {
throw failure('fatal', `${operation} returned no JSON-RPC result`);
}
return jsonRpcResponse.Result as Result;
}
function mapArtifact(value: unknown): LegacySandboxFile {
const artifactName = isJsonObject(value) && typeof value.ArtifactName === 'string'
? value.ArtifactName
: '';
const artifactPath = isJsonObject(value) && typeof value.ArtifactPath === 'string'
? value.ArtifactPath
: '';
const isCsv = artifactName.trim().toLowerCase().endsWith('.csv')
|| artifactPath.trim().toLowerCase().endsWith('.csv');
return {
fileName: artifactName,
filePath: artifactPath,
originalFilePath: artifactPath,
fileType: isCsv ? 'csv' : '',
};
}
/** Creates the host-owned OpenAPI list/read adapter used by the shared client. */
export function createChatBILegacySandboxTransport(
options: ChatBILegacySandboxTransportOptions = {},
): LegacySandboxTransport {
const fetcher = options.fetch ?? globalThis.fetch;
const listEndpoint = options.listEndpoint ?? DEFAULT_LIST_ENDPOINT;
const metaEndpoint = options.metaEndpoint ?? DEFAULT_META_ENDPOINT;
const maxResponseBytes = positiveSafeInteger(
options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
'maxResponseBytes',
);
const classifyError = createLegacySandboxErrorClassifier({
getFailureKind: (error) => (
error instanceof OpenApiTransportError ? error.kind : undefined
),
getStatus: (error) => (
error instanceof OpenApiTransportError ? error.status : undefined
),
});
return {
async listFiles({ sessionId, requestId, signal }) {
const normalizedSessionId = requiredText(sessionId, 'sessionId');
const normalizedRequestId = requestId?.trim() || undefined;
const files: LegacySandboxFile[] = [];
const seenTokens = new Set<string>();
let nextToken: string | undefined;
for (let page = 0; page < MAX_ARTIFACT_PAGES; page += 1) {
const result = await postJsonRpc<ListArtifactsResult>(
fetcher,
listEndpoint,
{
SessionId: normalizedSessionId,
...(normalizedRequestId ? { RequestId: normalizedRequestId } : {}),
MaxResults: 50,
...(nextToken ? { NextToken: nextToken } : {}),
},
signal,
'ListAgentSessionArtifacts',
maxResponseBytes,
);
if (!isJsonObject(result) || !Array.isArray(result.Artifacts)) {
throw failure('fatal', 'ListAgentSessionArtifacts returned no artifact list');
}
files.push(...result.Artifacts.map(mapArtifact));
const token = result.NextToken;
if (token === undefined || token === null || token === '') {
nextToken = undefined;
break;
}
if (typeof token !== 'string') {
throw failure('fatal', 'ListAgentSessionArtifacts returned an invalid NextToken');
}
if (seenTokens.has(token)) {
throw failure('fatal', 'ListAgentSessionArtifacts returned a repeated NextToken');
}
seenTokens.add(token);
nextToken = token;
}
if (nextToken) {
throw failure('fatal', `ListAgentSessionArtifacts exceeded ${MAX_ARTIFACT_PAGES} pages`);
}
return files;
},
async readFile({ sessionId, file, signal }) {
const normalizedSessionId = requiredText(sessionId, 'sessionId');
const artifactPath = requiredText(file.originalFilePath, 'file.originalFilePath');
const meta = await postJsonRpc<ArtifactMetaResult>(
fetcher,
metaEndpoint,
{ SessionId: normalizedSessionId, ArtifactPath: artifactPath },
signal,
'GetAgentSessionArtifactMeta',
maxResponseBytes,
);
if (!isJsonObject(meta) || typeof meta.ArtifactContent !== 'string') {
throw failure('fatal', 'GetAgentSessionArtifactMeta returned no ArtifactContent');
}
return meta.ArtifactContent;
},
classifyError,
};
}