1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 require 'google/api_client'
9 class Google::APIClient
10 def discovery_document(api, version)
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)
23 def disk_cached_discovery_document(cache_path)
25 if (Time.now - File.mtime(cache_path)) < 86400
26 open(cache_path) do |cache_file|
27 return JSON.load(cache_file)
30 rescue IOError, SystemCallError, JSON::JSONError
31 # Error reading the cache. Act like it doesn't exist.
36 def write_cached_discovery_document(cache_path, body)
37 cache_dir = File.dirname(cache_path)
40 FileUtils.makedirs(cache_dir)
41 cache_file = Tempfile.new("discovery", cache_dir)
42 cache_file.write(body)
44 File.rename(cache_file.path, cache_path)
45 rescue IOError, SystemCallError
46 # Failure to write the cache is non-fatal. Do nothing.
48 cache_file.close! unless cache_file.nil?
52 def fetched_discovery_document(uri, cache_path)
53 response = self.execute!(:http_method => :get,
55 :authenticated => false)
56 write_cached_discovery_document(cache_path, response.body)
57 JSON.load(response.body)