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

Enforce storage quota before upload #8385

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

MichaelBuessemeyer
Copy link
Contributor

@MichaelBuessemeyer MichaelBuessemeyer commented Feb 6, 2025

Currently, the storage quota enforcement does not consider the size of the current upload. With these changes the upload sends it upload size so the check can be done including the size of the dataset that should be uploaded. The backend auto rejects in case the total sum overflows the allowed storage quota. Additionally, the backend automatically rejects chucks which would overflow the reserved amount of bytes for the upload.

URL of deployed dev instance (used for testing):

  • https://___.webknossos.xyz

Steps to test:

  • I suggest testing locally
  • Just upload a dataset via the frontend. Everything should be working nicely.
  • Open the frontend file dataset_upload_view.tsx and edit line 319 to force it to be less bytes than the dataset you now want to upload. Then save and reload the frontend.
  • Try uploading the dataset, during upload the request should fail as the frontend tries to upload more bytes than originally reserved with the request
  • Undo the dataset_upload_view.tsx file changes
  • Open the database and restrict the allowed storage amount of the default orga such that the next dataset you want to upload should exceed the limit.
    • in application.conf set
    fetchUsedStorage {
      rescanInterval = 30 seconds # do not scan organizations whose last scan is more recent than this
      tickerInterval = 10 seconds # scan some organizations at each tick
      scansPerTick = 10 # scan x organizations at each tick
    }
    
    • and reportUsedStorage.enabled = true
    • And set organization plan to Team or so (not sure whether that necessary)
  • Now try to upload the dataset. The request should also fail.

TODOs:

  • rename totalFileSize to totalFileSizeInBytes
  • Clean up redis keys upon successful upload
  • When the reserve upload is rejected because the new dataset would exceed the orgas storage quota, the error sent by the backend to the frontend is nested and not so clear:
    image
    Do you have an improvement idea?

Issues:


(Please delete unneeded items, merge only when none are left open)

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

📝 Walkthrough

Walkthrough

This pull request enhances the dataset upload process by incorporating the total file size into storage quota validations. The frontend now calculates the total file size of the files to be uploaded and passes this information to the backend. Consequently, several backend components, including the reserve and upload methods across multiple controllers and services, have been updated to consider the incoming upload size when validating available storage. Additionally, a new error message is introduced to handle cases where the upload exceeds the reserved space.

Changes

File(s) Change Summary
app/.../WKRemoteDataStoreController.scala Updated reserveDatasetUpload to check if usedStorageBytes + totalFileSize is within the storage quota.
webknossos-datastore/.../DataSourceController.scala Modified reserveManualUpload and add methods to include an optional totalFileSize parameter for improved upload reservation logic.
frontend/javascripts/.../dataset_upload_view.tsx Added a new variable totalFileSize (using a reduce method) in handleSubmit to send total file size information to the backend.
webknossos-datastore/.../ComposeService.scala
webknossos-datastore/.../UploadService.scala
Updated ReserveUploadInformation to include a totalFileSize field; in UploadService, added Redis key methods and logic for managing total file size.
conf/messages Introduced a new error message (dataset.upload.moreBytesThanReserved) for notifying users when the uploaded dataset exceeds the reserved size.

Assessment against linked issues

Objective ([#7962]) Addressed Explanation
Enforce storage quota by validating total upload size pre-upload and during each chunk upload

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • fm3

Poem

I'm a rabbit with a twirl and a hop,
Guiding uploads from bottom to top.
Bytes add up with a skip and a cheer,
Ensuring quota is always clear.
With each change, the process is tight—
Hoppy code makes everything right!
🐇🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f131d94 and aeb062c.

📒 Files selected for processing (2)
  • frontend/javascripts/admin/dataset/dataset_upload_view.tsx (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/UploadService.scala (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/javascripts/admin/dataset/dataset_upload_view.tsx
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/UploadService.scala
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: circleci_build

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MichaelBuessemeyer MichaelBuessemeyer marked this pull request as ready for review February 6, 2025 15:27
@MichaelBuessemeyer
Copy link
Contributor Author

@fm3 Would you please take a look at this PR? The changes in the frontend are very minimal right now. So it should be ok if no frontend dev takes a look at it imo.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5447c6e and 43a60e1.

📒 Files selected for processing (6)
  • app/controllers/WKRemoteDataStoreController.scala (1 hunks)
  • conf/messages (1 hunks)
  • frontend/javascripts/admin/dataset/dataset_upload_view.tsx (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/DataSourceController.scala (3 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/ComposeService.scala (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/UploadService.scala (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: circleci_build
🔇 Additional comments (9)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/ComposeService.scala (1)

64-64: LGTM!

The addition of None for the totalFileSize parameter is correct, as this service is used for composing datasets rather than direct uploads.

conf/messages (1)

113-113: LGTM!

The error message is clear and provides helpful guidance to users when they exceed their reserved upload size.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/UploadService.scala (3)

38-38: LGTM!

The addition of totalFileSize field to ReserveUploadInformation is appropriate.


129-132: LGTM!

The Redis key definitions for tracking total and current upload sizes follow the existing naming convention.


651-652: LGTM!

The cleanup of Redis keys in removeFromRedis is complete and correct.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/DataSourceController.scala (2)

125-125: LGTM! Added totalFileSize parameter for storage quota validation.

The addition of the totalFileSize parameter in the ReserveUploadInformation constructor aligns with the PR's objective to enforce storage quota before upload.


417-417: LGTM! Added totalFileSize parameter for storage quota validation.

The addition of the totalFileSize parameter in the ReserveUploadInformation constructor is consistent with the changes in the manual upload method.

frontend/javascripts/admin/dataset/dataset_upload_view.tsx (2)

319-319: LGTM! Correctly calculates total file size.

The implementation uses reduce to calculate the total size of all files, which is an efficient approach.


328-328: LGTM! Added totalFileSize to upload information.

The calculated total file size is correctly included in the reserveUploadInformation object sent to the backend.

@@ -73,7 +73,7 @@ class WKRemoteDataStoreController @Inject()(
uploadInfo.organization) ~> NOT_FOUND
usedStorageBytes <- organizationDAO.getUsedStorage(organization._id)
_ <- Fox.runOptional(organization.includedStorageBytes)(includedStorage =>
bool2Fox(usedStorageBytes <= includedStorage)) ?~> "dataset.upload.storageExceeded" ~> FORBIDDEN
bool2Fox(usedStorageBytes + uploadInfo.totalFileSize.getOrElse(0L) <= includedStorage)) ?~> "dataset.upload.storageExceeded" ~> FORBIDDEN
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider requiring totalFileSize for uploads.

The current implementation uses getOrElse(0L) which could silently pass the quota check if totalFileSize is None. Consider making totalFileSize a required field for uploads to prevent accidentally bypassing the quota check.

-bool2Fox(usedStorageBytes + uploadInfo.totalFileSize.getOrElse(0L) <= includedStorage)
+uploadInfo.totalFileSize match {
+  case Some(size) => bool2Fox(usedStorageBytes + size <= includedStorage)
+  case None => Fox.failure("dataset.upload.totalFileSizeRequired")
+}

Also add this message to conf/messages:

dataset.upload.totalFileSizeRequired=Total file size must be provided for uploads to enforce storage quota.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bool2Fox(usedStorageBytes + uploadInfo.totalFileSize.getOrElse(0L) <= includedStorage)) ?~> "dataset.upload.storageExceeded" ~> FORBIDDEN
uploadInfo.totalFileSize match {
case Some(size) => bool2Fox(usedStorageBytes + size <= includedStorage)
case None => Fox.failure("dataset.upload.totalFileSizeRequired")
} ?~> "dataset.upload.storageExceeded" ~> FORBIDDEN

Comment on lines 256 to 262
totalFileSize <- runningUploadMetadataStore.find(redisKeyForTotalFileSize(uploadId))
_ <- Fox.runOptional(totalFileSize) { maxFileSize =>
runningUploadMetadataStore
.find(redisKeyForCurrentUploadedTotalFileSize(uploadId))
.flatMap(alreadyUploadedAmountOfBytes =>
bool2Fox(alreadyUploadedAmountOfBytes.getOrElse("0").toLong + chunkSize <= maxFileSize.toLong))
} ?~> "dataset.upload.moreBytesThanReserved"
Copy link
Contributor

@coderabbitai coderabbitai bot Feb 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential race condition in size validation.

The current implementation has a race condition between checking the total size and updating it. Multiple concurrent uploads could each pass the check but collectively exceed the limit.

-totalFileSize <- runningUploadMetadataStore.find(redisKeyForTotalFileSize(uploadId))
-_ <- Fox.runOptional(totalFileSize) { maxFileSize =>
-  runningUploadMetadataStore
-    .find(redisKeyForCurrentUploadedTotalFileSize(uploadId))
-    .flatMap(alreadyUploadedAmountOfBytes =>
-      bool2Fox(alreadyUploadedAmountOfBytes.getOrElse("0").toLong + chunkSize <= maxFileSize.toLong))
-} ?~> "dataset.upload.moreBytesThanReserved"
+_ <- runningUploadMetadataStore.withLock(s"upload_size_check_$uploadId") {
+  for {
+    totalFileSize <- runningUploadMetadataStore.find(redisKeyForTotalFileSize(uploadId))
+    _ <- Fox.runOptional(totalFileSize) { maxFileSize =>
+      for {
+        currentSize <- runningUploadMetadataStore.find(redisKeyForCurrentUploadedTotalFileSize(uploadId))
+        newSize = currentSize.getOrElse("0").toLong + chunkSize
+        _ <- bool2Fox(newSize <= maxFileSize.toLong) ?~> "dataset.upload.moreBytesThanReserved"
+        _ <- runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(uploadId), 
+               String.valueOf(newSize))
+      } yield ()
+    }
+  } yield ()
+}

Also add a method to DataStoreRedisStore:

def withLock[T](key: String)(f: => Fox[T]): Fox[T] = {
  // Implement Redis-based distributed locking
  // Consider using Redisson or other battle-tested implementations
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that might actually be a thing. Will take a look at it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MichaelBuessemeyer Thanks for considering this feedback! Let me know if you need any help with implementing the distributed locking solution.

(_/)

(^.^)

(> <) Thanks for the feedback!


✏️ Learnings added
Learnt from: MichaelBuessemeyer
PR: scalableminds/webknossos#8385
File: webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/uploading/UploadService.scala:256-262
Timestamp: 2025-02-07T09:22:54.315Z
Learning: The size validation in UploadService should use distributed locking to prevent race conditions between checking the total size and updating it, as multiple concurrent uploads could collectively exceed the limit.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines 171 to 179
_ <- Fox.runOptional(reserveUploadInfo.totalFileSize) { fileSize =>
Fox.combined(
List(
runningUploadMetadataStore.insert(redisKeyForTotalFileSize(reserveUploadInfo.uploadId),
String.valueOf(fileSize)),
runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
))
}
_ <- runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix duplicate initialization of currentUploadedTotalFileSize.

The currentUploadedTotalFileSize is initialized twice:

  1. Inside the Fox.runOptional(reserveUploadInfo.totalFileSize) block
  2. Immediately after the block
 _ <- Fox.runOptional(reserveUploadInfo.totalFileSize) { fileSize =>
   Fox.combined(
     List(
       runningUploadMetadataStore.insert(redisKeyForTotalFileSize(reserveUploadInfo.uploadId),
                                         String.valueOf(fileSize)),
       runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
     ))
 }
-_ <- runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_ <- Fox.runOptional(reserveUploadInfo.totalFileSize) { fileSize =>
Fox.combined(
List(
runningUploadMetadataStore.insert(redisKeyForTotalFileSize(reserveUploadInfo.uploadId),
String.valueOf(fileSize)),
runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
))
}
_ <- runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
_ <- Fox.runOptional(reserveUploadInfo.totalFileSize) { fileSize =>
Fox.combined(
List(
runningUploadMetadataStore.insert(redisKeyForTotalFileSize(reserveUploadInfo.uploadId),
String.valueOf(fileSize)),
runningUploadMetadataStore.insert(redisKeyForCurrentUploadedTotalFileSize(reserveUploadInfo.uploadId), "0")
))
}

Michael Büßemeyer added 2 commits February 7, 2025 10:38
…ableminds/webknossos into enforce-storage-quota-before-upload
@@ -324,6 +325,7 @@ class DatasetUploadView extends React.Component<PropsWithFormAndRouter, State> {
organization: activeUser.organization,
totalFileCount: formValues.zipFile.length,
filePaths: filePaths,
totalFileSizeInBytes,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @markbader,

here are the changes I mentioned which would need to be added to wklibs when uploading a dataset. Simply put: the initial reserve upload request now needs a new parameter called totalFileSizeInBytes which is the sum of all files' sizes in bytes. The rest is backend work and no more changes are needed.

Old wklibs version should still work as this parameter is optional for now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enforce Storage Quota already before upload
1 participant