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

Refactoring Credentials #20

Merged
merged 8 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--require spec_helper
3 changes: 3 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ AllCops:

Style/Documentation:
Enabled: false

require:
- rubocop-rspec
4 changes: 3 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ gemspec
group :test, :development do
gem 'dotenv', '~> 3.1', '>= 3.1.2'
gem 'pry-byebug', '~> 3.10', '>= 3.10.1'
gem 'rubocop', '~> 1.63', '>= 1.63.5'
gem 'rspec', '~> 3.13'
gem 'rubocop', '~> 1.64', '>= 1.64.1'
gem 'rubocop-rspec', '~> 3.0', '>= 3.0.1'
end
46 changes: 32 additions & 14 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,33 @@ PATH
specs:
gemini-ai (4.0.0)
event_stream_parser (~> 1.0)
faraday (~> 2.9)
faraday (~> 2.9, >= 2.9.2)
faraday-typhoeus (~> 1.1)
googleauth (~> 1.8)
typhoeus (~> 1.4, >= 1.4.1)

GEM
remote: https://rubygems.org/
specs:
addressable (2.8.6)
public_suffix (>= 2.0.2, < 6.0)
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
ast (2.4.2)
base64 (0.2.0)
byebug (11.1.3)
coderay (1.1.3)
diff-lcs (1.5.1)
dotenv (3.1.2)
ethon (0.16.0)
ffi (>= 1.15.0)
event_stream_parser (1.0.0)
faraday (2.9.0)
faraday (2.9.2)
faraday-net_http (>= 2.0, < 3.2)
faraday-net_http (3.1.0)
net-http
faraday-typhoeus (1.1.0)
faraday (~> 2.0)
typhoeus (~> 1.4)
ffi (1.16.3)
ffi (1.17.0)
google-cloud-env (2.1.1)
faraday (>= 1.0, < 3.a)
googleauth (1.11.0)
Expand All @@ -39,16 +40,16 @@ GEM
os (>= 0.9, < 2.0)
signet (>= 0.16, < 2.a)
json (2.7.2)
jwt (2.8.1)
jwt (2.8.2)
base64
language_server-protocol (3.17.0.3)
method_source (1.1.0)
multi_json (1.15.0)
net-http (0.4.1)
uri
os (1.1.4)
parallel (1.24.0)
parser (3.3.1.0)
parallel (1.25.1)
parser (3.3.3.0)
ast (~> 2.4.1)
racc
pry (0.14.2)
Expand All @@ -57,13 +58,26 @@ GEM
pry-byebug (3.10.1)
byebug (~> 11.0)
pry (>= 0.13, < 0.15)
public_suffix (5.0.5)
racc (1.7.3)
public_suffix (6.0.0)
racc (1.8.0)
rainbow (3.1.1)
regexp_parser (2.9.2)
rexml (3.2.8)
strscan (>= 3.0.9)
rubocop (1.63.5)
rexml (3.3.0)
strscan
rspec (3.13.0)
rspec-core (~> 3.13.0)
rspec-expectations (~> 3.13.0)
rspec-mocks (~> 3.13.0)
rspec-core (3.13.0)
rspec-support (~> 3.13.0)
rspec-expectations (3.13.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-mocks (3.13.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-support (3.13.1)
rubocop (1.64.1)
json (~> 2.3)
language_server-protocol (>= 3.17.0)
parallel (~> 1.10)
Expand All @@ -76,6 +90,8 @@ GEM
unicode-display_width (>= 2.4.0, < 3.0)
rubocop-ast (1.31.3)
parser (>= 3.3.1.0)
rubocop-rspec (3.0.1)
rubocop (~> 1.61)
ruby-progressbar (1.13.0)
signet (0.19.0)
addressable (~> 2.8)
Expand All @@ -95,7 +111,9 @@ DEPENDENCIES
dotenv (~> 3.1, >= 3.1.2)
gemini-ai!
pry-byebug (~> 3.10, >= 3.10.1)
rubocop (~> 1.63, >= 1.63.5)
rspec (~> 3.13)
rubocop (~> 1.64, >= 1.64.1)
rubocop-rspec (~> 3.0, >= 3.0.1)

BUNDLED WITH
2.4.22
3 changes: 2 additions & 1 deletion components/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ module Gemini
module Errors
class GeminiError < StandardError
def initialize(message = nil)
super(message)
super
end
end

class MissingProjectIdError < GeminiError; end
class UnsupportedServiceError < GeminiError; end
class ConflictingCredentialsError < GeminiError; end
class BlockWithoutServerSentEventsError < GeminiError; end

class RequestError < GeminiError
Expand Down
35 changes: 26 additions & 9 deletions controllers/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,24 @@ def initialize(config)
@service = config[:credentials][:service]

unless %w[vertex-ai-api generative-language-api].include?(@service)
raise Errors::UnsupportedServiceError, "Unsupported service: #{@service}"
raise Errors::UnsupportedServiceError, "Unsupported service: '#{@service}'."
end

avoid_conflicting_credentials!(config[:credentials])

if config[:credentials][:api_key]
@authentication = :api_key
@api_key = config[:credentials][:api_key]
elsif config[:credentials][:file_path]
@authentication = :service_account
@authorizer = ::Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open(config[:credentials][:file_path]),
scope: 'https://www.googleapis.com/auth/cloud-platform'
)
elsif config[:credentials][:file_contents]
elsif config[:credentials][:file_path] || config[:credentials][:file_contents]
@authentication = :service_account
json_key_io = if config[:credentials][:file_path]
File.open(config[:credentials][:file_path])
else
StringIO.new(config[:credentials][:file_contents])
end

@authorizer = ::Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: StringIO.new(config[:credentials][:file_contents]),
json_key_io:,
scope: 'https://www.googleapis.com/auth/cloud-platform'
)
else
Expand Down Expand Up @@ -81,6 +83,21 @@ def initialize(config)
end
end

def avoid_conflicting_credentials!(credentials)
conflicting_keys = %i[api_key file_path file_contents]

found = credentials.keys.filter { |key| conflicting_keys.include?(key) }

return unless found.size > 1

message = found.sort.each_with_index.map do |key, i|
i == found.size - 1 ? "or '#{key}'" : "'#{key}'"
end.join(', ')

raise Errors::ConflictingCredentialsError,
"You must choose either #{message}."
end

def predict(payload, server_sent_events: nil, &callback)
result = request(
"#{@model_address}:predict", payload,
Expand Down
2 changes: 1 addition & 1 deletion gemini-ai.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Gem::Specification.new do |spec|
spec.require_paths = ['ports/dsl']

spec.add_dependency 'event_stream_parser', '~> 1.0'
spec.add_dependency 'faraday', '~> 2.9'
spec.add_dependency 'faraday', '~> 2.9', '>= 2.9.2'
spec.add_dependency 'faraday-typhoeus', '~> 1.1'

# Before upgrading, check this:
Expand Down
48 changes: 48 additions & 0 deletions spec/controllers/client_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# frozen_string_literal: true

require_relative '../../ports/dsl/gemini-ai'
require_relative '../../components/errors'

RSpec.describe Gemini do
it 'avoids unsupported services' do
expect do
described_class.new(
credentials: {
service: 'unknown-service'
}
)
end.to raise_error(
Gemini::Errors::UnsupportedServiceError,
"Unsupported service: 'unknown-service'."
)
end

it 'avoids conflicts with credential keys' do
expect do
described_class.new(
credentials: {
service: 'vertex-ai-api',
api_key: 'key',
file_path: 'path',
file_contents: 'contents'
}
)
end.to raise_error(
Gemini::Errors::ConflictingCredentialsError,
"You must choose either 'api_key', 'file_contents', or 'file_path'."
)

expect do
described_class.new(
credentials: {
service: 'vertex-ai-api',
file_path: 'path',
file_contents: 'contents'
}
)
end.to raise_error(
Gemini::Errors::ConflictingCredentialsError,
"You must choose either 'file_contents', or 'file_path'."
)
end
end
98 changes: 98 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# frozen_string_literal: true

# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end

# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end

# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # This allows you to limit a spec run to individual examples or groups
# # you care about by tagging them with `:focus` metadata. When nothing
# # is tagged with `:focus`, all examples get run. RSpec also provides
# # aliases for `it`, `describe`, and `context` that include `:focus`
# # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
#
# # Allows RSpec to persist some state between runs in order to support
# # the `--only-failures` and `--next-failure` CLI options. We recommend
# # you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
#
# # Limits the available syntax to the non-monkey patched syntax that is
# # recommended. For more details, see:
# # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/
# config.disable_monkey_patching!
#
# # This setting enables warnings. It's recommended, but in some cases may
# # be too noisy due to issues in dependencies.
# config.warnings = true
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Run specs in random order to surface order dependencies. If you find an
# # order dependency and want to debug it, you can fix the order by providing
# # the seed, which is printed after each run.
# # --seed 1234
# config.order = :random
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
end
Loading