#!/usr/bin/env python3
"""
Asynchronous frontend server.

This application contains 2 components: the queue manager, which received queue
creation commands from the Web UI and subscribes to them, and the Ajax
frontend, which receives HTTP calls from Javascript and gets messages from the
queue manager.
"""

from twisted.application.internet import TCPServer
from twisted.application.service import Application

from canonical.twisted.site import MaxMemorySite
from canonical.txlongpoll.frontend import QueueManager, FrontEndAjax

from canonical.landscape.environment import get_raw_config
from canonical.landscape.setup import setup_broker, get_instance_id
from canonical.landscape.scripts.async_frontend import run


if __name__ == "__main__":
    run()


application = Application("async-frontend")

cp = get_raw_config()
instance = get_instance_id()
frontend_port = cp.getint("async-frontend", "base-port") + instance - 1
max_service_memory = cp.getint("global", "max-service-memory", fallback=0)

manager = QueueManager("landscape")
resource = FrontEndAjax(manager)

setup_broker({"broker": dict(cp.items("broker"))}, manager.connected,
             manager.disconnected, application)

TCPServer(
    frontend_port,
    MaxMemorySite(resource, max_memory_mib=max_service_memory),
).setServiceParent(application)
