import { o_assign, o_create, is_func, as_func } from './builtins.jsy' import { bindTimeouts } from './timeouts.jsy' import { bindCoreRouterAPI } from './router_core.jsy' import { base_channel, channel_kinds } from './channel.jsy' export class FabricRouter :: constructor(hub, {ms_interval}) :: o_assign @ this, @{} timeouts: bindTimeouts(ms_interval, err => this._on_error('timer', err)), _channel_: @{} __proto__: base_channel, router: this public_routes: this._initPublicRoutes() let self = o_create(this) if ! this._skip_bind_api :: o_assign @ this, bindCoreRouterAPI @ self, hub, this._initRoutes() return self _initRoutes() :: return new Map() _initPublicRoutes() :: return new Map() _on_error(scope, err) :: console.error @ 'router', scope, err on_dispatch_error(err) :: this._on_error('hub_dispatch', err) ref() :: this.loopback.ref() unref() :: this.loopback.unref() async publishRoute(route) :: await route.ready let id_route = route.id_route if 'string' === typeof id_route :: this.public_routes.set @ id_route, route return route setUpstream(upstream, opt) :: if null != opt :: this.upstream_opt = opt return this.upstream = as_func @ upstream.dispatch || upstream.send || upstream upstreamRoute(id_route) :: let { upstream, upstream_opt } = this if upstream :: return this.addDynamic @ id_route, upstream, upstream_opt discoverRoute(id_route, router_ctx) :: // see plugins/discovery // router_ctx || = this.router_ctx addPeer(id_route, channel, opt) :: let disp = channel.dispatch || channel.send let res = this.addRoute @ id_route, disp, opt if res && channel.when_closed :: channel.when_closed.then @ res.cancel return res addDynamic(id_route, route, opt) :: return is_func(route) ? this.addRoute(id_route, route, opt) : this.addPeer(id_route, route, opt) /* // from bindCoreRouterAPI addRoute(id_route, route, override) : [route, bound removeRoute] removeRoute(id_route, route) : Boolean removeRoute({id_route}) : Boolean hasRoute(id_route) : Boolean dispatch(pkt, channel) : Promise resolveRoute(id_route, allowDiscover, allowUpstream) : route function loopback router_ctx */ o_assign @ FabricRouter.prototype, channel_kinds, @{} upstream_opt: @{} ms_ttl: 60000