syndicate_utils/src/json_socket_translator.nim

34 lines
1.1 KiB
Nim

# 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
bootDataspace("main") do (ds: Ref; turn: var Turn):
connectStdio(ds, turn)
during(turn, ds, ?config.JsonSocket) do (label: Assertion, socketPath: string):
let socket = newAsyncSocket(
domain = AF_UNIX,
sockType = SOCK_STREAM,
protocol = cast[Protocol](0),
buffered = false)
waitFor connectUnix(socket, socketPath)
onMessage(turn, ds, recordPattern(label, ?1, grab())) do (data: Assertion):
var js: JsonNode
if fromPreserve(js, data):
asyncCheck socket.send($js & "\n")
let f = turn.facet
proc processIncoming(fut: Future[string]) {.gcsafe.} =
var data = fut.read.parseJson.toPreserve(Ref)
run(f) do (turn: var Turn):
message(turn, ds, initRecord(label, 0.toPreserve(Ref), data))
socket.recvLine.addCallback(processIncoming)
socket.recvLine.addCallback(processIncoming)
runForever()