view src/luan/modules/Rpc.luan @ 1098:bae624e455e2

add Time.time_zone
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 29 Mar 2017 19:54:45 -0600
parents bae2d0c2576c
children e8fc6712b468
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 Rpc = {}

Rpc.port = 9101

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

Rpc.functions = {}

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

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

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

function Rpc.serve(port,fns)
	local server = Io.socket_server(port or Rpc.port)
	while true do
		try {
			function()
				local socket = server()
				local function respond()
					try {
						function()
							Rpc.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 Rpc