async def main():
    # Declare the protocol stack used for serialization.
    # Protocol stacks must match between publishers and subscribers.
    prot_factory = FProtocolFactory(TBinaryProtocol.TBinaryProtocolFactory())

    # Open a NATS connection to receive requests
    nats_client = NatsClient()
    options = {"verbose": True, "servers": ["nats://127.0.0.1:4222"]}

    await nats_client.connect(**options)

    # Create a pub sub scope using the configured transport and protocol
    transport_factory = FNatsSubscriberTransportFactory(nats_client)
    provider = FScopeProvider(None, transport_factory, prot_factory)

    subscriber = AlbumWinnersSubscriber(provider)

    def event_handler(ctx, req):
        root.info("You won! {}".format(req.ASIN))

    def start_contest_handler(ctx, albums):
        root.info("Contest started, available albums: {}".format(albums))

    await subscriber.subscribe_Winner(event_handler)
    await subscriber.subscribe_ContestStart(start_contest_handler)

    root.info("Subscriber starting...")
Beispiel #2
0
async def test_pub_sub(nats_client, protocol_factory, port):
    global response_received
    pub_transport_factory = FNatsPublisherTransportFactory(nats_client)
    sub_transport_factory = FNatsSubscriberTransportFactory(nats_client)
    provider = FScopeProvider(pub_transport_factory, sub_transport_factory,
                              protocol_factory)
    publisher = EventsPublisher(provider)

    await publisher.open()

    def subscribe_handler(context, event):
        print("Response received {}".format(event))
        global response_received
        if context:
            response_received = True

    # Subscribe to response
    preamble = "foo"
    ramble = "bar"
    subscriber = EventsSubscriber(provider)
    await subscriber.subscribe_EventCreated(preamble, ramble, "response",
                                            "{}".format(port),
                                            subscribe_handler)

    event = Event(Message="Sending Call")
    context = FContext("Call")
    context.set_request_header(PREAMBLE_HEADER, preamble)
    context.set_request_header(RAMBLE_HEADER, ramble)
    print("Publishing...")
    await publisher.publish_EventCreated(context, preamble, ramble, "call",
                                         "{}".format(port), event)

    # Loop with sleep interval. Fail if not received within 3 seconds
    total_time = 0
    interval = 0.1
    while total_time < 3:
        if response_received:
            break
        else:
            await asyncio.sleep(interval)
            total_time += interval

    if not response_received:
        print("Pub/Sub response timed out!")
        exit(1)

    await publisher.close()
    exit(0)
Beispiel #3
0
async def main():
    parser = argparse.ArgumentParser(
        description="Run an asyncio python server")
    parser.add_argument('--port', dest='port', default='9090')
    parser.add_argument('--protocol',
                        dest='protocol_type',
                        default="binary",
                        choices="binary, compact, json")
    parser.add_argument('--transport',
                        dest="transport_type",
                        default=NATS_NAME,
                        choices="nats, http")

    args = parser.parse_args()

    protocol_factory = get_protocol_factory(args.protocol_type)

    nats_client = NatsClient()
    await nats_client.connect(**get_nats_options())

    port = args.port

    handler = FrugalTestHandler()
    subject = "frugal.*.*.rpc.{}".format(args.port)
    processor = Processor(handler)

    # Setup subscriber, send response upon receipt
    pub_transport_factory = FNatsPublisherTransportFactory(nats_client)
    sub_transport_factory = FNatsSubscriberTransportFactory(nats_client)
    provider = FScopeProvider(pub_transport_factory, sub_transport_factory,
                              protocol_factory)
    publisher = EventsPublisher(provider)
    await publisher.open()

    async def response_handler(context, event):
        preamble = context.get_request_header(PREAMBLE_HEADER)
        if preamble is None or preamble == "":
            logging.error("Client did not provide preamble header")
            return
        ramble = context.get_request_header(RAMBLE_HEADER)
        if ramble is None or ramble == "":
            logging.error("Client did not provide ramble header")
            return
        response_event = Event(Message="Sending Response")
        response_context = FContext("Call")
        await publisher.publish_EventCreated(response_context, preamble,
                                             ramble, "response",
                                             "{}".format(port), response_event)

    subscriber = EventsSubscriber(provider)
    await subscriber.subscribe_EventCreated("*", "*", "call",
                                            "{}".format(args.port),
                                            response_handler)

    if args.transport_type == NATS_NAME:
        server = FNatsServer(nats_client, [subject], processor,
                             protocol_factory)
        # start healthcheck so the test runner knows the server is running
        threading.Thread(target=healthcheck, args=(port, )).start()

        print("Starting {} server...".format(args.transport_type))
        await server.serve()

    elif args.transport_type == HTTP_NAME:
        print('starting http server')
        handler = new_http_handler(processor, protocol_factory)
        app = web.Application(loop=asyncio.get_event_loop())
        app.router.add_route("*", "/", handler)
        srv = await asyncio.get_event_loop().create_server(
            app.make_handler(), '0.0.0.0', port)

    else:
        logging.error("Unknown transport type: %s", args.transport_type)
        sys.exit(1)