Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: gracefully handle download errors #1058

Merged
merged 9 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/modern-numbers-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"uploadthing": patch
---

fix: gracefully handle download errors in `utapi.uploadFilesFromUrl`
124 changes: 57 additions & 67 deletions packages/uploadthing/src/sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@ import {
HttpClientResponse,
} from "@effect/platform";
import * as Arr from "effect/Array";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import type * as ManagedRuntime from "effect/ManagedRuntime";
import * as Predicate from "effect/Predicate";
import type { ManagedRuntime } from "effect/ManagedRuntime";
import * as Redacted from "effect/Redacted";
import * as S from "effect/Schema";

import type {
ACL,
FetchEsque,
MaybeUrl,
SerializedUploadThingError,
} from "@uploadthing/shared";
import type { ACL, FetchEsque, MaybeUrl } from "@uploadthing/shared";
import { parseTimeToSeconds, UploadThingError } from "@uploadthing/shared";

import { ApiUrl, UPLOADTHING_VERSION, UTToken } from "../internal/config";
Expand All @@ -36,14 +31,14 @@ import type {
UTApiOptions,
} from "./types";
import { UTFile } from "./ut-file";
import { downloadFiles, guardServerOnly, uploadFilesInternal } from "./utils";
import { downloadFile, guardServerOnly, uploadFile } from "./utils";

export { UTFile };

export class UTApi {
private fetch: FetchEsque;
private defaultKeyType: "fileKey" | "customId";
private runtime: ManagedRuntime.ManagedRuntime<
private runtime: ManagedRuntime<
HttpClient.HttpClient | FetchHttpClient.Fetch,
UploadThingError
>;
Expand Down Expand Up @@ -89,13 +84,16 @@ export class UTApi {
program: Effect.Effect<A, E, HttpClient.HttpClient>,
signal?: AbortSignal,
) => {
const result = await program.pipe(
const exit = await program.pipe(
Effect.withLogSpan("utapi.#executeAsync"),
(e) => this.runtime.runPromise(e, signal ? { signal } : undefined),
(e) => this.runtime.runPromiseExit(e, signal ? { signal } : undefined),
);

await this.runtime.dispose();
return result;
if (exit._tag === "Failure") {
throw Cause.squash(exit.cause);
}

return exit.value;
juliusmarminge marked this conversation as resolved.
Show resolved Hide resolved
};

/**
Expand All @@ -118,31 +116,35 @@ export class UTApi {
files: FileEsque[],
opts?: UploadFilesOptions,
): Promise<UploadFileResult[]>;
async uploadFiles(
uploadFiles(
files: FileEsque | FileEsque[],
opts?: UploadFilesOptions,
): Promise<UploadFileResult | UploadFileResult[]> {
guardServerOnly();

const uploads = await this.executeAsync(
Effect.flatMap(
uploadFilesInternal({
files: Arr.ensure(files),
contentDisposition: opts?.contentDisposition ?? "inline",
acl: opts?.acl,
const program: Effect.Effect<
UploadFileResult | UploadFileResult[],
never,
HttpClient.HttpClient
> = Effect.forEach(Arr.ensure(files), (file) =>
uploadFile(file, opts ?? {}).pipe(
Effect.match({
onSuccess: (data) => ({ data, error: null }),
onFailure: (error) => ({ data: null, error }),
}),
(ups) => Effect.succeed(Array.isArray(files) ? ups : ups[0]),
).pipe(
Effect.tap((res) =>
Effect.logDebug("Finished uploading").pipe(
Effect.annotateLogs("uploadResult", res),
),
),
).pipe(
Effect.map((ups) => (Array.isArray(files) ? ups : ups[0])),
Effect.tap((res) =>
Effect.logDebug("Finished uploading").pipe(
Effect.annotateLogs("uploadResult", res),
),
Effect.withLogSpan("uploadFiles"),
),
opts?.signal,
Effect.withLogSpan("uploadFiles"),
);
return uploads;

// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.executeAsync(program, opts?.signal) as any;
juliusmarminge marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand All @@ -166,49 +168,37 @@ export class UTApi {
urls: (MaybeUrl | UrlWithOverrides)[],
opts?: UploadFilesOptions,
): Promise<UploadFileResult[]>;
async uploadFilesFromUrl(
uploadFilesFromUrl(
urls: MaybeUrl | UrlWithOverrides | (MaybeUrl | UrlWithOverrides)[],
opts?: UploadFilesOptions,
): Promise<UploadFileResult | UploadFileResult[]> {
guardServerOnly();

const downloadErrors: Record<number, SerializedUploadThingError> = {};
const arr = Arr.ensure(urls);

const program = Effect.gen(function* () {
const downloadedFiles = yield* downloadFiles(arr, downloadErrors).pipe(
Effect.map((files) => Arr.filter(files, Predicate.isNotNullable)),
);

yield* Effect.logDebug(
`Downloaded ${downloadedFiles.length}/${arr.length} files`,
).pipe(Effect.annotateLogs("downloadedFiles", downloadedFiles));

const uploads = yield* uploadFilesInternal({
files: downloadedFiles,
contentDisposition: opts?.contentDisposition ?? "inline",
acl: opts?.acl,
});

/** Put it all back together, preserve the order of files */
const responses = arr.map((_, index) => {
if (downloadErrors[index]) {
return { data: null, error: downloadErrors[index] };
}
return uploads.shift()!;
});

/** Return single object or array based on input urls */
const uploadFileResponse = Array.isArray(urls) ? responses : responses[0];
yield* Effect.logDebug("Finished uploading").pipe(
Effect.annotateLogs("uploadResult", uploadFileResponse),
Effect.withLogSpan("utapi.uploadFilesFromUrl"),
);

return uploadFileResponse;
}).pipe(Effect.withLogSpan("uploadFilesFromUrl"));
const program: Effect.Effect<
UploadFileResult | UploadFileResult[],
never,
HttpClient.HttpClient
> = Effect.forEach(Arr.ensure(urls), (url) =>
downloadFile(url).pipe(
Effect.flatMap((file) => uploadFile(file, opts ?? {})),
Effect.match({
onSuccess: (data) => ({ data, error: null }),
onFailure: (error) => ({ data: null, error }),
}),
),
)
.pipe(
Effect.map((ups) => (Array.isArray(urls) ? ups : ups[0])),
Effect.tap((res) =>
Effect.logDebug("Finished uploading").pipe(
Effect.annotateLogs("uploadResult", res),
),
),
Effect.withLogSpan("uploadFiles"),
)
.pipe(Effect.withLogSpan("uploadFilesFromUrl"));

return await this.executeAsync(program, opts?.signal);
return this.executeAsync(program, opts?.signal);
juliusmarminge marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
Loading
Loading