Skip to content

Commit

Permalink
fixed race condition on apiContext
Browse files Browse the repository at this point in the history
  • Loading branch information
eric2788 committed Oct 25, 2024
1 parent a5b765e commit 68d70fe
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 18 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"@types/react-dom": "18.2.15",
"@types/semver": "^7.5.8",
"@webgpu/types": "^0.1.49",
"async-mutex": "^0.5.0",
"dotenv": "^16.4.5",
"esbuild": "^0.20.2",
"gify-parse": "^1.0.7",
Expand Down
35 changes: 20 additions & 15 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 11 additions & 3 deletions tests/helpers/bilibili-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { sendInternal } from "~background/messages";
import type { StreamUrls } from "~background/messages/get-stream-urls";
import type { V1Response, StreamUrlResponse } from "~types/bilibili";
import logger from "./logger";
import { Mutex } from 'async-mutex';

export interface LiveRoomInfo {
roomid: number;
Expand Down Expand Up @@ -35,6 +36,8 @@ export default class BilbiliApi {
return new BilbiliApi(context)
}

private readonly mutex = new Mutex()

/**
* 构造BilbiliApi的新实例。
* @param context - API请求的上下文。
Expand All @@ -48,9 +51,14 @@ export default class BilbiliApi {
* @throws 如果获取操作失败,则抛出错误。
*/
private async fetch<T = any>(path: string): Promise<T> {
const res = await this.context.get(path)
if (!res.ok()) throw new Error(`获取bilibili API失败:${res.statusText()}`)
return await res.json()
const release = await this.mutex.acquire()
try {
const res = await this.context.get(path)
if (!res.ok()) throw new Error(`获取bilibili API失败:${res.statusText()}`)
return await res.json()
} finally {
release()
}
}

/**
Expand Down

0 comments on commit 68d70fe

Please sign in to comment.