local easybox = require 'easybox'
local fs = require 'filesystem'
local pipe = require 'pipe'
local stream = require 'stream'
local util = require '../common'

local root = fs.current_working_directory() / 'examples' / 'pipe_plugin'
local worker = easybox.new{
    module = fs.path.new('/plugin.lua'),
    source_tree_cache = {
        ['plugin.lua'] = util.read_source(root / 'plugin.lua'),
    },
    stdout = 'share',
    stderr = 'share',
}

-- These are the only request-specific resources the plugin receives.
local child_input, host_output = pipe.pair()
local host_input, child_output = pipe.pair()
child_input = child_input:release()
child_output = child_output:release()

worker:send{ input = child_input, output = child_output }
child_input:close()
child_output:close()

-- Writing in a separate fiber prevents a full pipe from deadlocking the host
-- while it is trying to read the response.
spawn(function()
    stream.write_all(host_output, 'HELLO FROM THE HOST')
    host_output:close()
end):detach()

print(util.read_to_eof(host_input))
