Skip to content

Commit

Permalink
Add presigned_url method.
Browse files Browse the repository at this point in the history
For GCS, return an actual presigned URL for the file. For disk, return a
standard `file://` url. For inmemory, return the original URL, for the
sake of completeness.
  • Loading branch information
danielroseman authored and ivgiuliani committed Oct 29, 2021
1 parent 8954621 commit ee96213
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/bucket_store/disk.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ def delete!(bucket:, key:)
true
end

# rubocop: disable Lint/UnusedMethodArgument
def presigned_url(bucket:, key:, expiry:)
"file://#{key_path(bucket, key)}"
end
# rubocop: enable Lint/UnusedMethodArgument

private

attr_reader :base_dir
Expand Down
4 changes: 4 additions & 0 deletions lib/bucket_store/gcs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ def delete!(bucket:, key:)
true
end

def presigned_url(bucket:, key:, expiry:)
get_bucket(bucket).file(key).signed_url(expires: expiry)
end

private

attr_reader :storage
Expand Down
6 changes: 6 additions & 0 deletions lib/bucket_store/in_memory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,11 @@ def delete!(bucket:, key:)

true
end

# rubocop: disable Lint/UnusedMethodArgument
def presigned_url(bucket:, key:, expiry:)
"inmemory://#{bucket}/#{key}"
end
# rubocop: enable Lint/UnusedMethodArgument
end
end
19 changes: 19 additions & 0 deletions lib/bucket_store/key_storage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,25 @@ def exists?
list.first == "#{adapter_type}://#{bucket}/#{key}"
end

# Generates a pre-signed URL for the referenced key.
#
# @param [Integer] expiry The time to expiry for the URL; defaults to 24 hours.
# @return [String] The pre-signed URL
#
# @example Generate a presigned URL for a file
# BucketStore.for("gcs://bucket/file.txt").presigned_url
def presigned_url(expiry: 86400)
BucketStore.logger.info(event: "key_storage.presigned_url_started")

start = BucketStore::Timing.monotonic_now
url = adapter.presigned_url(bucket: bucket, key: key, expiry: expiry)

BucketStore.logger.info(event: "key_storage.presigned_url_finished",
duration: BucketStore::Timing.monotonic_now - start)

url
end

private

attr_reader :adapter
Expand Down
8 changes: 8 additions & 0 deletions spec/bucket_store/key_storage_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,12 @@ def build_for(key)
expect(build_for("inmemory://bucket/prefix/a").exists?).to be false
end
end

describe "#presigned_url" do
let(:url) { "inmemory://bucket/file1" }

it "returns a URL" do
expect(build_for(url).presigned_url).to eq(url)
end
end
end

0 comments on commit ee96213

Please sign in to comment.