Ejemplo n.º 1
0
    def __init__(self,
                 host: str = 'localhost',
                 port: int = 8080,
                 path: str = '/',
                 realm: str = 'default',
                 *,
                 reconnect_delay: int = 5,
                 max_reconnection_attempts: int = None,
                 registry: Union[WAMPRegistry, str] = None,
                 ssl: Union[bool, str, SSLContext] = False,
                 serializer: Union[Serializer, str] = None,
                 auth_method: str = 'anonymous',
                 auth_id: str = None,
                 auth_secret: str = None):
        """
        The following parameters are also available as instance attributes:

        :param host: host address of the WAMP router
        :param port: port to connect to
        :param path: HTTP path on the router
        :param realm: the WAMP realm to join the application session to (defaults to the resource
            name if not specified)
        :param reconnect_delay: delay between connection attempts (in seconds)
        :param max_reconnection_attempts: maximum number of connection attempts before giving up
        :param registry: a WAMP registry or a string reference to one (defaults to creating a new
            instance if omitted)
        :param ssl: one of the following:

            * ``False`` to disable SSL
            * ``True`` to enable SSL using the default context
            * an :class:`ssl.SSLContext` instance
            * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance
            * name of an :class:`ssl.SSLContext` resource
        :param serializer: a serializer instance or the name of a
            :class:`asphalt.serialization.api.Serializer` resource (defaults to creating a new
            :class:`~asphalt.serialization.json.JSONSerializer` if omitted)
        :param auth_method: authentication method to use (valid values are currently ``anonymous``,
            ``wampcra`` and ``ticket``)
        :param auth_id: authentication ID (username)
        :param auth_secret: secret to use for authentication (ticket or password)

        """
        assert check_argument_types()
        self.host = host
        self.port = port
        self.path = path
        self.reconnect_delay = reconnect_delay
        self.max_reconnection_attempts = max_reconnection_attempts
        self.realm = realm
        self.registry = resolve_reference(registry) or WAMPRegistry()
        self.ssl = resolve_reference(ssl)
        self.serializer = resolve_reference(serializer) or JSONSerializer()
        self.auth_method = auth_method
        self.auth_id = auth_id
        self.auth_secret = auth_secret

        self._context = None
        self._session = None  # type: AsphaltSession
        self._session_details = None  # type: SessionDetails
        self._connect_task = None  # type: Task
Ejemplo n.º 2
0
    def __init__(
        self,
        *,
        url: str | URL | dict[str, Any] | None = None,
        bind: Connection | Engine | AsyncConnection | AsyncEngine
        | None = None,
        engine_args: dict[str, Any] | None = None,
        session_args: dict[str, Any] | None = None,
        commit_executor_workers: int = 5,
        ready_callback: Callable[[Engine, sessionmaker], Any] | str
        | None = None,
        poolclass: str | type[Pool] | None = None,
        resource_name: str = "default",
    ):
        self.resource_name = resource_name
        self.commit_executor_workers = commit_executor_workers
        self.ready_callback = resolve_reference(ready_callback)
        engine_args = engine_args or {}
        session_args = session_args or {}
        session_args["expire_on_commit"] = False
        session_args["future"] = True

        if bind:
            self.bind = bind
            self.engine = cast("Engine | AsyncEngine", bind.engine)
        else:
            if isinstance(url, dict):
                url = URL.create(**url)
            elif isinstance(url, str):
                url = make_url(url)
            elif url is None:
                raise TypeError('both "url" and "bind" cannot be None')

            # This is a hack to get SQLite to play nice with asphalt-sqlalchemy's
            # juggling of connections between multiple threads. The same connection
            # should, however, never be used in multiple threads at once.
            if url.get_dialect().name == "sqlite":
                connect_args = engine_args.setdefault("connect_args", {})
                connect_args.setdefault("check_same_thread", False)

            if isinstance(poolclass, str):
                poolclass = resolve_reference(poolclass)

            pool_class = cast("type[Pool]", poolclass)
            try:
                self.engine = self.bind = create_async_engine(
                    url, poolclass=pool_class, **engine_args)
            except InvalidRequestError:
                self.engine = self.bind = create_engine(url,
                                                        poolclass=pool_class,
                                                        **engine_args)

            if url.get_dialect().name == "sqlite":
                apply_sqlite_hacks(self.engine)

        if isinstance(self.engine, AsyncEngine):
            session_args.setdefault("class_", AsyncSession)

        self.sessionmaker = sessionmaker(bind=self.bind, **session_args)
Ejemplo n.º 3
0
    def __init__(self, app, ip: str = "127.0.0.1", port: int = 4444, **cfg):
        from kyoukai.app import Kyoukai
        if not isinstance(app, Kyoukai):
            app = resolve_reference(app)

        #: The application object for a this component.
        self.app = app

        #: The IP address to boot the server on.
        self.ip = ip

        #: The port to boot the server on.
        self.port = port

        #: The config file to use.
        self.cfg = cfg

        #: The :class:`asyncio.Server` instance that is serving us today.
        self.server = None

        #: The base context for this server.
        self.base_context = None  # type: Context

        #: The backend to use for the HTTP server.
        self.backend = self.cfg.get("backend", "kyoukai.backends.httptools_")

        self.logger = logging.getLogger("Kyoukai")

        self._server_name = app.server_name or socket.getfqdn()
 def __init__(self, encoder_options: Dict[str, Any] = None,
              decoder_options: Dict[str, Any] = None,
              custom_type_codec: Union[CBORTypeCodec, str] = None) -> None:
     assert check_argument_types()
     super().__init__(resolve_reference(custom_type_codec) or CBORTypeCodec())
     self.encoder_options = encoder_options or {}
     self.decoder_options = decoder_options or {}
Ejemplo n.º 5
0
    def __init__(self, app, ip: str = "127.0.0.1", port: int = 4444, **cfg):
        from kyoukai.app import Kyoukai
        if not isinstance(app, Kyoukai):
            app = resolve_reference(app)

        #: The application object for a this component.
        self.app = app

        #: The IP address to boot the server on.
        self.ip = ip

        #: The port to boot the server on.
        self.port = port

        #: The config file to use.
        self.cfg = cfg

        #: The :class:`asyncio.Server` instance that is serving us today.
        self.server = None

        #: The base context for this server.
        self.base_context = None  # type: Context

        #: The backend to use for the HTTP server.
        self.backend = self.cfg.get("backend", "kyoukai.backends.httptools_")

        self.logger = logging.getLogger("Kyoukai")

        self._server_name = app.server_name or socket.getfqdn()
Ejemplo n.º 6
0
 def __init__(self, encoder_options: Dict[str, Any] = None,
              decoder_options: Dict[str, Any] = None,
              custom_type_codec: Union[CBORTypeCodec, str] = None):
     assert check_argument_types()
     super().__init__(resolve_reference(custom_type_codec) or CBORTypeCodec())
     self.encoder_options = encoder_options or {}
     self.decoder_options = decoder_options or {}
Ejemplo n.º 7
0
    def __init__(self, encoder_options: Dict[str, Any] = None,
                 decoder_options: Dict[str, Any] = None, encoding: str = 'utf-8',
                 custom_type_codec: Union[JSONTypeCodec, str] = None):
        assert check_argument_types()
        super().__init__(resolve_reference(custom_type_codec) or JSONTypeCodec())
        self.encoding = encoding

        self.encoder_options = encoder_options or {}
        self.encoder_options['default'] = resolve_reference(self.encoder_options.get('default'))
        self._encoder = JSONEncoder(**self.encoder_options)

        self.decoder_options = decoder_options or {}
        self.decoder_options['object_hook'] = resolve_reference(
            self.decoder_options.get('object_hook'))
        self.decoder_options['object_pairs_hook'] = resolve_reference(
            self.decoder_options.get('object_pairs_hook'))
        self._decoder = JSONDecoder(**self.decoder_options)
    def __init__(self, encoder_options: Dict[str, Any] = None,
                 decoder_options: Dict[str, Any] = None, encoding: str = 'utf-8',
                 custom_type_codec: Union[JSONTypeCodec, str] = None) -> None:
        assert check_argument_types()
        super().__init__(resolve_reference(custom_type_codec) or JSONTypeCodec())
        self.encoding = encoding

        self.encoder_options = encoder_options or {}
        self.encoder_options['default'] = resolve_reference(self.encoder_options.get('default'))
        self._encoder = JSONEncoder(**self.encoder_options)

        self.decoder_options = decoder_options or {}
        self.decoder_options['object_hook'] = resolve_reference(
            self.decoder_options.get('object_hook'))
        self.decoder_options['object_pairs_hook'] = resolve_reference(
            self.decoder_options.get('object_pairs_hook'))
        self._decoder = JSONDecoder(**self.decoder_options)
Ejemplo n.º 9
0
    def configure_engine(cls, url: Union[str, URL, Dict[str, Any]] = None,
                         bind: Union[Connection, Engine] = None, session: Dict[str, Any] = None,
                         ready_callback: Union[Callable[[Engine, sessionmaker], Any], str] = None,
                         poolclass: Union[str, Pool] = None,
                         **engine_args):
        """
        Create an engine and selectively apply certain hacks to make it Asphalt friendly.

        :param url: the connection url passed to :func:`~sqlalchemy.create_engine`
            (can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
        :param bind: a connection or engine to use instead of creating a new engine
        :param session: keyword arguments to :class:`~sqlalchemy.orm.session.sessionmaker`
        :param ready_callback: callable (or a ``module:varname`` reference to one) called with two
            arguments: the Engine and the sessionmaker when the component is started but before the
            resources are added to the context
        :param poolclass: the SQLAlchemy Pool class to use; passed to
            :func:`~sqlalchemy.create_engine`
        :param engine_args: keyword arguments passed to :func:`~sqlalchemy.create_engine`

        """
        assert check_argument_types()
        if bind is None:
            if isinstance(url, dict):
                url = URL(**url)
            elif isinstance(url, str):
                url = make_url(url)
            elif url is None:
                raise TypeError('both "url" and "bind" cannot be None')
            if isinstance(poolclass, str):
                poolclass = resolve_reference(poolclass)

            # This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of
            # connections between multiple threads. The same connection should, however, never be
            # used in multiple threads at once.
            if url.get_dialect().name == 'sqlite':
                connect_args = engine_args.setdefault('connect_args', {})
                connect_args.setdefault('check_same_thread', False)

            bind = create_engine(url, poolclass=poolclass, **engine_args)

        session = session or {}
        session.setdefault('expire_on_commit', False)
        ready_callback = resolve_reference(ready_callback)
        return bind, sessionmaker(bind, **session), ready_callback
Ejemplo n.º 10
0
 def __init__(self,
              packer_options: Dict[str, Any] = None,
              unpacker_options: Dict[str, Any] = None,
              custom_type_codec: Union[MsgpackTypeCodec, str] = None):
     assert check_argument_types()
     super().__init__(
         resolve_reference(custom_type_codec) or MsgpackTypeCodec())
     self.packer_options = packer_options or {}
     self.packer_options.setdefault('use_bin_type', True)
     self.unpacker_options = unpacker_options or {}
     self.unpacker_options.setdefault('encoding', 'utf-8')
Ejemplo n.º 11
0
    def __init__(self, environment: Union[Environment, Dict[str, Any]] = None,
                 loader_class: Union[type, str] = PackageLoader, **loader_args):
        assert check_argument_types()
        if environment is None:
            environment = {}
        if isinstance(environment, dict):
            environment = Environment(**environment)
        self.environment = environment

        if self.environment.loader is None:
            loader_class = resolve_reference(loader_class)
            self.environment.loader = loader_class(**loader_args)
Ejemplo n.º 12
0
    def __init__(self, app: Union[str, Kyoukai], ip: str = '0.0.0.0', port: int = 4444, **cfg):
        assert check_argument_types()
        if not isinstance(app, Kyoukai):
            self.app = resolve_reference(app)
        else:
            self.app = app
        self.ip = ip
        self.port = port
        self._extra_cfg = cfg

        # Reconfigure the app with the extra config.
        self.app.reconfigure(**self._extra_cfg)

        self.server = None
Ejemplo n.º 13
0
    def __init__(
        self,
        environment: Environment | dict[str, Any] = None,
        loader_class: type | str = PackageLoader,
        **loader_args,
    ) -> None:
        if environment is None:
            environment = {}
        if isinstance(environment, dict):
            environment = Environment(**environment)
        self.environment = environment

        if self.environment.loader is None:
            resolved_loader_class = resolve_reference(loader_class)
            self.environment.loader = resolved_loader_class(**loader_args)
Ejemplo n.º 14
0
 def __init__(self, router: Union[Router, str], host: Union[str, Sequence[str]] = None,
              port: int = 8888, socket_path: Union[str, Path] = None, backlog: int = 100,
              external_host: str = None, external_port: int = None,
              external_prefix: str = None):
     assert check_argument_types()
     self.router = resolve_reference(router)  # type: Router
     self.host = host if isinstance(host, str) else tuple(host)
     self.port = port
     self.socket_path = str(socket_path) if socket_path else None
     self.backlog = backlog
     self.external_host = external_host
     self.external_port = external_port or port
     self.external_prefix = external_prefix
     self.parent_ctx = None  # type: Context
     self.clients = set()
     self.logger = logging.getLogger(self.__class__.__module__)
    def configure_engine(cls, context_attr: str = None, metadata: Union[str, MetaData] = None,
                         url: Union[str, URL, Dict[str, Any]] = None, bind: Connectable = None,
                         **engine_args):
        """
        Create an engine and optionally bind it to a :class:`~sqlalchemy.schema.MetaData`.

        If both ``url`` and ``bind`` are provided, the ``bind`` parameter takes priority.

        :param context_attr: context attribute for the engine
        :param metadata: a metadata object to bind to
        :param url: the connection url passed to :func:`~sqlalchemy.create_engine`
            (can also be a dictionary of :class:`~sqlalchemy.engine.url.URL` keyword arguments)
        :param bind: a connection or engine instance to use instead of creating a new engine
        :param engine_args: keyword arguments passed to :func:`~sqlalchemy.create_engine`

        """
        assert check_argument_types()
        if url and not bind:
            if isinstance(url, dict):
                url = URL(**url)
            elif isinstance(url, str):
                url = make_url(url)

            # This is a hack to get SQLite to play nice with asphalt-sqlalchemy's juggling of
            # connections between multiple threads. The same connection should, however, never be
            # used in multiple threads at once.
            if url.drivername.split('+')[0] == 'sqlite':
                connect_args = engine_args.setdefault('connect_args', {})
                connect_args.setdefault('check_same_thread', False)

            bind = create_engine(url, **engine_args)
        elif not bind:
            raise ValueError('specify either url or bind')

        if metadata:
            metadata = resolve_reference(metadata)
            assert isinstance(metadata, MetaData)
            metadata.bind = bind

        return context_attr, bind
Ejemplo n.º 16
0
    def configure_client(
        cls,
        context_attr: str,
        address: Union[str, Path] = "localhost",
        port: int = 6379,
        db: int = 0,
        password: str = None,
        ssl: Union[bool, str, SSLContext] = False,
        **client_args
    ):
        """
        Configure a Redis client.

        :param context_attr: context attribute of the serializer (if omitted, the resource name
            will be used instead)
        :param address: IP address, host name or path to a UNIX socket
        :param port: port number to connect to (ignored for UNIX sockets)
        :param db: database number to connect to
        :param password: password used if the server requires authentication
        :param ssl: one of the following:

            * ``False`` to disable SSL
            * ``True`` to enable SSL using the default context
            * an :class:`ssl.SSLContext` instance
            * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance
            * name of an :class:`ssl.SSLContext` resource
        :param client_args: extra keyword arguments passed to
            :func:`~aioredis.create_reconnecting_redis`

        """
        assert check_argument_types()
        if isinstance(address, str) and not address.startswith("/"):
            address = (address, port)

        client_args.update({"address": address, "db": db, "password": password, "ssl": resolve_reference(ssl)})
        return context_attr, client_args
Ejemplo n.º 17
0
    def __init__(self, host: str = 'localhost', port: int = 8080, path: str = '/ws',
                 realm: str = 'realm1', *, protocol_options: Dict[str, Any] = None,
                 connection_timeout: float = 10, reconnect_delay: float = 5,
                 max_reconnection_attempts: Optional[int] = 15,
                 shutdown_timeout: Optional[float] = 15,
                 registry: Union[WAMPRegistry, str] = None, tls: bool = False,
                 tls_context: Union[str, SSLContext] = None,
                 serializer: Union[Serializer, str] = None, auth_method: str = 'anonymous',
                 auth_id: str = None, auth_secret: str = None) -> None:
        """
        :param host: host address of the WAMP router
        :param port: port to connect to
        :param path: HTTP path on the router
        :param realm: the WAMP realm to join the application session to (defaults to the resource
            name if not specified)
        :param protocol_options: dictionary of Autobahn's `websocket protocol options`_
        :param connection_timeout: maximum time to wait for the client to connect to the router and
            join a realm
        :param reconnect_delay: delay between connection attempts (in seconds)
        :param max_reconnection_attempts: maximum number of connection attempts before giving up
        :param shutdown_timeout: maximum number of seconds to wait for the client to complete its
            shutdown sequence (unregister procedures/subscriptions, wait for running handlers to
            finish, leave the realm)
        :param registry: a :class:`~asphalt.wamp.registry.WAMPRegistry` instance, a
            ``module:varname`` reference or resource name of one
        :param tls: ``True`` to use TLS when connecting to the router
        :param tls_context: an :class:`~ssl.SSLContext` instance or the resource name of one
        :param serializer: a :class:`asphalt.serialization.api.Serializer` instance or the resource
            name of one
        :param auth_method: authentication method to use (valid values are currently ``anonymous``,
            ``wampcra`` and ``ticket``)
        :param auth_id: authentication ID (username)
        :param auth_secret: secret to use for authentication (ticket or password)

        .. _websocket protocol options:
            http://autobahn.readthedocs.io/en/latest/websocket/programming.html#websocket-options

        """
        assert check_argument_types()
        self.host = host
        self.port = port
        self.path = path
        self.reconnect_delay = reconnect_delay
        self.connection_timeout = connection_timeout
        self.shutdown_timeout = shutdown_timeout
        self.max_reconnection_attempts = max_reconnection_attempts
        self.realm = realm
        self.protocol_options = protocol_options or {}
        self.tls = tls
        self.tls_context = tls_context
        self.serializer = serializer or JSONSerializer()
        self.auth_method = auth_method
        self.auth_id = auth_id
        self.auth_secret = auth_secret

        self._parent_context = None  # type: Context
        self._loop = None  # type: AbstractEventLoop
        self._registry = resolve_reference(registry) or WAMPRegistry()
        self._session = None  # type: AsphaltSession
        self._session_details = None  # type: SessionDetails
        self._connect_task = None  # type: Task
        self._request_tasks = set()  # type: Set[Task]
        self._registrations = []  # type: List[IRegistration]
        self._subscriptions = []  # type: List[ISubscription]