Skip to content

Commit

Permalink
Merge pull request #372 from refly-ai/fix/stream-invoke-401
Browse files Browse the repository at this point in the history
Fix/stream invoke 401
  • Loading branch information
mrcfps authored Jan 15, 2025
2 parents f822016 + 7cf3a07 commit c40047b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
43 changes: 33 additions & 10 deletions packages/ai-workspace-common/src/utils/sse-post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,38 @@ import { getServerOrigin } from '@refly/utils/url';
import { InvokeSkillRequest, SkillEvent } from '@refly/openapi-schema';
import { scrollToBottom } from '@refly-packages/ai-workspace-common/utils/ui';
import { extractBaseResp } from '@refly-packages/ai-workspace-common/requests/proxiedRequest';
import { ConnectionError } from '@refly/errors';
import { ConnectionError, AuthenticationExpiredError } from '@refly/errors';
import { refreshToken } from './auth';

const makeSSERequest = async (
payload: InvokeSkillRequest,
controller: AbortController,
isRetry = false,
): Promise<Response> => {
const response = await fetch(`${getServerOrigin()}/v1/skill/streamInvoke`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
signal: controller.signal,
body: JSON.stringify(payload),
});

if (response.status === 401 && !isRetry) {
try {
await refreshToken();
return makeSSERequest(payload, controller, true);
} catch (error) {
if (error instanceof AuthenticationExpiredError) {
throw error;
}
throw new ConnectionError(error);
}
}

return response;
};

export const ssePost = async ({
controller,
Expand Down Expand Up @@ -36,15 +67,7 @@ export const ssePost = async ({
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;

try {
const response = await fetch(`${getServerOrigin()}/v1/skill/streamInvoke`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
signal: controller.signal,
body: JSON.stringify(payload),
});
const response = await makeSSERequest(payload, controller);

const baseResp = await extractBaseResp(response);
if (!baseResp.success) {
Expand Down
5 changes: 3 additions & 2 deletions packages/errors/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ export abstract class BaseError extends Error {
abstract messageDict: Record<string, string>;

constructor(message?: string) {
super(message);
super(message ?? ''); // compatible with safari
Object.setPrototypeOf(this, new.target.prototype);
}

toString() {
return `[${this.code}] ${this.messageDict['en']}`;
return `[${this.code}] ${this.messageDict?.['en'] ?? 'Unknown error occurred'}`;
}

getMessage(locale: string) {
Expand Down

0 comments on commit c40047b

Please sign in to comment.