///|
/// anthropos-gateway——moonanthos FaaS 网关(A1-0 核心竖切)
/// POST /eval body=moonanthos 源码 → lang 编译 → rpc 推靶机 exec →
/// JSON 回执 {"ok":true,"result":...}/{"ok":false,"crash":现场}
/// 节点发现:复用 /tmp/anthos_up.node 协议(anthropos_target boot 写)
///|
const VERSION : String = "0.3.4"
///|
const PORT : Int32 = 7990
///|
/// EtfVal→人读(回执渲染;list 显示面小账同 eval)
fn fmt_val(v : @rpc.EtfVal) -> String {
match v {
VInt(n) => "\{n}"
VAtom(a) => a
VString(sv) => "\"\{sv}\""
VNil => "[]"
VFloat(d) => "\{d}"
VTuple(items) => "{" + join_vals(items) + "}"
VList(items) => "[" + join_vals(items) + "]"
VBinary(b) => {
let parts : Array[String] = []
let n = if b.length() > 16 { 16 } else { b.length() }
for i in 0.. 16 {
let _ = parts.push("...")
}
"<<\{parts.join(", ")}>>"
}
_ => "?"
}
}
///|
fn join_vals(items : Array[@rpc.EtfVal]) -> String {
let parts : Array[String] = []
for i in items {
let _ = parts.push(fmt_val(i))
}
parts.join(", ")
}
///|
/// 发现文件读取(node 短名+cookie)
///|
async fn read_discover() -> (String, String)? {
let text = read_discover_text()
if text.length() == 0 {
return None
}
let mut n = ""
let mut c = "moonbit123"
for line in text.split("\n") {
let ln = (line + "").to_owned()
n = kv_of(ln, "node=", n)
c = kv_of(ln, "cookie=", c)
}
if n.length() > 0 {
Some((n, c))
} else {
None
}
}
///|
async fn read_discover_text() -> String {
let data = @fs.read_file("/tmp/anthos_up.node") catch { _ => return "" }
@utf8.decode_lossy(data.binary()).trim().to_owned()
}
///|
/// 行=「键=值」形则取值,否则返原
fn kv_of(line : String, key : String, cur : String) -> String {
// 逐字符前缀判+尾段拼接(零切片 API 依赖)
if line.length() <= key.length() {
return cur
}
let mut hit = true
for i in 0.. (Bool, String) raise Error {
conn_seq_cell[0] = conn_seq_cell[0] + 1
let my_name = "gw\{conn_seq_cell[0]}"
let client = @client.BeamClient::connect(
node_short~,
cookie~,
name=my_name,
alive_port=17999,
drain=2,
) catch {
_ => return (false, "靶机连接拒(未起?bin/start.sh)")
}
let codec_impl = @eetf_codec.EtfCodecEetf::new(tag=0)
let port : &@rpc.RpcPort = GwRpcPort::{
sock: client.sock(),
codec: codec_impl,
}
let codec : &@rpc.EtfCodec = codec_impl
let my_full = "\{my_name}@dev"
let caller = @rpc.EtfVal::VPid(my_full, 1, 1, client.creation())
let mut refi = 900
fn next_ref() -> @rpc.EtfVal {
refi += 1
@rpc.EtfVal::VRef(my_full, refi, 0, client.creation())
}
let mname = "ae"
let has_fn = expr.contains("fn ")
let src = if has_fn {
"module \{mname}\n\{expr}\n"
} else {
"module \{mname}\nfn go() { \{expr} }\n"
}
let forms2 = @lang.parse_module(src) catch {
Parse(m) => return (false, "parse: \{m}")
Lex(m) => return (false, "lex: \{m}")
_ => return (false, "parse: 拒")
}
let reply = @rpc.call(
codec,
port,
node_short,
caller~,
ref_=next_ref(),
"compile",
"forms",
[@lang.forms_of(forms2), @rpc.EtfVal::VNil],
) catch {
_ => return (false, "compile rpc 拒")
}
let beam_bin = match reply {
VTuple(items) =>
if items.length() == 3 && items[0] is VAtom("ok") {
match items[2] {
VBinary(b) => b
_ => return (false, "compile: 回执非 binary")
}
} else {
return (false, "compile: 非 ok(\{fmt_val(reply)})")
}
_ => return (false, "compile: 拒(\{fmt_val(reply)})")
}
let _ = @rpc.call(
codec,
port,
node_short,
caller~,
ref_=next_ref(),
"code",
"load_binary",
[VAtom(mname), VString(""), VBinary(beam_bin)],
) catch {
_ => return (false, "load 拒")
}
let call_reply = @rpc.call(
codec,
port,
node_short,
caller~,
ref_=next_ref(),
"anthropos_exec",
"eval",
[VAtom(mname), VAtom("go"), VNil],
) catch {
_ => return (false, "exec rpc 拒")
}
match call_reply {
VTuple(items) =>
if items.length() == 2 && items[0] is VAtom("ok") {
(true, fmt_val(items[1]))
} else if items.length() == 2 && items[0] is VAtom("crash") {
(false, "exec 崩溃现场: \{fmt_val(items[1])}")
} else {
(false, "回执异常形: \{fmt_val(call_reply)}")
}
_ => (false, "回执非元组: \{fmt_val(call_reply)}")
}
}
///|
struct GwRpcPort {
sock : @socket.Tcp
codec : &@dist.EtfPort
}
///|
impl @rpc.RpcPort for GwRpcPort with fn send(self, node : String, frame : Bytes) -> Unit raise @rpc.RpcError {
let out : Array[Byte] = [0x70]
for i in 0.. raise @rpc.RpcError::Transport("send 拒")
}
}
///|
impl @rpc.RpcPort for GwRpcPort with fn recv(self) -> Bytes raise @rpc.RpcError {
// drain 收:空 tick/非 'p' 帧/'p' 但 msg 项非 {Ref,Reply} 形(EXIT/io
// 协议等信号)全跳——只放行真回执(runtime_concurrency 茧篇地基案:
// spawn 的输出经 group_leader 路由回本连接,信号与回执共享通道;
// 探针实证 EXIT 形 'p' 帧混入——msg 首元 VRef 才是回执判据)
let mut result : Bytes? = None
while result is None {
let body = @channel.recv_frame(self.sock) catch {
_ => raise @rpc.RpcError::Transport("recv 拒")
}
if body.length() == 0 {
continue
}
if body.length() < 2 || body[0].to_int() != 112 || body[1].to_int() != 131 {
continue
}
let stripped = body[1:].to_owned()
let ctl_dec = self.codec.decode_term(stripped, 1, []) catch {
_ => continue
}
let next_pos = ctl_dec.1
// ctl 判:tag 22(SEND_SENDER)={22,FromPid,ToPid}+msg——**rex reply
// 投递实形**(dop_gen 词表直书,probe dump 铁证 2026-11-07);io 类
// 信号(tag 6 REG_SEND 到 user/无名)全 drain;ref 精核在 parse_reply
let is_reply_ctl = match ctl_dec.0 {
@dist.EtfItem::ITuple(items) =>
items.length() >= 1 && items[0] is IInt(22)
_ => false
}
if !is_reply_ctl {
continue
}
if next_pos >= stripped.length() {
continue
}
let rest : Array[Byte] = []
for i2 in next_pos.. continue
}
let msg_val = msg_dec.0
match msg_val {
@dist.EtfItem::ITuple(items) =>
if items.length() == 2 {
result = Some(msg_bytes)
}
_ => ()
}
}
match result {
Some(b) => b
None => raise @rpc.RpcError::Transport("recv 无回执")
}
}
///|
fn json_escape(s : String) -> String {
let sb = StringBuilder()
for ch in s {
if ch == '"' {
let _ = sb.write_char('\\')
let _ = sb.write_char('"')
} else if ch == '\\' {
let _ = sb.write_char('\\')
let _ = sb.write_char('\\')
} else if ch.to_int() == 10 {
let _ = sb.write_char('\\')
let _ = sb.write_char('n')
} else if ch.to_int() < 32 {
let _ = sb.write_char(' ')
} else {
let _ = sb.write_char(ch)
}
}
sb.to_string()
}
///|
async fn main {
let args = @env.args()
for ai in 0.. None }
match discovered {
Some((dn, _dc)) => println("ok: 靶机 \{dn}(发现文件)")
None =>
println(
"warn: 发现文件缺席——起靶机: anthropos_target/bin/start.sh",
)
}
let server = @http.Server(@socket.Addr::parse("0.0.0.0:\{PORT}"))
println(
"anthropos-gateway \{VERSION} 监听 : \{PORT}(POST /eval body=源码)",
)
server.run_forever() <| async fn(request, body, conn) {
let path = request.path
let meth = request.meth
// query 拆分:path 可能含 ?name=x(符号寻址面)
let mut route_path = path
let mut query_s = ""
let qidx = path.find("?")
if qidx is Some(qp) {
route_path = path[:qp].to_owned()
query_s = path[qp + 1:].to_owned()
}
if meth is Post && route_path == "/eval" {
let code = @utf8.decode_lossy(body.read_all().binary())
let node_cookie = read_discover() catch { _ => None }
let (ok, result) = match node_cookie {
Some((dn, dc)) =>
gateway_eval(code, dn, dc) catch {
_ => (false, "内部拒")
}
None => (false, "无靶机(发现文件缺席)")
}
let payload = if ok {
"{\"ok\":true,\"result\":\"\{json_escape(result)}\"}"
} else {
"{\"ok\":false,\"crash\":\"\{json_escape(result)}\"}"
}
conn.send_response(200, "OK")
let _ = conn.write_string(payload)
()
} else if meth is Post &&
(
route_path == "/spawn" ||
route_path == "/send" ||
route_path == "/call" ||
route_path == "/monitor" ||
route_path == "/terminate" ||
route_path == "/deploy" ||
route_path == "/invoke" ||
route_path == "/debug"
) {
let code = @utf8.decode_lossy(body.read_all().binary())
let out = actor_route(route_path, code, query_s)
conn.send_response(200, "OK")
let _ = conn.write_string(out)
()
} else if meth is Get && route_path == "/health" {
conn.send_response(200, "OK")
let _ = conn.write_string("{\"ok\":true,\"gateway\":\"\{VERSION}\"}")
()
} else {
conn.send_response(404, "NotFound")
()
}
}
}