├── .gitignore ├── lib ├── etre-client.rb └── etre-client │ ├── version.rb │ ├── errors.rb │ └── client.rb ├── Rakefile ├── .travis.yml ├── Gemfile ├── CHANGELOG.md ├── spec ├── unit_helper.rb └── client_spec.rb ├── CONTRIBUTING.md ├── etre-client.gemspec ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | -------------------------------------------------------------------------------- /lib/etre-client.rb: -------------------------------------------------------------------------------- 1 | require 'etre-client/client' 2 | require 'etre-client/errors' 3 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'rspec/core/rake_task' 2 | 3 | desc "run specs" 4 | RSpec::Core::RakeTask.new 5 | -------------------------------------------------------------------------------- /lib/etre-client/version.rb: -------------------------------------------------------------------------------- 1 | module Etre 2 | class Client 3 | VERSION = "0.8.6" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.3 4 | - 2.4 5 | - 2.5 6 | script: bundle exec rake spec 7 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'rest-client' 4 | 5 | group :test, :development do 6 | gem 'rspec-rails' 7 | end 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | Version 0.8.0 *(2017-10-31)* 5 | ---------------------------- 6 | 7 | Initial alpha release of etre-client. 8 | -------------------------------------------------------------------------------- /spec/unit_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) 2 | 3 | RSpec.configure do |config| 4 | config.mock_with :rspec do |mocks| 5 | mocks.verify_doubled_constant_names = true 6 | mocks.verify_partial_doubles = true 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /lib/etre-client/errors.rb: -------------------------------------------------------------------------------- 1 | module Etre 2 | class Client 3 | class EntityIdSet < StandardError; end 4 | class EntityNotProvided < StandardError; end 5 | class EntityTypeMismatch < StandardError; end 6 | class IdNotProvided < StandardError; end 7 | class LabelNotSet < StandardError; end 8 | class PatchIdSet < StandardError; end 9 | class PatchNotProvided < StandardError; end 10 | class QueryNotProvided < StandardError; end 11 | class RequestFailed < StandardError; end 12 | class UnexpectedResponseCode < StandardError; end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | If you would like to contribute code to this project you can do so through GitHub by 5 | forking the repository and sending a pull request. 6 | 7 | When submitting code, please make every effort to follow existing conventions 8 | and style in order to keep the code as readable as possible. Please also make 9 | sure your code compiles by running `mvn clean verify`. Checkstyle failures 10 | during compilation indicate errors in your style and can be viewed in the 11 | `checkstyle-result.xml` file. 12 | 13 | Before your code can be accepted into the project you must also sign the 14 | [Individual Contributor License Agreement (CLA)][1]. 15 | 16 | 17 | [1]: https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1 18 | -------------------------------------------------------------------------------- /etre-client.gemspec: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'etre-client/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = 'etre-client' 8 | spec.version = Etre::Client::VERSION 9 | spec.license = 'Apache-2.0' 10 | spec.authors = ['Michael Finch'] 11 | spec.email = ['mfinch@squareup.com'] 12 | spec.summary = 'Client gem for interacting with Etre' 13 | spec.homepage = 'https://github.com/square/etre-client-ruby' 14 | spec.required_ruby_version = '>= 2.3.0' 15 | 16 | spec.files = `git ls-files -z`.split("\x0") 17 | spec.test_files = spec.files.grep(/^(test|spec|features)\//) 18 | spec.require_paths = ['lib'] 19 | 20 | spec.add_runtime_dependency 'json' 21 | spec.add_runtime_dependency 'rest-client', '~> 2.0' 22 | 23 | spec.add_development_dependency 'rake', '~> 12.2', '>= 12.2.0' 24 | spec.add_development_dependency 'rspec', '~> 3.0' 25 | end 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Build Status](https://travis-ci.org/square/etre-client-ruby.svg?branch=master) 2 | 3 | Description 4 | ------ 5 | etre-client is a client gem for [Etre](https://github.com/square/etre). 6 | 7 | Installation 8 | ------ 9 | etre-client is hosted on rubygems.org. To install it 10 | 1. Add "etre-client" to your Gemfile 11 | 2. Run "bundle install" 12 | 13 | Alternatively, you can just "gem install etre-client". 14 | 15 | Usage 16 | ------ 17 | Require the gem 18 | ``` 19 | require 'etre-client' 20 | ``` 21 | 22 | Create a new client 23 | ``` 24 | # Create a standard client. 25 | e = Etre::Client.new(entity_type: "node", url: "http://127.0.0.1:8080") 26 | 27 | # Create a client with advanced HTTP options. These are passed down to the rest-client within the Etre Client. 28 | # See https://github.com/rest-client/rest-client#passing-advanced-options for more details. 29 | options = { 30 | :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("path_to_ssl_cert")), 31 | :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("path_to_ssl_key")), 32 | :ssl_ca_file => "path_to_ssl_ca", 33 | :verify_ssl => OpenSSL::SSL::VERIFY_PEER, 34 | :cookies => {:foo => "bar"}, 35 | } 36 | e = Etre::Client.new(entity_type: "node", url: "http://127.0.0.1:8080", options: options) 37 | ``` 38 | 39 | Insert entities 40 | ``` 41 | entities = [{"foo" => "bar"}, {"foo" => "abc"}, {"l1" => "a", "l2" => "b"}] 42 | e.insert(entities) 43 | => [{"id"=>"59f90caadd1b176f02eddcd8", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcd8"}, {"id"=>"59f90caadd1b176f02eddcda", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcda"}, {"id"=>"59f90e3fdd1b176f02eddce5", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90e3fdd1b176f02eddce5"}] 44 | ``` 45 | 46 | Read entities 47 | ``` 48 | query = "foo=bar" 49 | e.query(query) 50 | => [{"_id"=>"59f90caadd1b176f02eddcd8", "_rev"=>0, "_type"=>"node", "foo"=>"bar"}] 51 | ``` 52 | 53 | Update entities 54 | ``` 55 | query = "foo=bar" 56 | patch = {"foo" => "newbar"} 57 | e.update(query, patch) 58 | => [{"id"=>"59f90caadd1b176f02eddcd8", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcd8", "diff"=>{"_id"=>"59f90caadd1b176f02eddcd8", "_rev"=>0, "_type"=>"node", "foo"=>"bar"}}] 59 | ``` 60 | 61 | Update a single entity 62 | ``` 63 | id = "59f90caadd1b176f02eddcda" 64 | patch = {"foo" => "slug"} 65 | e.update_one(id, patch) 66 | => {"id"=>"59f90caadd1b176f02eddcda", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcda", "diff"=>{"_id"=>"59f90caadd1b176f02eddcda", "_rev"=>0, "_type"=>"node", "foo"=>"abc"}} 67 | ``` 68 | 69 | Delete entities 70 | ``` 71 | query = "foo=slug" 72 | e.delete(query) 73 | => [{"id"=>"59f90caadd1b176f02eddcda", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcda", "diff"=>{"_id"=>"59f90caadd1b176f02eddcda", "_rev"=>1, "_type"=>"node", "foo"=>"slug"}}] 74 | ``` 75 | 76 | Delete a single entity 77 | ``` 78 | id = "59f90caadd1b176f02eddcd8" 79 | e.delete_one(id) 80 | => {"id"=>"59f90caadd1b176f02eddcd8", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90caadd1b176f02eddcd8", "diff"=>{"_id"=>"59f90caadd1b176f02eddcd8", "_rev"=>1, "_type"=>"node", "foo"=>"newbar"}} 81 | ``` 82 | 83 | List the labels for an entity 84 | ``` 85 | id = "59f90e3fdd1b176f02eddce5" 86 | e.labels(id) 87 | => ["f1", "f2"] 88 | ``` 89 | 90 | Delete the label on an entity 91 | ``` 92 | id = "59f90e3fdd1b176f02eddce5" 93 | label = "l1" 94 | e.delete_label(id) 95 | => {"id"=>"59f90e3fdd1b176f02eddce5", "uri"=>"127.0.0.1:8080/api/v1/entity/59f90e3fdd1b176f02eddce5", "diff"=>{"_id"=>"59f90e3fdd1b176f02eddce5", "_rev"=>0, "_type"=>"node", "l1"=>"a", "l2"=>"b"}} 96 | ``` 97 | 98 | Development 99 | ------ 100 | Run the tests 101 | ``` 102 | bundle exec rake spec 103 | ``` 104 | 105 | Publish a new version of the gem: 106 | 1. Bump the version in lib/etre-client/version.rb 107 | 2. Build the gem with `gem build etre-client.gemspec` 108 | 3. Publish the new gem with `gem push etre-client-#{GEM_VERSION}.gem` 109 | 110 | ## License 111 | 112 | Copyright (c) 2017 Square Inc. Distributed under the Apache 2.0 License. 113 | See LICENSE file for further details. 114 | -------------------------------------------------------------------------------- /lib/etre-client/client.rb: -------------------------------------------------------------------------------- 1 | require 'etre-client/errors' 2 | require 'logger' 3 | require 'rest-client' 4 | require 'json' 5 | 6 | module Etre 7 | class Client 8 | attr_reader :entity_type, :url 9 | 10 | API_ROOT = "/api/v1" 11 | META_LABEL_ID = "_id" 12 | META_LABEL_TYPE = "_type" 13 | 14 | def initialize(entity_type:, url:, query_timeout: '5s', retry_count: 0, retry_wait: 1, options: {}) 15 | @entity_type = entity_type 16 | @url = url 17 | @query_timeout = query_timeout # http request timeout in seconds 18 | @retry_count = retry_count # retry count on network or API error 19 | @retry_wait = retry_wait # wait time between retries in seconds 20 | @options = options 21 | 22 | @logger = Logger.new(STDOUT) 23 | end 24 | 25 | # query returns an array of entities that satisfy a query. 26 | def query(query, filter = nil) 27 | if query.nil? || query.empty? 28 | raise QueryNotProvided 29 | end 30 | 31 | # @todo: translate filter to query params 32 | 33 | # Do the normal GET /entities?query unless the query is ~2k characters 34 | # becuase that brings the entire URL length close to the max supported 35 | # limit across most HTTP servers. In that case, switch to alternate 36 | # endpoint to POST the long query. 37 | if query.length < 2000 38 | # Always escape the query. 39 | query = CGI::escape(query) 40 | 41 | begin 42 | resp = etre_get("/entities/#{@entity_type}?query=#{query}") 43 | rescue RestClient::ExceptionWithResponse => e 44 | raise RequestFailed, e.response 45 | end 46 | else 47 | # DO NOT ESCAPE THE QUERY! It's not sent via URL, so no escaping needed. 48 | begin 49 | resp = etre_post("/query/#{@entity_type}", query) 50 | rescue RestClient::ExceptionWithResponse => e 51 | raise RequestFailed, e.response 52 | end 53 | end 54 | 55 | if resp.code != 200 56 | raise UnexpectedResponseCode, "expected 200, got #{resp.code}" 57 | end 58 | 59 | return JSON.parse(resp.body) 60 | end 61 | 62 | # insert inserts an array of entities. 63 | def insert(entities) 64 | if entities.nil? || !entities.any? 65 | raise EntityNotProvided 66 | end 67 | 68 | entities.each do |e| 69 | if e.key?(META_LABEL_ID) 70 | raise EntityIdSet, "entity: #{e}" 71 | end 72 | 73 | if e.key?(META_LABEL_TYPE) && e[META_LABEL_TYPE] != @entity_type 74 | raise EntityTypeMismatch, "only valid type is '#{@entity_type}', but " + 75 | "entity has type '#{e[META_LABEL_TYPE]}'" 76 | end 77 | end 78 | 79 | begin 80 | resp = etre_post("/entities/#{@entity_type}", entities) 81 | rescue RestClient::ExceptionWithResponse => e 82 | raise RequestFailed, e.response 83 | end 84 | 85 | if ![200, 201].include?(resp.code) 86 | raise UnexpectedResponseCode, "expected 200 or 201, got #{resp.code}" 87 | end 88 | 89 | return JSON.parse(resp.body) 90 | end 91 | 92 | # update updates entities with the given patch that satisfy the given query. 93 | def update(query, patch) 94 | if query.nil? || query.empty? 95 | raise QueryNotProvided 96 | end 97 | 98 | # Always escape the query. 99 | query = CGI::escape(query) 100 | 101 | if patch.nil? || !patch.any? 102 | raise PatchNotProvided 103 | end 104 | 105 | if patch.key?(META_LABEL_ID) 106 | raise PatchIdSet, "patch: #{patch}" 107 | end 108 | 109 | if patch.key?(META_LABEL_TYPE) && patch[META_LABEL_TYPE] != @entity_type 110 | raise EntityTypeMismatch, "only valid type is '#{@entity_type}', but " + 111 | "patch has type '#{patch[META_LABEL_TYPE]}'" 112 | end 113 | 114 | begin 115 | resp = etre_put("/entities/#{@entity_type}?query=#{query}", patch) 116 | rescue RestClient::ExceptionWithResponse => e 117 | raise RequestFailed, e.response 118 | end 119 | 120 | if ![200, 201].include?(resp.code) 121 | raise UnexpectedResponseCode, "expected 200 or 201, got #{resp.code}" 122 | end 123 | 124 | return JSON.parse(resp.body) 125 | end 126 | 127 | # update_one updates the given entity id with the provided patch. 128 | def update_one(id, patch) 129 | if id.nil? || id.empty? 130 | raise IdNotProvided 131 | end 132 | 133 | if patch.nil? || !patch.any? 134 | raise PatchNotProvided 135 | end 136 | 137 | if patch.key?(META_LABEL_ID) 138 | raise PatchIdSet, "patch: #{patch}" 139 | end 140 | 141 | if patch.key?(META_LABEL_TYPE) && patch[META_LABEL_TYPE] != @entity_type 142 | raise EntityTypeMismatch, "only valid type is '#{@entity_type}', but " + 143 | "patch has type '#{patch[META_LABEL_TYPE]}'" 144 | end 145 | 146 | begin 147 | resp = etre_put("/entity/#{@entity_type}/#{id}", patch) 148 | rescue RestClient::ExceptionWithResponse => e 149 | raise RequestFailed, e.response 150 | end 151 | 152 | if ![200, 201].include?(resp.code) 153 | raise UnexpectedResponseCode, "expected 200 or 201, got #{resp.code}" 154 | end 155 | 156 | return JSON.parse(resp.body) 157 | end 158 | 159 | # delete deletes the entities that satisfy the given query. 160 | def delete(query) 161 | if query.nil? || query.empty? 162 | raise QueryNotProvided 163 | end 164 | 165 | # Always escape the query. 166 | query = CGI::escape(query) 167 | 168 | begin 169 | resp = etre_delete("/entities/#{@entity_type}?query=#{query}") 170 | rescue RestClient::ExceptionWithResponse => e 171 | raise RequestFailed, e.response 172 | end 173 | 174 | if resp.code != 200 175 | raise UnexpectedResponseCode, "expected 200, got #{resp.code}" 176 | end 177 | 178 | return JSON.parse(resp.body) 179 | end 180 | 181 | # delete_one deletes the entity with the given id. 182 | def delete_one(id) 183 | if id.nil? || id.empty? 184 | raise IdNotProvided 185 | end 186 | 187 | begin 188 | resp = etre_delete("/entity/#{@entity_type}/#{id}") 189 | rescue RestClient::ExceptionWithResponse => e 190 | raise RequestFailed, e.response 191 | end 192 | 193 | if resp.code != 200 194 | raise UnexpectedResponseCode, "expected 200, got #{resp.code}" 195 | end 196 | 197 | return JSON.parse(resp.body) 198 | end 199 | 200 | # labels returns an array of labels for the given entity id. 201 | def labels(id) 202 | if id.nil? || id.empty? 203 | raise IdNotProvided 204 | end 205 | 206 | begin 207 | resp = etre_get("/entity/#{@entity_type}/#{id}/labels") 208 | rescue RestClient::ExceptionWithResponse => e 209 | raise RequestFailed, e.response 210 | end 211 | 212 | if resp.code != 200 213 | raise UnexpectedResponseCode, "expected 200, got #{resp.code}" 214 | end 215 | 216 | return JSON.parse(resp.body) 217 | end 218 | 219 | # delete_label deletes the given label on the provided entity id. 220 | def delete_label(id, label) 221 | if id.nil? || id.empty? 222 | raise IdNotProvided 223 | end 224 | 225 | if label.nil? || label.empty? 226 | raise LabelNotSet 227 | end 228 | 229 | begin 230 | resp = etre_delete("/entity/#{@entity_type}/#{id}/labels/#{label}") 231 | rescue RestClient::ExceptionWithResponse => e 232 | raise RequestFailed, e.response 233 | end 234 | 235 | if resp.code != 200 236 | raise UnexpectedResponseCode, "expected 200, got #{resp.code}" 237 | end 238 | 239 | return JSON.parse(resp.body) 240 | end 241 | 242 | private 243 | 244 | def etre_get(route) 245 | rest_retry { 246 | resource_for_route(route).get( 247 | get_headers, 248 | ) 249 | } 250 | end 251 | 252 | def etre_post(route, params = nil) 253 | rest_retry { 254 | resource_for_route(route).post( 255 | params.to_json, 256 | post_headers, 257 | ) 258 | } 259 | end 260 | 261 | def etre_put(route, params = nil) 262 | rest_retry { 263 | resource_for_route(route).put( 264 | params.to_json, 265 | put_headers, 266 | ) 267 | } 268 | end 269 | 270 | def etre_delete(route) 271 | rest_retry { 272 | resource_for_route(route).delete( 273 | delete_headers, 274 | ) 275 | } 276 | end 277 | 278 | def get_headers 279 | { 280 | :accept => 'application/json', 281 | :x_etre_query_timeout => @query_timeout 282 | } 283 | end 284 | 285 | def post_headers 286 | get_headers.merge!(:content_type => 'application/json') 287 | end 288 | 289 | def put_headers 290 | post_headers 291 | end 292 | 293 | def delete_headers 294 | get_headers 295 | end 296 | 297 | def resource_for_route(route) 298 | RestClient::Resource.new( 299 | @url + API_ROOT + route, 300 | @options 301 | ) 302 | end 303 | 304 | def parse_response(response) 305 | JSON.parse(response) 306 | end 307 | 308 | def rest_retry(&block) 309 | retries = 0 310 | 311 | begin 312 | yield 313 | rescue => e 314 | if (retries += 1) <= @retry_count 315 | @logger.warn("Error querying etre (#{e}). Sleeping for #{@retry_wait} seconds before trying again (attmept #{retries}/#{@retry_count}).") 316 | sleep(@retry_wait) 317 | retry 318 | else 319 | raise 320 | end 321 | end 322 | end 323 | end 324 | end 325 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Square, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /spec/client_spec.rb: -------------------------------------------------------------------------------- 1 | require 'etre-client' 2 | require 'ostruct' 3 | 4 | describe Etre::Client do 5 | let(:etre_client) { Etre::Client.new(entity_type: "node", url: "http://localhost:3000") } 6 | let(:get_headers) { {:accept => "application/json", :x_etre_query_timeout => '5s'} } 7 | let(:post_headers) { get_headers.merge({:content_type => "application/json"}) } 8 | let(:put_headers) { post_headers } 9 | let(:delete_headers) { get_headers } 10 | let(:entity1) { {"_id" => "abc", "foo" => "bar"} } 11 | let(:entity2) { {"oof" => "rab"} } 12 | let(:entity3) { {"blah" => "slug"} } 13 | let(:entity4) { {"_type" => "host", "a" => "b"} } 14 | let(:response_double) { instance_double(RestClient::Response) } 15 | let(:resource_double) { instance_double(RestClient::Resource) } 16 | 17 | describe '#query' do 18 | it "makes GET request when query is short" do 19 | q = "foo=bar" 20 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(q)}" 21 | 22 | expect(response_double).to receive(:code).and_return(200) 23 | expect(response_double).to receive(:body).and_return([entity1].to_json) 24 | expect(resource_double).to receive(:get).with(get_headers).and_return(response_double) 25 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 26 | expect(etre_client.query(q)).to eq([entity1]) 27 | end 28 | 29 | it "makes POST request when query is too long" do 30 | q = "foo=bar," * 300 31 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/query/#{etre_client.entity_type}" 32 | 33 | expect(response_double).to receive(:code).and_return(200) 34 | expect(response_double).to receive(:body).and_return([entity1].to_json) 35 | expect(resource_double).to receive(:post).with(q.to_json, post_headers).and_return(response_double) 36 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 37 | expect(etre_client.query(q)).to eq([entity1]) 38 | end 39 | 40 | it "raises if query is empty" do 41 | q = "" 42 | 43 | expect{etre_client.query(q)}.to raise_error(Etre::Client::QueryNotProvided) 44 | end 45 | 46 | it "raises if it gets an unexpected response code" do 47 | q = "foo=bar" 48 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(q)}" 49 | 50 | expect(response_double).to receive(:code).twice.and_return(400) 51 | expect(resource_double).to receive(:get).with(get_headers).and_return(response_double) 52 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 53 | expect{etre_client.query(q)}.to raise_error(Etre::Client::UnexpectedResponseCode) 54 | end 55 | end 56 | 57 | describe "#insert" do 58 | before :each do 59 | @path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}" 60 | end 61 | 62 | it "inserts entities" do 63 | entities = [entity2, entity3] 64 | 65 | expect(response_double).to receive(:code).and_return(200) 66 | expect(response_double).to receive(:body).and_return(entities.to_json) 67 | expect(resource_double).to receive(:post).with(entities.to_json, post_headers).and_return(response_double) 68 | expect(RestClient::Resource).to receive(:new).with(@path, {}).and_return(resource_double) 69 | expect(etre_client.insert(entities)).to eq(entities) 70 | end 71 | 72 | it "raises if an entity has _id set" do 73 | entities = [entity1, entity2] 74 | 75 | expect{etre_client.insert(entities)}.to raise_error(Etre::Client::EntityIdSet) 76 | end 77 | 78 | it "raises if an entity has the wrong _type set" do 79 | entities = [entity2, entity4] 80 | 81 | expect{etre_client.insert(entities)}.to raise_error(Etre::Client::EntityTypeMismatch) 82 | end 83 | 84 | it "raises if it gets an unexpected response code" do 85 | entities = [entity2, entity3] 86 | 87 | expect(response_double).to receive(:code).twice.and_return(400) 88 | expect(resource_double).to receive(:post).with(entities.to_json, post_headers).and_return(response_double) 89 | expect(RestClient::Resource).to receive(:new).with(@path, {}).and_return(resource_double) 90 | expect{etre_client.insert(entities)}.to raise_error(Etre::Client::UnexpectedResponseCode) 91 | end 92 | end 93 | 94 | describe "#update" do 95 | it "updates entities" do 96 | query = "foo=bar" 97 | patch = {"foo" => "new"} 98 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(query)}" 99 | 100 | expect(response_double).to receive(:code).and_return(200) 101 | expect(response_double).to receive(:body).and_return({}.to_json) 102 | expect(resource_double).to receive(:put).with(patch.to_json, put_headers).and_return(response_double) 103 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 104 | expect(etre_client.update(query, patch)).to eq({}) 105 | end 106 | 107 | it "raises if query is empty" do 108 | query = "" 109 | patch = {"foo" => "new"} 110 | 111 | expect{etre_client.update(query, patch)}.to raise_error(Etre::Client::QueryNotProvided) 112 | end 113 | 114 | it "raises if patch is empty" do 115 | query = "foo=bar" 116 | patch = {} 117 | 118 | expect{etre_client.update(query, patch)}.to raise_error(Etre::Client::PatchNotProvided) 119 | end 120 | 121 | it "raises if _id is set in patch" do 122 | query = "foo=bar" 123 | patch = {"_id" => "abc"} 124 | 125 | expect{etre_client.update(query, patch)}.to raise_error(Etre::Client::PatchIdSet) 126 | end 127 | 128 | it "raises if patch has the wrong _type set" do 129 | query = "foo=bar" 130 | patch = {"_type" => "host"} 131 | 132 | expect{etre_client.update(query, patch)}.to raise_error(Etre::Client::EntityTypeMismatch) 133 | end 134 | 135 | it "raises if it gets an unexpected response code" do 136 | query = "foo=bar" 137 | patch = {"foo" => "new"} 138 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(query)}" 139 | 140 | expect(response_double).to receive(:code).twice.and_return(400) 141 | expect(resource_double).to receive(:put).with(patch.to_json, put_headers).and_return(response_double) 142 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 143 | expect{etre_client.update(query, patch)}.to raise_error(Etre::Client::UnexpectedResponseCode) 144 | end 145 | end 146 | 147 | describe "#update_one" do 148 | it "updates an entity" do 149 | id = "abc" 150 | patch = {"foo" => "new"} 151 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}" 152 | 153 | expect(response_double).to receive(:code).and_return(200) 154 | expect(response_double).to receive(:body).and_return({}.to_json) 155 | expect(resource_double).to receive(:put).with(patch.to_json, put_headers).and_return(response_double) 156 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 157 | expect(etre_client.update_one(id, patch)).to eq({}) 158 | end 159 | 160 | it "raises if id is empty" do 161 | id = "" 162 | patch = {"foo" => "new"} 163 | 164 | expect{etre_client.update_one(id, patch)}.to raise_error(Etre::Client::IdNotProvided) 165 | end 166 | 167 | it "raises if patch is empty" do 168 | id = "abc" 169 | patch = {} 170 | 171 | expect{etre_client.update_one(id, patch)}.to raise_error(Etre::Client::PatchNotProvided) 172 | end 173 | 174 | it "raises if _id is set in patch" do 175 | id = "abc" 176 | patch = {"_id" => "abc"} 177 | 178 | expect{etre_client.update_one(id, patch)}.to raise_error(Etre::Client::PatchIdSet) 179 | end 180 | 181 | it "raises if patch has the wrong _type set" do 182 | id = "abc" 183 | patch = {"_type" => "host"} 184 | 185 | expect{etre_client.update_one(id, patch)}.to raise_error(Etre::Client::EntityTypeMismatch) 186 | end 187 | 188 | it "raises if it gets an unexpected response code" do 189 | id = "abc" 190 | patch = {"foo" => "new"} 191 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}" 192 | 193 | expect(response_double).to receive(:code).twice.and_return(400) 194 | expect(resource_double).to receive(:put).with(patch.to_json, put_headers).and_return(response_double) 195 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 196 | expect{etre_client.update_one(id, patch)}.to raise_error(Etre::Client::UnexpectedResponseCode) 197 | end 198 | end 199 | 200 | describe "#delete" do 201 | it "deletes entities" do 202 | query = "foo=bar" 203 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(query)}" 204 | 205 | expect(response_double).to receive(:code).and_return(200) 206 | expect(response_double).to receive(:body).and_return({}.to_json) 207 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 208 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 209 | expect(etre_client.delete(query)).to eq({}) 210 | end 211 | 212 | it "raises if query is empty" do 213 | query = "" 214 | 215 | expect{etre_client.delete(query)}.to raise_error(Etre::Client::QueryNotProvided) 216 | end 217 | 218 | it "raises if it gets an unexpected response code" do 219 | query = "foo=bar" 220 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entities/#{etre_client.entity_type}?query=#{CGI::escape(query)}" 221 | 222 | expect(response_double).to receive(:code).twice.and_return(400) 223 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 224 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 225 | expect{etre_client.delete(query)}.to raise_error(Etre::Client::UnexpectedResponseCode) 226 | end 227 | end 228 | 229 | describe "#delete_one" do 230 | it "deletes an entity" do 231 | id = "abc" 232 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}" 233 | 234 | expect(response_double).to receive(:code).and_return(200) 235 | expect(response_double).to receive(:body).and_return({}.to_json) 236 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 237 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 238 | expect(etre_client.delete_one(id)).to eq({}) 239 | end 240 | 241 | it "raises if id is empty" do 242 | id = "" 243 | 244 | expect{etre_client.delete_one(id)}.to raise_error(Etre::Client::IdNotProvided) 245 | end 246 | 247 | it "raises if it gets an unexpected response code" do 248 | id = "abc" 249 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}" 250 | 251 | expect(response_double).to receive(:code).twice.and_return(400) 252 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 253 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 254 | expect{etre_client.delete_one(id)}.to raise_error(Etre::Client::UnexpectedResponseCode) 255 | end 256 | end 257 | 258 | describe "#labels" do 259 | it "lists the lables for an entity" do 260 | id = "abc" 261 | labels = ["foo1", "foo2"] 262 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}/labels" 263 | 264 | expect(response_double).to receive(:code).and_return(200) 265 | expect(response_double).to receive(:body).and_return(labels.to_json) 266 | expect(resource_double).to receive(:get).with(get_headers).and_return(response_double) 267 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 268 | expect(etre_client.labels(id)).to eq(labels) 269 | end 270 | 271 | it "raises if id is empty" do 272 | id = "" 273 | 274 | expect{etre_client.labels(id)}.to raise_error(Etre::Client::IdNotProvided) 275 | end 276 | 277 | it "raises if it gets an unexpected response code" do 278 | id = "abc" 279 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}/labels" 280 | 281 | expect(response_double).to receive(:code).twice.and_return(400) 282 | expect(resource_double).to receive(:get).with(get_headers).and_return(response_double) 283 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 284 | expect{etre_client.labels(id)}.to raise_error(Etre::Client::UnexpectedResponseCode) 285 | end 286 | end 287 | 288 | describe "#delete_label" do 289 | it "deletes the label on an entity" do 290 | id = "abc" 291 | label = "foo" 292 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}/labels/#{label}" 293 | 294 | expect(response_double).to receive(:code).and_return(200) 295 | expect(response_double).to receive(:body).and_return({}.to_json) 296 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 297 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 298 | expect(etre_client.delete_label(id, label)).to eq({}) 299 | end 300 | 301 | it "raises if id is empty" do 302 | id = "" 303 | label = "foo" 304 | 305 | expect{etre_client.delete_label(id, label)}.to raise_error(Etre::Client::IdNotProvided) 306 | end 307 | 308 | it "raises if label is empty" do 309 | id = "" 310 | label = "" 311 | 312 | expect{etre_client.delete_label(id, label)}.to raise_error(Etre::Client::IdNotProvided) 313 | end 314 | 315 | it "raises if it gets an unexpected response code" do 316 | id = "abc" 317 | label = "foo" 318 | path = "#{etre_client.url}#{Etre::Client::API_ROOT}/entity/#{etre_client.entity_type}/#{id}/labels/#{label}" 319 | 320 | expect(response_double).to receive(:code).twice.and_return(400) 321 | expect(resource_double).to receive(:delete).with(delete_headers).and_return(response_double) 322 | expect(RestClient::Resource).to receive(:new).with(path, {}).and_return(resource_double) 323 | expect{etre_client.delete_label(id, label)}.to raise_error(Etre::Client::UnexpectedResponseCode) 324 | end 325 | end 326 | end 327 | --------------------------------------------------------------------------------