Class: PythonWebClient

Inherits:
Object
  • Object
show all
Defined in:
app/services/python_web_client.rb

Overview

require ‘websocket-client-simple’

Class Method Summary collapse

Class Method Details

.connObject



90
91
92
93
94
95
96
97
98
99
100
101
# File 'app/services/python_web_client.rb', line 90

def conn
  @conn ||= Faraday.new(url: Rails.application.config.python_web_host) do |faraday|
    faraday.request :json
    faraday.response :json, content_type: /\bjson$/
    faraday.response :raise_error
    # faraday.use FaradayCustomErrorMiddleware
    faraday.headers['Accept'] = 'application/json'
    faraday.adapter Faraday.default_adapter
    faraday.options.timeout = 180 # Set timeout to 3 minutes
    faraday.options.open_timeout = 180 # Set open timeout to 3 minutes
  end
end

.get(path:, params: {}) ⇒ Object



5
6
7
8
9
# File 'app/services/python_web_client.rb', line 5

def get(path:, params: {})
  Rails.logger.info "PythonWebClient GET: #{path} with params: #{params}"
  response = conn.get(path, params)
  soft_parse(response.body)
end

.parse_or_nil(body) ⇒ Object



109
110
111
112
113
# File 'app/services/python_web_client.rb', line 109

def parse_or_nil(body)
  JSON.parse(body)
rescue StandardError
  nil
end

.post(path:, params: {}, &_block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/services/python_web_client.rb', line 11

def post(path:, params: {}, &_block)
  Rails.logger.info "PythonWebClient POST: #{path} with params: #{params}"

  if block_given?
    # Streaming mode
    conn.post do |req|
      req.url path
      req.body = params.to_json
      req.headers['Content-Type'] = 'application/json'
      req.headers['Accept'] = 'text/event-stream' if params[:stream] # Add SSE Accept header

      req.options.on_data = proc do |chunk, _size, _env|
        # Process each chunk as it arrives
        chunk_str = chunk.to_s.strip
        if chunk_str.start_with?('data: ') && chunk_str.length > 6
          # Extract the JSON data part from the SSE format (data: {...})
          json_str = chunk_str.sub(/^data: /, '').strip
          begin
            yield json_str
          rescue StandardError => e
            Rails.logger.error "Error processing chunk: #{e.message}"
          end
        elsif chunk_str.length > 0 && chunk_str != "\n" && !chunk_str.start_with?(':')
          # Handle non-SSE format as fallback
          yield chunk_str
        end
      end
    end
    nil # Return nil when streaming since data is processed in the block
  else
    # Regular mode
    response = conn.post(path, params)
    soft_parse(response.body)
  end
end

.soft_parse(body) ⇒ Object



103
104
105
106
107
# File 'app/services/python_web_client.rb', line 103

def soft_parse(body)
  JSON.parse(body)
rescue StandardError
  body || {}
end

.websocket(path:, &block) ⇒ Object



47
48
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
# File 'app/services/python_web_client.rb', line 47

def websocket(path:, &block)
  ws_url = "#{Rails.application.config.python_web_host.sub(/^http/, 'ws')}#{path}"
  ws = WebSocket::Client::Simple.connect(ws_url)
  retry_count = 0
  retry_delay = 0.5
  max_retries = 5

  ws.on :open do
    Rails.logger.info "WebSocket connection established to #{ws_url}"
  end

  ws.on :message do |msg|
    if msg.data == 'ping'
      ws.send('pong')
    else
      msg_data = PythonWebClient.parse_or_nil(msg.data)
      block.call(msg_data) if msg_data
    end
  end

  ws.on :close do |_e|
    # Trigger reconnection unless max retries exceeded
    if retry_count < max_retries
      retry_count += 1
      Rails.logger.info "Attempting to reconnect (#{retry_count}/#{max_retries}) to #{ws_url}"
      sleep retry_delay
      raise StandardError, 'WebSocket closed, retrying'
    else
      Rails.logger.error "Max reconnection attempts (#{max_retries}) reached for #{ws_url}"
    end
  end

  ws.on :error do |e|
    Rails.logger.error "WebSocket error: #{e.message}"
    raise StandardError, 'WebSocket error'
  end

  ws
rescue StandardError => e
  Rails.logger.error "WebSocket connection error: #{e.message}"
  raise
end