Line data Source code
1 : import type { AxiosInstance } from 'axios'
2 : import axios from 'axios'
3 : import {
4 : webSessionRequests,
5 : webSessionSend
6 : } from '@comfyorg/api-client/webSessionFetch'
7 : import {
8 : UNKNOWN_ERROR_CODE,
9 : errorResponseFromBody
10 : } from '@/platform/remote/comfyui/errors'
11 : import type { AuthHeader } from '@comfyorg/api-client/authTypes'
12 : import { createWebSessionAdapter } from './webSessionAdapter'
13 : import { attachCapabilityRevisionInterceptor } from './capabilityRevision'
14 : import {
15 : NO_WORKSPACE_ACCESS,
16 : NoWorkspaceAccessError,
17 : WorkspaceApiError
18 : } from './ingestApiError'
19 : export interface IngestApiAuth {
20 : getWorkspaceAuthHeader(): Promise<AuthHeader>
21 : getFirebaseAuthHeader(): Promise<AuthHeader>
22 : attachRetryInterceptor(client: AxiosInstance): void
23 : }
24 :
25 2356 : export const ingestApiClient = axios.create({
26 : headers: {
27 : 'Content-Type': 'application/json'
28 : }
29 : })
30 :
31 2356 : attachCapabilityRevisionInterceptor(ingestApiClient)
32 :
33 2356 : let ingestApiAuth: IngestApiAuth | undefined
34 :
35 2355 : export function setIngestApiAuth(auth: IngestApiAuth): void {
36 2355 : ingestApiAuth = auth
37 2355 : auth.attachRetryInterceptor(ingestApiClient)
38 : }
39 :
40 141 : export function requireIngestApiAuth(): IngestApiAuth {
41 141 : if (!ingestApiAuth) {
42 0 : throw new WorkspaceApiError('Workspace API auth is not installed', 401)
43 : }
44 141 : return ingestApiAuth
45 : }
46 :
47 141 : export async function requestAuth() {
48 141 : if (webSessionRequests()) {
49 0 : const send = await webSessionSend()
50 0 : if (send) return { adapter: createWebSessionAdapter(send) }
51 : }
52 141 : return { headers: await requireIngestApiAuth().getWorkspaceAuthHeader() }
53 : }
54 :
55 0 : function retryAfterSeconds(header: unknown): number | undefined {
56 0 : return typeof header === 'string' && /^\d+$/.test(header.trim())
57 : ? Number(header)
58 : : undefined
59 : }
60 :
61 0 : export function handleAxiosError(err: unknown, operation: string): never {
62 0 : if (axios.isAxiosError(err)) {
63 0 : const status = err.response?.status
64 0 : const { code, message } = errorResponseFromBody(
65 : err.response?.data,
66 : err.message
67 : )
68 0 : if (status === 403 && code === NO_WORKSPACE_ACCESS) {
69 0 : throw new NoWorkspaceAccessError(message, status, operation)
70 : }
71 :
72 0 : throw new WorkspaceApiError(
73 : message,
74 : status,
75 : code === UNKNOWN_ERROR_CODE ? undefined : code,
76 : undefined,
77 : operation,
78 : retryAfterSeconds(err.response?.headers['retry-after'])
79 : )
80 : }
81 0 : throw err
82 : }
|