Class: ConfigFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb

Overview

ConfigFetcher

Handles fetching configurations from the App Configuration API. This class encapsulates all API call logic and response handling.

Instance Method Summary collapse

Constructor Details

#initialize(collection_id:, environment_id:, logger: nil) ⇒ ConfigFetcher

Initialize the config fetcher

Parameters:

  • collection_id (String)

    Collection ID for API request

  • environment_id (String)

    Environment ID for API request

  • logger (Logger) (defaults to: nil)

    Optional logger instance



37
38
39
40
41
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb', line 37

def initialize(collection_id:, environment_id:, logger: nil)
  @collection_id = collection_id
  @environment_id = environment_id
  @logger = logger || Logger.instance
end

Instance Method Details

#display_response(data) ⇒ Object

Display API response in a readable format

Parameters:

  • data (Hash)

    API response data



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb', line 121

def display_response(data)
  # require 'json'

  # @logger.info("\nšŸ“Š API Response Summary:")
  # @logger.info("-" * 80)

  # # Display features
  # if data['features'] && data['features'].any?
  #   @logger.info("\nšŸ“‹ Features (#{data['features'].length}):")
  #   data['features'].each_with_index do |feature, index|
  #     @logger.info("  #{index + 1}. #{feature['name']} (#{feature['feature_id']})")
  #     @logger.info("     Type: #{feature['type']}")
  #     @logger.info("     Enabled: #{feature['enabled']}")
  #     if feature['segment_rules'] && feature['segment_rules'].any?
  #       @logger.info("     Segment Rules: #{feature['segment_rules'].length}")
  #     end
  #   end
  # else
  #   @logger.info("\nšŸ“‹ Features: None")
  # end

  # # Display properties
  # if data['properties'] && data['properties'].any?
  #   @logger.info("\nšŸ”§ Properties (#{data['properties'].length}):")
  #   data['properties'].each_with_index do |property, index|
  #     @logger.info("  #{index + 1}. #{property['name']} (#{property['property_id']})")
  #     @logger.info("     Type: #{property['type']}")
  #     @logger.info("     Value: #{property['value']}")
  #     if property['segment_rules'] && property['segment_rules'].any?
  #       @logger.info("     Segment Rules: #{property['segment_rules'].length}")
  #     end
  #   end
  # else
  #   @logger.info("\nšŸ”§ Properties: None")
  # end

  # # Display segments
  # if data['segments'] && data['segments'].any?
  #   @logger.info("\nšŸ‘„ Segments (#{data['segments'].length}):")
  #   data['segments'].each_with_index do |segment, index|
  #     @logger.info("  #{index + 1}. #{segment['name']} (#{segment['segment_id']})")
  #     if segment['rules'] && segment['rules'].any?
  #       @logger.info("     Rules: #{segment['rules'].length}")
  #     end
  #   end
  # else
  #   @logger.info("\nšŸ‘„ Segments: None")
  # end

  # @logger.info("\nšŸ“„ Full JSON Response:")
  # @logger.info("-" * 80)
  # @logger.info(JSON.pretty_generate(data))
  # @logger.info("=" * 80)
end

#fetchHash

Fetch configuration from API

Makes a direct API call to the /config endpoint Returns a hash with status information

Returns:

  • (Hash)

    Result hash with :ok, :retryable, :status, and :data keys



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb', line 49

def fetch
  # Get the BaseService client
  client = ApiManager.base_service_client
  url_builder = UrlBuilder.instance

  # Build the API endpoint URL
  api_path = "/apprapp/feature/v1/instances/#{url_builder.guid}/config"

  @logger.info("šŸ“” Calling API: #{url_builder.base_service_url}#{api_path}")

  # Make the API request
  response = client.request(
    method: "GET",
    url: api_path,
    headers: ApiManager.headers,
    params: {
      action: "sdkConfig",
      collection_id: @collection_id,
      environment_id: @environment_id
    }
  )

  # Success case
  if response.status == 200
    @logger.info("āœ“ API call successful (200)")
    {
      ok: true,
      retryable: false,
      status: 200,
      data: response.result
    }
  else
    # Unexpected status code
    @logger.warn("āš ļø  Unexpected status code: #{response.status}")
    {
      ok: false,
      retryable: true,
      status: response.status,
      data: nil
    }
  end
rescue IBMCloudSdkCore::ApiException => e
  status_code = e.code.to_i
  @logger.error("āŒ API Exception: #{e.message} (Status: #{status_code})")

  # Determine if error is retryable
  # Non-retryable: 4xx except 429
  # Retryable: 429, 5xx
  retryable = status_code == 429 || status_code >= 500

  {
    ok: false,
    retryable: retryable,
    status: status_code,
    data: nil
  }
rescue StandardError => e
  @logger.error("āŒ Unexpected error: #{e.message}")
  @logger.error(e.backtrace.first(3).join("\n"))

  # Treat unexpected errors as retryable
  {
    ok: false,
    retryable: true,
    status: 500,
    data: nil
  }
end

#load_configurations_to_cache(data) ⇒ Boolean

Load configurations to cache

Delegates to ConfigurationHandler singleton to maintain a single source of truth. This ensures all parts of the application use the same cache.

Parameters:

  • data (Hash)

    Configuration data with :features, :properties, and :segments keys

Returns:

  • (Boolean)

    true if configurations were loaded successfully



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb', line 232

def load_configurations_to_cache(data)
  return false unless data

  begin
    @logger.info("šŸ“¦ Loading configurations to ConfigurationHandler cache...")

    # Delegate to ConfigurationHandler singleton (single source of truth)
    handler = ConfigurationHandler.instance
    handler.load_configurations_to_cache(data)

    @logger.info("āœ… Configurations loaded to cache successfully")
    @logger.info("  āœ“ Features: #{data[:features]&.length || 0}")
    @logger.info("  āœ“ Properties: #{data[:properties]&.length || 0}")
    @logger.info("  āœ“ Segments: #{data[:segments]&.length || 0}")

    true
  rescue StandardError => e
    @logger.error("āŒ Error loading configurations to cache: #{e.message}")
    @logger.error(e.backtrace.first(5).join("\n"))
    false
  end
end

#process_and_load_configurations(api_response) ⇒ Boolean

Process API response and load to cache

This method:

  1. Takes the raw API response

  2. Calls extract_configurations to parse and validate the data

  3. Calls load_configurations_to_cache to store in cache

Parameters:

  • api_response (Hash)

    Raw API response data

Returns:

  • (Boolean)

    true if processing was successful, false otherwise



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/ibm_appconfiguration_ruby_sdk/configurations/internal/retry_manager/config_fetcher.rb', line 185

def process_and_load_configurations(api_response)
  return false unless api_response

  begin
    @logger.info("šŸ”„ Processing API response...")

    # Convert string keys to symbol keys if needed
    symbolized_data = symbolize_keys(api_response)

    # Extract configurations using utils.rb method
    # This validates the data and extracts only the relevant features, properties, and segments
    # for the specified environment and collection
    extracted_config = extract_configurations(
      symbolized_data,
      @environment_id,
      @collection_id
    )

    @logger.info("āœ“ Configurations extracted successfully")
    @logger.info("  Features: #{extracted_config[:features]&.length || 0}")
    @logger.info("  Properties: #{extracted_config[:properties]&.length || 0}")
    @logger.info("  Segments: #{extracted_config[:segments]&.length || 0}")

    # Load the extracted configurations to cache
    success = load_configurations_to_cache(extracted_config)

    if success
      @logger.info("āœ… Configurations processed and loaded successfully")
    else
      @logger.error("āŒ Failed to load configurations to cache")
    end

    success
  rescue StandardError => e
    @logger.error("āŒ Error processing API response: #{e.message}")
    @logger.error(e.backtrace.first(5).join("\n"))
    false
  end
end