import{_ as n,o as a,c as s,d as e}from"./app-EhCe7g9m.js";const t={},p=e(`

func set_channel()

说明: 设置通道实例

参数:

源代码
def set_channel(name: str, channel: 'Channel'):
    """
    设置通道实例
    Args:
        name: 通道名称
        channel: 通道实例
    """
    if not isinstance(channel, Channel):
        raise TypeError(f'channel_ must be an instance of Channel, {type(channel)} found')
    if IS_MAIN_PROCESS:
        if name in _channel:
            raise ValueError(f'Channel {name} already exists')
        _channel[name] = channel
    else:
        channel_deliver_passive_channel.send(('set_channel', {'name': name, 'channel_': channel}))

func set_channels()

说明: 设置通道实例

参数:

源代码
def set_channels(channels: dict[str, 'Channel']):
    """
    设置通道实例
    Args:
        channels: 通道名称
    """
    for (name, channel) in channels.items():
        set_channel(name, channel)

func get_channel() -> Channel

说明: 获取通道实例

参数:

源代码
def get_channel(name: str) -> 'Channel':
    """
    获取通道实例
    Args:
        name: 通道名称
    Returns:
    """
    if IS_MAIN_PROCESS:
        return _channel[name]
    else:
        recv_chan = Channel[Channel[Any]]('recv_chan')
        channel_deliver_passive_channel.send(('get_channel', {'name': name, 'recv_chan': recv_chan}))
        return recv_chan.receive()

func get_channels() -> dict[str, Channel]

说明: 获取通道实例

源代码
def get_channels() -> dict[str, 'Channel']:
    """
    获取通道实例
    Returns:
    """
    if IS_MAIN_PROCESS:
        return _channel
    else:
        recv_chan = Channel[dict[str, Channel[Any]]]('recv_chan')
        channel_deliver_passive_channel.send(('get_channels', {'recv_chan': recv_chan}))
        return recv_chan.receive()

@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'set_channel')

func on_set_channel()

源代码
@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'set_channel')
def on_set_channel(data: tuple[str, dict[str, Any]]):
    (name, channel) = (data[1]['name'], data[1]['channel_'])
    set_channel(name, channel)

@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channel')

func on_get_channel()

源代码
@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channel')
def on_get_channel(data: tuple[str, dict[str, Any]]):
    (name, recv_chan) = (data[1]['name'], data[1]['recv_chan'])
    recv_chan.send(get_channel(name))

@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channels')

func on_get_channels()

源代码
@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channels')
def on_get_channels(data: tuple[str, dict[str, Any]]):
    recv_chan = data[1]['recv_chan']
    recv_chan.send(get_channels())

class Channel(Generic[T])

method __init__(self, name: str, type_check: Optional[bool] = None)

说明: 初始化通道

参数:

源代码
def __init__(self, name: str, type_check: Optional[bool]=None):
    """
        初始化通道
        Args:
            name: 通道ID
            type_check: 是否开启类型检查, 若为空,则传入泛型默认开启,否则默认关闭
        """
    (self.conn_send, self.conn_recv) = Pipe()
    (self._conn_send_inner, self._conn_recv_inner) = Pipe()
    self._closed = False
    self._on_main_receive_func_ids: list[int] = []
    self._on_sub_receive_func_ids: list[int] = []
    self.name: str = name
    self.is_receive_loop_running = False
    if type_check is None:
        type_check = self._get_generic_type() is not None
    elif type_check:
        if self._get_generic_type() is None:
            raise TypeError('Type hint is required for enforcing type check.')
    self.type_check = type_check
    if name in _channel:
        raise ValueError(f'Channel {name} already exists')
    if IS_MAIN_PROCESS:
        if name in _channel:
            raise ValueError(f'Channel {name} already exists')
        _channel[name] = self
        logger.debug(f'Channel {name} initialized in main process')
    else:
        logger.debug(f'Channel {name} initialized in sub process, should manually set in main process')

method _get_generic_type(self) -> Optional[type]

说明: 获取通道传递泛型类型

返回: Optional[type]: 泛型类型

源代码
def _get_generic_type(self) -> Optional[type]:
    """
        获取通道传递泛型类型

        Returns:
            Optional[type]: 泛型类型
        """
    if hasattr(self, '__orig_class__'):
        return get_args(self.__orig_class__)[0]
    return None

method _validate_structure(self, data: Any, structure: type) -> bool

说明: 验证数据结构

返回: bool: 是否通过验证

参数:

源代码
def _validate_structure(self, data: Any, structure: type) -> bool:
    """
        验证数据结构
        Args:
            data: 数据
            structure: 结构

        Returns:
            bool: 是否通过验证
        """
    if isinstance(structure, type):
        return isinstance(data, structure)
    elif isinstance(structure, tuple):
        if not isinstance(data, tuple) or len(data) != len(structure):
            return False
        return all((self._validate_structure(d, s) for (d, s) in zip(data, structure)))
    elif isinstance(structure, list):
        if not isinstance(data, list):
            return False
        return all((self._validate_structure(d, structure[0]) for d in data))
    elif isinstance(structure, dict):
        if not isinstance(data, dict):
            return False
        return all((k in data and self._validate_structure(data[k], structure[k]) for k in structure))
    return False

method send(self, data: T)

说明: 发送数据,发送函数为同步函数,没有异步的必要

参数:

源代码
def send(self, data: T):
    """
        发送数据,发送函数为同步函数,没有异步的必要
        Args:
            data: 数据
        """
    if self.type_check:
        _type = self._get_generic_type()
        if _type is not None and (not self._validate_structure(data, _type)):
            raise TypeError(f'Data must be an instance of {_type}, {type(data)} found')
    if self._closed:
        raise RuntimeError('Cannot send to a closed channel_')
    self.conn_send.send(data)

method receive(self) -> T

说明: 同步接收数据,会阻塞线程

源代码
def receive(self) -> T:
    """
        同步接收数据,会阻塞线程
        Args:
        """
    if self._closed:
        raise RuntimeError('Cannot receive from a closed channel_')
    while True:
        data = self.conn_recv.recv()
        return data

async method async_receive(self) -> T

说明: 异步接收数据,会挂起等待

源代码
async def async_receive(self) -> T:
    """
        异步接收数据,会挂起等待
        """
    print('等待接收数据')
    loop = asyncio.get_running_loop()
    data = await loop.run_in_executor(None, self.receive)
    print('接收到数据')
    return data

method on_receive(self, filter_func: Optional[FILTER_FUNC] = None) -> Callable[[Callable[[T], Any]], Callable[[T], Any]]

说明: 接收数据并执行函数

返回: 装饰器,装饰一个函数在接收到数据后执行

参数:

源代码
def on_receive(self, filter_func: Optional[FILTER_FUNC]=None) -> Callable[[Callable[[T], Any]], Callable[[T], Any]]:
    """
        接收数据并执行函数
        Args:
            filter_func: 过滤函数,为None则不过滤
        Returns:
            装饰器,装饰一个函数在接收到数据后执行
        """
    if not IS_MAIN_PROCESS:
        raise RuntimeError('on_receive can only be used in main process')

    def decorator(func: Callable[[T], Any]) -> Callable[[T], Any]:
        global _func_id

        async def wrapper(data: T) -> Any:
            if filter_func is not None:
                if is_coroutine_callable(filter_func):
                    if not await filter_func(data):
                        return
                elif not filter_func(data):
                    return
            if is_coroutine_callable(func):
                return await func(data)
            else:
                return func(data)
        _callback_funcs[_func_id] = wrapper
        if IS_MAIN_PROCESS:
            self._on_main_receive_func_ids.append(_func_id)
        else:
            self._on_sub_receive_func_ids.append(_func_id)
        _func_id += 1
        return func
    return decorator

async method _run_on_receive_funcs(self, data: Any)

说明: 运行接收函数

参数:

源代码
async def _run_on_receive_funcs(self, data: Any):
    """
        运行接收函数
        Args:
            data: 数据
        """
    if IS_MAIN_PROCESS:
        [asyncio.create_task(_callback_funcs[func_id](data)) for func_id in self._on_main_receive_func_ids]
    else:
        [asyncio.create_task(_callback_funcs[func_id](data)) for func_id in self._on_sub_receive_func_ids]

async method start_receive_loop(self)

说明: 开始接收数据 会自动判断主进程和子进程,需要在对应进程都调度一次

源代码
async def start_receive_loop(self):
    """
        开始接收数据
        会自动判断主进程和子进程,需要在对应进程都调度一次
        """
    if len(self._on_main_receive_func_ids) == 0:
        logger.warning(f'No on_receive function registered for {self.name}')
        return
    self.is_receive_loop_running = True
    logger.debug(f'Starting receive loop for {self.name}')
    while not self._closed:
        data = await self.async_receive()
        await self._run_on_receive_funcs(data)

var SYNC_ON_RECEIVE_FUNC = Callable[[T], Any]

var ASYNC_ON_RECEIVE_FUNC = Callable[[T], Coroutine[Any, Any, Any]]

var ON_RECEIVE_FUNC = SYNC_ON_RECEIVE_FUNC | ASYNC_ON_RECEIVE_FUNC

var SYNC_FILTER_FUNC = Callable[[T], bool]

var ASYNC_FILTER_FUNC = Callable[[T], Coroutine[Any, Any, bool]]

var FILTER_FUNC = SYNC_FILTER_FUNC | ASYNC_FILTER_FUNC

var _func_id = 0

var _channel = {}

var _callback_funcs = {}

var active_channel = Channel(name='active_channel')

var passive_channel = Channel(name='passive_channel')

var publish_channel = Channel(name='publish_channel')

var channel_deliver_active_channel = NO_DEFAULT

var channel_deliver_passive_channel = NO_DEFAULT

`,96),c=[p];function l(o,i){return a(),s("div",null,c)}const r=n(t,[["render",l],["__file","channel.html.vue"]]),d=JSON.parse(`{"path":"/api/comm/channel.html","title":"liteyuki.comm.channel","lang":"zh-CN","frontmatter":{"title":"liteyuki.comm.channel","description":"func set_channel() 说明: 设置通道实例 参数: name: 通道名称 channel: 通道实例 源代码 func set_channels() 说明: 设置通道实例 参数: channels: 通道名称 源代码 func get_channel() -> Channel 说明: 获取通道实例 参数: name: 通道名称 源代码 ...","head":[["link",{"rel":"alternate","hreflang":"en-us","href":"https://vuepress-theme-hope-docs-demo.netlify.app/en/api/comm/channel.html"}],["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/api/comm/channel.html"}],["meta",{"property":"og:site_name","content":"LiteyukiBot 轻雪机器人"}],["meta",{"property":"og:title","content":"liteyuki.comm.channel"}],["meta",{"property":"og:description","content":"func set_channel() 说明: 设置通道实例 参数: name: 通道名称 channel: 通道实例 源代码 func set_channels() 说明: 设置通道实例 参数: channels: 通道名称 源代码 func get_channel() -> Channel 说明: 获取通道实例 参数: name: 通道名称 源代码 ..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"zh-CN"}],["meta",{"property":"og:locale:alternate","content":"en-US"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"liteyuki.comm.channel\\",\\"image\\":[\\"\\"],\\"dateModified\\":null,\\"author\\":[]}"]]},"headers":[{"level":3,"title":"func set_channel()","slug":"func-set-channel","link":"#func-set-channel","children":[]},{"level":3,"title":"func set_channels()","slug":"func-set-channels","link":"#func-set-channels","children":[]},{"level":3,"title":"func get_channel() -> Channel","slug":"func-get-channel-channel","link":"#func-get-channel-channel","children":[]},{"level":3,"title":"func get_channels() -> dict[str, Channel]","slug":"func-get-channels-dict-str-channel","link":"#func-get-channels-dict-str-channel","children":[]},{"level":3,"title":"@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'set_channel')","slug":"channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-set-channel","link":"#channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-set-channel","children":[]},{"level":3,"title":"func on_set_channel()","slug":"func-on-set-channel","link":"#func-on-set-channel","children":[]},{"level":3,"title":"@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channel')","slug":"channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-get-channel","link":"#channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-get-channel","children":[]},{"level":3,"title":"func on_get_channel()","slug":"func-on-get-channel","link":"#func-on-get-channel","children":[]},{"level":3,"title":"@channel_deliver_passive_channel.on_receive(filter_func=lambda data: data[0] == 'get_channels')","slug":"channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-get-channels","link":"#channel-deliver-passive-channel-on-receive-filter-func-lambda-data-data-0-get-channels","children":[]},{"level":3,"title":"func on_get_channels()","slug":"func-on-get-channels","link":"#func-on-get-channels","children":[]},{"level":3,"title":"class Channel(Generic[T])","slug":"class-channel-generic-t","link":"#class-channel-generic-t","children":[]},{"level":3,"title":"method __init__(self, name: str, type_check: Optional[bool] = None)","slug":"method-init-self-name-str-type-check-optional-bool-none","link":"#method-init-self-name-str-type-check-optional-bool-none","children":[]},{"level":3,"title":"method _get_generic_type(self) -> Optional[type]","slug":"method-get-generic-type-self-optional-type","link":"#method-get-generic-type-self-optional-type","children":[]},{"level":3,"title":"method _validate_structure(self, data: Any, structure: type) -> bool","slug":"method-validate-structure-self-data-any-structure-type-bool","link":"#method-validate-structure-self-data-any-structure-type-bool","children":[]},{"level":3,"title":"method send(self, data: T)","slug":"method-send-self-data-t","link":"#method-send-self-data-t","children":[]},{"level":3,"title":"method receive(self) -> T","slug":"method-receive-self-t","link":"#method-receive-self-t","children":[]},{"level":3,"title":"async method async_receive(self) -> T","slug":"async-method-async-receive-self-t","link":"#async-method-async-receive-self-t","children":[]},{"level":3,"title":"method on_receive(self, filter_func: Optional[FILTER_FUNC] = None) -> Callable[[Callable[[T], Any]], Callable[[T], Any]]","slug":"method-on-receive-self-filter-func-optional-filter-func-none-callable-callable-t-any-callable-t-any","link":"#method-on-receive-self-filter-func-optional-filter-func-none-callable-callable-t-any-callable-t-any","children":[]},{"level":3,"title":"async method _run_on_receive_funcs(self, data: Any)","slug":"async-method-run-on-receive-funcs-self-data-any","link":"#async-method-run-on-receive-funcs-self-data-any","children":[]},{"level":3,"title":"async method start_receive_loop(self)","slug":"async-method-start-receive-loop-self","link":"#async-method-start-receive-loop-self","children":[]},{"level":3,"title":"var SYNC_ON_RECEIVE_FUNC = Callable[[T], Any]","slug":"var-sync-on-receive-func-callable-t-any","link":"#var-sync-on-receive-func-callable-t-any","children":[]},{"level":3,"title":"var ASYNC_ON_RECEIVE_FUNC = Callable[[T], Coroutine[Any, Any, Any]]","slug":"var-async-on-receive-func-callable-t-coroutine-any-any-any","link":"#var-async-on-receive-func-callable-t-coroutine-any-any-any","children":[]},{"level":3,"title":"var ON_RECEIVE_FUNC = SYNC_ON_RECEIVE_FUNC | ASYNC_ON_RECEIVE_FUNC","slug":"var-on-receive-func-sync-on-receive-func-async-on-receive-func","link":"#var-on-receive-func-sync-on-receive-func-async-on-receive-func","children":[]},{"level":3,"title":"var SYNC_FILTER_FUNC = Callable[[T], bool]","slug":"var-sync-filter-func-callable-t-bool","link":"#var-sync-filter-func-callable-t-bool","children":[]},{"level":3,"title":"var ASYNC_FILTER_FUNC = Callable[[T], Coroutine[Any, Any, bool]]","slug":"var-async-filter-func-callable-t-coroutine-any-any-bool","link":"#var-async-filter-func-callable-t-coroutine-any-any-bool","children":[]},{"level":3,"title":"var FILTER_FUNC = SYNC_FILTER_FUNC | ASYNC_FILTER_FUNC","slug":"var-filter-func-sync-filter-func-async-filter-func","link":"#var-filter-func-sync-filter-func-async-filter-func","children":[]},{"level":3,"title":"var _func_id = 0","slug":"var-func-id-0","link":"#var-func-id-0","children":[]},{"level":3,"title":"var _channel = {}","slug":"var-channel","link":"#var-channel","children":[]},{"level":3,"title":"var _callback_funcs = {}","slug":"var-callback-funcs","link":"#var-callback-funcs","children":[]},{"level":3,"title":"var active_channel = Channel(name='active_channel')","slug":"var-active-channel-channel-name-active-channel","link":"#var-active-channel-channel-name-active-channel","children":[]},{"level":3,"title":"var passive_channel = Channel(name='passive_channel')","slug":"var-passive-channel-channel-name-passive-channel","link":"#var-passive-channel-channel-name-passive-channel","children":[]},{"level":3,"title":"var publish_channel = Channel(name='publish_channel')","slug":"var-publish-channel-channel-name-publish-channel","link":"#var-publish-channel-channel-name-publish-channel","children":[]},{"level":3,"title":"var channel_deliver_active_channel = NO_DEFAULT","slug":"var-channel-deliver-active-channel-no-default","link":"#var-channel-deliver-active-channel-no-default","children":[]},{"level":3,"title":"var channel_deliver_passive_channel = NO_DEFAULT","slug":"var-channel-deliver-passive-channel-no-default","link":"#var-channel-deliver-passive-channel-no-default","children":[]}],"git":{"createdTime":null,"updatedTime":null,"contributors":[]},"readingTime":{"minutes":5.4,"words":1621},"filePathRelative":"api/comm/channel.md","autoDesc":true}`);export{r as comp,d as data};