diff src/luan/modules/Rpc.luan @ 775:1a68fc55a80c

simplify dir structure
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 26 Aug 2016 14:36:40 -0600
parents core/src/luan/modules/Rpc.luan@3f461f85243d
children bae2d0c2576c
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/luan/modules/Rpc.luan	Fri Aug 26 14:36:40 2016 -0600
@@ -0,0 +1,68 @@
+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