view core/src/luan/modules/Rpc.luan @ 762:3f461f85243d

better rpc thread handling
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 20 Jul 2016 23:55:59 -0600
parents 2c41f2aec92f
children
line wrap: on
line source

java()
local RpcLuan = require "java:luan.modules.RpcLuan"
local Luan = require "luan:Luan.luan"
local error = Luan.error
local set_metatable = Luan.set_metatable or error()
local try = Luan.try or error()
local Io = require "luan:Io.luan"
local Thread = require "luan:Thread.luan"
local Logging = require "luan:logging/Logging.luan"  -- external dependency
local logger = Logging.logger "Rpc"


local M = {}

M.port = 9101

M.call = RpcLuan.call  -- Rpc.call(socket,fn_name,...)

M.functions = {}

function M.respond(socket,fns)
	RpcLuan.respond( socket, fns or M.functions )
end

function M.remote_socket(socket_uri)
	local mt = {}
	function mt.__index(_,key)
		return function(...)
			local socket = Io.uri(socket_uri)
			return M.call(socket,key,...)
		end
	end
	local t = {}
	set_metatable(t,mt)
	return t
end

function M.remote(domain)
	local socket = "socket:" .. domain .. ":" .. M.port
	return M.remote_socket(socket)
end

function M.serve(port,fns)
	local server = Io.socket_server(port or M.port)
	while true do
		try {
			function()
				local socket = server()
				local function respond()
					try {
						function()
							M.respond(socket,fns)
						end
						catch = function(e)
							logger.error(e)
						end
					}
				end
				Thread.fork(respond)
			end
			catch = function(e)
				logger.error(e)
			end
		}
	end
end

return M