Merge branch '8784-dir-listings'
[arvados.git] / sdk / ruby / lib / arvados / google_api_client.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 require 'google/api_client'
6 require 'json'
7 require 'tempfile'
8
9 class Google::APIClient
10   def discovery_document(api, version)
11     api = api.to_s
12     discovery_uri = self.discovery_uri(api, version)
13     discovery_uri_hash = Digest::MD5.hexdigest(discovery_uri)
14     discovery_cache_path =
15       File.expand_path("~/.cache/arvados/discovery-#{discovery_uri_hash}.json")
16     @discovery_documents[discovery_uri_hash] ||=
17       disk_cached_discovery_document(discovery_cache_path) or
18       fetched_discovery_document(discovery_uri, discovery_cache_path)
19   end
20
21   private
22
23   def disk_cached_discovery_document(cache_path)
24     begin
25       if (Time.now - File.mtime(cache_path)) < 86400
26         open(cache_path) do |cache_file|
27           return JSON.load(cache_file)
28         end
29       end
30     rescue IOError, SystemCallError, JSON::JSONError
31       # Error reading the cache.  Act like it doesn't exist.
32     end
33     nil
34   end
35
36   def write_cached_discovery_document(cache_path, body)
37     cache_dir = File.dirname(cache_path)
38     cache_file = nil
39     begin
40       FileUtils.makedirs(cache_dir)
41       cache_file = Tempfile.new("discovery", cache_dir)
42       cache_file.write(body)
43       cache_file.flush
44       File.rename(cache_file.path, cache_path)
45     rescue IOError, SystemCallError
46       # Failure to write the cache is non-fatal.  Do nothing.
47     ensure
48       cache_file.close! unless cache_file.nil?
49     end
50   end
51
52   def fetched_discovery_document(uri, cache_path)
53     response = self.execute!(:http_method => :get,
54                              :uri => uri,
55                              :authenticated => false)
56     write_cached_discovery_document(cache_path, response.body)
57     JSON.load(response.body)
58   end
59 end