syndicate_utils/src/json_socket_translator.nim

37 lines
1.2 KiB
Nim
Raw Normal View History

2022-06-09 18:15:13 +00:00
# SPDX-FileCopyrightText: ☭ 2022 Emery Hemingway
# SPDX-License-Identifier: Unlicense
import std/[asyncdispatch, asyncnet, json]
from std/nativesockets import AF_UNIX, SOCK_STREAM, Protocol
import preserves, preserves/jsonhooks, syndicate, syndicate/patterns
import ./schema/config
2022-06-09 18:15:13 +00:00
bootDataspace("main") do (root: Ref; turn: var Turn):
connectStdio(root, turn)
during(turn, root, ?JsonSocketTranslatorArguments) do (ds: Ref, socketPath: string):
2022-06-09 18:15:13 +00:00
let socket = newAsyncSocket(
domain = AF_UNIX,
sockType = SOCK_STREAM,
protocol = cast[Protocol](0),
buffered = false,
)
2022-06-09 18:15:13 +00:00
waitFor connectUnix(socket, socketPath)
let f = turn.facet
proc processOutput(fut: Future[string]) {.gcsafe.} =
2022-06-09 18:15:13 +00:00
run(f) do (turn: var Turn):
var data = fut.read.parseJson.toPreserve
message(turn, ds, initRecord("recv-json", data))
socket.recvLine.addCallback(processOutput)
socket.recvLine.addCallback(processOutput)
onMessage(turn, ds, ?Input) do (data: Assertion):
var js: JsonNode
if fromPreserve(js, data):
asyncCheck(turn, send(socket, $js & "\n"))
else:
writeLine(stderr, "cannot convert assertion to JSON - ", data)
2022-06-09 18:15:13 +00:00
runForever()