nse_data 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/.rubocop.yml +7 -0
  3. data/CHANGELOG.md +22 -0
  4. data/CODE_OF_CONDUCT.md +84 -0
  5. data/Gemfile +24 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +179 -0
  8. data/Rakefile +72 -0
  9. data/doc/NseData/API/Base.html +350 -0
  10. data/doc/NseData/API/SpecialPreopen.html +220 -0
  11. data/doc/NseData/API.html +117 -0
  12. data/doc/NseData/APIManager.html +644 -0
  13. data/doc/NseData/Cache/CachePolicy.html +907 -0
  14. data/doc/NseData/Cache/CacheStore.html +674 -0
  15. data/doc/NseData/Cache.html +117 -0
  16. data/doc/NseData/Client.html +385 -0
  17. data/doc/NseData/Config/Base.html +552 -0
  18. data/doc/NseData/Config/Logger.html +430 -0
  19. data/doc/NseData/Config.html +117 -0
  20. data/doc/NseData/Error.html +124 -0
  21. data/doc/NseData/HttpClient/BaseClient.html +349 -0
  22. data/doc/NseData/HttpClient/FaradayClient.html +301 -0
  23. data/doc/NseData/HttpClient.html +117 -0
  24. data/doc/NseData.html +524 -0
  25. data/doc/_index.html +243 -0
  26. data/doc/class_list.html +54 -0
  27. data/doc/css/common.css +1 -0
  28. data/doc/css/full_list.css +58 -0
  29. data/doc/css/style.css +503 -0
  30. data/doc/file.README.html +304 -0
  31. data/doc/file_list.html +59 -0
  32. data/doc/frames.html +22 -0
  33. data/doc/index.html +304 -0
  34. data/doc/js/app.js +344 -0
  35. data/doc/js/full_list.js +242 -0
  36. data/doc/js/jquery.js +4 -0
  37. data/doc/method_list.html +294 -0
  38. data/doc/top-level-namespace.html +110 -0
  39. data/lib/nse_data/api_manager.rb +83 -0
  40. data/lib/nse_data/cache/README.md +77 -0
  41. data/lib/nse_data/cache/cache_policy.rb +118 -0
  42. data/lib/nse_data/cache/cache_store.rb +84 -0
  43. data/lib/nse_data/cache/redis_cache_store.rb +3 -0
  44. data/lib/nse_data/config/api_endpoints.yml +56 -0
  45. data/lib/nse_data/config/base.rb +38 -0
  46. data/lib/nse_data/config/logger.rb +39 -0
  47. data/lib/nse_data/http_client/base_client.rb +26 -0
  48. data/lib/nse_data/http_client/faraday_client.rb +68 -0
  49. data/lib/nse_data/version.rb +5 -0
  50. data/lib/nse_data.rb +65 -0
  51. data/nse_data.gemspec +34 -0
  52. metadata +131 -0
@@ -0,0 +1,294 @@
1
+ <!DOCTYPE html>
2
+ <html >
3
+ <head>
4
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
5
+ <meta charset="utf-8" />
6
+
7
+ <link rel="stylesheet" href="css/full_list.css" type="text/css" media="screen" />
8
+
9
+ <link rel="stylesheet" href="css/common.css" type="text/css" media="screen" />
10
+
11
+
12
+
13
+ <script type="text/javascript" charset="utf-8" src="js/jquery.js"></script>
14
+
15
+ <script type="text/javascript" charset="utf-8" src="js/full_list.js"></script>
16
+
17
+
18
+ <title>Method List</title>
19
+ <base id="base_target" target="_parent" />
20
+ </head>
21
+ <body>
22
+ <div id="content">
23
+ <div class="fixed_header">
24
+ <h1 id="full_list_header">Method List</h1>
25
+ <div id="full_list_nav">
26
+
27
+ <span><a target="_self" href="class_list.html">
28
+ Classes
29
+ </a></span>
30
+
31
+ <span><a target="_self" href="method_list.html">
32
+ Methods
33
+ </a></span>
34
+
35
+ <span><a target="_self" href="file_list.html">
36
+ Files
37
+ </a></span>
38
+
39
+ </div>
40
+
41
+ <div id="search">
42
+ <label for="search-class">Search:</label>
43
+ <input id="search-class" type="text" />
44
+ </div>
45
+ </div>
46
+
47
+ <ul id="full_list" class="method">
48
+
49
+
50
+ <li class="odd ">
51
+ <div class="item">
52
+ <span class='object_link'><a href="NseData/Config/Base.html#[]-instance_method" title="NseData::Config::Base#[] (method)">#[]</a></span>
53
+ <small>NseData::Config::Base</small>
54
+ </div>
55
+ </li>
56
+
57
+
58
+ <li class="even ">
59
+ <div class="item">
60
+ <span class='object_link'><a href="NseData/Config/Base.html#[]=-instance_method" title="NseData::Config::Base#[]= (method)">#[]=</a></span>
61
+ <small>NseData::Config::Base</small>
62
+ </div>
63
+ </li>
64
+
65
+
66
+ <li class="odd ">
67
+ <div class="item">
68
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#add_custom_ttl-instance_method" title="NseData::Cache::CachePolicy#add_custom_ttl (method)">#add_custom_ttl</a></span>
69
+ <small>NseData::Cache::CachePolicy</small>
70
+ </div>
71
+ </li>
72
+
73
+
74
+ <li class="even ">
75
+ <div class="item">
76
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#add_no_cache_endpoint-instance_method" title="NseData::Cache::CachePolicy#add_no_cache_endpoint (method)">#add_no_cache_endpoint</a></span>
77
+ <small>NseData::Cache::CachePolicy</small>
78
+ </div>
79
+ </li>
80
+
81
+
82
+ <li class="odd ">
83
+ <div class="item">
84
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#cache_store-instance_method" title="NseData::Cache::CachePolicy#cache_store (method)">#cache_store</a></span>
85
+ <small>NseData::Cache::CachePolicy</small>
86
+ </div>
87
+ </li>
88
+
89
+
90
+ <li class="even ">
91
+ <div class="item">
92
+ <span class='object_link'><a href="NseData.html#configure-class_method" title="NseData.configure (method)">configure</a></span>
93
+ <small>NseData</small>
94
+ </div>
95
+ </li>
96
+
97
+
98
+ <li class="odd ">
99
+ <div class="item">
100
+ <span class='object_link'><a href="NseData/Config/Logger.html#default_log_file-class_method" title="NseData::Config::Logger.default_log_file (method)">default_log_file</a></span>
101
+ <small>NseData::Config::Logger</small>
102
+ </div>
103
+ </li>
104
+
105
+
106
+ <li class="even ">
107
+ <div class="item">
108
+ <span class='object_link'><a href="NseData.html#define_api_methods-class_method" title="NseData.define_api_methods (method)">define_api_methods</a></span>
109
+ <small>NseData</small>
110
+ </div>
111
+ </li>
112
+
113
+
114
+ <li class="odd ">
115
+ <div class="item">
116
+ <span class='object_link'><a href="NseData/Cache/CacheStore.html#delete-instance_method" title="NseData::Cache::CacheStore#delete (method)">#delete</a></span>
117
+ <small>NseData::Cache::CacheStore</small>
118
+ </div>
119
+ </li>
120
+
121
+
122
+ <li class="even ">
123
+ <div class="item">
124
+ <span class='object_link'><a href="NseData/APIManager.html#endpoints-instance_method" title="NseData::APIManager#endpoints (method)">#endpoints</a></span>
125
+ <small>NseData::APIManager</small>
126
+ </div>
127
+ </li>
128
+
129
+
130
+ <li class="odd ">
131
+ <div class="item">
132
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#fetch-instance_method" title="NseData::Cache::CachePolicy#fetch (method)">#fetch</a></span>
133
+ <small>NseData::Cache::CachePolicy</small>
134
+ </div>
135
+ </li>
136
+
137
+
138
+ <li class="even ">
139
+ <div class="item">
140
+ <span class='object_link'><a href="NseData/Cache/CacheStore.html#fetch-instance_method" title="NseData::Cache::CacheStore#fetch (method)">#fetch</a></span>
141
+ <small>NseData::Cache::CacheStore</small>
142
+ </div>
143
+ </li>
144
+
145
+
146
+ <li class="odd ">
147
+ <div class="item">
148
+ <span class='object_link'><a href="NseData/APIManager.html#fetch_data-instance_method" title="NseData::APIManager#fetch_data (method)">#fetch_data</a></span>
149
+ <small>NseData::APIManager</small>
150
+ </div>
151
+ </li>
152
+
153
+
154
+ <li class="even ">
155
+ <div class="item">
156
+ <span class='object_link'><a href="NseData/HttpClient/FaradayClient.html#get-instance_method" title="NseData::HttpClient::FaradayClient#get (method)">#get</a></span>
157
+ <small>NseData::HttpClient::FaradayClient</small>
158
+ </div>
159
+ </li>
160
+
161
+
162
+ <li class="odd ">
163
+ <div class="item">
164
+ <span class='object_link'><a href="NseData/HttpClient/BaseClient.html#get-instance_method" title="NseData::HttpClient::BaseClient#get (method)">#get</a></span>
165
+ <small>NseData::HttpClient::BaseClient</small>
166
+ </div>
167
+ </li>
168
+
169
+
170
+ <li class="even ">
171
+ <div class="item">
172
+ <span class='object_link'><a href="NseData/Cache/CacheStore.html#initialize-instance_method" title="NseData::Cache::CacheStore#initialize (method)">#initialize</a></span>
173
+ <small>NseData::Cache::CacheStore</small>
174
+ </div>
175
+ </li>
176
+
177
+
178
+ <li class="odd ">
179
+ <div class="item">
180
+ <span class='object_link'><a href="NseData/Config/Base.html#initialize-instance_method" title="NseData::Config::Base#initialize (method)">#initialize</a></span>
181
+ <small>NseData::Config::Base</small>
182
+ </div>
183
+ </li>
184
+
185
+
186
+ <li class="even ">
187
+ <div class="item">
188
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#initialize-instance_method" title="NseData::Cache::CachePolicy#initialize (method)">#initialize</a></span>
189
+ <small>NseData::Cache::CachePolicy</small>
190
+ </div>
191
+ </li>
192
+
193
+
194
+ <li class="odd ">
195
+ <div class="item">
196
+ <span class='object_link'><a href="NseData/APIManager.html#initialize-instance_method" title="NseData::APIManager#initialize (method)">#initialize</a></span>
197
+ <small>NseData::APIManager</small>
198
+ </div>
199
+ </li>
200
+
201
+
202
+ <li class="even ">
203
+ <div class="item">
204
+ <span class='object_link'><a href="NseData/HttpClient/BaseClient.html#initialize-instance_method" title="NseData::HttpClient::BaseClient#initialize (method)">#initialize</a></span>
205
+ <small>NseData::HttpClient::BaseClient</small>
206
+ </div>
207
+ </li>
208
+
209
+
210
+ <li class="odd ">
211
+ <div class="item">
212
+ <span class='object_link'><a href="NseData/Config/Logger.html#initialize-instance_method" title="NseData::Config::Logger#initialize (method)">#initialize</a></span>
213
+ <small>NseData::Config::Logger</small>
214
+ </div>
215
+ </li>
216
+
217
+
218
+ <li class="even ">
219
+ <div class="item">
220
+ <span class='object_link'><a href="NseData.html#list_all_endpoints-class_method" title="NseData.list_all_endpoints (method)">list_all_endpoints</a></span>
221
+ <small>NseData</small>
222
+ </div>
223
+ </li>
224
+
225
+
226
+ <li class="odd ">
227
+ <div class="item">
228
+ <span class='object_link'><a href="NseData/APIManager.html#load_endpoints-instance_method" title="NseData::APIManager#load_endpoints (method)">#load_endpoints</a></span>
229
+ <small>NseData::APIManager</small>
230
+ </div>
231
+ </li>
232
+
233
+
234
+ <li class="even ">
235
+ <div class="item">
236
+ <span class='object_link'><a href="NseData.html#logger-class_method" title="NseData.logger (method)">logger</a></span>
237
+ <small>NseData</small>
238
+ </div>
239
+ </li>
240
+
241
+
242
+ <li class="odd ">
243
+ <div class="item">
244
+ <span class='object_link'><a href="NseData/Config/Logger.html#logger-instance_method" title="NseData::Config::Logger#logger (method)">#logger</a></span>
245
+ <small>NseData::Config::Logger</small>
246
+ </div>
247
+ </li>
248
+
249
+
250
+ <li class="even ">
251
+ <div class="item">
252
+ <span class='object_link'><a href="NseData/Cache/CacheStore.html#read-instance_method" title="NseData::Cache::CacheStore#read (method)">#read</a></span>
253
+ <small>NseData::Cache::CacheStore</small>
254
+ </div>
255
+ </li>
256
+
257
+
258
+ <li class="odd ">
259
+ <div class="item">
260
+ <span class='object_link'><a href="NseData/Config/Base.html#settings-instance_method" title="NseData::Config::Base#settings (method)">#settings</a></span>
261
+ <small>NseData::Config::Base</small>
262
+ </div>
263
+ </li>
264
+
265
+
266
+ <li class="even ">
267
+ <div class="item">
268
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#ttl_for-instance_method" title="NseData::Cache::CachePolicy#ttl_for (method)">#ttl_for</a></span>
269
+ <small>NseData::Cache::CachePolicy</small>
270
+ </div>
271
+ </li>
272
+
273
+
274
+ <li class="odd ">
275
+ <div class="item">
276
+ <span class='object_link'><a href="NseData/Cache/CachePolicy.html#use_cache%3F-instance_method" title="NseData::Cache::CachePolicy#use_cache? (method)">#use_cache?</a></span>
277
+ <small>NseData::Cache::CachePolicy</small>
278
+ </div>
279
+ </li>
280
+
281
+
282
+ <li class="even ">
283
+ <div class="item">
284
+ <span class='object_link'><a href="NseData/Cache/CacheStore.html#write-instance_method" title="NseData::Cache::CacheStore#write (method)">#write</a></span>
285
+ <small>NseData::Cache::CacheStore</small>
286
+ </div>
287
+ </li>
288
+
289
+
290
+
291
+ </ul>
292
+ </div>
293
+ </body>
294
+ </html>
@@ -0,0 +1,110 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>
7
+ Top Level Namespace
8
+
9
+ &mdash; Documentation by YARD 0.9.37
10
+
11
+ </title>
12
+
13
+ <link rel="stylesheet" href="css/style.css" type="text/css" />
14
+
15
+ <link rel="stylesheet" href="css/common.css" type="text/css" />
16
+
17
+ <script type="text/javascript">
18
+ pathId = "";
19
+ relpath = '';
20
+ </script>
21
+
22
+
23
+ <script type="text/javascript" charset="utf-8" src="js/jquery.js"></script>
24
+
25
+ <script type="text/javascript" charset="utf-8" src="js/app.js"></script>
26
+
27
+
28
+ </head>
29
+ <body>
30
+ <div class="nav_wrap">
31
+ <iframe id="nav" src="class_list.html?1"></iframe>
32
+ <div id="resizer"></div>
33
+ </div>
34
+
35
+ <div id="main" tabindex="-1">
36
+ <div id="header">
37
+ <div id="menu">
38
+
39
+ <a href="_index.html">Index</a> &raquo;
40
+
41
+
42
+ <span class="title">Top Level Namespace</span>
43
+
44
+ </div>
45
+
46
+ <div id="search">
47
+
48
+ <a class="full_list_link" id="class_list_link"
49
+ href="class_list.html">
50
+
51
+ <svg width="24" height="24">
52
+ <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
53
+ <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
54
+ <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
55
+ </svg>
56
+ </a>
57
+
58
+ </div>
59
+ <div class="clear"></div>
60
+ </div>
61
+
62
+ <div id="content"><h1>Top Level Namespace
63
+
64
+
65
+
66
+ </h1>
67
+ <div class="box_info">
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+ </div>
80
+
81
+ <h2>Defined Under Namespace</h2>
82
+ <p class="children">
83
+
84
+
85
+ <strong class="modules">Modules:</strong> <span class='object_link'><a href="NseData.html" title="NseData (module)">NseData</a></span>
86
+
87
+
88
+
89
+
90
+ </p>
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+ </div>
101
+
102
+ <div id="footer">
103
+ Generated on Tue Sep 10 12:25:13 2024 by
104
+ <a href="https://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a>
105
+ 0.9.37 (ruby-3.2.2).
106
+ </div>
107
+
108
+ </div>
109
+ </body>
110
+ </html>
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require_relative 'http_client/faraday_client'
5
+ require_relative 'cache/cache_policy'
6
+ require_relative 'cache/cache_store'
7
+
8
+ module NseData
9
+ # APIManager class to handle API calls to NSE (National Stock Exchange) India website.
10
+ class APIManager
11
+ BASE_URL = 'https://www.nseindia.com/api/'
12
+
13
+ # Initializes a new instance of the APIManager class.
14
+ #
15
+ # @param cache_store [CacheStore, RedisCacheStore, nil] The cache store to use for caching.
16
+ # If nil, in-memory cache is used.
17
+ def initialize(cache_store: nil)
18
+ # Initialize cache policy with the provided cache store or default to in-memory cache.
19
+ @cache_policy = NseData::Cache::CachePolicy.new(cache_store || NseData::Cache::CacheStore.new)
20
+
21
+ # Configure cache policy (e.g., setting endpoints with no cache or custom TTL).
22
+ configure_cache_policy
23
+
24
+ # Initialize Faraday client with the base URL and cache policy.
25
+ @client = NseData::HttpClient::FaradayClient.new(BASE_URL, @cache_policy)
26
+
27
+ # Load API endpoints from the configuration file.
28
+ @endpoints = load_endpoints
29
+ end
30
+
31
+ # Fetches data from the specified API endpoint.
32
+ #
33
+ # @param endpoint_key [String] The key of the API endpoint to fetch data from.
34
+ # @param force_refresh [Boolean] Whether to force refresh the data, bypassing the cache.
35
+ # @return [Faraday::Response] The response object containing the fetched data.
36
+ # @raise [ArgumentError] If the provided endpoint key is invalid.
37
+ def fetch_data(endpoint_key, force_refresh: false)
38
+ NseData.logger.debug("#{self.class}##{__method__}: fetching data for #{endpoint_key}")
39
+ endpoint = @endpoints[endpoint_key]
40
+ raise ArgumentError, "Invalid endpoint key: #{endpoint_key}" unless endpoint
41
+
42
+ # Use cache policy to fetch data, with an option to force refresh.
43
+ @cache_policy.fetch(endpoint['path'], force_refresh:) do
44
+ @client.get(endpoint['path'])
45
+ end
46
+ end
47
+
48
+ # Loads the API endpoints from the configuration file.
49
+ #
50
+ # @return [Hash] The hash containing the loaded API endpoints.
51
+ # @raise [RuntimeError] If the configuration file is missing or has syntax errors.
52
+ def load_endpoints
53
+ yaml_content = YAML.load_file(File.expand_path('config/api_endpoints.yml', __dir__))
54
+ yaml_content['apis']
55
+ rescue Errno::ENOENT => e
56
+ raise "Configuration file not found: #{e.message}"
57
+ rescue Psych::SyntaxError => e
58
+ raise "YAML syntax error: #{e.message}"
59
+ end
60
+
61
+ # @return [Hash] The hash containing the loaded API endpoints.
62
+ attr_reader :endpoints
63
+
64
+ private
65
+
66
+ # Configures the cache policy with specific settings.
67
+ #
68
+ # This method sets endpoints that should not be cached and custom TTL values for specific endpoints.
69
+ def configure_cache_policy
70
+ # TODO: Review and refine cache policy for endpoints.
71
+ # Plan to analyze the API responses and categorize endpoints into:
72
+ # - No cache
73
+ # - Cacheable
74
+ # - Custom TTL
75
+
76
+ # Set specific endpoints that should not be cached.
77
+ @cache_policy.add_no_cache_endpoint('market_status')
78
+
79
+ # Set custom TTL (time-to-live) for specific endpoints.
80
+ @cache_policy.add_custom_ttl('equity_master', 600) # Custom TTL: 10 mins
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,77 @@
1
+ # Caching Mechanism Usage and Customization
2
+
3
+ ## Overview
4
+
5
+ The **NseData** gem includes a flexible caching mechanism to improve performance and reduce redundant API calls. This documentation provides an overview of how to use and customize the caching mechanism.
6
+
7
+ ## Cache Policy
8
+
9
+ The `CachePolicy` class is responsible for managing caching behavior, including setting global TTLs, custom TTLs for specific endpoints, and controlling which endpoints should bypass the cache.
10
+
11
+ ### Initializing CachePolicy
12
+
13
+ To use caching, you need to initialize the `CachePolicy` with a cache store and optional global TTL:
14
+
15
+ ```ruby
16
+ require 'nse_data/cache/cache_policy'
17
+ require 'nse_data/cache/cache_store'
18
+
19
+ # Initialize the cache store (e.g., in-memory cache store)
20
+ cache_store = NseData::Cache::CacheStore.new
21
+
22
+ # Initialize the CachePolicy with the cache store and a global TTL of 300 seconds (5 minutes)
23
+ cache_policy = NseData::Cache::CachePolicy.new(cache_store, global_ttl: 300)
24
+ ```
25
+
26
+ ### Configuring Cache Policy
27
+ #### Adding No-Cache Endpoints
28
+ You can specify endpoints that should bypass the cache:
29
+ ```ruby
30
+ # Add an endpoint to the no-cache list
31
+ cache_policy.add_no_cache_endpoint('/no-cache')
32
+ ```
33
+
34
+ #### Adding Custom TTLs
35
+ You can define custom TTLs for specific endpoints:
36
+
37
+ ```ruby
38
+ # Set a custom TTL of 600 seconds (10 minutes) for a specific endpoint
39
+ cache_policy.add_custom_ttl('/custom-ttl', ttl: 600)
40
+ ```
41
+
42
+ #### Fetching Data with Cache
43
+ Use the fetch method to retrieve data with caching applied:
44
+
45
+ ```ruby
46
+ # Fetch data for an endpoint with optional cache
47
+ data = cache_policy.fetch('/some-endpoint') do
48
+ # The block should fetch fresh data if cache is not used or is stale
49
+ # e.g., perform an API call or other data retrieval operation
50
+ Faraday::Response.new(body: 'fresh data')
51
+ end
52
+ ```
53
+ ## Custom Cache Stores
54
+ You can extend the caching mechanism to support different types of cache stores. Implement a custom cache store by inheriting from the CacheStore base class and overriding the read and write methods.
55
+
56
+ ### Example Custom Cache Store
57
+ ```ruby
58
+ class CustomCacheStore < NseData::Cache::CacheStore
59
+ def read(key)
60
+ # Implement custom read logic
61
+ end
62
+
63
+ def write(key, value, ttl)
64
+ # Implement custom write logic
65
+ end
66
+ end
67
+ ```
68
+ ### Using a Custom Cache Store
69
+ To use a custom cache store, initialize CachePolicy with an instance of your custom cache store:
70
+
71
+ ```ruby
72
+ # Initialize the custom cache store
73
+ custom_cache_store = CustomCacheStore.new
74
+
75
+ # Initialize CachePolicy with the custom cache store
76
+ cache_policy = NseData::Cache::CachePolicy.new(custom_cache_store, global_ttl: 300)
77
+ ```
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NseData
4
+ module Cache
5
+ # CachePolicy manages caching behavior, including cache storage and time-to-live (TTL) settings.
6
+ #
7
+ # It allows setting global TTLs, custom TTLs for specific endpoints, and controlling which
8
+ # endpoints should not use the cache.
9
+ #
10
+ # @attr_reader [CacheStore] cache_store The cache store used for storing cached data.
11
+ class CachePolicy
12
+ attr_reader :cache_store
13
+
14
+ # Initializes the CachePolicy with a cache store and global TTL.
15
+ #
16
+ # @param cache_store [CacheStore, RedisCacheStore] The cache store to use for caching.
17
+ # @param global_ttl [Integer] The default TTL (in seconds) for caching.
18
+ def initialize(cache_store, global_ttl = 300)
19
+ @cache_store = cache_store
20
+ @global_ttl = global_ttl
21
+ @custom_ttls = {}
22
+ @no_cache_endpoints = []
23
+ end
24
+
25
+ # Adds an endpoint that should bypass the cache.
26
+ #
27
+ # @param endpoint [String] The endpoint to exclude from caching.
28
+ def add_no_cache_endpoint(endpoint)
29
+ @no_cache_endpoints << endpoint
30
+ end
31
+
32
+ # Adds a custom TTL for a specific endpoint.
33
+ #
34
+ # @param endpoint [String] The endpoint to apply a custom TTL to.
35
+ # @param ttl [Integer] The custom TTL value in seconds.
36
+ def add_custom_ttl(endpoint, ttl = 300)
37
+ @custom_ttls[endpoint] = ttl
38
+ end
39
+
40
+ # Returns the TTL for a specific endpoint. Defaults to the global TTL if no custom TTL is set.
41
+ #
42
+ # @param endpoint [String] The endpoint to fetch the TTL for.
43
+ # @return [Integer] The TTL in seconds.
44
+ def ttl_for(endpoint)
45
+ @custom_ttls.fetch(endpoint, @global_ttl)
46
+ end
47
+
48
+ # Determines if caching should be used for the given endpoint.
49
+ #
50
+ # @param endpoint [String] The endpoint to check.
51
+ # @return [Boolean] True if caching is enabled for the endpoint, false otherwise.
52
+ def use_cache?(endpoint)
53
+ !@no_cache_endpoints.include?(endpoint)
54
+ end
55
+
56
+ # Fetches the data for the given endpoint, using cache if applicable.
57
+ #
58
+ # @param endpoint [String] The endpoint to fetch data for.
59
+ # @param force_refresh [Boolean] Whether to force refresh the data, bypassing the cache.
60
+ # @yield The block that fetches fresh data if cache is not used or is stale.
61
+ # @return [Object] The data fetched from cache or fresh data.
62
+ def fetch(endpoint, force_refresh: false, &block)
63
+ if force_refresh || !use_cache?(endpoint)
64
+ fetch_fresh_data(endpoint, &block)
65
+ else
66
+ fetch_cached_or_fresh_data(endpoint, &block)
67
+ end
68
+ end
69
+
70
+ private
71
+
72
+ # Fetches fresh data and writes it to the cache if applicable.
73
+ #
74
+ # @param endpoint [String] The endpoint to fetch fresh data for.
75
+ # @yield The block that fetches fresh data.
76
+ # @return [Object] The fresh data.
77
+ def fetch_fresh_data(endpoint)
78
+ NseData.logger.debug("#{self.class}##{__method__}: fetching fresh data for #{endpoint}")
79
+
80
+ fresh_data = yield
81
+ cache_fresh_data(endpoint, fresh_data)
82
+ fresh_data
83
+ end
84
+
85
+ # Fetches cached data or fresh data if not available in the cache.
86
+ #
87
+ # @param endpoint [String] The endpoint to fetch data for.
88
+ # @yield The block that fetches fresh data if cache is not used or is stale.
89
+ # @return [Object] The cached or fresh data.
90
+ def fetch_cached_or_fresh_data(endpoint, &block)
91
+ cached_data = @cache_store.read(endpoint)
92
+ if cached_data
93
+ NseData.logger.debug("#{self.class}##{__method__}: fetching cached data for #{endpoint}")
94
+ Faraday::Response.new(body: cached_data)
95
+ else
96
+ fetch_fresh_data(endpoint, &block)
97
+ end
98
+ end
99
+
100
+ # Writes fresh data to the cache.
101
+ #
102
+ # @param endpoint [String] The endpoint for which to store the data.
103
+ # @param fresh_data [Object] The data to be stored in the cache.
104
+ def cache_fresh_data(endpoint, fresh_data)
105
+ ttl = determine_ttl(endpoint)
106
+ @cache_store.write(endpoint, fresh_data.body, ttl) if fresh_data.is_a?(Faraday::Response)
107
+ end
108
+
109
+ # Determines the TTL value for the given endpoint.
110
+ #
111
+ # @param endpoint [String] The endpoint to fetch the TTL for.
112
+ # @return [Integer] The TTL value in seconds.
113
+ def determine_ttl(endpoint)
114
+ @custom_ttls.fetch(endpoint, @global_ttl)
115
+ end
116
+ end
117
+ end
118
+ end