Rename eventSource_Factory and fetch_implementation (#8209)

* rename eventSource_factory -> stream_factory + rename event_source -> steam

* rename fetch_implementation -> fetch

* rename fetch to _fetch due to global.fetch conflict

* add changeset

* format

* format

* format

* format

* fix

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
This commit is contained in:
Hannah 2024-05-03 15:24:19 +02:00 committed by GitHub
parent 24b2286a22
commit b9afe93915
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 104 additions and 100 deletions

View File

@ -0,0 +1,19 @@
---
"@gradio/app": minor
"@gradio/audio": minor
"@gradio/client": minor
"@gradio/dataframe": minor
"@gradio/file": minor
"@gradio/gallery": minor
"@gradio/image": minor
"@gradio/imageeditor": minor
"@gradio/model3d": minor
"@gradio/multimodaltextbox": minor
"@gradio/simpleimage": minor
"@gradio/storybook": minor
"@gradio/upload": minor
"@gradio/video": minor
"gradio": minor
---
feat:Rename `eventSource_Factory` and `fetch_implementation`

View File

@ -65,14 +65,11 @@ export class Client {
unclosed_events: Set<string> = new Set();
heartbeat_event: EventSource | null = null;
fetch_implementation(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
eventSource_factory(url: URL): EventSource | null {
stream_factory(url: URL): EventSource | null {
if (typeof window === "undefined" || typeof EventSource === "undefined") {
import("eventsource")
.then((EventSourceModule) => {
@ -157,7 +154,7 @@ export class Client {
const heartbeat_url = new URL(
`${this.config.root}/heartbeat/${this.session_hash}`
);
this.heartbeat_event = this.eventSource_factory(heartbeat_url); // Just connect to the endpoint without parsing the response. Ref: https://github.com/gradio-app/gradio/pull/7974#discussion_r1557717540
this.heartbeat_event = this.stream_factory(heartbeat_url); // Just connect to the endpoint without parsing the response. Ref: https://github.com/gradio-app/gradio/pull/7974#discussion_r1557717540
if (this.config.space_id && this.options.hf_token) {
this.jwt = await get_jwt(
@ -342,14 +339,11 @@ export class Client {
}
try {
const response = await this.fetch_implementation(
`${root_url}/component_server/`,
{
method: "POST",
body: body,
headers
}
);
const response = await this.fetch(`${root_url}/component_server/`, {
method: "POST",
body: body,
headers
});
if (!response.ok) {
throw new Error(

View File

@ -75,12 +75,9 @@ export async function resolve_config(
config.root = config_root;
return { ...config, path };
} else if (endpoint) {
const response = await this.fetch_implementation(
`${endpoint}/${CONFIG_URL}`,
{
headers
}
);
const response = await this.fetch(`${endpoint}/${CONFIG_URL}`, {
headers
});
if (response?.status === 200) {
let config = await response.json();

View File

@ -129,7 +129,7 @@ describe("Client class", () => {
);
class CustomClient extends Client {
fetch_implementation = mocked_fetch;
fetch = mocked_fetch;
}
await CustomClient.connect("hmb/hello_world");

View File

@ -17,7 +17,7 @@ describe("open_stream", () => {
beforeEach(async () => {
app = await Client.connect("hmb/hello_world");
app.eventSource_factory = vi.fn().mockImplementation(() => {
app.stream_factory = vi.fn().mockImplementation(() => {
mock_eventsource = new EventSource("");
return mock_eventsource;
});
@ -38,13 +38,13 @@ describe("open_stream", () => {
it("should connect to the SSE endpoint and handle messages", async () => {
app.open_stream();
const eventsource_mock_call = app.eventSource_factory.mock.calls[0][0];
const eventsource_mock_call = app.stream_factory.mock.calls[0][0];
expect(eventsource_mock_call.href).toMatch(
/https:\/\/hmb-hello-world\.hf\.space\/queue\/data\?session_hash/
);
expect(app.eventSource_factory).toHaveBeenCalledWith(eventsource_mock_call);
expect(app.stream_factory).toHaveBeenCalledWith(eventsource_mock_call);
const onMessageCallback = mock_eventsource.onmessage;
const onErrorCallback = mock_eventsource.onerror;

View File

@ -70,7 +70,7 @@ export type client_return = {
fn_name: string,
data: unknown[]
) => any;
view_api: (fetch_implementation: typeof fetch) => Promise<ApiInfo<JsApiData>>;
view_api: (_fetch: typeof fetch) => Promise<ApiInfo<JsApiData>>;
};
export type SubmitReturn = {

View File

@ -16,7 +16,7 @@ export async function post_data(
headers.Authorization = `Bearer ${this.options.hf_token}`;
}
try {
var response = await this.fetch_implementation(url, {
var response = await this.fetch(url, {
method: "POST",
body: JSON.stringify(body),
headers: { ...headers, ...additional_headers }

View File

@ -17,7 +17,7 @@ export function open_stream(this: Client): void {
stream_status.open = true;
let event_source: EventSource | null = null;
let stream: EventSource | null = null;
let params = new URLSearchParams({
session_hash: this.session_hash
}).toString();
@ -28,17 +28,17 @@ export function open_stream(this: Client): void {
url.searchParams.set("__sign", jwt);
}
event_source = this.eventSource_factory(url);
stream = this.stream_factory(url);
if (!event_source) {
if (!stream) {
console.warn("Cannot connect to SSE endpoint: " + url.toString());
return;
}
event_source.onmessage = async function (event: MessageEvent) {
stream.onmessage = async function (event: MessageEvent) {
let _data = JSON.parse(event.data);
if (_data.msg === "close_stream") {
close_stream(stream_status, event_source);
close_stream(stream_status, stream);
return;
}
const event_id = _data.event_id;
@ -55,7 +55,7 @@ export function open_stream(this: Client): void {
) {
unclosed_events.delete(event_id);
if (unclosed_events.size === 0) {
close_stream(stream_status, event_source);
close_stream(stream_status, stream);
}
}
let fn: (data: any) => void = event_callbacks[event_id];
@ -72,7 +72,7 @@ export function open_stream(this: Client): void {
pending_stream_messages[event_id].push(_data);
}
};
event_source.onerror = async function () {
stream.onerror = async function () {
await Promise.all(
Object.keys(event_callbacks).map((event_id) =>
event_callbacks[event_id]({
@ -81,17 +81,17 @@ export function open_stream(this: Client): void {
})
)
);
close_stream(stream_status, event_source);
close_stream(stream_status, stream);
};
}
export function close_stream(
stream_status: { open: boolean },
event_source: EventSource | null
stream: EventSource | null
): void {
if (stream_status && event_source) {
if (stream_status && stream) {
stream_status.open = false;
event_source?.close();
stream?.close();
}
}

View File

@ -31,7 +31,7 @@ export function submit(
try {
const { hf_token } = this.options;
const {
fetch_implementation,
fetch,
app_reference,
config,
session_hash,
@ -56,7 +56,7 @@ export function submit(
);
let websocket: WebSocket;
let event_source: EventSource | null;
let stream: EventSource | null;
let protocol = config.protocol ?? "ws";
const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
@ -125,7 +125,7 @@ export function submit(
}
cancel_request = { fn_index, session_hash };
} else {
event_source?.close();
stream?.close();
cancel_request = { event_id };
}
@ -134,7 +134,7 @@ export function submit(
throw new Error("Could not resolve app config");
}
await fetch_implementation(`${config.root}/reset`, {
await fetch(`${config.root}/reset`, {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify(cancel_request)
@ -372,15 +372,15 @@ export function submit(
url.searchParams.set("__sign", this.jwt);
}
event_source = this.eventSource_factory(url);
stream = this.stream_factory(url);
if (!event_source) {
if (!stream) {
return Promise.reject(
new Error("Cannot connect to SSE endpoint: " + url.toString())
);
}
event_source.onmessage = async function (event: MessageEvent) {
stream.onmessage = async function (event: MessageEvent) {
const _data = JSON.parse(event.data);
const { type, status, data } = handle_message(
_data,
@ -397,7 +397,7 @@ export function submit(
...status
});
if (status.stage === "error") {
event_source?.close();
stream?.close();
}
} else if (type === "data") {
event_id = _data.event_id as string;
@ -416,7 +416,7 @@ export function submit(
fn_index,
time: new Date()
});
event_source?.close();
stream?.close();
}
} else if (type === "complete") {
complete = status;
@ -460,7 +460,7 @@ export function submit(
endpoint: _endpoint,
fn_index
});
event_source?.close();
stream?.close();
}
}
};
@ -631,7 +631,7 @@ export function submit(
time: new Date()
});
if (["sse_v2", "sse_v2.1"].includes(protocol)) {
close_stream(stream_status, event_source);
close_stream(stream_status, stream);
stream_status.open = false;
}
}

View File

@ -30,7 +30,7 @@ export async function upload_files(
? `${root_url}/upload?upload_id=${upload_id}`
: `${root_url}/${UPLOAD_URL}`;
response = await this.fetch_implementation(upload_url, {
response = await this.fetch(upload_url, {
method: "POST",
body: formData,
headers

View File

@ -28,7 +28,7 @@ export async function view_api(this: Client): Promise<any> {
let response: Response;
if (semiver(config?.version || "2.0.0", "3.30") < 0) {
response = await this.fetch_implementation(SPACE_FETCHER_URL, {
response = await this.fetch(SPACE_FETCHER_URL, {
method: "POST",
body: JSON.stringify({
serialize: false,
@ -37,12 +37,9 @@ export async function view_api(this: Client): Promise<any> {
headers
});
} else {
response = await this.fetch_implementation(
`${config?.root}/${API_INFO_URL}`,
{
headers
}
);
response = await this.fetch(`${config?.root}/${API_INFO_URL}`, {
headers
});
}
if (!response.ok) {

View File

@ -87,7 +87,7 @@
export let container: boolean;
export let info: boolean;
export let eager: boolean;
let eventSource: EventSource;
let stream: EventSource;
// These utilities are exported to be injectable for the Wasm version.
export let mount_css: typeof default_mount_css = default_mount_css;
@ -301,13 +301,13 @@
setTimeout(() => {
const { host } = new URL(api_url);
let url = new URL(`http://${host}/dev/reload`);
eventSource = new EventSource(url);
eventSource.addEventListener("error", async (e) => {
stream = new EventSource(url);
stream.addEventListener("error", async (e) => {
new_message_fn("Error reloading app", "error");
// @ts-ignore
console.error(JSON.parse(e.data));
});
eventSource.addEventListener("reload", async (event) => {
stream.addEventListener("reload", async (event) => {
app.close();
app = await Client.connect(api_url, {
status_callback: handle_status

View File

@ -6,7 +6,7 @@ import type { SvelteComponent } from "svelte";
import { WorkerProxy, type WorkerProxyOptions } from "@gradio/wasm";
import { Client } from "@gradio/client";
import { wasm_proxied_fetch } from "./fetch";
import { wasm_proxied_EventSource_factory } from "./sse";
import { wasm_proxied_stream_factory } from "./sse";
import { wasm_proxied_mount_css, mount_prebuilt_css } from "./css";
import type { mount_css } from "../css";
import Index from "../Index.svelte";
@ -127,15 +127,12 @@ export function create(options: Options): GradioAppController {
mount_prebuilt_css(document.head);
class LiteClient extends Client {
fetch_implementation(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return wasm_proxied_fetch(worker_proxy, input, init);
}
eventSource_factory(url: URL): EventSource {
return wasm_proxied_EventSource_factory(worker_proxy, url);
stream_factory(url: URL): EventSource {
return wasm_proxied_stream_factory(worker_proxy, url);
}
}

View File

@ -6,7 +6,7 @@ import { is_self_host } from "@gradio/wasm/network";
* which also falls back to the original WebSocket() for external resource requests.
*/
export function wasm_proxied_EventSource_factory(
export function wasm_proxied_stream_factory(
worker_proxy: WorkerProxy,
url: URL
): EventSource {

View File

@ -226,7 +226,7 @@
{waveform_options}
{trim_region_settings}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
>
<UploadText i18n={gradio.i18n} type="audio" />
</InteractiveAudio>

View File

@ -35,7 +35,7 @@
export let editable = true;
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
$: dispatch("drag", dragging);

View File

@ -151,6 +151,6 @@
{line_breaks}
{column_widths}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
/>
</Block>

View File

@ -40,7 +40,7 @@
export let line_breaks = true;
export let column_widths: string[] = [];
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let selected: false | [number, number] = false;
export let display_value: string[][] | null = null;

View File

@ -88,7 +88,7 @@
{:else}
<FileUpload
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
{label}
{show_label}
{value}

View File

@ -20,7 +20,7 @@
export let i18n: I18nFormatter;
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
async function handle_upload({
detail

View File

@ -78,7 +78,7 @@
file_types={["image"]}
i18n={gradio.i18n}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
on:upload={(e) => {
const files = Array.isArray(e.detail) ? e.detail : [e.detail];
value = files.map((x) => ({ image: x, caption: null }));
@ -112,7 +112,7 @@
{show_share_button}
{show_download_button}
i18n={gradio.i18n}
fetch_implementation={gradio.client.fetch_implementation}
_fetch={gradio.client.fetch}
/>
{/if}
</Block>

View File

@ -31,7 +31,7 @@
export let i18n: I18nFormatter;
export let selected_index: number | null = null;
export let interactive: boolean;
export let fetch_implementation: typeof fetch;
export let _fetch: typeof fetch;
const dispatch = createEventDispatcher<{
change: undefined;
@ -169,7 +169,7 @@
async function download(file_url: string, name: string): Promise<void> {
let response;
try {
response = await fetch_implementation(file_url);
response = await _fetch(file_url);
} catch (error) {
if (error instanceof TypeError) {
// If CORS is not allowed (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#checking_that_the_fetch_was_successful),

View File

@ -157,7 +157,7 @@
max_file_size={gradio.max_file_size}
i18n={gradio.i18n}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
>
{#if active_source === "upload" || !active_source}
<UploadText i18n={gradio.i18n} type="image" />

View File

@ -27,7 +27,7 @@
export let i18n: I18nFormatter;
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let upload_input: Upload;
let uploading = false;

View File

@ -208,7 +208,7 @@
{layers}
status={loading_status?.status}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
></InteractiveImageEditor>
</Block>
{/if}

View File

@ -47,7 +47,7 @@
export let canvas_size: [number, number] | undefined;
export let realtime: boolean;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
const dispatch = createEventDispatcher<{
clear?: never;

View File

@ -26,7 +26,7 @@
export let mirror_webcam = true;
export let i18n: I18nFormatter;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
const { active_tool } = getContext<ToolContext>(TOOL_KEY);
const { pixi, dimensions, register_context, reset, editor_box } =

View File

@ -128,7 +128,7 @@
i18n={gradio.i18n}
max_file_size={gradio.max_file_size}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
>
<UploadText i18n={gradio.i18n} type="file" />
</Model3DUpload>

View File

@ -25,7 +25,7 @@
null
];
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
async function handle_upload({
detail

View File

@ -98,6 +98,6 @@
}}
disabled={!interactive}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
/>
</Block>

View File

@ -36,7 +36,7 @@
export let file_types: string[] | null = null;
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let upload_component: Upload;
let hidden_upload: HTMLInputElement;

View File

@ -91,7 +91,7 @@
<ImageUploader
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
bind:value
{root}
on:clear={() => gradio.dispatch("clear")}

View File

@ -12,7 +12,7 @@
export let show_label: boolean;
export let root: string;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let upload_component: Upload;
let uploading = false;

View File

@ -23,7 +23,7 @@ const preview: Preview = {
null,
formatter,
// @ts-ignore
{ client: { fetch_implementation() {}, upload() {} } }
{ client: { fetch() {}, upload() {} } }
)
},
argTypes: {

View File

@ -20,7 +20,7 @@
export let show_progress = true;
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let upload_id: string;
let file_data: FileData[];

View File

@ -7,9 +7,9 @@
export let upload_id: string;
export let root: string;
export let files: FileData[];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
let event_source: ReturnType<Client["eventSource_factory"]>;
let stream: ReturnType<Client["stream_factory"]>;
let progress = false;
let current_file_upload: FileDataWithProgress;
let file_to_display: FileDataWithProgress;
@ -38,19 +38,19 @@
}
onMount(() => {
event_source = stream_handler(
stream = stream_handler(
new URL(`${root}/upload_progress?upload_id=${upload_id}`)
);
if (event_source == null) {
if (stream == null) {
throw new Error("Event source is not defined");
}
// Event listener for progress updates
event_source.onmessage = async function (event) {
stream.onmessage = async function (event) {
const _data = JSON.parse(event.data);
if (!progress) progress = true;
if (_data.msg === "done") {
event_source?.close();
stream?.close();
dispatch("done");
} else {
current_file_upload = _data;
@ -59,7 +59,7 @@
};
});
onDestroy(() => {
if (event_source != null || event_source != undefined) event_source.close();
if (stream != null || stream != undefined) stream.close();
});
function calculateTotalProgress(files: FileData[]): number {

View File

@ -208,7 +208,7 @@
i18n={gradio.i18n}
max_file_size={gradio.max_file_size}
upload={gradio.client.upload}
stream_handler={gradio.client.eventSource_factory}
stream_handler={gradio.client.stream_factory}
>
<UploadText i18n={gradio.i18n} type="video" />
</Video>

View File

@ -30,7 +30,7 @@
export let handle_reset_value: () => void = () => {};
export let max_file_size: number | null = null;
export let upload: Client["upload"];
export let stream_handler: Client["eventSource_factory"];
export let stream_handler: Client["stream_factory"];
const dispatch = createEventDispatcher<{
change: FileData | null;