Class: E2B::Services::EnvdHttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/e2b/services/base_service.rb

Overview

HTTP client for envd daemon communication

Handles both standard HTTP requests and Connect RPC protocol calls. Connect RPC uses a binary envelope format: 1 byte flags + 4 bytes big-endian length + JSON message body.

Defined Under Namespace

Classes: RpcResponse

Constant Summary collapse

DEFAULT_TIMEOUT =
120

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, api_key:, access_token: nil, sandbox_id:, logger: nil) ⇒ EnvdHttpClient

Returns a new instance of EnvdHttpClient.



152
153
154
155
156
157
158
159
# File 'lib/e2b/services/base_service.rb', line 152

def initialize(base_url:, api_key:, access_token: nil, sandbox_id:, logger: nil)
  @base_url = base_url.end_with?("/") ? base_url : "#{base_url}/"
  @api_key = api_key
  @access_token = access_token
  @sandbox_id = sandbox_id
  @logger = logger
  @connection = build_connection
end

Instance Method Details

#delete(path, timeout: DEFAULT_TIMEOUT, headers: nil) ⇒ Object



181
182
183
184
185
186
187
188
# File 'lib/e2b/services/base_service.rb', line 181

def delete(path, timeout: DEFAULT_TIMEOUT, headers: nil)
  handle_response do
    @connection.delete(normalize_path(path)) do |req|
      req.options.timeout = timeout
      req.headers.update(headers) if headers
    end
  end
end

#get(path, params: {}, timeout: DEFAULT_TIMEOUT, headers: nil) ⇒ Object



161
162
163
164
165
166
167
168
169
# File 'lib/e2b/services/base_service.rb', line 161

def get(path, params: {}, timeout: DEFAULT_TIMEOUT, headers: nil)
  handle_response do
    @connection.get(normalize_path(path)) do |req|
      req.params = params
      req.options.timeout = timeout
      req.headers.update(headers) if headers
    end
  end
end

#handle_streaming_rpc(path, envelope, timeout, on_event, headers) ⇒ Object

Streaming RPC with chunked response processing. Uses Faraday for the HTTP connection (same as non-streaming RPCs) to inherit proxy configuration and SSL settings. The streaming is handled via Faraday’s on_data callback for chunked response processing.

Streaming RPCs are NOT idempotent (e.g. process.Process/Start spawns a process), so we only retry while no events have been emitted to the caller yet. Once any byte has been delivered via on_event, a retry would replay output AND start a second process server-side.



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/e2b/services/base_service.rb', line 257

def handle_streaming_rpc(path, envelope, timeout, on_event, headers)
  result = { events: [], stdout: "", stderr: "", exit_code: nil }
  buffer = "".b

  full_path = normalize_path(path)

  with_retry("Streaming RPC #{path}", abort_if: -> { result[:events].any? }) do
    ssl_verify = ENV.fetch("E2B_SSL_VERIFY", "true").downcase != "false"

    streaming_conn = Faraday.new(url: @base_url, ssl: { verify: ssl_verify }) do |conn|
      conn.options.timeout = timeout
      conn.options.open_timeout = 30
      conn.adapter Faraday.default_adapter
    end

    req_headers = {
      "Content-Type" => "application/connect+json",
      "Connection" => "keep-alive",
      "E2b-Sandbox-Id" => @sandbox_id,
      "E2b-Sandbox-Port" => "#{BaseService::ENVD_PORT}",
      "X-API-Key" => @api_key
    }
    req_headers["X-Access-Token"] = @access_token if @access_token
    if headers
      headers.each { |k, v| req_headers[k.to_s] = v.to_s if v }
    end

    response = streaming_conn.post(full_path) do |req|
      req.headers.merge!(req_headers)
      req.body = envelope
      req.options.on_data = proc do |chunk, _overall_size, _env|
        next if chunk.nil? || chunk.empty?
        buffer << chunk

        while buffer.bytesize >= 5
          flags = buffer.getbyte(0)
          length = buffer.byteslice(1, 4).unpack1("N")

          break if length.nil? || buffer.bytesize < 5 + length

          message_bytes = buffer.byteslice(5, length)
          buffer = buffer.byteslice(5 + length..-1) || "".b

          next if message_bytes.nil? || message_bytes.empty?

          message_str = message_bytes.force_encoding("UTF-8")

          begin
            msg = JSON.parse(message_str)
            msg = msg["result"] if msg["result"]

            result[:events] << msg

            stdout_data = nil
            stderr_data = nil

            if msg["event"]
              event = msg["event"]

              data_event = event["Data"] || event["data"]
              if data_event
                stdout_data = decode_base64(data_event["stdout"]) if data_event["stdout"]
                stderr_data = decode_base64(data_event["stderr"]) if data_event["stderr"]
                result[:stdout] += stdout_data if stdout_data
                result[:stderr] += stderr_data if stderr_data
              end

              end_event = event["End"] || event["end"]
              if end_event
                result[:exit_code] = parse_exit_code(end_event["exitCode"] || end_event["exit_code"] || end_event["status"])
              end
            end

            if msg["stdout"]
              stdout_data = decode_base64(msg["stdout"])
              result[:stdout] += stdout_data
            end
            if msg["stderr"]
              stderr_data = decode_base64(msg["stderr"])
              result[:stderr] += stderr_data
            end
            if msg["exitCode"] || msg["exit_code"]
              result[:exit_code] = parse_exit_code(msg["exitCode"] || msg["exit_code"])
            end

            on_event.call(
              stdout: stdout_data,
              stderr: stderr_data,
              exit_code: result[:exit_code],
              event: msg
            )
          rescue JSON::ParserError
            # Skip unparseable messages
          end
        end
      end
    end

    unless response.status.between?(200, 299)
      handle_error(response)
    end
  end

  result
end

#post(path, body: nil, timeout: DEFAULT_TIMEOUT, headers: nil) ⇒ Object



171
172
173
174
175
176
177
178
179
# File 'lib/e2b/services/base_service.rb', line 171

def post(path, body: nil, timeout: DEFAULT_TIMEOUT, headers: nil)
  handle_response do
    @connection.post(normalize_path(path)) do |req|
      req.body = body.to_json if body
      req.options.timeout = timeout
      req.headers.update(headers) if headers
    end
  end
end

#rpc(service, method, body: {}, timeout: DEFAULT_TIMEOUT, on_event: nil, headers: nil) ⇒ Hash

Connect RPC call with streaming support

Parameters:

  • service (String)

    Service name

  • method (String)

    Method name

  • body (Hash) (defaults to: {})

    Request body

  • timeout (Integer) (defaults to: DEFAULT_TIMEOUT)

    Timeout in seconds

  • on_event (Proc, nil) (defaults to: nil)

    Callback for streaming events

Returns:

  • (Hash)

    Response



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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/e2b/services/base_service.rb', line 198

def rpc(service, method, body: {}, timeout: DEFAULT_TIMEOUT, on_event: nil, headers: nil)
  path = "/#{service}/#{method}"
  json_body = body.to_json
  envelope = create_connect_envelope(json_body)

  log_debug("RPC #{service}/#{method}")

  if on_event
    return handle_streaming_rpc(path, envelope, timeout, on_event, headers)
  end

  # Unary RPCs: try Connect protocol first, fall back to plain JSON.
  # Some envd versions (e.g., 0.5.4 on self-hosted) reject
  # application/connect+json for unary calls but accept application/json.
  handle_rpc_response(service, method) do
    with_retry("RPC #{service}/#{method}") do
      url = URI.parse("#{@base_url.chomp('/')}#{path}")
      http = build_http(url, timeout)

      request = Net::HTTP::Post.new(url.request_uri)
      request["Content-Type"] = "application/connect+json"
      request["X-Access-Token"] = @access_token if @access_token
      request["Connection"] = "keep-alive"
      apply_custom_headers(request, headers)
      request.body = envelope

      response = http.request(request)

      # Fall back to plain JSON if Connect protocol is unsupported (HTTP 415)
      if response.code.to_i == 415
        log_debug("Connect protocol unsupported for #{service}/#{method}, falling back to plain JSON")
        request = Net::HTTP::Post.new(url.request_uri)
        request["Content-Type"] = "application/json"
        request["X-Access-Token"] = @access_token if @access_token
        request["Connection"] = "keep-alive"
        apply_custom_headers(request, headers)
        request.body = json_body

        response = http.request(request)
      end

      RpcResponse.new(
        status: response.code.to_i,
        body: response.body,
        headers: response.to_hash
      )
    end
  end
end