2023-05-06 19:08:38 +00:00
|
|
|
# SPDX-FileCopyrightText: ☭ Emery Hemingway
|
2022-06-09 18:15:13 +00:00
|
|
|
# SPDX-License-Identifier: Unlicense
|
|
|
|
|
|
|
|
import std/[asyncdispatch, asyncnet, json]
|
|
|
|
from std/nativesockets import AF_UNIX, SOCK_STREAM, Protocol
|
2023-10-05 17:05:06 +00:00
|
|
|
import preserves, preserves/jsonhooks, syndicate, syndicate/relays
|
2022-06-09 18:15:13 +00:00
|
|
|
|
2024-01-08 19:14:33 +00:00
|
|
|
import ../schema/config, ../json_messages
|
2022-06-09 18:15:13 +00:00
|
|
|
|
2023-12-25 23:11:54 +00:00
|
|
|
proc spawnJsonSocketTranslator*(turn: var Turn; root: Cap): Actor =
|
2024-01-08 19:14:33 +00:00
|
|
|
spawn("json-socket-translator", turn) do (turn: var Turn):
|
2023-12-25 23:11:54 +00:00
|
|
|
during(turn, root, ?:JsonSocketTranslatorArguments) do (ds: Cap, socketPath: string):
|
|
|
|
let socket = newAsyncSocket(
|
|
|
|
domain = AF_UNIX,
|
|
|
|
sockType = SOCK_STREAM,
|
|
|
|
protocol = cast[Protocol](0),
|
|
|
|
buffered = false,
|
|
|
|
)
|
|
|
|
addCallback(connectUnix(socket, socketPath), turn) do (turn: var Turn):
|
|
|
|
let a = JsonTranslatorConnected(path: socketPath)
|
|
|
|
discard publish(turn, ds, a)
|
2022-06-09 18:15:13 +00:00
|
|
|
|
2023-12-25 23:11:54 +00:00
|
|
|
let socketFacet = turn.facet
|
|
|
|
proc processOutput(fut: Future[string]) {.gcsafe.} =
|
|
|
|
run(socketFacet) do (turn: var Turn):
|
|
|
|
var data = fut.read.parseJson
|
|
|
|
message(turn, ds, RecvJson(data: data))
|
|
|
|
socket.recvLine.addCallback(processOutput)
|
2023-05-16 09:51:56 +00:00
|
|
|
socket.recvLine.addCallback(processOutput)
|
2023-05-05 16:38:04 +00:00
|
|
|
|
2023-12-25 23:11:54 +00:00
|
|
|
onMessage(turn, ds, ?:SendJson) do (data: JsonNode):
|
|
|
|
asyncCheck(turn, send(socket, $data & "\n"))
|
|
|
|
do:
|
|
|
|
close(socket)
|
|
|
|
|
|
|
|
when isMainModule:
|
|
|
|
runActor("json_socket_translator") do (turn: var Turn; root: Cap):
|
|
|
|
connectStdio(turn, root)
|
|
|
|
discard spawnJsonSocketTranslator(turn, root)
|