Skip to content

Commit 15ab356

Browse files
committed
NF: Introduce HTTP POST publishing
1 parent cce943e commit 15ab356

7 files changed

Lines changed: 44 additions & 11 deletions

File tree

pelita/game.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from .exceptions import NoFoodWarning, PelitaBotError, PelitaIllegalGameState
1818
from .gamestate_filters import noiser, relocate_expired_food, update_food_age, in_homezone
1919
from .layout import get_legal_positions, initial_positions
20-
from .network import Controller, RemotePlayerFailure, RemotePlayerRecvTimeout, RemotePlayerSendError, ZMQPublisher
20+
from .network import Controller, RemotePlayerFailure, RemotePlayerRecvTimeout, RemotePlayerSendError, ZMQPublisher, POSTPublisher
2121
from .team import RemoteTeam, make_team
2222
from .viewer import (AsciiViewer, ProgressViewer, ReplayWriter, ReplyToViewer,
2323
ResultPrinter)
@@ -272,6 +272,9 @@ def setup_viewers(viewers, print_result=True):
272272
zmq_context = zmq.Context()
273273
zmq_external_publisher = ZMQPublisher(address=viewer_opts, bind=False, zmq_context=zmq_context)
274274
viewer_state['viewers'].append(zmq_external_publisher)
275+
elif viewer == 'http-post-to':
276+
post_publisher = POSTPublisher(address=viewer_opts)
277+
viewer_state['viewers'].append(post_publisher)
275278
elif viewer == 'tk':
276279
zmq_context = zmq.Context()
277280
zmq_publisher = ZMQPublisher(address='tcp://127.0.0.1', zmq_context=zmq_context)

pelita/network.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,31 @@ def recv_timeout(self, expected_id, timeout):
333333
def __repr__(self):
334334
return "RemotePlayerConnection(%r)" % self.socket
335335

336+
337+
class POSTPublisher:
338+
""" A viewer which dumps to a given stream.
339+
"""
340+
def __init__(self, address):
341+
import httpx
342+
self.url = address
343+
self.http_session = httpx.Client()
344+
345+
def _send(self, action, data):
346+
# import requests
347+
348+
info = {'round': data['round'], 'turn': data['turn']}
349+
# TODO: this should be game_phase
350+
if data['gameover']:
351+
info['gameover'] = True
352+
_logger.debug(f"--#> [{action}] %r", info)
353+
message = {"__action__": action, "__data__": data}
354+
as_json = json.dumps(message, cls=SetEncoder)
355+
self.http_session.post(self.url, content=as_json)
356+
357+
def show_state(self, game_state):
358+
self._send(action="observe", data=game_state)
359+
360+
336361
class ZMQPublisher:
337362
""" Sets up a simple Publisher which sends all viewed events
338363
over a zmq connection.

pelita/scripts/pelita_main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,8 @@ def long_help(s):
280280
help=long_help('Communicate the result of the game on this channel.'))
281281
advanced_settings.add_argument('--publish', type=str, metavar='URL', dest='publish_to',
282282
help=long_help('Publish the game to this zmq socket.'))
283+
advanced_settings.add_argument('--http-post', type=str, metavar='URL', dest='http_post_to',
284+
help=long_help('POST the game to this http socket.'))
283285
advanced_settings.add_argument('--controller', type=str, metavar='URL', default="tcp://127.0.0.1",
284286
help=long_help('Channel for controlling the game.'))
285287

@@ -355,6 +357,8 @@ def main():
355357
viewers.append(('reply-to', args.reply_to))
356358
if args.publish_to:
357359
viewers.append(('publish-to', args.publish_to))
360+
if args.http_post_to:
361+
viewers.append(('http-post-to', args.http_post_to))
358362
if args.write_replay:
359363
viewers.append(('write-replay-to', args.write_replay))
360364

pelita/scripts/pelita_tournament.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,9 @@ def setup():
140140
del config["bonusmatch"]
141141
break
142142

143-
res = input_choice("Should the web-viewer be activated? (publishes to tcp://127.0.0.1:5559) (y/n)", [], "yn")
143+
res = input_choice("Should the web-viewer be activated? (publishes to http://localhost:3000/api/collect) (y/n)", [], "yn")
144144
if res == "y":
145-
config['publish'] = "tcp://127.0.0.1:5559"
145+
config['publish'] = "http://localhost:3000/api/collect"
146146
elif res == "n":
147147
config['publish'] = None
148148

pelita/tournament/__init__.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import time
1313
from dataclasses import dataclass
1414

15+
import httpx
1516
import yaml
1617
import zmq
1718

@@ -137,7 +138,7 @@ def call_pelita(team_specs, *, rounds, size, viewer, seed, timeout=3, initial_ti
137138
seed = ['--seed', seed] if seed else []
138139
timeout = ['--timeout', str(timeout)]
139140
initial_timeout = ['--initial-timeout', str(initial_timeout)]
140-
publish = ['--publish', publish] if publish else []
141+
publish = ['--http-post', publish] if publish else []
141142
write_replay = ['--write-replay', write_replay] if write_replay else []
142143
store_output = ['--store-output', store_output] if store_output else []
143144
append_blue = ['--append-blue', team_infos[0]] if team_infos[0] else []
@@ -306,11 +307,9 @@ def __init__(self, config):
306307
self.tournament_log_file = None
307308

308309
if self.publish:
309-
ctx = zmq.Context()
310-
self.socket = ctx.socket(zmq.PUB)
311-
self.socket.connect(self.publish)
310+
self.http_session = httpx.Client()
312311
else:
313-
self.socket = None
312+
self.http_session = None
314313

315314
@property
316315
def team_ids(self):
@@ -329,13 +328,14 @@ def team_spec(self, team):
329328
return self.teams[team]["spec"]
330329

331330
def send_remote(self, action, data=None):
332-
if not self.socket:
331+
if not self.http_session:
333332
return
333+
334334
if data is None:
335335
publish_string = {"__action__": action}
336336
else:
337337
publish_string = {"__action__": action, "__data__": data}
338-
self.socket.send_json(publish_string)
338+
self.http_session.post(self.publish, content=json.dumps(publish_string))
339339

340340
def _print(self, *args, **kwargs):
341341
print(*args, **kwargs)

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ dependencies = [
3232
"zeroconf",
3333
"rich",
3434
"click",
35+
"httpx"
3536
]
3637
dynamic = ["version"]
3738

tournament.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ location: Munich
33
date: 2015
44
seed: null
55
bonusmatch: True
6-
publish: tcp://127.0.0.1:5559
6+
#publish: http://localhost:3000/api/collect
77
teams:
88
- spec: pelita/player/StoppingPlayer
99
members:

0 commit comments

Comments
 (0)