def setup_server(disconnect_delay=0):
    app = FastAPI()
    # Multiprocess shared value
    counter = Value("i", 0)

    async def on_connect(channel: RpcChannel):
        if counter.value == 0:
            # Immediate death
            if disconnect_delay == 0:
                logger.info("Disconnect once")
                await channel.socket.close()
            # Delayed death
            else:

                async def disconn():
                    await asyncio.sleep(disconnect_delay)
                    logger.info("Disconnect once")
                    await channel.socket.close()

                asyncio.create_task(disconn())
            counter.value = 1

    # PubSub websocket endpoint
    endpoint = PubSubEndpoint(on_connect=[on_connect])
    endpoint.register_route(app, "/pubsub")
    uvicorn.run(app, port=PORT)
def setup_server():
    app = FastAPI()
    remote_id_ok = asyncio.Event()

    async def try_to_get_remote_id(channel: RpcChannel):
        logger.info(f"trying to get remote channel id")
        channel_other_channel_id = await channel.get_other_channel_id()
        logger.info(f"finished getting remote channel id")
        if channel_other_channel_id is not None:
            remote_id_ok.set()
            logger.info(f"remote channel id: {channel_other_channel_id}")
        logger.info(f"local channel id: {channel_other_channel_id}")

    async def on_connect(channel: RpcChannel):
        logger.info(f"Connected to remote channel")
        asyncio.create_task(try_to_get_remote_id(channel))

    # PubSub websocket endpoint - setting up the server with remote id
    endpoint = PubSubEndpoint(rpc_channel_get_remote_id=True,
                              on_connect=[on_connect])
    endpoint.register_route(app, path="/pubsub")

    # Regular REST endpoint - that publishes to PubSub
    setup_server_rest_routes(app, endpoint, remote_id_ok)
    uvicorn.run(app, port=PORT)
def setup_server():
    app = FastAPI()
    # PubSub websocket endpoint
    endpoint = PubSubEndpoint()
    endpoint.register_route(app, path="/pubsub")
    # Regular REST endpoint - that publishes to PubSub
    setup_server_rest_route(app, endpoint)
    uvicorn.run(app, port=PORT)
예제 #4
0
def setup_server():
    app = FastAPI()
    router = APIRouter()
    # PubSub websocket endpoint
    endpoint = PubSubEndpoint()
    endpoint.register_route(router, "/pubsub")
    app.include_router(router)
    uvicorn.run(app, port=PORT)
예제 #5
0
    def __init__(self, signer: JWTSigner, broadcaster_uri: str = None):
        """
        Args:
            broadcaster_uri (str, optional): Which server/medium should the PubSub use for broadcasting. Defaults to BROADCAST_URI.
            None means no broadcasting.
        """
        broadcaster_uri = broadcaster_uri or opal_server_config.BROADCAST_URI
        self.router = APIRouter()
        self.endpoint = PubSubEndpoint(broadcaster=broadcaster_uri)
        verifier = JWTVerifierWebsocket(signer)

        @self.router.websocket("/ws")
        async def websocket_rpc_endpoint(websocket: WebSocket,
                                         logged_in: bool = Depends(verifier)):
            """
            this is the main websocket endpoint the sidecar uses to register on policy updates.
            as you can see, this endpoint is protected by an HTTP Authorization Bearer token.
            """
            if not logged_in:
                logger.info(
                    "Closing connection, remote address: {remote_address}",
                    remote_address=websocket.client,
                    reason="Authentication failed")
                await websocket.close()
                return
            # Init PubSub main-loop with or without broadcasting
            if broadcaster_uri is not None:
                async with self.endpoint.broadcaster:
                    await self.endpoint.main_loop(websocket)
            else:
                await self.endpoint.main_loop(websocket)
예제 #6
0
def setup_server():
    app = FastAPI()
    # PubSub websocket endpoint
    endpoint = PubSubEndpoint()
    endpoint.register_route(app, path="/pubsub")

    # receive an event and publish another (this time for the client)
    async def event_callback(subscription: Subscription, data):
        logger.info(f"Got topic {subscription.topic} - re-publishing as {CLIENT_TOPIC}")
        asyncio.create_task(endpoint.publish([CLIENT_TOPIC], data))

    @app.on_event("startup")
    async def startup():
        # subscribe to our own events
        await endpoint.subscribe([SERVER_TOPIC], event_callback)

    # Regular REST endpoint - that publishes to PubSub
    setup_server_rest_route(app, endpoint)
    uvicorn.run(app, port=PORT)
예제 #7
0
def setup_server():
    app = FastAPI()
    # PubSub websocket endpoint
    endpoint = PubSubEndpoint()
    endpoint.notifier.add_channel_restriction(verify_permitted_topics)

    @app.websocket("/pubsub")
    async def websocket_endpoint(websocket: WebSocket):
        headers = eval(websocket.headers["headers"])
        await endpoint.main_loop(websocket, **headers)

    @app.get("/trigger")
    async def trigger_events():
        logger.info("Triggered via HTTP route - publishing event")
        # Publish an event - to our own server callback / which will trigger another event for the client
        # Since we are calling back (RPC) to the client- this would deadlock if we wait on it
        asyncio.create_task(endpoint.publish([CLIENT_TOPIC], data=DATA))
        return "triggered"

    uvicorn.run(app, port=PORT)
 - 1. run this script for the server
 - 2. once the server is up, run notifier_client_test.py
 - 3. send get request to server on: 'http://*****:*****@app.get("/trigger")
sys.path.append(os.path.abspath(os.path.join(os.path.basename(__file__),
                                             "..")))

from fastapi_websocket_pubsub import PubSubEndpoint
import asyncio
import os
from starlette.websockets import WebSocket
import uvicorn
from fastapi import FastAPI
from fastapi.routing import APIRouter

PORT = int(os.environ.get("PORT") or "8000")

app = FastAPI()
router = APIRouter()
endpoint = PubSubEndpoint(broadcaster="postgres://*****:*****@router.websocket("/pubsub")
async def websocket_rpc_endpoint(websocket: WebSocket):
    async with endpoint.broadcaster:
        await endpoint.main_loop(websocket)


app.include_router(router)


async def events():
    await asyncio.sleep(1)
    await endpoint.publish(["guns", "germs"])
    await asyncio.sleep(1)
예제 #10
0
import os
import sys

OPENAPI_NAME = os.getenv("OPENAPI_NAME", "Webhooks")
PROJECT_VERSION = os.getenv("PROJECT_VERSION", "0.0.1BETA")
LOG_LEVEL = os.getenv("LOG_LEVEL", "error")
log = logging.getLogger(__name__)

app = FastAPI(
    title=OPENAPI_NAME,
    description=
    "Welcome to the OpenAPI interface for the AriesCloudAPI webhooks handler",
    version=PROJECT_VERSION,
)
router = APIRouter()
endpoint = PubSubEndpoint()
endpoint.register_route(router, "/pubsub")
app.include_router(router)


@app.api_route("/{topic}/{wallet_id}")
@inject
async def wallet_hooks(
    topic: str,
    wallet_id: str,
    service: Service = Depends(Provide[Container.service])
) -> List[TopicItem[Any]]:
    data = await service.get_all_for_topic_by_wallet_id(topic=topic,
                                                        wallet_id=wallet_id)
    return data