Reuse persistent feeds by resolved market endpoint
A chart could open a dated IB future through search, detach, then request its continuous alias against the same datad. Lookup by the request spelling missed the existing feed and tried to allocate a second history writer on its SHM. Failed startup could leave the quote producer running without a sampler to drain its channel. Resolve metadata before allocation and key `_FeedsBus.feeds` only by canonical, broker-qualified FQME. Recheck under the allocation lock and return the existing `Flume` without starting another producer. Require `get_mkt_info()` rather than trying provisional quote subscriptions to discover endpoint identity. Split the decision/lifetime from allocation: - `maybe_allocate_persistent_feed()` resolves/reuses, or opens a feed-local `trio` nursery for a new endpoint; - `allocate_persistent_feed()` starts quote/history children and returns the descriptor, writable buffers and sampling inputs; - the `maybe_` parent publishes and starts back the `Flume`, then handles readiness, buffer seeding and the blocking sampler call; - cancel/join the local children when that operating body exits, including normal sampler return and failed history startup. Preserve startup ordering, explain task/scope ownership, qualify request-name logging and configure the shared data logger itself. This is lifetime cleanup, not independent restart supervision. Human verified the alias reopen fix and found full Binance boots with/without the patch felt comparable on AC; no latency benchmark or startup-speedup claim is implied. Regression suites are retained for a separate test commit. (this patch was generated in some part by `opencode` using `openai/gpt-6-astra` (`openai`))wkt/history_segment_refill
parent
6834573276
commit
ff136ecb84
|
|
@ -38,6 +38,7 @@ from typing import (
|
|||
Any,
|
||||
AsyncContextManager,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Sequence,
|
||||
TYPE_CHECKING,
|
||||
)
|
||||
|
|
@ -81,6 +82,7 @@ from ._sampling import (
|
|||
if TYPE_CHECKING:
|
||||
from .flows import Flume
|
||||
from tractor.discovery._addr import Address
|
||||
from tractor.ipc._shm import ShmArray
|
||||
from tractor.msg.types import Aid
|
||||
|
||||
|
||||
|
|
@ -127,7 +129,10 @@ class _FeedsBus(Struct):
|
|||
'''
|
||||
brokername: str
|
||||
nursery: trio.Nursery
|
||||
feeds: dict[str, tuple[dict, dict]] = {}
|
||||
# `_FeedsBus.feeds` holds one descriptor per resolved,
|
||||
# broker-qualified market endpoint. Request aliases belong to
|
||||
# provider resolution, not this registry.
|
||||
feeds: dict[str, Flume] = {}
|
||||
|
||||
task_lock: trio.StrictFIFOLock = trio.StrictFIFOLock()
|
||||
|
||||
|
|
@ -232,11 +237,13 @@ def get_feed_bus(
|
|||
)
|
||||
assert not _bus.feeds
|
||||
|
||||
assert _bus.brokername == brokername, "Uhhh wtf"
|
||||
assert _bus.brokername == brokername, (
|
||||
f'Uhhh wtf, mismatched `_FeedBus.brokername != {brokername!r}'
|
||||
)
|
||||
return _bus
|
||||
|
||||
|
||||
async def allocate_persistent_feed(
|
||||
async def maybe_allocate_persistent_feed(
|
||||
bus: _FeedsBus,
|
||||
sub_registered: trio.Event,
|
||||
|
||||
|
|
@ -246,36 +253,257 @@ async def allocate_persistent_feed(
|
|||
start_stream: bool = True,
|
||||
init_timeout: float = 616,
|
||||
|
||||
task_status: TaskStatus[FeedInit] = trio.TASK_STATUS_IGNORED,
|
||||
task_status: TaskStatus[Flume] = trio.TASK_STATUS_IGNORED,
|
||||
|
||||
) -> None:
|
||||
'''
|
||||
Create and maintain a "feed bus" which allocates tasks for real-time
|
||||
streaming and optional historical data storage per broker/data provider
|
||||
backend; this normally task runs *in* a `datad` actor.
|
||||
Allocate or reuse a data feed, deliver a `Flume` handle.
|
||||
|
||||
If none exists, this allocates a ``_FeedsBus`` which manages the
|
||||
lifetimes of streaming tasks created for each requested symbol.
|
||||
- The caller holds ``_FeedsBus.task_lock`` until startup
|
||||
completes.
|
||||
- Require provider metadata via `get_mkt_info()` before
|
||||
quote/history task starts.
|
||||
- Report an existing ``Flume`` immediately, without opening a
|
||||
nursery or quote subscription for that endpoint.
|
||||
- Otherwise await ``allocate_persistent_feed()`` for its allocated
|
||||
state, report startup, and run sampling in this parent task.
|
||||
|
||||
task/scope architecture::
|
||||
|
||||
2 tasks are created:
|
||||
- a real-time streaming task which connec
|
||||
{> _FeedsBus.nursery
|
||||
|_>( maybe_allocate_persistent_feed [parent task]
|
||||
>> resolve endpoint; check _FeedsBus.feeds
|
||||
>> reuse: started(flume), then return
|
||||
>{ tn [new endpoint only]
|
||||
|_>> await allocate_persistent_feed [same task]
|
||||
|_>( mod.stream_quotes [child task] )
|
||||
|_>( manage_history [child task] )
|
||||
>> return allocated state
|
||||
>> publish Flume; started(flume)
|
||||
>> await live/subscriber readiness
|
||||
>> await sample_and_broadcast [same task]
|
||||
>c} finally: cancel tn children, nursery exit
|
||||
>) maybe_allocate_persistent_feed exit
|
||||
|
||||
sclang-syntax:
|
||||
(> task-start
|
||||
{> scope-open
|
||||
>> in-task work.
|
||||
|
||||
``tn`` owns all children, errors propagate to
|
||||
`_FeedsBus.nursery`; (currently) no restart supervision is
|
||||
provided.
|
||||
|
||||
'''
|
||||
# load backend module
|
||||
mod: ModuleType
|
||||
try:
|
||||
mod = get_brokermod(brokername)
|
||||
except ImportError:
|
||||
mod = get_ingestormod(brokername)
|
||||
|
||||
# Prefer resolving before opening a quote subscription: some
|
||||
# backends share one subscription for aliases of a contract,
|
||||
# so opening and then cancelling a duplicate can disturb it.
|
||||
# Native details stay opaque here; only `MktPair` identity
|
||||
# participates in the `_FeedsBus.feeds` lookup.
|
||||
get_mkt_info: Callable[
|
||||
[str],
|
||||
Awaitable[tuple[MktPair, object]|None],
|
||||
]|None = getattr(
|
||||
mod,
|
||||
'get_mkt_info',
|
||||
None,
|
||||
)
|
||||
if get_mkt_info is None:
|
||||
raise NotImplementedError(
|
||||
f'{brokername!r} must expose get_mkt_info() before '
|
||||
f'allocating a persistent feed for {symstr!r}'
|
||||
)
|
||||
|
||||
# Providers own metadata caching. In this datad process,
|
||||
# `piker.brokers.ib.symbols.get_mkt_info()` is decorated with
|
||||
# `async_lifo_cache()`, keyed by request spelling, so its
|
||||
# later streaming call can reuse this result. Distinct
|
||||
# aliases can still require a lookup each. This is in-memory
|
||||
# caching, not persistent `SymbologyCache` support or a
|
||||
# guarantee about other providers' caches.
|
||||
with trio.fail_after(init_timeout):
|
||||
resolved: tuple[MktPair, object]|None = (
|
||||
await get_mkt_info(symstr)
|
||||
)
|
||||
|
||||
if resolved is None:
|
||||
raise ValueError(
|
||||
f'{brokername!r} returned no market metadata for {symstr!r}'
|
||||
)
|
||||
|
||||
mkt: MktPair
|
||||
_provider_details: object
|
||||
mkt, _provider_details = resolved
|
||||
fqme: str = mkt.fqme
|
||||
existing_flume: Flume|None = bus.feeds.get(fqme)
|
||||
if existing_flume is not None:
|
||||
log.info(f'Reusing feed for alias {symstr!r} -> {fqme!r}')
|
||||
task_status.started(existing_flume)
|
||||
return
|
||||
|
||||
# Only a new endpoint needs operating tasks. Own its quote/history
|
||||
# children here so failed startup cannot leave a producer in
|
||||
# `bus.nursery` without a sampler. The allocating parent runs
|
||||
# sampling until completion/cancellation; this is lifetime
|
||||
# ownership, not failure containment or restart supervision.
|
||||
tn: trio.Nursery
|
||||
async with (
|
||||
trionics.collapse_eg(),
|
||||
trio.open_nursery() as tn,
|
||||
):
|
||||
try:
|
||||
flume: Flume
|
||||
rt_shm: ShmArray
|
||||
hist_shm: ShmArray
|
||||
quote_stream: trio.MemoryReceiveChannel[dict]
|
||||
feed_is_live: trio.Event
|
||||
sum_tick_vlm: bool
|
||||
(
|
||||
flume,
|
||||
rt_shm,
|
||||
hist_shm,
|
||||
quote_stream,
|
||||
feed_is_live,
|
||||
sum_tick_vlm,
|
||||
) = await allocate_persistent_feed(
|
||||
tn=tn,
|
||||
mod=mod,
|
||||
mkt=mkt,
|
||||
symstr=symstr,
|
||||
loglevel=loglevel,
|
||||
init_timeout=init_timeout,
|
||||
)
|
||||
|
||||
# `_FeedsBus.feeds` registers only resolved endpoints.
|
||||
# Publish after allocation, while `bus.task_lock` is
|
||||
# still held by the caller awaiting our startup result.
|
||||
bus.feeds[fqme] = flume
|
||||
|
||||
# signal the ``open_feed_bus()`` caller task to continue
|
||||
# since we now have (some) history pushed to SHM.
|
||||
task_status.started(flume)
|
||||
|
||||
if not start_stream:
|
||||
await trio.sleep_forever()
|
||||
|
||||
# begin real-time updates of shm and tsdb once the feed
|
||||
# goes live; the backend indicates quotes have begun.
|
||||
await feed_is_live.wait()
|
||||
|
||||
# NOTE: if no high-freq sampled data has (yet) loaded,
|
||||
# seed the buffer with history - handy for backends
|
||||
# without 1s OHLC but with slower data such as 1m OHLC.
|
||||
if (
|
||||
not len(rt_shm.array)
|
||||
and
|
||||
hist_shm.array.size
|
||||
):
|
||||
rt_shm.push(hist_shm.array[-3:-1])
|
||||
ohlckeys: list[str] = ['open', 'high', 'low', 'close']
|
||||
rt_shm.array[ohlckeys][-2:] = (
|
||||
hist_shm.array['close'][-1]
|
||||
)
|
||||
rt_shm.array['volume'][-2:] = 0
|
||||
|
||||
# set fast buffer time step to 1s
|
||||
ts: int = round(time.time())
|
||||
rt_shm.array['time'][0] = ts
|
||||
rt_shm.array['time'][1] = ts + 1
|
||||
|
||||
elif hist_shm.array.size == 0:
|
||||
i: int
|
||||
for i in range(100):
|
||||
await trio.sleep(0.1)
|
||||
if hist_shm.array.size > 0:
|
||||
break
|
||||
else:
|
||||
await tractor.pause()
|
||||
raise RuntimeError(
|
||||
f'History (1m) Shm for {fqme} is empty!?'
|
||||
)
|
||||
|
||||
# wait for the spawning caller to register its
|
||||
# subscriber send-stream entry before sampling.
|
||||
await sub_registered.wait()
|
||||
|
||||
# Run OHLC sampling/broadcasting in this parent task.
|
||||
# `manage_history()` registers the separate incrementer.
|
||||
try:
|
||||
log.info(f'Starting sampler task for {fqme}')
|
||||
await sample_and_broadcast(
|
||||
bus=bus,
|
||||
rt_shm=rt_shm,
|
||||
hist_shm=hist_shm,
|
||||
quote_stream=quote_stream,
|
||||
brokername=brokername,
|
||||
sum_tick_vlm=sum_tick_vlm,
|
||||
)
|
||||
finally:
|
||||
log.warning(f'{fqme} feed task terminated')
|
||||
finally:
|
||||
# on sampler return we stop the quote/history siblings
|
||||
# too: nursery exit alone would wait forever.
|
||||
tn.cancel_scope.cancel()
|
||||
|
||||
|
||||
async def allocate_persistent_feed(
|
||||
tn: trio.Nursery,
|
||||
mod: ModuleType,
|
||||
mkt: MktPair,
|
||||
symstr: str,
|
||||
loglevel: str,
|
||||
init_timeout: float,
|
||||
) -> tuple[
|
||||
Flume,
|
||||
ShmArray,
|
||||
ShmArray,
|
||||
trio.MemoryReceiveChannel[dict],
|
||||
trio.Event,
|
||||
bool,
|
||||
]:
|
||||
'''
|
||||
Allocate a new endpoint's quote/history tasks and feed descriptor.
|
||||
|
||||
``maybe_allocate_persistent_feed()`` has resolved the endpoint
|
||||
and checked ``_FeedsBus.feeds`` under its allocation lock. It
|
||||
owns ``tn`` and keeps the children alive after this function
|
||||
returns. Return the ``Flume``, writable realtime/history SHM
|
||||
handles, quote receiver, live-readiness event and volume policy.
|
||||
The caller publishes the descriptor, reports startup and runs
|
||||
sampling without reattaching to the original writable buffers.
|
||||
|
||||
Provider ``FeedInit`` supplies quote/write options. Its market
|
||||
endpoint must agree with the metadata resolved before allocation;
|
||||
no reuse decision or fallback subscription is performed here.
|
||||
|
||||
'''
|
||||
|
||||
# mem chan handed to broker backend so it can push real-time
|
||||
# quotes to this task for sampling and history storage (see below).
|
||||
# quotes to this task for sampling and history storage
|
||||
# (see below).
|
||||
send: trio.MemorySendChannel[dict]
|
||||
quote_stream: trio.MemoryReceiveChannel[dict]
|
||||
send, quote_stream = trio.open_memory_channel(616)
|
||||
|
||||
# data sync signals for both history loading and market quotes
|
||||
some_data_ready = trio.Event()
|
||||
feed_is_live = trio.Event()
|
||||
|
||||
# Feed operating tasks:
|
||||
# - `mod.stream_quotes()` runs as a child of `tn` and supplies
|
||||
# realtime quotes through `quote_stream`.
|
||||
# - `manage_history()` runs as another child of `tn`, loading
|
||||
# history and maintaining configured storage backends.
|
||||
# - The caller awaits `sample_and_broadcast()` after allocation
|
||||
# to consume quotes, update SHM and broadcast to subscribers.
|
||||
#
|
||||
# establish broker backend quote stream by calling
|
||||
# ``stream_quotes()``, a required broker backend endpoint.
|
||||
init_msgs: (
|
||||
|
|
@ -290,66 +518,80 @@ async def allocate_persistent_feed(
|
|||
(
|
||||
init_msgs,
|
||||
first_quote,
|
||||
) = await bus.nursery.start(
|
||||
) = await tn.start(
|
||||
partial(
|
||||
mod.stream_quotes,
|
||||
send_chan=send,
|
||||
feed_is_live=feed_is_live,
|
||||
|
||||
# NOTE / TODO: eventualy we may support providing more then
|
||||
# one input here such that a datad daemon can multiplex
|
||||
# multiple live feeds from one task, instead of getting
|
||||
# a new request (and thus new task) for each subscription.
|
||||
# NOTE / TODO: eventualy we may support providing
|
||||
# more then one input here such that a datad daemon
|
||||
# can multiplex multiple live feeds from one task,
|
||||
# instead of getting a new request (and thus new
|
||||
# task) for each subscription.
|
||||
symbols=[symstr],
|
||||
)
|
||||
)
|
||||
|
||||
# TODO: this is indexed by symbol for now since we've planned (for
|
||||
# some time) to expect backends to handle single
|
||||
# TODO: this is indexed by symbol for now since we've planned
|
||||
# (for some time) to expect backends to handle single
|
||||
# ``.stream_quotes()`` calls with multiple symbols inputs to just
|
||||
# work such that a backend can do its own multiplexing if desired.
|
||||
# work such that a backend can do its own multiplexing if
|
||||
# desired.
|
||||
#
|
||||
# Likely this will require some design changes:
|
||||
# - the .started() should return some config output determining
|
||||
# whether the backend does indeed multiplex multi-symbol quotes
|
||||
# internally or whether separate task spawns should be done per
|
||||
# symbol (as it is right now).
|
||||
# - information about discovery of non-local host daemons which can
|
||||
# be contacted in the case where we want to support load disti
|
||||
# over multi-use clusters; eg. some new feed request is
|
||||
# re-directed to another daemon cluster because the current one is
|
||||
# at max capacity.
|
||||
# - the same ideas ^ but when a local core is maxxed out (like how
|
||||
# binance does often with hft XD
|
||||
# - information about discovery of non-local host daemons which
|
||||
# can be contacted in the case where we want to support load
|
||||
# disti over multi-use clusters; eg. some new feed request is
|
||||
# re-directed to another daemon cluster because the current
|
||||
# one is at max capacity.
|
||||
# - the same ideas ^ but when a local core is maxxed out (like
|
||||
# how binance does often with hft XD
|
||||
# - if a datad is non-local then we can't just allocate a mem
|
||||
# channel here and have the datad write it, we instead need
|
||||
# a small streaming machine around the remote feed which can then
|
||||
# do the normal work of sampling and writing shm buffers
|
||||
# (depending on if we want sampling done on the far end or not?)
|
||||
# a small streaming machine around the remote feed which can
|
||||
# then do the normal work of sampling and writing shm buffers
|
||||
# (depending on if we want sampling done on the far end or
|
||||
# not?)
|
||||
init: FeedInit = validate_backend(
|
||||
mod,
|
||||
[symstr],
|
||||
init_msgs, # NOTE: only 1 should be delivered for now..
|
||||
)
|
||||
mkt: MktPair = init.mkt_info
|
||||
fqme: str = mkt.fqme
|
||||
startup_fqme: str = init.mkt_info.fqme
|
||||
if startup_fqme != fqme:
|
||||
raise ValueError(
|
||||
f'Quote startup endpoint {startup_fqme!r} differs from '
|
||||
f'resolved endpoint {fqme!r}'
|
||||
)
|
||||
|
||||
# HISTORY storage, run 2 tasks:
|
||||
# - a history loader / maintainer
|
||||
# - a real-time streamer which consumers and sends new data to any
|
||||
# consumers as well as writes to storage backends (as configured).
|
||||
|
||||
# XXX: neither of these will raise but will cause an inf hang due to:
|
||||
# Await the history startup handshake for its SHM handles.
|
||||
# `tn.start_soon()` would not return those handles or propagate
|
||||
# a startup failure directly to this awaiter.
|
||||
#
|
||||
# Historical service-nursery startup hang:
|
||||
# https://github.com/python-trio/trio/issues/2258
|
||||
# bus.nursery.start_soon(
|
||||
# await bus.start_task(
|
||||
# Starting into `bus.nursery` from outside its cancellation
|
||||
# scope can leave startup waiting for a sibling which failed.
|
||||
# Here we start into local `tn` from inside its scope, so its
|
||||
# cancellation reaches this pending startup too. Do not replace
|
||||
# this with `bus.start_task()` without revisiting that ownership.
|
||||
|
||||
izero_hist: int
|
||||
hist_shm: ShmArray
|
||||
izero_rt: int
|
||||
rt_shm: ShmArray
|
||||
(
|
||||
izero_hist,
|
||||
hist_shm,
|
||||
izero_rt,
|
||||
rt_shm,
|
||||
) = await bus.nursery.start(
|
||||
) = await tn.start(
|
||||
partial(
|
||||
manage_history,
|
||||
mod=mod,
|
||||
|
|
@ -360,8 +602,7 @@ async def allocate_persistent_feed(
|
|||
)
|
||||
)
|
||||
|
||||
# yield back control to starting nursery once we receive either
|
||||
# some history or a real-time quote.
|
||||
# Return allocation state once history has reported data ready.
|
||||
log.info(
|
||||
f'loading OHLCV history: {fqme!r}\n'
|
||||
)
|
||||
|
|
@ -372,8 +613,8 @@ async def allocate_persistent_feed(
|
|||
flume = Flume(
|
||||
|
||||
# TODO: we have to use this for now since currently the
|
||||
# MktPair above doesn't render the correct output key it seems
|
||||
# when we provide the `MktInfo` here?..?
|
||||
# MktPair above doesn't render the correct output key it
|
||||
# seems when we provide the `MktInfo` here?..?
|
||||
mkt=mkt,
|
||||
|
||||
first_quote=first_quote,
|
||||
|
|
@ -387,26 +628,6 @@ async def allocate_persistent_feed(
|
|||
_has_vlm=init.shm_write_opts['has_vlm'],
|
||||
)
|
||||
|
||||
# for ambiguous names we simply register the
|
||||
# flume for all possible name (sub) sets.
|
||||
# feed to that name (for now).
|
||||
bus.feeds.update({
|
||||
symstr: flume,
|
||||
fqme: flume,
|
||||
mkt.bs_fqme: flume,
|
||||
})
|
||||
|
||||
# signal the ``open_feed_bus()`` caller task to continue since
|
||||
# we now have (some) history pushed to the shm buffer.
|
||||
task_status.started(init)
|
||||
|
||||
if not start_stream:
|
||||
await trio.sleep_forever()
|
||||
|
||||
# begin real-time updates of shm and tsb once the feed goes live and
|
||||
# the backend will indicate when real-time quotes have begun.
|
||||
await feed_is_live.wait()
|
||||
|
||||
# NOTE: if not configured otherwise, we always sum tick volume
|
||||
# values in the OHLCV sampler.
|
||||
sum_tick_vlm: bool = True
|
||||
|
|
@ -416,72 +637,43 @@ async def allocate_persistent_feed(
|
|||
True,
|
||||
)
|
||||
|
||||
# NOTE: if no high-freq sampled data has (yet) been loaded,
|
||||
# seed the buffer with a history datum - this is most handy
|
||||
# for many backends which don't sample @ 1s OHLC but do have
|
||||
# slower data such as 1m OHLC.
|
||||
if (
|
||||
not len(rt_shm.array)
|
||||
and hist_shm.array.size
|
||||
):
|
||||
rt_shm.push(hist_shm.array[-3:-1])
|
||||
ohlckeys = ['open', 'high', 'low', 'close']
|
||||
rt_shm.array[ohlckeys][-2:] = hist_shm.array['close'][-1]
|
||||
rt_shm.array['volume'][-2:] = 0
|
||||
|
||||
# set fast buffer time step to 1s
|
||||
ts = round(time.time())
|
||||
rt_shm.array['time'][0] = ts
|
||||
rt_shm.array['time'][1] = ts + 1
|
||||
|
||||
elif hist_shm.array.size == 0:
|
||||
for i in range(100):
|
||||
await trio.sleep(0.1)
|
||||
if hist_shm.array.size > 0:
|
||||
break
|
||||
else:
|
||||
await tractor.pause()
|
||||
raise RuntimeError(f'History (1m) Shm for {fqme} is empty!?')
|
||||
|
||||
# wait the spawning parent task to register its subscriber
|
||||
# send-stream entry before we start the sample loop.
|
||||
await sub_registered.wait()
|
||||
|
||||
# start sample loop and shm incrementer task for OHLC style sampling
|
||||
# at the above registered step periods.
|
||||
try:
|
||||
log.info(f'Starting sampler task for {fqme}')
|
||||
await sample_and_broadcast(
|
||||
bus,
|
||||
return (
|
||||
flume,
|
||||
rt_shm,
|
||||
hist_shm,
|
||||
quote_stream,
|
||||
brokername,
|
||||
sum_tick_vlm
|
||||
feed_is_live,
|
||||
sum_tick_vlm,
|
||||
)
|
||||
finally:
|
||||
log.warning(f'{fqme} feed task terminated')
|
||||
|
||||
|
||||
@tractor.context
|
||||
async def open_feed_bus(
|
||||
ctx: tractor.Context,
|
||||
brokername: str,
|
||||
symbols: list[str], # normally expected to the broker-specific fqme
|
||||
symbols: list[str], # provider-native requests; see below
|
||||
|
||||
loglevel: str = 'error',
|
||||
tick_throttle: float | None = None,
|
||||
tick_throttle: float|None = None,
|
||||
start_stream: bool = True,
|
||||
allow_remote_ctl_ui: bool = False,
|
||||
|
||||
) -> dict[
|
||||
str, # fqme
|
||||
tuple[dict, dict] # pair of dicts of the initmsg and first quotes
|
||||
]:
|
||||
) -> None:
|
||||
'''
|
||||
Open a data feed "bus": an actor-persistent per-broker task-oriented
|
||||
data feed registry which allows managing real-time quote streams per
|
||||
symbol.
|
||||
Open client subscriptions to persistent market endpoint feeds.
|
||||
|
||||
``symbols`` normally contains provider-native names: for IB,
|
||||
``qqq.nasdaq`` or ``mnq.cme.20261218``. Their canonical piker
|
||||
FQMEs include the broker: ``qqq.nasdaq.ib`` and
|
||||
``mnq.cme.20261218.ib``. A continuous request such as ``mnq.cme``
|
||||
must also resolve its expiry before selecting a canonical feed.
|
||||
|
||||
- Look up explicit names in ``_FeedsBus.feeds``. For unresolved
|
||||
names, start the allocator and use its returned ``Flume``.
|
||||
- Serialize allocation with ``_FeedsBus.task_lock`` and register
|
||||
descriptors only under resolved, broker-qualified FQMEs.
|
||||
- On client closure, remove its ``_FeedsBus._subscribers`` entries
|
||||
while the feed writers remain in the service nursery.
|
||||
|
||||
'''
|
||||
if loglevel is None:
|
||||
|
|
@ -494,14 +686,14 @@ async def open_feed_bus(
|
|||
or
|
||||
tractor.current_actor().loglevel
|
||||
),
|
||||
name=__name__,
|
||||
name=log.logger.name,
|
||||
)
|
||||
|
||||
# local state sanity checks
|
||||
# TODO: check for any stale shm entries for this symbol
|
||||
# (after we also group them in a nice `/dev/shm/piker/` subdir).
|
||||
# ensure we are who we think we are
|
||||
servicename = tractor.current_actor().name
|
||||
servicename: str = tractor.current_actor().name
|
||||
assert 'datad' in servicename
|
||||
assert brokername in servicename
|
||||
|
||||
|
|
@ -509,44 +701,58 @@ async def open_feed_bus(
|
|||
sub_registered = trio.Event()
|
||||
|
||||
flumes: dict[str, Flume] = {}
|
||||
symbol: str
|
||||
for symbol in symbols:
|
||||
|
||||
# if no cached feed for this symbol has been created for this
|
||||
# datad yet, start persistent stream and shm writer task in
|
||||
# service nursery
|
||||
flume = bus.feeds.get(symbol)
|
||||
requested_fqme: str = symbol
|
||||
if not symbol.endswith(f'.{brokername}'):
|
||||
requested_fqme = f'{symbol}.{brokername}'
|
||||
|
||||
flume: Flume|None = bus.feeds.get(requested_fqme)
|
||||
if flume is None:
|
||||
# allocate a new actor-local stream bus which
|
||||
# will persist for this `datad`'s service lifetime.
|
||||
async with bus.task_lock:
|
||||
await bus.nursery.start(
|
||||
# Another subscriber may have registered this name
|
||||
# in `_FeedsBus.feeds` while we waited for the lock.
|
||||
# Re-read it to reuse that feed; allocate only if
|
||||
# the requested endpoint is still absent.
|
||||
flume = bus.feeds.get(requested_fqme)
|
||||
if flume is None:
|
||||
flume = await bus.nursery.start(
|
||||
partial(
|
||||
allocate_persistent_feed,
|
||||
maybe_allocate_persistent_feed,
|
||||
|
||||
bus=bus,
|
||||
sub_registered=sub_registered,
|
||||
brokername=brokername,
|
||||
# here we pass through the selected symbol in native
|
||||
# "format" (i.e. upper vs. lowercase depending on
|
||||
# provider).
|
||||
# here we pass through the selected
|
||||
# symbol in native "format" (i.e. upper
|
||||
# vs. lowercase depending on provider).
|
||||
symstr=symbol,
|
||||
loglevel=loglevel,
|
||||
start_stream=start_stream,
|
||||
)
|
||||
)
|
||||
# TODO: we can remove this?
|
||||
# assert isinstance(bus.feeds[symbol], tuple)
|
||||
|
||||
# XXX: ``.first_quote`` may be outdated here if this is secondary
|
||||
# subscriber
|
||||
flume: Flume = bus.feeds[symbol]
|
||||
# XXX: ``.first_quote`` may be outdated here if this is
|
||||
# secondary subscriber
|
||||
mkt: MktPair = flume.mkt
|
||||
bs_fqme: str = mkt.bs_fqme
|
||||
fqme: str = mkt.fqme
|
||||
assert brokername in fqme
|
||||
|
||||
if mkt.suffix:
|
||||
log.warning(f'{brokername} expanded symbol {symbol} -> {bs_fqme}')
|
||||
# TODO: we can remove this?
|
||||
# assert isinstance(bus.feeds[fqme], tuple)
|
||||
|
||||
if requested_fqme != fqme:
|
||||
log.warning(
|
||||
f'{brokername!r} expanded symbol '
|
||||
f'{symbol!r} -> {bs_fqme!r}'
|
||||
)
|
||||
|
||||
# pack for ``.started()`` sync msg
|
||||
flumes[fqme] = flume
|
||||
|
|
@ -568,6 +774,7 @@ async def open_feed_bus(
|
|||
await trio.sleep_forever()
|
||||
|
||||
# real-time stream loop
|
||||
stream: tractor.MsgStream
|
||||
async with (
|
||||
ctx.open_stream(
|
||||
# NOTE we allow this since it's common to have the live
|
||||
|
|
@ -577,11 +784,13 @@ async def open_feed_bus(
|
|||
) as stream,
|
||||
):
|
||||
|
||||
local_subs: dict[str, set[tuple]] = {}
|
||||
local_subs: dict[str, set[Sub]] = {}
|
||||
fqme: str
|
||||
flume: Flume
|
||||
for fqme, flume in flumes.items():
|
||||
# re-send to trigger display loop cycle (necessary especially
|
||||
# when the mkt is closed and no real-time messages are
|
||||
# expected).
|
||||
# re-send to trigger display loop cycle (necessary
|
||||
# especially when the mkt is closed and no real-time
|
||||
# messages are expected).
|
||||
await stream.send({fqme: flume.first_quote})
|
||||
|
||||
# set a common msg stream for all requested symbols
|
||||
|
|
@ -589,12 +798,12 @@ async def open_feed_bus(
|
|||
flume.stream = stream
|
||||
|
||||
# Add a real-time quote subscription to feed bus:
|
||||
# This ``sub`` subscriber entry is added to the feed bus set so
|
||||
# that the ``sample_and_broadcast()`` task (spawned inside
|
||||
# ``allocate_persistent_feed()``) will push real-time quote
|
||||
# (ticks) to this new consumer.
|
||||
cs: trio.CancelScope | None = None
|
||||
send: trio.MemorySendChannel | None = None
|
||||
# This ``sub`` subscriber entry is added to the feed
|
||||
# bus set so that the ``sample_and_broadcast()`` task
|
||||
# (spawned inside ``allocate_persistent_feed()``) will
|
||||
# push real-time quote (ticks) to this new consumer.
|
||||
cs: trio.CancelScope|None = None
|
||||
tx: trio.MemorySendChannel|None = None
|
||||
if tick_throttle:
|
||||
flume.throttle_rate = tick_throttle
|
||||
|
||||
|
|
@ -602,10 +811,11 @@ async def open_feed_bus(
|
|||
# chan and only pushes them to the target
|
||||
# actor-consumer at a max ``tick_throttle``
|
||||
# (instantaneous) rate.
|
||||
send, recv = trio.open_memory_channel(2**10)
|
||||
rx: trio.MemoryReceiveChannel
|
||||
tx, rx = trio.open_memory_channel(2**10)
|
||||
|
||||
# NOTE: the ``.send`` channel here is a swapped-in
|
||||
# trio mem chan which gets `.send()`-ed by the normal
|
||||
# NOTE: ``tx`` is a swapped-in ``trio`` memory
|
||||
# channel which gets ``.send()``-ed by the normal
|
||||
# sampler task but instead of being sent directly
|
||||
# over the IPC msg stream it's the throttle task
|
||||
# does the work of incrementally forwarding to the
|
||||
|
|
@ -613,21 +823,21 @@ async def open_feed_bus(
|
|||
cs: trio.CancelScope = await bus.start_task(
|
||||
uniform_rate_send,
|
||||
tick_throttle,
|
||||
recv,
|
||||
rx,
|
||||
stream,
|
||||
)
|
||||
|
||||
sub = Sub(
|
||||
sub: Sub = Sub(
|
||||
ipc=stream,
|
||||
send_chan=send,
|
||||
send_chan=tx,
|
||||
throttle_rate=tick_throttle,
|
||||
_throttle_cs=cs,
|
||||
rc_ui=allow_remote_ctl_ui,
|
||||
)
|
||||
|
||||
# TODO: add an api for this on the bus?
|
||||
# maybe use the current task-id to key the sub list that's
|
||||
# added / removed? Or maybe we can add a general
|
||||
# maybe use the current task-id to key the sub list
|
||||
# that's added / removed? Or maybe we can add a general
|
||||
# pause-resume by sub-key api?
|
||||
bs_fqme = fqme.removesuffix(f'.{brokername}')
|
||||
local_subs.setdefault(
|
||||
|
|
@ -665,7 +875,8 @@ async def open_feed_bus(
|
|||
raise ValueError(msg)
|
||||
finally:
|
||||
log.info(
|
||||
f'Stopping {symbol}.{brokername} feed for {ctx.chan.uid}')
|
||||
f'Stopping {requested_fqme!r} feed for {uid!r}'
|
||||
)
|
||||
|
||||
if tick_throttle:
|
||||
# TODO: a one-cancels-one nursery
|
||||
|
|
|
|||
Loading…
Reference in New Issue