nexus_mods 0.2.0 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: efdb25aee2a65f563017933ab77b1360d3ab04d26abf3f945cd9c1cf3d0a1a0d
4
- data.tar.gz: dc538a350901669fbca2e6cbc299daf091bcf0779f82c3e9b718398b5f61e877
3
+ metadata.gz: 79e4d81970dd1549db43105a2a155b6b275692df4f06827e2234ab02fce6276b
4
+ data.tar.gz: 4d96df8a39784c8a2eb6fb9bd72a247f3cafa2765aa03059dfc661afd9db7a38
5
5
  SHA512:
6
- metadata.gz: 6e2f2ee9025ab0650fc96ad4d10ff41e8375caa8c6ab51e64ceec5527630e97806bfdbce74d2db2ba63bc58a45371392c98d4fb20ccbd7399b2711123fce125f
7
- data.tar.gz: a6519240cb31bc1cf25a5f0b7001be67e91b41588817739f50a8c8b4d1558a2129ecb43ba6239454717fe47d6aea47f152eeb08c374bce18c83fe84003a378fd
6
+ metadata.gz: 9c13d188694e09dc06998846791322a4887bbb5163ff634d5e6f813abca187a6a2dc8aeb102e040b43812d6276feb6c1ee59665c5e5e408c6acbff4dca0539b3
7
+ data.tar.gz: 3e37eb153f00bb6335efb8e0b377065f4b0613cbef46066a1a5d7095b1e1767b1786d59f28681298e75be49e1cfeb739ea6ce2f7b13fefc6b28362b27d7536b5
data/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # [v0.4.0](https://github.com/Muriel-Salvan/nexus_mods/compare/v0.3.0...v0.4.0) (2023-04-10 10:15:41)
2
+
3
+ ### Features
4
+
5
+ * [[Feature] Add persistent API caching in files](https://github.com/Muriel-Salvan/nexus_mods/commit/f124ecf58b0f478ecdca5f6ad2309779d1ab67ac)
6
+
7
+ # [v0.3.0](https://github.com/Muriel-Salvan/nexus_mods/compare/v0.2.0...v0.3.0) (2023-04-10 09:13:43)
8
+
9
+ ### Features
10
+
11
+ * [[Feature] Implement caching of API queries with configurable expiry times](https://github.com/Muriel-Salvan/nexus_mods/commit/7f74e25d046adbcec394ce33a3802ed9e91f3a52)
12
+
1
13
  # [v0.2.0](https://github.com/Muriel-Salvan/nexus_mods/compare/v0.1.1...v0.2.0) (2023-04-10 08:45:44)
2
14
 
3
15
  ### Features
@@ -0,0 +1,189 @@
1
+ require 'fileutils'
2
+ require 'faraday'
3
+ require 'faraday-http-cache'
4
+ require 'nexus_mods/file_cache'
5
+ require 'nexus_mods/cacheable_api'
6
+
7
+ class NexusMods
8
+
9
+ # Base class handling HTTP calls to the NexusMods API.
10
+ # Handle caching if needed.
11
+ class ApiClient
12
+
13
+ include CacheableApi
14
+
15
+ # Default expiry times, in seconds
16
+ DEFAULT_API_CACHE_EXPIRY = {
17
+ games: 24 * 60 * 60,
18
+ mod: 24 * 60 * 60,
19
+ mod_files: 24 * 60 * 60
20
+ }
21
+
22
+ # Constructor
23
+ #
24
+ # Parameters::
25
+ # * *api_key* (String or nil): The API key to be used, or nil for another authentication [default: nil]
26
+ # * *http_cache_file* (String): File used to store the HTTP cache, or nil for no cache [default: "#{Dir.tmpdir}/nexus_mods_http_cache.json"]
27
+ # * *api_cache_expiry* (Hash<Symbol,Integer>): Expiry times in seconds, per expiry key. Possible keys are:
28
+ # * *games*: Expiry associated to queries on games [default: 1 day]
29
+ # * *mod*: Expiry associated to queries on mod [default: 1 day]
30
+ # * *mod_files*: Expiry associated to queries on mod files [default: 1 day]
31
+ # * *api_cache_file* (String): File used to store the NexusMods API cache, or nil for no cache [default: "#{Dir.tmpdir}/nexus_mods_api_cache.json"]
32
+ # * *logger* (Logger): The logger to be used for log messages [default: Logger.new(STDOUT)]
33
+ def initialize(
34
+ api_key: nil,
35
+ http_cache_file: "#{Dir.tmpdir}/nexus_mods_http_cache.json",
36
+ api_cache_expiry: DEFAULT_API_CACHE_EXPIRY,
37
+ api_cache_file: "#{Dir.tmpdir}/nexus_mods_api_cache.json",
38
+ logger: Logger.new($stdout)
39
+ )
40
+ @api_key = api_key
41
+ @api_cache_expiry = DEFAULT_API_CACHE_EXPIRY.merge(api_cache_expiry)
42
+ @api_cache_file = api_cache_file
43
+ ApiClient.api_client = self
44
+ @logger = logger
45
+ # Initialize our HTTP client
46
+ @http_cache = http_cache_file.nil? ? nil : FileCache.new(http_cache_file)
47
+ @http_client = Faraday.new do |builder|
48
+ # Indicate that the cache is not shared, meaning that private resources (depending on the session) can be cached as we consider only 1 user is using it for a given file cache.
49
+ # Use Marshal serializer as some URLs can't get decoded correctly due to UTF-8 issues
50
+ builder.use :http_cache,
51
+ store: @http_cache,
52
+ shared_cache: false,
53
+ serializer: Marshal
54
+ builder.adapter Faraday.default_adapter
55
+ end
56
+ Cacheable.cache_adapter = :persistent_json
57
+ load_api_cache
58
+ end
59
+
60
+ # Send an HTTP request to the API and get back the answer as a JSON.
61
+ # Use caching.
62
+ #
63
+ # Parameters::
64
+ # * *path* (String): API path to contact (from v1/ and without .json)
65
+ # * *verb* (Symbol): Verb to be used (:get, :post...) [default: :get]
66
+ # Result::
67
+ # * Object: The JSON response
68
+ def api(path, verb: :get)
69
+ res = http(path, verb:)
70
+ json = JSON.parse(res.body)
71
+ uri = api_uri(path)
72
+ @logger.debug "[API call] - #{verb} #{uri} => #{res.status}\n#{
73
+ JSON.
74
+ pretty_generate(json).
75
+ split("\n").
76
+ map { |line| " #{line}" }.
77
+ join("\n")
78
+ }\n#{
79
+ res.
80
+ headers.
81
+ map { |header, value| " #{header}: #{value}" }.
82
+ join("\n")
83
+ }"
84
+ case res.status
85
+ when 200
86
+ # Happy
87
+ when 429
88
+ # Some limits of the API have been reached
89
+ raise LimitsExceededError, "Exceeding limits of API calls: #{res.headers.select { |header, _value| header =~ /^x-rl-.+$/ }}"
90
+ else
91
+ raise ApiError, "API #{uri} returned error code #{res.status}" unless res.status == '200'
92
+ end
93
+ json
94
+ end
95
+ cacheable_api(
96
+ :api,
97
+ expiry_from_key: proc do |key|
98
+ # Example of keys:
99
+ # NexusMods::ApiClient/api/games
100
+ # NexusMods::ApiClient/api/games/skyrimspecialedition/mods/2014
101
+ # NexusMods::ApiClient/api/games/skyrimspecialedition/mods/2014/files
102
+ # NexusMods::ApiClient/api/users/validate
103
+ key_components = key.split('/')[2..]
104
+ case key_components[0]
105
+ when 'games'
106
+ if key_components[1].nil?
107
+ ApiClient.api_client.api_cache_expiry[:games]
108
+ else
109
+ case key_components[2]
110
+ when 'mods'
111
+ case key_components[4]
112
+ when nil
113
+ ApiClient.api_client.api_cache_expiry[:mod]
114
+ when 'files'
115
+ ApiClient.api_client.api_cache_expiry[:mod_files]
116
+ else
117
+ raise "Unknown API path: #{key}"
118
+ end
119
+ else
120
+ raise "Unknown API path: #{key}"
121
+ end
122
+ end
123
+ when 'users'
124
+ # Don't cache this path as it is used to know API limits
125
+ 0
126
+ else
127
+ raise "Unknown API path: #{key}"
128
+ end
129
+ end,
130
+ on_cache_update: proc do
131
+ ApiClient.api_client.save_api_cache
132
+ end
133
+ )
134
+
135
+ # Send an HTTP request to the API and get back the HTTP response
136
+ #
137
+ # Parameters::
138
+ # * *path* (String): API path to contact (from v1/ and without .json)
139
+ # * *verb* (Symbol): Verb to be used (:get, :post...) [default: :get]
140
+ # Result::
141
+ # * Faraday::Response: The HTTP response
142
+ def http(path, verb: :get)
143
+ @http_client.send(verb) do |req|
144
+ req.url api_uri(path)
145
+ req.headers['apikey'] = @api_key
146
+ req.headers['User-Agent'] = "nexus_mods (#{RUBY_PLATFORM}) Ruby/#{RUBY_VERSION}"
147
+ end
148
+ end
149
+
150
+ # Load the API cache if a file was given to this client
151
+ def load_api_cache
152
+ Cacheable.cache_adapter.load(@api_cache_file) if @api_cache_file && File.exist?(@api_cache_file)
153
+ end
154
+
155
+ # Save the API cache if a file was given to this client
156
+ def save_api_cache
157
+ return unless @api_cache_file
158
+
159
+ FileUtils.mkdir_p(File.dirname(@api_cache_file))
160
+ Cacheable.cache_adapter.save(@api_cache_file)
161
+ end
162
+
163
+ # Some attributes exposed for the cacheable feature to work
164
+ attr_reader :api_cache_expiry
165
+
166
+ private
167
+
168
+ class << self
169
+
170
+ # ApiClient: The API client to be used by the cacheable adapter (singleton pattern)
171
+ attr_accessor :api_client
172
+
173
+ end
174
+
175
+ @api_client = nil
176
+
177
+ # Get the real URI to query for a given API path
178
+ #
179
+ # Parameters::
180
+ # * *path* (String): API path to contact (from v1/ and without .json)
181
+ # Result::
182
+ # * String: The URI
183
+ def api_uri(path)
184
+ "https://api.nexusmods.com/v1/#{path}.json"
185
+ end
186
+
187
+ end
188
+
189
+ end
@@ -0,0 +1,58 @@
1
+ require 'cacheable'
2
+ require 'nexus_mods/core_extensions/cacheable/method_generator'
3
+ require 'nexus_mods/cacheable_with_expiry'
4
+
5
+ class NexusMods
6
+
7
+ # Provide cacheable helpers for API methods that can be invalidated with an expiry time in seconds
8
+ module CacheableApi
9
+
10
+ # Callback when the module is included in another module/class
11
+ #
12
+ # Parameters::
13
+ # * *base* (Class or Module): The class/module including this module
14
+ def self.included(base)
15
+ base.include CacheableWithExpiry
16
+ base.extend CacheableApi::CacheableHelpers
17
+ end
18
+
19
+ # Some class helpers to make API calls easily cacheable
20
+ module CacheableHelpers
21
+
22
+ # Cache methods used for the NexusMods API with a given expiry time in seconds
23
+ #
24
+ # Parameters::
25
+ # * *original_method_names* (Array<Symbol>): List of methods to which this cache apply
26
+ # * *expiry_from_key* (Proc): Code giving the number of seconds of cache expiry from the key
27
+ # * Parameters::
28
+ # * *key* (String): The key for which we want the expiry time in seconds
29
+ # * Result::
30
+ # * Integer: Corresponding expiry time
31
+ # * *on_cache_update* (Proc): Proc called when the cache has been updated
32
+ def cacheable_api(*original_method_names, expiry_from_key:, on_cache_update:)
33
+ cacheable_with_expiry(
34
+ *original_method_names,
35
+ key_format: lambda do |target, method_name, method_args, method_kwargs|
36
+ (
37
+ [
38
+ target.class,
39
+ method_name
40
+ ] +
41
+ method_args +
42
+ method_kwargs.map { |key, value| "#{key}:#{value}" }
43
+ ).join('/')
44
+ end,
45
+ expiry_from_key:,
46
+ cache_options: {
47
+ on_cache_update: proc do |_adapter, _key, _value, _options, _context|
48
+ on_cache_update.call
49
+ end
50
+ }
51
+ )
52
+ end
53
+
54
+ end
55
+
56
+ end
57
+
58
+ end
@@ -0,0 +1,72 @@
1
+ require 'time'
2
+ require 'nexus_mods/core_extensions/cacheable/cache_adapters/persistent_json_adapter'
3
+
4
+ class NexusMods
5
+
6
+ # Add cacheable properties that can be expired using time in seconds
7
+ module CacheableWithExpiry
8
+
9
+ # Callback when the module is included in another module/class
10
+ #
11
+ # Parameters::
12
+ # * *base* (Class or Module): The class/module including this module
13
+ def self.included(base)
14
+ base.include Cacheable
15
+ base.extend CacheableWithExpiry::CacheableHelpers
16
+ end
17
+
18
+ # Some class helpers to make cacheable calls easy with expiry proc
19
+ module CacheableHelpers
20
+
21
+ # Wrap Cacheable's cacheable method to add the expiry_rules kwarg and use to invalidate the cache of a PersistentJsonAdapter based on the key format.
22
+ #
23
+ # Parameters::
24
+ # * *original_method_names* (Array<Symbol>): List of methods to which this cache apply
25
+ # * *opts* (Hash<Symbol,Object>): kwargs that will be transferred to the cacheable method, with the following ones interpreted:
26
+ # * *expiry_from_key* (Proc): Code giving the number of seconds of cache expiry from the key
27
+ # * Parameters::
28
+ # * *key* (String): The key for which we want the expiry time in seconds
29
+ # * Result::
30
+ # * Integer: Corresponding expiry time
31
+ def cacheable_with_expiry(*original_method_names, **opts)
32
+ expiry_cache = {}
33
+ cacheable(
34
+ *original_method_names,
35
+ **opts.merge(
36
+ {
37
+ cache_options: (opts[:cache_options] || {}).merge(
38
+ {
39
+ expiry_from_key: opts[:expiry_from_key],
40
+ invalidate_if: proc do |key, options, context|
41
+ next true unless context['invalidate_time']
42
+
43
+ # Find if we know already the expiry for this key
44
+ expiry_cache[key] = options[:expiry_from_key].call(key) unless expiry_cache.key?(key)
45
+ expiry_cache[key].nil? || (Time.now.utc - Time.parse(context['invalidate_time']).utc > expiry_cache[key])
46
+ end,
47
+ update_context_after_fetch: proc do |_key, _value, _options, context|
48
+ context['invalidate_time'] = Time.now.utc.strftime('%FT%TUTC')
49
+ end
50
+ }
51
+ )
52
+ }
53
+ )
54
+ )
55
+ @_cacheable_expiry_caches = [] unless defined?(@_cacheable_expiry_caches)
56
+ @_cacheable_expiry_caches << expiry_cache
57
+ end
58
+
59
+ # Clear expiry times caches
60
+ def clear_cacheable_expiry_caches
61
+ return unless defined?(@_cacheable_expiry_caches)
62
+
63
+ @_cacheable_expiry_caches.each do |expiry_cache|
64
+ expiry_cache.replace({})
65
+ end
66
+ end
67
+
68
+ end
69
+
70
+ end
71
+
72
+ end
@@ -0,0 +1,98 @@
1
+ require 'cacheable'
2
+ require 'json'
3
+
4
+ module Cacheable
5
+
6
+ module CacheAdapters
7
+
8
+ # Adapter that adds JSON serialization functionality to save and load in files.
9
+ # Also adds contexts linked to keys being fetched to support more complex cache-invalidation schemes.
10
+ # This works only if:
11
+ # * The cached values are JSON serializable.
12
+ # * The cache keys are strings.
13
+ # * The context information is JSON serializable.
14
+ class PersistentJsonAdapter < MemoryAdapter
15
+
16
+ # Fetch a key with the givien cache options
17
+ #
18
+ # Parameters::
19
+ # * *key* (String): Key to be fetched
20
+ # * *options* (Hash): Cache options. The following options are interpreted by this fetch:
21
+ # * *invalidate_if* (Proc or nil): Optional code called to know if the cache should be invalidated for a given key:
22
+ # * Parameters::
23
+ # * *key* (String): The key for which we check the cache invalidation
24
+ # * *options* (Hash): Cache options linked to this key
25
+ # * *key_context* (Hash): Context linked to this key, that can be set using the update_context_after_fetch callback.
26
+ # * Result::
27
+ # * Boolean: Should we invalidate the cached value of this key?
28
+ # * *update_context_after_fetch* (Proc or nil): Optional code called when the value has been fetched for real (without cache), used to update the context
29
+ # * Parameters::
30
+ # * *key* (String): The key for which we just fetched the value
31
+ # * *value* (Object): The value that has just been fetched
32
+ # * *options* (Hash): Cache options linked to this key
33
+ # * *key_context* (Hash): Context linked to this key, that is supposed to be updated in place by this callback
34
+ # * *on_cache_update* (Proc or nil): Optional code called once the cache has been updated
35
+ # * Parameters::
36
+ # * *adapter* (Object): Adapter that has the cache being updated
37
+ # * *key* (String): The key for which we just fetched the value
38
+ # * *value* (Object): The value that has just been fetched
39
+ # * *options* (Hash): Cache options linked to this key
40
+ # * *key_context* (Hash): Context linked to this key
41
+ # * CodeBlock: Code called to fetch the value if not in the cache
42
+ # Result::
43
+ # * Object: The value for this key
44
+ def fetch(key, options = {})
45
+ context[key] = {} unless context.key?(key)
46
+ key_context = context[key]
47
+ delete(key) if options[:invalidate_if]&.call(key, options, key_context)
48
+ return read(key) if exist?(key)
49
+
50
+ value = yield
51
+ options[:update_context_after_fetch]&.call(key, value, options, key_context)
52
+ write(key, value)
53
+ options[:on_cache_update]&.call(self, key, value, options, key_context)
54
+ value
55
+ end
56
+
57
+ # Clear the cache
58
+ def clear
59
+ @context = {}
60
+ super
61
+ end
62
+
63
+ # Save the cache and context into a JSON file
64
+ #
65
+ # Parameters::
66
+ # * *file* (String): The file to save to
67
+ def save(file)
68
+ # Remove from the context the keys that are not in the cache
69
+ File.write(
70
+ file,
71
+ JSON.dump(
72
+ {
73
+ 'cache' => cache,
74
+ 'context' => context.select { |key, _value| @cache.key?(key) }
75
+ }
76
+ )
77
+ )
78
+ end
79
+
80
+ # Load the cache and context from a JSON file
81
+ #
82
+ # Parameters::
83
+ # * *file* (String): The file to load from
84
+ def load(file)
85
+ loaded_content = JSON.parse(File.read(file))
86
+ @cache = loaded_content['cache']
87
+ @context = loaded_content['context']
88
+ end
89
+
90
+ private
91
+
92
+ attr_reader :context
93
+
94
+ end
95
+
96
+ end
97
+
98
+ end
@@ -0,0 +1,62 @@
1
+ class NexusMods
2
+
3
+ module CoreExtensions
4
+
5
+ module Cacheable
6
+
7
+ # Make the cacheable method generators compatible with methods having kwargs
8
+ # TODO: Remove this core extension when cacheable will be compatible with kwargs
9
+ module MethodGenerator
10
+
11
+ private
12
+
13
+ # Create all methods to allow cacheable functionality, for a given original method name
14
+ #
15
+ # Parameters::
16
+ # * *original_method_name* (Symbol): The original method name
17
+ # * *opts* (Hash): The options given to the cacheable call
18
+ def create_cacheable_methods(original_method_name, opts = {})
19
+ method_names = create_method_names(original_method_name)
20
+ key_format_proc = opts[:key_format] || default_key_format
21
+
22
+ const_get(method_interceptor_module_name).class_eval do
23
+ define_method(method_names[:key_format_method_name]) do |*args, **kwargs|
24
+ key_format_proc.call(self, original_method_name, args, kwargs)
25
+ end
26
+
27
+ define_method(method_names[:clear_cache_method_name]) do |*args, **kwargs|
28
+ ::Cacheable.cache_adapter.delete(__send__(method_names[:key_format_method_name], *args, **kwargs))
29
+ end
30
+
31
+ define_method(method_names[:without_cache_method_name]) do |*args, **kwargs|
32
+ original_method = method(original_method_name).super_method
33
+ original_method.call(*args, **kwargs)
34
+ end
35
+
36
+ define_method(method_names[:with_cache_method_name]) do |*args, **kwargs|
37
+ ::Cacheable.cache_adapter.fetch(__send__(method_names[:key_format_method_name], *args, **kwargs), opts[:cache_options]) do
38
+ __send__(method_names[:without_cache_method_name], *args, **kwargs)
39
+ end
40
+ end
41
+
42
+ define_method(original_method_name) do |*args, **kwargs|
43
+ unless_proc = opts[:unless].is_a?(Symbol) ? opts[:unless].to_proc : opts[:unless]
44
+
45
+ if unless_proc&.call(self, original_method_name, args)
46
+ __send__(method_names[:without_cache_method_name], *args, **kwargs)
47
+ else
48
+ __send__(method_names[:with_cache_method_name], *args, **kwargs)
49
+ end
50
+ end
51
+ end
52
+ end
53
+
54
+ end
55
+
56
+ end
57
+
58
+ end
59
+
60
+ end
61
+
62
+ Cacheable::MethodGenerator.prepend NexusMods::CoreExtensions::Cacheable::MethodGenerator
@@ -0,0 +1,71 @@
1
+ class NexusMods
2
+
3
+ # Simple key/value file cache
4
+ class FileCache
5
+
6
+ # Constructor
7
+ #
8
+ # Parameters::
9
+ # * *file* (String): File to use as a cache
10
+ def initialize(file)
11
+ @file = file
12
+ @cache_content = File.exist?(file) ? JSON.parse(File.read(file)) : {}
13
+ end
14
+
15
+ # Dump the cache in file
16
+ def dump
17
+ File.write(@file, @cache_content.to_json)
18
+ end
19
+
20
+ # Get the cache content as a Hash
21
+ #
22
+ # Result::
23
+ # * Hash<String, Object>: Cache content
24
+ def to_h
25
+ @cache_content
26
+ end
27
+
28
+ # Is a given key present in the cache?
29
+ #
30
+ # Parameters::
31
+ # * *key* (String): The key
32
+ # Result::
33
+ # * Boolean: Is a given key present in the cache?
34
+ def key?(key)
35
+ @cache_content.key?(key)
36
+ end
37
+
38
+ # Read a key from the cache
39
+ #
40
+ # Parameters:
41
+ # * *key* (String): The cache key
42
+ # Result::
43
+ # * Object or nil: JSON-serializable object storing the value, or nil in case of cache-miss
44
+ def read(key)
45
+ @cache_content.key?(key) ? @cache_content[key] : nil
46
+ end
47
+
48
+ alias [] read
49
+
50
+ # Write a key/value in the cache
51
+ #
52
+ # Parameters:
53
+ # * *key* (String): The key
54
+ # * *value* (Object): JSON-serializable object storing the value
55
+ def write(key, value)
56
+ @cache_content[key] = value
57
+ end
58
+
59
+ alias []= write
60
+
61
+ # Delete a key in the cache
62
+ #
63
+ # Parameters:
64
+ # * *key* (String): The key
65
+ def delete(key)
66
+ @cache_content.delete(key)
67
+ end
68
+
69
+ end
70
+
71
+ end
@@ -1,5 +1,5 @@
1
1
  class NexusMods
2
2
 
3
- VERSION = '0.2.0'
3
+ VERSION = '0.4.0'
4
4
 
5
5
  end
data/lib/nexus_mods.rb CHANGED
@@ -1,8 +1,7 @@
1
- require 'addressable/uri'
2
1
  require 'json'
3
2
  require 'time'
4
3
  require 'tmpdir'
5
- require 'faraday'
4
+ require 'nexus_mods/api_client'
6
5
  require 'nexus_mods/api/api_limits'
7
6
  require 'nexus_mods/api/category'
8
7
  require 'nexus_mods/api/game'
@@ -40,27 +39,39 @@ class NexusMods
40
39
  # * *game_domain_name* (String): Game domain name to query by default [default: 'skyrimspecialedition']
41
40
  # * *mod_id* (Integer): Mod to query by default [default: 1]
42
41
  # * *file_id* (Integer): File to query by default [default: 1]
42
+ # * *http_cache_file* (String): File used to store the HTTP cache, or nil for no cache [default: "#{Dir.tmpdir}/nexus_mods_http_cache.json"]
43
+ # * *api_cache_expiry* (Hash<Symbol,Integer>): Expiry times in seconds, per expiry key. Possible keys are:
44
+ # * *games*: Expiry associated to queries on games [default: 1 day]
45
+ # * *mod*: Expiry associated to queries on mod [default: 1 day]
46
+ # * *mod_files*: Expiry associated to queries on mod files [default: 1 day]
47
+ # * *api_cache_file* (String): File used to store the NexusMods API cache, or nil for no cache [default: "#{Dir.tmpdir}/nexus_mods_api_cache.json"]
43
48
  # * *logger* (Logger): The logger to be used for log messages [default: Logger.new(STDOUT)]
44
49
  def initialize(
45
50
  api_key: nil,
46
51
  game_domain_name: 'skyrimspecialedition',
47
52
  mod_id: 1,
48
53
  file_id: 1,
54
+ http_cache_file: "#{Dir.tmpdir}/nexus_mods_http_cache.json",
55
+ api_cache_expiry: {},
56
+ api_cache_file: "#{Dir.tmpdir}/nexus_mods_api_cache.json",
49
57
  logger: Logger.new($stdout)
50
58
  )
51
- @api_key = api_key
52
59
  @game_domain_name = game_domain_name
53
60
  @mod_id = mod_id
54
61
  @file_id = file_id
55
62
  @logger = logger
56
63
  @premium = false
57
- # Initialize our HTTP client
58
- @http_client = Faraday.new do |builder|
59
- builder.adapter Faraday.default_adapter
60
- end
64
+ @api_client = ApiClient.new(
65
+ api_key:,
66
+ http_cache_file:,
67
+ api_cache_expiry:,
68
+ api_cache_file:,
69
+ logger:
70
+ )
71
+
61
72
  # Check that the key is correct and know if the user is premium
62
73
  begin
63
- @premium = api('users/validate')['is_premium?']
74
+ @premium = @api_client.api('users/validate')['is_premium?']
64
75
  rescue LimitsExceededError
65
76
  raise
66
77
  rescue ApiError
@@ -74,7 +85,7 @@ class NexusMods
74
85
  # Result::
75
86
  # * ApiLimits: API calls limits
76
87
  def api_limits
77
- api_limits_headers = http('users/validate').headers
88
+ api_limits_headers = @api_client.http('users/validate').headers
78
89
  Api::ApiLimits.new(
79
90
  daily_limit: Integer(api_limits_headers['x-rl-daily-limit']),
80
91
  daily_remaining: Integer(api_limits_headers['x-rl-daily-remaining']),
@@ -90,7 +101,7 @@ class NexusMods
90
101
  # Result::
91
102
  # * Array<Game>: List of games
92
103
  def games
93
- api('games').map do |game_json|
104
+ @api_client.api('games').map do |game_json|
94
105
  # First create categories tree
95
106
  # Hash<Integer, [Category, Integer]>: Category and its parent category id, per category id
96
107
  categories = game_json['categories'].to_h do |category_json|
@@ -137,7 +148,7 @@ class NexusMods
137
148
  # Result::
138
149
  # * Mod: Mod information
139
150
  def mod(game_domain_name: @game_domain_name, mod_id: @mod_id)
140
- mod_json = api "games/#{game_domain_name}/mods/#{mod_id}"
151
+ mod_json = @api_client.api "games/#{game_domain_name}/mods/#{mod_id}"
141
152
  Api::Mod.new(
142
153
  uid: mod_json['uid'],
143
154
  mod_id: mod_json['mod_id'],
@@ -185,7 +196,7 @@ class NexusMods
185
196
  # Result::
186
197
  # * Array<ModFile>: List of mod's files
187
198
  def mod_files(game_domain_name: @game_domain_name, mod_id: @mod_id)
188
- api("games/#{game_domain_name}/mods/#{mod_id}/files")['files'].map do |file_json|
199
+ @api_client.api("games/#{game_domain_name}/mods/#{mod_id}/files")['files'].map do |file_json|
189
200
  category_id = FILE_CATEGORIES[file_json['category_id']]
190
201
  raise "Unknown file category: #{file_json['category_id']}" if category_id.nil?
191
202
 
@@ -210,66 +221,4 @@ class NexusMods
210
221
  end
211
222
  end
212
223
 
213
- private
214
-
215
- # Send an HTTP request to the API and get back the answer as a JSON
216
- #
217
- # Parameters::
218
- # * *path* (String): API path to contact (from v1/ and without .json)
219
- # * *verb* (Symbol): Verb to be used (:get, :post...) [default: :get]
220
- # Result::
221
- # * Object: The JSON response
222
- def api(path, verb: :get)
223
- res = http(path, verb:)
224
- json = JSON.parse(res.body)
225
- uri = api_uri(path)
226
- @logger.debug "[API call] - #{verb} #{uri} => #{res.status}\n#{
227
- JSON.
228
- pretty_generate(json).
229
- split("\n").
230
- map { |line| " #{line}" }.
231
- join("\n")
232
- }\n#{
233
- res.
234
- headers.
235
- map { |header, value| " #{header}: #{value}" }.
236
- join("\n")
237
- }"
238
- case res.status
239
- when 200
240
- # Happy
241
- when 429
242
- # Some limits of the API have been reached
243
- raise LimitsExceededError, "Exceeding limits of API calls: #{res.headers.select { |header, _value| header =~ /^x-rl-.+$/ }}"
244
- else
245
- raise ApiError, "API #{uri} returned error code #{res.status}" unless res.status == '200'
246
- end
247
- json
248
- end
249
-
250
- # Send an HTTP request to the API and get back the HTTP response
251
- #
252
- # Parameters::
253
- # * *path* (String): API path to contact (from v1/ and without .json)
254
- # * *verb* (Symbol): Verb to be used (:get, :post...) [default: :get]
255
- # Result::
256
- # * Faraday::Response: The HTTP response
257
- def http(path, verb: :get)
258
- @http_client.send(verb) do |req|
259
- req.url api_uri(path)
260
- req.headers['apikey'] = @api_key
261
- req.headers['User-Agent'] = "nexus_mods (#{RUBY_PLATFORM}) Ruby/#{RUBY_VERSION}"
262
- end
263
- end
264
-
265
- # Get the real URI to query for a given API path
266
- #
267
- # Parameters::
268
- # * *path* (String): API path to contact (from v1/ and without .json)
269
- # Result::
270
- # * String: The URI
271
- def api_uri(path)
272
- "https://api.nexusmods.com/v1/#{path}.json"
273
- end
274
-
275
224
  end
@@ -55,6 +55,9 @@ module NexusModsTest
55
55
  def nexus_mods(**args)
56
56
  if @nexus_mods.nil?
57
57
  args[:api_key] = MOCKED_API_KEY unless args.key?(:api_key)
58
+ # By default running tests should not persistent cache files
59
+ args[:http_cache_file] = nil unless args.key?(:http_cache_file)
60
+ args[:api_cache_file] = nil unless args.key?(:api_cache_file)
58
61
  # Redirect any log into a string so that they don't pollute the tests output and they could be asserted.
59
62
  nexus_mods_logger = StringIO.new
60
63
  args[:logger] = Logger.new(nexus_mods_logger)
@@ -134,6 +137,19 @@ module NexusModsTest
134
137
  )
135
138
  end
136
139
 
140
+ # Setup an API cache file to be used (does not create it)
141
+ #
142
+ # Parameters::
143
+ # * CodeBlock: The code called when the API cache file is reserved
144
+ # * Parameters::
145
+ # * *api_cache_file* (String): File name to be used for the API cache file
146
+ def with_api_cache_file
147
+ api_cache_file = "#{Dir.tmpdir}/nexus_mods_test/api_cache.json"
148
+ FileUtils.mkdir_p(File.dirname(api_cache_file))
149
+ FileUtils.rm_f(api_cache_file)
150
+ yield api_cache_file
151
+ end
152
+
137
153
  end
138
154
 
139
155
  end
@@ -145,6 +161,8 @@ RSpec.configure do |config|
145
161
  config.include NexusModsTest::Factories::ModFiles
146
162
  config.before do
147
163
  @nexus_mods = nil
164
+ # Reload the ApiClient as it stores caches at class level
165
+ NexusMods::ApiClient.clear_cacheable_expiry_caches
148
166
  # Keep a list of the etags we should have returned, so that we know when queries should contain them
149
167
  # Array<String>
150
168
  @expected_returned_etags = []
@@ -152,6 +170,11 @@ RSpec.configure do |config|
152
170
  # Array< [ WebMock::RequestStub, Integer ] >
153
171
  @expected_stubs = []
154
172
  end
173
+ config.after do
174
+ @expected_stubs.each do |(stub, times)|
175
+ expect(stub).to have_been_made.times(times)
176
+ end
177
+ end
155
178
  end
156
179
 
157
180
  # Set a bigger output length for expectation errors, as most error messages include API keys and headers which can be lengthy
@@ -0,0 +1,157 @@
1
+ require 'fileutils'
2
+
3
+ describe NexusMods do
4
+
5
+ context 'when testing caching' do
6
+
7
+ it 'does not cache user queries' do
8
+ expect_validate_user(times: 3)
9
+ nexus_mods.api_limits
10
+ nexus_mods.api_limits
11
+ end
12
+
13
+ it 'caches games queries' do
14
+ expect_validate_user
15
+ expect_http_call_to(
16
+ path: '/v1/games.json',
17
+ json: [
18
+ json_game100,
19
+ json_game101
20
+ ]
21
+ )
22
+ games = nexus_mods.games
23
+ expect(nexus_mods.games).to eq(games)
24
+ end
25
+
26
+ it 'caches mod queries' do
27
+ expect_validate_user
28
+ expect_http_call_to(
29
+ path: '/v1/games/skyrimspecialedition/mods/2014.json',
30
+ json: json_complete_mod
31
+ )
32
+ mod = nexus_mods.mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)
33
+ expect(nexus_mods.mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)).to eq(mod)
34
+ end
35
+
36
+ it 'caches mod files queries' do
37
+ expect_validate_user
38
+ expect_http_call_to(
39
+ path: '/v1/games/skyrimspecialedition/mods/2014/files.json',
40
+ json: { files: [json_mod_file2472, json_mod_file2487] }
41
+ )
42
+ mod_files = nexus_mods.mod_files(game_domain_name: 'skyrimspecialedition', mod_id: 2014)
43
+ expect(nexus_mods.mod_files(game_domain_name: 'skyrimspecialedition', mod_id: 2014)).to eq(mod_files)
44
+ end
45
+
46
+ it 'expires games queries cache' do
47
+ expect_validate_user
48
+ expect_http_call_to(
49
+ path: '/v1/games.json',
50
+ json: [
51
+ json_game100,
52
+ json_game101
53
+ ],
54
+ times: 2
55
+ )
56
+ nexus_mods_instance = nexus_mods(api_cache_expiry: { games: 1 })
57
+ games = nexus_mods_instance.games
58
+ sleep 2
59
+ expect(nexus_mods_instance.games).to eq(games)
60
+ end
61
+
62
+ it 'expires mod queries cache' do
63
+ expect_validate_user
64
+ expect_http_call_to(
65
+ path: '/v1/games/skyrimspecialedition/mods/2014.json',
66
+ json: json_complete_mod,
67
+ times: 2
68
+ )
69
+ nexus_mods_instance = nexus_mods(api_cache_expiry: { mod: 1 })
70
+ mod = nexus_mods_instance.mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)
71
+ sleep 2
72
+ expect(nexus_mods_instance.mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)).to eq(mod)
73
+ end
74
+
75
+ it 'expires mod files queries cache' do
76
+ expect_validate_user
77
+ expect_http_call_to(
78
+ path: '/v1/games/skyrimspecialedition/mods/2014/files.json',
79
+ json: { files: [json_mod_file2472, json_mod_file2487] },
80
+ times: 2
81
+ )
82
+ nexus_mods_instance = nexus_mods(api_cache_expiry: { mod_files: 1 })
83
+ mod_files = nexus_mods_instance.mod_files(game_domain_name: 'skyrimspecialedition', mod_id: 2014)
84
+ sleep 2
85
+ expect(nexus_mods_instance.mod_files(game_domain_name: 'skyrimspecialedition', mod_id: 2014)).to eq(mod_files)
86
+ end
87
+
88
+ context 'with file persistence' do
89
+
90
+ it 'persists API cache in a file' do
91
+ with_api_cache_file do |api_cache_file|
92
+ expect_validate_user
93
+ expect_http_call_to(
94
+ path: '/v1/games.json',
95
+ json: [
96
+ json_game100,
97
+ json_game101
98
+ ]
99
+ )
100
+ nexus_mods(api_cache_file:).games
101
+ expect(File.exist?(api_cache_file)).to be true
102
+ expect(File.size(api_cache_file)).to be > 0
103
+ end
104
+ end
105
+
106
+ it 'uses API cache from a file' do
107
+ with_api_cache_file do |api_cache_file|
108
+ expect_validate_user(times: 2)
109
+ expect_http_call_to(
110
+ path: '/v1/games.json',
111
+ json: [
112
+ json_game100,
113
+ json_game101
114
+ ]
115
+ )
116
+ # Generate the cache first
117
+ games = nexus_mods(api_cache_file:).games
118
+ # Force a new instance of NexusMods API to run
119
+ @nexus_mods = nil
120
+ expect(nexus_mods(api_cache_file:).games).to eq games
121
+ end
122
+ end
123
+
124
+ it 'completes the API cache from a file' do
125
+ with_api_cache_file do |api_cache_file|
126
+ expect_validate_user(times: 3)
127
+ # Generate the cache first for games only
128
+ expect_http_call_to(
129
+ path: '/v1/games.json',
130
+ json: [
131
+ json_game100,
132
+ json_game101
133
+ ]
134
+ )
135
+ games = nexus_mods(api_cache_file:).games
136
+ # Force a new instance of NexusMods API to run
137
+ @nexus_mods = nil
138
+ # Complete the cache with a mod
139
+ expect_http_call_to(
140
+ path: '/v1/games/skyrimspecialedition/mods/2014.json',
141
+ json: json_complete_mod
142
+ )
143
+ mod = nexus_mods(api_cache_file:).mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)
144
+ # Force a new instance of NexusMods API to run
145
+ @nexus_mods = nil
146
+ # Check that both API calls were cached correctly
147
+ nexus_mods_instance = nexus_mods(api_cache_file:)
148
+ expect(nexus_mods_instance.games).to eq games
149
+ expect(nexus_mods_instance.mod(game_domain_name: 'skyrimspecialedition', mod_id: 2014)).to eq mod
150
+ end
151
+ end
152
+
153
+ end
154
+
155
+ end
156
+
157
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nexus_mods
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Muriel Salvan
@@ -38,6 +38,20 @@ dependencies:
38
38
  - - "~>"
39
39
  - !ruby/object:Gem::Version
40
40
  version: '2.4'
41
+ - !ruby/object:Gem::Dependency
42
+ name: cacheable
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
41
55
  - !ruby/object:Gem::Dependency
42
56
  name: rspec
43
57
  requirement: !ruby/object:Gem::Requirement
@@ -128,6 +142,12 @@ files:
128
142
  - lib/nexus_mods/api/mod.rb
129
143
  - lib/nexus_mods/api/mod_file.rb
130
144
  - lib/nexus_mods/api/user.rb
145
+ - lib/nexus_mods/api_client.rb
146
+ - lib/nexus_mods/cacheable_api.rb
147
+ - lib/nexus_mods/cacheable_with_expiry.rb
148
+ - lib/nexus_mods/core_extensions/cacheable/cache_adapters/persistent_json_adapter.rb
149
+ - lib/nexus_mods/core_extensions/cacheable/method_generator.rb
150
+ - lib/nexus_mods/file_cache.rb
131
151
  - lib/nexus_mods/version.rb
132
152
  - spec/nexus_mods_test/factories/games.rb
133
153
  - spec/nexus_mods_test/factories/mod_files.rb
@@ -138,6 +158,7 @@ files:
138
158
  - spec/nexus_mods_test/scenarios/nexus_mods/api/mod_file_spec.rb
139
159
  - spec/nexus_mods_test/scenarios/nexus_mods/api/mod_spec.rb
140
160
  - spec/nexus_mods_test/scenarios/nexus_mods_access_spec.rb
161
+ - spec/nexus_mods_test/scenarios/nexus_mods_caching_spec.rb
141
162
  - spec/nexus_mods_test/scenarios/rubocop_spec.rb
142
163
  - spec/spec_helper.rb
143
164
  homepage: https://github.com/Muriel-Salvan/nexus_mods