syndicate-py/chat.py

53 lines
2.0 KiB
Python
Raw Permalink Normal View History

2018-11-20 19:45:27 +00:00
import sys
2021-08-19 21:27:42 +00:00
import argparse
2018-11-20 19:45:27 +00:00
import asyncio
import random
import syndicate
from syndicate import patterns as P, actor, dataspace, turn
2023-02-04 15:27:31 +00:00
from syndicate.schema import sturdy
from preserves.schema import load_schema_file
simpleChatProtocol = load_schema_file('./chat.bin').chat
2018-11-20 19:45:27 +00:00
2021-08-19 21:27:42 +00:00
parser = argparse.ArgumentParser(description='Simple dataspace-server-mediated text chat.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--address', metavar='\'<tcp "HOST" PORT>\'',
help='transport address of the server',
2021-12-13 21:22:40 +00:00
default='<ws "ws://localhost:9001/">')
2021-08-19 21:27:42 +00:00
parser.add_argument('--cap', metavar='\'<ref ...>\'',
help='capability for the dataspace on the server',
2023-02-10 11:16:23 +00:00
default='<ref {oid: "syndicate" sig: #[acowDB2/oI+6aSEC3YIxGg==]}>')
2021-08-19 21:27:42 +00:00
args = parser.parse_args()
Present = simpleChatProtocol.Present
Says = simpleChatProtocol.Says
2018-11-20 19:45:27 +00:00
2021-08-19 21:09:07 +00:00
@actor.run_system(name = 'chat', debug = False)
def main():
root_facet = turn.active_facet()
2021-08-19 17:26:12 +00:00
@syndicate.relay.connect(args.address, sturdy.SturdyRef.decode(syndicate.parse(args.cap)))
def on_connected(ds):
turn.on_stop(lambda: turn.stop(root_facet))
2021-08-19 21:04:35 +00:00
me = 'user_' + str(random.randint(10, 1000))
2018-11-20 19:45:27 +00:00
2021-08-19 21:04:35 +00:00
turn.publish(ds, Present(me))
2018-11-20 19:45:27 +00:00
@dataspace.during(ds, P.rec('Present', P.CAPTURE), inert_ok=True)
def on_presence(who):
2021-08-19 21:04:35 +00:00
print('%s joined' % (who,))
turn.on_stop(lambda: print('%s left' % (who,)))
@dataspace.on_message(ds, P.rec('Says', P.CAPTURE, P.CAPTURE))
def on_says(who, what):
2021-08-19 21:04:35 +00:00
print('%s says %r' % (who, what))
2018-11-20 19:45:27 +00:00
2021-08-19 21:04:35 +00:00
@turn.linked_task()
async def accept_input(f):
reader = asyncio.StreamReader()
2023-03-06 22:24:36 +00:00
await f.loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), sys.stdin)
2021-08-19 21:04:35 +00:00
while line := (await reader.readline()).decode('utf-8'):
turn.external(f, lambda: turn.send(ds, Says(me, line.strip())))