Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

normal put

Manav Rathib68d95d48190
diff --git a/web/apps/photos/src/services/upload-manager.ts b/web/apps/photos/src/services/upload-manager.ts
index 17034a4eb5..13dd2220cb 100644
--- a/web/apps/photos/src/services/upload-manager.ts
+++ b/web/apps/photos/src/services/upload-manager.ts
@@ -1,4 +1,3 @@
-import { Canceler } from "axios";
import { isDesktop } from "ente-base/app";
import { createComlinkCryptoWorker } from "ente-base/crypto";
import { type CryptoWorker } from "ente-base/crypto/worker";
@@ -7,7 +6,6 @@ import type { PublicAlbumsCredentials } from "ente-base/http";
import log from "ente-base/log";
import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import {
- RANDOM_PERCENTAGE_PROGRESS_FOR_PUT,
markUploadedAndObtainProcessableItem,
shouldDisableCFUploadProxy,
type ClusteredUploadItem,
@@ -267,50 +265,6 @@ class UIService {
);
this.updateProgressBarUI();
}
-
- trackUploadProgress(
- fileLocalID: number,
- percentPerPart = RANDOM_PERCENTAGE_PROGRESS_FOR_PUT(),
- index = 0,
- ) {
- const cancel: { exec: Canceler } = { exec: () => {} };
- const cancelTimedOutRequest = () => cancel.exec("Request timed out");
-
- const cancelCancelledUploadRequest = () =>
- cancel.exec(CustomError.UPLOAD_CANCELLED);
-
- let timeout = null;
- const resetTimeout = () => {
- if (timeout) {
- clearTimeout(timeout);
- }
- timeout = setTimeout(cancelTimedOutRequest, 30 * 1000 /* 30 sec */);
- };
- return {
- cancel,
- onUploadProgress: (event) => {
- this.inProgressUploads.set(
- fileLocalID,
- Math.min(
- Math.round(
- percentPerPart * index +
- (percentPerPart * event.loaded) / event.total,
- ),
- 98,
- ),
- );
- this.updateProgressBarUI();
- if (event.loaded === event.total) {
- clearTimeout(timeout);
- } else {
- resetTimeout();
- }
- if (uploadCancelService.isUploadCancelationRequested()) {
- cancelCancelledUploadRequest();
- }
- },
- };
- }
}
function convertInProgressUploadsToList(inProgressUploads) {
@@ -568,6 +522,12 @@ class UploadManager {
private async uploadNextItemInQueue(worker: CryptoWorker) {
const uiService = this.uiService;
+ const uploadContext = {
+ isCFUploadProxyDisabled: shouldDisableCFUploadProxy(),
+ abortIfCancelled: this.abortIfCancelled.bind(this),
+ updateUploadProgress:
+ uiService.updateUploadProgress.bind(uiService),
+ };
while (this.itemsToBeUploaded.length > 0) {
this.abortIfCancelled();
@@ -581,29 +541,12 @@ class UploadManager {
uiService.setFileProgress(localID, 0);
await wait(0);
- const uploadContext = {
- isCFUploadProxyDisabled: shouldDisableCFUploadProxy(),
- abortIfCancelled: this.abortIfCancelled.bind(this),
- updateUploadProgress:
- uiService.updateUploadProgress.bind(uiService),
- };
-
const { uploadResult, uploadedFile } = await upload(
uploadableItem,
this.uploaderName,
this.existingFiles,
this.parsedMetadataJSONMap,
worker,
- (
- fileLocalID: number,
- percentPerPart?: number,
- index?: number,
- ) =>
- uiService.trackUploadProgress(
- fileLocalID,
- percentPerPart,
- index,
- ),
uploadContext,
);
@@ -613,8 +556,8 @@ class UploadManager {
uploadedFile,
);
- this.uiService.moveFileToResultList(localID, finalUploadResult);
- this.uiService.increaseFileUploaded();
+ uiService.moveFileToResultList(localID, finalUploadResult);
+ uiService.increaseFileUploaded();
UploadService.reducePendingUploadCount();
}
}
diff --git a/web/packages/gallery/services/upload/remote.ts b/web/packages/gallery/services/upload/remote.ts
index eccc114ec4..71b51ad3bf 100644
--- a/web/packages/gallery/services/upload/remote.ts
+++ b/web/packages/gallery/services/upload/remote.ts
@@ -14,7 +14,7 @@ import {
import log from "ente-base/log";
import { apiURL, uploaderOrigin } from "ente-base/origins";
import { type EnteFile } from "ente-media/file";
-import { CustomError, handleUploadError } from "ente-shared/error";
+import { handleUploadError } from "ente-shared/error";
import HTTPService from "ente-shared/network/HTTPService";
import { nullToUndefined } from "ente-utils/transform";
import { z } from "zod";
@@ -104,70 +104,46 @@ export class PhotosUploadHTTPClient {
throw e;
}
}
+}
- async putFile(
- fileUploadURL: ObjectUploadURL,
- file: Uint8Array,
- progressTracker: unknown,
- ): Promise<string> {
- try {
- await retryAsyncOperation(
- () =>
- HTTPService.put(
- fileUploadURL.url,
- file,
- // @ts-ignore
- null,
- null,
- progressTracker,
- ),
- handleUploadError,
- );
- return fileUploadURL.objectKey;
- } catch (e) {
- if (
- !(
- e instanceof Error &&
- e.message == CustomError.UPLOAD_CANCELLED
- )
- ) {
- log.error("putFile to dataStore failed ", e);
- }
- throw e;
- }
- }
+/**
+ * Upload a file using a pre-signed URL.
+ *
+ * @param fileUploadURL A pre-signed URL that can be used to upload data to the
+ * remote S3-compatible storage.
+ *
+ * @param fileData The data to upload.
+ *
+ * @param retrier A function to wrap the request in retries if needed.
+ */
+export const putFile = async (
+ fileUploadURL: string,
+ fileData: Uint8Array,
+ retrier: HTTPRequestRetrier,
+) =>
+ retrier(() =>
+ fetch(fileUploadURL, {
+ method: "PUT",
+ headers: publicRequestHeaders(),
+ body: fileData,
+ }),
+ );
- async putFileV2(
- fileUploadURL: ObjectUploadURL,
- file: Uint8Array,
- progressTracker: unknown,
- ): Promise<string> {
- try {
- const origin = await uploaderOrigin();
- await retryAsyncOperation(() =>
- HTTPService.put(
- `${origin}/file-upload`,
- file,
- // @ts-ignore
- null,
- { "UPLOAD-URL": fileUploadURL.url },
- progressTracker,
- ),
- );
- return fileUploadURL.objectKey;
- } catch (e) {
- if (
- !(
- e instanceof Error &&
- e.message == CustomError.UPLOAD_CANCELLED
- )
- ) {
- log.error("putFile to dataStore failed ", e);
- }
- throw e;
- }
- }
-}
+/**
+ * Variant of {@link putFile} that uses a CF worker.
+ */
+export const putFileViaWorker = async (
+ fileUploadURL: string,
+ fileData: Uint8Array,
+ retrier: HTTPRequestRetrier,
+) =>
+ retrier(async () =>
+ fetch(`${await uploaderOrigin()}/file-upload`, {
+ method: "PUT",
+ headers: { ...publicRequestHeaders(), "UPLOAD-URL": fileUploadURL },
+ body: fileData,
+ }),
+ );
/**
* Upload a part of a multipart upload using a pre-signed URL.
@@ -316,6 +292,8 @@ const createMultipartUploadRequestBody = (
* @param completedParts Information about all the parts of the file that have
* been uploaded. The part numbers must start at 1 and must be consecutive.
*
+ * @param retrier A function to wrap the request in retries if needed.
+ *
* [Note: Multipart uploads]
*
* Multipart uploads are a mechanism to upload large files onto an remote
@@ -363,12 +341,15 @@ const createMultipartUploadRequestBody = (
export const completeMultipartUpload = (
completionURL: string,
completedParts: MultipartCompletedPart[],
+ retrier: HTTPRequestRetrier,
) =>
- fetch(completionURL, {
- method: "POST",
- headers: { ...publicRequestHeaders(), "Content-Type": "text/xml" },
- body: createMultipartUploadRequestBody(completedParts),
- });
+ retrier(() =>
+ fetch(completionURL, {
+ method: "POST",
+ headers: { ...publicRequestHeaders(), "Content-Type": "text/xml" },
+ body: createMultipartUploadRequestBody(completedParts),
+ }),
+ );
/**
* Variant of {@link completeMultipartUpload} that uses a CF worker.
@@ -376,16 +357,19 @@ export const completeMultipartUpload = (
export const completeMultipartUploadViaWorker = async (
completionURL: string,
completedParts: MultipartCompletedPart[],
+ retrier: HTTPRequestRetrier,
) =>
- fetch(`${await uploaderOrigin()}/multipart-complete`, {
- method: "POST",
- headers: {
- ...publicRequestHeaders(),
- "Content-Type": "text/xml",
- "UPLOAD-URL": completionURL,
- },
- body: createMultipartUploadRequestBody(completedParts),
- });
+ retrier(async () =>
+ fetch(`${await uploaderOrigin()}/multipart-complete`, {
+ method: "POST",
+ headers: {
+ ...publicRequestHeaders(),
+ "Content-Type": "text/xml",
+ "UPLOAD-URL": completionURL,
+ },
+ body: createMultipartUploadRequestBody(completedParts),
+ }),
+ );
/**
* Lowest layer for file upload related HTTP operations when we're running in
diff --git a/web/packages/gallery/services/upload/upload-service.ts b/web/packages/gallery/services/upload/upload-service.ts
index 1422972674..8e4cc73933 100644
--- a/web/packages/gallery/services/upload/upload-service.ts
+++ b/web/packages/gallery/services/upload/upload-service.ts
@@ -65,8 +65,10 @@ import {
completeMultipartUploadViaWorker,
PhotosUploadHTTPClient,
PublicAlbumsUploadHTTPClient,
+ putFile,
putFilePart,
putFilePartViaWorker,
+ putFileViaWorker,
type MultipartCompletedPart,
type ObjectUploadURL,
} from "./remote";
@@ -533,19 +535,6 @@ const uploadItemCreationDate = async (
return parsedMetadata?.creationDate?.timestamp;
};
-/**
- * A function that can be called to obtain a "progressTracker" that then is
- * directly fed to axios to both cancel the upload if needed, and update the
- * progress status.
- *
- * Enhancement: The return value needs to be typed.
- */
-type MakeProgressTracker = (
- fileLocalID: number,
- percentPerPart?: number,
- index?: number,
-) => unknown;
-
/**
* Some state and callbacks used during upload that are not tied to a specific
* file being uploaded.
@@ -597,7 +586,6 @@ export const upload = async (
existingFiles: EnteFile[],
parsedMetadataJSONMap: Map<string, ParsedMetadataJSON>,
worker: CryptoWorker,
- makeProgressTracker: MakeProgressTracker,
uploadContext: UploadContext,
): Promise<UploadResponse> => {
const { abortIfCancelled } = uploadContext;
@@ -704,10 +692,11 @@ export const upload = async (
const backupedFile = await uploadToBucket(
encryptedFilePieces,
- makeProgressTracker,
uploadContext,
);
+ abortIfCancelled();
+
const uploadedFile = await uploadService.uploadFile({
collectionID: collection.id,
encryptedKey: encryptedFileKey.encryptedData,
@@ -1494,95 +1483,82 @@ const encryptFileStream = async (
const uploadToBucket = async (
encryptedFilePieces: EncryptedFilePieces,
- makeProgressTracker: MakeProgressTracker,
uploadContext: UploadContext,
): Promise<BackupedFile> => {
- const { isCFUploadProxyDisabled } = uploadContext;
+ const { isCFUploadProxyDisabled, abortIfCancelled, updateUploadProgress } =
+ uploadContext;
const { localID, file, thumbnail, metadata, pubMagicMetadata } =
encryptedFilePieces;
- try {
- let fileObjectKey: string;
- let fileSize: number;
- const encryptedData = file.encryptedData;
- if (
- !(encryptedData instanceof Uint8Array) &&
- encryptedData.chunkCount >= multipartChunksPerPart
- ) {
- // We have a stream, and it is more than multipartChunksPerPart
- // chunks long, so use a multipart upload to upload it.
- ({ objectKey: fileObjectKey, fileSize } =
- await uploadStreamUsingMultipart(
- localID,
- encryptedData,
- uploadContext,
- ));
- } else {
- const data =
- encryptedData instanceof Uint8Array
- ? encryptedData
- : await readEntireStream(encryptedData.stream);
- fileSize = data.length;
-
- const progressTracker = makeProgressTracker(localID);
- const fileUploadURL = await uploadService.getUploadURL();
- if (!isCFUploadProxyDisabled) {
- fileObjectKey = await photosHTTPClient.putFileV2(
- fileUploadURL,
- data,
- progressTracker,
- );
- } else {
- fileObjectKey = await photosHTTPClient.putFile(
- fileUploadURL,
- data,
- progressTracker,
- );
- }
- }
- const thumbnailUploadURL = await uploadService.getUploadURL();
- let thumbnailObjectKey: string;
+ const requestRetrier = createAbortableRetryEnsuringHTTPOk(abortIfCancelled);
+
+ let fileObjectKey: string;
+ let fileSize: number;
+
+ const encryptedData = file.encryptedData;
+ if (
+ !(encryptedData instanceof Uint8Array) &&
+ encryptedData.chunkCount >= multipartChunksPerPart
+ ) {
+ // We have a stream, and it is more than multipartChunksPerPart
+ // chunks long, so use a multipart upload to upload it.
+ ({ objectKey: fileObjectKey, fileSize } =
+ await uploadStreamUsingMultipart(
+ localID,
+ encryptedData,
+ uploadContext,
+ requestRetrier,
+ ));
+ } else {
+ const data =
+ encryptedData instanceof Uint8Array
+ ? encryptedData
+ : await readEntireStream(encryptedData.stream);
+ fileSize = data.length;
+
+ const fileUploadURL = await uploadService.getUploadURL();
+ fileObjectKey = fileUploadURL.objectKey;
if (!isCFUploadProxyDisabled) {
- thumbnailObjectKey = await photosHTTPClient.putFileV2(
- thumbnailUploadURL,
- thumbnail.encryptedData,
- null,
- );
+ await putFileViaWorker(fileUploadURL.url, data, requestRetrier);
} else {
- thumbnailObjectKey = await photosHTTPClient.putFile(
- thumbnailUploadURL,
- thumbnail.encryptedData,
- null,
- );
+ await putFile(fileUploadURL.url, data, requestRetrier);
}
+ updateUploadProgress(localID, RANDOM_PERCENTAGE_PROGRESS_FOR_PUT(), 1);
+ }
- const backupedFile: BackupedFile = {
- file: {
- decryptionHeader: file.decryptionHeader,
- objectKey: fileObjectKey,
- size: fileSize,
- },
- thumbnail: {
- decryptionHeader: thumbnail.decryptionHeader,
- objectKey: thumbnailObjectKey,
- size: thumbnail.encryptedData.length,
- },
- metadata: {
- encryptedData: metadata.encryptedDataB64,
- decryptionHeader: metadata.decryptionHeaderB64,
- },
- pubMagicMetadata: pubMagicMetadata,
- };
- return backupedFile;
- } catch (e) {
- if (
- !(e instanceof Error && e.message == CustomError.UPLOAD_CANCELLED)
- ) {
- log.error("Error when uploading to bucket", e);
- }
- throw e;
+ const thumbnailUploadURL = await uploadService.getUploadURL();
+ if (!isCFUploadProxyDisabled) {
+ await putFileViaWorker(
+ thumbnailUploadURL.url,
+ thumbnail.encryptedData,
+ requestRetrier,
+ );
+ } else {
+ await putFile(
+ thumbnailUploadURL.url,
+ thumbnail.encryptedData,
+ requestRetrier,
+ );
}
+
+ return {
+ file: {
+ decryptionHeader: file.decryptionHeader,
+ objectKey: fileObjectKey,
+ size: fileSize,
+ },
+ thumbnail: {
+ decryptionHeader: thumbnail.decryptionHeader,
+ objectKey: thumbnailUploadURL.objectKey,
+ size: thumbnail.encryptedData.length,
+ },
+ metadata: {
+ encryptedData: metadata.encryptedDataB64,
+ decryptionHeader: metadata.decryptionHeaderB64,
+ },
+ pubMagicMetadata: pubMagicMetadata,
+ };
};
/**
@@ -1624,16 +1600,15 @@ const uploadStreamUsingMultipart = async (
fileLocalID: number,
dataStream: EncryptedFileStream,
uploadContext: UploadContext,
+ requestRetrier: HTTPRequestRetrier,
) => {
const { isCFUploadProxyDisabled, abortIfCancelled, updateUploadProgress } =
uploadContext;
- const abortableRetryEnsuringHTTPOk =
- createAbortableRetryEnsuringHTTPOk(abortIfCancelled);
-
const uploadPartCount = Math.ceil(
dataStream.chunkCount / multipartChunksPerPart,
);
+
const multipartUploadURLs =
await uploadService.fetchMultipartUploadURLs(uploadPartCount);
@@ -1659,13 +1634,9 @@ const uploadStreamUsingMultipart = async (
? await putFilePartViaWorker(
partUploadURL,
partData,
- abortableRetryEnsuringHTTPOk,
+ requestRetrier,
)
- : await putFilePart(
- partUploadURL,
- partData,
- abortableRetryEnsuringHTTPOk,
- );
+ : await putFilePart(partUploadURL, partData, requestRetrier);
if (!eTag) throw new Error(CustomErrorMessage.eTagMissing);
updateUploadProgress(fileLocalID, percentPerPart, partNumber);
@@ -1676,12 +1647,16 @@ const uploadStreamUsingMultipart = async (
const completionURL = multipartUploadURLs.completeURL;
if (!isCFUploadProxyDisabled) {
- await abortableRetryEnsuringHTTPOk(() =>
- completeMultipartUploadViaWorker(completionURL, completedParts),
+ await completeMultipartUploadViaWorker(
+ completionURL,
+ completedParts,
+ requestRetrier,
);
} else {
- await abortableRetryEnsuringHTTPOk(() =>
- completeMultipartUpload(completionURL, completedParts),
+ await completeMultipartUpload(
+ completionURL,
+ completedParts,
+ requestRetrier,
);
}