local inbox = require 'inbox'
local asio_error = require 'asio_error'
local ip = require 'ip'
local pipe = require 'pipe'
local stream = require 'stream'

local function request(endpoint, text)
    local sock = ip.tcp.dial(endpoint)
    stream.write_all(sock, text .. '\n')

    local response = byte_span.new(0)
    while true do
        local buf = byte_span.new(4096)
        local ok, value = pcall(function()
            return sock:read_some(buf)
        end)

        if ok then
            response = byte_span.append(response, buf:first(value))
        elseif value == asio_error.misc.eof then
            break
        else
            error(value)
        end
    end
    sock:close()
    return tostring(response)
end

-- One allowed request and one request that the supervisor will reject.
for _ = 1, 2 do
    local msg = inbox:receive()
    local ok, result = pcall(request, msg.endpoint, msg.text)

    local output = pipe.write_stream.new()
    output:assign(msg.output)
    if ok then
        stream.write_all(output, result)
    else
        stream.write_all(output, 'POLICY_DENIED: ' .. tostring(result))
    end
    output:close()
end
