Class: LocalDevelopmentGateway::DatabaseRouter::DockerApi

Inherits:
Object
  • Object
show all
Defined in:
lib/local_development_gateway/database_router/docker_api.rb

Constant Summary collapse

MAX_RESPONSE_BYTES =
8 * 1024 * 1024
SOCKET_PATH =
"/var/run/docker.sock"

Instance Method Summary collapse

Constructor Details

#initialize(socket_path: SOCKET_PATH) ⇒ DockerApi

Returns a new instance of DockerApi.



13
14
15
# File 'lib/local_development_gateway/database_router/docker_api.rb', line 13

def initialize(socket_path: SOCKET_PATH)
  @socket_path = socket_path
end

Instance Method Details

#get(path) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/local_development_gateway/database_router/docker_api.rb', line 17

def get(path)
  socket = UNIXSocket.new(@socket_path)
  socket.write(
    "GET #{path} HTTP/1.1\r\nHost: docker\r\nConnection: close\r\n\r\n"
  )
  response =
    DatabaseRouter::Wire.read_until_eof(
      socket,
      max_bytes: MAX_RESPONSE_BYTES,
      deadline: DatabaseRouter::Wire.deadline
    )
  headers, body = response.split("\r\n\r\n", 2)
  unless headers&.start_with?("HTTP/1.1 200", "HTTP/1.0 200")
    raise Error,
          "Docker API request failed: #{headers&.lines&.first&.strip}"
  end

  body = decode_chunks(body) if headers.downcase.include?(
    "transfer-encoding: chunked"
  )
  JSON.parse(body)
ensure
  socket&.close
end