(endpoint: string, path: string, payload: string, timeoutMs?: number)
| 10 | |
| 11 | |
| 12 | export function send_rpc_request<T = any>(endpoint: string, path: string, payload: string, timeoutMs?: number): Promise<T> { |
| 13 | return new Promise((resolve, reject) => { |
| 14 | const abortController = new AbortController() |
| 15 | let isCompleted = false |
| 16 | |
| 17 | const safeReject = (error: Error) => { |
| 18 | if (!isCompleted) { |
| 19 | isCompleted = true |
| 20 | reject(error) |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | const safeResolve = (result: T) => { |
| 25 | if (!isCompleted) { |
| 26 | isCompleted = true |
| 27 | resolve(result) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | const timeout = setTimeout(() => { |
| 32 | abortController.abort() |
| 33 | safeReject(new Error('request timed out')) |
| 34 | }, timeoutMs || 30_000) // Default 30 seconds timeout |
| 35 | |
| 36 | const cleanup = () => { |
| 37 | clearTimeout(timeout) |
| 38 | abortController.signal.removeEventListener('abort', onAbort) |
| 39 | } |
| 40 | |
| 41 | const onAbort = () => { |
| 42 | cleanup() |
| 43 | safeReject(new Error('request aborted')) |
| 44 | } |
| 45 | |
| 46 | abortController.signal.addEventListener('abort', onAbort) |
| 47 | |
| 48 | const isHttp = endpoint.startsWith('http://') || endpoint.startsWith('https://') |
| 49 | |
| 50 | if (isHttp) { |
| 51 | const url = new URL(path, endpoint) |
| 52 | const options = { |
| 53 | method: 'POST', |
| 54 | headers: { |
| 55 | 'Content-Type': 'application/json', |
| 56 | 'Content-Length': Buffer.byteLength(payload), |
| 57 | 'User-Agent': `dstack-sdk-js/${__version__}`, |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | const req = (url.protocol === 'https:' ? https : http).request(url, options, (res) => { |
| 62 | let data = '' |
| 63 | res.on('data', (chunk) => { |
| 64 | data += chunk |
| 65 | }) |
| 66 | res.on('end', () => { |
| 67 | cleanup() |
| 68 | try { |
| 69 | const result = JSON.parse(data) |
no test coverage detected