|
| 1 | +# Elasticsearch API 9.x Compatibility Patch |
| 2 | +# |
| 3 | +# Fixes crashes in elasticsearch-api gem 9.1.2 when connecting to ES 7.x/8.x servers. |
| 4 | +# |
| 5 | +# Bug: The gem expects ES 9 headers and crashes with NoMethodError when they're nil |
| 6 | +# Fix: Add nil safety checks and skip ES9-specific processing for ES 7/8 |
| 7 | +# |
| 8 | +# This patch is only needed if using elasticsearch gem 9.x |
| 9 | +# Not needed if using elasticsearch gem 7.x or 8.x |
| 10 | + |
| 11 | +require 'elasticsearch/api' |
| 12 | + |
| 13 | +module Elasticsearch |
| 14 | + module API |
| 15 | + module Utils |
| 16 | + class << self |
| 17 | + if method_defined?(:update_ndjson_headers!) |
| 18 | + alias_method :original_update_ndjson_headers!, :update_ndjson_headers! |
| 19 | + |
| 20 | + def update_ndjson_headers!(headers, client_headers) |
| 21 | + return headers unless client_headers.is_a?(Hash) |
| 22 | + |
| 23 | + current_content = client_headers.keys.find { |c| c.to_s.match?(/content[-_]?type/i) } |
| 24 | + return headers unless current_content |
| 25 | + |
| 26 | + content_value = client_headers[current_content] |
| 27 | + return headers unless content_value |
| 28 | + |
| 29 | + # ES 7/8 compatibility: Only process ES9-specific headers |
| 30 | + # If no "compatible-with" present, this is ES 7/8 format |
| 31 | + return headers unless content_value.to_s.include?('compatible-with') |
| 32 | + |
| 33 | + # ES 9 detected, safe to call original |
| 34 | + original_update_ndjson_headers!(headers, client_headers) |
| 35 | + rescue StandardError => e |
| 36 | + warn "[elasticsearch-api-compat] Failed to update headers: #{e.class} - #{e.message}" |
| 37 | + headers |
| 38 | + end |
| 39 | + end |
| 40 | + end |
| 41 | + end |
| 42 | + end |
| 43 | +end |
0 commit comments