From d04d8d4f694d7fa13bc3b0f50a627346fb6cc8c4 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 25 Sep 2026 14:34:20 +0100 Subject: [PATCH 01/42] Add di.torq.proc.discovery: one-to-one port of TorQ's discovery service di.torq.proc.discovery 0.1.0 repackages TorQ code/processes/discovery.q line for line (register, getservices, subs, the startup addw pass and autodiscovery push, .z.pc prune), publishing register/getservices at their legacy root names. di.torq.servers 0.3.0 -> 0.4.0 ports the client half of the protocol from code/handlers/trackservers.q at its legacy root names (.servers.*, .dotz.liveh*): addw, removerows, cleanup, retrydiscovery, autodiscovery, querydiscovery, registerfromdiscovery, addprocs, procupdate, startup and friends, with SERVERS (now carrying attributes) and the trackservers settings as root .servers.* globals. Exported API unchanged. servers.md lists each ported line, the conversions, what was not ported, and the behaviour changes. di.torq: discovery registered as a built-in; legacy STARTUP ported (torq.q l.673) so the hdb registers with discovery as legacy's does; settings/default.q carries legacy default.q's .servers values, settings/discovery.q legacy's discovery settings, settings/hdb.q startup:1b. Note: legacy defaults route every process's connections through discovery - a stack with no discovery process no longer dials process.csv peers directly. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/discovery/VERSION | 1 + di/torq/proc/discovery/deps.toml | 3 + di/torq/proc/discovery/discovery.md | 92 ++++++++ di/torq/proc/discovery/discovery.q | 37 ++++ di/torq/proc/discovery/init.q | 5 + di/torq/proc/discovery/test.csv | 48 +++++ di/torq/proc/discovery/test.q | 67 ++++++ di/torq/servers/VERSION | 2 +- di/torq/servers/servers.md | 196 +++++++++++------ di/torq/servers/servers.q | 322 +++++++++++++++++++--------- di/torq/servers/test.csv | 11 +- di/torq/servers/test.q | 3 +- di/torq/settings/default.q | 25 ++- di/torq/settings/discovery.q | 21 ++ di/torq/settings/hdb.q | 2 + di/torq/torq.q | 4 +- 16 files changed, 660 insertions(+), 179 deletions(-) create mode 100644 di/torq/proc/discovery/VERSION create mode 100644 di/torq/proc/discovery/deps.toml create mode 100644 di/torq/proc/discovery/discovery.md create mode 100644 di/torq/proc/discovery/discovery.q create mode 100644 di/torq/proc/discovery/init.q create mode 100644 di/torq/proc/discovery/test.csv create mode 100644 di/torq/proc/discovery/test.q create mode 100644 di/torq/settings/discovery.q diff --git a/di/torq/proc/discovery/VERSION b/di/torq/proc/discovery/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/torq/proc/discovery/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/torq/proc/discovery/deps.toml b/di/torq/proc/discovery/deps.toml new file mode 100644 index 00000000..b43234ae --- /dev/null +++ b/di/torq/proc/discovery/deps.toml @@ -0,0 +1,3 @@ +# Peer modules di.torq.proc.discovery `use`s (see di/torq/depcheck/depcheck.md for the manifest-graph mechanism). +[dependencies] +"di.torq.servers" = "0.4.0" # requires the legacy .servers.* root names (addw, removerows, cleanup, procupdate, autodiscovery) diff --git a/di/torq/proc/discovery/discovery.md b/di/torq/proc/discovery/discovery.md new file mode 100644 index 00000000..35cca8bc --- /dev/null +++ b/di/torq/proc/discovery/discovery.md @@ -0,0 +1,92 @@ +# di.torq.proc.discovery + +TorQ's discovery service (`code/processes/discovery.q`) repackaged as a kdb-x module: a +one-to-one port, nothing added, nothing dropped. The process dials every process in +`process.csv` once at start up, records the processes that register with it, answers +`getservices` queries, and pushes each new registration to the processes subscribed to its +proctype. + +Discovery is the server half of a protocol whose client half lives in `trackservers.q`. That +half is `di.torq.servers` (0.4.0+), ported at the same legacy root names — see +[servers.md](../../servers/servers.md#discovery-protocol-ported-from-trackserversq). + +## Line map + +| discovery.q | here | +|---|---| +| l.8 `.servers.startup[]` | `init`: `.servers.startup config` | +| l.11 `subs` | `subs` (module state) | +| l.13–23 `register` | `register`, published at root `register` (peers call `` `..register ``) | +| l.27–30 `getservices` | `getservices`, published at root `getservices` | +| l.33 `addw` each live handle | `init` | +| l.37 `.servers.autodiscovery` push | `init` | +| l.40 `.z.pc` drops from `subs` | `init`, via `handlers[`register]` | + +**Conversions:** +- `.lg.e` becomes the injected `log[`error]`. +- `.dotz.set[`.z.pc;...]` becomes an observer registered with the injected `handlers`. +- The module is `use`-loaded, so `register`/`getservices` are published at root with `set`. +- `subs` lives in module state (`.z.m.subs`). + +## How the protocol runs + +1. Discovery starts, runs `.servers.startup` with `connections:`ALL`, and dials every non-discovery + row of `process.csv`. +2. It calls `addw` on each live handle, which fetches `.servers.getdetails[]` (name, type, + attributes). Then it sends `.servers.autodiscovery` to each peer. +3. A peer with `discoveryretry>0` runs `retrydiscovery`: + - it connects to discovery; + - it sends `` `..register `` if `discoveryregister`; + - if `connectionsfromdiscovery`, it calls `getservices[connections;subscribetodiscovery]` + synchronously and adds the rows returned, without connecting to them. `retry` dials them later. +4. `register` records the caller, removes any other row on the same host:port, and pushes the + caller's row as `.servers.procupdate` to each handle subscribed to its proctype or `` `ALL ``. +5. When a subscriber disconnects, `.z.pc` removes it from `subs`. + +Behaviours of legacy worth knowing (kept as is): +- The pushed row is added by the subscriber's `addprocs` without connecting. `retry` dials it later. +- A re-push of a row the subscriber already has changes nothing: the attribute `lj` is filtered + by the same "not already known" condition. +- A restarted discovery only dials `process.csv`. A peer outside it comes back through its own + `discoveryretry` timer. + +## Dependencies + +`deps.toml` pins `di.torq.servers` 0.4.0 (the legacy `.servers.*` root names). `init` requires +the injected `log` and `handlers`. + +## Config + +`di/torq/settings/discovery.q` is legacy `config/settings/discovery.q`: +- `connections:`ALL`; +- `discoveryregister` / `connectionsfromdiscovery` 0b; +- `tracknontorqprocess` 1b; +- `discoveryretry:0D`; +- `hopentimeout:200`; +- `retry:0D00`; +- `retain` `0W`; +- `autoclean:0b`; +- `debug:1b`. + +## Usage + +Proctype `discovery` is a di.torq built-in: + +``` +torqx -proctype discovery -procname discovery1 +``` + +## Testing + +`test.q` + `test.csv` (30 checks) stub the `.servers.*` names discovery calls and spawn two real +q peers, so `.z.w`/`.z.W` run over genuine handles. They cover: +- init validation; +- each legacy line in `init`; +- `getservices` filtering and `cleanup`; +- subscribe, register with duplicate removal, and the `procupdate` push; +- the `.z.pc` prune. + +```q +k4unit:use`di.k4unit +k4unit.moduletest`di.torq.proc.discovery +``` diff --git a/di/torq/proc/discovery/discovery.q b/di/torq/proc/discovery/discovery.q new file mode 100644 index 00000000..c68f8dd3 --- /dev/null +++ b/di/torq/proc/discovery/discovery.q @@ -0,0 +1,37 @@ +/ di.torq.proc.discovery - TorQ's discovery service (code/processes/discovery.q) as a kdb-x module + +/ subscriptions - handles to list of required proc types +subs:(`int$())!() + +register:{ + / add the new handle + .servers.addw .z.w; + / If there already was an entry for the same host:port as the supplied handle, close it and delete the entry + if[count toclose:exec i from .servers.SERVERS where not w=.z.w,hpup in exec hpup from .servers.SERVERS where w=.z.w; + .servers.removerows toclose]; + / publish the updates + new:select proctype,procname,hpup,attributes from .servers.SERVERS where w=.z.w; + (neg ((where ((first new`proctype) in/: .z.m.subs) or .z.m.subs~\:enlist`ALL) inter key .z.W) except .z.w)@\:(`.servers.procupdate;new); + } + +/ get a list of services +getservices:{[proctypes;subscribe] + .servers.cleanup[]; + if[subscribe;.z.m.subs[.z.w]:proctypes,()]; + distinct select procname,proctype,hpup,attributes from .servers.SERVERS where proctype in ?[(proctypes~`ALL) or proctypes~enlist`ALL;proctype;proctypes],not proctype=`discovery} + +init:{[config;deps] + if[not `log in key deps;'"di.torq.proc.discovery: log dependency is required - see di.util.log"]; + if[not `handlers in key deps;'"di.torq.proc.discovery: handlers dependency is required - see di.torq.handlers"]; + .z.m.log:deps`log; + / initialise connections + .servers.startup config; + set[`register;register]; + set[`getservices;getservices]; + / add each handle + @[.servers.addw;;{.z.m.log[`error][`discovery;x]}] each exec w from .servers.SERVERS where .dotz.liveh w,not hpup in exec hpup from .servers.nontorqprocesstab; + / try to make each server connect back in + (neg exec w from .servers.SERVERS where .dotz.liveh w,not hpup in exec hpup from .servers.nontorqprocesstab)@\:(`.servers.autodiscovery;`); + / drop items out of the subscription dictionary on close + (deps[`handlers]`register)[`.z.pc;`;`discovery;0j;{[W] .z.m.subs:(enlist W) _ .z.m.subs}]; + } diff --git a/di/torq/proc/discovery/init.q b/di/torq/proc/discovery/init.q new file mode 100644 index 00000000..4b193be6 --- /dev/null +++ b/di/torq/proc/discovery/init.q @@ -0,0 +1,5 @@ +\l ::discovery.q + +version:first read0`:::VERSION + +export:([init;version]) diff --git a/di/torq/proc/discovery/test.csv b/di/torq/proc/discovery/test.csv new file mode 100644 index 00000000..496f899d --- /dev/null +++ b/di/torq/proc/discovery/test.csv @@ -0,0 +1,48 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,disc:use`di.torq.proc.discovery,1,,load module +before,0,0,q,system "l di/torq/proc/discovery/test.q",1,,load mocks and peer fixture helpers +before,0,0,q,setupfixture[],1,,write the peer script and pick two free ports +before,0,0,q,spawnpeers[],1,,launch peers A and B and open a handle to each +before,0,0,q,stubservers[],1,,stub the .servers.* root names discovery calls + +comment,,,,,,,init - dependency validation +fail,0,0,q,"disc[`init][()!();enlist[`handlers]!enlist mockhandlers]",1,,init without a log dependency must error +fail,0,0,q,"disc[`init][()!();enlist[`log]!enlist mocklog]",1,,init without a handlers dependency must error + +comment,,,,,,,init - discovery.q l.8-40 +run,0,0,q,initrows[],1,,peer A (alpha) and peer B (beta) live; B listed as non-torq +run,0,0,q,"disc[`init][`connections`processcsv!(`ALL;""/x/process.csv"");`log`handlers!(mocklog;mockhandlers)]",1,,init +true,0,0,q,"(enlist `connections`processcsv!(`ALL;""/x/process.csv""))~argsof`startup",1,,l.8 startup called once with the config +true,0,0,q,all `register`getservices in key `.,1,,register and getservices published at root (legacy names) +true,0,0,q,(enlist hA)~argsof`addw,1,,l.33 addw on each live handle - the non-torq one skipped +true,0,0,q,(enlist`autodiscovery)~hA"got",1,,l.37 peer A told to run .servers.autodiscovery +true,0,0,q,()~hB"got",1,,l.37 the non-torq peer B not told +true,0,0,q,1=count select from handlercalls where event=`.z.pc,name=`discovery,1,,l.40 .z.pc observer registered via handlers + +comment,,,,,,,getservices - l.27-30 +run,0,0,q,servicerows[],1,,alpha + beta + discovery's own row +run,0,0,q,delete from `calls,1,,reset call log +true,0,0,q,`alpha`beta~asc exec proctype from getservices[`ALL;0b],1,,ALL returns every proctype except discovery +true,0,0,q,`alpha`beta~asc exec proctype from getservices[enlist`ALL;0b],1,,enlist`ALL behaves the same +true,0,0,q,(enlist`beta)~exec proctype from getservices[`beta;0b],1,,a proctype list filters +true,0,0,q,0=count getservices[`discovery;0b],1,,discovery rows are never returned +true,0,0,q,`procname`proctype`hpup`attributes~cols getservices[`ALL;0b],1,,returns procname/proctype/hpup/attributes +true,0,0,q,5=count argsof`cleanup,1,,each call runs .servers.cleanup first + +comment,,,,,,,register - l.13-23 (peer A subscribes to beta; peer B registers) +run,0,0,q,registerrows[],1,,servicerows plus a stale row sharing B's host:port +run,0,0,q,delete from `calls,1,,reset call log +true,0,0,q,"(enlist`beta)~exec proctype from hA""(.z.w)(`getservices;`beta;1b)""",1,,peer A subscribes to beta over its handle +run,0,0,q,"hB""(.z.w)(`register;`)""",1,,peer B registers over its handle +true,0,0,q,(enlist hB)~argsof`addw,1,,addw called with the registering handle +true,0,0,q,(enlist enlist 3)~argsof`removerows,1,,the stale row on B's host:port removed +true,0,0,q,"(enlist`beta1)~exec procname from last hA""got""",1,,procupdate pushed B's row to subscriber A +true,0,0,q,`proctype`procname`hpup`attributes~cols last hA"got",1,,pushed row carries proctype/procname/hpup/attributes +true,0,0,q,()~hB"got",1,,the registering handle is not pushed to + +comment,,,,,,,.z.pc - l.40 drops the closed handle's subscription +run,0,0,q,pcfunc[][hA],1,,fire the .z.pc observer for peer A's handle +run,0,0,q,"hB""(.z.w)(`register;`)""",1,,peer B registers again +true,0,0,q,2=count hA"got",1,,A is no longer subscribed - nothing new pushed + +after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/discovery/test.q b/di/torq/proc/discovery/test.q new file mode 100644 index 00000000..024f1fb8 --- /dev/null +++ b/di/torq/proc/discovery/test.q @@ -0,0 +1,67 @@ +/ di.torq.proc.discovery test helpers (loaded by test.csv): mock log/handlers, stubbed .servers.* +/ root names that record their calls, and two real q peers so the .z.w/.z.W paths run over +/ genuine handles (a peer calls back into this process over the handle it was asked on). + +logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()); +mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}); + +handlercalls:([]event:`symbol$();name:`symbol$();func:()); +mockhandlers:enlist[`register]!enlist {[ev;ph;nm;pri;fn]`handlercalls upsert(ev;nm;fn)}; +pcfunc:{[] last exec func from handlercalls where event=`.z.pc,name=`discovery}; + +calls:([]fn:`symbol$();arg:()); +rec:{[f;a]`calls upsert(f;a);}; +argsof:{[f] exec arg from calls where fn=f}; + +/ the .servers.* names discovery.q calls, recording instead of connecting +stubservers:{[] + .servers.SERVERS::([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();attributes:()); + .servers.nontorqprocesstab::([]hpup:`symbol$()); + .servers.startup::{rec[`startup;x]}; + .servers.cleanup::{rec[`cleanup;::]}; + .servers.addw::{rec[`addw;x];x}; + .servers.removerows::{rec[`removerows;x]; delete from `.servers.SERVERS where i in x}; + .dotz.liveh::{x in key .z.W}; + }; + +row:{[pn;pt;hp;wh] ([]procname:enlist pn;proctype:enlist pt;hpup:enlist hp;w:enlist wh;attributes:enlist ()!())}; + +/ peer A (alpha) and peer B (beta) live; B's hpup listed as a non-torq process +initrows:{[] + .servers.SERVERS::row[`alpha1;`alpha;`:a:1;hA],row[`beta1;`beta;`:b:2;hB]; + .servers.nontorqprocesstab::([]hpup:enlist`:b:2); + }; + +/ alpha/beta plus discovery's own row, no non-torq rows +servicerows:{[] + .servers.SERVERS::row[`alpha1;`alpha;`:a:1;hA],row[`beta1;`beta;`:b:2;hB],row[`discovery1;`discovery;`:d:3;0Ni]; + .servers.nontorqprocesstab::([]hpup:`symbol$()); + }; + +/ a stale row sharing peer B's host:port on another handle - register must remove it +registerrows:{[] servicerows[]; .servers.SERVERS::.servers.SERVERS,row[`beta1;`beta;`:b:2;0Ni];}; + +/ --- real peer fixture --- +FIXDIR:"/tmp/didiscoverytest"; +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe"; +isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; +pickport:{[start] first (start+til 500) where isfree each start+til 500}; +waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.p/dev/null 2>&1 &"} each PORTA,PORTB; + if[not all waitlisten each PORTA,PORTB;'"test: peers failed to listen"]; + hA::hopen (`$":localhost:",string PORTA;2000); + hB::hopen (`$":localhost:",string PORTB;2000); + }; + +teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each hA,hB; system "sleep 0.3"; system "rm -rf ",FIXDIR;}; diff --git a/di/torq/servers/VERSION b/di/torq/servers/VERSION index 9325c3cc..1d0ba9ea 100644 --- a/di/torq/servers/VERSION +++ b/di/torq/servers/VERSION @@ -1 +1 @@ -0.3.0 \ No newline at end of file +0.4.0 diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 3cbc748c..d8dd9492 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -1,10 +1,11 @@ # di.torq.servers Connection management and handle-by-type lookup for the modular TorQ world — the `di.*` -analogue of TorQ's `.servers` (`code/handlers/trackservers.q` + `servers.q`), scoped down -for v1: no discovery service, no password/access-list files, no non-TorQ process tracking, -no FinSpace. `process.csv` here is a static **phone book** (who to *dial*), **not** an -identity source — self-identity comes from config, injected by `di.torq`. +analogue of TorQ's `.servers` (`code/handlers/trackservers.q` + `servers.q`). The parts of +`trackservers.q` the discovery protocol uses are **ported line for line** and published at +their **legacy root names** (`.servers.*`, `.dotz.liveh*`), with the registry and config at +legacy's root `.servers.*` globals — see [Discovery protocol](#discovery-protocol-ported-from-trackserversq). +No password/access-list files, no FinSpace. FRAMEWORK-tier module: no hard `di.*` dependencies; `log`, `timer` and `handlers` are all **injected** (all required, no fallback). @@ -13,11 +14,12 @@ FRAMEWORK-tier module: no hard `di.*` dependencies; `log`, `timer` and `handlers Standard **one-arg `init[deps]`**: `di.torq` merges this process's resolved config slice into the same `deps` dict it passes the injectables in, so `deps` carries both the injectable -dependencies **and** the config keys. `init` wires the deps, records self-identity, and -installs two one-time process-global side effects — a `.z.pc` cleanup handler and a 10s retry -timer job. It is **idempotent** (guarded by an internal `registered` flag): `di.torq` calls -it once per process, but a second call refreshes the dep refs without re-registering (a -duplicate `di.timer.addjob` id would throw). `init` does **not** open connections. +dependencies **and** the config keys. `init` wires the deps, records self-identity, sets the +`.servers.*` config globals, publishes the legacy root names, and installs the one-time +process-global side effects — a `.z.pc` handler and trackservers.q's `discoveryretry` and +`serversretry` timer jobs. It is **idempotent** (guarded by an internal `registered` flag): a +second call refreshes deps, config and root names without re-registering (a duplicate +`di.timer.addjob` id would throw). `init` does **not** open connections. `deps` keys: @@ -26,14 +28,35 @@ duplicate `di.timer.addjob` id would throw). `init` does **not** open connection | `log` | injectable | binary `` `info`warn`error `` `{[c;m]}` logger dict | | `timer` | injectable | di.timer contract; `addjob` = the 6-arg `custom` form `{[id;func;params;period;mode;opts]}` | | `handlers` | injectable | di.torq.handlers contract; `register[event;phase;nm;pri;func]` | -| `proctype`/`procname` | config | this process's own identity (required); used to exclude self from `process.csv` | -| `connections` | config | proctypes this process should dial (symbols, or strings from a `.toml` cascade — normalised). Optional; default = none | -| `processcsv` | config | **path** to `process.csv`; supplied by di.torq. Optional; required only once `connections` is non-empty | +| `proctype`/`procname` | config | this process's own identity (required); returned by `.servers.getdetails` | +| `processcsv` | config | **path** to `process.csv`; supplied by di.torq (legacy `.proc.file`) | +| `nontorqprocessfile` | config | path to the non-TorQ process file (legacy `NONTORQPROCESSFILE`); default `nontorqprocess.csv` in `processcsv`'s directory | + +The trackservers.q settings (l.13–28) are flat config keys, each setting its legacy global. The +default is trackservers.q's own. `di/torq/settings/default.q` carries legacy +`config/settings/default.q`'s values, and `di/torq/settings/discovery.q` carries legacy +`config/settings/discovery.q`'s. + +| key | global | trackservers.q default | +|---|---|---| +| `connections` | `.servers.CONNECTIONS` | `` ` `` | +| `discoveryregister` | `.servers.DISCOVERYREGISTER` | `1b` | +| `connectionsfromdiscovery` | `.servers.CONNECTIONSFROMDISCOVERY` | `1b` | +| `subscribetodiscovery` | `.servers.SUBSCRIBETODISCOVERY` | `1b` | +| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05` | +| `tracknontorqprocess` | `.servers.TRACKNONTORQPROCESS` | `0b` | +| `hopentimeout` | `.servers.HOPENTIMEOUT` | `2000` | +| `retry` | `.servers.RETRY` | `0D00:05` | +| `retain` | `.servers.RETAIN` | `` `long$0D00:30 `` | +| `autoclean` | `.servers.AUTOCLEAN` | `0b` | +| `debug` | `.servers.DEBUG` | `1b` | +| `startup` | `.servers.STARTUP` | `0b` — when set, di.torq runs `.servers.startup` after the process module loads (legacy torq.q l.673); `di/torq/settings/hdb.q` sets it, as legacy's hdb.q does | +| `discovery` | `.servers.DISCOVERY` | `` enlist` `` | ```q svc:use`di.torq.servers -svc.init[deps] / deps = injectables + config, assembled by di.torq -svc.startup[] / open the configured connections (reads init config) +svc.init[deps] / deps = injectables + config, assembled by di.torq +svc.startup[config] / config`connections / config`processcsv as legacy CONNECTIONS / .proc.file h:svc.gethandlebytype[`hdb;`any] h "1+1" ``` @@ -42,87 +65,120 @@ h "1+1" | Function | Signature | Description | |---|---|---| -| `init` | `init[deps]` | Wire deps + config, record identity, install the `.z.pc` handler + retry job. Idempotent. | -| `startup` | `startup[]` | Read `process.csv` (`processcsv`), drop self, connect to each row whose proctype is in `connections`. A failed connection is logged (not raised) and left as `w:0Ni` for `retry`. No-op if no connections configured. | +| `init` | `init[deps]` | Wire deps + config, record identity, publish root names, install the `.z.pc` handler + timer jobs. Idempotent. | +| `startup` | `startup[config]` | Legacy `startup` (l.323–345). `config`connections`/`config`processcsv` stand in for `.servers.CONNECTIONS`/`.proc.file`. | | `getservers` | `getservers[proctype]` | Live (`w` non-null) `SERVERS` rows for a proctype. | | `gethandlebytype` | `gethandlebytype[proctype;selection]` | One live handle via `` `any``/`roundrobin`/`last``; `0Ni` if none. Bumps usage stats. | | `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Block until a live connection exists or timeout; `1b`/`0b`. Caller decides if a timeout is fatal. `startup` must have run first. | | `getapimeta` | `getapimeta[]` | This module's api metadata, one row per **callable** API function (`init`/`getapimeta` plumbing omitted), for `di.torq` to register with `di.api`. | -Export is deliberately conservative — only functions `di.torq` or a consumer actually calls -(so `di.api` lists exactly these). The rest are **internal**: `retry` (the scheduled -`serversretry` job — passed to the timer *by value* at init, so it needs no export; it first -runs `cleanup` to sweep ungracefully-vanished handles, then reopens every dead handle), -`cleanup`, `formathp`, `opencon`, `readprocesscsv`, `retryrows`, `selector`, `updatestats`, -`signalfound`, `raiseerror`; plus state (`SERVERS`, `self`, `registered`, `HOPENTIMEOUT`, -`connections`, `processcsv`). - ## The `SERVERS` table +Legacy's `.servers.SERVERS` (l.10), at that root name: + ```q -SERVERS:([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$()) +.servers.SERVERS:([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:()) ``` -A direct analogue of legacy TorQ's `.servers.SERVERS`: `w` is the live handle (`0Ni` when -disconnected), `hits`/`lastp` drive handle selection, `startp`/`endp` track lifecycle. +`w` is the live handle (`0Ni` when disconnected), `hits`/`lastp` drive handle selection, +`startp`/`endp` track lifecycle, `attributes` is the process's `.proc.getattributes[]` dict. +`.servers.procstab` and `.servers.nontorqprocesstab` (l.325–326) are set by `startup`. + +## Discovery protocol (ported from trackservers.q) + +Published at root by `init`, same bodies as legacy: + +| Name | trackservers.q | +|---|---| +| `.dotz.liveh` / `.dotz.livehn` / `.dotz.liveh0` | dotz.q l.8 | +| `.servers.opencon` | l.50–59 (DEBUG logging; no passwords) | +| `.servers.cleanup` | l.116–118 | +| `.servers.addnthawc` | l.121–128 | +| `.servers.getdetails` | l.137 | +| `.servers.addhw` / `.servers.addw` | l.139–150 | +| `.servers.retry` | l.157 | +| `.servers.retrydiscovery` | l.158–168 | +| `.servers.autodiscovery` | l.171 | +| `.servers.retryrows` | l.174–185 | +| `.servers.removerows` | l.201–204 | +| `.servers.register` | l.207–211 | +| `.servers.querydiscovery` | l.215–221 | +| `.servers.registerfromdiscovery` | l.225–231 | +| `.servers.addprocs` | l.233–244 | +| `.servers.procupdate` | l.251 | +| `.servers.domainsocketsenabled` | l.261–267 | +| `.servers.formathp` | l.271–307 | +| `.servers.formatprocs` | l.310–314 | +| `.servers.startup` | l.323–345 | +| `.servers.pc` | l.383, run on `.z.pc` | +| timers `discoveryretry` / `serversretry` | l.387–389 | + +The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, +`startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to +peers. Peers call discovery's root `register` (as `` `..register ``) and `getservices`. + +**Conversions** (legacy calls with no di equivalent): +- `.lg.*` becomes the injected `log`. +- `.dotz.set` on `.z.pc` becomes `handlers[`register]`. +- `.timer.repeat` becomes `timer[`addjob]`, using mode 2 (legacy's default schedule) and the period in seconds. +- `.proc.cp[]` becomes `.z.p`. +- `.proc.procname`/`proctype` in `getdetails` become init's identity. +- `.proc.readprocs` becomes `readprocesscsv`. +- `.proc.getconfigfile` becomes `nontorqprocessfile`. +- In `querydiscovery`, the 5-arg `getservers[`proctype;`discovery;()!();0b;0b]` becomes its result: + live discovery rows. + +**Not ported** (discovery does not reach them): +- passwords (`loadpassword`, `USERPASS`, `PASSWORDS`, `LOADPASSWORD`); +- `SOCKETTYPE`/FinSpace (so `formathp`'s ipctype is always `` `tcp `` from `formatprocs`/`addhw`, + and `retryrows` dials `hpup`); +- the 5-arg `getservers`/`attributematch`/`getserverbytype`/`gethpbytype`; +- `names`/`types`/`unregistered`/`checkw`/`reset`; +- the `connectcustom`/`addprocscustom` hooks; +- `refreshattributes`; +- `startupdep*`; +- `enabled`. + +**Legacy behaviour that differs from di.torq.servers 0.3.0:** +- `startup` no longer excludes this process's own row. +- `retry` skips discovery rows and no longer sweeps first (`cleanup` runs from `.z.pc` and + `addnthawc`). +- The retry job runs every `RETRY` (5m), not 10s. +- `localhost` hpups resolve to `.z.h`. +- Legacy defaults route connections through a discovery process: with + `connectionsfromdiscovery` on, `startup` dials only discovery rows and learns the rest from it. ## `.z.pc` registration via di.torq.handlers `.z.pc` (connection closed) is a **simple/observer** event in di.torq.handlers — side-effect only, -fan-out — so di.torq.servers registers its cleanup callback through the injected `handlers` -dependency rather than assigning `.z.pc` directly: +fan-out — so di.torq.servers registers `pc` through the injected `handlers` dependency rather +than assigning `.z.pc` directly: ```q -(handlers[`register])[`.z.pc;`;`servers;0j;pcfunc] +(handlers[`register])[`.z.pc;`;`servers;0j;pc] ``` `register`'s signature is `register[event;phase;nm;pri;func]`; for a simple event the `phase` -must be `` ` `` (null) — di.torq.handlers rejects a non-null phase on an observer event. This lets -di.torq.servers' disconnect hook coexist with every other `.z.pc` registrant in the same -priority-ordered fan-out. +must be `` ` `` (null) — di.torq.handlers rejects a non-null phase on an observer event. ## Conventions (learnings from di.torq.config) -- **One-arg `init[deps]`** with config folded into `deps` (the project convention; matches - `di.eodtime`'s optional-config-in-deps pattern), not a two-arg `init[config;deps]`. -- **Three-flat-var logging** — `.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`, matching - `consistency.md`, `di.compression` and `di.torq.config`. (The project hasn't globally frozen this - vs. the single-dict form — flag before changing.) -- **`raiseerror` (log-then-signal)** for all post-init domain errors (`formathp` unknown - ipctype, `selector` unknown selection, missing `process.csv`). `init`'s own dependency - validation is the one exception (plain `'` — no logger yet). -- **`getapimeta`** exported; a test asserts it documents exactly the module's *callable* - exports — `init`/`getapimeta` are plumbing (di.torq calls them by convention) and are - deliberately omitted from the registry rows, matching di.util.toml and the skill convention. No - `version` export / VERSION file yet — deferred to the di.torq.depcheck rollout, as in di.torq.config. -- **Env-free** — di.torq.servers reads no environment variable; the `process.csv` path arrives via - `config`processcsv` (di.torq resolves it), holding di.torq.config's env-free boundary. - -## Open items / not yet done - -- **Live-peer integration tests are in place** (`test.q` + `test.csv`, 33 checks). They spawn a - genuinely separate `q` peer (a self-connect returns pseudo-handle `0`, not a real socket) and - cover: `startup` connecting to a live peer and logging a failed dial while excluding self, - `gethandlebytype` returning a live remote handle (`2=h"1+1"`), the retry cycle recovering an - ungraceful kill (`cleanup`+reopen), and `waitfortype` connected-vs-timeout — plus the mockable - surface (init validation, dep-wiring, idempotency, input validation, `getapimeta`). Because - `retry`/`cleanup` are internal, the retry cycle is driven by invoking the callback the **mock - timer captured** at `addjob` (the actually-wired path), not a direct export. -- **Injected providers are mocked in tests by design.** `di.util.log` and `di.torq.handlers` are - both present on this branch now (log = the real structured logger from `main` PR #90), but the - unit tests still mock them so a failure localises to `di.torq.servers` rather than a provider. - The handlers mock uses the real `register[event;phase;nm;pri;func]` shape from `handlers.q`; the - real wiring is exercised end-to-end by di.torq's own suite. -- **`config`processcsv` and the assembled `connections` list** depend on di.torq's config - wiring — coordinate when di.torq's servers dep is built. -- Scoped-out (v1): discovery service, password/access-list files, non-TorQ tracking, and the - `tcps`/`unix` socket types end-to-end (only `tcp` is wired through `startup`). +- **One-arg `init[deps]`** with config folded into `deps`, not a two-arg `init[config;deps]`. +- **Three-flat-var logging** — `.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`. +- **`raiseerror` (log-then-signal)** for di's own post-init domain errors (`selector` unknown + selection, missing `process.csv`). `init`'s dependency validation signals plainly (no logger yet). +- **`getapimeta`** exported; a test asserts it documents exactly the module's *callable* exports. +- **Env-free** — the `process.csv` path arrives via `config`processcsv` (di.torq resolves it). ## Tests -Run in a fresh q session (spawns and kills a real peer process; don't interleave with other -modules' tests). Needs `QHOME` set (the peer is launched via `$QHOME/bin/q`) and `di.os` on -`QPATH` (the harness uses `os.abspath` to load `test.q`): +`test.q` + `test.csv` (36 checks) spawn a genuinely separate `q` peer and cover init validation, +wiring and idempotency, `startup` against a live and a dead peer (discovery switched off in the +fixture), `gethandlebytype`, retry recovering an ungraceful kill, `waitfortype`, input validation +and `getapimeta`. The discovery protocol is exercised by `di.torq.proc.discovery`'s suite. + +Run in a fresh q session. Needs `QHOME` set to a q install whose `bin/q` can be launched (the +peer is started via `$QHOME/bin/q`): ```q k4unit:use`di.k4unit diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 5d7dcb21..ff23fef2 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -1,7 +1,7 @@ / connection management and handle-by-type lookup for the modular torq world - the di.* analogue -/ of TorQ's .servers (code/handlers/trackservers.q + servers.q), scoped down for v1: no discovery -/ service, no password/access-list files, no non-torq process tracking, no FinSpace. process.csv -/ is a static phone book (who to dial), NOT an identity source - self-identity comes from config. +/ of TorQ's .servers (code/handlers/trackservers.q + servers.q). The discovery-protocol parts of +/ trackservers.q are ported line for line and published at their legacy root names (.servers.*, +/ .dotz.liveh*); registry state and config live at legacy's root .servers.* globals. See servers.md. / FRAMEWORK-tier module: no hard di.* deps; log, timer and handlers are injected (all required). / standard one-arg init[deps]: di.torq merges this process's config slice (proctype/procname, / connections, processcsv) into the same deps dict it passes the injectables in. conventions match @@ -11,26 +11,30 @@ / --- module-local state (initial values at load; read/written via .z.m at runtime) --- -SERVERS:([] - procname:`symbol$(); - proctype:`symbol$(); - hpup:`symbol$(); - w:`int$(); - hits:`int$(); - startp:`timestamp$(); - lastp:`timestamp$(); - endp:`timestamp$()); - -HOPENTIMEOUT:2000; - self:`proctype`procname!``; -/ guards init's one-time process-global side effects (the .z.pc observer + the retry timer job) so +/ guards init's one-time process-global side effects (the .z.pc observer + the timer jobs) so / init is IDEMPOTENT - di.torq calls it once per process, but a second call (a test re-run, a / future re-init) must not re-register: di.timer.addjob throws on a duplicate id. the dep refs are / always refreshed; only the one-time registrations are guarded. registered:0b; +/ trackservers.q l.13-28: flat config key -> (.servers global;trackservers default) +settings:`connections`discoveryregister`connectionsfromdiscovery`subscribetodiscovery`discoveryretry`tracknontorqprocess`hopentimeout`retry`retain`autoclean`debug`startup`discovery!( + (`.servers.CONNECTIONS;`); + (`.servers.DISCOVERYREGISTER;1b); + (`.servers.CONNECTIONSFROMDISCOVERY;1b); + (`.servers.SUBSCRIBETODISCOVERY;1b); + (`.servers.DISCOVERYRETRY;0D00:05); + (`.servers.TRACKNONTORQPROCESS;0b); + (`.servers.HOPENTIMEOUT;2000); + (`.servers.RETRY;0D00:05); + (`.servers.RETAIN;`long$0D00:30); + (`.servers.AUTOCLEAN;0b); + (`.servers.DEBUG;1b); + (`.servers.STARTUP;0b); + (`.servers.DISCOVERY;enlist`)); + raiseerror:{[ctx;msg] / internal - log an error under ctx via the injected logger, then signal it, so a failure is / observable in the log as well as thrown. used for all post-init domain errors (init's own @@ -41,10 +45,10 @@ raiseerror:{[ctx;msg] init:{[deps] / wire the injected deps (log/timer/handlers - all required, no fallback) and this process's - / config (proctype/procname identity, connections, processcsv), and install the one-time side - / effects (a .z.pc cleanup observer via handlers + a 10s serversretry job via timer). config - / arrives in the SAME deps dict (the one-arg init convention - di.torq merges the config slice - / into it). idempotent (see `registered). does NOT open connections - that is startup's job. + / config (proctype/procname identity, processcsv, the trackservers settings), publish the legacy + / root names, and install the one-time side effects (a .z.pc observer via handlers + the + / trackservers.q timer jobs via timer). idempotent (see `registered). does NOT open + / connections - that is startup's job. if[99h<>type deps; '"di.torq.servers: deps must be a dict of injectables + config"]; if[not all `log`timer`handlers in key deps; @@ -67,39 +71,36 @@ init:{[deps] .z.m.timer:deps`timer; .z.m.handlers:deps`handlers; .z.m.self:`proctype`procname!deps`proctype`procname; - .z.m.connections:$[`connections in key deps;deps`connections;`symbol$()]; .z.m.processcsv:$[`processcsv in key deps;deps`processcsv;""]; + / trackservers.q l.10 + @[value;`.servers.SERVERS;{set[`.servers.SERVERS;([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:())]}]; + / trackservers.q l.13-28 + {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; + set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; + / dotz.q l.8 + set[`.dotz.liveh;{x in key .z.W}]; + set[`.dotz.livehn;{x in 0Ni,key .z.W}]; + set[`.dotz.liveh0;{x in 0i,key .z.W}]; + pub:`opencon`cleanup`addnthawc`getdetails`addhw`addw`retry`retrydiscovery`autodiscovery`retryrows`removerows`register`querydiscovery`registerfromdiscovery`addprocs`procupdate`domainsocketsenabled`formathp`formatprocs`startup`pc!(opencon;cleanup;addnthawc;getdetails;addhw;addw;retry;retrydiscovery;autodiscovery;retryrows;removerows;register;querydiscovery;registerfromdiscovery;addprocs;procupdate;domainsocketsenabled;formathp;formatprocs;startup;pc); + set'[` sv/:`.servers,/:key pub;value pub]; if[not .z.m.registered; - / .z.pc is a SIMPLE (observer) event in di.torq.handlers - side-effect only, fan-out. registered via - / the injected handlers dep with di.torq.handlers' register[event;phase;nm;pri;func] contract; phase - / is ` (null) for a simple event, pri 0. the callback marks a closed handle's row disconnected. - / (param `wh`, not `w`, so it does not shadow the SERVERS column w.) - pcfunc:{[wh] .z.m.SERVERS:update endp:.z.p,w:0Ni from .z.m.SERVERS where w=wh; }; - (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pcfunc]; - / di.timer mode-1h period is in SECONDS, so 10 = a 10-second retry (a bare 10000 here would be - / ~2.8h - the latent typo that made dead-handle recovery effectively never fire in early POCs). - (.z.m.timer[`addjob])[`serversretry;retry;();10;1;()!()]; + / trackservers.q l.385 + (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; + / trackservers.q l.387-389 (legacy .timer.repeat's default schedule is mode 2) + if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;2;()!()]]; + if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;2;()!()]]; .z.m.registered:1b; ]; .z.m.loginfo[`init;"di.torq.servers initialised"]; }; -formathp:{[host;port;ipctype] - / internal - build a connection-handle symbol for `tcp`/`tcps`/`unix. only `tcp is exercised by - / startup in v1; the others exist for a future SOCKETTYPE-style config. - h:string host; - p:string port; - $[ipctype=`tcp; lower `$":",h,":",p; - ipctype=`tcps;lower `$":tcps://",h,":",p; - ipctype=`unix;lower `$":unix://",p; - raiseerror[`formathp;"unknown ipctype ",string ipctype]] - }; - +/ open a connection opencon:{[hpup] - / open a connection, logging (not erroring) on failure - a downed peer isn't necessarily an - / error at connect time; retry keeps trying. NOTE the timeout form is hopen[(handle;timeoutms)] - / (a single 2-item list), not the dyadic hopen[handle;timeoutms], which throws 'rank. - r:@[{(hopen (x;.z.m.HOPENTIMEOUT);"")};hpup;{(0Ni;x)}]; + if[.servers.DEBUG;.z.m.loginfo[`conn;"attempting to open handle to ",string hpup]]; + / NOTE the timeout form is hopen[(handle;timeoutms)] (a single 2-item list), not the dyadic + / hopen[handle;timeoutms], which throws 'rank. + r:@[{(hopen (x;.servers.HOPENTIMEOUT);"")};hpup;{(0Ni;x)}]; + if[.servers.DEBUG;.z.m.loginfo[`conn;"connection to ",(string hpup),$[null first r;" failed: ",last r;" successful"]]]; if[null first r;.z.m.logwarn[`servers;"failed to open connection to ",(string hpup),": ",last r]]; first r }; @@ -113,68 +114,189 @@ readprocesscsv:{[path] ("SISS";enlist",") 0: fsym }; -startup:{[config] - / open connections to every process.csv row whose proctype is in the configured connections list, - / excluding this process's own row. `connections` and `processcsv` are read from the config arg - - / NOT from init - because each consumer computes its OWN role-specific connection list (e.g. an rdb - / dials its tickerplant+hdb types, a gateway its backend types) and passes it in via its config - / slice; di.torq cannot know that list at init time. a failed connection is logged (not raised) and - / left as w:0Ni for retry. a no-op if no connections are configured. - / normalise connections to symbols to match process.csv's `proctype column (always a symbol via - / the "S" spec): a .q settings file gives symbols already (`$ throws 'type on a symbol - it is - / NOT idempotent, hence the type check); a .toml one gives plain strings (TOML has no symbol). - conns:$[`connections in key config;config`connections;`symbol$()]; - conns:$[11h=abs type conns;conns;`$conns]; - if[0=count conns;.z.m.loginfo[`servers;"no configured connections to make"];:()]; - if[not `processcsv in key config;raiseerror[`startup;"processcsv (path to process.csv) is required in config to open connections"]]; - procs:readprocesscsv[config`processcsv]; - pt:.z.m.self`proctype; - pn:.z.m.self`procname; - procs:update isme:(proctype=pt)&procname=pn from procs; - procs:select from procs where not isme; - procs:select from procs where proctype in conns; - if[0=count procs;.z.m.loginfo[`servers;"no process.csv rows match the configured connections"];:()]; - {[row] - hpup:formathp[row`host;row`port;`tcp]; - w:opencon[hpup]; - if[not null w;.z.m.loginfo[`servers;"connected to ",(string row`proctype),"/",(string row`procname)," at ",string hpup]]; - / catenate+reassign, NOT `tablename insert - a symbol-based insert into `.z.m.SERVERS` misses - / the compile-time module-local rewrite a source-level .z.m.SERVERS gets, silently targeting the - / wrong (literal) table. - newrow:([]procname:enlist row`procname;proctype:enlist row`proctype;hpup:enlist hpup;w:enlist w;hits:enlist 0i;startp:enlist $[null w;0Np;.z.p];lastp:enlist .z.p;endp:enlist 0Np); - .z.m.SERVERS:.z.m.SERVERS,newrow; - } each 0!procs; - }; +cleanup:{if[count w0:exec w from`.servers.SERVERS where not .dotz.livehn w; + update endp:.z.p,lastp:.z.p,w:0Ni from`.servers.SERVERS where w in w0]; + if[.servers.AUTOCLEAN;delete from`.servers.SERVERS where not .dotz.liveh w,(.z.p^endp)<.z.p-.servers.RETAIN];} + +/ add a new server for current session +addnthawc:{[name;proctype;hpup;attributes;W;checkhandle] + if[checkhandle and not isalive:.dotz.liveh W;'"invalid handle"]; + cleanup[]; + $[not hpup in (exec hpup from .servers.SERVERS) inter (exec hpup from .servers.nontorqprocesstab); + `.servers.SERVERS insert(name;proctype;lower hpup;W;0i;$[isalive;.z.p;0Np];.z.p;0Np;attributes); + .z.m.loginfo[`conn;"Removed double entries: name->", string[name],", proctype->",string[proctype],", hpup->\"",string[hpup],"\""]]; + W + } +/ return the details of the current process +getdetails:{(.z.f;.z.h;system"p";.z.m.self`procname;.z.m.self`proctype;@[value;(`.proc.getattributes;`);()!()])} + +/ add session behind a handle +addhw:{[hpuP;W] + / Get the information around a process + info:`f`h`port`procname`proctype`attributes!(@[W;({$[`getdetails in key`.servers;.servers.getdetails[];(.z.f;.z.h;system"p";`;`;$[`getattributes in key`.proc;.proc.getattributes[];()!()])]};`);(`;`;0Ni;`;`;()!())]); + if[0Ni~info`port;'"remote call failed on handle ",string W]; + if[null name:info`procname;name:`$last("/"vs string info`f)except enlist""]; + if[0=count name;name:`default]; + if[null hpuP;hpuP:formathp[info`h;info`port;`tcp;info`proctype;info`procname]]; + / If this handle already has an entry, delete the old entry + delete from `.servers.SERVERS where w=W; + addnthawc[name;info`proctype;hpuP;info`attributes;W;0b]} + +addw:addhw[`] + +/ after getting new servers run retry to open connections +retry:{retryrows exec i from `.servers.SERVERS where not .dotz.liveh0 w,not proctype=`discovery} + +retrydiscovery:{ + if[count d:exec i from `.servers.SERVERS where proctype=`discovery,not ({any .dotz.liveh0 x};w) fby hpup, i=(first;i) fby hpup; + .z.m.loginfo[`conn;"attempting to connect to discovery services"]; + retryrows d; + / register with the newly opened discovery services + if[.servers.DISCOVERYREGISTER and count h:exec w from .servers.SERVERS[d] where .dotz.liveh w; + .z.m.loginfo[`conn;"registering with discovery services"]; + @[;(`..register;`);()] each neg h]; + if[.servers.CONNECTIONSFROMDISCOVERY and count h; + registerfromdiscovery[$[`discovery in .servers.CONNECTIONS;(.servers.CONNECTIONS,()) except `discovery;.servers.CONNECTIONS];0b]]; + ]} + +/ Called by the discovery service when it restarts +autodiscovery:{if[.servers.DISCOVERYRETRY>0; .servers.retrydiscovery[]]} + +/ Attempt to make a connection for specified row ids retryrows:{[rows] - / internal - reattempt opencon for the given SERVERS row indices, updating w/lastp (and startp on - / a successful reconnect). - hs:opencon each exec hpup from .z.m.SERVERS where i in rows; - .z.m.SERVERS:update w:hs,lastp:.z.p from .z.m.SERVERS where i in rows; - .z.m.SERVERS:update startp:.z.p from .z.m.SERVERS where i in rows, not null w; - }; + / a returns the remote .proc.getattributes[] for a live handle, else an empty dict + a:{$[not null x;@[x;({.proc.getattributes[]};::);()!()];()!()]}; + handles:opencon each exec hpup from .servers.SERVERS where i in rows; + update lastp:.z.p,w:handles from`.servers.SERVERS where i in rows; + update attributes:a each w,startp:?[null w;0Np;.z.p] from`.servers.SERVERS where i in rows;} -cleanup:{[] - / internal - sweep any row whose handle has vanished from key .z.W (a peer that died WITHOUT a - / clean .z.pc on this side) and mark it disconnected, so retry will reopen it. the .z.pc observer - / already catches clean closes; this catches the ungraceful ones. - dead:exec w from .z.m.SERVERS where not null w, not w in key .z.W; - if[count dead;.z.m.SERVERS:update endp:.z.p,w:0Ni from .z.m.SERVERS where w in dead]; - }; +/ close handles and remove rows from the table +removerows:{[rows] + @[hclose;;()] each .servers.SERVERS[rows][`w] except 0 0Ni; + @[.z.pc;;()] each .servers.SERVERS[rows][`w] except 0 0Ni; + delete from `.servers.SERVERS where i in rows} -retry:{[] - / internal - the scheduled `serversretry job (driven by the injected timer; passed by value at - / init, so it needs no export). first sweep ungracefully-vanished handles (cleanup), then reopen - / every dead (null) handle - so both clean and unclean drops are recovered on the retry cycle. - cleanup[]; - rows:exec i from .z.m.SERVERS where null w; - if[count rows;retryrows[rows]]; - }; +/ Create some connections and optionally connect to them +register:{[connectiontab;proc;connect] + {addnthawc[x`procname;x`proctype;x`hpup;()!();0Ni;0b]}each distinct select from connectiontab where proctype=proc; + / automatically connect + if[connect; + $[`discovery=proc;retrydiscovery[];retry[]]]}; + +/ Query a discovery service, and get the list of available services +/ Does not attempt to re-open any discovery services +querydiscovery:{[procs] + if[0=count procs;:()]; + .z.m.loginfo[`conn;"querying discovery services for processes of types "," " sv string procs,()]; + h:exec w from .servers.SERVERS where proctype=`discovery,.dotz.liveh w; + $[0=count h; + [.z.m.loginfo[`conn;"no discovery services available"];()]; + raze @[;(`getservices;procs;.servers.SUBSCRIBETODISCOVERY);()] each h]} + +/ register processes from the discovery service +registerfromdiscovery:{[procs;connect] + if[`discovery in procs; '"cannot use registerfromdiscovery to locate discovery services"]; + .z.m.loginfo[`conn;"requesting processes from discovery service"]; + res:querydiscovery[procs]; + if[0=count res; .z.m.loginfo[`conn;"no processes found"]; :()]; + / add the processes + addprocs[res;procs;connect];} + +addprocs:{[connectiontab;procs;connect] + connectiontab:formatprocs[delete split from update host:hpup^`$last each -1 _' split, port:"I"$last each split from update split:{":" vs string x}each hpup from connectiontab]; + / filter out any we already have - same name,type and hpup + res:select from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS; + / we've dropped some items - maybe there are updated attributes + if[not count[res]=count connectiontab; + if[`attributes in cols connectiontab; + .servers.SERVERS:.servers.SERVERS lj 3!select procname,proctype,hpup,attributes from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS]]; + / if we have a match where the hpup is the same, but different name/type, then remove the old details + removerows exec i from `.servers.SERVERS where hpup in exec hpup from res; + register[res;;connect] each $[procs~`ALL;exec distinct proctype from res;procs,()];} + +/ used to handle updates from the discovery service +procupdate:{[procs] addprocs[procs;exec distinct proctype from procs;0b];} + +/ return true if unix domain sockets can be used +domainsocketsenabled:{[] + / unix domain sockets only works on unix and not windows + notwin:not .z.o like "w*"; + / v3.4 brought in the first version of unix domain sockets ipc + iskdbv:3.4<=.z.K; + :notwin and iskdbv; + } + +/ format hpup from procs table, take into account ipc type +formathp:{[HOST;PORT;IPCTYPE;PROCTYPE;PROCNAME] + ipctype:IPCTYPE; + isunixsocket:ipctype = `unix; + notsamebox:not any HOST in `localhost,.z.h; + host:string $[HOST=`localhost;.z.h;HOST]; + port:string PORT; + / revert socket to tcp + if[isunixsocket and notsamebox; + .z.m.logwarn[`formathp;"Expects to connect via domain sockets, but host is not on the same machine. Reverting IPC mechanism to TCP"]; + ipctype:`tcp; + ]; + if[isunixsocket and not domainsocketsenabled[]; + .z.m.logwarn[`formathp;"Domain sockets are not enabled for this system. Reverting IPC mechanism from to TCP"]; + ipctype:`tcp; + ]; + / Format hpup file handle + if[ipctype = `tcp; + hpup:lower `$":",host,":",port; + ]; + if[ipctype = `tcps; + hpup:lower `$":tcps://",host,":",port; + ]; + if[ipctype = `unix; + hpup:lower `$":unix://",port; + ]; + :hpup; + } + +/ do full formatting of proc table +formatprocs:{[PROCS] + procs:update ipctype:`tcp from PROCS; + procs:update hpup:.servers.formathp'[host;port;ipctype;proctype;procname] from procs; + :procs; + } + +/ called at start up. config`connections / config`processcsv stand in for legacy's +/ .servers.CONNECTIONS / .proc.file (a TOML config gives strings - normalised to symbols) +startup:{[config] + if[`connections in key config; + .servers.CONNECTIONS:$[11h=abs type c:config`connections;c;`$c]]; + pf:$[`processcsv in key config;config`processcsv;.z.m.processcsv]; + / correctly format procs and hpup + .servers.procstab:procs:formatprocs readprocesscsv pf; + .servers.nontorqprocesstab:formatprocs $[count key .servers.NONTORQPROCESSFILE;readprocesscsv 1_string .servers.NONTORQPROCESSFILE;0#procs]; + / If DISCOVERY servers have been explicity defined + if[count .servers.DISCOVERY; + if[not null first .servers.DISCOVERY; + if[count select from procs where hpup in .servers.DISCOVERY; .z.m.logerr[`startup; "host:port in .servers.DISCOVERY list is already present in data read from ",pf]]; + procs,:([]host:`;port:0Ni;proctype:`discovery;procname:`;hpup:.servers.DISCOVERY)]]; + / Remove any processes that have an active connection + connectedprocs:select procname, proctype, hpup from .servers.SERVERS; + procs:delete from procs where ([] procname; proctype; hpup) in connectedprocs; + nontorqprocs:delete from .servers.nontorqprocesstab where ([] procname; proctype; hpup) in connectedprocs; + / if there aren't any processes left to connect to, then escape + if[not any count each (procs;nontorqprocs); .z.m.loginfo[`conn;"No new processes to connect to. Escaping..."];:()]; + if[.servers.CONNECTIONSFROMDISCOVERY or .servers.DISCOVERYREGISTER; + register[procs;`discovery;0b]; + retrydiscovery[]]; + if[not .servers.CONNECTIONSFROMDISCOVERY; register[procs;;0b] each $[.servers.CONNECTIONS~`ALL;exec distinct proctype from procs;.servers.CONNECTIONS]]; + if[.servers.TRACKNONTORQPROCESS;register[nontorqprocs;;0b] each $[.servers.CONNECTIONS~`ALL;exec distinct proctype from nontorqprocs;.servers.CONNECTIONS]]; + / try and open dead connections + retry[]} + +pc:{[W] update w:0Ni,endp:.z.p from`.servers.SERVERS where w=W;cleanup[];} getservers:{[pt] / every live (non-null handle) SERVERS row for a proctype. if[not -11h=type pt;raiseerror[`getservers;"proctype must be a symbol"]]; - select from .z.m.SERVERS where proctype=pt, not null w + select from .servers.SERVERS where proctype=pt, not null w }; selector:{[tab;selection] @@ -187,7 +309,7 @@ selector:{[tab;selection] updatestats:{[wh] / internal - bump hits/lastp on the row whose handle was just handed out. - .z.m.SERVERS:update lastp:.z.p,hits:1+hits from .z.m.SERVERS where w=wh + .servers.SERVERS:update lastp:.z.p,hits:1+hits from .servers.SERVERS where w=wh }; gethandlebytype:{[pt;selection] diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 117ad8c7..72539911 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -13,13 +13,14 @@ comment,,,,,,,init - wiring and idempotency run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,init with mock deps + config (dial otherproc and deadproc) true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,init registered its .z.pc observer via the handlers dep true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init scheduled the retry job via the timer dep -true,0,0,q,10=first exec period from timercalls where id=`serversretry,1,1,retry period is 10s (di.timer mode-1h period in seconds - guards the old 10000 typo) +true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is trackservers.q's RETRY 0D00:05 in seconds (di.timer period unit) +true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled trackservers.q's discoveryretry job (DISCOVERYRETRY>0) run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,idempotent re-init did NOT add a second retry job true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,idempotent re-init did NOT re-register the pc handler -comment,,,,,,,startup - connect to a live peer and a dead one (self excluded) +comment,,,,,,,startup - connect to a live peer and a dead one run,0,0,q,svc.startup[svrdeps[`otherproc`deadproc]],1,1,open connections to otherproc (live) and deadproc (nothing listening) - connections+processcsv come from the config arg -true,0,0,q,0=count svc.getservers[`selfproc],1,1,self is excluded even though it is in process.csv +true,0,0,q,0=count svc.getservers[`selfproc],1,1,selfproc is not in connections so it is not dialled true,0,0,q,1=count svc.getservers[`otherproc],1,1,otherproc connected successfully true,0,0,q,0=count svc.getservers[`deadproc],1,1,deadproc failed (nothing listening) so it is not live true,0,0,q,"warnlogged[""failed to open connection""]",1,1,the failed dial was logged at warn @@ -29,8 +30,8 @@ true,0,0,q,"2=h ""1+1""",1,1,the handle is a live remote connection to a separat comment,,,,,,,cleanup + retry recover an ungraceful kill run,0,0,q,killpeer[],1,1,kill the peer ungracefully (handlers are mocked so no auto .z.pc fires) run,0,0,q,"@[{h ""1+1""};();{[e]e}]",1,1,touch the dead handle so kdb+ drops it from .z.W (protected - expected to error) -run,0,0,q,firejob[`serversretry],1,1,fire the retry job (runs cleanup then reopen) exactly as the timer would -true,0,0,q,0=count svc.getservers[`otherproc],1,1,cleanup marked the dead connection as gone +run,0,0,q,firejob[`serversretry],1,1,fire the retry job (reopens every row whose handle is not live) exactly as the timer would +true,0,0,q,0=count svc.getservers[`otherproc],1,1,retry's failed reopen marked the dead connection as gone run,0,0,q,spawnpeer[],1,1,bring a fresh peer up on the same port run,0,0,q,firejob[`serversretry],1,1,fire retry again - should reconnect now a peer is listening true,0,0,q,1=count svc.getservers[`otherproc],1,1,retry reconnected to otherproc diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 0b1b2a8b..7e272e08 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -67,4 +67,5 @@ setupfixture:{[] teardownfixture:{[] killpeer[]; system "rm -rf ",FIXDIR;}; / build the deps dict di.torq would assemble: injectables + this process's config slice. -svrdeps:{[conns] `log`timer`handlers`proctype`procname`connections`processcsv!(mocklog;mocktimer;mockhandlers;`selfproc;`selfinst;conns;FIXDIR,"/process.csv")}; +/ discovery off, so startup dials process.csv directly (trackservers.q's own defaults are 1b). +svrdeps:{[conns] `log`timer`handlers`proctype`procname`connections`processcsv`discoveryregister`connectionsfromdiscovery!(mocklog;mocktimer;mockhandlers;`selfproc;`selfinst;conns;FIXDIR,"/process.csv";0b;0b)}; diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index 09f96f7f..6ac54ffa 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1 +1,24 @@ -/ built-in framework defaults - empty for v0 +/ built-in framework defaults +/ Server connection details - legacy TorQ config/settings/default.q .servers section (flat keys) +/ whether to register with the discovery service (legacy DISCOVERYREGISTER:DISCOVERYCONNECT) +discoveryregister:$[`lim in key`.Q;@[{$[0W=x[`conns][`lim];1b;0b]};.Q.lim[];1b];1b] +/ whether to get connection details from the discovery service (legacy CONNECTIONSFROMDISCOVERY:DISCOVERYREGISTER) +connectionsfromdiscovery:$[`lim in key`.Q;@[{$[0W=x[`conns][`lim];1b;0b]};.Q.lim[];1b];1b] +/ whether to track and register non torQ processes +tracknontorqprocess:1b +/ whether to subscribe to the discovery service for new processes becoming available +subscribetodiscovery:1b +/ how often to retry the connection to the discovery service. If 0, no connection is made +discoveryretry:0D00:05 +/ new connection time out value in milliseconds +hopentimeout:2000 +/ period on which to retry dead connections. If 0, no reconnection attempts +retry:0D00:05 +/ length of time to retain server records +retain:`long$0D00:30 +/ clean out old records when handling a close +autoclean:0b +/ log messages when opening new connections +debug:1b +/ list of discovery services to connect to (if not using process.csv) +discovery:enlist` diff --git a/di/torq/settings/discovery.q b/di/torq/settings/discovery.q new file mode 100644 index 00000000..70bfaade --- /dev/null +++ b/di/torq/settings/discovery.q @@ -0,0 +1,21 @@ +/ Bespoke config for the discovery service - legacy TorQ config/settings/discovery.q (flat keys) +/ list of connections to make at start up +connections:`ALL +/ whether to register with the discovery service +discoveryregister:0b +/ whether to get connection details from the discovery service (as opposed to the static file) +connectionsfromdiscovery:0b +/ whether to track and register non torQ processes throught discovery +tracknontorqprocess:1b +/ how often to retry the connection to the discovery service. If 0, no connection is made +discoveryretry:0D +/ new connection time out value in milliseconds +hopentimeout:200 +/ length of time to retry dead connections. If 0, no reconnection attempts +retry:0D00 +/ length of time to retain server records +retain:`long$0Wp +/ clean out old records when handling a close +autoclean:0b +/ log messages when opening new connections +debug:1b diff --git a/di/torq/settings/hdb.q b/di/torq/settings/hdb.q index 8369fe78..a01fc1c0 100644 --- a/di/torq/settings/hdb.q +++ b/di/torq/settings/hdb.q @@ -1 +1,3 @@ dir:`:hdb +/ create connections (legacy config/settings/hdb.q) +startup:1b diff --git a/di/torq/torq.q b/di/torq/torq.q index 214e1b7b..08018019 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -4,7 +4,7 @@ / same init[config;deps] calling convention. / built-in process type registry: proctype -> di.* module name -builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping +builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery reqenv:{[e] v:getenv e; @@ -294,6 +294,8 @@ init:{[proctype;procname;overrides] / module init (so it can reference the module's tables/state) and BEFORE runhook (so an / app file may define/override ..run for the hook to pick up). loadappcode[logdep;config;proctype;procname]; + / initialise connections (legacy torq.q l.673) + if[@[value;`.servers.STARTUP;0b];.servers.startup config]; / optional query logging - a no-op unless [querylog] enabled=true. LAST of everything that binds .z.*, because / di.querylog wraps whatever is bound at this moment by direct assignment (see initquerylog / torq.md) initquerylog[config;deps]; From 3c67d3c7ed3fbf1771c3f5cf2d0f19259e625031 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Sun, 27 Sep 2026 23:55:50 +0100 Subject: [PATCH 02/42] Fix di.torq.servers timer modes: legacy mode 2 is di.timer mode 3 Legacy TorQ timer modes 0/1/2 schedule the next run from the scheduled start, the actual start and the finish (code/common/timer.q l.8-11); di.timer's 1h/2h/3h mean the same, so legacy mode n is di.timer mode n+1. d04d8d4 ported legacy's .timer.repeat (default mode 2, from finish) as di mode 2 (from actual start) for the discoveryretry and serversretry jobs. Both now use mode 3. The servers suite gains a row asserting mode 3 for both jobs; it fails against d04d8d4. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 2 +- di/torq/servers/servers.q | 6 +++--- di/torq/servers/test.csv | 1 + di/torq/servers/test.q | 6 +++--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index d8dd9492..a3d63617 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -120,7 +120,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser **Conversions** (legacy calls with no di equivalent): - `.lg.*` becomes the injected `log`. - `.dotz.set` on `.z.pc` becomes `handlers[`register]`. -- `.timer.repeat` becomes `timer[`addjob]`, using mode 2 (legacy's default schedule) and the period in seconds. +- `.timer.repeat` becomes `timer[`addjob]`, using mode 3 (legacy's default mode 2, next run counted from finish; legacy mode n is di.timer mode n+1) and the period in seconds. - `.proc.cp[]` becomes `.z.p`. - `.proc.procname`/`proctype` in `getdetails` become init's identity. - `.proc.readprocs` becomes `readprocesscsv`. diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index ff23fef2..7e2fc8c7 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -86,9 +86,9 @@ init:{[deps] if[not .z.m.registered; / trackservers.q l.385 (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; - / trackservers.q l.387-389 (legacy .timer.repeat's default schedule is mode 2) - if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;2;()!()]]; - if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;2;()!()]]; + / trackservers.q l.387-389 (legacy .timer.repeat's default mode 2, from finish, is di.timer mode 3) + if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; + if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]; .z.m.registered:1b; ]; .z.m.loginfo[`init;"di.torq.servers initialised"]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 72539911..eb0b05c6 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -14,6 +14,7 @@ run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,init with mock deps + confi true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,init registered its .z.pc observer via the handlers dep true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init scheduled the retry job via the timer dep true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is trackservers.q's RETRY 0D00:05 in seconds (di.timer period unit) +true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use di.timer mode 3 (legacy .timer.repeat default mode 2 - next run from finish) true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled trackservers.q's discoveryretry job (DISCOVERYRETRY>0) run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,idempotent re-init did NOT add a second retry job diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 7e272e08..9ed6d383 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -10,12 +10,12 @@ mocklog:`info`warn`error!( {[c;m]`logrows upsert(`warn;c;m)}; {[c;m]`logrows upsert(`error;c;m)}); -/ timer mock: records (id;period) for the wiring asserts AND captures each job's func by id, so a +/ timer mock: records (id;period;mode) for the wiring asserts AND captures each job's func by id, so a / test can fire the retry cycle exactly as the real timer would (retry/cleanup are INTERNAL - not / exported - so they are driven only via this captured callback). -timercalls:([]id:`symbol$();period:`long$()); +timercalls:([]id:`symbol$();period:`long$();mode:`long$()); timerjobs:(`symbol$())!(); -mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] timerjobs[id]:func; `timercalls upsert (id;period);}; +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] timerjobs[id]:func; `timercalls upsert (id;period;`long$mode);}; / handlers mock: records (event;name) with di.torq.handlers' register[event;phase;nm;pri;func] shape. it / does NOT actually bind .z.pc - so the only cleanup path exercised here is the explicit retry-> From 06609557ab9ac43f77b1c706a63e0412503cbfb3 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 15:12:01 +0100 Subject: [PATCH 03/42] Fix di.torq.servers waitfortype: reach a discovery service that comes up during the wait With connections taken from discovery (the builtin default), a process started before discovery registers only a dead discovery row. waitfortype polled retry[], which skips discovery rows and never re-queries, so the rdb, wdb and feed each waited out tpwaittimeout (30s) and aborted init, left running but uninitialised. Reproduced on TorqX-POC with discovery1 last in process.csv. Each poll now calls startup ()!() (reconnect discovery, register, take the rows it names) and keeps retry[]. The servers suite gains a discovery stub that comes up after startup; the waitfortype row fails against 3c67d3c and passes here. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 7 ++++--- di/torq/servers/servers.q | 5 +++-- di/torq/servers/test.csv | 7 +++++++ di/torq/servers/test.q | 28 +++++++++++++++++++++++++++- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index a3d63617..7e412139 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -69,7 +69,7 @@ h "1+1" | `startup` | `startup[config]` | Legacy `startup` (l.323–345). `config`connections`/`config`processcsv` stand in for `.servers.CONNECTIONS`/`.proc.file`. | | `getservers` | `getservers[proctype]` | Live (`w` non-null) `SERVERS` rows for a proctype. | | `gethandlebytype` | `gethandlebytype[proctype;selection]` | One live handle via `` `any``/`roundrobin`/`last``; `0Ni` if none. Bumps usage stats. | -| `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Block until a live connection exists or timeout; `1b`/`0b`. Caller decides if a timeout is fatal. `startup` must have run first. | +| `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Block until a live connection exists or timeout; `1b`/`0b`. Caller decides if a timeout is fatal. `startup` must have run first. Each poll re-runs `startup` then `retry`, so a discovery service that comes up during the wait is reached and the proctype it names is dialled. | | `getapimeta` | `getapimeta[]` | This module's api metadata, one row per **callable** API function (`init`/`getapimeta` plumbing omitted), for `di.torq` to register with `di.api`. | ## The `SERVERS` table @@ -172,9 +172,10 @@ must be `` ` `` (null) — di.torq.handlers rejects a non-null phase on an obser ## Tests -`test.q` + `test.csv` (36 checks) spawn a genuinely separate `q` peer and cover init validation, +`test.q` + `test.csv` (43 checks) spawn a genuinely separate `q` peer and cover init validation, wiring and idempotency, `startup` against a live and a dead peer (discovery switched off in the -fixture), `gethandlebytype`, retry recovering an ungraceful kill, `waitfortype`, input validation +fixture), `gethandlebytype`, retry recovering an ungraceful kill, `waitfortype` (including a +discovery stub that comes up after `startup`), input validation and `getapimeta`. The discovery protocol is exercised by `di.torq.proc.discovery`'s suite. Run in a fresh q session. Needs `QHOME` set to a q install whose `bin/q` can be launched (the diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 7e2fc8c7..96f301e2 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -333,8 +333,8 @@ signalfound:{[pt] waitfortype:{[pt;timeoutms;pollms] / block until at least one LIVE connection to pt exists, or timeoutms elapses. the DI-scoped / analogue of legacy TorQ's startupdepcycles - "fail fast, but wait for a hard dependency to come - / up". startup must have run first (so a pt row exists to reattempt). polls retry between tries, - / sleeping pollms. returns 1b once connected, 0b on timeout - the CALLER decides if that is fatal. + / up". each poll re-runs startup (reaches a discovery service that came up late, and so the pt rows + / it names) then retry, sleeping pollms. returns 1b once connected, 0b on timeout - the CALLER decides if that is fatal. / NOTE the blocking system"sleep" is fine at startup (single-threaded; the injected timer's .z.ts / just doesn't fire during the sleep). if[not -11h=type pt;raiseerror[`waitfortype;"proctype must be a symbol"]]; @@ -343,6 +343,7 @@ waitfortype:{[pt;timeoutms;pollms] deadline:.z.p+`timespan$1000000*`long$timeoutms; .z.m.loginfo[`servers;"waiting up to ",(string timeoutms),"ms for a ",(string pt)," connection"]; while[(0=count getservers pt) and .z.p/dev/null 2>&1 &"; + if[not waitlisten[port;3000];'"test: q failed to listen on ",string port]; + h:hopen (`$":localhost:",string port;2000); + DISCPIDS,:h ".z.i"; + hclose h;}; + +spawndisc:{[] spawnq["";TPPORT]; spawnq[FIXDIR,"/disc.q";DISCPORT];}; +killdisc:{[] {@[system;"kill ",string x;{}]} each DISCPIDS; DISCPIDS::`long$();}; / build the deps dict di.torq would assemble: injectables + this process's config slice. / discovery off, so startup dials process.csv directly (trackservers.q's own defaults are 1b). From 3eadcbced59e84b3843469eaf15d11c1f002c3fb Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 15:41:36 +0100 Subject: [PATCH 04/42] Trim di.torq.servers and discovery comments and docs to what, not why servers.q: the header, registered, init, opencon, timer, startup and waitfortype comments cut to one line each. servers.md: intro and init prose condensed; the .z.pc registration and conventions sections dropped (the conversions list covers the first); tests section listed. Test helper headers cut to one line. Comment and doc changes only; the servers (43), discovery (30) and di.torq (56) suites pass. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/discovery/test.q | 4 +-- di/torq/servers/servers.md | 66 ++++++++++------------------------- di/torq/servers/servers.q | 36 ++++--------------- di/torq/servers/test.q | 3 +- 4 files changed, 26 insertions(+), 83 deletions(-) diff --git a/di/torq/proc/discovery/test.q b/di/torq/proc/discovery/test.q index 024f1fb8..42ea6079 100644 --- a/di/torq/proc/discovery/test.q +++ b/di/torq/proc/discovery/test.q @@ -1,6 +1,4 @@ -/ di.torq.proc.discovery test helpers (loaded by test.csv): mock log/handlers, stubbed .servers.* -/ root names that record their calls, and two real q peers so the .z.w/.z.W paths run over -/ genuine handles (a peer calls back into this process over the handle it was asked on). +/ di.torq.proc.discovery test helpers: mock log/handlers, recording .servers.* stubs, two real q peers logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()); mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}); diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 7e412139..9bcda23c 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -1,25 +1,16 @@ # di.torq.servers -Connection management and handle-by-type lookup for the modular TorQ world — the `di.*` -analogue of TorQ's `.servers` (`code/handlers/trackservers.q` + `servers.q`). The parts of -`trackservers.q` the discovery protocol uses are **ported line for line** and published at -their **legacy root names** (`.servers.*`, `.dotz.liveh*`), with the registry and config at -legacy's root `.servers.*` globals — see [Discovery protocol](#discovery-protocol-ported-from-trackserversq). -No password/access-list files, no FinSpace. - -FRAMEWORK-tier module: no hard `di.*` dependencies; `log`, `timer` and `handlers` are all -**injected** (all required, no fallback). +TorQ's `.servers` (`code/handlers/trackservers.q`) as a kdb-x module. The parts the discovery +protocol uses are ported line for line and published at their legacy root names (`.servers.*`, +`.dotz.liveh*`); the registry and settings are the legacy root `.servers.*` globals. No +password/access-list files, no FinSpace. `log`, `timer` and `handlers` are injected (all required). ## init and config -Standard **one-arg `init[deps]`**: `di.torq` merges this process's resolved config slice into -the same `deps` dict it passes the injectables in, so `deps` carries both the injectable -dependencies **and** the config keys. `init` wires the deps, records self-identity, sets the -`.servers.*` config globals, publishes the legacy root names, and installs the one-time -process-global side effects — a `.z.pc` handler and trackservers.q's `discoveryretry` and -`serversretry` timer jobs. It is **idempotent** (guarded by an internal `registered` flag): a -second call refreshes deps, config and root names without re-registering (a duplicate -`di.timer.addjob` id would throw). `init` does **not** open connections. +`init[deps]` takes the injectables and this process's config in one dict (di.torq merges them). +It sets the `.servers.*` globals, publishes the legacy root names, and registers a `.z.pc` +observer (via `handlers`) and the `discoveryretry`/`serversretry` timer jobs (via `timer`). A +second call refreshes everything but registers nothing twice. It opens no connections. `deps` keys: @@ -69,7 +60,7 @@ h "1+1" | `startup` | `startup[config]` | Legacy `startup` (l.323–345). `config`connections`/`config`processcsv` stand in for `.servers.CONNECTIONS`/`.proc.file`. | | `getservers` | `getservers[proctype]` | Live (`w` non-null) `SERVERS` rows for a proctype. | | `gethandlebytype` | `gethandlebytype[proctype;selection]` | One live handle via `` `any``/`roundrobin`/`last``; `0Ni` if none. Bumps usage stats. | -| `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Block until a live connection exists or timeout; `1b`/`0b`. Caller decides if a timeout is fatal. `startup` must have run first. Each poll re-runs `startup` then `retry`, so a discovery service that comes up during the wait is reached and the proctype it names is dialled. | +| `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Poll `startup` then `retry` every `pollms` until a live connection exists (`1b`) or `timeoutms` passes (`0b`). | | `getapimeta` | `getapimeta[]` | This module's api metadata, one row per **callable** API function (`init`/`getapimeta` plumbing omitted), for `di.torq` to register with `di.api`. | ## The `SERVERS` table @@ -120,7 +111,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser **Conversions** (legacy calls with no di equivalent): - `.lg.*` becomes the injected `log`. - `.dotz.set` on `.z.pc` becomes `handlers[`register]`. -- `.timer.repeat` becomes `timer[`addjob]`, using mode 3 (legacy's default mode 2, next run counted from finish; legacy mode n is di.timer mode n+1) and the period in seconds. +- `.timer.repeat` becomes `timer[`addjob]`, mode 3 (legacy mode 2: next run from finish), period in seconds. - `.proc.cp[]` becomes `.z.p`. - `.proc.procname`/`proctype` in `getdetails` become init's identity. - `.proc.readprocs` becomes `readprocesscsv`. @@ -148,38 +139,17 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - Legacy defaults route connections through a discovery process: with `connectionsfromdiscovery` on, `startup` dials only discovery rows and learns the rest from it. -## `.z.pc` registration via di.torq.handlers - -`.z.pc` (connection closed) is a **simple/observer** event in di.torq.handlers — side-effect only, -fan-out — so di.torq.servers registers `pc` through the injected `handlers` dependency rather -than assigning `.z.pc` directly: - -```q -(handlers[`register])[`.z.pc;`;`servers;0j;pc] -``` - -`register`'s signature is `register[event;phase;nm;pri;func]`; for a simple event the `phase` -must be `` ` `` (null) — di.torq.handlers rejects a non-null phase on an observer event. - -## Conventions (learnings from di.torq.config) - -- **One-arg `init[deps]`** with config folded into `deps`, not a two-arg `init[config;deps]`. -- **Three-flat-var logging** — `.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`. -- **`raiseerror` (log-then-signal)** for di's own post-init domain errors (`selector` unknown - selection, missing `process.csv`). `init`'s dependency validation signals plainly (no logger yet). -- **`getapimeta`** exported; a test asserts it documents exactly the module's *callable* exports. -- **Env-free** — the `process.csv` path arrives via `config`processcsv` (di.torq resolves it). - ## Tests -`test.q` + `test.csv` (43 checks) spawn a genuinely separate `q` peer and cover init validation, -wiring and idempotency, `startup` against a live and a dead peer (discovery switched off in the -fixture), `gethandlebytype`, retry recovering an ungraceful kill, `waitfortype` (including a -discovery stub that comes up after `startup`), input validation -and `getapimeta`. The discovery protocol is exercised by `di.torq.proc.discovery`'s suite. +`test.q` + `test.csv` (43 checks) spawn real q peers. They cover: +- init validation, wiring and idempotency; +- `startup` against a live and a dead peer (discovery off); +- `gethandlebytype`, and retry recovering an ungraceful kill; +- `waitfortype`, including a discovery stub that comes up after `startup`; +- input validation and `getapimeta`. -Run in a fresh q session. Needs `QHOME` set to a q install whose `bin/q` can be launched (the -peer is started via `$QHOME/bin/q`): +The rest of the discovery protocol is covered by `di.torq.proc.discovery`'s suite. Run in a fresh +q session with `QHOME` set to a q install whose `bin/q` can be launched: ```q k4unit:use`di.k4unit diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 96f301e2..87e9655c 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -1,22 +1,10 @@ -/ connection management and handle-by-type lookup for the modular torq world - the di.* analogue -/ of TorQ's .servers (code/handlers/trackservers.q + servers.q). The discovery-protocol parts of -/ trackservers.q are ported line for line and published at their legacy root names (.servers.*, -/ .dotz.liveh*); registry state and config live at legacy's root .servers.* globals. See servers.md. -/ FRAMEWORK-tier module: no hard di.* deps; log, timer and handlers are injected (all required). -/ standard one-arg init[deps]: di.torq merges this process's config slice (proctype/procname, -/ connections, processcsv) into the same deps dict it passes the injectables in. conventions match -/ di.torq.config: strict init validation (no fallback), three-flat-var logging, log-then-signal via -/ raiseerror, getapimeta for di.api, and the env-free boundary (the process.csv path arrives via -/ config; di.torq.servers reads no env itself). +/ di.torq.servers - TorQ's .servers (code/handlers/trackservers.q) as a kdb-x module, at the legacy root names. See servers.md / --- module-local state (initial values at load; read/written via .z.m at runtime) --- self:`proctype`procname!``; -/ guards init's one-time process-global side effects (the .z.pc observer + the timer jobs) so -/ init is IDEMPOTENT - di.torq calls it once per process, but a second call (a test re-run, a -/ future re-init) must not re-register: di.timer.addjob throws on a duplicate id. the dep refs are -/ always refreshed; only the one-time registrations are guarded. +/ whether init has registered the .z.pc observer and timer jobs registered:0b; / trackservers.q l.13-28: flat config key -> (.servers global;trackservers default) @@ -44,11 +32,7 @@ raiseerror:{[ctx;msg] }; init:{[deps] - / wire the injected deps (log/timer/handlers - all required, no fallback) and this process's - / config (proctype/procname identity, processcsv, the trackservers settings), publish the legacy - / root names, and install the one-time side effects (a .z.pc observer via handlers + the - / trackservers.q timer jobs via timer). idempotent (see `registered). does NOT open - / connections - that is startup's job. + / wire deps and config, publish the legacy root names, register the .z.pc observer and timer jobs once if[99h<>type deps; '"di.torq.servers: deps must be a dict of injectables + config"]; if[not all `log`timer`handlers in key deps; @@ -86,7 +70,7 @@ init:{[deps] if[not .z.m.registered; / trackservers.q l.385 (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; - / trackservers.q l.387-389 (legacy .timer.repeat's default mode 2, from finish, is di.timer mode 3) + / trackservers.q l.387-389 if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]; .z.m.registered:1b; @@ -97,8 +81,6 @@ init:{[deps] / open a connection opencon:{[hpup] if[.servers.DEBUG;.z.m.loginfo[`conn;"attempting to open handle to ",string hpup]]; - / NOTE the timeout form is hopen[(handle;timeoutms)] (a single 2-item list), not the dyadic - / hopen[handle;timeoutms], which throws 'rank. r:@[{(hopen (x;.servers.HOPENTIMEOUT);"")};hpup;{(0Ni;x)}]; if[.servers.DEBUG;.z.m.loginfo[`conn;"connection to ",(string hpup),$[null first r;" failed: ",last r;" successful"]]]; if[null first r;.z.m.logwarn[`servers;"failed to open connection to ",(string hpup),": ",last r]]; @@ -263,8 +245,7 @@ formatprocs:{[PROCS] :procs; } -/ called at start up. config`connections / config`processcsv stand in for legacy's -/ .servers.CONNECTIONS / .proc.file (a TOML config gives strings - normalised to symbols) +/ called at start up; config`connections and config`processcsv replace .servers.CONNECTIONS and .proc.file startup:{[config] if[`connections in key config; .servers.CONNECTIONS:$[11h=abs type c:config`connections;c;`$c]]; @@ -331,12 +312,7 @@ signalfound:{[pt] }; waitfortype:{[pt;timeoutms;pollms] - / block until at least one LIVE connection to pt exists, or timeoutms elapses. the DI-scoped - / analogue of legacy TorQ's startupdepcycles - "fail fast, but wait for a hard dependency to come - / up". each poll re-runs startup (reaches a discovery service that came up late, and so the pt rows - / it names) then retry, sleeping pollms. returns 1b once connected, 0b on timeout - the CALLER decides if that is fatal. - / NOTE the blocking system"sleep" is fine at startup (single-threaded; the injected timer's .z.ts - / just doesn't fire during the sleep). + / poll startup and retry every pollms until pt is live (1b) or timeoutms passes (0b) if[not -11h=type pt;raiseerror[`waitfortype;"proctype must be a symbol"]]; if[not (abs type timeoutms) within 5 7h;raiseerror[`waitfortype;"timeoutms must be an integer (ms)"]]; if[not (abs type pollms) within 5 7h;raiseerror[`waitfortype;"pollms must be an integer (ms)"]]; diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 999aac59..e3221f72 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -70,8 +70,7 @@ teardownfixture:{[] killpeer[]; killdisc[]; system "rm -rf ",FIXDIR;}; QBIN:first system "readlink -f /proc/",(string .z.i),"/exe"; DISCPORT:0N; TPPORT:0N; DISCPIDS:`long$(); -/ process.csv gains a discovery row; the stub answers getservices with the tpproc peer. -/ addprocs' removerows calls .z.pc, which the handlers mock never binds +/ add a discovery row to process.csv, write the stub, and bind the .z.pc that addprocs calls setupdisc:{[] .z.pc:{}; DISCPORT::pickport DEADPORT+1; From f198b578aa79fb227871bc8429c5d900cf43d11b Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 16:38:29 +0100 Subject: [PATCH 05/42] di.torq settings: discovery off by default, debug off; tidy default.q discoveryregister and connectionsfromdiscovery default to 0b, so a process dials its process.csv peers directly unless the app turns discovery on. debug defaults to 0b. default.q regrouped into discovery, connections and server-record blocks with aligned one-line comments. servers.md updated to match. The di.torq suite gains a row asserting the cascaded defaults for a non-discovery proctype; it fails on the previous default.q. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 12 +++++------ di/torq/settings/default.q | 42 ++++++++++++++++---------------------- di/torq/test.csv | 1 + 3 files changed, 25 insertions(+), 30 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 9bcda23c..e124a58d 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -23,10 +23,10 @@ second call refreshes everything but registers nothing twice. It opens no connec | `processcsv` | config | **path** to `process.csv`; supplied by di.torq (legacy `.proc.file`) | | `nontorqprocessfile` | config | path to the non-TorQ process file (legacy `NONTORQPROCESSFILE`); default `nontorqprocess.csv` in `processcsv`'s directory | -The trackservers.q settings (l.13–28) are flat config keys, each setting its legacy global. The -default is trackservers.q's own. `di/torq/settings/default.q` carries legacy -`config/settings/default.q`'s values, and `di/torq/settings/discovery.q` carries legacy -`config/settings/discovery.q`'s. +The settings are flat config keys, each setting its `.servers.*` global. `di/torq/settings/default.q` +supplies every process's values; `discoveryregister`, `connectionsfromdiscovery` and `debug` are +`0b` there, so discovery is off unless the app turns it on. `di/torq/settings/discovery.q` +supplies the discovery process's values. | key | global | trackservers.q default | |---|---|---| @@ -136,8 +136,8 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser `addnthawc`). - The retry job runs every `RETRY` (5m), not 10s. - `localhost` hpups resolve to `.z.h`. -- Legacy defaults route connections through a discovery process: with - `connectionsfromdiscovery` on, `startup` dials only discovery rows and learns the rest from it. +- With `connectionsfromdiscovery` on (off by default), `startup` dials only discovery rows and + learns the rest from it. ## Tests diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index 6ac54ffa..4d5745f4 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1,24 +1,18 @@ -/ built-in framework defaults -/ Server connection details - legacy TorQ config/settings/default.q .servers section (flat keys) -/ whether to register with the discovery service (legacy DISCOVERYREGISTER:DISCOVERYCONNECT) -discoveryregister:$[`lim in key`.Q;@[{$[0W=x[`conns][`lim];1b;0b]};.Q.lim[];1b];1b] -/ whether to get connection details from the discovery service (legacy CONNECTIONSFROMDISCOVERY:DISCOVERYREGISTER) -connectionsfromdiscovery:$[`lim in key`.Q;@[{$[0W=x[`conns][`lim];1b;0b]};.Q.lim[];1b];1b] -/ whether to track and register non torQ processes -tracknontorqprocess:1b -/ whether to subscribe to the discovery service for new processes becoming available -subscribetodiscovery:1b -/ how often to retry the connection to the discovery service. If 0, no connection is made -discoveryretry:0D00:05 -/ new connection time out value in milliseconds -hopentimeout:2000 -/ period on which to retry dead connections. If 0, no reconnection attempts -retry:0D00:05 -/ length of time to retain server records -retain:`long$0D00:30 -/ clean out old records when handling a close -autoclean:0b -/ log messages when opening new connections -debug:1b -/ list of discovery services to connect to (if not using process.csv) -discovery:enlist` +/ built-in framework defaults: the .servers settings + +/ discovery - off unless the app turns it on +discoveryregister:0b / register with the discovery service +connectionsfromdiscovery:0b / get connection details from discovery, not process.csv +subscribetodiscovery:1b / subscribe to discovery for new processes +discoveryretry:0D00:05 / how often to retry discovery; 0D means never +discovery:enlist` / discovery services to use if not in process.csv + +/ connections +hopentimeout:2000 / hopen timeout in milliseconds +retry:0D00:05 / how often to retry dead connections; 0D means never +tracknontorqprocess:1b / track and register non-TorQ processes +debug:0b / log each connection attempt + +/ server records +retain:`long$0D00:30 / how long to keep a closed server's record +autoclean:0b / drop expired records when a connection closes diff --git a/di/torq/test.csv b/di/torq/test.csv index 578b8f71..0affd0e9 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -13,6 +13,7 @@ fail,0,0,q,tq.init[`;`;()!()],1,,auto-detect must fail when this session's port run,0,0,q,r:tq.init[`hdb;`hdb;()!()],1,,explicit-identity init for the built-in hdb proctype true,0,0,q,`hdb~r`proctype,1,,identity resolved from the explicit args true,0,0,q,`k4unittest~(r`config)`owner,1,,config cascade reached the app-level default.q +true,0,0,q,000b~(r`config)`discoveryregister`connectionsfromdiscovery`debug,1,,builtin default.q leaves discovery off and debug off true,0,0,q,`widgets in tables[],1,,the built-in hdb module actually mounted the fixture hdb dir true,0,0,q,(`handlers`log`servers`timer)~asc key r`deps,1,,all four core deps (incl injected servers) were built and passed through From 4ee2727d5a8ff0166fd0cd7d7491e5276f711435 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 11:27:39 +0100 Subject: [PATCH 06/42] di.torq.servers: add the enabled setting; tests spawn peers with QBIN - settings gains `enabled` -> .servers.enabled (1b), gating the discoveryretry and serversretry timer jobs (trackservers.q l.12, l.387). Lines are byte-identical to di.torq.servers 0.5.0, so feature-chainedtp inherits them. - test.csv: enabled defaults to 1b. - test.q: spawnpeer runs QBIN (the running q binary) instead of $QHOME/bin/q; QBIN is defined once in the fixture block. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 1 + di/torq/servers/servers.q | 8 +++++--- di/torq/servers/test.csv | 1 + di/torq/servers/test.q | 8 ++++---- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index e124a58d..ea24d343 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -30,6 +30,7 @@ supplies the discovery process's values. | key | global | trackservers.q default | |---|---|---| +| `enabled` | `.servers.enabled` | `1b` — gates the `discoveryretry`/`serversretry` timer jobs | | `connections` | `.servers.CONNECTIONS` | `` ` `` | | `discoveryregister` | `.servers.DISCOVERYREGISTER` | `1b` | | `connectionsfromdiscovery` | `.servers.CONNECTIONSFROMDISCOVERY` | `1b` | diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 87e9655c..87d1363e 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -8,7 +8,8 @@ self:`proctype`procname!``; registered:0b; / trackservers.q l.13-28: flat config key -> (.servers global;trackservers default) -settings:`connections`discoveryregister`connectionsfromdiscovery`subscribetodiscovery`discoveryretry`tracknontorqprocess`hopentimeout`retry`retain`autoclean`debug`startup`discovery!( +settings:`enabled`connections`discoveryregister`connectionsfromdiscovery`subscribetodiscovery`discoveryretry`tracknontorqprocess`hopentimeout`retry`retain`autoclean`debug`startup`discovery!( + (`.servers.enabled;1b); (`.servers.CONNECTIONS;`); (`.servers.DISCOVERYREGISTER;1b); (`.servers.CONNECTIONSFROMDISCOVERY;1b); @@ -71,8 +72,9 @@ init:{[deps] / trackservers.q l.385 (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; / trackservers.q l.387-389 - if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; - if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]; + if[.servers.enabled; + if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; + if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]]; .z.m.registered:1b; ]; .z.m.loginfo[`init;"di.torq.servers initialised"]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 40a82d2e..92e7fb70 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -16,6 +16,7 @@ true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init schedu true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is trackservers.q's RETRY 0D00:05 in seconds (di.timer period unit) true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use di.timer mode 3 (legacy .timer.repeat default mode 2 - next run from finish) true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled trackservers.q's discoveryretry job (DISCOVERYRETRY>0) +true,0,0,q,.servers.enabled,1,1,enabled defaults to 1b run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,idempotent re-init did NOT add a second retry job true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,idempotent re-init did NOT re-register the pc handler diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index e3221f72..2f7a8635 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -1,7 +1,7 @@ / di.torq.servers live-peer integration test helpers (loaded by test.csv). / recording mock deps + a genuinely separate spawned q peer: hopen to a port THIS process is / listening on returns a pseudo-handle 0 and never exercises real disconnect/retry/cleanup, so we -/ spawn a real peer (the licensed q via QHOME) to dial. +/ spawn a real peer to dial. / --- recording mock dependencies --- logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()); @@ -31,6 +31,7 @@ firejob:{[id] timerjobs[id][]}; / --- real peer process fixture --- FIXDIR:"/tmp/diserverstest"; +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe"; isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; pickport:{[start] first (start+til 500) where isfree each start+til 500}; PEERPORT:0N; DEADPORT:0N; PEERPID:0N; @@ -41,9 +42,9 @@ waitlisten:{[port;timeoutms] not isfree port}; spawnpeer:{[] - / launch the licensed q (via QHOME) as a detached listener; wait until it accepts connections, + / launch q as a detached listener; wait until it accepts connections, / then grab its pid over IPC (.z.i) for an exact-pid kill later. - system (getenv[`QHOME]),"/bin/q -p ",string[PEERPORT]," -q /dev/null 2>&1 &"; + system QBIN," -p ",string[PEERPORT]," -q /dev/null 2>&1 &"; if[not waitlisten[PEERPORT;3000];'"test: peer failed to listen on ",string PEERPORT]; h:hopen (`$":localhost:",string PEERPORT;2000); PEERPID::h ".z.i"; @@ -67,7 +68,6 @@ setupfixture:{[] teardownfixture:{[] killpeer[]; killdisc[]; system "rm -rf ",FIXDIR;}; / --- discovery-later fixture: a discovery stub naming one tpproc peer, started after startup --- -QBIN:first system "readlink -f /proc/",(string .z.i),"/exe"; DISCPORT:0N; TPPORT:0N; DISCPIDS:`long$(); / add a discovery row to process.csv, write the stub, and bind the .z.pc that addprocs calls From f6788a98fe6d6134b107f62173cfcc3a43c2472c Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 12:00:17 +0100 Subject: [PATCH 07/42] Accept TOML-style retry and discoveryretry settings di.torq.servers converts retry and discoveryretry from a timespan, a "0D00:00:10" string or a number of seconds. TOML has no timespan type, so these settings can now live in .toml files. New test rows fail on the previous code. The di.torq.servers half of c95ce2f from feature-torqx-poc-demo; the chainedtp half lives on feature-chainedtp. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 6 +++--- di/torq/servers/servers.q | 5 +++++ di/torq/servers/test.csv | 3 +++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index ea24d343..ed323166 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -35,10 +35,10 @@ supplies the discovery process's values. | `discoveryregister` | `.servers.DISCOVERYREGISTER` | `1b` | | `connectionsfromdiscovery` | `.servers.CONNECTIONSFROMDISCOVERY` | `1b` | | `subscribetodiscovery` | `.servers.SUBSCRIBETODISCOVERY` | `1b` | -| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05` | +| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | | `tracknontorqprocess` | `.servers.TRACKNONTORQPROCESS` | `0b` | | `hopentimeout` | `.servers.HOPENTIMEOUT` | `2000` | -| `retry` | `.servers.RETRY` | `0D00:05` | +| `retry` | `.servers.RETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | | `retain` | `.servers.RETAIN` | `` `long$0D00:30 `` | | `autoclean` | `.servers.AUTOCLEAN` | `0b` | | `debug` | `.servers.DEBUG` | `1b` | @@ -142,7 +142,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (43 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (46 checks) spawn real q peers. They cover: - init validation, wiring and idempotency; - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 87d1363e..243dfde7 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -32,6 +32,9 @@ raiseerror:{[ctx;msg] '"di.torq.servers: ",string[ctx],": ",msg; }; +/ a timespan, a "0D00:00:10" string or a number of seconds (TOML has no timespan type) +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + init:{[deps] / wire deps and config, publish the legacy root names, register the .z.pc observer and timer jobs once if[99h<>type deps; @@ -61,6 +64,8 @@ init:{[deps] @[value;`.servers.SERVERS;{set[`.servers.SERVERS;([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:())]}]; / trackservers.q l.13-28 {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; + .servers.RETRY:totimespan .servers.RETRY; + .servers.DISCOVERYRETRY:totimespan .servers.DISCOVERYRETRY; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; / dotz.q l.8 set[`.dotz.liveh;{x in key .z.W}]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 92e7fb70..b79bff4c 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -47,6 +47,9 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names +comment,,,,,,,retry periods from toml +run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds +true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection From 55caea08376bb7d87f9f26b76e744414583e4b26 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 12:43:04 +0100 Subject: [PATCH 08/42] Revert "Accept TOML-style retry and discoveryretry settings" This reverts commit f6788a9. Nothing in this repo sets retry or discoveryretry as a string or number, and it is outside this PR's scope. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 6 +++--- di/torq/servers/servers.q | 5 ----- di/torq/servers/test.csv | 3 --- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index ed323166..ea24d343 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -35,10 +35,10 @@ supplies the discovery process's values. | `discoveryregister` | `.servers.DISCOVERYREGISTER` | `1b` | | `connectionsfromdiscovery` | `.servers.CONNECTIONSFROMDISCOVERY` | `1b` | | `subscribetodiscovery` | `.servers.SUBSCRIBETODISCOVERY` | `1b` | -| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | +| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05` | | `tracknontorqprocess` | `.servers.TRACKNONTORQPROCESS` | `0b` | | `hopentimeout` | `.servers.HOPENTIMEOUT` | `2000` | -| `retry` | `.servers.RETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | +| `retry` | `.servers.RETRY` | `0D00:05` | | `retain` | `.servers.RETAIN` | `` `long$0D00:30 `` | | `autoclean` | `.servers.AUTOCLEAN` | `0b` | | `debug` | `.servers.DEBUG` | `1b` | @@ -142,7 +142,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (46 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (43 checks) spawn real q peers. They cover: - init validation, wiring and idempotency; - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 243dfde7..87d1363e 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -32,9 +32,6 @@ raiseerror:{[ctx;msg] '"di.torq.servers: ",string[ctx],": ",msg; }; -/ a timespan, a "0D00:00:10" string or a number of seconds (TOML has no timespan type) -totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; - init:{[deps] / wire deps and config, publish the legacy root names, register the .z.pc observer and timer jobs once if[99h<>type deps; @@ -64,8 +61,6 @@ init:{[deps] @[value;`.servers.SERVERS;{set[`.servers.SERVERS;([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:())]}]; / trackservers.q l.13-28 {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; - .servers.RETRY:totimespan .servers.RETRY; - .servers.DISCOVERYRETRY:totimespan .servers.DISCOVERYRETRY; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; / dotz.q l.8 set[`.dotz.liveh;{x in key .z.W}]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index b79bff4c..92e7fb70 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -47,9 +47,6 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names -comment,,,,,,,retry periods from toml -run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds -true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection From 48f48c77850aad1c1967bdfdd5ce8d6da1e39ec7 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 00:27:11 +0100 Subject: [PATCH 09/42] di.torq.servers 0.5.0: port the trackservers.q lines legacy .sub and chainedtp call At their legacy root names, as trackservers.q's own text in a \d .servers section: attributematch and the legacy 5-arg .servers.getservers (l.64-89), connectcustom (l.198, called from retryrows as l.184-185 does), reqprocsnotconn/reqprocnamesnotconn and startupdepcyclestypename/startupdepnamecycles (l.348-379). The exported 1-arg getservers is unchanged. enabled (l.12, default.q l.60) gates the discoveryretry/serversretry timer jobs as l.387 does. Conversions in startupdepcyclestypename: .servers.startup[] -> .servers.startup ()!(), .lg.e -> .z.m.logerr, .proc.procname -> init's identity, .os.sleep -> system "sleep ". Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/VERSION | 2 +- di/torq/servers/servers.md | 19 ++++++++--- di/torq/servers/servers.q | 61 ++++++++++++++++++++++++++++++++-- di/torq/servers/test.csv | 11 ++++++ di/torq/servers/test_enabled.q | 6 ++++ di/torq/settings/default.q | 1 + 6 files changed, 92 insertions(+), 8 deletions(-) create mode 100644 di/torq/servers/test_enabled.q diff --git a/di/torq/servers/VERSION b/di/torq/servers/VERSION index 1d0ba9ea..8f0916f7 100644 --- a/di/torq/servers/VERSION +++ b/di/torq/servers/VERSION @@ -1 +1 @@ -0.4.0 +0.5.0 diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index ea24d343..c72bf1b9 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -105,6 +105,16 @@ Published at root by `init`, same bodies as legacy: | `.servers.pc` | l.383, run on `.z.pc` | | timers `discoveryretry` / `serversretry` | l.387–389 | +Defined directly at root in a `\d .servers` section, for legacy `.sub` and chainedtp: + +| Name | trackservers.q | +|---|---| +| `.servers.attributematch` | l.64–68 | +| `.servers.getservers` (legacy 5-arg; the exported 1-arg `getservers` is separate) | l.75–89 | +| `.servers.connectcustom` (called by `retryrows`) | l.198 | +| `.servers.reqprocsnotconn` / `.servers.reqprocnamesnotconn` | l.348–351, l.357 | +| `.servers.startupdepcyclestypename` / `.servers.startupdepnamecycles` | l.360–373, l.379 | + The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, `startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to peers. Peers call discovery's root `register` (as `` `..register ``) and `getservices`. @@ -119,17 +129,18 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - `.proc.getconfigfile` becomes `nontorqprocessfile`. - In `querydiscovery`, the 5-arg `getservers[`proctype;`discovery;()!();0b;0b]` becomes its result: live discovery rows. +- In `startupdepcyclestypename`, `.servers.startup[]` becomes `.servers.startup ()!()` (the stored + globals), `.proc.procname` becomes init's identity, and `.os.sleep` becomes `system "sleep "`. **Not ported** (discovery does not reach them): - passwords (`loadpassword`, `USERPASS`, `PASSWORDS`, `LOADPASSWORD`); - `SOCKETTYPE`/FinSpace (so `formathp`'s ipctype is always `` `tcp `` from `formatprocs`/`addhw`, and `retryrows` dials `hpup`); -- the 5-arg `getservers`/`attributematch`/`getserverbytype`/`gethpbytype`; +- `getserverbytype`/`gethpbytype`; - `names`/`types`/`unregistered`/`checkw`/`reset`; -- the `connectcustom`/`addprocscustom` hooks; +- the `addprocscustom` hook; - `refreshattributes`; -- `startupdep*`; -- `enabled`. +- `reqproctypesnotconn`/`startupdepcycles`/`startupdependent`. **Legacy behaviour that differs from di.torq.servers 0.3.0:** - `startup` no longer excludes this process's own row. diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 87d1363e..39a514fa 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -7,7 +7,7 @@ self:`proctype`procname!``; / whether init has registered the .z.pc observer and timer jobs registered:0b; -/ trackservers.q l.13-28: flat config key -> (.servers global;trackservers default) +/ trackservers.q l.12-28: flat config key -> (.servers global;trackservers default) settings:`enabled`connections`discoveryregister`connectionsfromdiscovery`subscribetodiscovery`discoveryretry`tracknontorqprocess`hopentimeout`retry`retain`autoclean`debug`startup`discovery!( (`.servers.enabled;1b); (`.servers.CONNECTIONS;`); @@ -71,7 +71,7 @@ init:{[deps] if[not .z.m.registered; / trackservers.q l.385 (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; - / trackservers.q l.387-389 + / retry timers if[.servers.enabled; if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();`long$.servers.DISCOVERYRETRY%0D00:00:01;3;()!()]]; if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();`long$.servers.RETRY%0D00:00:01;3;()!()]]]; @@ -153,7 +153,9 @@ retryrows:{[rows] a:{$[not null x;@[x;({.proc.getattributes[]};::);()!()];()!()]}; handles:opencon each exec hpup from .servers.SERVERS where i in rows; update lastp:.z.p,w:handles from`.servers.SERVERS where i in rows; - update attributes:a each w,startp:?[null w;0Np;.z.p] from`.servers.SERVERS where i in rows;} + update attributes:a each w,startp:?[null w;0Np;.z.p] from`.servers.SERVERS where i in rows; + if[count connectedrows:select from`.servers.SERVERS where i in rows,.dotz.liveh0 w; + .servers.connectcustom[connectedrows]]} / close handles and remove rows from the table removerows:{[rows] @@ -340,3 +342,56 @@ getapimeta:{[] (`gethandlebytype; 1b; "one live handle for a proctype via any/roundrobin/last selection"; "[symbol: proctype; symbol: selection]"; "int: handle, 0Ni if none"); (`waitfortype; 1b; "block until a proctype connects or timeout elapses"; "[symbol: proctype; long: timeoutms; long: pollms]"; "boolean: 1b connected, 0b timed out")); }; + +/ trackservers.q l.64-89, 198, 348-379, at their legacy root names +\d .servers + +/ match required attributes against advertised ones +attributematch:{[req;avail] + vals:key[req] inter key avail; + notpresent:noval!(count noval:key[req] except key avail)#enlist(0b;()); + notpresent,vals!{($[0>type y;x~y;all x in y];(x,()) inter y,())}'[req vals;avail vals]} + +/ servers matching types or names, optionally reopening closed handles +getservers:{[nameortype;lookups;req;autoopen;onlyone] + r:$[`~lookups; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS; + nameortype~`proctype; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where proctype in lookups; + select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where procname in lookups]; + if[0=count r;:update attributematch:attributes from r]; + r:update alive:.dotz.liveh w from r; + if[autoopen; + if[(count r) > alivecount:sum r`alive; + if[(alivecount=0) or (not onlyone) or (any not exec max alive by agg:?[nameortype~`proctype;proctype;procname] from r); + retryrows exec index from r where not alive; + r:select procname,proctype,lastp,w,hpup,attributes,alive:.dotz.liveh w from .servers.SERVERS where i in r`index]]]; + select procname,proctype,lastp,w,hpup,attributes,attribmatch:.servers.attributematch[req]each attributes from r where alive} + +/ run on (re)connected SERVERS rows +connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}] + +/ are any required processes not connected +reqprocsnotconn:{[requiredprocs;typeorname] + not all requiredprocs in ?[`.servers.SERVERS;enlist (`.dotz.liveh;`w);();typeorname] + }; + +reqprocnamesnotconn:reqprocsnotconn[;`procname]; + +/ block until all required processes are connected +startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles] + n:1; + .servers.startup ()!(); + while[typeornamefunc requiredprocs; + if[n>cycles; + b:((),requiredprocs)except(),exec proctype from .servers.SERVERS where .dotz.liveh w; + .z.m.logerr[`connectionreport;s:string[.z.m.self`procname]," cannot connect to ",","sv string'[b]]; + 's; + ]; + system "sleep ",string timeintv; + n+:1; + .servers.startup ()!(); + ]; + }; + +startupdepnamecycles:startupdepcyclestypename[;.servers.reqprocnamesnotconn;;]; + +\d . diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 92e7fb70..cfefdeaf 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -17,6 +17,7 @@ true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retr true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use di.timer mode 3 (legacy .timer.repeat default mode 2 - next run from finish) true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled trackservers.q's discoveryretry job (DISCOVERYRETRY>0) true,0,0,q,.servers.enabled,1,1,enabled defaults to 1b +true,0,0,q,"0~first ""J""$system (getenv[`QHOME]),""/bin/q di/torq/servers/test_enabled.q -q""",1,1,enabled:0b schedules neither retry job run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,idempotent re-init did NOT add a second retry job true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,idempotent re-init did NOT re-register the pc handler @@ -35,8 +36,10 @@ run,0,0,q,"@[{h ""1+1""};();{[e]e}]",1,1,touch the dead handle so kdb+ drops it run,0,0,q,firejob[`serversretry],1,1,fire the retry job (reopens every row whose handle is not live) exactly as the timer would true,0,0,q,0=count svc.getservers[`otherproc],1,1,retry's failed reopen marked the dead connection as gone run,0,0,q,spawnpeer[],1,1,bring a fresh peer up on the same port +run,0,0,q,".servers.connectcustom:{[r] `ccrows set r}",1,1,record what retryrows passes to connectcustom run,0,0,q,firejob[`serversretry],1,1,fire retry again - should reconnect now a peer is listening true,0,0,q,1=count svc.getservers[`otherproc],1,1,retry reconnected to otherproc +true,0,0,q,(enlist`otherinst)~exec procname from ccrows,1,1,retryrows passed the reconnected row to .servers.connectcustom (trackservers.q l.184-185) comment,,,,,,,waitfortype - connected vs timeout true,0,0,q,svc.waitfortype[`otherproc;2000;200],1,1,returns 1b immediately for an already-connected proctype true,0,0,q,0b~svc.waitfortype[`deadproc;700;200],1,1,returns 0b on timeout for a proctype that never comes up @@ -47,6 +50,14 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names +comment,,,,,,,legacy trackservers.q l.12 64-89 348-379 at root .servers +true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values +true,0,0,q,"(enlist`otherproc)~exec proctype from .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,legacy 5-arg getservers returns the live row +true,0,0,q,"`attribmatch in cols .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,legacy getservers adds attribmatch +true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,legacy getservers drops dead rows +run,0,0,q,".servers.startupdepnamecycles[`otherinst;0;1]",1,1,startupdepnamecycles returns once otherinst is connected +fail,0,0,q,".servers.startupdepnamecycles[`nosuchinst;0;0]",1,1,startupdepnamecycles signals after its cycles are used up +true,0,0,q,`connectionreport in exec ctx from logrows where lvl=`error,1,1,the failure was logged as legacy's connectionreport error comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection diff --git a/di/torq/servers/test_enabled.q b/di/torq/servers/test_enabled.q new file mode 100644 index 00000000..cb4513cb --- /dev/null +++ b/di/torq/servers/test_enabled.q @@ -0,0 +1,6 @@ +/ enabled:0b registers no timer jobs (fresh process: init registers once) +svc:use`di.torq.servers +system "l di/torq/servers/test.q" +svc.init[svrdeps[`otherproc],enlist[`enabled]!enlist 0b] +-1 string count timercalls; +exit 0 diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index 4d5745f4..5b82f46a 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -8,6 +8,7 @@ discoveryretry:0D00:05 / how often to retry discovery; 0D means never discovery:enlist` / discovery services to use if not in process.csv / connections +enabled:1b / track servers hopentimeout:2000 / hopen timeout in milliseconds retry:0D00:05 / how often to retry dead connections; 0D means never tracknontorqprocess:1b / track and register non-TorQ processes From 0f2f1416e4653bdc39d5b83ad297b4831bc80c5a Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 00:36:53 +0100 Subject: [PATCH 10/42] di.torq.servers: querydiscovery calls the legacy 5-arg getservers (trackservers.q l.218) d04d8d4 inlined the result of getservers[`proctype;`discovery;()!();0b;0b] because the 5-arg function did not exist yet; 1a4ecfd ported it, so querydiscovery now makes legacy's own call (qualified as .servers.getservers - the bare name in the module is the exported 1-arg getservers). The matching deviation is dropped from servers.md. Co-Authored-By: Claude Opus 5.5 --- di/torq/servers/servers.md | 2 -- di/torq/servers/servers.q | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index c72bf1b9..0cc90305 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -127,8 +127,6 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - `.proc.procname`/`proctype` in `getdetails` become init's identity. - `.proc.readprocs` becomes `readprocesscsv`. - `.proc.getconfigfile` becomes `nontorqprocessfile`. -- In `querydiscovery`, the 5-arg `getservers[`proctype;`discovery;()!();0b;0b]` becomes its result: - live discovery rows. - In `startupdepcyclestypename`, `.servers.startup[]` becomes `.servers.startup ()!()` (the stored globals), `.proc.procname` becomes init's identity, and `.os.sleep` becomes `system "sleep "`. diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 39a514fa..de6eae93 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -175,7 +175,7 @@ register:{[connectiontab;proc;connect] querydiscovery:{[procs] if[0=count procs;:()]; .z.m.loginfo[`conn;"querying discovery services for processes of types "," " sv string procs,()]; - h:exec w from .servers.SERVERS where proctype=`discovery,.dotz.liveh w; + h:exec w from .servers.getservers[`proctype;`discovery;()!();0b;0b]; $[0=count h; [.z.m.loginfo[`conn;"no discovery services available"];()]; raze @[;(`getservices;procs;.servers.SUBSCRIBETODISCOVERY);()] each h]} From 67dd128680f8c5a5c034e95709480252d9225294 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 00:58:13 +0100 Subject: [PATCH 11/42] di.pubsub 0.2.0: port the legacy pubsub.q lines chainedtp uses Legacy TorQ code/common/pubsub.q, as its own text in a \d .stpps section at the end of pubsub.q, at its root names: .stpps state, suball/subfiltered/add/errparse/addfiltered/selfiltered/pub, delhandle/delhandlef/closesub/extractschema/init (l.9-124), root .u.sub (l.134-141) and .ps.loaded/publish/subscribe/init/initialise (l.147-151). It keeps its own state; the existing di.pubsub API and behaviour are unchanged. init takes an optional deps carrying log, used for legacy's .lg.e calls; init[] is unchanged. l.129's .z.pc binding is left to the consumer (closesub via handlers), as for di.pubsub's own. Not ported: .stpps.endp/end/pubclear/attrstrip, .u.pub, .ps.subtable*, .ds.*. Processes that load di.pubsub now carry root .stpps/.ps and a legacy .u.sub until they set their own; the tickerplant and segmentedtp set theirs after use. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/VERSION | 2 +- di/pubsub/pubsub.md | 20 ++++++++- di/pubsub/pubsub.q | 98 ++++++++++++++++++++++++++++++++++++++++++++- di/pubsub/test.csv | 25 ++++++++++++ 4 files changed, 142 insertions(+), 3 deletions(-) diff --git a/di/pubsub/VERSION b/di/pubsub/VERSION index 6e8bf73a..0ea3a944 100644 --- a/di/pubsub/VERSION +++ b/di/pubsub/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0 diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 1790411e..4303d533 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -81,6 +81,24 @@ q)pubsub.subscribestrfilter["quote";"bid>50.0";"time,sym,bid"] ## Notes: - By default, all tables on top level of the process are available for subscription. -- The user should define the `.u.sub` and the `.u.pub` functions within the process. +- Loading the module defines legacy TorQ's root `.u.sub` (see below); a process that wants its own `.u.sub`/`.u.pub` sets them after `use`. - The module initializes with defined list of tables to subscribe to and fetches their schemas and columns for use. This is done via calling `init` function. - The module does **not** bind `closesub` to `.z.pc` itself. A load-time `.z.pc` assignment from a `use`-loaded module replaces whatever the process had already bound - in a `di.torq` process that is the `di.torq.handlers` dispatcher carrying `di.torq.servers`' cleanup hook - so the consumer binds it: `handlers.register[`.z.pc;`;`pubsub;0;pubsub.closesub]` through its injected handlers dependency, or `.z.pc:pubsub.closesub` in a bare process. + +## Legacy TorQ pubsub.q layer + +Legacy `code/common/pubsub.q`, the part legacy chainedtp uses, in a `\d .stpps` section at the end of `pubsub.q`, at its root +names. It keeps its own state, separate from the API above: + +| Root name | pubsub.q | +|---|---| +| `.stpps.t` / `subrequestall` / `subrequestfiltered` | l.9–15 | +| `.stpps.allsubhandles` | l.28–30 | +| `.stpps.suball` / `subfiltered` / `add` / `errparse` / `addfiltered` / `selfiltered` / `pub` | l.33–83 | +| `.stpps.delhandle` / `delhandlef` / `closesub` / `extractschema` / `init` | l.92–124 | +| `.u.sub` | l.134–141 | +| `.ps.loaded` / `publish` / `subscribe` / `init` / `initialise` | l.147–151 | + +- `.lg.e` → the log passed as `init[enlist[`log]!enlist log]` (optional; `init[]` is unchanged). +- l.129 `.z.pc` → the consumer registers `.stpps.closesub` through its handlers dependency. +- Not ported: `.stpps.endp`/`end`/`pubclear`/`attrstrip`, `.u.pub`, `.ps.subtable*`, `.ds.*`. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 41993ffd..64de25f1 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -121,9 +121,105 @@ setsubtables`; initialized:0b; -init:{ +init:{[deps] + / optional deps: log for the legacy pubsub.q section + if[99h=type deps; + if[not `log in key deps;'"di.pubsub: log dependency is required - see di.util.log"]; + .z.m.log:deps`log]; .z.m.t:$[count subtables;subtables;tables[]except`reqfilteredtbl]; .z.m.schemas:t!extractschema each t; .z.m.tabcols:t!cols each t; if[count tabcols;.z.m.initialized:1b]; }; + +/ legacy TorQ pubsub.q (.stpps, .u.sub, .ps) at its root names +\d .stpps + +t:` +subrequestall:enlist[`]!enlist () +subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()) + +allsubhandles:{ + distinct raze union/[value subrequestall;exec handle from .stpps.subrequestfiltered] + }; + +suball:{ + delhandle[x;.z.w]; + add[x]; + :(x;schemas[x]); + }; + +subfiltered:{[x;y] + delhandlef[x;.z.w]; + val:![11 99h;(selfiltered;addfiltered)][type y] . (x;y); + $[all raze null val;(x;schemas[x]);val] + }; + +add:{ + if[not (count subrequestall x)>i:subrequestall[x]?.z.w; + subrequestall[x],:.z.w]; + }; + +errparse:{.z.m.log[`error][`addfiltered;m:y," error: ",x];'m}; + +addfiltered:{[x;y] + filters:$[all null f:y[x;`filters];();@[parse;"select from t where ",f;.stpps.errparse[;"Filter"]] 2]; + columns:last $[all null c:y[x;`columns];();@[parse;"select ",c," from t";.stpps.errparse[;"Column"]]]; + @[eval;(?;.stpps.schemas[x];filters;0b;columns);.stpps.errparse[;"Query"]]; + `.stpps.subrequestfiltered upsert (x;.z.w;filters;columns); + }; + +selfiltered:{[x;y] + filts:enlist enlist (in;`sym;enlist y); + @[eval;(?;.stpps.schemas[x];filts;0b;());.stpps.errparse[;"Query"]]; + `.stpps.subrequestfiltered upsert (x;.z.w;filts;()); + }; + +pub:{[t;x] + if[not count x;:()]; + if[count h:subrequestall[t];-25!(h;(`upd;t;x))]; + if[t in .stpps.subrequestfiltered`tbl; + {[t;x;sels] data:eval(?;x;sels`filts;0b;sels`columns); + if[count data;neg[sels`handle](`upd;t;data)]}[t;x;] + each select handle,filts,columns from .stpps.subrequestfiltered where tbl=t + ]; + }; + +delhandle:{[t;h] + @[`.stpps.subrequestall;t;except;h]; + }; + +delhandlef:{[t;h] + delete from `.stpps.subrequestfiltered where tbl=t,handle=h; + }; + +closesub:{[h] + delhandle[;h]each t; + delhandlef[;h]each t; + }; + +extractschema:{t:value x; $[.Q.qp t; t; 0#t]}; + +init:{[t] + if[count b:t where not t in tables[];{.z.m.log[`error][`psinit;m:"Table ",string[x]," does not exist"];'m} each b]; + .stpps.t:t except b; + .stpps.schemas:.stpps.t!extractschema each .stpps.t; + .stpps.tabcols:.stpps.t!cols each .stpps.t; + }; + +\d . + +.u.sub:{[x;y] + if[x~`;:.z.s[;y] each .stpps.t]; + if[not x in .stpps.t; + .z.m.log[`error][`sub;m:"Table ",string[x]," not in list of stp pub/sub tables"]; + :(x;m) + ]; + $[y~`;.stpps.suball[x];.stpps.subfiltered[x;y]] + }; + +.ps.loaded:1b; +.ps.publish:.stpps.pub; +.ps.subscribe:.u.sub; +.ps.init:.stpps.init; +.ps.initialise:{.ps.init[tables[]];.ps.initialised:1b}; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index 950d9e78..74fdb832 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -114,5 +114,30 @@ run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table=`quote",1,, run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription true,0,0,q,res[`filts][0]~enlist enlist(>;`bid;50f),1,, test symbols are listed under filters +comment,,,,,,,legacy pubsub.q layer at root .stpps/.u.sub/.ps +true,0,0,q,"h"".ps.loaded""",1,,.ps.loaded is set when the module loads +run,0,0,q,"h""pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m] `lastlog set (c;m)}]""",1,,wire a recording log through init's optional deps +fail,0,0,q,"h""pubsub.init[enlist[`x]!enlist 1]""",1,,init deps without log must error +run,0,0,q,"h"".ps.initialise[]""",1,,.ps.initialise registers every root table +true,0,0,q,"h"".ps.initialised""",1,,initialised flag set +true,0,0,q,"all `trade`quote in h"".stpps.t""",1,,trade and quote are pub/sub tables +run,0,0,q,"r:h(`.u.sub;`trade;`)",1,,legacy .u.sub for all trade syms +true,0,0,q,`trade~first r,1,,.u.sub returns the table name +true,0,0,q,98h~type last r,1,,and its schema +true,0,0,q,"clt in h"".stpps.subrequestall`trade""",1,,client registered in subrequestall +run,0,0,q,delete from `trade,1,,clear the local trade table +run,0,0,q,"h(`.ps.publish;`trade;ntrade)",1,,.ps.publish on the server +true,0,0,q,ntrade~trade,1,,client received exactly the published rows +run,0,0,q,"r:h(`.u.sub;`nosuch;`)",1,,subscribe to a table that is not published +true,0,0,q,`nosuch~first r,1,,.u.sub returns the table name +true,0,0,q,"(`sub;""Table nosuch not in list of stp pub/sub tables"")~h""lastlog""",1,,and logs the error through the injected log +run,0,0,q,"r:h(`.u.sub;`quote;enlist`IBM)",1,,legacy sym-filtered subscription (a sym list - as .sub.subscribe sends) +true,0,0,q,"clt in h""exec handle from .stpps.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered +true,0,0,q,"clt in h"".stpps.allsubhandles[]""",1,,allsubhandles includes the client +run,0,0,q,"h(`.stpps.closesub;clt)",1,,closesub for the client handle +true,0,0,q,"not clt in h"".stpps.allsubhandles[]""",1,,client removed from both registries +true,0,0,q,"""Table nosuchtable does not exist""~h""@[.stpps.init;enlist`nosuchtable;{x}]""",1,,init signals on a missing table +true,0,0,q,"(`psinit;""Table nosuchtable does not exist"")~h""lastlog""",1,,and logs it through the injected log + run,0,0,q,neg[h](exit;0);neg[h](::),1,,close background process and flush run,0,0,q,hclose h,1,,close handle From 1bb4af9d1492713cfc914cac03662d91a885f626 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 01:23:57 +0100 Subject: [PATCH 12/42] di.subscriptions 0.2.0: add .sub; trim comments across the chainedtp work di.subscriptions: TorQ code/common/subscriptions.q (l.5-166) as its own text in a \d .sub section at the end of subscriptions.q: SUBSCRIPTIONS, getsubscriptionhandles, updatesubscriptions, reducesubs, createtables, replay, subscribe (tptype handshake), replayupd, checksubscriptions, retrysubscription, autoreconnect, pc. The existing API is unchanged. init now requires timer and handlers, applies the autoreconnect/checksubscriptionperiod settings (default.q 0b / 0D00:00:10), and registers once per process, in every di.subscriptions user: .sub.pc on .z.pc and the checksubscriptions timer job. Deviations from TorQ's text: - .lg.o/.lg.e -> .z.m.log; .proc.cp[] -> .z.p. - .z.pc via handlers as the projection .sub.pc[::;] (an observer receives only the handle). - checksubscriptions: timespan period converted to seconds; TorQ mode 0 = di.timer mode 1. - the "timer not enabled" error branch is dropped (the timer is always injected). - once-only guard: a second init registers nothing, where TorQ's dupcheck throws. - deps.toml pins di.torq.servers 0.5.0 (.servers.getservers/enabled/connectcustom). Tests: a live check with a separate idle client and real handlers shows a peer's close marks the subscription inactive at once, with no checksubscriptions run; it fails if .sub.pc is registered bare. Comments: across servers, pubsub, discovery, settings and torq.q, comments are one line and no longer refer to TorQ sources or line numbers; test descriptions likewise. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/pubsub.md | 25 ++---- di/pubsub/pubsub.q | 4 +- di/pubsub/test.csv | 6 +- di/subscriptions/VERSION | 2 +- di/subscriptions/deps.toml | 1 + di/subscriptions/subscriptions.md | 22 ++++- di/subscriptions/subscriptions.q | 129 +++++++++++++++++++++++++++++ di/subscriptions/test.csv | 35 +++++++- di/subscriptions/test.q | 44 +++++++++- di/torq/proc/discovery/discovery.q | 6 +- di/torq/proc/discovery/test.csv | 20 ++--- di/torq/servers/servers.md | 11 +-- di/torq/servers/servers.q | 39 +++------ di/torq/servers/test.csv | 24 +++--- di/torq/servers/test.q | 2 +- di/torq/settings/default.q | 30 ++++--- di/torq/settings/discovery.q | 2 +- di/torq/settings/hdb.q | 2 +- di/torq/torq.q | 2 +- 19 files changed, 301 insertions(+), 105 deletions(-) diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 4303d533..1e8afe3c 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -81,24 +81,17 @@ q)pubsub.subscribestrfilter["quote";"bid>50.0";"time,sym,bid"] ## Notes: - By default, all tables on top level of the process are available for subscription. -- Loading the module defines legacy TorQ's root `.u.sub` (see below); a process that wants its own `.u.sub`/`.u.pub` sets them after `use`. +- Loading the module defines a root `.u.sub` (see below); a process that wants its own `.u.sub`/`.u.pub` sets them after `use`. - The module initializes with defined list of tables to subscribe to and fetches their schemas and columns for use. This is done via calling `init` function. - The module does **not** bind `closesub` to `.z.pc` itself. A load-time `.z.pc` assignment from a `use`-loaded module replaces whatever the process had already bound - in a `di.torq` process that is the `di.torq.handlers` dispatcher carrying `di.torq.servers`' cleanup hook - so the consumer binds it: `handlers.register[`.z.pc;`;`pubsub;0;pubsub.closesub]` through its injected handlers dependency, or `.z.pc:pubsub.closesub` in a bare process. -## Legacy TorQ pubsub.q layer +## `.stpps`, `.u.sub`, `.ps` -Legacy `code/common/pubsub.q`, the part legacy chainedtp uses, in a `\d .stpps` section at the end of `pubsub.q`, at its root -names. It keeps its own state, separate from the API above: +A second pub/sub API at root, in a `\d .stpps` section at the end of `pubsub.q`, with its own state, +separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `.stpps.allsubhandles`, +`suball`/`subfiltered`/`add`/`errparse`/`addfiltered`/`selfiltered`/`pub`, +`delhandle`/`delhandlef`/`closesub`/`extractschema`/`init`, root `.u.sub`, and +`.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`. -| Root name | pubsub.q | -|---|---| -| `.stpps.t` / `subrequestall` / `subrequestfiltered` | l.9–15 | -| `.stpps.allsubhandles` | l.28–30 | -| `.stpps.suball` / `subfiltered` / `add` / `errparse` / `addfiltered` / `selfiltered` / `pub` | l.33–83 | -| `.stpps.delhandle` / `delhandlef` / `closesub` / `extractschema` / `init` | l.92–124 | -| `.u.sub` | l.134–141 | -| `.ps.loaded` / `publish` / `subscribe` / `init` / `initialise` | l.147–151 | - -- `.lg.e` → the log passed as `init[enlist[`log]!enlist log]` (optional; `init[]` is unchanged). -- l.129 `.z.pc` → the consumer registers `.stpps.closesub` through its handlers dependency. -- Not ported: `.stpps.endp`/`end`/`pubclear`/`attrstrip`, `.u.pub`, `.ps.subtable*`, `.ds.*`. +- `init[enlist[`log]!enlist log]` wires its error logging (optional; `init[]` is unchanged). +- The consumer registers `.stpps.closesub` on `.z.pc` through its handlers dependency. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 64de25f1..625b6715 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -122,7 +122,7 @@ setsubtables`; initialized:0b; init:{[deps] - / optional deps: log for the legacy pubsub.q section + / optional deps: log if[99h=type deps; if[not `log in key deps;'"di.pubsub: log dependency is required - see di.util.log"]; .z.m.log:deps`log]; @@ -132,7 +132,7 @@ init:{[deps] if[count tabcols;.z.m.initialized:1b]; }; -/ legacy TorQ pubsub.q (.stpps, .u.sub, .ps) at its root names +/ .stpps, .u.sub, .ps \d .stpps t:` diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index 74fdb832..34979c3b 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -114,14 +114,14 @@ run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table=`quote",1,, run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription true,0,0,q,res[`filts][0]~enlist enlist(>;`bid;50f),1,, test symbols are listed under filters -comment,,,,,,,legacy pubsub.q layer at root .stpps/.u.sub/.ps +comment,,,,,,,root .stpps/.u.sub/.ps true,0,0,q,"h"".ps.loaded""",1,,.ps.loaded is set when the module loads run,0,0,q,"h""pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m] `lastlog set (c;m)}]""",1,,wire a recording log through init's optional deps fail,0,0,q,"h""pubsub.init[enlist[`x]!enlist 1]""",1,,init deps without log must error run,0,0,q,"h"".ps.initialise[]""",1,,.ps.initialise registers every root table true,0,0,q,"h"".ps.initialised""",1,,initialised flag set true,0,0,q,"all `trade`quote in h"".stpps.t""",1,,trade and quote are pub/sub tables -run,0,0,q,"r:h(`.u.sub;`trade;`)",1,,legacy .u.sub for all trade syms +run,0,0,q,"r:h(`.u.sub;`trade;`)",1,,.u.sub for all trade syms true,0,0,q,`trade~first r,1,,.u.sub returns the table name true,0,0,q,98h~type last r,1,,and its schema true,0,0,q,"clt in h"".stpps.subrequestall`trade""",1,,client registered in subrequestall @@ -131,7 +131,7 @@ true,0,0,q,ntrade~trade,1,,client received exactly the published rows run,0,0,q,"r:h(`.u.sub;`nosuch;`)",1,,subscribe to a table that is not published true,0,0,q,`nosuch~first r,1,,.u.sub returns the table name true,0,0,q,"(`sub;""Table nosuch not in list of stp pub/sub tables"")~h""lastlog""",1,,and logs the error through the injected log -run,0,0,q,"r:h(`.u.sub;`quote;enlist`IBM)",1,,legacy sym-filtered subscription (a sym list - as .sub.subscribe sends) +run,0,0,q,"r:h(`.u.sub;`quote;enlist`IBM)",1,,sym-filtered subscription (a sym list) true,0,0,q,"clt in h""exec handle from .stpps.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered true,0,0,q,"clt in h"".stpps.allsubhandles[]""",1,,allsubhandles includes the client run,0,0,q,"h(`.stpps.closesub;clt)",1,,closesub for the client handle diff --git a/di/subscriptions/VERSION b/di/subscriptions/VERSION index 6e8bf73a..0ea3a944 100644 --- a/di/subscriptions/VERSION +++ b/di/subscriptions/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0 diff --git a/di/subscriptions/deps.toml b/di/subscriptions/deps.toml index 249ffb7f..acb0fa54 100644 --- a/di/subscriptions/deps.toml +++ b/di/subscriptions/deps.toml @@ -1,3 +1,4 @@ # Peer modules di.subscriptions `use`s (see di/torq/depcheck/depcheck.md). [dependencies] "di.tplogmgr" = "0.1.0" +"di.torq.servers" = "0.5.0" # .sub calls its .servers.getservers/enabled/connectcustom diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 9d4d5cf5..95142638 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -10,14 +10,14 @@ classic standard-TP `.u.i`/`.u.L`/`.u.d` global reads. ## Dependency -`log` (required) — the injected di.torq logging dep. `init` also `use`s `di.tplogmgr` -(for the repair-aware, count-limited replay). +`log`, `timer` and `handlers` (required) — the injected di.torq deps. `init` also `use`s +`di.tplogmgr` (for the repair-aware, count-limited replay). ## Functions | Function | Description | |---|---| -| `init[config;deps]` | validate the `log` dep, stash it, load di.tplogmgr | +| `init[config;deps]` | validate the deps, stash `log`, load di.tplogmgr, apply the `.sub` settings, register `.sub.pc` and the `checksubscriptions` job (once) | | `subscribe[tph;tabs;syms;replay]` | subscribe over an open TP handle; returns the subdetails dict | | `subscribed[]` | `1b` if any subscription is active | | `getsubscriptions[]` | the active-subscriptions registry table | @@ -53,9 +53,23 @@ in di.tplogmgr's module context) lands in the module's *private* namespace, not `@[`.;t;…]`. A bare `upd:insert` would, under replay, insert into the wrong namespace and silently capture nothing. (Reads are safe: a bare `value t` falls through to root.) +## `.sub` + +A second subscription API at root `.sub`, in a `\d .sub` section at the end of `subscriptions.q`, with +its own state: `AUTORECONNECT`, `checksubscriptionperiod`, `SUBSCRIPTIONS`, `getsubscriptionhandles`, +`updatesubscriptions`, `reconnectinit`, `reducesubs`, `createtables`, `replay`, `subscribe`, +`replayupd`, `checksubscriptions`, `retrysubscription`, `autoreconnect`, `pc`. `subscribe` asks the +publisher for its `tptype` (`standard`, `chained` or `segmented`) and subscribes to match. It calls +`.servers.getservers`, `.servers.enabled` and `.servers.connectcustom` from `di.torq.servers` 0.5.0. + +- Settings (flat config): `autoreconnect` (default `0b`), `checksubscriptionperiod` (default `0D00:00:10`). +- `init` registers, once per process: `.sub.pc[::;]` on `.z.pc` through `handlers`, and + `checksubscriptions` every `checksubscriptionperiod` (converted to seconds, timer mode 1) through + `timer` when the period is above 0. + ## Not yet (future) -Auto-reconnect / resubscribe on TP bounce; filtered-**column** subscriptions; +Auto-reconnect / resubscribe on TP bounce (for the API above); filtered-**column** subscriptions; remote-log streaming (v1 assumes the subscriber shares the TP's filesystem to read the log — the classic tick assumption). diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 1b3d852f..30d15561 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -13,10 +13,22 @@ / registry of active subscriptions - for health checks now, reconnect later. SUBSCRIPTIONS:([]handle:`int$();tabs:();syms:();subtime:`timestamp$()) +/ .sub .z.pc handler and check job are registered once +registered:0b + init:{[config;deps] if[not `log in key deps;'"di.subscriptions: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.subscriptions: timer dependency is required - see di.timer"]; + if[not `handlers in key deps;'"di.subscriptions: handlers dependency is required - see di.torq.handlers"]; .z.m.log:deps`log; .z.m.tp:use`di.tplogmgr; / for replayupto (repair-aware, count-limited -11!) + / .sub settings + if[`autoreconnect in key config;.sub.AUTORECONNECT:config`autoreconnect]; + if[`checksubscriptionperiod in key config;.sub.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod]; + if[not .z.m.registered; + (deps[`handlers]`register)[`.z.pc;`;`sub;0j;.sub.pc[::;]]; + if[.sub.checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;.sub.checksubscriptions;();`long$.sub.checksubscriptionperiod%0D00:00:01;1;()!()]]; + .z.m.registered:1b]; } / filtering replay wrapper installed as root `upd` during log replay: forward only rows @@ -75,3 +87,120 @@ subscribed:{[] 0type first x;enlist c!x;flip c!x] where sym in syms; + f[t;x] + } + +checksubscriptions:{update active:0b from `.sub.SUBSCRIPTIONS where not w in key .z.W;} + +retrysubscription:{[row] + subscribe[row`table;$[((),`) ~ insts:row`instruments;`;insts];0b;0b;3#row]; + } + +autoreconnect:{[rows] + s:select from SUBSCRIPTIONS where ([]procname;proctype)in (select procname, proctype from rows), not active; + s:s lj 2!select procname,proctype,w from rows; + if[count s;.sub.retrysubscription each s]; + } + +pc:{[result;W] update active:0b from `.sub.SUBSCRIPTIONS where w=W;result} + +\d . diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index a77b4f77..c31534b1 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -4,8 +4,10 @@ before,0,0,q,system "l di/subscriptions/test.q",1,,load fixture helpers before,0,0,q,buildlog[4],1,,build a real 4-message tp log via di.tplogmgr fail,0,0,q,sub.init[()!();()!()],1,,init without the log dependency must error +fail,0,0,q,"sub.init[()!();`log`handlers!(mocklog[];mockhandlers)]",1,,init without the timer dependency must error +fail,0,0,q,"sub.init[()!();`log`timer!(mocklog[];mocktimer)]",1,,init without the handlers dependency must error -run,0,0,q,sub.init[()!();deps[]],1,,init with a mock log dependency +run,0,0,q,sub.init[()!();deps[]],1,,init with mock log/timer/handlers dependencies run,0,0,q,`upd set rootupd,1,,define the root-namespace-safe upd the replay drives - as di.rdb does run,0,0,q,@[`.;`trade;:;0#tradeschema[]],1,,ensure no stale trade table before subscribing run,0,0,q,sd:sub.subscribe[mocktph[4];`;`;1b],1,,subscribe all/all with replay over the mock TP handle @@ -21,4 +23,35 @@ run,0,0,q,sdf:sub.subscribe[mocktph[4];`;enlist`S1;1b],1,,subscribe with a sym f true,0,0,q,1=count trade,1,,replay filtered to the single subscribed sym true,0,0,q,`S1=first trade`sym,1,,the replayed row is the subscribed sym +comment,,,,,,,.sub at root +true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`sub",1,,init registered .sub.pc on .z.pc +true,0,0,q,"(enlist(`checksubscriptions;10;1))~flip value flip timercalls",1,,init registered checksubscriptions every 10s +run,0,0,q,sub.init[()!();deps[]],1,,init again +true,0,0,q,"(1;1)~(count handlercalls;count timercalls)",1,,second init registers nothing new +true,0,0,q,.sub.AUTORECONNECT,1,,AUTORECONNECT defaults to 1b +run,0,0,q,"sub.init[`autoreconnect`checksubscriptionperiod!(0b;0D00:00:30);deps[]]",1,,config sets the .sub settings +true,0,0,q,"(0b;0D00:00:30)~(.sub.AUTORECONNECT;.sub.checksubscriptionperiod)",1,,settings applied +run,0,0,q,spawnpeer[],1,,start a real chained-tickerplant peer +run,0,0,q,`trade set 0#tradeschema[],1,,reset the table +run,0,0,q,"r:.sub.subscribe[`trade;`;1b;1b;peerproc[]]",1,,subscribe through the tptype handshake +true,0,0,q,4=count trade,1,,schema set and the peer's 4 logged messages replayed +true,0,0,q,"(enlist`trade;D;4)~r`subtables`tplogdate`i",1,,returns subtables/tplogdate/i as a chained subscription +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,w=tph,active",1,,subscription recorded active +true,0,0,q,"99h=type .sub.subscribe[`trade;`;0b;0b;peerproc[]]",1,,a repeat all-syms subscription is not deduplicated (stored enlist` vs bare `) - it subscribes again +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade",1,,and the keyed upsert keeps one row +run,0,0,q,hclose tph,1,,drop the peer handle +run,0,0,q,.sub.checksubscriptions[],1,,run the check job +true,0,0,q,"not first exec active from .sub.SUBSCRIPTIONS where table=`trade",1,,the dropped subscription is marked inactive +run,0,0,q,"`tph set hopen (`$"":localhost:"",string PEERPORT;2000)",1,,reopen the peer handle +run,0,0,q,".sub.pc[::;tph]",1,,.sub.pc on a handle with no active subscription +run,0,0,q,"x:(`time`sym`price`size)!(2#.z.p;`S1`S2;1 2f;1 2i); .sub.replayupd[{[t;x] `got set x};`trade;enlist`S1;`trade;value x]",1,,replayupd with a sym filter +true,0,0,q,`S1~first got`sym,1,,replayupd kept only the subscribed sym +true,0,0,q,1=count got,1,,and only one row +run,0,0,q,".servers.getservers:{[nt;l;a;o;one] ([]procname:enlist`ctp1;proctype:enlist`chainedtp;w:enlist 5i)}",1,,stub the servers lookup this suite does not load +true,0,0,q,"(enlist`ctp1)~exec procname from .sub.getsubscriptionhandles[`;`ctp1;()!()]",1,,getsubscriptionhandles resolves a procname through .servers.getservers +run,0,0,q,".servers.enabled:1b;.servers.connectcustom:{[r]};.sub.AUTORECONNECT:1b;.sub.reconnectinit:0b",1,,autoreconnect on with server tracking enabled +run,0,0,q,".sub.subscribe[`trade;`;0b;0b;peerproc[]]",1,,subscribe +true,0,0,q,.sub.reconnectinit,1,,subscribe wrapped .servers.connectcustom for autoreconnect once +true,0,0,q,10b~pcclosecheck[],1,,closing a subscribed handle marks it inactive through .z.pc at once (no checksubscriptions run) + after,0,0,q,teardownfixture[],1,,remove the temp log dir diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index dad2081f..7267302b 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -14,7 +14,11 @@ calls:([]lvl:`symbol$();ctx:`symbol$();msg:()) resetcalls:{[] `calls set ([]lvl:`symbol$();ctx:`symbol$();msg:()); } mocklogfn:{[lvl;ctx;msg] `calls insert (lvl;ctx;msg); } mocklog:{[] `info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;])} -deps:{[] enlist[`log]!enlist mocklog[]} +timercalls:([]id:`symbol$();period:`long$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;`long$period;`long$mode);} +handlercalls:([]event:`symbol$();name:`symbol$()) +mockhandlers:enlist[`register]!enlist {[ev;ph;nm;pri;fn] `handlercalls upsert (ev;nm);} +deps:{[] `log`timer`handlers!(mocklog[];mocktimer;mockhandlers)} / the trade schema a TP would return (g# on sym, as di.torq.proc.tickerplant applies) tradeschema:{[] ([]time:`timestamp$();sym:`g#`symbol$();price:`float$();size:`int$())} @@ -39,4 +43,40 @@ buildlog:{[n] / referencing the real log + the given rowcount mocktph:{[n] {[n;msg] `tables`schemas`logfile`rowcount`date!(enlist`trade;(enlist`trade)!enlist tradeschema[];LOGFILE;n;D)}[n]} -teardownfixture:{[] system "rm -rf ",BASE; } +/ a real peer answering .sub.subscribe as a chained tickerplant, over the real log above +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" +isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} +PEERPORT:0N; tph:0N +spawnpeer:{[] + (`$":",BASE,"/peer.q") 0: ( + "tptype:`chained"; + "tablelist:{enlist`trade}"; + "subdetails:{[t;s] `schemalist`logfilelist`rowcounts`date!(enlist(`trade;([]time:`timestamp$();sym:`g#`symbol$();price:`float$();size:`int$()));enlist(4;",(-3!LOGFILE),");(enlist`trade)!enlist 4;",(string D),")}"); + `PEERPORT set first p where isfree each p:30000+(`int$.z.i mod 20000)+til 500; + system QBIN," ",BASE,"/peer.q -p ",(string PEERPORT)," -q /dev/null 2>&1 &"; + d:.z.p+0D00:00:03; while[(.z.p/dev/null 2>&1 &"; + d:.z.p+0D00:00:03; while[(.z.p (.servers global;trackservers default) +/ flat config key -> (.servers global;default) settings:`enabled`connections`discoveryregister`connectionsfromdiscovery`subscribetodiscovery`discoveryretry`tracknontorqprocess`hopentimeout`retry`retain`autoclean`debug`startup`discovery!( (`.servers.enabled;1b); (`.servers.CONNECTIONS;`); @@ -33,7 +33,7 @@ raiseerror:{[ctx;msg] }; init:{[deps] - / wire deps and config, publish the legacy root names, register the .z.pc observer and timer jobs once + / wire deps and config, publish root names, register .z.pc and retry timers once if[99h<>type deps; '"di.torq.servers: deps must be a dict of injectables + config"]; if[not all `log`timer`handlers in key deps; @@ -57,19 +57,19 @@ init:{[deps] .z.m.handlers:deps`handlers; .z.m.self:`proctype`procname!deps`proctype`procname; .z.m.processcsv:$[`processcsv in key deps;deps`processcsv;""]; - / trackservers.q l.10 + / registry @[value;`.servers.SERVERS;{set[`.servers.SERVERS;([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:())]}]; - / trackservers.q l.13-28 + / config {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; - / dotz.q l.8 + / live-handle checks set[`.dotz.liveh;{x in key .z.W}]; set[`.dotz.livehn;{x in 0Ni,key .z.W}]; set[`.dotz.liveh0;{x in 0i,key .z.W}]; pub:`opencon`cleanup`addnthawc`getdetails`addhw`addw`retry`retrydiscovery`autodiscovery`retryrows`removerows`register`querydiscovery`registerfromdiscovery`addprocs`procupdate`domainsocketsenabled`formathp`formatprocs`startup`pc!(opencon;cleanup;addnthawc;getdetails;addhw;addw;retry;retrydiscovery;autodiscovery;retryrows;removerows;register;querydiscovery;registerfromdiscovery;addprocs;procupdate;domainsocketsenabled;formathp;formatprocs;startup;pc); set'[` sv/:`.servers,/:key pub;value pub]; if[not .z.m.registered; - / trackservers.q l.385 + / .z.pc (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; / retry timers if[.servers.enabled; @@ -117,13 +117,11 @@ getdetails:{(.z.f;.z.h;system"p";.z.m.self`procname;.z.m.self`proctype;@[value;( / add session behind a handle addhw:{[hpuP;W] - / Get the information around a process info:`f`h`port`procname`proctype`attributes!(@[W;({$[`getdetails in key`.servers;.servers.getdetails[];(.z.f;.z.h;system"p";`;`;$[`getattributes in key`.proc;.proc.getattributes[];()!()])]};`);(`;`;0Ni;`;`;()!())]); if[0Ni~info`port;'"remote call failed on handle ",string W]; if[null name:info`procname;name:`$last("/"vs string info`f)except enlist""]; if[0=count name;name:`default]; if[null hpuP;hpuP:formathp[info`h;info`port;`tcp;info`proctype;info`procname]]; - / If this handle already has an entry, delete the old entry delete from `.servers.SERVERS where w=W; addnthawc[name;info`proctype;hpuP;info`attributes;W;0b]} @@ -136,7 +134,6 @@ retrydiscovery:{ if[count d:exec i from `.servers.SERVERS where proctype=`discovery,not ({any .dotz.liveh0 x};w) fby hpup, i=(first;i) fby hpup; .z.m.loginfo[`conn;"attempting to connect to discovery services"]; retryrows d; - / register with the newly opened discovery services if[.servers.DISCOVERYREGISTER and count h:exec w from .servers.SERVERS[d] where .dotz.liveh w; .z.m.loginfo[`conn;"registering with discovery services"]; @[;(`..register;`);()] each neg h]; @@ -149,7 +146,6 @@ autodiscovery:{if[.servers.DISCOVERYRETRY>0; .servers.retrydiscovery[]]} / Attempt to make a connection for specified row ids retryrows:{[rows] - / a returns the remote .proc.getattributes[] for a live handle, else an empty dict a:{$[not null x;@[x;({.proc.getattributes[]};::);()!()];()!()]}; handles:opencon each exec hpup from .servers.SERVERS where i in rows; update lastp:.z.p,w:handles from`.servers.SERVERS where i in rows; @@ -166,12 +162,10 @@ removerows:{[rows] / Create some connections and optionally connect to them register:{[connectiontab;proc;connect] {addnthawc[x`procname;x`proctype;x`hpup;()!();0Ni;0b]}each distinct select from connectiontab where proctype=proc; - / automatically connect if[connect; $[`discovery=proc;retrydiscovery[];retry[]]]}; -/ Query a discovery service, and get the list of available services -/ Does not attempt to re-open any discovery services +/ services from the live discovery services querydiscovery:{[procs] if[0=count procs;:()]; .z.m.loginfo[`conn;"querying discovery services for processes of types "," " sv string procs,()]; @@ -186,18 +180,14 @@ registerfromdiscovery:{[procs;connect] .z.m.loginfo[`conn;"requesting processes from discovery service"]; res:querydiscovery[procs]; if[0=count res; .z.m.loginfo[`conn;"no processes found"]; :()]; - / add the processes addprocs[res;procs;connect];} addprocs:{[connectiontab;procs;connect] connectiontab:formatprocs[delete split from update host:hpup^`$last each -1 _' split, port:"I"$last each split from update split:{":" vs string x}each hpup from connectiontab]; - / filter out any we already have - same name,type and hpup res:select from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS; - / we've dropped some items - maybe there are updated attributes if[not count[res]=count connectiontab; if[`attributes in cols connectiontab; .servers.SERVERS:.servers.SERVERS lj 3!select procname,proctype,hpup,attributes from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS]]; - / if we have a match where the hpup is the same, but different name/type, then remove the old details removerows exec i from `.servers.SERVERS where hpup in exec hpup from res; register[res;;connect] each $[procs~`ALL;exec distinct proctype from res;procs,()];} @@ -206,9 +196,7 @@ procupdate:{[procs] addprocs[procs;exec distinct proctype from procs;0b];} / return true if unix domain sockets can be used domainsocketsenabled:{[] - / unix domain sockets only works on unix and not windows notwin:not .z.o like "w*"; - / v3.4 brought in the first version of unix domain sockets ipc iskdbv:3.4<=.z.K; :notwin and iskdbv; } @@ -220,7 +208,6 @@ formathp:{[HOST;PORT;IPCTYPE;PROCTYPE;PROCNAME] notsamebox:not any HOST in `localhost,.z.h; host:string $[HOST=`localhost;.z.h;HOST]; port:string PORT; - / revert socket to tcp if[isunixsocket and notsamebox; .z.m.logwarn[`formathp;"Expects to connect via domain sockets, but host is not on the same machine. Reverting IPC mechanism to TCP"]; ipctype:`tcp; @@ -229,7 +216,6 @@ formathp:{[HOST;PORT;IPCTYPE;PROCTYPE;PROCNAME] .z.m.logwarn[`formathp;"Domain sockets are not enabled for this system. Reverting IPC mechanism from to TCP"]; ipctype:`tcp; ]; - / Format hpup file handle if[ipctype = `tcp; hpup:lower `$":",host,":",port; ]; @@ -249,31 +235,26 @@ formatprocs:{[PROCS] :procs; } -/ called at start up; config`connections and config`processcsv replace .servers.CONNECTIONS and .proc.file +/ called at start up; config`connections and config`processcsv give the connections and process file startup:{[config] if[`connections in key config; .servers.CONNECTIONS:$[11h=abs type c:config`connections;c;`$c]]; pf:$[`processcsv in key config;config`processcsv;.z.m.processcsv]; - / correctly format procs and hpup .servers.procstab:procs:formatprocs readprocesscsv pf; .servers.nontorqprocesstab:formatprocs $[count key .servers.NONTORQPROCESSFILE;readprocesscsv 1_string .servers.NONTORQPROCESSFILE;0#procs]; - / If DISCOVERY servers have been explicity defined if[count .servers.DISCOVERY; if[not null first .servers.DISCOVERY; if[count select from procs where hpup in .servers.DISCOVERY; .z.m.logerr[`startup; "host:port in .servers.DISCOVERY list is already present in data read from ",pf]]; procs,:([]host:`;port:0Ni;proctype:`discovery;procname:`;hpup:.servers.DISCOVERY)]]; - / Remove any processes that have an active connection connectedprocs:select procname, proctype, hpup from .servers.SERVERS; procs:delete from procs where ([] procname; proctype; hpup) in connectedprocs; nontorqprocs:delete from .servers.nontorqprocesstab where ([] procname; proctype; hpup) in connectedprocs; - / if there aren't any processes left to connect to, then escape if[not any count each (procs;nontorqprocs); .z.m.loginfo[`conn;"No new processes to connect to. Escaping..."];:()]; if[.servers.CONNECTIONSFROMDISCOVERY or .servers.DISCOVERYREGISTER; register[procs;`discovery;0b]; retrydiscovery[]]; if[not .servers.CONNECTIONSFROMDISCOVERY; register[procs;;0b] each $[.servers.CONNECTIONS~`ALL;exec distinct proctype from procs;.servers.CONNECTIONS]]; if[.servers.TRACKNONTORQPROCESS;register[nontorqprocs;;0b] each $[.servers.CONNECTIONS~`ALL;exec distinct proctype from nontorqprocs;.servers.CONNECTIONS]]; - / try and open dead connections retry[]} pc:{[W] update w:0Ni,endp:.z.p from`.servers.SERVERS where w=W;cleanup[];} @@ -343,7 +324,7 @@ getapimeta:{[] (`waitfortype; 1b; "block until a proctype connects or timeout elapses"; "[symbol: proctype; long: timeoutms; long: pollms]"; "boolean: 1b connected, 0b timed out")); }; -/ trackservers.q l.64-89, 198, 348-379, at their legacy root names +/ root .servers functions for .sub and startup waits \d .servers / match required attributes against advertised ones diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index cfefdeaf..73f89c16 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -13,9 +13,9 @@ comment,,,,,,,init - wiring and idempotency run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,init with mock deps + config (dial otherproc and deadproc) true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,init registered its .z.pc observer via the handlers dep true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init scheduled the retry job via the timer dep -true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is trackservers.q's RETRY 0D00:05 in seconds (di.timer period unit) -true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use di.timer mode 3 (legacy .timer.repeat default mode 2 - next run from finish) -true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled trackservers.q's discoveryretry job (DISCOVERYRETRY>0) +true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is 300s +true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use timer mode 3 +true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled the discoveryretry job true,0,0,q,.servers.enabled,1,1,enabled defaults to 1b true,0,0,q,"0~first ""J""$system (getenv[`QHOME]),""/bin/q di/torq/servers/test_enabled.q -q""",1,1,enabled:0b schedules neither retry job run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent @@ -39,10 +39,18 @@ run,0,0,q,spawnpeer[],1,1,bring a fresh peer up on the same port run,0,0,q,".servers.connectcustom:{[r] `ccrows set r}",1,1,record what retryrows passes to connectcustom run,0,0,q,firejob[`serversretry],1,1,fire retry again - should reconnect now a peer is listening true,0,0,q,1=count svc.getservers[`otherproc],1,1,retry reconnected to otherproc -true,0,0,q,(enlist`otherinst)~exec procname from ccrows,1,1,retryrows passed the reconnected row to .servers.connectcustom (trackservers.q l.184-185) +true,0,0,q,(enlist`otherinst)~exec procname from ccrows,1,1,retryrows passed the reconnected row to .servers.connectcustom comment,,,,,,,waitfortype - connected vs timeout true,0,0,q,svc.waitfortype[`otherproc;2000;200],1,1,returns 1b immediately for an already-connected proctype true,0,0,q,0b~svc.waitfortype[`deadproc;700;200],1,1,returns 0b on timeout for a proctype that never comes up +comment,,,,,,,root .servers functions +true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values +true,0,0,q,"(enlist`otherproc)~exec proctype from .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,5-arg getservers returns the live row +true,0,0,q,"`attribmatch in cols .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,getservers adds attribmatch +true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,getservers drops dead rows +run,0,0,q,".servers.startupdepnamecycles[`otherinst;0;1]",1,1,startupdepnamecycles returns once otherinst is connected +fail,0,0,q,".servers.startupdepnamecycles[`nosuchinst;0;0]",1,1,startupdepnamecycles signals after its cycles are used up +true,0,0,q,`connectionreport in exec ctx from logrows where lvl=`error,1,1,the failure was logged as a connectionreport error comment,,,,,,,waitfortype - discovery comes up after startup run,0,0,q,setupdisc[],1,1,add a discovery row to process.csv and write a discovery stub naming a tpproc peer run,0,0,q,"svc.init[svrdeps[`tpproc],`discoveryregister`connectionsfromdiscovery!11b]",1,1,re-init taking connections from discovery @@ -50,14 +58,6 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names -comment,,,,,,,legacy trackservers.q l.12 64-89 348-379 at root .servers -true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values -true,0,0,q,"(enlist`otherproc)~exec proctype from .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,legacy 5-arg getservers returns the live row -true,0,0,q,"`attribmatch in cols .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,legacy getservers adds attribmatch -true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,legacy getservers drops dead rows -run,0,0,q,".servers.startupdepnamecycles[`otherinst;0;1]",1,1,startupdepnamecycles returns once otherinst is connected -fail,0,0,q,".servers.startupdepnamecycles[`nosuchinst;0;0]",1,1,startupdepnamecycles signals after its cycles are used up -true,0,0,q,`connectionreport in exec ctx from logrows where lvl=`error,1,1,the failure was logged as legacy's connectionreport error comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 2f7a8635..8ecf42be 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -92,5 +92,5 @@ spawndisc:{[] spawnq["";TPPORT]; spawnq[FIXDIR,"/disc.q";DISCPORT];}; killdisc:{[] {@[system;"kill ",string x;{}]} each DISCPIDS; DISCPIDS::`long$();}; / build the deps dict di.torq would assemble: injectables + this process's config slice. -/ discovery off, so startup dials process.csv directly (trackservers.q's own defaults are 1b). +/ discovery off, so startup dials process.csv directly svrdeps:{[conns] `log`timer`handlers`proctype`procname`connections`processcsv`discoveryregister`connectionsfromdiscovery!(mocklog;mocktimer;mockhandlers;`selfproc;`selfinst;conns;FIXDIR,"/process.csv";0b;0b)}; diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index 5b82f46a..2d51a959 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1,19 +1,23 @@ -/ built-in framework defaults: the .servers settings +/ built-in framework defaults: the .servers and .sub settings / discovery - off unless the app turns it on -discoveryregister:0b / register with the discovery service -connectionsfromdiscovery:0b / get connection details from discovery, not process.csv -subscribetodiscovery:1b / subscribe to discovery for new processes -discoveryretry:0D00:05 / how often to retry discovery; 0D means never -discovery:enlist` / discovery services to use if not in process.csv +discoveryregister:0b / register with the discovery service +connectionsfromdiscovery:0b / get connection details from discovery, not process.csv +subscribetodiscovery:1b / subscribe to discovery for new processes +discoveryretry:0D00:05 / how often to retry discovery; 0D means never +discovery:enlist` / discovery services to use if not in process.csv / connections -enabled:1b / track servers -hopentimeout:2000 / hopen timeout in milliseconds -retry:0D00:05 / how often to retry dead connections; 0D means never -tracknontorqprocess:1b / track and register non-TorQ processes -debug:0b / log each connection attempt +enabled:1b / track servers +hopentimeout:2000 / hopen timeout in milliseconds +retry:0D00:05 / how often to retry dead connections; 0D means never +tracknontorqprocess:1b / track and register non-TorQ processes +debug:0b / log each connection attempt / server records -retain:`long$0D00:30 / how long to keep a closed server's record -autoclean:0b / drop expired records when a connection closes +retain:`long$0D00:30 / how long to keep a closed server's record +autoclean:0b / drop expired records when a connection closes + +/ subscriptions +autoreconnect:0b / resubscribe to processes previously subscribed to +checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never diff --git a/di/torq/settings/discovery.q b/di/torq/settings/discovery.q index 70bfaade..c197cb20 100644 --- a/di/torq/settings/discovery.q +++ b/di/torq/settings/discovery.q @@ -1,4 +1,4 @@ -/ Bespoke config for the discovery service - legacy TorQ config/settings/discovery.q (flat keys) +/ discovery service settings / list of connections to make at start up connections:`ALL / whether to register with the discovery service diff --git a/di/torq/settings/hdb.q b/di/torq/settings/hdb.q index a01fc1c0..8ea92b07 100644 --- a/di/torq/settings/hdb.q +++ b/di/torq/settings/hdb.q @@ -1,3 +1,3 @@ dir:`:hdb -/ create connections (legacy config/settings/hdb.q) +/ create connections startup:1b diff --git a/di/torq/torq.q b/di/torq/torq.q index 08018019..781a61a0 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -294,7 +294,7 @@ init:{[proctype;procname;overrides] / module init (so it can reference the module's tables/state) and BEFORE runhook (so an / app file may define/override ..run for the hook to pick up). loadappcode[logdep;config;proctype;procname]; - / initialise connections (legacy torq.q l.673) + / initialise connections if[@[value;`.servers.STARTUP;0b];.servers.startup config]; / optional query logging - a no-op unless [querylog] enabled=true. LAST of everything that binds .z.*, because / di.querylog wraps whatever is bound at this moment by direct assignment (see initquerylog / torq.md) From ca1b0c210005d79f7a2ecd5873ff50cef94fdaa1 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 01:29:09 +0100 Subject: [PATCH 13/42] di.torq: initialise pubsub at startup; chainedtp settings torq.q runs .ps.initialise[] when .ps.loaded is set, directly before the STARTUP line, as TorQ's torq.q l.670-673 does. Processes that load di.pubsub (tickerplant, segmentedtp) now fill the .stpps state at startup; nothing in them reads it. settings/chainedtp.q: TorQ's config/settings/chainedtp.q as flat keys (tickerplantname, pubinterval, tpconnsleep, createlogfile, logdir, subscribeto, subscribesyms, replay, schema, clearlogonsubscription, tpcheckcycles, connections, startup). Its .hb/.usage lines are not carried: di has no heartbeat reader, and [querylog] is already off unless enabled. Co-Authored-By: Claude Opus 5.5 --- di/torq/settings/chainedtp.q | 27 +++++++++++++++++++++++++++ di/torq/torq.q | 2 ++ 2 files changed, 29 insertions(+) create mode 100644 di/torq/settings/chainedtp.q diff --git a/di/torq/settings/chainedtp.q b/di/torq/settings/chainedtp.q new file mode 100644 index 00000000..902689d3 --- /dev/null +++ b/di/torq/settings/chainedtp.q @@ -0,0 +1,27 @@ +/ chained tickerplant settings +/ tickerplant names to try and make a connection to +tickerplantname:`tickerplant1 +/ publish batch updates at this interval, 0D00:00:00 for tick by tick +pubinterval:0D00:00:00 +/ seconds between attempts to connect to the source tickerplant +tpconnsleep:10 +/ create a log file +createlogfile:0b +/ directory containing tp logs +logdir:`:tplogs +/ tables to subscribe for +subscribeto:` +/ syms to subscribe to +subscribesyms:` +/ replay the tickerplant log file +replay:0b +/ retrieve schema from tickerplant +schema:1b +/ clear logfile on subscription +clearlogonsubscription:0b +/ number of times to check for an available tickerplant +tpcheckcycles:0W +/ connections to make at start up +connections:`tickerplant +/ create connections +startup:1b diff --git a/di/torq/torq.q b/di/torq/torq.q index 781a61a0..ddf205c7 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -294,6 +294,8 @@ init:{[proctype;procname;overrides] / module init (so it can reference the module's tables/state) and BEFORE runhook (so an / app file may define/override ..run for the hook to pick up). loadappcode[logdep;config;proctype;procname]; + / initialise pubsub + if[@[value;`.ps.loaded;0b];.ps.initialise[]]; / initialise connections if[@[value;`.servers.STARTUP;0b];.servers.startup config]; / optional query logging - a no-op unless [querylog] enabled=true. LAST of everything that binds .z.*, because From 77594ad7c8afa04479a09b9395299d8d4e40768a Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 01:40:43 +0100 Subject: [PATCH 14/42] di.torq.proc.chainedtp 0.2.0: rebuild as TorQ's chainedtp.q The module is rebuilt from TorQ's code/processes/chainedtp.q, as its own text in TorQ's order: root tptype/tablelist/subdetails; the .ctp settings and state; clearlog, openlog, subscribe, writetolog, tickpub, batchpub, publishalltables, tableschemas, cleartables, createlogfilename, refreshtp, notpconnected, sub; and .u.end. init runs TorQ's load-time statements in order (l.155 .z.pc, l.160 .ctp.upd, l.194 root upd, l.197 .ps.initialise, l.200 startupdepnamecycles, l.203 subscribe, l.206 tableschemas, l.209 batch timer), after wiring di.pubsub, di.subscriptions and .stpps.closesub as TorQ's common-code loading does. The previous module and its integration tests are removed. Deviations from TorQ's text: - .lg.o/.lg.e -> .z.m.log; .proc.procname -> config's procname. - l.155 .dotz.set on .z.pc -> a handlers observer taking only the handle (logs, then exit 0). - l.194 root upd:.ctp.upd -> set[`upd;.ctp.upd]. - l.209 .timer.rep -> timer addjob, period in seconds, TorQ mode 1h = di.timer mode 2. TorQ's timer runs sub-second; di.timer's period is whole seconds, so a pubinterval that is not a whole number of seconds fails init rather than rounding. - the .ctp setting guards stay as written; init applies config values over them. Kept as TorQ has it: a corrupt own log is reported and opened anyway; upd is set only if absent; tpcheckcycles 0W waits for the upstream indefinitely; only .u.end is defined, so a segmented upstream (which sends endofday) never ends the day here; .u.icounts values are one-item lists after an all-syms subscribe. Tests: a real upstream (segmented surface, found through di.torq.servers) and a real downstream: subscribe and schema, tick-by-tick delivery, subdetails, tablelist, .u.end, the own log, batch publish, clearlogonsubscription, a corrupt log, and pubinterval validation. Live: discovery -> segmentedtp -> chainedtp -> a .sub subscriber; data reached the subscriber; .u.end, invoked by hand on the chainedtp (the segmented upstream never sends it), reached the subscriber and rolled the date; stopping the upstream made the chainedtp log and exit. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/VERSION | 2 +- di/torq/proc/chainedtp/chainedtp.md | 364 ++-------- di/torq/proc/chainedtp/chainedtp.q | 630 +++++------------ di/torq/proc/chainedtp/deps.toml | 6 +- di/torq/proc/chainedtp/init.q | 2 +- di/torq/proc/chainedtp/test.csv | 131 ++-- di/torq/proc/chainedtp/test.q | 644 ++---------------- di/torq/proc/chainedtp/test_integration.csv | 28 - di/torq/proc/chainedtp/test_integration.q | 424 ------------ di/torq/proc/chainedtp/test_integration_ctp.q | 31 - di/torq/proc/chainedtp/test_integration_rdb.q | 28 - di/torq/proc/chainedtp/test_integration_tp.q | 21 - di/torq/proc/chainedtp/test_upstream.q | 16 - 13 files changed, 324 insertions(+), 2003 deletions(-) delete mode 100644 di/torq/proc/chainedtp/test_integration.csv delete mode 100644 di/torq/proc/chainedtp/test_integration.q delete mode 100644 di/torq/proc/chainedtp/test_integration_ctp.q delete mode 100644 di/torq/proc/chainedtp/test_integration_rdb.q delete mode 100644 di/torq/proc/chainedtp/test_integration_tp.q delete mode 100644 di/torq/proc/chainedtp/test_upstream.q diff --git a/di/torq/proc/chainedtp/VERSION b/di/torq/proc/chainedtp/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/torq/proc/chainedtp/VERSION +++ b/di/torq/proc/chainedtp/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index bde08ded..8b687299 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -1,313 +1,67 @@ # di.torq.proc.chainedtp -The chained tickerplant: a **subscriber** to an upstream tickerplant (as `di.torq.proc.rdb` is, through -`di.subscriptions` over a handle from the injected `di.torq.servers`) that re-presents itself to its own -subscribers as a **tickerplant** — the same root surface `di.torq.proc.tickerplant` publishes, in the -same two publish modes, with an optional log of its own that a downstream can replay from. It lets a tick -chain fan out through an intermediate hop, or bridge a tickerplant across a process or network boundary, -instead of every consumer dialling the origin. It is the TorqX process type for TorQ's `chainedtp` -proctype, built from `TorQ/code/processes/chainedtp.q` and `config/settings/chainedtp.q` onto the -`di.torq` process-module conventions. - -It follows the upstream's date rather than computing one: the date arrives with the subscription and -advances when the upstream ends its day. It therefore has no `di.eodtime` and no schema file of its -own — the tables it relays are whatever the upstream's `.u.subdetails` returns. - -| Dependency | Kind | Role | -| --- | --- | --- | -| `log` | injected | `` `info`warn`error ``, each `{[ctx;msg]}` — required | -| `timer` | injected | `` `addjob`deletejobs `` (di.timer contract) — required; used only in batched mode, but required unconditionally, as `di.torq` injects all four into every process | -| `handlers` | injected | `` `register`remove `` (di.torq.handlers contract) — required; the `.z.pc` registrations | -| `servers` | injected | `` `startup`gethandlebytype`waitfortype `` (di.torq.servers contract) — required; dials and waits for the upstream | -| `di.subscriptions` | `use` | the single `.u.subdetails` call that registers for live delivery and defines the tables at root | -| `di.pubsub` | `use` | subscribe / publish / end-of-day broadcast to this process's own subscribers | -| `di.tplogmgr` | `use` | `write` and `replayupto` only — the own log is named, opened, counted and rolled here (see the design record) | - -`deps.toml` declares all three `use`d modules at `0.1.0`. - ---- - -## Config - -`init[config;deps]` — the merged settings dict from `di.torq`'s cascade. Values may be symbols (`.q` -settings), strings (`.toml`, command-line overrides) or numbers; each is coerced where it is read -(booleans accept `1b`/`0b`, `"true"`/`"false"`, `"1"`/`"0"`; integers accept numbers or numeric -strings — strings are parsed, never cast). - -| Key | Default | Notes | -| --- | --- | --- | -| `upstreamtype` | **required** | the **proctype** of the tickerplant to subscribe to, e.g. `` `tickerplant `` (or another `chainedtp` - see Known gaps). No name-based option: `di.torq.servers` looks up by proctype only | -| `subscribeto` | `` ` `` | tables to subscribe to; `` ` `` for all | -| `subscribesyms` | `` ` `` | syms to subscribe to; `` ` `` for all | -| `replay` | `0b` | replay the upstream's log on subscribe, into the own log (and, in batched mode, the buffer) | -| `clearlogonsubscription` | `0b` | truncate the own log on (re)subscribe. Pair it with `replay` — a replay onto a log that already holds the day's messages appends them again (logged at `warn`) | -| `tplogdir` | absent = no log | the own log's directory, relative to `TORQXDATAHOME` (falls back to `TORQXAPPHOME`) or absolute. **Presence is the switch**, as `di.torq.proc.tickerplant`; an empty value is absence | -| `publishmode` | `` `immediate `` | `immediate` (publish every update as it arrives) or `batched` (buffer at root, flush on a timer), exactly `di.torq.proc.tickerplant`'s fork | -| `pubperiod` | `1` | batched only: flush period in **seconds** (di.timer's unit) | -| `connecttimeoutms` / `connectpollms` | `10000` / `500` | passed straight to `di.torq.servers.waitfortype`; a timeout fails `init` naming the proctype | -| `logprefix` | the process name | the own log is `/_` — TorQ named it `_`, and `di.torq` stamps `procname` into every config, so two chained tickerplants sharing a directory, or one sharing its upstream's, cannot write the same file. `"chainedtp"` only when no `procname` is in the config; an empty value is rejected | -| `proctype` / `procname` | stamped by `di.torq` | identity; `procname` names the log | - -`publishmode` is a dispatch key, so an unrecognised value fails `init` naming the setting; so do a -non-positive `pubperiod`, `connecttimeoutms` or `connectpollms`. - -Deliberately absent, versus TorQ's `.ctp` settings: `tickerplantname` (proctype-keyed lookup only), -`tpconnsleep`/`tpcheckcycles` (`di.torq.servers.waitfortype` owns the retry loop), `schema` (the tables -always come from the upstream's `.u.subdetails` — there is nothing to toggle), `createlogfile`/`logdir` -(folded into `tplogdir`), `pubinterval` (`publishmode`/`pubperiod`). - -```toml -# appconfig/settings/chainedtp.toml -upstreamtype = "tickerplant" -tplogdir = "ctplog" -publishmode = "immediate" -replay = true -clearlogonsubscription = true -``` - ---- - -## Initialisation - -```q -ctp:use`di.torq.proc.chainedtp -ctp.init[`upstreamtype`tplogdir!(`tickerplant;"ctplog");`log`timer`handlers`servers!(logdep;timerdep;handlersdep;serversdep)] -``` - -`di.torq` does this for a `chainedtp` proctype (`di.torq.builtin`). `init`: - -1. validates the four deps (plain signals — nothing is wired yet), tears down a previous successful - `init`, and releases anything a previous *failed* `init` left behind (the log handle, the flush job, - the `.z.pc` registrations — removals are no-ops when absent); -2. reads and validates every setting; -3. loads `di.pubsub`, `di.subscriptions` and `di.tplogmgr`, and registers `di.pubsub`'s `closesub` on - `.z.pc` through `handlers` (name `` `pubsub ``); -4. publishes the root IPC surface: `upd`, `.u.upd`, `.u.sub`, `.u.subdetails`, `endofday`, `.u.end`; -5. dials the upstream: `servers.startup` with `connections` = the upstream proctype (skipped when an - earlier `init`'s handle is still live), `waitfortype`, `gethandlebytype`; -6. registers its own `.z.pc` handler (name `` `chainedtp ``) — before subscribing, so an upstream lost - during the subscription is seen; -7. subscribes: **one** `.u.subdetails` call through `di.subscriptions.subscribe` with replay **off**, - which registers this process for live delivery and defines the subscribed tables at root; the date - and the table list come back with it. `connected[]` is true from here, and the root surface is live; -8. initialises `di.pubsub` on those tables; -9. opens the own log for that date (cleared first when `clearlogonsubscription`), counting — never - executing — whatever it already holds; -10. if `replay` and the upstream had logged anything: replays the upstream's log through root `upd` - itself, count-limited to the `rowcount` the subscription reported (`di.tplogmgr.replayupto`), with - a table/sym filter installed for a narrowed subscription — so every replayed message lands in the - own log; -11. schedules the flush job `` `chainedtp `` every `pubperiod` seconds in batched mode; -12. sets its initialised flag as the **literal last statement**, so a throw anywhere above leaves the - module uninitialised and a retry runs a full `init`. - -Steps 8–11 run under a protected apply: the root surface goes live at step 7 (the upstream may already be -sending), so a failure after it — an unwritable `tplogdir`, a corrupt upstream log — takes the surface down -again (`connected[]` `0b`, `upd` signals) rather than leaving a half-initialised process relaying with no -log and no flush job. The retry is a full `init`. - -Every exported function except `init`, `getapimeta` and `version` signals if called before `init`; the -root surface signals until the subscription exists. All post-`init` errors are logged at `error` before -being signalled. - ---- - -## Exported functions - -| Function | Description | -| --- | --- | -| `init[config;deps]` | see above | -| `upd[t;x]` | what the upstream publishes and what its log replays (also root `upd` / `.u.upd`): `t` one table symbol (or its string — a symbol list is rejected), `x` a table or a list of columns, already timestamped by the upstream. Written to the own log, then published (immediate) or buffered at root (batched). A publish that throws (a subscriber gone without `.z.pc` firing) is logged at `error` and signalled rather than lost in the async handler | -| `connected[]` | is the upstream subscription live — `1b` once subscribed, `0b` after the upstream connection closes or `teardown`. Backed by module state: `di.subscriptions`' registry tracks no disconnects (TorQ's `notpconnected` read `.sub.SUBSCRIPTIONS where active`; there is no `active` column now) | -| `getcounts[]` | `` `msgcount`date`tables `` — messages in the own log for the current date, the date, and per-table `rowcount` (published) and `pendingrowcount` (in the unflushed batch) | -| `teardown[]` | flush, close the own log, remove the flush job and the module's own `.z.pc` registration. `di.pubsub`'s `closesub` registration is deliberately left in place — a subscriber leaving between a teardown and the next init would otherwise stay registered and the first publish after that init would throw on its dead handle. The upstream subscription itself cannot be withdrawn (no protocol for it) and the socket stays with `di.torq.servers` | -| `getapimeta[]` | api metadata for `di.torq` to register with `di.api` (callable functions only) | -| `version` | the `VERSION` file's contents | - -`sub`/`subdetails`/`endofday` are not exported: they exist only as the root surface below. - ---- - -## The surface offered to this process's own subscribers - -Structurally identical to `di.torq.proc.tickerplant`'s, so `di.torq.proc.rdb` (via `di.subscriptions`) -subscribes to a chained tickerplant exactly as it would to the origin, without knowing the difference: - -| Root name | Description | -| --- | --- | -| `upd` / `.u.upd` | the feed entry point — here fed by the upstream's publishes and log replay rather than a feed | -| `.u.sub[tabs;syms]` | `di.pubsub.subscribe` | -| `.u.subdetails[tabs;syms]` | registers the caller and returns `` `tables`schemas`logfile`rowcount`date `` — `logfile` is the own log (`` ` `` without one), `rowcount` the messages it holds, `date` the upstream's date. In batched mode the buffer is **flushed first**, to the subscribers that already exist: the new one replays those rows from the log, so its replay count never includes a row it would also receive in the next flush (`di.torq.proc.tickerplant` had that double-delivery; fixed alongside this module) | -| `endofday[d]` / `.u.end[d]` | what the upstream sends at its end of day (`di.pubsub.callendofday`'s `` (`endofday;d) ``): flush, `callendofday[d]` to this process's own subscribers — so the chain chains — then roll the own log into `d+1` and follow the date. A `d` **later** than the current date is followed with a `warn`; a `d` **earlier** than it — a day already ended — is ignored with a `warn` (rolling into `d+1` would reopen an older log and move the date backwards, and re-broadcasting would make every subscriber save that day down twice); a non-date is rejected | - -Note `endofday` here is **monadic** (`[d]`, what a subscriber receives) where `di.torq.proc.tickerplant`'s -is niladic (its own roll). The names match; the arity follows the direction of the call. - ---- - -## Connection loss - -The `.z.pc` handler, registered through `handlers` as a simple event alongside `di.torq.servers`' own -cleanup hook and `di.pubsub`'s `closesub`, checks whether the closed handle is the upstream's. If it is: -the loss is logged at `error`, `connected[]` flips to `0b`, and the process **exits with code 0**. - -This is deliberate, not a bare port of TorQ's `exit 0`: nothing in the current stack resubscribes a -bounced tickerplant — `di.subscriptions` lists auto-reconnect/resubscribe under *not yet*, and while -`di.torq.servers`' retry job would reopen the socket, nothing would call `di.subscriptions.subscribe` -on it again. A process that stayed up would be silently disconnected for good. Under a process -supervisor (`torqx.sh` / systemd, restart-on-exit) a clean `exit 0` — an expected, handled condition — -is the right signal. If `di.subscriptions` gains reconnect support, revisit this. The exit goes through -an internal `exitfn` so the tests can observe it without leaving. - ---- - -## Design record - -### Verified against the current modules, not assumed - -- `di.subscriptions.subscribe[tph;tabs;syms;replay]` always calls `` tph(`.u.subdetails;tabs;syms) `` — - no `tptype` branching, no `tablelist` — so legacy's `tptype`/`tablelist` exports have nothing to - serve and are gone. This process only has to present the same root surface the origin does. -- `di.torq.servers` is proctype-keyed throughout (`getservers`/`gethandlebytype`/`waitfortype`), hence - `upstreamtype`, and its `waitfortype` replaces the `tpconnsleep`/`tpcheckcycles` retry loop. -- `di.subscriptions.SUBSCRIPTIONS` has no `active` column and no disconnect tracking, hence - `connected[]` is backed by module state. -- `di.pubsub` has no `getsubtables`; `setsubtables` + `init` are called after the subscription has - defined the tables at root. - -### Why the log is opened before the replay, and the replay is driven here - -The own log must be open — for the upstream's date — before any replayed message reaches `upd`, or -that history never lands in it and no downstream can replay it from this process (TorQ's `refreshtp` -opened the log first, reading the upstream's `.u.d` directly). `di.torq.proc.tickerplant` publishes no -root `.u.d`; the date only comes back inside `.u.subdetails`, and `di.subscriptions.subscribe` replays -inside that same call. Calling `.u.subdetails` twice would register twice and double-process live ticks -arriving between the calls (a sync call services queued async messages on its handle). So `subscribe` -is called with replay off, the log is opened for the returned date, and the replay is then driven here -with `di.tplogmgr.replayupto` — count-limited to the reported `rowcount`, since live delivery has -already started, and filtered for a narrowed subscription (the upstream log holds every table and sym, -as `di.subscriptions`' own private `replayfilter` handles for an rdb). The filter is a private mirror of -that function — a second instance, after segmentedtp, of `di.subscriptions`' replay machinery being -needed but not exported (see *Findings*). - -`upd` treats a log that is not yet open as a skip, never a throw: under single-threaded input no tick -can reach it between the subscription and the log open (`init` runs as one block against the event -loop), but di.torq.handlers documents multithreaded input (a negative `-p`) as a real exception, and the -window costs nothing to close. The integration suite feeds ticks before, during and after the process -starts and asserts every one reaches the own log exactly once. - -### Why log handling is self-implemented on top of `di.tplogmgr.write` - -`di.tplogmgr.open` replays an existing log through root `upd` — right for a tickerplant restoring its -buffer, wrong here, where `upd` **publishes**: a restart would republish the day. The own log is -therefore **counted** on open (`-11!(-2;file)`, which streams without executing) and only appended to. -It is also named `_`, not `tp`, so it cannot collide with an upstream's log in a -shared directory. Rolling is a close and an open of the next date. - -Corruption is handled as `di.torq.proc.segmentedtp` handles it, not with `di.tplogmgr`'s re-exported -`check`/`repair`: `di.tplog.repair`'s byte signature is hardcoded to `` `trade `` messages, so it would -silently drop every other table — and this process relays whatever it was subscribed to. The good -prefix is copied to `.good` in bounded chunks, the original is left untouched, the recovery is -logged at `warn`, and later starts keep using the `.good`. TorQ's `openlog` had no recovery at all (a -corrupt log was fatal). - -### The batched buffer is appended in place, by name - -The buffer is a root table appended with `t insert x` — a runtime symbol, which resolves to the root -table from this module's private namespace and under `-11!` replay alike; only *source-level* names are -rewritten module-local (the unit suite drives both paths and asserts the rows land at root). The -`@[`.;t;{tab upsert …}]` idiom `di.torq.proc.rdb` uses is root-safe too, but it copies the whole buffer on -every update: measured on this build, 20k single-row updates took 242ms and 40k 878ms (quadratic), against -14ms by name. For a buffer holding a whole `pubperiod` of a busy feed that matters; the integration suite's -`volume` scenario pushes 2,000 ten-row batches through each mode. - -### Batched-mode replay count - -`.u.subdetails` flushes the batched buffer *before* registering the caller. `di.torq.proc.tickerplant` -counts a message the moment it is logged, so a subscriber arriving while rows sit in the buffer replays -them from the log and then receives them again in the next flush; flushing first (to the existing -subscribers only) keeps the count exact without pending counters. Building this exposed the same -double-delivery in `di.torq.proc.tickerplant`'s own batched mode (its `upd` logs before it buffers and its -`subdetails` registered the caller without flushing); it is fixed there the same way, with a test. - -### Other divergences from TorQ's `chainedtp.q` - -- Payloads are normalised to vector columns before logging and publishing, so a single record and a - batch take one path and a replayed message is always column-list form (what a narrowed replay filter - indexes). -- An update for a table not in the subscription is rejected (logged, signalled) rather than inserted - blind; the upstream only ever sends subscribed tables. -- `.u.end` propagates `di.pubsub.callendofday[d]` — `` (`endofday;d) `` — the message - `di.torq.proc.rdb` expects, rather than legacy's `` (`.u.end;d) ``. -- The `.z.pc` registration coexists with `di.torq.servers`' in `di.torq.handlers`' fan-out instead of - wrapping the previous handler by hand. This required `di.pubsub` to stop assigning `.z.pc` itself at - load (which replaced the dispatcher — and `di.torq.servers`' hook — in every process that loaded it): - consumers now register `closesub` through `handlers`, as this module, `di.torq.proc.tickerplant` and - `di.torq.proc.segmentedtp` do. -- No FinSpace paths, no `.api.add` (api metadata is `getapimeta[]`). - ---- - -## Findings outside this module (flagged, not fixed here) - -- **`di.tplogmgr.replayupto` repairs a corrupt log with `di.tplog.repair`**, whose message signature is - hardcoded to `` `trade ``; every subscriber replaying a multi-table log through `di.subscriptions` - is exposed to silent non-trade message loss on corruption. The fix is generalising `di.tplog`'s - byte-signature scan — standalone work on a shared module. -- **`di.subscriptions`' replay machinery (`replayfilter`/`runreplay`/`doreplay`) is private.** Both - `di.torq.proc.segmentedtp` and this module needed private variants of pieces of it; worth exporting - or factoring. -- `di/torq/torq.md` still describes the `builtin` registry as holding one entry. -- `di.torq.proc.tickerplant.subdetails` assumes `di.pubsub.subscribe` returned cleanly: for a request - naming a table it does not have, pubsub returns `(errmsg;(tables;schemas))` and the tickerplant's - `tables` becomes the error symbol. `di.torq.proc.segmentedtp` and this module unpack that shape. -- `di.pubsub.publish` sends with `-25!` to every all-data subscriber at once; one dead handle (a subscriber - that vanished before `.z.pc` ran) fails the send for all of them. This module logs and signals it; it - cannot prune the handle, as pubsub's registry is private. -- On this build `0#` keeps `` `g# `` on an empty table but drops it once the table has held rows, so - `di.pubsub.pubclear`'s `0#` strips the attribute from a batched buffer after its first flush. Harmless for - a transient buffer (schemas are captured at `init`, while the tables are empty), noted in case a consumer - ever derives a schema from a live buffer. - -## Known gaps - -- No resubscribe path (hence `exit 0` on upstream loss); no unsubscribe on `teardown`. -- One upstream: if `process.csv` holds several processes of `upstreamtype`, `gethandlebytype[…;`any]` picks - one at random and only that connection is watched. -- Multithreaded input (a negative `-p`) is untested; the no-log-yet skip in `upd` is the only concession - to it. -- `replay` without `tplogdir` is harmless but pointless: nothing is retained for a downstream to replay. -- Only `` `tickerplant ``-shaped upstreams (a `.u.subdetails` returning `` `tables`schemas`logfile`rowcount`date ``) - are supported — `di.torq.proc.tickerplant`, or another chained tickerplant. `di.torq.proc.segmentedtp`'s - `subdetails` returns a different dict, as `di.subscriptions` does not yet speak it either. - ---- - -## Running tests - -**Unit suite** (`test.csv` + `test.q`, 56 checks): mock log, timer, handlers and servers, with the servers -mock handing out a genuine IPC handle to a stub upstream (`test_upstream.q`, spawned as a separate -process) that answers `.u.subdetails` from a fixture log. Real `di.pubsub`, `di.subscriptions` and -`di.tplogmgr`. Run from the repo root in a fresh session: +A chained tickerplant. It subscribes to an upstream tickerplant through `.sub`, optionally writes +what it receives to a log of its own, and republishes to its own subscribers, tick by tick or in +batches. + +## Surface + +| Name | What | +|---|---| +| `tptype` | `` `chained `` | +| `tablelist[]` | the published tables (`.stpps.t`) | +| `subdetails[tabs;instruments]` | subscribes the caller and returns `schemalist`, `logfilelist`, `rowcounts`, `date` | +| `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`.u.end;d) `` to subscribers | +| `upd` | set at root to `.ctp.upd` if no `upd` exists | +| `.ctp.*` | settings, `subscribe`, `writetolog`, `tickpub`, `batchpub`, `publishalltables`, `cleartables`, `openlog`, `clearlog`, `refreshtp`, `createlogfilename`, `notpconnected`, `sub` | +| `.u.i`/`.u.j`/`.u.icounts`/`.u.jcounts`/`.u.L`/`.u.l`/`.u.d` | publish and log counts, log file and handle, date | + +## Settings + +`di/torq/settings/chainedtp.q` (flat config): + +| Key | Default | +|---|---| +| `tickerplantname` | `` `tickerplant1 `` — procname(s) of the upstream | +| `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer | +| `tpconnsleep` / `tpcheckcycles` | `10` / `0W` — seconds between, and number of, upstream checks | +| `createlogfile` / `logdir` / `clearlogonsubscription` | `0b` / `` `:tplogs `` / `0b` — log file `/_` | +| `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms | +| `replay` / `schema` | `0b` / `1b` | +| `connections` / `startup` | `` `tickerplant `` / `1b` | + +## init[config;deps] + +Requires `log`, `timer` and `handlers`. It initialises `di.pubsub` (with the log) and +`di.subscriptions`, registers `.stpps.closesub` on `.z.pc`, applies the settings, then: + +1. registers a `.z.pc` observer that logs and exits 0 when the upstream handle closes; +2. sets `.ctp.upd` from `createlogfile`/`pubinterval`, and root `upd` if absent; +3. `.ps.initialise[]`; +4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; +5. `.ctp.subscribe[]`; +6. builds `.ctp.tableschemas`; +7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). + +di.torq runs `.ps.initialise[]` again after the module loads, which publishes the subscribed tables. + +## Behaviour to know + +- The upstream is found by procname through `di.torq.servers` (with the default settings, through + discovery). With `tpcheckcycles` `0W` it waits for it indefinitely. +- An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. +- A corrupt own log is reported and opened anyway. +- `.u.icounts` values are one-item lists after an all-syms subscribe. +- `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. + +## Testing ```q k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.chainedtp ``` -**Integration suite** (`test_integration.csv` + `test_integration.q`, 10 scenarios): real child -`di.torq.proc.tickerplant`, `di.torq.proc.chainedtp` and `di.torq.proc.rdb` processes wired to `di.timer`, -`di.torq.handlers`, `di.util.log` and `di.torq.servers`, with the test session as a downstream subscriber -— relay, exactly-once across a replaying start, 2,000-batch volume in each mode, the real timer's batched -flush, a narrowed subscription, a **real rdb** replaying from the chained tp through `di.subscriptions` then -following live and ending its day on the chained broadcast, a **chain of two** chained tickerplants, end of -day through the chain, a `kill -9` of the upstream (exit code 0 observed), and a real `di.torq` boot of both -process types through `torqx_init.q`. Children run the same kdb-x binary as -the session and are killed by the `after` row; `moduletest` only loads `test.csv`, so run this directly: - -```q -k4unit:use`di.k4unit -.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.torq.proc.chainedtp;`test_integration.csv] -.m.di.0k4unit.KUrt[] -k4unit.getresults[] -``` +`test.q`/`test.csv` run a real upstream (segmented tickerplant surface, found through +`di.torq.servers`) and a real downstream subscriber: subscribe and schema, tick-by-tick delivery, +`subdetails`, `tablelist`, `.u.end`, the own log, batch publish, `clearlogonsubscription`, and a +corrupt log. diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 2b562174..0913eeae 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -1,476 +1,162 @@ -/ di.torq.proc.chainedtp - chained tickerplant. Subscribes to an upstream tickerplant (as di.torq.proc.rdb does, via -/ di.subscriptions over a handle from the injected di.torq.servers), optionally writes what it receives to a log of its -/ own, and re-presents itself to its own subscribers as a tickerplant (the same root surface as di.torq.proc.tickerplant: -/ upd, .u.upd, .u.sub, .u.subdetails, endofday, .u.end) in immediate or batched publish mode. It follows the upstream's -/ date rather than computing one: the date arrives with the subscription and advances when the upstream ends its day. -/ Built from TorQ/code/processes/chainedtp.q onto the di.torq process-module conventions; the divergences from the -/ legacy process are recorded in chainedtp.md. Hard deps: di.pubsub, di.subscriptions, di.tplogmgr (write only - the -/ log is named, opened and rolled here, because di.tplogmgr.open replays through upd, which would republish). -/ Injected deps: log, timer, handlers, servers - all required. - -/ --- constants --- - -jobid:`chainedtp; / the flush timer job and the .z.pc handler name -pubmodes:`immediate`batched; -copychunk:8388608; / bytes per read when copying a corrupt log's good prefix - -/ --- module state read before init has run (everything else is written by init) --- - -initdone:0b; / the exported api may be called -ready:0b; / the root surface may be called (set once subscribed, before init completes) -logwired:0b; -upstreamup:0b; / what connected[] reports -logh:0i; -logname:`; -msgcount:0; -tph:0Ni; -exitfn:{[code] exit code}; / how the .z.pc handler leaves the process; replaced by the tests - -/ --- shared helpers (as di.torq.proc.segmentedtp) --- - -/ base dirs: CODE/CONFIG under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falling back to TORQXAPPHOME) -datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]}; - -/ resolve a possibly-relative dir setting to an absolute path STRING under base; symbol (.q) or string (.toml) input -resolvedir:{[base;dir] - dir:$[10h=abs type dir;dir;string dir]; - dir:$[(0type first x;enlist each x;x] - }; - -/ shell-quote a path for system calls (mkdir / mv) -shq:{[p] "\"",p,"\""}; - -raiseerror:{[ctx;msg] - / log (once a logger is wired) then signal, so failures are observable as well as thrown - if[.z.m.logwired;.z.m.log[`error][ctx;msg]]; - '"di.torq.proc.chainedtp: ",(string ctx),": ",msg; - }; - -requireinit:{[ctx] - if[not .z.m.initdone;raiseerror[ctx;"init must be called before any other function"]]; - }; - -requireready:{[ctx] - / the root surface is live from the moment the upstream subscription exists - upstream replay drives upd before - / init has completed - and dead again after teardown - if[not .z.m.ready;raiseerror[ctx;"init must be called before any other function"]]; - }; - -/ --- own log: one file per date, /_, as TorQ's chainedtp named it --- - -lognamefor:{[d] hsym `$.z.m.tplogdir,"/",.z.m.logprefix,"_",string d}; - -goodname:{[ln] `$(string ln),".good"}; - -/ a log recovered on an earlier start lives on as .good - keep using it rather than the corrupt original -resolvelog:{[ln] $[type key g:goodname ln;g;ln]}; - -clearlog:{[ln] - / truncate an existing log (clearlogonsubscription): the upstream replay rebuilds it - if[not type key ln;:()]; - .z.m.log[`info][`clearlog;"clearing log ",1_string ln]; - .[ln;();:;()]; - }; - -openfile:{[ln] - / hopen a log, creating it if absent. an existing log is COUNTED first without executing it (executing it would - / republish every message), and a corrupt one is never opened blind - its good prefix is copied to .good and - / that is opened. returns (name;handle;message count) - if[not type key ln;.[ln;();:;()]]; - / a zero-byte file (a crash between create and header write) is safely re-headed; a file shorter than the 8-byte - / header, or one -11!(-2;..) cannot read at all, holds no recoverable message - recover it as an empty log - if[0=hcount ln;.[ln;();:;()]]; - info:@[-11!;(-2;ln);{0 0}]; - if[1info 1;.[tmp;();:;()];copyprefix[ln;tmp;info 1]]; - system "mv -f ",(shq 1_string tmp)," ",shq 1_string g; - .z.m.log[`warn][`openlog;"corrupt log ",(1_string ln),": kept ",(string info 0)," good message(s) (",(string info 1)," bytes) in ",1_string g]; - g - }; - -copyprefix:{[src;dst;n] - / copy the first n bytes of src to dst in bounded chunks; the destination handle is closed even if a read fails - dst 1: `byte$(); - h:hopen dst; - r:@[{[src;h;n] copychunkto[src;h;n]/[0j]}[src;h];n;{[e] (`copyfailed;e)}]; - hclose h; - if[`copyfailed~first r;'"copying ",(1_string src),": ",r 1]; - }; - -copychunkto:{[src;h;n;o] - / append the next chunk of src from offset o; returns the new offset, unchanged once at n (ending the over) - if[o>=n;:o]; - k:copychunk&n-o; - h read1 (src;o;k); - o+k - }; - -openlog:{[d;clear] - / open the log for date d - cleared first when asked - and take its message count as the replay count offered to - / subscribers - ln:resolvelog lognamefor d; - if[clear;clearlog ln]; - r:openfile ln; - .z.m.logname:r 0; - .z.m.logh:r 1; - .z.m.msgcount:r 2; - .z.m.log[`info][`openlog;"logging to ",(1_string r 0),", holding ",(string r 2)," message(s)"]; - }; - -closefail:{[e] .z.m.log[`warn][`closelog;"log handle already closed: ",e];}; - -closelog:{[] - if[.z.m.logh>0;@[hclose;.z.m.logh;closefail]]; - .z.m.logh:0i; - }; - -writelog:{[t;x] - / append to the own log. no log (tplogdir unset) or a log not yet open (a tick that beats the open under - / multithreaded input) is a skip, not a throw - the message still reaches the subscribers - if[not .z.m.logh>0;:()]; - (.z.m.tp`write)[.z.m.logh;(`upd;t;x)]; - .z.m.msgcount+:1; - }; - -/ --- updates and the two publish modes (as di.torq.proc.tickerplant) --- - -publishfail:{[t;e] raiseerror[`upd;"publish of ",(string t)," failed (a subscriber gone without .z.pc?): ",e]}; - -pubimmediate:{[t;x] - / publish now. a send to a handle that died without .z.pc firing throws inside di.pubsub - logged here, then - / signalled, rather than vanishing into the async handler - d:flip .z.m.tabcols[t]!x; - .z.m.rowcount[t]+:count d; - .[.z.m.ps`publish;(t;d);publishfail[t]]; - }; - -pubbatched:{[t;x] - / buffer into the ROOT table for the flush job. insert by NAME: a runtime symbol resolves to the root table from - / this module's private namespace and under -11! replay alike (only source-level names are rewritten module-local; - / the unit suite proves both paths), and it appends in place - the @[`.;t;upsert-by-value] idiom copies the whole - / buffer on every update (measured: 20k rows 242ms, 40k rows 878ms, against 14ms here) - t insert x; - .z.m.pending[t]+:count first x; - }; - -pubfns:`immediate`batched!(pubimmediate;pubbatched); - -upd:{[t;x] - / feed entry point (root upd / .u.upd): what the upstream publishes and what its log replays. the data arrives - / already timestamped by the upstream, so nothing is stamped here - requireready`upd; - / a string table name (a one-character one is a char atom) is accepted; anything but one symbol is not - a symbol - / list would otherwise throw a bare 'type from the membership test below - if[10h=abs type t;t:`$(),t]; - if[not -11h=type t;raiseerror[`upd;"table must be one symbol; got ",-3!t]]; - if[not t in .z.m.tables;raiseerror[`upd;"not a subscribed table: ",-3!t]]; - x:tocols x; - writelog[t;x]; - .z.m.pubfn[t;x]; - }; - -flush:{[] - / batched-mode flush (timer job): publish every buffered table and clear it. a no-op in immediate mode - if[.z.m.publishmode=`immediate;:()]; - @[.z.m.ps`pubclear;.z.m.tables;publishfail[`$", " sv string .z.m.tables]]; - .z.m.rowcount+:.z.m.pending; - .z.m.pending:.z.m.tables!count[.z.m.tables]#0; - }; - -/ --- the surface this process presents to its own subscribers (root .u.sub / .u.subdetails / endofday / .u.end) --- - -sub:{[tabs;syms] - requireready`sub; - (.z.m.ps`subscribe)[tabs;syms] - }; - -subdetails:{[tabs;syms] - / register the caller with di.pubsub and return, in one synchronous call, what di.subscriptions needs to define and - / replay the subscribed tables - the same dict as di.torq.proc.tickerplant.subdetails. in batched mode the buffer is - / flushed FIRST, to the subscribers that already exist: the new one replays those rows from the log, so the replay - / count never includes a message it would also receive in the next flush - requireready`subdetails; - flush[]; - r:(.z.m.ps`subscribe)[tabs;syms]; - if[-11h=type r;raiseerror[`subdetails;string r]]; - if[-11h=type first r;.z.m.log[`warn][`subdetails;string first r];r:last r]; - `tables`schemas`logfile`rowcount`date!(r 0;(r 0)!r 1;$[.z.m.logh>0;.z.m.logname;`];.z.m.msgcount;.z.m.date) - }; - -endofday:{[d] - / what the upstream sends at its end of day (di.pubsub's (`endofday;d) broadcast; .u.end is the alias): flush, pass - / the end of day on to this process's own subscribers, roll the own log into d+1 and follow the upstream's date - requireready`endofday; - if[not -14h=type d;raiseerror[`endofday;"expected a date; got ",-3!d]]; - / a day already ended is not ended again: rolling into d+1 would reopen an older log and move the date backwards, - / and re-broadcasting would make every subscriber save that day down twice - if[d<.z.m.date;.z.m.log[`warn][`endofday;"upstream ended ",(string d)," but the current date is already ",(string .z.m.date),"; ignored"];:()]; - if[d>.z.m.date;.z.m.log[`warn][`endofday;"upstream ended ",(string d)," but the current date is ",(string .z.m.date),"; following it"]]; - flush[]; - (.z.m.ps`callendofday)[d]; - if[.z.m.logh>0;closelog[];openlog[d+1;0b]]; - .z.m.date:d+1; - .z.m.log[`info][`endofday;"end of day complete, ",(string d)," -> ",string d+1]; - }; - -/ --- the upstream side --- - -connect:{[] - / dial the upstream through the injected di.torq.servers and block until it is up. startup is skipped when an - / earlier init's connection is still live (init is idempotent; a second startup would dial and register it again) - if[not .z.m.tph in key .z.W; - (.z.m.svc`startup)[.z.m.cfg,(enlist`connections)!enlist enlist .z.m.upstreamtype]]; - if[not (.z.m.svc`waitfortype)[.z.m.upstreamtype;.z.m.connecttimeoutms;.z.m.connectpollms]; - raiseerror[`init;"no ",(string .z.m.upstreamtype)," connection within ",(string .z.m.connecttimeoutms),"ms"]]; - .z.m.tph:(.z.m.svc`gethandlebytype)[.z.m.upstreamtype;`any]; - if[null .z.m.tph;raiseerror[`init;"no live ",(string .z.m.upstreamtype)," handle after waiting"]]; - }; - -subscribe:{[] - / one .u.subdetails call through di.subscriptions: registers this process for live delivery and defines the - / subscribed tables at root. replay is NOT asked of di.subscriptions - the own log must be open, for the date this - / call returns, before any replayed message reaches upd - so the replay is driven here afterwards (see doreplay) - sd:(.z.m.subs`subscribe)[.z.m.tph;.z.m.subscribeto;.z.m.subscribesyms;0b]; - if[not all `tables`schemas`logfile`rowcount`date in key sd;raiseerror[`init;"upstream .u.subdetails returned ",-3!key sd]]; - .z.m.date:sd`date; - .z.m.tables:sd`tables; - .z.m.tabcols:(key sd`schemas)!cols each value sd`schemas; - .z.m.rowcount:.z.m.tables!count[.z.m.tables]#0; - .z.m.pending:.z.m.tables!count[.z.m.tables]#0; - .z.m.upstreamup:1b; - / live from here: an update can now arrive on tph - .z.m.ready:1b; - .z.m.log[`info][`subscribe;"subscribed to ",(", " sv string .z.m.tables)," on ",(string .z.m.upstreamtype),", date ",string .z.m.date]; - sd - }; - -replayfilter:{[origupd;tabs;syms;t;x] - / installed as root upd during the replay of a narrowed subscription: the upstream log holds every table and sym, - / so drop what was not subscribed before the real upd sees it (as di.subscriptions' own replay does for an rdb) - if[not t in tabs;:()]; - x:tocols x; - if[not syms~`;x:x@\:where x[1] in syms]; - if[not count first x;:()]; - origupd[t;x]; - }; - -runreplay:{[lf;n] .[{[m;lf;n] (m`replayupto)[lf;n]};(.z.m.tp;lf;n);{[e] (`replayerr;e)}]}; - -doreplay:{[sd] - / replay the messages the upstream had logged at subscription time through root upd - so they land in the own log - / and, in batched mode, the buffer. count-limited to rowcount, as live delivery has started - lf:sd`logfile; - n:sd`rowcount; - if[null lf;raiseerror[`replay;"upstream reports ",(string n)," logged message(s) but no log file"]]; - narrowed:not (.z.m.subscribeto~`) and .z.m.subscribesyms~`; - origupd:`. `upd; - if[narrowed;@[`.;`upd;:;replayfilter[origupd;sd`tables;.z.m.subscribesyms]]]; - r:runreplay[lf;n]; - if[narrowed;@[`.;`upd;:;origupd]]; - if[`replayerr~first r;raiseerror[`replay;"replay of ",(1_string lf)," failed: ",r 1]]; - .z.m.log[`info][`replay;"replayed ",(string r)," of ",(string n)," message(s) from ",1_string lf]; - }; - -warnappend:{[n] - / the upstream replay appends to whatever the own log already holds - legacy's clearlogonsubscription exists for this - msg:"replay will append ",(string n)," message(s) to a log already holding ",string .z.m.msgcount; - .z.m.log[`warn][`init;msg," - set clearlogonsubscription to rebuild it instead"]; - }; - -pcfunc:{[w] - / .z.pc (via di.torq.handlers, alongside di.torq.servers' own hook): losing the upstream ends this process. nothing - / in the stack resubscribes a bounced tickerplant yet (di.torq.servers reopens the socket, but no one calls - / di.subscriptions.subscribe again on it), so a clean exit 0 hands the restart to the supervisor - if[not w=.z.m.tph;:()]; - .z.m.upstreamup:0b; - msg:"lost the ",(string .z.m.upstreamtype)," connection on handle ",string w; - .z.m.log[`error][`pc;msg,"; no resubscribe path exists - exiting 0 for the supervisor to restart"]; - .z.m.exitfn 0; - }; - -/ --- exported api --- - -connected:{[] - / is the upstream subscription live? backed by local state (flipped by subscribe and the .z.pc handler) - - / di.subscriptions' registry tracks no disconnects - requireinit`connected; - .z.m.upstreamup - }; - -getcounts:{[] - / messages in the own log for the current date, the date, and per-table rows published and rows pending in the - / unflushed batch - requireinit`getcounts; - t:.z.m.tables; - `msgcount`date`tables!(.z.m.msgcount;.z.m.date;([tbl:t]rowcount:.z.m.rowcount t;pendingrowcount:.z.m.pending t)) - }; - -teardown:{[] - / stop the module: flush, close the own log, remove the flush job and the own .z.pc handler. the upstream - / subscription itself cannot be withdrawn (no protocol for it); the socket stays with di.torq.servers - requireinit`teardown; - flush[]; - closelog[]; - (.z.m.timer`deletejobs)[enlist jobid]; - (.z.m.handlers`remove)[`.z.pc;`;jobid]; - / the pubsub cleanup registration stays: a subscriber that leaves between a teardown and the next init would - / otherwise remain registered, and the first publish after that init would fail on its dead handle - .z.m.upstreamup:0b; - .z.m.ready:0b; - .z.m.initdone:0b; - .z.m.log[`info][`teardown;"stopped"]; - }; - -checkdep:{[deps;k;fns;hint] - if[not k in key deps;'"di.torq.proc.chainedtp: ",(string k)," dependency is required - ",hint]; - if[99h<>type deps k;'"di.torq.proc.chainedtp: ",(string k)," dependency must be a dict - ",hint]; - if[count missing:fns except key deps k;'"di.torq.proc.chainedtp: ",(string k)," dependency is missing ",", " sv string missing]; - }; - -checkdeps:{[deps] - / validate the injected deps before anything is wired - plain signals, as no logger is usable yet. all four are - / required whatever the config (timer is only used in batched mode), as di.torq injects all four into every process - if[99h<>type deps;'"di.torq.proc.chainedtp: deps must be a dict with `log`timer`handlers`servers keys"]; - checkdep[deps;`log;`info`warn`error;"see di.util.log"]; - checkdep[deps;`timer;`addjob`deletejobs;"see di.timer"]; - checkdep[deps;`handlers;`register`remove;"see di.torq.handlers"]; - checkdep[deps;`servers;`startup`gethandlebytype`waitfortype;"injected by di.torq, see di.torq.servers"]; - }; - -checkin:{[k;v;ok] - if[not v in ok;raiseerror[`init;(string k)," must be one of ",(", " sv string ok),"; got ",-3!v]]; - }; - -readconfig:{[config] - / read and validate every setting up front - .z.m.cfg:config; - if[not `upstreamtype in key config;raiseerror[`init;"upstreamtype is required - the proctype of the tickerplant to subscribe to"]]; - .z.m.upstreamtype:astz config`upstreamtype; - .z.m.subscribeto:astz cfgor[config;`subscribeto;`]; - .z.m.subscribesyms:astz cfgor[config;`subscribesyms;`]; - .z.m.replay:tobool cfgor[config;`replay;0b]; - .z.m.clearlogonsubscription:tobool cfgor[config;`clearlogonsubscription;0b]; - / the presence of tplogdir is the logging switch, as di.torq.proc.tickerplant; an empty value is absence - .z.m.tplogdir:$[(`tplogdir in key config) and count tostr config`tplogdir;resolvedir[datahome[];config`tplogdir];""]; - .z.m.publishmode:astz cfgor[config;`publishmode;`immediate]; - .z.m.pubperiod:tolong cfgor[config;`pubperiod;1]; - .z.m.connecttimeoutms:tolong cfgor[config;`connecttimeoutms;10000]; - .z.m.connectpollms:tolong cfgor[config;`connectpollms;500]; - / the log file name carries the process name, as TorQ's chainedtp did, so two chained tickerplants sharing a - / tplogdir - or one sharing its upstream's - cannot write the same file. "chainedtp" only when no procname is known - .z.m.logprefix:tostr cfgor[config;`logprefix;$[`procname in key config;config`procname;"chainedtp"]]; - .z.m.proctype:astz cfgor[config;`proctype;`chainedtp]; - .z.m.procname:astz cfgor[config;`procname;`]; - checkin[`publishmode;.z.m.publishmode;pubmodes]; - if[not 0<.z.m.pubperiod;raiseerror[`init;"pubperiod must be a positive number of seconds"]]; - if[not 0<.z.m.connecttimeoutms;raiseerror[`init;"connecttimeoutms must be a positive number of milliseconds"]]; - if[not 0<.z.m.connectpollms;raiseerror[`init;"connectpollms must be a positive number of milliseconds"]]; - if[0=count .z.m.logprefix;raiseerror[`init;"logprefix must not be empty"]]; - .z.m.pubfn:pubfns .z.m.publishmode; - }; - -publishroot:{[] - / the IPC surface the upstream, its log replay and this process's own subscribers call by name - use keeps module - / code in a private namespace, so each is set at a real root name - set[`upd;upd]; - set[`.u.upd;upd]; - set[`.u.sub;sub]; - set[`.u.subdetails;subdetails]; - set[`endofday;endofday]; - set[`.u.end;endofday]; - }; - -finishinit:{[sd] - / the part of init that runs once subscribed: pubsub on the subscribed tables, the own log, the replay, the flush job - (.z.m.ps`setsubtables)[.z.m.tables]; - (.z.m.ps`init)[]; - .z.m.msgcount:0; - .z.m.logname:`; - if[count .z.m.tplogdir; - mkdirfail:{[dir;e] raiseerror[`init;"cannot create the log directory ",dir,": ",e]}[.z.m.tplogdir]; - @[system;"mkdir -p ",shq .z.m.tplogdir;mkdirfail]; - openlog[.z.m.date;.z.m.clearlogonsubscription]]; - if[.z.m.replay and 00;warnappend[sd`rowcount]]; - doreplay sd]; - if[.z.m.publishmode=`batched;(.z.m.timer`addjob)[jobid;flush;();.z.m.pubperiod;1h;()!()]]; - }; +/ di.torq.proc.chainedtp - chained tickerplant init:{[config;deps] - / wire the injected deps, read config, publish the root surface, connect and subscribe to the upstream, open the - / own log, replay if asked, and schedule the flush job. safe to call again, and to retry after a call that failed - / part-way - checkdeps deps; - if[.z.m.initdone;teardown[]]; + if[not `log in key deps;'"di.torq.proc.chainedtp: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.torq.proc.chainedtp: timer dependency is required - see di.timer"]; + if[not `handlers in key deps;'"di.torq.proc.chainedtp: handlers dependency is required - see di.torq.handlers"]; .z.m.log:deps`log; - .z.m.logwired:1b; - .z.m.timer:deps`timer; - .z.m.handlers:deps`handlers; - .z.m.svc:deps`servers; - / a failed earlier init may have left the log open or a job/handler registered (all removals are no-ops if absent) - closelog[]; - (.z.m.timer`deletejobs)[enlist jobid]; - (.z.m.handlers`remove)[`.z.pc;`;jobid]; - .z.m.upstreamup:0b; - .z.m.ready:0b; - readconfig config; - .z.m.ps:use`di.pubsub; - .z.m.subs:use`di.subscriptions; - (.z.m.subs`init)[config;deps]; - .z.m.tp:use`di.tplogmgr; - / di.pubsub's subscriber cleanup goes on .z.pc through the handlers dep, a simple event alongside di.torq.servers' - / hook and this module's own (di.pubsub does not bind .z.pc itself - that replaced the di.torq.handlers dispatcher) - (.z.m.handlers`register)[`.z.pc;`;`pubsub;0;.z.m.ps`closesub]; - publishroot[]; - connect[]; - / registered before subscribing, so an upstream lost during the subscription is seen - (.z.m.handlers`register)[`.z.pc;`;jobid;0;pcfunc]; - sd:subscribe[]; - / from here the root surface is live (the upstream may already be sending); a failure below takes it down again - / so a half-initialised process does not keep relaying with no log and no flush job - r:@[finishinit;sd;{[e] .z.m.ready:0b;.z.m.upstreamup:0b;closelog[];(`initfailed;e)}]; - if[`initfailed~first r;'r 1]; - msg:"initialised, upstream=",(string .z.m.upstreamtype),", mode=",string .z.m.publishmode; - msg,:", log=",$[count .z.m.tplogdir;1_string .z.m.logname;"off"]; - .z.m.log[`info][`chainedtp;msg,", tables=",", " sv string .z.m.tables]; - / written last: a throw anywhere above leaves the module uninitialised, so a retry is a full init, not a re-init - .z.m.initdone:1b; - }; + .z.m.procname:config`procname; + (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; + (deps[`handlers]`register)[`.z.pc;`;`stpps;0j;.stpps.closesub]; + (use`di.subscriptions)[`init][config;deps]; + {[config;k] if[k in key config;set[` sv `.ctp,k;config k]]}[config] each `tickerplantname`pubinterval`tpconnsleep`createlogfile`logdir`subscribeto`subscribesyms`replay`schema`clearlogonsubscription`tpcheckcycles; + if[0<>(`long$.ctp.pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; + (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[.ctp.tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .ctp.tickerplantname];exit 0]}]; + .ctp.upd:$[.ctp.createlogfile; + $[.ctp.pubinterval;{[t;x] .ctp.writetolog[t;x];.ctp.batchpub[t;x];};{[t;x] .ctp.writetolog[t;x];.ctp.tickpub[t;x];}]; + $[.ctp.pubinterval;.ctp.batchpub;.ctp.tickpub]]; + if[not `upd in key `.;set[`upd;.ctp.upd]]; + .ps.initialise[]; + .servers.startupdepnamecycles[.ctp.tickerplantname;.ctp.tpconnsleep;.ctp.tpcheckcycles]; + .ctp.subscribe[]; + .ctp.tableschemas:{x!(0#)@'value@'x} (),$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto]; + if[.ctp.pubinterval;(deps[`timer]`addjob)[`publishalltables;.ctp.publishalltables;();`long$.ctp.pubinterval%0D00:00:01;2;()!()]]; + } + +\d . + +tptype:`chained; + +tablelist:{.stpps.t} + +subdetails:{[tabs;instruments] + r:.ctp.sub[tabs;instruments]; + `schemalist`logfilelist`rowcounts`date!r@/:(`schema;$[r[`logfile]~();();enlist`i`logfile];`icounts;`d) + } + +\d .ctp + +tickerplantname:@[value;`tickerplantname;`tickerplant1]; +pubinterval:@[value;`pubinterval;0D00:00:00]; +tpconnsleep:@[value;`tpconnsleep;10]; +createlogfile:@[value;`createlogfile;0b]; +logdir:@[value;`logdir;`:tplogs]; +subscribeto:@[value;`subscribeto;`]; +subscribesyms:@[value;`subscribesyms;`]; +replay:@[value;`replay;0b]; +schema:@[value;`schema;1b]; +clearlogonsubscription:@[value;`clearlogonsubscription;0b]; +tpcheckcycles:@[value;`tpcheckcycles;0W]; + +tph:0N; +.u.icounts:.u.jcounts:(`symbol$())!0#0,(); +.u.i:.u.j:0; + +clearlog:{[lgfile] + if[not type key lgfile;:()]; + .z.m.log[`info][`clearlog;"clearing log file : ",string lgfile]; + .[set;(lgfile;());{.z.m.log[`error][`clearlog;"cannot empty tickerplant log: ", x]}] + } + +openlog:{[lgfile] + lgfileexists:type key lgfile; + .z.m.log[`info][`openlog; + $[lgfileexists; + "opening log file : "; + "creating new log file : "],string lgfile]; + if[not lgfileexists; + .[set;(lgfile;());{[lgf;err] .z.m.log[`error][`openlog;"cannot create new log file : ",string[lgf]," : ", err]}[lgfile]]]; + updold:`. `upd; + @[`.;`upd;:;{[t;x] .u.icounts[t]+:count x;}]; + .u.i:.u.j:@[-11!;lgfile;-11!(-2;lgfile)]; + @[`.;`upd;:;updold]; + if[0<=type .u.i; + .z.m.log[`error][`openlog;"log file : ",(string lgfile)," is corrupt. Please remove and restart."]]; + hopen lgfile + } -getapimeta:{[] - / this module's api metadata, one row per CALLABLE API function, for di.torq to register with di.api. init and - / getapimeta are plumbing di.torq calls by convention and are deliberately not listed. names are bare. - :flip `name`public`descrip`params`return!flip( - (`upd; 1b; "log and publish an update from the upstream (also root upd / .u.upd)"; "[symbol: t; list|table: x]"; "null"); - (`connected; 1b; "is the upstream subscription live"; "[]"; "boolean"); - (`getcounts; 1b; "own-log message count, the date, and per-table published/pending rows"; "[]"; "dict"); - (`teardown; 1b; "flush, close the own log, remove the flush job and .z.pc handlers"; "[]"; "null")); - }; +subscribe:{[] + s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; + if[count s; + subproc:first s; + .ctp.tph:subproc`w; + refreshtp @[tph;".u.d";.z.D]; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; + if[`d in key r;.u.d::r[`d]]; + if[(`icounts in key r) & (not createlogfile); + subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); + .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; + ] + ]; + } + +writetolog:{[t;x] + if[not 98h=type x;x:flip cols[value t]!(),/:x]; + .u.l enlist (`upd;t;x); + .u.j+:1; + } + +tickpub:{[t;x] + .ps.publish[t;x]; + .u.i:.u.j; + .u.icounts[t]+:count x; + } + +batchpub:{[t;x] + insert[t;x]; + .u.jcounts[t]+:count x; + } + +publishalltables:{[] + pubtables:$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto],(); + .ps.publish'[pubtables;value each pubtables]; + cleartables[pubtables]; + .u.i:.u.j; + .u.icounts:.u.jcounts; + } + +tableschemas:()!() + +cleartables:{[t] + @[`.;t;:;tableschemas t]; + } + +createlogfilename:{[d] + ` sv (.ctp.logdir;`$string[.z.m.procname],"_",string d) + } + +refreshtp:{[d] + if[@[value;`.u.l;0]; @[hclose;.u.l;()]]; + .u.i:.u.j:0; + .u.icounts::.u.jcounts::(`symbol$())!0#0,(); + if[createlogfile; + .u.L:createlogfilename[d]; + if[clearlogonsubscription;clearlog .u.L]; + ]; + .u.l:$[createlogfile;openlog .u.L;1i]; + .u.d:d; + } + +notpconnected:{[] + 0 = count select from .sub.SUBSCRIPTIONS where procname in .ctp.tickerplantname, active} + +sub:{[subtabs;subsyms] + r:(`schema`icounts`i`logfile`d)!(); + r[`schema]:$[-11h=type subtabs;first;::] .u.sub\:[subtabs,();subsyms]; + if[subscribesyms~`;r[`icounts]:.u.icounts]; + if[createlogfile;r[`i]:.u.i;r[`logfile]:.u.L]; + r[`d]:.u.d; + r + } + +\d .u + +end:{[d] + .z.m.log[`info][`end;"end of day invoked"]; + .ctp.publishalltables[]; + .ctp.refreshtp[d+1]; + (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`.u.end;d) + } + +\d . diff --git a/di/torq/proc/chainedtp/deps.toml b/di/torq/proc/chainedtp/deps.toml index da3694f9..a2776cf8 100644 --- a/di/torq/proc/chainedtp/deps.toml +++ b/di/torq/proc/chainedtp/deps.toml @@ -1,5 +1,5 @@ # Peer modules di.torq.proc.chainedtp `use`s (see di/torq/depcheck/depcheck.md). [dependencies] -"di.pubsub" = "0.1.0" -"di.subscriptions" = "0.1.0" -"di.tplogmgr" = "0.1.0" +"di.pubsub" = "0.2.0" +"di.subscriptions" = "0.2.0" +"di.torq.servers" = "0.5.0" diff --git a/di/torq/proc/chainedtp/init.q b/di/torq/proc/chainedtp/init.q index f4a7ebe9..4f77b6a2 100644 --- a/di/torq/proc/chainedtp/init.q +++ b/di/torq/proc/chainedtp/init.q @@ -2,4 +2,4 @@ version:first read0`:::VERSION -export:([init;upd;teardown;connected;getcounts;getapimeta;version]) +export:([init;version]) diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 28ca66a9..e2a895b1 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -1,78 +1,67 @@ action,ms,bytes,lang,code,repeat,minver,comment -before,0,0,q,ct:use`di.torq.proc.chainedtp,1,,load module -before,0,0,q,system "l di/torq/proc/chainedtp/test.q",1,,load fixture helpers -before,0,0,q,setupfixture[],1,,fixture dir and the upstream log; spawn the stub upstream process +before,0,0,q,ctp:use`di.torq.proc.chainedtp,1,,load module +before,0,0,q,system "l di/torq/proc/chainedtp/test.q",1,,load mocks and fixture helpers +before,0,0,q,setupfixture[],1,,start the upstream and downstream peers and write process.csv +before,0,0,q,initservers[],1,,init di.torq.servers against the fixture process.csv -comment,,,,,,,api contract -true,0,0,q,"(asc (key ct) except `init`getapimeta`version)~asc exec name from ct.getapimeta[]",1,,getapimeta documents exactly the callable exports (plumbing omitted) -true,0,0,q,"not any `init`getapimeta in exec name from ct.getapimeta[]",1,,framework plumbing is not registered in the api -true,0,0,q,`name`public`descrip`params`return~cols ct.getapimeta[],1,,getapimeta rows carry the registry columns -true,0,0,q,versionok[],1,,version is exported from the VERSION file as a clean semver string +comment,,,,,,,init - dependencies +fail,0,0,q,"ctp.init[cfg[];enlist[`log]!enlist mocklog]",1,,init without timer must error +fail,0,0,q,"ctp.init[cfg[];`log`timer!(mocklog;mocktimer)]",1,,init without handlers must error +fail,0,0,q,"ctp.init[cfg[];`timer`handlers!(mocktimer;mockhandlers)]",1,,init without log must error +fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,a sub-second pubinterval must error +fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error -comment,,,,,,,init validation - plain signals before anything is wired -true,0,0,q,initnotdict[],1,,deps must be a dict -true,0,0,q,initnolog[],1,,log dependency is required -true,0,0,q,initnotimer[],1,,timer dependency is required even in immediate mode -true,0,0,q,initnohandlers[],1,,handlers dependency is required -true,0,0,q,initnoservers[],1,,servers dependency is required -true,0,0,q,initlogkeys[],1,,a log dict missing a level is rejected naming the level -true,0,0,q,initserverskeys[],1,,a servers dict missing a contract function is rejected naming it -true,0,0,q,initnoupstream[],1,,upstreamtype is required -true,0,0,q,"initrejects[`publishmode;`sometimes;""publishmode must be one of""]",1,,an unrecognised publishmode fails init naming the setting -true,0,0,q,"initrejects[`pubperiod;0;""pubperiod must be""]",1,,a non-positive pubperiod is rejected -true,0,0,q,"initrejects[`connecttimeoutms;-1;""connecttimeoutms must be""]",1,,a non-positive connect timeout is rejected -true,0,0,q,"initrejects[`logprefix;"""";""logprefix must not be empty""]",1,,an empty logprefix is rejected -true,0,0,q,initwaittimeout[],1,,no upstream within the timeout fails init naming the proctype - nothing subscribed -true,0,0,q,fixpartway[],1,,an init that threw after connecting is not initialised and never subscribed; the retry subscribes once -true,0,0,q,initfailslate[],1,,an init that fails after subscribing takes the root surface down again; the retry succeeds +comment,,,,,,,init - connect and subscribe +run,0,0,q,ctp.init[cfg[];deps[]],1,,init +true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle +true,0,0,q,`trade in tables[],1,,upstream schema defined at root +true,0,0,q,.u.d~D,1,,date taken from the upstream +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade +true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered +true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade +true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 +true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish +run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) +true,0,0,q,`trade in .stpps.t,1,,trade is published -comment,,,,,,,config -true,0,0,q,defaults[],1,,every default reaches module state; the date and tables come from the upstream -true,0,0,q,stringconfig[],1,,string (toml / command-line) settings are parsed into the right types -true,0,0,q,prefixok[],1,,the own log carries procname; an explicit logprefix wins -true,0,0,q,emptylogdir[],1,,an empty tplogdir means no log -true,0,0,q,logdictwiring[],1,,init accepts di.util.log's real logdict joined with the other deps - as di.torq wires it +comment,,,,,,,tick by tick +run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstream peer +run,0,0,q,"r:dh""(.z.w)(`.u.sub;`trade;`)""",1,,downstream subscribes to trade +true,0,0,q,`trade~first r,1,,.u.sub returns the table +true,0,0,q,"dh in .stpps.subrequestall`trade",1,,downstream registered +run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows +true,0,0,q,(enlist 3)~.u.icounts`trade,1,,icounts updated (one-item list as the subscribe reshape leaves it) +true,0,0,q,"(1;3)~dh""(count got;count last last got)""",1,,downstream received the 3 rows +true,0,0,q,"`schemalist`logfilelist`rowcounts`date~key dh""(.z.w)(`subdetails;`trade;`)""",1,,subdetails keys +true,0,0,q,"()~(dh""(.z.w)(`subdetails;`trade;`)"")`logfilelist",1,,no log file without createlogfile +true,0,0,q,"`trade in dh""(.z.w)(`tablelist;`)""",1,,tablelist lists trade -comment,,,,,,,wiring -true,0,0,q,rootok[],1,,root surface published; own .z.pc and pubsub closesub registered through handlers; upstream dialled and waited for -true,0,0,q,reinit[],1,,a second init is clean: no second dial while the handle lives - one subscription - flush job replaced +comment,,,,,,,end of day +run,0,0,q,.u.end D,1,,end of day +true,0,0,q,"(enlist D)~dh""ended""",1,,.u.end passed to the downstream +true,0,0,q,.u.d=D+1,1,,date rolled +true,0,0,q,0=count trade,1,,trade cleared -comment,,,,,,,updates under both publish modes -true,0,0,q,immediateok[],1,,immediate: nothing retained - every message logged - rows counted per table - no flush job -true,0,0,q,immediatenolog[],1,,immediate without a log publishes and counts rows with no handle open -true,0,0,q,batchedok[],1,,batched: rows buffer at root and are logged at once; the flush job is scheduled; flush publishes and clears -true,0,0,q,batchednolog[],1,,batched without a log buffers without error -true,0,0,q,payloadok[],1,,table - single record - batch and string table name payloads all land; the log holds vector columns -true,0,0,q,unknowntable[],1,,a table not subscribed upstream - a symbol list - a non-symbol are each rejected with a logged error -true,0,0,q,publishfailok[],1,,a publish that throws is logged at error and signalled -true,0,0,q,earlytick[],1,,a tick arriving before the log is open is published and skipped by the log - never thrown +comment,,,,,,,own log and batch publish +run,0,0,q,".ctp.createlogfile:1b;.ctp.logdir:hsym`$FIXDIR;.ctp.refreshtp D",1,,create a log for D +true,0,0,q,".u.L~hsym`$FIXDIR,""/chainedtp1_"",string D",1,,log named /_ +run,0,0,q,.ctp.writetolog[`trade;rows 2],1,,write one message +true,0,0,q,"(1;1)~(.u.j;-11!(-2;.u.L))",1,,one message counted and on disk +run,0,0,q,.ctp.batchpub[`trade;rows 2],1,,batch 2 rows +true,0,0,q,2=count trade,1,,batched in the root table +run,0,0,q,.ctp.publishalltables[],1,,publish the batch +true,0,0,q,"(2;2)~dh""(count got;count last last got)""",1,,downstream received the batch +true,0,0,q,"(0;1)~(count trade;.u.i)",1,,trade cleared and .u.i caught up +run,0,0,q,.ctp.refreshtp D,1,,reopen the existing log +true,0,0,q,1=.u.i,1,,existing messages counted +run,0,0,q,".ctp.clearlogonsubscription:1b;.ctp.refreshtp D",1,,reopen with clearlogonsubscription +true,0,0,q,0=.u.i,1,,log cleared +run,0,0,q,"r:subdetails[`trade;`]",1,,subdetails with a log +true,0,0,q,"(enlist(0;.u.L))~r`logfilelist",1,,logfilelist carries i and the log file +run,0,0,q,"bf:hsym`$FIXDIR,""/bad""; bf set (); lh:hopen bf; lh enlist(`upd;`trade;rows 1); hclose lh; bf 1: (read1 bf),0x0102030405",1,,write a log with one message and a bad tail +run,0,0,q,bh:.ctp.openlog bf,1,,open it +true,0,0,q,"errlogged""is corrupt""",1,,corruption reported +true,0,0,q,-6h=type bh,1,,and the log opened anyway +true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 -comment,,,,,,,the upstream replay into the own log -true,0,0,q,replayok[],1,,replay with a cleared log: the upstream's messages land in the own log and are counted per table; one subscription -true,0,0,q,replaybatched[],1,,batched replay buffers the replayed rows at root -true,0,0,q,replaynarrowed[],1,,a table-narrowed subscription replays only that table -true,0,0,q,replaysyms[],1,,a sym-narrowed subscription replays only those syms -true,0,0,q,replaynone[],1,,nothing logged upstream means no replay -true,0,0,q,replaynofile[],1,,an upstream reporting messages but no log file fails init -true,0,0,q,replayappendwarn[],1,,replay onto a non-empty log appends and warns -true,0,0,q,existingcount[],1,,a restart counts the day's log without republishing it -true,0,0,q,clearlogok[],1,,clearlogonsubscription truncates the log on init -true,0,0,q,corruptok[],1,,a smashed log is recovered into .good with its good count - original untouched - and stays in use - -comment,,,,,,,the surface offered to this process's own subscribers -true,0,0,q,subdetailsok[],1,,.u.subdetails returns the tickerplant-shaped dict with the own log file and message count -true,0,0,q,subdetailsnolog[],1,,.u.subdetails without a log reports no file and zero to replay -true,0,0,q,subdetailsflush[],1,,batched: the buffer is flushed before the caller is registered -true,0,0,q,subbad[],1,,subscribing to an unknown table is rejected -true,0,0,q,subok[],1,,.u.sub registers the caller and returns the schema -true,0,0,q,eodok[],1,,the upstream's end of day is passed downstream - the own log rolls into the next date - a later date is followed with a warning - an earlier one is ignored -true,0,0,q,eodnolog[],1,,end of day without a log advances the date and tells the subscribers -true,0,0,q,eodbaddate[],1,,end of day rejects a non-date - -comment,,,,,,,connection loss and lifecycle -true,0,0,q,connectedok[],1,,connected is true after init; a foreign handle closing is ignored; losing the upstream flips it and exits 0 -true,0,0,q,pcviahandlers[],1,,the handler registered through handlers is the module's own; the pubsub registration is closesub -true,0,0,q,teardownok[],1,,teardown flushes - closes the log - removes the flush job and the own .z.pc handler - keeps pubsub's cleanup registered -true,0,0,q,afterteardown[],1,,every api and root function signals after teardown - -after,0,0,q,teardownfixture[],1,,tear down the module; kill the stub upstream; remove the fixture dir +after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 96189bec..3882ebde 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -1,603 +1,43 @@ -/ fixture helpers for di.torq.proc.chainedtp's unit tests. Assumes cwd is the kdbx-modules repo root. -/ Uses REAL di.pubsub / di.subscriptions / di.tplogmgr with a recording mock log, timer, handlers and servers. The -/ servers mock hands out a genuine IPC handle to a STUB UPSTREAM (test_upstream.q, spawned here as a separate q -/ process) that answers .u.subdetails with whatever the harness set, so subscribe and replay run over real IPC without a -/ full tickerplant. The timer never runs a cycle, so the batched flush fires only when a test calls it. Each scenario -/ helper inits the module against its own log dir and returns 1b only if every named check passes; the per-check dict -/ is left in LAST so a failing row can be diagnosed with `show LAST`. Helpers live here because CSV fields cannot hold -/ commas. - -BASE:"/tmp/di_chainedtp_k4unit"; -MOD:`.m.di.0torq.0proc.0chainedtp; -UPDATE:2026.01.05; / the date the stub upstream reports - -/ read / write module state and reach internal functions -mv:{[n] get .Q.dd[MOD;n]}; -mset:{[n;v] .Q.dd[MOD;n] set v;}; - -chk:{[d] `LAST set d; all value d}; -errmsg:{[f] @[f;::;{x}]}; - -/ 1b only if f throws AND the error names the expected reason - a bare `fail` row would also pass on an -/ unrelated error (a fixture bug), proving nothing about the path under test -throws:{[f;s] r:errmsg f; (10h=type r) and 0>",BASE,"/stub.log 2>&1 & echo $!"; - `STUBH set waitopen[STUBPORT;40]; - if[null STUBH;'"test: stub upstream failed to listen on ",string STUBPORT]; - }; - -killstub:{[] - if[not null STUBH;@[hclose;STUBH;{}]]; - if[not null STUBPID;@[system;"kill -9 ",(string STUBPID)," 2>/dev/null";{}]]; - `STUBH set 0Ni; - `STUBPID set 0N; - }; - -/ the schemas and the upstream's own log the stub offers: 4 messages - 3 trade (2 of them sym A), 1 quote (sym C) -schemas:{[] `trade`quote!(([]time:`timestamp$();sym:`g#`symbol$();price:`float$());([]time:`timestamp$();sym:`g#`symbol$();bid:`float$()))}; -UPLOG:hsym`$BASE,"/upstream/tp",string UPDATE; -uplogmsgs:( - (`upd;`trade;(2026.01.05D09:00:00;`A;1.0)); - (`upd;`trade;(2026.01.05D09:00:01;`B;2.0)); - (`upd;`quote;(2026.01.05D09:00:02;`C;0.9)); - (`upd;`trade;(2026.01.05D09:00:03;`A;3.0))); - -writeuplog:{[] - UPLOG set (); - h:hopen UPLOG; - {[h;m] h enlist m}[h] each uplogmsgs; - hclose h; - }; - -/ what the stub replies to .u.subdetails: full log by default; a test can override rowcount/logfile -setstub:{[extra] STUBH (set;`SD;(`tables`schemas`logfile`rowcount`date!(`trade`quote;schemas[];UPLOG;4;UPDATE)),extra);}; -stubcalls:{[] STUBH "CALLS"}; - -/ --- fixture --- - +/ test helpers: recording mocks, a real upstream (segmented tickerplant surface) and a real downstream subscriber + +logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()) +mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}) +timercalls:([]id:`symbol$();period:`long$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;`long$period;`long$mode);} +handlercalls:([]event:`symbol$();name:`symbol$()) +mockhandlers:`register`remove`list!({[ev;ph;nm;pri;fn]`handlercalls upsert(ev;nm)};{[ev;ph;nm]};{[ev]}) +errlogged:{[s] any (exec msg from logrows where lvl=`error) like "*",s,"*"} + +FIXDIR:"/tmp/dictptest" +D:2026.09.28 +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" +isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} +waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.ptype c;c;first c]}; -cnt:{[t;col] c:0!((ct`getcounts)[])`tables; first (c col) where c[`tbl]=t}; -msgs:{[] ((ct`getcounts)[])`msgcount}; - -/ open file descriptors of this process pointing exactly at a file (0 once closed) -fdcount:{[f] count @[system;"ls -l /proc/",(string .z.i),"/fd 2>/dev/null | awk '$NF==\"",(1_string f),"\"'";{()}]}; - -/ feed n rows of table t through the published root upd (column-list form, one record each) as the upstream would -feed:{[t;n] {[t;i] upd[t;(2026.01.05D10:00:00+i;`$"S",string i;1.0*i)]}[t] each til n;}; - -/ truncate a log mid-message -smash:{[f] n:hcount f; f 1: read1 (f;0;n-5);}; - -/ --- init validation --- - -initnotdict:{[] throws[{(ct`init)[cfg["tplog/v";()!()];(::)]};"deps must be a dict"]}; -initnolog:{[] throws[{(ct`init)[cfg["tplog/v";()!()];`timer`handlers`servers#deps[]]};"log dependency is required"]}; -initnotimer:{[] throws[{(ct`init)[cfg["tplog/v";()!()];`log`handlers`servers#deps[]]};"timer dependency is required"]}; -initnohandlers:{[] throws[{(ct`init)[cfg["tplog/v";()!()];`log`timer`servers#deps[]]};"handlers dependency is required"]}; -initnoservers:{[] throws[{(ct`init)[cfg["tplog/v";()!()];`log`timer`handlers#deps[]]};"servers dependency is required"]}; -initlogkeys:{[] throws[{(ct`init)[cfg["tplog/v";()!()];@[deps[];`log;:;`info`warn#mocklog[]]]};"missing error"]}; -initserverskeys:{[] throws[{(ct`init)[cfg["tplog/v";()!()];@[deps[];`servers;:;`startup`gethandlebytype#mockservers[]]]};"missing waitfortype"]}; -initnoupstream:{[] throws[{(ct`init)[enlist[`tplogdir]!enlist "tplog/v";deps[]]};"upstreamtype is required"]}; -initbad:{[k;v] resetmocks[]; (ct`init)[cfg["tplog/v";enlist[k]!enlist v];deps[]]}; -initrejects:{[k;v;s] throws[{[k;v;x] initbad[k;v]}[k;v];s]}; - -initwaittimeout:{[] - `WAITOK set 0b; - r:throws[{doinit cfg["tplog/wait";()!()]};"no stubtp connection within"]; - `WAITOK set 1b; - chk `threw`notinit`errorlogged`nosubscription!(r;not mv`initdone;logged[`error;`init];0=stubcalls[]) - }; - -fixpartway:{[] - / a throw from the module's own .z.pc registration, after the connection is up but before the subscription - resetmocks[]; - boom:{[event;phase;name;priority;func] if[name=`chainedtp;'"boom"]; mockregister[event;phase;name;priority;func]}; - bad:@[deps[];`handlers;:;`register`remove!(boom;mockremove)]; - r:@[(ct`init)[cfg["tplog/partway";()!()]];bad;{x}]; - notdone:not mv`initdone; - nosub:0=stubcalls[]; - doinit cfg["tplog/partway";()!()]; - chk `threw`notdone`nosubscription`done`onesubscription`registered!(10h=type r;notdone;nosub;mv`initdone;1=stubcalls[];registered`chainedtp) - }; - -defaults:{[] - doinit cfg["tplog/defaults";()!()]; - chk `upstreamtype`subscribeto`subscribesyms`replay`clearlog`publishmode`pubperiod`timeout`poll`logprefix`tplogdir`date`tables!( - `stubtp=mv`upstreamtype; - `~mv`subscribeto; - `~mv`subscribesyms; - 0b~mv`replay; - 0b~mv`clearlogonsubscription; - `immediate=mv`publishmode; - 1=mv`pubperiod; - 10000=mv`connecttimeoutms; - 500=mv`connectpollms; - "chainedtp"~mv`logprefix; - (BASE,"/tplog/defaults")~mv`tplogdir; - UPDATE=mv`date; - `trade`quote~mv`tables) - }; - -stringconfig:{[] - / .toml / command-line overrides deliver strings and plain numbers - each must reach state as the right type - ks:`upstreamtype`replay`clearlogonsubscription`pubperiod`publishmode`connecttimeoutms`subscribeto; - doinit cfg["tplog/strcfg";ks!("stubtp";"true";"1";"5";"batched";20000;"trade")]; - chk `upstreamtype`replay`clearlog`pubperiod`publishmode`timeout`subscribeto!( - `stubtp=mv`upstreamtype; - 1b~mv`replay; - 1b~mv`clearlogonsubscription; - 5=mv`pubperiod; - `batched=mv`publishmode; - 20000=mv`connecttimeoutms; - `trade=mv`subscribeto) - }; - -/ file names carry procname when di.torq supplies one, so a chained tp sharing a tplogdir cannot collide -prefixok:{[] - doinit cfg["tplog/prefix";enlist[`procname]!enlist`ctp7]; - a:enlist[`procname]!enlist (hsym`$BASE,"/tplog/prefix/ctp7_",string UPDATE)~ownlog[]; - doinit cfg["tplog/prefix2";`procname`logprefix!(`ctp7;"custom")]; - chk a,enlist[`explicitwins]!enlist (hsym`$BASE,"/tplog/prefix2/custom_",string UPDATE)~ownlog[] - }; - -emptylogdir:{[] - / an empty tplogdir is absence, not a log in the data root - doinit cfg["";()!()]; - chk `nolog`nohandle!(0=count mv`tplogdir;0i=mv`logh) - }; - -/ --- wiring --- - -rootok:{[] - / forget the live handle so this init dials afresh (startup is skipped while an earlier init's handle lives) - mset[`tph;0Ni]; - doinit cfg["tplog/root";()!()]; - chk `upd`uupd`sub`subdetails`endofday`uend`pc`pubsubpc`startup`waited`handle`connections!( - `upd in key `.; - `upd in key `.u; - `sub in key `.u; - `subdetails in key `.u; - `endofday in key `.; - `end in key `.u; - registered`chainedtp; - registered`pubsub; - 1=scount`startup; - (`stubtp;10000;500)~exec first arg from scalls where fn=`waitfortype; - STUBH=mv`tph; - (enlist`stubtp)~(exec first arg from scalls where fn=`startup)`connections) - }; - -reinit:{[] - c:cfg["tplog/reinit";enlist[`publishmode]!enlist`batched]; - doinit c; - doinit c; - chk `done`onestartup`onesubscription`jobreplaced`deletedfirst`onefd!( - mv`initdone; - 0=scount`startup; - 1=stubcalls[]; - 1=count select from tcalls where fn=`addjob; - (exec first i from tcalls where fn=`deletejobs)/dev/null 2>&1 &"}'[("up.q";"down.q");(UPPORT;DNPORT)]; + if[not all waitlisten each UPPORT,DNPORT;'"test: peers failed to listen"]; + (`$":",FIXDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string UPPORT),",tickerplant,tickerplant1"); + } + +svc:use`di.torq.servers +initservers:{[] svc.init[`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(mocklog;mocktimer;mockhandlers;`chainedtp;`chainedtp1;FIXDIR,"/process.csv";`tickerplant;0b;0b)]} + +cfg:{[] `proctype`procname`autoreconnect`pubinterval!(`chainedtp;`chainedtp1;0b;0D)} +deps:{[] `log`timer`handlers!(mocklog;mocktimer;mockhandlers)} + +rows:{[n] ([]time:n#.z.p;sym:n#`a`b;price:`float$til n)} + +teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each (.ctp.tph;dh); system "sleep 0.3"; system "rm -rf ",FIXDIR;} diff --git a/di/torq/proc/chainedtp/test_integration.csv b/di/torq/proc/chainedtp/test_integration.csv deleted file mode 100644 index a8b8f0a7..00000000 --- a/di/torq/proc/chainedtp/test_integration.csv +++ /dev/null @@ -1,28 +0,0 @@ -action,ms,bytes,lang,code,repeat,minver,comment -comment,,,,,,,integration test - a real child di.torq.proc.tickerplant upstream and a real child di.torq.proc.chainedtp wired to di.timer / di.torq.handlers / di.util.log / di.torq.servers; this process is the downstream subscriber -comment,,,,,,,requires QPATH resolving the di.* modules (the children run the same kdb-x binary as this session); skips cleanly if no child comes up -comment,,,,,,,child ports are OS-assigned; every child pid is killed by the after row; run from the repo root in a fresh q session - -before,0,0,q,system "l di/torq/proc/chainedtp/test_integration.q",1,,load integration helpers -before,0,0,q,setupintegration[],1,,fixture dir and schema; TORQXAPPHOME/TORQXDATAHOME for the children -before,0,0,q,if[not probe[];killall[];exit 0],1,,skip cleanly when no child kdb-x process can be started - -comment,,,,,,,relay through a real upstream -true,0,0,q,relay[],1,,ticks fed to the upstream reach this downstream through the chained tp as tables - its own log and counts hold them - connected - the servers / chainedtp / pubsub .z.pc handlers all coexist -true,0,0,q,startupticks[],1,,ticks arriving before / during / after the chained tp's start (replaying with a cleared log) reach its log exactly once; a downstream replaying that log then following live sees each once -true,0,0,q,batched[],1,,batched mode buffers and the real timer flushes one message to the downstream -true,0,0,q,narrowed[],1,,a table-narrowed subscription relays and logs only that table -true,0,0,q,volume[],1,,2000 ten-row batches relay exactly once in each publish mode; the batched buffer copes with the burst - -comment,,,,,,,the consumers the surface exists for -true,0,0,q,rdbdownstream[],1,,a real di.torq.proc.rdb subscribes through di.subscriptions - replays the chained tp's log - follows live - and ends its day on the chained tp's broadcast -true,0,0,q,chainoftwo[],1,,tp -> ctp1 -> ctp2: the second hop subscribes to the first by proctype - replays from its log - relays live - and the end of day travels the chain - -comment,,,,,,,end of day and upstream loss -true,0,0,q,eod[],1,,the upstream's end of day reaches this downstream through the chained tp - which rolls its log into the next date -true,0,0,q,upstreamloss[],1,,a kill -9 of the upstream makes the chained tp log the loss and exit 0 - -comment,,,,,,,a real di.torq boot through torqx_init.q with a settings cascade for both process types -true,0,0,q,stackboot[],1,,di.torq launches tp1 and ctp1 from process.csv + the proctype tomls - identity and settings reach the module - relay works - clean exits - -after,0,0,q,killall[],1,,kill every child and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test_integration.q b/di/torq/proc/chainedtp/test_integration.q deleted file mode 100644 index f4c3d499..00000000 --- a/di/torq/proc/chainedtp/test_integration.q +++ /dev/null @@ -1,424 +0,0 @@ -/ helpers for di.torq.proc.chainedtp's integration suite. Drives REAL child kdb-x processes on OS-assigned ports: an -/ upstream di.torq.proc.tickerplant (test_integration_tp.q) and the chained tickerplant under test -/ (test_integration_ctp.q, wired to the real di.timer, di.torq.handlers, di.util.log and di.torq.servers). THIS -/ process plays the downstream subscriber: it calls the chained tp's .u.subdetails over IPC and receives its -/ publishes and end-of-day at root. Every child is launched through a shell wrapper that records its exit code, and -/ every pid is killed by the after row whatever happened. Scenario helpers return 1b only if every named check passes -/ and leave the per-check dict in LAST. - -IBASE:"/tmp/di_chainedtp_integration"; -SM:".m.di.0torq.0proc.0chainedtp."; -TPM:".m.di.0torq.0proc.0tickerplant."; -PIDS:`long$(); - -chk:{[d] `LAST set d; all value d}; - -moddir:{[] p:.Q.m.mp`di.torq.proc.chainedtp; p:$[10h=type p;p;string p]; $[":"=first p;1_p;p]}; - -/ the binary running this session - guaranteed to be the kdb-x this suite runs on -QBIN:{[] r:@[system;"readlink /proc/",(string .z.i),"/exe";{()}]; $[count r;first r;"q"]}[]; - -/ what a downstream subscriber defines at root: the chained tp publishes (`upd;t;x) and broadcasts (`endofday;d) -RECV:(); -EOD:0Nd; -upd:{[t;x] `RECV set RECV,enlist (t;x);}; -endofday:{[d] `EOD set d;}; - -setupintegration:{[] - system "rm -rf ",IBASE; - system "mkdir -p ",IBASE; - (hsym`$IBASE,"/database.q") 0: ( - "trade:([]time:`timestamp$();sym:`symbol$();price:`float$())"; - "quote:([]time:`timestamp$();sym:`symbol$();bid:`float$())"); - setenv[`TORQXAPPHOME;IBASE]; - setenv[`TORQXDATAHOME;IBASE]; - }; - -killall:{[] - {@[system;"kill -9 ",(string x)," 2>/dev/null";{}]} each PIDS; - system "sleep 0.5"; - system "rm -rf ",IBASE; - }; - -/ ask the OS for a free port, then release it for the child to bind -freeport:{[] system"p 0W"; p:system"p"; system"p 0"; p}; - -tryopen:{[p] @[{hopen (`$":localhost:",string x;500)};p;0Ni]}; - -waitopen:{[p;n] - if[n<=0;:0Ni]; - if[not null h:tryopen p;:h]; - system "sleep 0.3"; - waitopen[p;n-1] - }; - -startchild:{[name;script;args;port] - / launch through a shell wrapper that appends EXIT= to .exit when the child ends; the wrapper's pid and, - / once the child answers, its own pid are both tracked for the kill - qcmd:QBIN," ",script," -q -p ",(string port)," ",args," >",IBASE,"/",name,".log 2>&1"; - cmd:"sh -c '",qcmd,"; echo EXIT=$? >> ",IBASE,"/",name,".exit' & echo $!"; - shpid:"J"$first system cmd; - `PIDS set PIDS,shpid; - h:waitopen[port;60]; - qpid:$[null h;0N;h ".z.i"]; - if[not null qpid;`PIDS set PIDS,qpid]; - `name`shpid`pid`port`h!(name;shpid;qpid;port;h) - }; - -starttp:{[dir;args] - startchild["tp";moddir[],"/test_integration_tp.q";"-tplogdir ",dir," -schemafile ",IBASE,"/database.q -publishmode immediate ",args;freeport[]] - }; - -/ the process.csv phone book di.torq.servers dials from: rows as (port;proctype;procname) -csvrow:{[r] "localhost,",(string r 0),",",(string r 1),",",string r 2}; -writecsvrows:{[path;rows] (hsym`$path) 0: enlist["host,port,proctype,procname"],csvrow each rows;}; -writecsv:{[path;tpport;ctpport] writecsvrows[path;((tpport;`tickerplant;`tp1);(ctpport;`chainedtp;`ctp1))];}; - -/ a chained tp named procname subscribing to the proctype uptype, whose phone book holds the given rows plus itself -startctpnamed:{[name;procname;dir;uptype;rows;args] - port:freeport[]; - pcsv:dir,"/process.csv"; - system "mkdir -p ",dir; - writecsvrows[pcsv;rows,enlist (port;`chainedtp;procname)]; - a:"-upstreamtype ",(string uptype)," -tplogdir ",dir,"/log -processcsv ",pcsv," -proctype chainedtp -procname ",(string procname)," ",args; - startchild[name;moddir[],"/test_integration_ctp.q";a;port] - }; - -startctp:{[dir;tp;args] startctpnamed["ctp";`ctp1;dir;`tickerplant;enlist (tp`port;`tickerplant;`tp1);args]}; - -/ a real di.torq.proc.rdb taking the chained tp as its tickerplant type (a replaying di.subscriptions consumer) -startrdb:{[dir;ctp] - port:freeport[]; - pcsv:dir,"/process.csv"; - system "mkdir -p ",dir; - writecsvrows[pcsv;((ctp`port;`chainedtp;`ctp1);(port;`rdb;`rdb1))]; - a:"-tickerplanttypes chainedtp -hdbdir ",dir,"/hdb -processcsv ",pcsv," -proctype rdb -procname rdb1"; - startchild["rdb";moddir[],"/test_integration_rdb.q";a;port] - }; - -kill9:{[c] - @[system;"kill -9 ",(string c`pid)," 2>/dev/null";{}]; - @[hclose;c`h;{}]; - system "sleep 0.5"; - }; - -/ n async feed updates (syms S..) then a sync round-trip, so the tickerplant has processed - and published - them all -feedtp:{[tp;t;from;n] - {[tp;t;i] neg[tp`h](`.u.upd;t;(`$"S",string i;1.0*i))}[tp;t] each from+til n; - tp[`h]"::"; - }; - -/ a sync round-trip to the chained tp: it has processed the upstream's publishes, and its own publishes queued on -/ this handle are processed here before the reply -sync:{[c] c[`h]"::";}; - -subscribe:{[c] `RECV set (); c[`h](`.u.subdetails;`;`)}; - -/ a sync round-trip is not a full barrier: the chained tp may answer it before draining the upstream's backlog on its -/ other socket. wait until its own message count reaches n, then round-trip to collect what it published -msgcount:{[c] (c[`h] "(use`di.torq.proc.chainedtp)[`getcounts][]")`msgcount}; -settle:{[c;n] waitfor[{[c;n;x] n<=msgcount c}[c;n];80]; sync c;}; - -logcount:{[f] r:-11!(-2;f); $[0>type r;r;first r]}; -ctpq:{[c;s] c[`h] s}; -connected:{[c] c[`h] "(use`di.torq.proc.chainedtp)[`connected][]"}; -pcnames:{[c] c[`h] "exec name from (use`di.torq.handlers)[`list]`.z.pc"}; -/ syms received, from a table (live publish) or a list of columns (a replayed log message) -recvsyms:{[] raze {x:last x; $[98h=type x;x`sym;x 1]} each RECV}; -exitcode:{[name] f:hsym`$IBASE,"/",name,".exit"; $[type key f;last read0 f;""]}; -alive:{[pid] not `dead~@[system;"kill -0 ",(string pid)," 2>/dev/null";{`dead}]}; - -/ poll a condition (called as f[], so pass a projection with one argument left) every 0.25s for up to n tries -waitfor:{[f;n] - if[n<=0;:0b]; - if[f[];:1b]; - system "sleep 0.25"; - waitfor[f;n-1] - }; - -probe:{[] - tp:starttp[IBASE,"/probe";""]; - ok:not null tp`h; - kill9 tp; - ok - }; - -relay:{[] - tp:starttp[IBASE,"/relay/tp";""]; - c:startctp[IBASE,"/relay/ctp";tp;""]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - sd:subscribe c; - feedtp[tp;`trade;0;3]; - sync c; - tpdate:tp[`h] "(",TPM,"eod`getd)[]"; - a:`tables`schemas`date`delivered`tableform`ownlog`msgcount`connected`pchandlers!( - `quote`trade~asc sd`tables; - all 98h=type each sd`schemas; - tpdate=sd`date; - `S0`S1`S2~recvsyms[]; - all 98h=type each last each RECV; - 3=logcount sd`logfile; - 3=(c[`h] "(use`di.torq.proc.chainedtp)[`getcounts][]")`msgcount; - connected c; - all `servers`chainedtp`pubsub in pcnames c); - kill9 c; - kill9 tp; - chk a - }; - -startupticks:{[] - / ticks flow into the upstream before, during and after the chained tp starts (replaying with a cleared log): every - / one reaches its log exactly once, and a downstream that replays from that log then follows live sees each once - dir:IBASE,"/ticks"; - tp:starttp[dir,"/tp";""]; - feedtp[tp;`trade;0;5]; - c:startctp[dir,"/ctp";tp;"-replay 1 -clearlogonsubscription 1"]; - / launched but not yet subscribed: these land in the upstream log and are replayed, or arrive live - either way once - feedtp[tp;`trade;5;5]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - feedtp[tp;`trade;10;5]; - sync c; - sd:subscribe c; - / replay the chained tp's own log here, as di.subscriptions would for an rdb, then take two more live - -11!(sd`rowcount;sd`logfile); - feedtp[tp;`trade;15;2]; - sync c; - tplog:tp[`h] "(.u.subdetails)[`;`]"; - kill9 c; - kill9 tp; - chk `replaycount`ownlogcount`tplogcount`received`unique`all!( - 15=sd`rowcount; - 17=logcount sd`logfile; - 17=logcount tplog`logfile; - 17=count RECV; - 17=count distinct recvsyms[]; - all (`$"S",/:string til 17) in recvsyms[]) - }; - -rdbdownstream:{[] - / the consumer this surface exists for: a real rdb, through di.subscriptions, replays the chained tp's log and then - / follows live - and gets the chained tp's end of day - dir:IBASE,"/rdb"; - tp:starttp[dir,"/tp";""]; - c:startctp[dir,"/ctp";tp;""]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - feedtp[tp;`trade;0;3]; - sync c; - r:startrdb[dir,"/rdb";c]; - if[null r`h;kill9 c;kill9 tp;:chk enlist[`rdbup]!enlist 0b]; - feedtp[tp;`trade;3;2]; - feedtp[tp;`quote;10;1]; - sync c; - r[`h]"::"; - a:`replayedandlive`quote`syms`subscribed`gattr!( - 5=r[`h]"count trade"; - 1=r[`h]"count quote"; - (`$"S",/:string til 5)~r[`h]"trade`sym"; - r[`h]"(use`di.subscriptions)[`subscribed][]"; - `g=r[`h]"attr trade`sym"); - tp[`h] "endofday[]"; - waitfor[{[c;r;x] sync c; r[`h]"::"; 0=r[`h]"count trade"}[c;r];40]; - a:a,enlist[`rdbeod]!enlist 0=r[`h]"count trade"; - kill9 r; - kill9 c; - kill9 tp; - chk a - }; - -chainoftwo:{[] - / tp -> ctp1 -> ctp2: the second chained tp subscribes to the first as its proctype, replays from ITS log, and this - / downstream receives through both hops - and the end of day travels the whole chain - dir:IBASE,"/chain"; - tp:starttp[dir,"/tp";""]; - c1:startctp[dir,"/ctp1";tp;""]; - if[null c1`h;kill9 tp;:chk enlist[`ctp1up]!enlist 0b]; - feedtp[tp;`trade;0;2]; - sync c1; - book:((tp`port;`tickerplant;`tp1);(c1`port;`chainedtp;`ctp1)); - c2:startctpnamed["ctp2";`ctp2;dir,"/ctp2";`chainedtp;book;"-replay 1 -clearlogonsubscription 1"]; - if[null c2`h;kill9 c1;kill9 tp;:chk enlist[`ctp2up]!enlist 0b]; - sd:subscribe c2; - -11!(sd`rowcount;sd`logfile); - feedtp[tp;`trade;2;3]; - sync c1; - sync c2; - `EOD set 0Nd; - tp[`h] "endofday[]"; - waitfor[{[c1;c2;x] sync c1; sync c2; not null EOD}[c1;c2];40]; - a:`replayed`received`unique`all`eodchained`upstreamname!( - 2=sd`rowcount; - 5=count RECV; - 5=count distinct recvsyms[]; - all (`$"S",/:string til 5) in recvsyms[]; - (sd`date)=EOD; - `chainedtp~c2[`h] SM,"upstreamtype"); - kill9 c2; - kill9 c1; - kill9 tp; - chk a - }; - -/ a burst of n ten-row batches (syms B) then a sync round-trip -burst:{[tp;n] - {[tp;i] neg[tp`h](`.u.upd;`trade;(10#`$"B",string i;10#1.0*i))}[tp] each til n; - tp[`h]"::"; - }; - -volume:{[] - / 2000 ten-row batches through each mode: nothing lost, nothing duplicated, the log holds one message per batch, and - / the batched buffer copes (the upsert-by-value idiom would go quadratic here) - tp:starttp[IBASE,"/volume/tp";""]; - c:startctp[IBASE,"/volume/ctp";tp;""]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - sd:subscribe c; - st:.z.p; - burst[tp;2000]; - settle[c;2000]; - imm:`immrows`immmsgs`immlog!(20000=count recvsyms[];2000=count RECV;2000=logcount sd`logfile); - immms:(`long$.z.p-st) div 1000000; - kill9 c; - c:startctp[IBASE,"/volume/ctpb";tp;"-publishmode batched -pubperiod 1"]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - sd:subscribe c; - st:.z.p; - burst[tp;2000]; - settle[c;2000]; - waitfor[{[c;x] sync c; 20000=count recvsyms[]}[c];40]; - bat:`batrows`batunique`batlog!(20000=count recvsyms[];2000=count distinct recvsyms[];2000=logcount sd`logfile); - batms:(`long$.z.p-st) div 1000000; - kill9 c; - kill9 tp; - `VOLMS set `immediate`batched!(immms;batms); - chk imm,bat - }; - -batched:{[] - tp:starttp[IBASE,"/batched/tp";""]; - c:startctp[IBASE,"/batched/ctp";tp;"-publishmode batched -pubperiod 1"]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - subscribe c; - feedtp[tp;`trade;0;2]; - sync c; - pending:(c[`h] "(use`di.torq.proc.chainedtp)[`getcounts][]")`tables; - system "sleep 2"; - sync c; - after:(c[`h] "(use`di.torq.proc.chainedtp)[`getcounts][]")`tables; - kill9 c; - kill9 tp; - chk `buffered`flushedbytimer`delivered`onemessage!( - 2=first exec pendingrowcount from pending where tbl=`trade; - (2;0)~first each exec (rowcount;pendingrowcount) from after where tbl=`trade; - `S0`S1~recvsyms[]; - 1=count RECV) - }; - -narrowed:{[] - tp:starttp[IBASE,"/narrowed/tp";""]; - c:startctp[IBASE,"/narrowed/ctp";tp;"-subscribeto trade"]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - sd:subscribe c; - feedtp[tp;`trade;0;2]; - feedtp[tp;`quote;10;2]; - sync c; - kill9 c; - kill9 tp; - chk `tables`tradeonly`ownlog!((enlist`trade)~sd`tables;all `trade=first each RECV;2=logcount sd`logfile) - }; - -eod:{[] - tp:starttp[IBASE,"/eod/tp";""]; - c:startctp[IBASE,"/eod/ctp";tp;""]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - sd:subscribe c; - feedtp[tp;`trade;0;2]; - sync c; - `EOD set 0Nd; - / the upstream ends its day: it tells the chained tp, which rolls and tells this process - tp[`h] "endofday[]"; - waitfor[{[c;x] sync c; not null EOD}[c];40]; - sd1:c[`h](`.u.subdetails;`;`); - kill9 c; - kill9 tp; - chk `downstream`dateadvanced`newlog`newlogempty`oldlogkept!( - (sd`date)=EOD; - (1+sd`date)=sd1`date; - (string sd1`logfile) like "*_",string 1+sd`date; - 0=sd1`rowcount; - 2=logcount sd`logfile) - }; - -upstreamloss:{[] - tp:starttp[IBASE,"/loss/tp";""]; - c:startctp[IBASE,"/loss/ctp";tp;""]; - if[null c`h;kill9 tp;:chk enlist[`childup]!enlist 0b]; - a:`upbefore`alivebefore!(connected c;alive c`pid); - / a real crash of the upstream - kill9 tp; - waitfor[{"EXIT=0"~exitcode"ctp"};60]; - a:a,`gone`exit0`logged!( - not alive c`pid; - "EXIT=0"~exitcode"ctp"; - 0 di.torq.init -> settings cascade -> startbuiltin, for both process types --- - -/ the kdbx-modules root that holds di/torq (two levels above the di.torq module dir) -torqxhome:{[] p:.Q.m.mp`di.torq; p:$[10h=type p;p;string p]; p:$[":"=first p;1_p;p]; "/" sv -2_"/" vs p}; - -stackapp:{[] - / a minimal app: schema, and a proctype-tier toml for each process type - app:IBASE,"/app"; - system "mkdir -p ",app,"/appconfig/settings"; - (hsym`$app,"/database.q") 0: ( - "trade:([]time:`timestamp$();sym:`g#`symbol$();price:`float$())"; - "quote:([]time:`timestamp$();sym:`g#`symbol$();bid:`float$())"); - (hsym`$app,"/appconfig/settings/default.toml") 0: enlist "# app defaults"; - (hsym`$app,"/appconfig/settings/tickerplant.toml") 0: ("tplogdir = \"tplog\"";"publishmode = \"immediate\""); - (hsym`$app,"/appconfig/settings/chainedtp.toml") 0: ( - "upstreamtype = \"tickerplant\"";"tplogdir = \"ctplog\"";"publishmode = \"immediate\"";"connecttimeoutms = 15000"); - app}; - -startstack:{[app;proctype;procname;port] - / launch exactly as torqx.sh does: QINIT=torqx_init.q with explicit identity and a stack id - ident:" -proctype ",(string proctype)," -procname ",(string procname)," -torqxstackid itest"; - cmd:"QINIT=",torqxhome[],"/di/torq/bin/torqx_init.q ",QBIN," -q -p ",(string port),ident; - pid:"J"$first system cmd," >",IBASE,"/stack_",(string procname),".log 2>&1 & echo $!"; - `PIDS set PIDS,pid; - `pid`port`h!(pid;port;waitopen[port;120])}; - -stackboot:{[] - / kdb-x abandons a QINIT script silently at the first error and leaves the process at its prompt, so a boot failure - / looks like a running process: assert the module's observable effects, never just "it came up" - app:stackapp[]; - setenv[`TORQXHOME;torqxhome[]]; - setenv[`TORQXAPPCONFIG;app,"/appconfig"]; - setenv[`TORQXAPPHOME;app]; - setenv[`TORQXDATAHOME;app]; - tpport:freeport[]; - ctpport:freeport[]; - writecsv[app,"/appconfig/process.csv";tpport;ctpport]; - tp:startstack[app;`tickerplant;`tp1;tpport]; - if[null tp`h;:chk enlist[`tpup]!enlist 0b]; - c:startstack[app;`chainedtp;`ctp1;ctpport]; - if[null c`h;:chk enlist[`ctpup]!enlist 0b]; - sd:subscribe c; - feedtp[tp;`trade;0;3]; - sync c; - a:`identity`updpublished`cascade`connected`pchandlers`ownlog`delivered!( - (`chainedtp;`ctp1)~c[`h]"(",SM,"proctype;",SM,"procname)"; - c[`h]"`upd in key `."; - (`tickerplant;`immediate;15000;app,"/ctplog")~c[`h]"(",SM,"upstreamtype;",SM,"publishmode;",SM,"connecttimeoutms;",SM,"tplogdir)"; - connected c; - all `servers`chainedtp`pubsub in pcnames c; - 3=logcount sd`logfile; - `S0`S1`S2~recvsyms[]); - @[c`h;"exit 0";{}]; - @[tp`h;"exit 0";{}]; - system "sleep 1"; - setenv[`TORQXAPPHOME;IBASE]; - setenv[`TORQXDATAHOME;IBASE]; - chk a - }; diff --git a/di/torq/proc/chainedtp/test_integration_ctp.q b/di/torq/proc/chainedtp/test_integration_ctp.q deleted file mode 100644 index 6d5cb3e9..00000000 --- a/di/torq/proc/chainedtp/test_integration_ctp.q +++ /dev/null @@ -1,31 +0,0 @@ -/ child process for test_integration.csv - not a test file itself; test_integration.q launches it. Runs -/ di.torq.proc.chainedtp wired the way di.torq wires it: the REAL di.util.log, di.timer, di.torq.handlers and - built -/ last, as it consumes the other three - di.torq.servers, whose init takes this process's identity and the process.csv -/ phone book from the config. Every -flag value on the command line becomes a config setting as a STRING (as a .toml -/ or a command-line override would deliver it), so the module's own coercions are exercised: -upstreamtype -tplogdir -/ -publishmode -pubperiod -replay -clearlogonsubscription -subscribeto -subscribesyms -connecttimeoutms -processcsv -/ -proctype -procname - -o:.Q.opt .z.x; -cfg:(key o)!first each value o; -/ di.torq.servers requires its self-identity as symbols (di.torq stamps them so) -cfg[`proctype]:`$cfg`proctype; -cfg[`procname]:`$cfg`procname; - -lg:use`di.util.log; -logdep:`info`warn`error!(lg`info;lg`warn;lg`error); - -tm:use`di.timer; -tm[`init][()!()]; -timerdep:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!((tm`addjob)`custom;tm`deletejobs;tm`enablejobs;tm`disablejobs;tm`getactivejobs); - -hz:use`di.torq.handlers; -hz[`init][enlist[`log]!enlist logdep]; -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list); - -srv:use`di.torq.servers; -srv[`init][cfg,`log`timer`handlers!(logdep;timerdep;handlersdep)]; -serversdep:`startup`getservers`gethandlebytype`waitfortype!(srv`startup;srv`getservers;srv`gethandlebytype;srv`waitfortype); - -ctp:use`di.torq.proc.chainedtp; -ctp[`init][cfg;`log`timer`handlers`servers!(logdep;timerdep;handlersdep;serversdep)]; diff --git a/di/torq/proc/chainedtp/test_integration_rdb.q b/di/torq/proc/chainedtp/test_integration_rdb.q deleted file mode 100644 index 463a2a21..00000000 --- a/di/torq/proc/chainedtp/test_integration_rdb.q +++ /dev/null @@ -1,28 +0,0 @@ -/ downstream child for test_integration.csv - not a test file itself; test_integration.q launches it. Runs a REAL -/ di.torq.proc.rdb wired as di.torq wires it (real di.util.log, di.timer, di.torq.handlers, di.torq.servers), pointed at -/ the chained tickerplant as its tickerplant type - so the chained tp's surface is exercised by the consumer it is meant -/ to be indistinguishable to, through di.subscriptions' real subscribe-and-replay. Every -flag value on the command line -/ becomes a config setting as a STRING: -tickerplanttypes -hdbdir -processcsv -proctype -procname -replaylog - -o:.Q.opt .z.x; -cfg:(key o)!first each value o; -cfg[`proctype]:`$cfg`proctype; -cfg[`procname]:`$cfg`procname; - -lg:use`di.util.log; -logdep:`info`warn`error!(lg`info;lg`warn;lg`error); - -tm:use`di.timer; -tm[`init][()!()]; -timerdep:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!((tm`addjob)`custom;tm`deletejobs;tm`enablejobs;tm`disablejobs;tm`getactivejobs); - -hz:use`di.torq.handlers; -hz[`init][enlist[`log]!enlist logdep]; -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list); - -srv:use`di.torq.servers; -srv[`init][cfg,`log`timer`handlers!(logdep;timerdep;handlersdep)]; -serversdep:`startup`getservers`gethandlebytype`waitfortype!(srv`startup;srv`getservers;srv`gethandlebytype;srv`waitfortype); - -rdb:use`di.torq.proc.rdb; -rdb[`init][cfg;`log`timer`handlers`servers!(logdep;timerdep;handlersdep;serversdep)]; diff --git a/di/torq/proc/chainedtp/test_integration_tp.q b/di/torq/proc/chainedtp/test_integration_tp.q deleted file mode 100644 index 3f7854ef..00000000 --- a/di/torq/proc/chainedtp/test_integration_tp.q +++ /dev/null @@ -1,21 +0,0 @@ -/ upstream child for test_integration.csv - not a test file itself; test_integration.q launches it. Runs a REAL -/ di.torq.proc.tickerplant wired to the real di.timer, di.torq.handlers and di.util.log (built as di.torq builds them), -/ so the chained tickerplant under test subscribes to, replays from and is cut off by a genuine tickerplant. Every -/ -flag value on the command line becomes a config setting as a STRING: -tplogdir -schemafile -publishmode -pubperiod - -o:.Q.opt .z.x; -cfg:(key o)!first each value o; - -lg:use`di.util.log; -logdep:`info`warn`error!(lg`info;lg`warn;lg`error); - -tm:use`di.timer; -tm[`init][()!()]; -timerdep:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!((tm`addjob)`custom;tm`deletejobs;tm`enablejobs;tm`disablejobs;tm`getactivejobs); - -hz:use`di.torq.handlers; -hz[`init][enlist[`log]!enlist logdep]; -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list); - -tp:use`di.torq.proc.tickerplant; -tp[`init][cfg;`log`timer`handlers!(logdep;timerdep;handlersdep)]; diff --git a/di/torq/proc/chainedtp/test_upstream.q b/di/torq/proc/chainedtp/test_upstream.q deleted file mode 100644 index 3e4e72a9..00000000 --- a/di/torq/proc/chainedtp/test_upstream.q +++ /dev/null @@ -1,16 +0,0 @@ -/ stub upstream for di.torq.proc.chainedtp's unit tests - not a test file itself; test.q launches it as a separate q -/ process and dials it, so di.subscriptions' .u.subdetails call and the module's .z.pc handling run over a genuine -/ IPC handle without a full tickerplant. The reply is whatever SD the harness last set over the handle, narrowed to -/ the requested tables; every call is counted so the harness can assert a single subscription per init. - -SD:()!(); -CALLS:0; - -.u.subdetails:{[tabs;syms] - CALLS+:1; - r:SD; - if[not tabs~`; - r[`tables]:(),tabs; - r[`schemas]:((),tabs)#r`schemas]; - r - }; From 7cd232098789e33c1af29cce1f39e70f8ce18f9e Mon Sep 17 00:00:00 2001 From: alowrydi Date: Mon, 28 Sep 2026 17:27:49 +0100 Subject: [PATCH 15/42] di.torq.proc.chainedtp 0.2.1: endofday convention and a temporary di-protocol layer End of day follows the rdb/wdb convention: .u.end sends (`endofday;d) to subscribers rather than (`.u.end;d), and root endofday[d] calls .u.end d. This is the one change to the ported legacy text, made on request: there are no legacy subscribers, and the di rdb/wdb only answer endofday (their .u.end alias, @[`.;`.u.end;:;endofday], does not resolve once a .u namespace exists). Temporary compatibility block (between / compat begin and / compat end), so chainedtp sits between the di tickerplant and di rdb/wdb, which speak di.subscriptions' .u.subdetails protocol: - upstream: init calls .ctp.subscribedi[] instead of .ctp.subscribe[] (the only other changed line). Same handle lookup and refreshtp, then di.subscriptions subscribe, then .u.d from the reply. - downstream: root .u.subdetails[tabs;syms] subscribes the caller through .ctp.sub and returns tables/schemas/logfile/rowcount/date. It handles the single-table pair shape. Limits: logfile is ` and rowcount 0 (no replay from chainedtp); .u.icounts starts empty; .sub.SUBSCRIPTIONS is not filled on this path; unknown-table error pairs pass through. chainedtp.md lists the removal steps. Tests: a compat: group with a real di.subscriptions subscriber peer, and a fixture upstream that also answers .u.subdetails. The legacy .sub path is still exercised by an explicit .ctp.subscribe[] row. Test peers answer endofday. 63/63; di.torq 56/56. Verified live on a scratch POC: feed -> tickerplant1 -> chainedtp1 -> rdb1/wdb1 -> hdb/gateway. Counts matched at each hop, and the gateway count equalled rdb plus hdb. A forced endofday on the tickerplant saved the partition into the hdb and reloaded the hdb and rdb. This needs hdb and gateway started before wdb. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/VERSION | 2 +- di/torq/proc/chainedtp/chainedtp.md | 32 ++++++++++++++++++++++++++--- di/torq/proc/chainedtp/chainedtp.q | 29 ++++++++++++++++++++++++-- di/torq/proc/chainedtp/test.csv | 23 +++++++++++++++++---- di/torq/proc/chainedtp/test.q | 24 ++++++++++++++-------- 5 files changed, 92 insertions(+), 18 deletions(-) diff --git a/di/torq/proc/chainedtp/VERSION b/di/torq/proc/chainedtp/VERSION index 0ea3a944..0c62199f 100644 --- a/di/torq/proc/chainedtp/VERSION +++ b/di/torq/proc/chainedtp/VERSION @@ -1 +1 @@ -0.2.0 +0.2.1 diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index 8b687299..9541f0fd 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -11,7 +11,8 @@ batches. | `tptype` | `` `chained `` | | `tablelist[]` | the published tables (`.stpps.t`) | | `subdetails[tabs;instruments]` | subscribes the caller and returns `schemalist`, `logfilelist`, `rowcounts`, `date` | -| `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`.u.end;d) `` to subscribers | +| `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`endofday;d) `` to subscribers | +| `endofday[d]` | root; calls `.u.end d` (the upstream's end-of-day message) | | `upd` | set at root to `.ctp.upd` if no `upd` exists | | `.ctp.*` | settings, `subscribe`, `writetolog`, `tickpub`, `batchpub`, `publishalltables`, `cleartables`, `openlog`, `clearlog`, `refreshtp`, `createlogfilename`, `notpconnected`, `sub` | | `.u.i`/`.u.j`/`.u.icounts`/`.u.jcounts`/`.u.L`/`.u.l`/`.u.d` | publish and log counts, log file and handle, date | @@ -49,11 +50,36 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th - The upstream is found by procname through `di.torq.servers` (with the default settings, through discovery). With `tpcheckcycles` `0W` it waits for it indefinitely. -- An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. +- End of day follows the rdb/wdb convention: `endofday[d]` in, `` (`endofday;d) `` out. - A corrupt own log is reported and opened anyway. - `.u.icounts` values are one-item lists after an all-syms subscribe. - `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. +## Compatibility layer (temporary) + +Between `/ compat begin` and `/ compat end` in `chainedtp.q`, plus the `/ compat` line in `init`. +It lets chainedtp sit between a di tickerplant and di rdb/wdb, which speak `di.subscriptions`' +`.u.subdetails` protocol. + +- Upstream: `init` subscribes with `.ctp.subscribedi[]` in place of `.ctp.subscribe[]`: same handle + lookup and `refreshtp`, then `di.subscriptions` `subscribe`, then `.u.d` from the reply. +- Downstream: root `.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub` and returns + `tables`, `schemas`, `logfile`, `rowcount`, `date`. + +Limits: +- `logfile` is always `` ` `` and `rowcount` 0, so subscribers never replay from chainedtp. +- The upstream reply carries no per-table counts; `.u.icounts` starts empty. +- `.sub.SUBSCRIPTIONS` is not filled on this path, so `.ctp.notpconnected` reads empty. +- An unknown table comes back as a `(table;message)` pair, unfiltered. + +To remove: +1. Delete the block between `/ compat begin` and `/ compat end`. +2. In `init`, put back `.ctp.subscribe[];` for `.ctp.subscribedi[]; / compat`. +3. Delete the `compat:` rows in `test.csv`, and the `compat:` lines in `test.q` (the fixture's + `.u.subdetails`, the `dsub.q` peer, `DSPORT`/`sh`); put the `.sub.SUBSCRIPTIONS` check back in + the init group. +4. Delete this section. + ## Testing ```q @@ -63,5 +89,5 @@ k4unit.moduletest`di.torq.proc.chainedtp `test.q`/`test.csv` run a real upstream (segmented tickerplant surface, found through `di.torq.servers`) and a real downstream subscriber: subscribe and schema, tick-by-tick delivery, -`subdetails`, `tablelist`, `.u.end`, the own log, batch publish, `clearlogonsubscription`, and a +`subdetails`, `tablelist`, end of day, the own log, batch publish, `clearlogonsubscription`, and a corrupt log. diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 0913eeae..5935a4df 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -18,7 +18,7 @@ init:{[config;deps] if[not `upd in key `.;set[`upd;.ctp.upd]]; .ps.initialise[]; .servers.startupdepnamecycles[.ctp.tickerplantname;.ctp.tpconnsleep;.ctp.tpcheckcycles]; - .ctp.subscribe[]; + .ctp.subscribedi[]; / compat .ctp.tableschemas:{x!(0#)@'value@'x} (),$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto]; if[.ctp.pubinterval;(deps[`timer]`addjob)[`publishalltables;.ctp.publishalltables;();`long$.ctp.pubinterval%0D00:00:01;2;()!()]]; } @@ -156,7 +156,32 @@ end:{[d] .z.m.log[`info][`end;"end of day invoked"]; .ctp.publishalltables[]; .ctp.refreshtp[d+1]; - (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`.u.end;d) + (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`endofday;d) } \d . + +endofday:{[d] .u.end d} + +/ compat begin +\d .ctp + +subscribedi:{[] + s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; + if[count s; + subproc:first s; + .ctp.tph:subproc`w; + refreshtp @[tph;".u.d";.z.D]; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:(use`di.subscriptions)[`subscribe][tph;subscribeto;subscribesyms;replay]; + .u.d::r`date]; + } + +\d . + +.u.subdetails:{[tabs;syms] + s:(.ctp.sub[tabs;syms])`schema; + if[-11h=type first s;s:enlist s]; + `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];`;0;.u.d) + } +/ compat end diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index e2a895b1..21a2372d 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -15,14 +15,16 @@ comment,,,,,,,init - connect and subscribe run,0,0,q,ctp.init[cfg[];deps[]],1,,init true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root -true,0,0,q,.u.d~D,1,,date taken from the upstream -true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade +true,0,0,q,.u.d~D,1,,compat: date taken from the .u.subdetails reply +true,0,0,q,"1=count (use`di.subscriptions)[`getsubscriptions][]",1,,compat: subscribed through di.subscriptions true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) true,0,0,q,`trade in .stpps.t,1,,trade is published +run,0,0,q,.ctp.subscribe[],1,,subscribe through .sub +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade comment,,,,,,,tick by tick run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstream peer @@ -37,8 +39,8 @@ true,0,0,q,"()~(dh""(.z.w)(`subdetails;`trade;`)"")`logfilelist",1,,no log file true,0,0,q,"`trade in dh""(.z.w)(`tablelist;`)""",1,,tablelist lists trade comment,,,,,,,end of day -run,0,0,q,.u.end D,1,,end of day -true,0,0,q,"(enlist D)~dh""ended""",1,,.u.end passed to the downstream +run,0,0,q,endofday D,1,,end of day through root endofday +true,0,0,q,"(enlist D)~dh""ended""",1,,endofday passed to the downstream true,0,0,q,.u.d=D+1,1,,date rolled true,0,0,q,0=count trade,1,,trade cleared @@ -64,4 +66,17 @@ true,0,0,q,"errlogged""is corrupt""",1,,corruption reported true,0,0,q,-6h=type bh,1,,and the log opened anyway true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 +comment,,,,,,,compat: di.subscriptions subscriber downstream +run,0,0,q,.stpps.closesub 0i,1,,compat: drop handle 0 left by the local subdetails call +run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,compat: connect to the di.subscriptions peer +run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,compat: peer subscribes to trade through .u.subdetails +true,0,0,q,(enlist`trade)~sd`tables,1,,compat: tables is a symbol list for one table +true,0,0,q,"(`;0)~sd`logfile`rowcount",1,,compat: no log and no replay +true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,compat: schema for trade +true,0,0,q,"sh""`trade in tables[]""",1,,compat: trade defined at root on the peer +true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,compat: peer recorded the subscription +true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `trade in sd2`tables",1,,compat: tables is a symbol list for all tables +run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,compat: upstream publishes 2 rows +true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,compat: peer received the rows + after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 3882ebde..df50b4e3 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -13,9 +13,9 @@ D:2026.09.28 QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.p/dev/null 2>&1 &"}'[("up.q";"down.q");(UPPORT;DNPORT)]; - if[not all waitlisten each UPPORT,DNPORT;'"test: peers failed to listen"]; + `UPPORT`DNPORT`DSPORT set' 3#p; + {system QBIN," ",FIXDIR,"/",x," -p ",(string y)," -q /dev/null 2>&1 &"}'[("up.q";"down.q";"dsub.q");(UPPORT;DNPORT;DSPORT)]; + if[not all waitlisten each UPPORT,DNPORT,DSPORT;'"test: peers failed to listen"]; (`$":",FIXDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string UPPORT),",tickerplant,tickerplant1"); } @@ -40,4 +48,4 @@ deps:{[] `log`timer`handlers!(mocklog;mocktimer;mockhandlers)} rows:{[n] ([]time:n#.z.p;sym:n#`a`b;price:`float$til n)} -teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each (.ctp.tph;dh); system "sleep 0.3"; system "rm -rf ",FIXDIR;} +teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each (.ctp.tph;dh;sh); system "sleep 0.3"; system "rm -rf ",FIXDIR;} From b2c51ade3beedf66a521a9c0f75ec0a292efc0f5 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 29 Sep 2026 10:47:09 +0100 Subject: [PATCH 16/42] di.torq.proc.chainedtp: .u.subdetails reports the own log and its count With createlogfile on, subscribers replay chainedtp's log on connect. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.md | 4 ++-- di/torq/proc/chainedtp/chainedtp.q | 4 ++-- di/torq/proc/chainedtp/test.csv | 7 ++++++- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index 9541f0fd..f8b24a2e 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -64,10 +64,10 @@ It lets chainedtp sit between a di tickerplant and di rdb/wdb, which speak `di.s - Upstream: `init` subscribes with `.ctp.subscribedi[]` in place of `.ctp.subscribe[]`: same handle lookup and `refreshtp`, then `di.subscriptions` `subscribe`, then `.u.d` from the reply. - Downstream: root `.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub` and returns - `tables`, `schemas`, `logfile`, `rowcount`, `date`. + `tables`, `schemas`, `logfile`, `rowcount`, `date`. With `createlogfile` on, `logfile` is `.u.L` + and `rowcount` `.u.i`, so subscribers replay chainedtp's own log; otherwise `` ` `` and 0. Limits: -- `logfile` is always `` ` `` and `rowcount` 0, so subscribers never replay from chainedtp. - The upstream reply carries no per-table counts; `.u.icounts` starts empty. - `.sub.SUBSCRIPTIONS` is not filled on this path, so `.ctp.notpconnected` reads empty. - An unknown table comes back as a `(table;message)` pair, unfiltered. diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 5935a4df..19494ad0 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -180,8 +180,8 @@ subscribedi:{[] \d . .u.subdetails:{[tabs;syms] - s:(.ctp.sub[tabs;syms])`schema; + r:.ctp.sub[tabs;syms]; s:r`schema; if[-11h=type first s;s:enlist s]; - `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];`;0;.u.d) + `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[.ctp.createlogfile;r`logfile;`];$[.ctp.createlogfile;r`i;0];.u.d) } / compat end diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 21a2372d..17e1cc35 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -68,10 +68,15 @@ true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 comment,,,,,,,compat: di.subscriptions subscriber downstream run,0,0,q,.stpps.closesub 0i,1,,compat: drop handle 0 left by the local subdetails call +run,0,0,q,".ctp.refreshtp D;.ctp.writetolog[`trade;rows 3];.ctp.tickpub[`trade;rows 3]",1,,compat: fresh log with one 3-row message before the peer subscribes run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,compat: connect to the di.subscriptions peer run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,compat: peer subscribes to trade through .u.subdetails true,0,0,q,(enlist`trade)~sd`tables,1,,compat: tables is a symbol list for one table -true,0,0,q,"(`;0)~sd`logfile`rowcount",1,,compat: no log and no replay +true,0,0,q,"(.u.L;1)~sd`logfile`rowcount",1,,compat: own log and its message count +true,0,0,q,"(1;`trade;3)~sh""(count got;first first got;count last first got)""",1,,compat: peer replayed the pre-subscribe message +run,0,0,q,".ctp.createlogfile:0b",1,,compat: logging off +true,0,0,q,"(`;0)~(sh""(.z.w)(`.u.subdetails;`trade;`)"")`logfile`rowcount",1,,compat: no log and no replay without createlogfile +run,0,0,q,".ctp.createlogfile:1b",1,,compat: logging back on true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,compat: schema for trade true,0,0,q,"sh""`trade in tables[]""",1,,compat: trade defined at root on the peer true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,compat: peer recorded the subscription From 81d07f468eed69d9fbe24cc513fb347a12f9256d Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 11:50:58 +0100 Subject: [PATCH 17/42] di.pubsub: log is a required init dependency; servers test spawns with QBIN - di.pubsub init errors unless deps is a dict with log, so .stpps errparse/init/sub always have a logger (a missing log no longer surfaces as a .z.m.log error). - di.torq.proc.tickerplant passes its log to di.pubsub init. - pubsub tests: init with a no-op log; init[] must error. - servers test.csv: the enabled:0b check runs QBIN, not $QHOME/bin/q. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/pubsub.md | 6 +++--- di/pubsub/pubsub.q | 7 +++---- di/pubsub/test.csv | 5 +++-- di/torq/proc/tickerplant/tickerplant.q | 2 +- di/torq/servers/test.csv | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 1e8afe3c..7fc5f6d8 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -53,7 +53,7 @@ publish data with/without filters. The function takes two arguments: t and x, wh | `pubsub.callendofperiod` | Broadcast an end-of-period event to all subscribers (requires `endofperiod`).| | `pubsub.closesub` | Remove handle upon connection close. Not bound to `.z.pc` by the module - the consumer binds it (see Notes). | | `pubsub.subclear` | Publish tables and clear up the contents. | -| `pubsub.init` | Initialize variables - run before calling pub/sub functions to populate required state (e.g., tables/schemas). | +| `pubsub.init` | Initialize variables - run before calling pub/sub functions to populate required state (e.g., tables/schemas). Takes a deps dict with a required `log`. | --- ### Example: @@ -63,7 +63,7 @@ q).u.sub:pubsub.subscribe q).u.pub:pubsub.publish q)pubsub.setsubtables[`trade`quote] -q)pubsub.init[] +q)pubsub.init[enlist[`log]!enlist log] q)pubsub.subscribe[`;`] q)pubsub.subscribe[`;`AAPL`GOOG] @@ -93,5 +93,5 @@ separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `. `delhandle`/`delhandlef`/`closesub`/`extractschema`/`init`, root `.u.sub`, and `.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`. -- `init[enlist[`log]!enlist log]` wires its error logging (optional; `init[]` is unchanged). +- `.stpps` logs its errors through the `log` passed to `init`. - The consumer registers `.stpps.closesub` on `.z.pc` through its handlers dependency. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 625b6715..16b1f328 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -122,10 +122,9 @@ setsubtables`; initialized:0b; init:{[deps] - / optional deps: log - if[99h=type deps; - if[not `log in key deps;'"di.pubsub: log dependency is required - see di.util.log"]; - .z.m.log:deps`log]; + if[99h<>type deps;'"di.pubsub: deps must be a dict with a log key"]; + if[not `log in key deps;'"di.pubsub: log dependency is required - see di.util.log"]; + .z.m.log:deps`log; .z.m.t:$[count subtables;subtables;tables[]except`reqfilteredtbl]; .z.m.schemas:t!extractschema each t; .z.m.tabcols:t!cols each t; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index 34979c3b..e5aa98ff 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -9,7 +9,7 @@ run,0,0,q,h".z.pc:pubsub.closesub",1,,bind closesub to .z.pc on the server (the true,0,0,q,h>0,1,,verify client connected to server run,0,0,q,h"trade:([]time:\"p\"$();`g#sym:`$();price:\"f\"$();tsize:\"i\"$());",1,,define trade table on server run,0,0,q,h"quote:([]time:\"p\"$();`g#sym:`$();bid:\"f\"$();bidsize:\"i\"$();ask:\"f\"$();asksize:\"i\"$());",1,,define quote table on server -run,0,0,q,h".m.di.0pubsub.init[]",, +run,0,0,q,"h"".m.di.0pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m]}]""",1,,init with a no-op log true,0,0,q,1b~h".m.di.0pubsub.initialized",1,,confirm server initialized with necessary data run,0,0,q,clt:first h"key[.z.W]",1,,get client handle on server run,0,0,q,upd:insert,1,,define local upd function @@ -116,8 +116,9 @@ true,0,0,q,res[`filts][0]~enlist enlist(>;`bid;50f),1,, test symbols are listed comment,,,,,,,root .stpps/.u.sub/.ps true,0,0,q,"h"".ps.loaded""",1,,.ps.loaded is set when the module loads -run,0,0,q,"h""pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m] `lastlog set (c;m)}]""",1,,wire a recording log through init's optional deps +run,0,0,q,"h""pubsub.init[enlist[`log]!enlist `info`warn`error!3#enlist{[c;m] `lastlog set (c;m)}]""",1,,wire a recording log through init fail,0,0,q,"h""pubsub.init[enlist[`x]!enlist 1]""",1,,init deps without log must error +fail,0,0,q,"h""pubsub.init[]""",1,,init without deps must error run,0,0,q,"h"".ps.initialise[]""",1,,.ps.initialise registers every root table true,0,0,q,"h"".ps.initialised""",1,,initialised flag set true,0,0,q,"all `trade`quote in h"".stpps.t""",1,,trade and quote are pub/sub tables diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 941900ae..73f2dadc 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -139,7 +139,7 @@ init:{[config;deps] / which used to replace the di.torq.handlers dispatcher installed moments earlier by di.torq .z.m.ps:use`di.pubsub; (.z.m.ps`setsubtables)[tabs]; - (.z.m.ps`init)[]; + (.z.m.ps`init)[enlist[`log]!enlist .z.m.log]; (.z.m.handlers`register)[`.z.pc;`;`pubsub;0;.z.m.ps`closesub]; / eodtime: single merged dict (log + tz config) diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 73f89c16..f82b6b6a 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -17,7 +17,7 @@ true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retr true,0,0,q,3 3~exec mode from timercalls where id in `serversretry`discoveryretry,1,1,both jobs use timer mode 3 true,0,0,q,1=count select from timercalls where id=`discoveryretry,1,1,init scheduled the discoveryretry job true,0,0,q,.servers.enabled,1,1,enabled defaults to 1b -true,0,0,q,"0~first ""J""$system (getenv[`QHOME]),""/bin/q di/torq/servers/test_enabled.q -q""",1,1,enabled:0b schedules neither retry job +true,0,0,q,"0~first ""J""$system QBIN,"" di/torq/servers/test_enabled.q -q""",1,1,enabled:0b schedules neither retry job run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,re-init must be idempotent true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,idempotent re-init did NOT add a second retry job true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,idempotent re-init did NOT re-register the pc handler From aff97ca38b5f33189a01188cd83ac600fb3e6003 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 29 Sep 2026 14:26:48 +0100 Subject: [PATCH 18/42] aligning subscription methods to the repo --- di/torq/proc/chainedtp/chainedtp.q | 48 +++++++----------------------- 1 file changed, 11 insertions(+), 37 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 19494ad0..fce9f4fb 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -18,7 +18,7 @@ init:{[config;deps] if[not `upd in key `.;set[`upd;.ctp.upd]]; .ps.initialise[]; .servers.startupdepnamecycles[.ctp.tickerplantname;.ctp.tpconnsleep;.ctp.tpcheckcycles]; - .ctp.subscribedi[]; / compat + .ctp.subscribe[]; .ctp.tableschemas:{x!(0#)@'value@'x} (),$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto]; if[.ctp.pubinterval;(deps[`timer]`addjob)[`publishalltables;.ctp.publishalltables;();`long$.ctp.pubinterval%0D00:00:01;2;()!()]]; } @@ -29,9 +29,10 @@ tptype:`chained; tablelist:{.stpps.t} -subdetails:{[tabs;instruments] - r:.ctp.sub[tabs;instruments]; - `schemalist`logfilelist`rowcounts`date!r@/:(`schema;$[r[`logfile]~();();enlist`i`logfile];`icounts;`d) +.u.subdetails:{[tabs;syms] + r:.ctp.sub[tabs;syms]; s:r`schema; + if[-11h=type first s;s:enlist s]; + `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[.ctp.createlogfile;r`logfile;`];$[.ctp.createlogfile;r`i;0];.u.d) } \d .ctp @@ -78,17 +79,12 @@ openlog:{[lgfile] subscribe:{[] s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; if[count s; - subproc:first s; - .ctp.tph:subproc`w; - refreshtp @[tph;".u.d";.z.D]; - .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; - r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; - if[`d in key r;.u.d::r[`d]]; - if[(`icounts in key r) & (not createlogfile); - subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); - .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; - ] - ]; + subproc:first s; + .ctp.tph:subproc`w; + refreshtp @[tph;".u.d";.z.D]; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:(use`di.subscriptions)[`subscribe][tph;subscribeto;subscribesyms;replay]; + .u.d::r`date]; } writetolog:{[t;x] @@ -163,25 +159,3 @@ end:{[d] endofday:{[d] .u.end d} -/ compat begin -\d .ctp - -subscribedi:{[] - s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; - if[count s; - subproc:first s; - .ctp.tph:subproc`w; - refreshtp @[tph;".u.d";.z.D]; - .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; - r:(use`di.subscriptions)[`subscribe][tph;subscribeto;subscribesyms;replay]; - .u.d::r`date]; - } - -\d . - -.u.subdetails:{[tabs;syms] - r:.ctp.sub[tabs;syms]; s:r`schema; - if[-11h=type first s;s:enlist s]; - `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[.ctp.createlogfile;r`logfile;`];$[.ctp.createlogfile;r`i;0];.u.d) - } -/ compat end From 0c95f36a5f749d897fec375d99336e98abbbec8c Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 12:04:31 +0100 Subject: [PATCH 19/42] di.torq.proc.chainedtp: tests and docs for the di.subscriptions path The di.subscriptions subscribe and root .u.subdetails are now the only path, so the tests check them in place of .sub and the old subdetails, the test upstream drops its segmented-tickerplant surface, and the compat labels and the temporary-layer section in chainedtp.md go. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.md | 48 +++++++++------------------- di/torq/proc/chainedtp/test.csv | 49 ++++++++++++++--------------- di/torq/proc/chainedtp/test.q | 10 ++---- 3 files changed, 41 insertions(+), 66 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index f8b24a2e..8902f215 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -1,8 +1,8 @@ # di.torq.proc.chainedtp -A chained tickerplant. It subscribes to an upstream tickerplant through `.sub`, optionally writes -what it receives to a log of its own, and republishes to its own subscribers, tick by tick or in -batches. +A chained tickerplant. It subscribes to an upstream tickerplant through `di.subscriptions`, +optionally writes what it receives to a log of its own, and republishes to its own subscribers, tick +by tick or in batches. ## Surface @@ -10,7 +10,7 @@ batches. |---|---| | `tptype` | `` `chained `` | | `tablelist[]` | the published tables (`.stpps.t`) | -| `subdetails[tabs;instruments]` | subscribes the caller and returns `schemalist`, `logfilelist`, `rowcounts`, `date` | +| `.u.subdetails[tabs;syms]` | root; subscribes the caller and returns `tables`, `schemas`, `logfile`, `rowcount`, `date` | | `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`endofday;d) `` to subscribers | | `endofday[d]` | root; calls `.u.end d` (the upstream's end-of-day message) | | `upd` | set at root to `.ctp.upd` if no `upd` exists | @@ -40,7 +40,8 @@ Requires `log`, `timer` and `handlers`. It initialises `di.pubsub` (with the log 2. sets `.ctp.upd` from `createlogfile`/`pubinterval`, and root `upd` if absent; 3. `.ps.initialise[]`; 4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; -5. `.ctp.subscribe[]`; +5. `.ctp.subscribe[]`: finds the upstream handle, `refreshtp`, subscribes through `di.subscriptions`, takes + `.u.d` from the reply; 6. builds `.ctp.tableschemas`; 7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). @@ -52,33 +53,14 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th discovery). With `tpcheckcycles` `0W` it waits for it indefinitely. - End of day follows the rdb/wdb convention: `endofday[d]` in, `` (`endofday;d) `` out. - A corrupt own log is reported and opened anyway. -- `.u.icounts` values are one-item lists after an all-syms subscribe. - `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. -## Compatibility layer (temporary) +## Downstream subscribers -Between `/ compat begin` and `/ compat end` in `chainedtp.q`, plus the `/ compat` line in `init`. -It lets chainedtp sit between a di tickerplant and di rdb/wdb, which speak `di.subscriptions`' -`.u.subdetails` protocol. - -- Upstream: `init` subscribes with `.ctp.subscribedi[]` in place of `.ctp.subscribe[]`: same handle - lookup and `refreshtp`, then `di.subscriptions` `subscribe`, then `.u.d` from the reply. -- Downstream: root `.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub` and returns - `tables`, `schemas`, `logfile`, `rowcount`, `date`. With `createlogfile` on, `logfile` is `.u.L` - and `rowcount` `.u.i`, so subscribers replay chainedtp's own log; otherwise `` ` `` and 0. - -Limits: -- The upstream reply carries no per-table counts; `.u.icounts` starts empty. -- `.sub.SUBSCRIPTIONS` is not filled on this path, so `.ctp.notpconnected` reads empty. -- An unknown table comes back as a `(table;message)` pair, unfiltered. - -To remove: -1. Delete the block between `/ compat begin` and `/ compat end`. -2. In `init`, put back `.ctp.subscribe[];` for `.ctp.subscribedi[]; / compat`. -3. Delete the `compat:` rows in `test.csv`, and the `compat:` lines in `test.q` (the fixture's - `.u.subdetails`, the `dsub.q` peer, `DSPORT`/`sh`); put the `.sub.SUBSCRIPTIONS` check back in - the init group. -4. Delete this section. +`.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub`, the protocol `di.subscriptions` +subscribers (di rdb/wdb) use. With `createlogfile` on, `logfile` is `.u.L` and `rowcount` `.u.i`, so +subscribers replay chainedtp's own log; otherwise `` ` `` and 0. Plain `.u.sub` subscribers are served +by `di.pubsub`. ## Testing @@ -87,7 +69,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.chainedtp ``` -`test.q`/`test.csv` run a real upstream (segmented tickerplant surface, found through -`di.torq.servers`) and a real downstream subscriber: subscribe and schema, tick-by-tick delivery, -`subdetails`, `tablelist`, end of day, the own log, batch publish, `clearlogonsubscription`, and a -corrupt log. +`test.q`/`test.csv` run a real upstream (di tickerplant surface, found through `di.torq.servers`) and +real `.u.sub` and `di.subscriptions` subscribers: subscribe and schema, tick-by-tick delivery, +`.u.subdetails`, `tablelist`, end of day, the own log, batch publish, `clearlogonsubscription`, a +corrupt log, and a subscriber replaying the own log. diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 17e1cc35..930ec5ac 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -15,16 +15,16 @@ comment,,,,,,,init - connect and subscribe run,0,0,q,ctp.init[cfg[];deps[]],1,,init true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root -true,0,0,q,.u.d~D,1,,compat: date taken from the .u.subdetails reply -true,0,0,q,"1=count (use`di.subscriptions)[`getsubscriptions][]",1,,compat: subscribed through di.subscriptions +true,0,0,q,.u.d~D,1,,date taken from the .u.subdetails reply +true,0,0,q,"1=count (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed through di.subscriptions true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) true,0,0,q,`trade in .stpps.t,1,,trade is published -run,0,0,q,.ctp.subscribe[],1,,subscribe through .sub -true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade +true,0,0,q,".ctp.tph~first exec handle from (use`di.subscriptions)[`getsubscriptions][]",1,,subscription is on the upstream handle +true,0,0,q,"`trade in first exec tabs from (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed to trade comment,,,,,,,tick by tick run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstream peer @@ -32,10 +32,10 @@ run,0,0,q,"r:dh""(.z.w)(`.u.sub;`trade;`)""",1,,downstream subscribes to trade true,0,0,q,`trade~first r,1,,.u.sub returns the table true,0,0,q,"dh in .stpps.subrequestall`trade",1,,downstream registered run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows -true,0,0,q,(enlist 3)~.u.icounts`trade,1,,icounts updated (one-item list as the subscribe reshape leaves it) +true,0,0,q,3=.u.icounts`trade,1,,icounts updated true,0,0,q,"(1;3)~dh""(count got;count last last got)""",1,,downstream received the 3 rows -true,0,0,q,"`schemalist`logfilelist`rowcounts`date~key dh""(.z.w)(`subdetails;`trade;`)""",1,,subdetails keys -true,0,0,q,"()~(dh""(.z.w)(`subdetails;`trade;`)"")`logfilelist",1,,no log file without createlogfile +true,0,0,q,"`tables`schemas`logfile`rowcount`date~key dh""(.z.w)(`.u.subdetails;`trade;`)""",1,,.u.subdetails keys +true,0,0,q,"(`;0)~(dh""(.z.w)(`.u.subdetails;`trade;`)"")`logfile`rowcount",1,,no log and no replay without createlogfile true,0,0,q,"`trade in dh""(.z.w)(`tablelist;`)""",1,,tablelist lists trade comment,,,,,,,end of day @@ -58,30 +58,27 @@ run,0,0,q,.ctp.refreshtp D,1,,reopen the existing log true,0,0,q,1=.u.i,1,,existing messages counted run,0,0,q,".ctp.clearlogonsubscription:1b;.ctp.refreshtp D",1,,reopen with clearlogonsubscription true,0,0,q,0=.u.i,1,,log cleared -run,0,0,q,"r:subdetails[`trade;`]",1,,subdetails with a log -true,0,0,q,"(enlist(0;.u.L))~r`logfilelist",1,,logfilelist carries i and the log file +run,0,0,q,"r:.u.subdetails[`trade;`]",1,,.u.subdetails with a log +true,0,0,q,"(.u.L;.u.i)~r`logfile`rowcount",1,,logfile and rowcount are the own log and .u.i run,0,0,q,"bf:hsym`$FIXDIR,""/bad""; bf set (); lh:hopen bf; lh enlist(`upd;`trade;rows 1); hclose lh; bf 1: (read1 bf),0x0102030405",1,,write a log with one message and a bad tail run,0,0,q,bh:.ctp.openlog bf,1,,open it true,0,0,q,"errlogged""is corrupt""",1,,corruption reported true,0,0,q,-6h=type bh,1,,and the log opened anyway true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 -comment,,,,,,,compat: di.subscriptions subscriber downstream -run,0,0,q,.stpps.closesub 0i,1,,compat: drop handle 0 left by the local subdetails call -run,0,0,q,".ctp.refreshtp D;.ctp.writetolog[`trade;rows 3];.ctp.tickpub[`trade;rows 3]",1,,compat: fresh log with one 3-row message before the peer subscribes -run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,compat: connect to the di.subscriptions peer -run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,compat: peer subscribes to trade through .u.subdetails -true,0,0,q,(enlist`trade)~sd`tables,1,,compat: tables is a symbol list for one table -true,0,0,q,"(.u.L;1)~sd`logfile`rowcount",1,,compat: own log and its message count -true,0,0,q,"(1;`trade;3)~sh""(count got;first first got;count last first got)""",1,,compat: peer replayed the pre-subscribe message -run,0,0,q,".ctp.createlogfile:0b",1,,compat: logging off -true,0,0,q,"(`;0)~(sh""(.z.w)(`.u.subdetails;`trade;`)"")`logfile`rowcount",1,,compat: no log and no replay without createlogfile -run,0,0,q,".ctp.createlogfile:1b",1,,compat: logging back on -true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,compat: schema for trade -true,0,0,q,"sh""`trade in tables[]""",1,,compat: trade defined at root on the peer -true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,compat: peer recorded the subscription -true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `trade in sd2`tables",1,,compat: tables is a symbol list for all tables -run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,compat: upstream publishes 2 rows -true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,compat: peer received the rows +comment,,,,,,,di.subscriptions subscriber downstream +run,0,0,q,.stpps.closesub 0i,1,,drop handle 0 left by the local .u.subdetails call +run,0,0,q,".ctp.refreshtp D;.ctp.writetolog[`trade;rows 3];.ctp.tickpub[`trade;rows 3]",1,,fresh log with one 3-row message before the peer subscribes +run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,connect to the di.subscriptions peer +run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,peer subscribes to trade through .u.subdetails +true,0,0,q,(enlist`trade)~sd`tables,1,,tables is a symbol list for one table +true,0,0,q,"(.u.L;1)~sd`logfile`rowcount",1,,own log and its message count +true,0,0,q,"(1;`trade;3)~sh""(count got;first first got;count last first got)""",1,,peer replayed the pre-subscribe message +true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,schema for trade +true,0,0,q,"sh""`trade in tables[]""",1,,trade defined at root on the peer +true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,peer recorded the subscription +true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `trade in sd2`tables",1,,tables is a symbol list for all tables +run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows +true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,peer received the rows after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index df50b4e3..5557083a 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -1,4 +1,4 @@ -/ test helpers: recording mocks, a real upstream (segmented tickerplant surface) and a real downstream subscriber +/ test helpers: recording mocks, a real upstream (di tickerplant surface) and real downstream subscribers logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()) mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}) @@ -15,19 +15,15 @@ isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.p Date: Thu, 1 Oct 2026 16:05:59 +0100 Subject: [PATCH 20/42] di.torq.proc.segmentedtp 0.2.0: rebuild as TorQ's segmented tickerplant; di.pubsub 0.3.0 segmentedtp is rebuilt from scratch, one to one from TorQ's code/segmentedtickerplant/{pubsub,sctp,stplog,stpmeta}.q and code/processes/segmentedtickerplant.q. Each TorQ file is a file of the same name in the module dir, except stpps.q for segmentedtickerplant/ pubsub.q (its .stpps.upd/.stpps.zts wrappers; the common/pubsub.q it loads is di.pubsub) and segmentedtp.q for the process file. They load in TorQ's order from init.q. Ledger (the only deviations from TorQ's text): 1. .lg.o/.lg.e -> .z.m.log[`info]/[`error]. 2. .proc.procname/proctype -> .z.m.procname/proctype. 3. .eodtime.* -> di.eodtime getd/setd/getnextroll/setnextroll/getdailyadj/ getroll. setnextroll returns ::, so dayrollover sets then reads. di.eodtime differs from eodtime.q only across a DST change (getroll re-resolves at p+1D; adjtime uses its argument, not .z.p); identical with GMT settings. The os.q/timezone.q/eodtime.q loads are dropped. 4. .dotz.set of .z.pc/.z.exit -> di.torq.handlers observers (the original runs last; TorQ's .z.exit replaces rather than chains). .dotz.set of .z.ts -> direct set around the current .z.ts (di.querylog precedent). 5. schemafile from config via system "l " with TorQ's trap and exit 1; customcsv is a setting (default null); kdbtplog keeps getenv`KDBTPLOG. 6. Load-time statements that read settings (stplog.q parent replaylog, segmentedtickerplant.q multilogperiod and custom csv) run in init after the settings are applied. 7. .os NT/Fex/pth/md from os.q:3-5,16, defined only if absent, in stplog.q next to createdld, their only caller (no di.os dependency). 8. Settings: stplg and sctp sections with TorQ's names set onto .stplg/.sctp, an eodtime section to di.eodtime init, flat createlogs and schemafile. The segmentedtickerplant settings-file defaults live in stplog.q until wired. Framework switches (.proc, .usage, .servers.enabled, .timer.enabled, .hb, .subcut) and .proc.addinitlist are not ported. 9. Descriptive comments trimmed to one line. 10. Root init folded into the module init; the four TorQ lines (segmentedtickerplant.q:78-87) are unchanged, only their caller moved. The root setup/loadschemas/generateschemas are called as (`..name)[]. Kept quirks: seq 0 for a fresh day's logs; currperiod::nextperiod in stpeoperiod; custom tables missing from the csv are not logged; period replay is distinct flip; chained non-create loghandles becomes a dict of ::; the .z.exit flush only in memorybatch. End of day/period stay TorQ's (`endofday;date;data) and (`endofperiod;cur;next;data). di rdb/wdb can't consume segmentedtp until they move onto .sub, and the endofday arity is undecided; both are tracked for the subscriber-alignment branch. No compat layer. di.pubsub 0.3.0 adds the rest of common/pubsub.q to the .stpps section, verbatim bar .lg -> .z.m.log: endp, end, pubclear, attrstrip (schemasnoattributes), .u.pub, .ps.subtable, .ps.subtablefiltered, .ds.*. pubsub, chainedtp and tickerplant still pass. Tests: five peers (defaultbatch/tabperiod, immediate/singular, memorybatch/tabular, chained create, chained parent), the test process subscribing through .sub.subscribe. Peers bind an OS-chosen port and write it to a file (fixed ports clashed with TIME_WAIT). 66/66 on ten consecutive runs in the development tree. Based on feature-chainedtp, which carries the dependencies: di.pubsub (the .stpps base, with log required at init; this commit adds only the Phase B increment), di.subscriptions 0.2.0 (.sub), di.torq.servers 0.5.0 (startupdepnamecycles). On this base: segmentedtp 66/66 (x2), pubsub 121/121, chainedtp 65/65, tickerplant 33/33, di.torq 57/57. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/VERSION | 2 +- di/pubsub/pubsub.md | 14 +- di/pubsub/pubsub.q | 45 + di/torq/proc/segmentedtp/VERSION | 2 +- di/torq/proc/segmentedtp/deps.toml | 5 +- di/torq/proc/segmentedtp/init.q | 6 +- di/torq/proc/segmentedtp/sctp.q | 44 + di/torq/proc/segmentedtp/segmentedtp.md | 453 ++-------- di/torq/proc/segmentedtp/segmentedtp.q | 853 ++---------------- di/torq/proc/segmentedtp/stplog.q | 257 ++++++ di/torq/proc/segmentedtp/stpmeta.q | 44 + di/torq/proc/segmentedtp/stpps.q | 27 + di/torq/proc/segmentedtp/test.csv | 164 ++-- di/torq/proc/segmentedtp/test.q | 694 ++------------ di/torq/proc/segmentedtp/test_integration.csv | 21 - di/torq/proc/segmentedtp/test_integration.q | 214 ----- .../proc/segmentedtp/test_integration_child.q | 24 - 17 files changed, 755 insertions(+), 2114 deletions(-) create mode 100644 di/torq/proc/segmentedtp/sctp.q create mode 100644 di/torq/proc/segmentedtp/stplog.q create mode 100644 di/torq/proc/segmentedtp/stpmeta.q create mode 100644 di/torq/proc/segmentedtp/stpps.q delete mode 100644 di/torq/proc/segmentedtp/test_integration.csv delete mode 100644 di/torq/proc/segmentedtp/test_integration.q delete mode 100644 di/torq/proc/segmentedtp/test_integration_child.q diff --git a/di/pubsub/VERSION b/di/pubsub/VERSION index 0ea3a944..0d91a54c 100644 --- a/di/pubsub/VERSION +++ b/di/pubsub/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0 diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 7fc5f6d8..96f57c64 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -88,10 +88,16 @@ q)pubsub.subscribestrfilter["quote";"bid>50.0";"time,sym,bid"] ## `.stpps`, `.u.sub`, `.ps` A second pub/sub API at root, in a `\d .stpps` section at the end of `pubsub.q`, with its own state, -separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `.stpps.allsubhandles`, -`suball`/`subfiltered`/`add`/`errparse`/`addfiltered`/`selfiltered`/`pub`, -`delhandle`/`delhandlef`/`closesub`/`extractschema`/`init`, root `.u.sub`, and -`.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`. +separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `.stpps.endp`/`end`, +`allsubhandles`, `suball`/`subfiltered`/`add`/`errparse`/`addfiltered`/`selfiltered`/`pub`/`pubclear`, +`delhandle`/`delhandlef`/`closesub`/`extractschema`/`attrstrip`/`init`, root `.u.sub`/`.u.pub`, +`.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`/`subtable`/`subtablefiltered`, and +`.ds.map`/`subreq`/`stripe`. + +- `endp[cur;next;data]` and `end[date;data]` send `(`endofperiod;cur;next;data)` and `(`endofday;date;data)` to + every subscriber. +- `pubclear[tabs]` publishes the tables and resets them to `schemasnoattributes`, which `attrstrip` sets. +- `.ds.stripe` needs `.ds.numseg` set. - `.stpps` logs its errors through the `log` passed to `init`. - The consumer registers `.stpps.closesub` on `.z.pc` through its handlers dependency. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 16b1f328..99513a7a 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -138,6 +138,14 @@ t:` subrequestall:enlist[`]!enlist () subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()) +endp:{ + (neg allsubhandles[])@\:(`endofperiod;x;y;z); + }; + +end:{ + (neg allsubhandles[])@\:(`endofday;x;y); + }; + allsubhandles:{ distinct raze union/[value subrequestall;exec handle from .stpps.subrequestfiltered] }; @@ -184,6 +192,11 @@ pub:{[t;x] ]; }; +pubclear:{ + .stpps.pub'[x;value each x,:()]; + @[`.;x;:;.stpps.schemasnoattributes[x]]; + } + delhandle:{[t;h] @[`.stpps.subrequestall;t;except;h]; }; @@ -199,6 +212,11 @@ closesub:{[h] extractschema:{t:value x; $[.Q.qp t; t; 0#t]}; +attrstrip:{[t] + {@[x;cols x;`#]} each .stpps.t:t; + .stpps.schemasnoattributes:.stpps.t!extractschema each .stpps.t; + }; + init:{[t] if[count b:t where not t in tables[];{.z.m.log[`error][`psinit;m:"Table ",string[x]," does not exist"];'m} each b]; .stpps.t:t except b; @@ -217,8 +235,35 @@ init:{[t] $[y~`;.stpps.suball[x];.stpps.subfiltered[x;y]] }; +.u.pub:.stpps.pub + .ps.loaded:1b; .ps.publish:.stpps.pub; .ps.subscribe:.u.sub; .ps.init:.stpps.init; .ps.initialise:{.ps.init[tables[]];.ps.initialised:1b}; + +.ps.subtable:{[tab;syms] + .z.m.log[`info][`subtable;"Received a subscription to ",$[count tab;tab;"all tables"]," for ",$[count syms;syms;"all syms"]]; + val:.u.sub[`$tab;$[count syms;::;first] `$csv vs syms]; + $[10h~type last val;'last val;val] + }; + +.ps.subtablefiltered:{[tab;filters;columns] + .z.m.log[`info][`subtablefiltered;"Received a subscription to ",$[count tab;tab;"all tables"]," for filters: ",filters," and columns: ",columns]; + val:.u.sub[`$tab;1!enlist `tabname`filters`columns!(`$tab;filters;columns)]; + $[10h~type last val;'last val;val] + }; + +.ds.map:{[numseg;sym] sym!(sum each string sym)mod numseg}; + +.ds.subreq:(`u#`$())!`int$(); + +.ds.stripe:{[input;skey] + if[0=count input;:`boolean$()]; + if[0N in val:.ds.subreq input; + .ds.subreq,:.ds.map[.ds.numseg;distinct input where null val]; + val:.ds.subreq input; + ]; + skey=val + }; diff --git a/di/torq/proc/segmentedtp/VERSION b/di/torq/proc/segmentedtp/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/torq/proc/segmentedtp/VERSION +++ b/di/torq/proc/segmentedtp/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/torq/proc/segmentedtp/deps.toml b/di/torq/proc/segmentedtp/deps.toml index 5e783dd7..8b8eb97f 100644 --- a/di/torq/proc/segmentedtp/deps.toml +++ b/di/torq/proc/segmentedtp/deps.toml @@ -1,5 +1,6 @@ # Peer modules di.torq.proc.segmentedtp `use`s (see di/torq/depcheck/depcheck.md). [dependencies] -"di.pubsub" = "0.1.0" +"di.pubsub" = "0.3.0" "di.eodtime" = "0.1.0" -"di.tplogmgr" = "0.1.0" +"di.subscriptions" = "0.2.0" +"di.torq.servers" = "0.5.0" diff --git a/di/torq/proc/segmentedtp/init.q b/di/torq/proc/segmentedtp/init.q index 31796976..ec4762fc 100644 --- a/di/torq/proc/segmentedtp/init.q +++ b/di/torq/proc/segmentedtp/init.q @@ -1,5 +1,9 @@ +\l ::stpps.q +\l ::sctp.q +\l ::stplog.q +\l ::stpmeta.q \l ::segmentedtp.q version:first read0`:::VERSION -export:([init;upd;teardown;tablelist;subdetails;readcustomcsv;setcustommode;getcounts;getapimeta;version]) +export:([init;version]) diff --git a/di/torq/proc/segmentedtp/sctp.q b/di/torq/proc/segmentedtp/sctp.q new file mode 100644 index 00000000..4d395822 --- /dev/null +++ b/di/torq/proc/segmentedtp/sctp.q @@ -0,0 +1,44 @@ +\d .sctp + +chainedtp:@[value;`chainedtp;0b]; / switches between STP and SCTP +loggingmode:@[value;`loggingmode;`none]; / [none|create|parent] +tickerplantname:@[value;`tickerplantname;`stp1]; +tpconnsleep:@[value;`tpconnsleep;10]; +tpcheckcycles:@[value;`tpcheckcycles;0W]; +subscribeto:@[value;`subscribeto;`]; +subscribesyms:@[value;`subscribesyms;`]; +replay:@[value;`replay;0b]; +schema:@[value;`schema;1b]; + +/ subscribe to segmented tickerplant +subscribe:{[] + s:.sub.getsubscriptionhandles[`;tickerplantname;()!()]; + if[count s; + subproc:first s; + `.sctp.tph set subproc`w; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; + if[`d in key r;.u.d::r[`d]]; + if[(`icounts in key r) & (loggingmode<>`create); + subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); + .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; + ] + ]; + } + +/ initialise chained STP +init:{ + (use`di.subscriptions)[`init][.z.m.params;.z.m.deps]; + `endofperiod set {[x;y;z] .stplg.endofperiod[x;y;z]}; + `endofday set {[x;y] .stplg.endofday[x;y]}; + .servers.startupdepnamecycles[.sctp.tickerplantname;.sctp.tpconnsleep;.sctp.tpcheckcycles]; + .sctp.subscribe[]; + }; + +\d . + +/ extract data from incoming table as a list +upd:{[t;x] + x:value flip x; + .u.upd[t;x] + } diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 1f093912..42bc2601 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -1,379 +1,90 @@ # di.torq.proc.segmentedtp -The segmented tickerplant: receives updates from feeds, timestamps them, writes them to a -configurable **layout of log files** (per table or shared, rolled per period or per day, or a -per-table mix), publishes them to subscribers in one of three **batch modes**, and rolls its -logs at end of period and end of day. It is the TorqX process type for TorQ's -`segmentedtickerplant` proctype. - -Built from the real TorQ source — `code/processes/segmentedtickerplant.q`, -`code/segmentedtickerplant/{stplog,stpmeta,pubsub}.q` and `config/settings/segmentedtickerplant.q` -— onto the `di.torq` process-module conventions, mirroring `di.torq.proc.tickerplant` wherever -segmented TP's own requirements don't force a divergence. **Standalone configuration only:** -TorQ's chained variant (`sctp.q`, which subscribes *to* a parent TP) is out of scope. - -| Dependency | Kind | Role | -| --- | --- | --- | -| `log` | injected | `` `info`warn`error ``, each `{[ctx;msg]}` — required | -| `timer` | injected | `` `addjob`deletejobs`enablejobs`disablejobs `` (di.timer contract) — required | -| `handlers` | injected | `` `register`remove `` (di.torq.handlers contract) — required | -| `servers` | injected | passed by `di.torq`, deliberately unread (no connection needs), as in `di.torq.proc.tickerplant` | -| `di.pubsub` | `use` | subscribe / publish / end-of-period and end-of-day broadcast; its `closesub` is registered on `.z.pc` through `handlers` (di.pubsub no longer binds `.z.pc` at load) | -| `di.eodtime` | `use` | roll date, next roll time, data-timezone adjustment | -| `di.tplogmgr` | `use` | `write` only — see "Why log handling is self-implemented" | - -`deps.toml` declares all three `use`d modules at `0.1.0`. - ---- - -## Config - -`init[config;deps]` — the merged settings dict from `di.torq`'s cascade. Values may be symbols -(`.q` settings) or strings (`.toml`); each is coerced where it is read. - -| Key | Default | Notes | -| --- | --- | --- | -| `kdbtplog` | **required** | root directory for the logs; relative to `TORQXDATAHOME` (falls back to `TORQXAPPHOME`) or absolute. TorQ read `KDBTPLOG`; there is no TorqX equivalent, and TorQ never allowed "no directory" — only `createlogs:0b` | -| `schemafile` | `/database.q` | as `di.torq.proc.tickerplant`: publishable tables are the unkeyed ones with `time`,`sym` first; `` `g# `` applied to `sym` | -| `multilog` | `` `tabperiod `` | naming mode — `tabperiod`, `singular`, `periodic`, `tabular` or `custom` | -| `multilogperiod` | `0D01` | period length (timespan, or a `"0D01:00:00"` string). **Forced to `1D` when the top-level mode is `singular` or `tabular`** — never inside `custom` | -| `batchmode` | `` `defaultbatch `` | `memorybatch`, `defaultbatch` or `immediate` | -| `replayperiod` | `` `day `` | `period` or `day` — what `subdetails` offers for replay | -| `errmode` | `1b` | divert updates that fail to a per-day error log | -| `errorlogname` | `` `segmentederrorlogfile `` | name part of the error log file | -| `createlogs` | `1b` | `0b` publishes without writing any log | -| `logprefix` | the process name | prefix for file and directory names — TorQ used `.proc.procname`, and `di.torq` stamps `procname` into every config, so two segmented tickerplants sharing a `kdbtplog` cannot write the same files or clobber each other's metatable. `"stp"` only when no `procname` is in the config (a hand-wired `init`). An explicit `logprefix` always wins; an empty one is rejected | -| `tickinterval` | `1` | **seconds** — di.timer's unit for modes 1-3. Not TorQ's `system"t 1000"` milliseconds; `1000` here would tick every ~16 minutes (a value of 60 or more is logged at `warn`). di.timer's period is a whole number of seconds, so a sub-second flush is not possible | -| `customcsv` | none | `table,mode` csv for `custom` mode, relative to `TORQXAPPHOME` or absolute | -| `rolltimezone` / `datatimezone` / `rolltimeoffset` | GMT / GMT / `0D` | passed to di.eodtime. `rolltimeoffset` accepts a timespan, a `"0D10:00:00"` string or seconds (like `multilogperiod`); a value that cannot be parsed is dropped with a `warn`, never silently — `di.torq.proc.tickerplant` drops a non-timespan silently | -| `proctype` / `procname` | stamped by `di.torq` | carried in the end-of-period data dict | - -`multilog`, `batchmode` and `replayperiod` are dispatch keys, so an unrecognised value **fails -`init`** with a message naming the setting; so do a non-positive `multilogperiod` or -`tickinterval`. TorQ's settings comment lists `prior` for `replayperiod`, but `stplog.q` never -implemented it — it is rejected. A `multilogperiod` shorter than the tick interval is logged at -`warn` (the past-period guard would trip on every roll). - -Type coercion: booleans accept `1b`/`0b`, `"true"`/`"false"`, `"1"`/`"0"` and numbers; integers -accept numbers or numeric strings; `multilogperiod` accepts a timespan, a `"0D01:00:00"` string, or a -number of seconds. Strings are *parsed*, never cast — `` `boolean$"true" `` is a boolean **list**, -which would throw `'type` in `if`/`$` on every update, and `"j"$"5"` is the character code 53. - ---- - -## Initialisation - -```q -sp:use`di.torq.proc.segmentedtp -sp.init[`kdbtplog`multilog`batchmode!("tplog";`singular;`immediate);`log`timer`handlers!(logdep;timerdep;handlersdep)] -``` - -`di.torq` does this for a `segmentedtp` proctype (`di.torq.builtin`). `init`: - -1. validates the deps (plain signals — nothing is wired yet), tears down a previous successful - `init`, and releases anything a previous *failed* `init` left open (handles, the timer job, - the `.z.exit` registration — removals are no-ops when absent); -2. reads and validates every setting, loads the schema file, initialises di.pubsub and di.eodtime; -3. publishes the root IPC surface: `upd`, `.u.upd`, `.u.sub`, `tablelist`, `subdetails`, and - `tptype:`segmented` (what TorQ's `.sub.subscribe` reads to choose its protocol); -4. opens the day's directory `/_`, its logs, error log and metatable; -5. schedules the timer job `` `segmentedtp `` every `tickinterval` seconds and registers - `.z.exit` (name `` `segmentedtp ``) and di.pubsub's `closesub` on `.z.pc` (name `` `pubsub ``) through - `handlers` as simple events; -6. sets its initialised flag as the **literal last statement**, so a throw anywhere above leaves - the module uninitialised and a retry runs a full `init`. - -Every exported function except `init`, `readcustomcsv`, `getapimeta` and `version` signals if -called before `init`. All post-`init` errors are logged at `error` before being signalled. - ---- - -## Exported functions - -| Function | Description | -| --- | --- | -| `init[config;deps]` | see above | -| `upd[t;x]` | feed entry point (also root `upd` / `.u.upd`). `t` a table symbol, or a symbol list with `x` a matching list of payloads; `x` a list of columns or a table | -| `tablelist[]` | the publishable tables — TorQ `.sub.subscribe`'s `tablesfunc` for a segmented TP | -| `subdetails[tabs;instruments]` | TorQ `.sub.subscribe`'s `subfunc`: registers the caller with di.pubsub and returns `` `schemalist`logfilelist`rowcounts`date`logdir `` | -| `readcustomcsv[path]` | reads a `table,mode` csv into a `table!mode` dict; touches no state, callable before `init` | -| `setcustommode[dict]` | replaces the custom assignment at runtime (custom mode only) | -| `getcounts[]` | `` `seqnum`tables `` — per-table `msgcount`/`rowcount` (logged and published) and `pendingmsgcount`/`pendingrowcount` (in the unflushed batch) | -| `teardown[]` | flush, close every segment and file, remove the timer job and the `.z.exit` and `.z.pc` handlers | -| `getapimeta[]` | api metadata for `di.torq` to register with `di.api` (callable functions only) | -| `version` | the `VERSION` file's contents | - ---- - -## Naming modes - -Files live in `/_/`; timestamps are `YYYYMMDDHHMMSS` of the period -start (data-timezone adjusted), exactly as `stplog.q` builds them with `logprefix` for `procname`. - -| Mode | Files | Rolled | -| --- | --- | --- | -| `tabperiod` | `stp_` — one per table | every `multilogperiod` | -| `singular` | `stp_` — one shared by all tables | daily (period forced to `1D`) | -| `periodic` | `stp_periodic` — one shared by all tables | every `multilogperiod` | -| `tabular` | `stp_
` — one per table | daily (period forced to `1D`) | -| `custom` | per table, under its own mode from the csv / `setcustommode` | periodic/tabperiod tables per period; singular/tabular tables daily only | - -Also in the directory: `stp_` (one error log per day, when `errmode`) -and `stpmeta`, the metatable. - -In custom mode a table absent from the assignment is published but not logged. Custom mode with -no `customcsv` starts with nothing logged and a warning, until `setcustommode` is called. -`setcustommode` flushes, closes every open segment, and reopens every assigned table under the new -layout: a table whose file name is unchanged reopens the same file and resumes its metatable row. - -## Batch modes - -| Mode | On `upd` | On the timer flush | -| --- | --- | --- | -| `immediate` | write the log, publish | nothing | -| `defaultbatch` | insert into the root table, write the log; counts held as **pending** | publish and clear every table, then count the pending messages | -| `memorybatch` | insert into the root table only | per table with rows: write the whole buffer as **one** message, count it, publish and clear | - -Holding `defaultbatch` counts as pending until they are published is what keeps a subscriber's -replay count exact: a message already written but not yet published is not included in -`subdetails`' counts, because the subscriber will receive it live. - -## Timer job, period end and day end - -The `` `segmentedtp `` job flushes the batch and then checks for boundaries (TorQ's -`.stpps.zts.def`). `upd` also checks, so a boundary is not missed between ticks. - -The job body is protected and any failure is logged at `error`, and the job is registered with -`disableonfail` off. Both are needed: di.timer swallows a job's error unless its own `debug` flag -is on, and with `disableonfail` (its default) the first transient failure — a full disk on a -memorybatch flush, say — would silently stop this process flushing and rolling for good. A guard -trip still stops the job deliberately (via `disablejobs`); the next successful roll re-enables it. - -- **End of period** — flush, `di.pubsub.callendofperiod`, advance the period, then roll the - period-rolled tables: close their metatable rows, close their files, reset their message counts, - open the new period's files and rows. -- **End of day** — flush, `di.pubsub.callendofday[date]`, advance di.eodtime (date, next roll, - daily adjustment), close every segment, file and the error log, then start the new day - (fresh counts, directory, logs, error log and metatable). - -## Metatable - -`stpmeta` in the day directory: `seq`, `logname`, `start`, `end`, `tbls`, `msgcount`, `schema`, -`additional` — as TorQ's `stpmeta.q`. Persisted on every open and close. `end`/`msgcount` are set -when a segment closes; a null `end` means open (or never closed). - -## Subscriber protocol - -`subdetails[tabs;instruments]` returns: - -| Key | Value | -| --- | --- | -| `schemalist` | list of `(table;empty schema)` pairs for the tables subscribed | -| `logfilelist` | list of `(message count;log file)` pairs, as `-11!` takes them | -| `rowcounts` | `table!rows` for the day, for the tables subscribed | -| `date` | the roll date | -| `logdir` | `kdbtplog` as a symbol — **carried**: TorQ's `.sub.subscribe` segmented branch returns `details[`logdir]` to its caller (`subscriptions.q:132`), so a consumer of this exact protocol expects it | - -`logfilelist` under `replayperiod`: -- `day` — every metatable row naming a subscribed table: closed segments `0W` (replay in full), - open segments their current message count; -- `period` — the files currently open for the subscribed tables. - -Either way there is **one pair per physical file**, counting the messages of *every* table in it — -including tables outside the request, whose messages the file physically holds. A filtered -subscriber (sym list or filter table) therefore replays unfiltered files and must filter during -replay itself, as TorQ's `.sub.replayupd` does. `rowcounts` are the **day's** row totals per table -(as TorQ's `rowcount`), even under `replayperiod=period`. - -Verified end to end (a real subscriber process calling `subdetails`, replaying `logfilelist` with -`-11!`, then receiving live): every batch mode, a shared singular file, and a subscription made -across a period roll each delivered every message exactly once. - ---- - -## Design record - -### Why log handling is self-implemented - -`di.tplogmgr`'s `open`/`roll`/`logname` are fixed at one file per date (`/tp`). -Segmented TP exists to write several files per day under several naming schemes, so naming, -opening, closing and rolling are implemented here; only `write` is taken from `di.tplogmgr`. - -### Defects in the TorQ source, fixed from day one - -Each is a confirmed defect in the shipped TorQ code, not hypothetical hardening. Each has a -regression test asserting the corrected behaviour. - -1. **Corrupt logs were opened blind.** `openlog` `hopen`ed an existing file with no check. Every - existing file is now counted with the non-executing `-11!(-2;file)` first. A corrupt file's - good prefix is copied to `.good` (via a temp file and `mv`), and that copy is opened, - recorded in `currlog` and renamed in the metatable. The corrupt original is left untouched. A - later start prefers an existing `.good`, so the recovery is not repeated and appended messages - are not lost. A file too short to hold a log header, or one `-11!(-2;…)` cannot read at all - (it throws `'type` on either), holds no recoverable message and is recovered as an empty - `.good`. A corrupt `.good` is recovered in place (its own good prefix), the one case where the - file being recovered is overwritten. - *Decision:* a generic byte-prefix copy rather than `di.tplogmgr.check`/`di.tplog.repair`. - `di.tplog`'s repair matches the `(`upd;`trade;…)` message header only, so for any other table, - and for any shared file, it would write an empty `.good` — silent data loss. -2. **A roll-guard trip stopped the whole process timer.** `stpeoperiod`/`dayrollover`/`checkends` - called `system"t 0"`. The guards now call `timer.disablejobs[enlist`segmentedtp]` — this - module's job only — and every successful roll calls `enablejobs` for it. -3. **The error log leaked a handle every day.** It is tracked apart from the table logs, and - `dayrollover` never closed it. Day roll, teardown and clean exit now close it explicitly. -4. **An unclean shutdown left never-closed metatable rows, and TorQ added a row on every open.** - After the day's logs are opened, still-open rows are reconciled by **logname**. A row for a file - opened again is resumed (and a file already in the metatable is reopened rather than repeated). - Any other still-open row is an orphan, closed with a **null** message count and logged at - `warn`. The count is not reconstructed by replaying the file, which would drive the root `upd`. -5. **Replay lists were built per table.** Under `singular`/`periodic` several tables share one - file, and a `(count;file)` pair per table double-counts it. Pairs are now built per physical - file, summing every table writing to it. -6. **Custom mode's metatable split was two-way.** `updmeta[`custom]` sent every non-periodic table - down the per-table path, so custom `singular` tables got a row each. Metatable rows are now - grouped by the physical file each table is actually writing. That gives one shared row for a - shared file and one row for a per-table file, whatever mode assigned it, so the four-way split - needs no mode dispatch. -7. **A failed `init` could look initialised.** The initialised flag is written only as the last - statement of `init`. A retry after a part-way failure also releases the leaked handles and the - job/handler registration, so it registers exactly once. -8. **Unrecognised `multilog`/`batchmode`/`replayperiod` failed late or silently.** Each indexes a - dispatch dict, where an unknown key gives null — a confusing error somewhere unrelated or, for - `replayperiod`, a bad `subdetails` answer with no error at all. All three are validated in - `init`, and each is resolved to its function once there. -9. **`createlogs:0b` made every update throw.** `` `..loghandles[t] enlist … `` applied a null handle. - TorQ's own chained TP masked this by setting `loghandles` to `(::)`; a standalone TP with - `createlogs:0b` — or a custom-mode table missing from the csv — threw on every `upd`. A table - with no open log is now published and counted without a write. - -### Further decisions - -- **Logs open at the period start, not at `.z.p`.** TorQ opened its first logs at the current - timestamp, so a restart always created new files. Opening at the aligned period start lets a - restart within a period resume the same files, which is the case fixes 1 and 4 exist for. Each - file's message count when opened is kept as its base count, so replay counts for a resumed file - include the messages already in it. -- **Period and day ends flush the batch mode, not just `pubclear`.** TorQ called `pubclear` at - period end. Under `memorybatch` that published the buffer without ever logging it, and under - `defaultbatch` it left pending counts to be added to the next period's file. -- **`upd` survives a failed boundary check.** The check is protected inside `upd`: a guard trip is - logged and stops the job, but the message that exposed it is still logged and published. In - TorQ's `errmode` the whole `.u.upd` was trapped, so that message went to the error log instead. -- **The error log is per day** (named with the day start), so a restart appends to it. -- **`.u.sub` and `tptype` are published** — TorQ's segmented TP exposed both; `.sub.subscribe` reads - `tptype` to pick the `tablelist`/`subdetails` protocol. -- **`logprefix` defaults to `procname`.** The first draft defaulted to a fixed `"stp"`, which dropped a - property TorQ had by construction: names unique per process. Review caught it; the process name from - `di.torq`'s config is now the default, `"stp"` the fallback for a hand-wired `init`. -- **A string table name in `upd` is accepted as the symbol.** `$[0h/fd` (Linux). +A segmented tickerplant. It stamps and logs incoming updates, per table and per period, and publishes them to +subscribers, filtered or not, immediately or in batches. With `sctp.chainedtp` on, it runs as a chained segmented +tickerplant: it subscribes to another one and republishes what it receives. + +## Files + +`init.q` loads, in order: `stpps.q` (`.stpps.upd`/`.stpps.zts`), `sctp.q` (`.sctp`, the chained mode), `stplog.q` +(`.stplg`, logging and batching, and the `.os` directory helpers if absent), `stpmeta.q` (`.stpm`, log metadata) and `segmentedtp.q` (the process and `init`). + +## Surface + +| Name | What | +|---|---| +| `tptype` | `` `segmented `` | +| `tablelist[]` | the published tables (`.stpps.t`) | +| `subdetails[tabs;instruments]` | subscribes the caller; returns `schemalist`, `logfilelist`, `rowcounts`, `date`, `logdir` | +| `.u.upd[t;x]` | the update entry point; `x` is a list of columns without `time` | +| `upd[t;x]` | chained: a table from the upstream, passed to `.u.upd` | +| `endofday[date;data]` / `endofperiod[cur;next;data]` | chained: set at root by `.sctp.init` | +| `currlog` / `loghandles` | open logs per table, and a view of their handles | +| `.stplg.*` | settings, `init`, `upd`/`zts` per batch mode, `replaylog`, `openlog`, `closelog`, `rolllog`, `endofday`, `endofperiod`, `checkends` | +| `.sctp.*` | settings, `subscribe`, `init` | +| `.stpm.metatable` | one row per opened log: `seq`, `logname`, `start`, `end`, `tbls`, `msgcount`, `schema`; saved as `stpmeta` in the log directory | + +Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;date;data)`, where `data` is +`proctype`, `procname`, `tables` and `p`. + +## Settings + +A `stplg` section, set onto `.stplg.`: + +| Key | Default | +|---|---| +| `multilog` | `` `tabperiod `` — `tabperiod`, `periodic`, `tabular`, `singular` or `custom` | +| `multilogperiod` | `0D01` | +| `errmode` | `1b` — failed updates go to an error log | +| `batchmode` | `` `defaultbatch `` — `immediate`, `defaultbatch` or `memorybatch` | +| `replayperiod` | `` `day `` — `day` or `period` | +| `customcsv` | `` ` `` — `table,mode` csv for `custom` | +| `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_` | +| `errorlogname` | `` `segmentederrorlogfile `` | + +A `sctp` section, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +`parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and +`subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). + +An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. + +Flat: `schemafile` (required unless chained), `createlogs` (`1b`). + +## init[config;deps] + +Requires `log`, `timer` and `handlers`. It: + +1. initialises di.pubsub and di.eodtime, and registers `.stpps.closesub` on `.z.pc`; +2. applies the settings; `singular` and `tabular` set `multilogperiod` to `1D`; `custom` loads `customcsv`; + `parent` makes `replaylog` ask the upstream; +3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush + `memorybatch`, close the logs); +4. sets `.u.upd` from `batchmode`, wraps `.z.ts` (the existing handler, then the batch timer and the end checks), + and sets `\t` to 1000 if it is off; +5. chained: initialises di.subscriptions, waits for the upstream and subscribes; otherwise loads `schemafile`; +6. strips attributes from the published tables and opens the logs. + +## Behaviour to know + +- End of period and end of day are checked on each update and each timer tick. +- The first logs of a day have `seq` 0, and each period roll adds 1. +- After an end of period, `currperiod` becomes the old `nextperiod`. +- `period` replay returns `distinct` count and log pairs for the tables asked for; `day` replay returns every log of + the day, closed ones with count `0W`. +- In `custom` mode a table missing from the csv is not logged. +- Chained without `create`, `loghandles` becomes a dictionary of `::`, and `.z.exit` leaves the logs alone. +- The `.z.exit` flush runs only in `memorybatch`. +- `subdetails` and `.stplg.replaylog` take a list of tables. + +## Testing ```q k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.segmentedtp ``` -Run from the repository root (the suite loads `di/torq/proc/segmentedtp/test.q` by relative path). -**Put this repository first on `QPATH`** — a shared `mod/di` directory earlier on the path (e.g. a -`/opt/kdbx/mod/di` symlink to another checkout) silently supplies its own `di.eodtime`, `di.pubsub`, -`di.timer` and `di.k4unit`, and the suite then tests someone else's dependencies. Check with -`.Q.m.mp`di.eodtime`. - -**Integration suite** (`test_integration.csv`) — spawns real child kdb-x processes -(`test_integration_child.q`, which wires the module to the real di.timer, di.torq.handlers and -di.util.log and takes every `-flag` as a string setting, exercising the config coercions), and one -**real `di.torq` boot**: a throwaway app (schema, `process.csv`, a `segmentedtp.toml`) launched -through `torqx_init.q` exactly as `torqx.sh` does, asserting identity and settings reached the -module, feeding it, and exiting it cleanly. Run it in its own fresh q session, not after `moduletest`: - -```q -k4unit:use`di.k4unit -.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.torq.proc.segmentedtp;`test_integration.csv] -.m.di.0k4unit.KUrt[] -k4unit.getresults[] -``` +`test.q`/`test.csv` start five peers: `defaultbatch` with `tabperiod`, `immediate` with `singular`, `memorybatch` +with `tabular`, and two chained peers (`create`, `parent`) on the first. The test process subscribes through +`.sub.subscribe`. The tests cover the settings, the handshake, each batch mode and log naming, error mode, sym and +filtered subscriptions, both replay periods, end of period, end of day (including through the chained peer), the +`.z.exit` flush and the chained exit when the upstream is lost. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index e39a91ae..64de8b0a 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -1,768 +1,93 @@ -/ di.torq.proc.segmentedtp - segmented tickerplant. Receives feed updates, timestamps them, writes them to one of -/ five log layouts (per table or shared, rolled per period or per day, or a per-table custom mix), publishes them -/ via di.pubsub in one of three batch modes, and rolls its logs at end of period and end of day. -/ Built from TorQ/code/processes/segmentedtickerplant.q and code/segmentedtickerplant/{stplog,stpmeta,pubsub}.q, -/ standalone configuration only (the chained sctp.q variant is out of scope). Hard deps: di.pubsub (sub/pub), -/ di.eodtime (roll timing), di.tplogmgr (write only - naming, open and roll are self-implemented because -/ di.tplogmgr is fixed at one file per date). Injected deps: log, timer, handlers. Design record: segmentedtp.md. - -/ --- constants --- - -modes:`tabperiod`singular`periodic`tabular`custom; -custommodes:`tabperiod`singular`periodic`tabular; -batchmodes:`memorybatch`defaultbatch`immediate; -replayperiods:`period`day; -jobid:`segmentedtp; / the timer job and .z.exit handler name -copychunk:8388608; / bytes per read when copying a corrupt log's good prefix - -/ live log per table: the file it writes to and the handle (shared by every table writing that file) -currlogschema:([tbl:`symbol$()]logname:`symbol$();handle:`int$()); - -/ on-disk metatable, one row per physical log file (TorQ's stpmeta.q) -metaschema:([]seq:`int$();logname:`symbol$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()); - -/ --- module state read before init has run (everything else is written by init) --- - -initdone:0b; -logwired:0b; -currlog:currlogschema; -errh:0Ni; - -/ --- shared helpers (as di.torq.proc.tickerplant) --- - -/ base dirs: CODE/CONFIG under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falling back to TORQXAPPHOME) -apphome:{getenv[`TORQXAPPHOME]}; -datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]}; - -/ resolve a possibly-relative dir setting to an absolute path STRING under base; symbol (.q) or string (.toml) input -resolvedir:{[base;dir] - dir:$[10h=abs type dir;dir;string dir]; - dir:$[(0.good - keep using it rather than the corrupt original -resolvelog:{[ln] $[type key g:goodname ln;g;ln]}; - -openfile:{[ln] - / hopen a log, creating it if absent. an existing log is counted first WITHOUT executing it, and a corrupt one - / is never opened blind (TorQ's openlog did) - its good prefix is copied to .good and that is opened. - / the message count found is kept as the file's base count. returns (name;handle) - if[not type key ln;.[ln;();:;()]]; - / a zero-byte file (a crash between create and header write) is safely re-headed; a file shorter than the 8-byte - / header, or one -11!(-2;..) cannot read at all, holds no recoverable message - recover it as an empty log - if[0=hcount ln;.[ln;();:;()]]; - info:@[-11!;(-2;ln);{0 0}]; - if[1info 1;.[tmp;();:;()];copyprefix[ln;tmp;info 1]]; - system "mv -f ",(shq 1_string tmp)," ",shq 1_string g; - renamemeta[ln;g]; - .z.m.log[`warn][`openlog;"corrupt log ",(1_string ln),": kept ",(string info 0)," good message(s) (",(string info 1)," bytes) in ",1_string g]; - g - }; - -copyprefix:{[src;dst;n] - / copy the first n bytes of src to dst in bounded chunks; the destination handle is closed even if a read fails - dst 1: `byte$(); - h:hopen dst; - r:@[{[src;h;n] copychunkto[src;h;n]/[0j]}[src;h];n;{[e] (`copyfailed;e)}]; - hclose h; - if[`copyfailed~first r;'"copying ",(1_string src),": ",r 1]; - }; - -/ shell-quote a path for system calls (mkdir / mv) -shq:{[p] "\"",p,"\""}; - -copychunkto:{[src;h;n;o] - / append the next chunk of src from offset o; returns the new offset, unchanged once at n (ending the over) - if[o>=n;:o]; - k:copychunk&n-o; - h read1 (src;o;k); - o+k - }; - -rebuildhandles:{[] .z.m.loghandles:exec tbl!handle from .z.m.currlog;}; - -openlog:{[tab;p] - / open - or share, when another table already has it open - the log tab writes to for the period starting p - ln:resolvelog lognamefor[tab;p]; - h:exec first handle from .z.m.currlog where logname=ln,not null handle; - if[null h;r:openfile ln;ln:r 0;h:r 1]; - .z.m.currlog:.z.m.currlog upsert (tab;ln;h); - rebuildhandles[]; - .z.m.log[`info][`openlog;"table ",(string tab)," logging to ",1_string ln]; - }; - -openfail:{[tab;e] .z.m.log[`error][`rolllog;"failed to open log for table ",(string tab),": ",e];}; - -openlogsafe:{[tab;p] .[openlog;(tab;p);openfail[tab]];}; - -closefail:{[h;e] .z.m.log[`warn][`closelog;"handle ",(string h)," already closed: ",e];}; - -closehandle:{[h] @[hclose;h;closefail[h]];}; - -closelogs:{[ts] - / close the files the given tables write to - a shared file is closed once, and only when no other table uses it - hs:distinct exec handle from .z.m.currlog where tbl in ts,not null handle; - hs:hs except exec handle from .z.m.currlog where not tbl in ts,not null handle; - closehandle each hs; - .z.m.currlog:update handle:0Ni from .z.m.currlog where tbl in ts; - rebuildhandles[]; - if[count hs;.z.m.log[`info][`closelog;"closed ",(string count hs)," log file(s)"]]; - }; - -openerrlog:{[] - / the day's error log for messages that fail in errmode - one per day, so a restart appends to it - d:(.z.m.eod`getd)[]; - r:openfile resolvelog lognameerror[.z.m.dldir;.z.m.errorlogname;"p"$d]; - .z.m.errlog:r 0; - .z.m.errh:r 1; - .z.m.log[`info][`openerrlog;"error log is ",1_string .z.m.errlog]; - }; - -closeerrlog:{[] - / the error log is tracked apart from currlog, so every roll and shutdown must close it explicitly - TorQ's - / dayrollover never did, leaking one handle per day - if[null .z.m.errh;:()]; - closehandle .z.m.errh; - .z.m.errh:0Ni; - .z.m.log[`info][`closeerrlog;"closed error log ",1_string .z.m.errlog]; - }; - -releaselogs:{[] - / close whatever an earlier init left open, without touching the metatable - used when init is called again - closehandle each distinct exec handle from .z.m.currlog where not null handle; - .z.m.currlog:currlogschema; - if[not null .z.m.errh;closehandle .z.m.errh]; - .z.m.errh:0Ni; - rebuildhandles[]; - }; - -writelog:{[t;msg] - / append to the table's log. tables with no open log (createlogs off, or unlisted in custom mode) are skipped - - / TorQ applied the null handle and threw on every update - if[not null h:.z.m.loghandles t;(.z.m.tp`write)[h;msg]]; - }; - -/ --- metatable (TorQ's stpmeta.q) --- - -filecount:{[ln] - / messages in a physical file: its count when opened plus what every table sharing it has written since - ts:exec tbl from .z.m.currlog where logname=ln; - (0^.z.m.basecount ln)+sum .z.m.msgcount ts - }; - -addmetarow:{[row] .z.m.metatable:.z.m.metatable,enlist row;}; - -renamemeta:{[ln;g] .z.m.metatable:update logname:g from .z.m.metatable where logname=ln;}; - -metaopen:{[p;ln;ts] - / a file already in the metatable (a restart or reassignment resuming the same segment) is reopened, not repeated - if[ln in .z.m.metatable`logname; - .z.m.metatable:update end:0Np,tbls:{distinct x,y}[;ts] each tbls from .z.m.metatable where logname=ln; - :()]; - addmetarow `seq`logname`start`end`tbls`msgcount`schema`additional!(.z.m.seq;ln;p;0Np;ts;0i;ts#.z.m.schemas;()!()); - }; - -metaclose:{[p;ln] - / stamp a segment closed with the messages its file holds - c:"i"$filecount ln; - .z.m.metatable:update end:p,msgcount:c from .z.m.metatable where logname=ln,null end; - }; - -updmeta:{[ev;ts;p] - / record segments opening or closing. grouped by PHYSICAL file, so a shared singular/periodic file gets one row and a - / per-table file one row whatever mode assigned it - TorQ's custom path wrote custom singular tables per table - if[not count ts;:()]; - grp:exec tbl by logname from .z.m.currlog where tbl in ts,not null logname; - if[count grp;$[ev=`open;metaopen[p]'[key grp;value grp];metaclose[p] each key grp]]; - setmeta[]; - }; - -setmetafail:{[e] .z.m.log[`error][`setmeta;"failed to persist the metatable: ",e];}; - -setmeta:{[] .[set;(hsym`$.z.m.dldir,"/stpmeta";.z.m.metatable);setmetafail];}; - -loadmetafail:{[e] - .z.m.log[`warn][`loadmeta;"unreadable metatable, starting a new one: ",e]; - :metaschema; - }; - -loadmeta:{[] - f:hsym`$.z.m.dldir,"/stpmeta"; - $[type key f;@[get;f;loadmetafail];metaschema] - }; - -reconcilemeta:{[] - / TorQ appended a row on every open, so an unclean exit left a never-closed row behind. a still-open row for a file - / opened again now is resumed; any other still-open row is an orphan - closed with an unknown (null) message count, - / not a count guessed by replaying the file, which would drive the root upd - cur:exec distinct logname from .z.m.currlog where not null logname; - stale:exec logname from .z.m.metatable where null end,not logname in cur; - now:.z.p+(.z.m.eod`getdailyadj)[]; - if[count stale; - .z.m.metatable:update end:now,msgcount:0Ni from .z.m.metatable where logname in stale; - .z.m.log[`warn][`reconcilemeta;"closed ",(string count stale)," segment(s) left open by an unclean shutdown: ",", " sv 1_'string stale]]; - resumed:exec seq from .z.m.metatable where logname in cur; - .z.m.seq:$[count resumed;max resumed;1i+-1i|max .z.m.metatable`seq]; - }; - -/ --- replay lists for subscribers: (message count;log file) pairs, as -11! takes them --- - -getlogsperiod:{[ts] - / the current period only: one pair per physical file, counting every table in it - not one pair per table, - / which double-counts a shared singular/periodic file - lns:exec distinct logname from .z.m.currlog where tbl in ts,not null handle; - flip (filecount each lns;lns) - }; - -getlogsday:{[ts] - / the whole day from the metatable: closed segments replay in full (0W), open ones up to their current count - m:select logname,end from .z.m.metatable where any each tbls in\: ts; - if[not count m;:()]; - flip (?[null m`end;filecount each m`logname;0W];m`logname) - }; - -getlogsfns:`period`day!(getlogsperiod;getlogsday); - -/ --- updates and the three batch modes (TorQ's .stplg.upd / .stplg.zts) --- - -stampcols:{[x;ts] - / prepend the arrival timestamp, unless the first column already is one (as di.torq.proc.tickerplant) - if[-12h=type first first x;:x]; - $[0>type first x;ts,x;(enlist(count first x)#ts),x] - }; - -updmemory:{[t;x;ts] - / memorybatch: buffer only - logging and publishing both wait for the flush - t insert stampcols[tocols x;ts]; - }; - -flushtable:{[t] - / memorybatch flush for one table: the whole buffer goes to the log as ONE message, then is published and cleared - if[not n:count value t;:()]; - writelog[t;(`upd;t;value flip value t)]; - .z.m.msgcount[t]+:1; - .z.m.rowcount[t]+:n; - (.z.m.ps`pubclear)[t]; - }; - -flushmemory:{[] flushtable each .z.m.pubtabs;}; - -upddefault:{[t;x;ts] - / defaultbatch: log straight away, publish on the flush. counts are held as pending until published, so a - / subscriber's replay count never includes a message it will also receive live - x:stampcols[tocols x;ts]; - t insert x; - writelog[t;(`upd;t;x)]; - .z.m.tmpmsgcount[t]+:1; - .z.m.tmprowcount[t]+:count first x; - }; - -resettmp:{[] - .z.m.tmpmsgcount:.z.m.pubtabs!count[.z.m.pubtabs]#0j; - .z.m.tmprowcount:.z.m.pubtabs!count[.z.m.pubtabs]#0j; - }; - -flushdefault:{[] - (.z.m.ps`pubclear)[.z.m.pubtabs]; - .z.m.msgcount+:.z.m.tmpmsgcount; - .z.m.rowcount+:.z.m.tmprowcount; - resettmp[]; - }; - -updimmediate:{[t;x;ts] - / immediate: log and publish on every update - x:stampcols[tocols x;ts]; - writelog[t;(`upd;t;x)]; - d:flip .z.m.tabcols[t]!$[0>type first x;enlist each x;x]; - .z.m.msgcount[t]+:1; - .z.m.rowcount[t]+:count d; - (.z.m.ps`publish)[t;d]; - }; - -flushimmediate:{[]}; - -updfns:`memorybatch`defaultbatch`immediate!(updmemory;upddefault;updimmediate); -flushfns:`memorybatch`defaultbatch`immediate!(flushmemory;flushdefault;flushimmediate); - -unknowntable:{[t;x;ts] raiseerror[`upd;"not a publishable table: ",-3!t]}; - -badmsg:{[t;x;e] - / errmode: log the failure, then keep the message in the error log as (`upderr;t;x) - .z.m.log[`warn][`upd;"bad message for ",(-3!t),": ",e]; - if[not null .z.m.errh;(.z.m.tp`write)[.z.m.errh;(`upderr;t;x)]]; - }; - -updmsg:{[t;x;ts] - / one table's message; in errmode a failure goes to the error log instead of back to the feed - f:$[t in .z.m.pubtabs;.z.m.updfn;unknowntable]; - $[.z.m.errmode;.[f;(t;x;ts);badmsg[t;x]];f[t;x;ts]]; - }; - -rollfail:{[e] .z.m.log[`error][`upd;"end of period/day check failed: ",e];}; - -upd:{[t;x] - / feed entry point (root upd / .u.upd): check for a period or day end, then log and publish under the batch mode. - / a failed roll is logged and stops the tick job, but does not lose the message that exposed it - requireinit`upd; - / a string table name would be iterated character by character below - if[10h=type t;t:`$t]; - now:.z.p; - if[.z.m.nextendutc.z.m.nextperiod;stopjob[`endofperiod;"next period is in the past"]]; - getnextendutc[]; - if[rolllogs and .z.m.createlogs;.z.m.seq+:1i;rolllog[.z.m.rolltabs;data`p]]; - (.z.m.timer`enablejobs)[enlist jobid]; - .z.m.log[`info][`endofperiod;"end of period complete, current period is now ",string .z.m.currperiod]; - }; - -closeday:{[p] - / close every open segment and file, the error log included - if[.z.m.createlogs;updmeta[`close;exec tbl from .z.m.currlog;p];closelogs exec tbl from .z.m.currlog]; - closeerrlog[]; - }; - -dayrollover:{[data] - nr:(.z.m.eod`getroll)[data`p]; - (.z.m.eod`setnextroll)[nr]; - if[(data`p)>nr;stopjob[`endofday;"next roll is in the past"]]; - (.z.m.eod`setd)[1+(.z.m.eod`getd)[]]; - closeday (data`p)+(.z.m.eod`getdailyadj)[]; - (.z.m.eod`setdailyadj)[(.z.m.eod`getdailyadjustment)[]]; - startday[]; - (.z.m.timer`enablejobs)[enlist jobid]; - .z.m.log[`info][`endofday;"end of day complete, date is now ",string (.z.m.eod`getd)[]]; - }; - -endofday:{[d;data] - / flush, tell subscribers, roll every log into the next day's directory - .z.m.flushfn[]; - (.z.m.ps`callendofday)[d]; - dayrollover data; - }; - -dayend:{[now] - if[(.z.m.eod`getd)[]<("d"$now)-1;stopjob[`checkends;"more than one day has passed since the last end of day"]]; - endofday[(.z.m.eod`getd)[];enddata now]; - }; - -checkends:{[now] - / fire end of period and/or end of day once a boundary has passed - if[.z.m.nextendutc>now;:()]; - adj:now+(.z.m.eod`getdailyadj)[]; - if[.z.m.nextperiodtype deps k;'"di.torq.proc.segmentedtp: ",(string k)," dependency must be a dict - ",hint]; - if[count missing:fns except key deps k;'"di.torq.proc.segmentedtp: ",(string k)," dependency is missing ",", " sv string missing]; - }; - -checkdeps:{[deps] - / validate the injected deps before anything is wired - plain signals, as no logger is usable yet - if[99h<>type deps;'"di.torq.proc.segmentedtp: deps must be a dict with `log`timer`handlers keys"]; - checkdep[deps;`log;`info`warn`error;"see di.util.log"]; - checkdep[deps;`timer;`addjob`deletejobs`enablejobs`disablejobs;"see di.timer"]; - checkdep[deps;`handlers;`register`remove;"see di.torq.handlers"]; - }; - -checkin:{[k;v;ok] - if[not v in ok;raiseerror[`init;(string k)," must be one of ",(", " sv string ok),"; got ",-3!v]]; - }; - -readconfig:{[config] - / read and validate every setting up front: a value used later as a dispatch key would otherwise index to null - / and fail somewhere unrelated - or, for replayperiod, not fail at all and corrupt subdetails - .z.m.cfg:config; - if[not `kdbtplog in key config;raiseerror[`init;"kdbtplog is required - the root directory for the log files"]]; - if[0=count tostr config`kdbtplog;raiseerror[`init;"kdbtplog must name a directory"]]; - .z.m.kdbtplog:resolvedir[datahome[];config`kdbtplog]; - .z.m.multilog:astz cfgor[config;`multilog;`tabperiod]; - .z.m.multilogperiod:totimespan cfgor[config;`multilogperiod;0D01]; - .z.m.errmode:tobool cfgor[config;`errmode;1b]; - .z.m.batchmode:astz cfgor[config;`batchmode;`defaultbatch]; - .z.m.replayperiod:astz cfgor[config;`replayperiod;`day]; - .z.m.errorlogname:astz cfgor[config;`errorlogname;`segmentederrorlogfile]; - .z.m.createlogs:tobool cfgor[config;`createlogs;1b]; - / file and directory names carry the process name, as TorQ's .proc.procname did: two segmented tickerplants - / sharing a kdbtplog then cannot write the same files or clobber each other's metatable. "stp" only when no - / procname is known (di.torq always stamps one) - .z.m.logprefix:tostr cfgor[config;`logprefix;$[`procname in key config;config`procname;"stp"]]; - if[0=count .z.m.logprefix;raiseerror[`init;"logprefix must not be empty"]]; - .z.m.tickinterval:tolong cfgor[config;`tickinterval;1]; - .z.m.proctype:astz cfgor[config;`proctype;`segmentedtp]; - .z.m.procname:astz cfgor[config;`procname;`]; - checkin[`multilog;.z.m.multilog;modes]; - checkin[`batchmode;.z.m.batchmode;batchmodes]; - checkin[`replayperiod;.z.m.replayperiod;replayperiods]; - if[not 0D<.z.m.multilogperiod;raiseerror[`init;"multilogperiod must be a positive timespan"]]; - if[not 0<.z.m.tickinterval;raiseerror[`init;"tickinterval must be a positive number of seconds"]]; - / TorQ's system"t 1000" was milliseconds; di.timer's period is seconds, so a carried-over 1000 is ~16 minutes - if[60<=.z.m.tickinterval; - .z.m.log[`warn][`init;"tickinterval is ",(string .z.m.tickinterval)," SECONDS - the batch flush and roll checks run that rarely"]]; - / singular and tabular roll daily - forced for the top-level mode only, never inside custom, as TorQ does - if[.z.m.multilog in `singular`tabular;.z.m.multilogperiod:1D]; - / a period the tick cannot keep up with trips the past-period guard on every roll - if[.z.m.multilogperiod<0D00:00:01*.z.m.tickinterval; - .z.m.log[`warn][`init;"multilogperiod ",(string .z.m.multilogperiod)," is shorter than the ",(string .z.m.tickinterval),"s tick interval"]]; - .z.m.updfn:updfns .z.m.batchmode; - .z.m.flushfn:flushfns .z.m.batchmode; - .z.m.getlogsfn:getlogsfns .z.m.replayperiod; - }; - -loadschema:{[config] - / load the schema file at root; publishable tables are the unkeyed ones with time,sym first (as di.torq.proc.tickerplant) - schemafile:$[`schemafile in key config;resolvedir[apphome[];config`schemafile];apphome[],"/database.q"]; - system "l ",schemafile; - allt:tables[]; - t:allt where {(98h=type value x) and `time`sym~2#cols x} each allt; - if[0=count t;raiseerror[`init;"schema file loaded no publishable tables (need unkeyed with time,sym first): ",schemafile]]; - {@[x;`sym;`g#]} each t; - .z.m.pubtabs:t; - .z.m.tabcols:t!cols each t; - .z.m.schemas:t!{0#value x} each t; - }; - -/ di.eodtime's merged init dict: the log dep plus any timezone config. built with ONE `!` over a general list - -/ amending keys onto enlist[`log]!enlist logdep (as di.torq.proc.tickerplant does) puts a TABLE on the value side, -/ since a one-element list of dicts is a table, and di.eodtime.init then throws 'type for any timezone setting. -/ rolltimeoffset is parsed like multilogperiod (a timespan, a "0D10:00:00" string, or seconds - TOML has no timespan -/ type); a value that cannot be parsed is dropped LOUDLY, at warn, not silently as a non-timespan would otherwise be -eoddeps:{[config;logdep] - ks:`rolltimezone`datatimezone inter key config; - tzvals:astz each config ks; - off:$[`rolltimeoffset in key config;totimespan config`rolltimeoffset;0Nn]; - if[(`rolltimeoffset in key config) and null off; - .z.m.log[`warn][`init;"rolltimeoffset ",(-3!config`rolltimeoffset)," is not a timespan, a timespan string or seconds - ignored"]]; - / a plain join, not ,: - amending a timespan onto a symbol vector in place throws 'type - if[not null off;ks,:`rolltimeoffset;tzvals:tzvals,enlist off]; - vals:(1+count ks)#(::); - vals[0]:logdep; - if[count ks;vals[1+til count ks]:tzvals]; - (`log,ks)!vals - }; - -publishroot:{[] - / the IPC surface a feed and TorQ's .sub.subscribe call by name - use keeps module code in a private namespace - set[`upd;upd]; - set[`.u.upd;upd]; - set[`.u.sub;sub]; - set[`tablelist;tablelist]; - set[`subdetails;subdetails]; - set[`tptype;`segmented]; - }; +/ di.torq.proc.segmentedtp - segmented tickerplant init:{[config;deps] - / wire the injected deps, read config, load the schema, publish the root IPC surface, open the day's logs and - / schedule the tick job. safe to call again, and to retry after a call that failed part-way - checkdeps deps; - if[.z.m.initdone;teardown[]]; + if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; + if[not `handlers in key deps;'"di.torq.proc.segmentedtp: handlers dependency is required - see di.torq.handlers"]; .z.m.log:deps`log; - .z.m.logwired:1b; - .z.m.timer:deps`timer; - .z.m.handlers:deps`handlers; - / a failed earlier init may have left handles open or a job/handler registered (both removals are no-ops if absent) - releaselogs[]; - (.z.m.timer`deletejobs)[enlist jobid]; - (.z.m.handlers`remove)[`.z.exit;`;jobid]; - (.z.m.handlers`remove)[`.z.pc;`;`pubsub]; - readconfig config; - loadschema config; - .z.m.ps:use`di.pubsub; - (.z.m.ps`setsubtables)[.z.m.pubtabs]; - (.z.m.ps`init)[]; - / di.pubsub's subscriber cleanup goes on .z.pc through the handlers dep (di.pubsub no longer binds .z.pc at load - - / that replaced the di.torq.handlers dispatcher, and di.torq.servers' hook with it, moments after di.torq installed it) - (.z.m.handlers`register)[`.z.pc;`;`pubsub;0;.z.m.ps`closesub]; + .z.m.procname:config`procname; + .z.m.proctype:config`proctype; + .z.m.params:config; + .z.m.deps:deps; + (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; + r:deps[`handlers]`register; + r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.eod:use`di.eodtime; - (.z.m.eod`init)[eoddeps[config;.z.m.log]]; - .z.m.tp:use`di.tplogmgr; - .z.m.custommode:(`symbol$())!`symbol$(); - if[.z.m.multilog=`custom;loadcustom config]; - .z.m.seqnum:0; - publishroot[]; - startday[]; - (.z.m.timer`addjob)[jobid;tick;();.z.m.tickinterval;1h;jobopts]; - (.z.m.handlers`register)[`.z.exit;`;jobid;0;exithandler]; - msg:"initialised, multilog=",(string .z.m.multilog),", batchmode=",string .z.m.batchmode; - .z.m.log[`info][`segmentedtp;msg,", tables=",", " sv string .z.m.pubtabs]; - / written last: a throw anywhere above leaves the module uninitialised, so a retry is a full init, not a re-init - .z.m.initdone:1b; - }; - -getapimeta:{[] - / this module's api metadata, one row per CALLABLE API function, for di.torq to register with di.api. init and - / getapimeta are plumbing di.torq calls by convention and are deliberately not listed. names are bare. - :flip `name`public`descrip`params`return!flip( - (`upd; 1b; "log and publish a feed update under the batch mode"; "[symbol|symbol list: t; list|table: x]"; "null"); - (`tablelist; 1b; "the publishable tables"; "[]"; "symbol list"); - (`subdetails; 1b; "subscribe the caller; return schemas and replay details"; "[symbol: tabs; symbols|null: instruments]"; "dict"); - (`readcustomcsv; 1b; "read a table,mode csv into a custom mode dict"; "[symbol|string: path]"; "dict: table!mode"); - (`setcustommode; 1b; "replace the custom log assignment and reopen the logs"; "[dict: table!mode]"; "null"); - (`getcounts; 1b; "per-table counted and pending counts, plus the seqnum"; "[]"; "dict"); - (`teardown; 1b; "close every log; remove the tick job and .z.exit handler"; "[]"; "null")); - }; + .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; + {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `stplg`sctp; + if[`createlogs in key config;set[`createlogs;config`createlogs]]; + / subscribers replay from the parent's logs + if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; + / singular or tabular: no intraday roll + if[.stplg.multilog in `singular`tabular;.stplg.multilogperiod:1D]; + / custom: logging mode per table + if[.stplg.multilog~`custom; + @[{.stplg.custommode:1_(!) . ("SS";",")0: x};.stplg.customcsv;{.z.m.log[`error][`stp;"failed to load custom mode csv"]}]]; + / die if the main STP dies + r[`.z.pc;`;`sctp;0j;{[x] if[.sctp.chainedtp;if[.sctp.tph=x;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .sctp.tickerplantname];exit 1]]}]; + / close logs on clean exit + r[`.z.exit;`;`stplg;0j;{[x] + if[not x~0i;.z.m.log[`error][`stpexit;"Bad exit!"];:()]; + .z.m.log[`info][`stpexit;"Exiting process"]; + if[.stplg.batchmode=`memorybatch; + .z.m.log[`info][`stpexit;"STP shutdown unexpectedly, batchmode = `memorybatch, therefore flushing any remaining data to the on-disk log file"]; + .stplg.zts.memorybatch[]; + .z.m.log[`info][`stpexit;"Complete!"]]; + if[.sctp.chainedtp and not .sctp.loggingmode=`create;:()]; + .z.m.log[`info][`stpexit;"Closing off log files"]; + .stpm.updmeta[.stplg.multilog][`close;.stpps.t;.z.p]; + .stplg.closelog each .stpps.t}]; + (`..setup)[.stplg.batchmode]; + / chained: subscribe to the main STP; otherwise load the schema file + $[.sctp.chainedtp;.sctp.init[];(`..loadschemas)[]]; + (`..generateschemas)[]; + .stplg.init[string .z.m.procname]; + } + +\d . + +/ allow tickerplant to create a log file +createlogs:@[value;`createlogs;1b]; + +/ subscribers use this to determine what type of process they are talking to +tptype:`segmented + +tablelist:{.stpps.t} + +/ subscribers who want to replay need this info +subdetails:{[tabs;instruments] + `schemalist`logfilelist`rowcounts`date`logdir!(.ps.subscribe\:[tabs;instruments];.stplg.replaylog[tabs];tabs#.stplg `rowcount;.z.m.eod.getd[];.stplg.kdbtplog) + } + +/ table and schema information and default table upd functions +generateschemas:{ + .stpps.init[tables[] except `currlog`heartbeat`logmsg`svrstoload]; + .stpps.attrstrip[.stpps.t]; + / table upd functions attach the current timestamp; chained they do nothing + $[.sctp.chainedtp; + .stplg.updtab:(.stpps.t!(count .stpps.t)#{[x;y] x}),.stplg.updtab; + .stplg.updtab:(.stpps.t!(count .stpps.t)#{(enlist(count first x)#y),x}),.stplg.updtab + ] + } + +/ load in schema file and kill proc if not present +loadschemas:{ + if[not `schemafile in key .z.m.params;.z.m.log[`error][`loadschema;"Schema file required!"];exit 1]; + @[{system"l ",x};raze .z.m.params[`schemafile];{.z.m.log[`error][`loadschema;"Failed to load schema file!"];exit 1}]; + }; + +/ upd and zts behaviour from the batch mode +setup:{[batch] + if[not all batch in/: key'[.stplg`upd`zts];'"mode ",(string batch)," must be defined in both .stplg.upd and .stplg.zts"]; + chainmode:$[.sctp.chainedtp;`chained;`def]; + .stplg.updmsg:.stplg.upd[batch]; + .stplg.ts:.stplg.zts[batch]; + .u.upd:.stpps.upd[chainmode]; + set[`.z.ts;{[f;x] @[;x;()]each f}(@[value;`.z.ts;{{}}];.stpps.zts[chainmode])]; + / error mode: failed updates go to a separate log + if[.stplg.errmode; + .stp.upd:.u.upd; + .u.upd:{[t;x] .[.stp.upd;(t;x);{.stplg.badmsg[x;y;z]}[;t;x]]} + ]; + if[not system "t";.z.m.log[`info][`timer;"defaulting timer to 1000ms"];system"t 1000"]; + }; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q new file mode 100644 index 00000000..a439a027 --- /dev/null +++ b/di/torq/proc/segmentedtp/stplog.q @@ -0,0 +1,257 @@ +/ periodic tp logging + +\d . + +/ live logs and handles to logs for each table +currlog:([tbl:`symbol$()]logname:`symbol$();handle:`int$()) + +/ view of log file handles for faster lookups +loghandles::exec tbl!handle from currlog + +\d .os + +if[not `md in key `.os; + NT:.z.o in`w32`w64; + Fex:{not 0h~type key hsym$[10=type x;`$x;x]}; + pth:{if[10h<>type x;x:string x]; if[NT;x:@[x;where"/"=x;:;"\\"]];$[":"=first x;1_x;x]}; + md:{if[not Fex x;system"mkdir \"",pth[x],"\""]}]; + +\d .stplg + +/ settings +multilog:`tabperiod / [tabperiod|none|periodic|tabular|custom] +multilogperiod:0D01 +errmode:1b +batchmode:`defaultbatch / [memorybatch|defaultbatch|immediate] +replayperiod:`day / [period|day|prior] +customcsv:` +kdbtplog:`$getenv`KDBTPLOG + +errorlogname:@[value;`.stplg.errorlogname;`segmentederrorlogfile] + +/ create log directory `:stplogs/date/tabname_time +createdld:{[name;date] + if[not count dir:hsym .stplg.kdbtplog;.z.m.log[`error][`stp;"log directory not defined"];exit 1]; + .os.md dir; + .os.md .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; + }; + +gentimeformat:{(raze string "dv"$x) except ".:"}; + +/ tabperiod: one log per table, rolled periodically +.stplg.logname.tabperiod:{[dir;tab;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";tab),.stplg.gentimeformat[p]) }; + +/ singular: one log, rolled daily +.stplg.logname.singular:{[dir;tab;p] ` sv (hsym dir;`$raze string .z.m.procname,"_",.stplg.gentimeformat[p]) }; + +/ periodic: one log, rolled periodically +.stplg.logname.periodic:{[dir;tab;p] ` sv (hsym dir;`$raze string .z.m.procname,"_periodic",.stplg.gentimeformat[p]) }; + +/ tabular: one log per table, rolled daily +.stplg.logname.tabular:{[dir;tab;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";tab),.stplg.gentimeformat[p]) }; + +/ custom: mode per table from the custom csv; tables not in it are not logged +.stplg.logname.custom:{[dir;tab;p] .stplg.logname[.stplg.custommode tab][dir;tab;p] }; + +.stplg.logname.error:{[dir;ename;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";ename),.stplg.gentimeformat[p]) }; + +/ upd and timer functions per batch mode; pre-existing definitions kept +upd:@[value;`.stplg.upd;enlist[`]!enlist ()]; +zts:@[value;`.stplg.zts;enlist[`]!enlist ()]; + +/ functions to add columns on updates +updtab:@[value;`.stplg.updtab;enlist[`]!enlist {(enlist(count first x)#y),x}] + +/ memorybatch: insert in memory; write, publish and count on the timer +upd[`memorybatch]:{[t;x;now] + t insert updtab[t] . (x;now); + }; + +zts[`memorybatch]:{ + {[t] + if[count value t; + `..loghandles[t] enlist (`upd;t;value flip value t); + @[`.stplg.msgcount;t;+;1]; + @[`.stplg.rowcount;t;+;count value t]; + .stpps.pubclear[t]]; + }each .stpps.t; + }; + +/ defaultbatch: write immediately, publish on the timer +upd[`defaultbatch]:{[t;x;now] + t insert x:.stplg.updtab[t] . (x;now); + `..loghandles[t] enlist(`upd;t;x); + @[`.stplg.tmpmsgcount;t;+;1]; + @[`.stplg.tmprowcount;t;+;count first x]; + }; + +zts[`defaultbatch]:{ + .stpps.pubclear[.stpps.t]; + .stplg.msgcount+:.stplg.tmpmsgcount; + .stplg.rowcount+:.stplg.tmprowcount; + .stplg.tmpmsgcount:.stplg.tmprowcount:()!(); + }; + +/ immediate: write and publish immediately +upd[`immediate]:{[t;x;now] + x:updtab[t] . (x;now); + `..loghandles[t] enlist(`upd;t;x); + x:$[0h>type last x;enlist;flip] .stpps.tabcols[t]!x; + @[`.stplg.msgcount;t;+;1]; + @[`.stplg.rowcount;t;+;count x]; + .stpps.pub[t;x] + }; + +zts[`immediate]:{} + +/ logcounts and lognames for client replay +replaylog:{[t] + getlogs[replayperiod][t] + } + +getlogs:enlist[`]!enlist () + +/ period: logs for the current logging period +getlogs[`period]:{[t] + distinct flip (.stplg.msgcount;exec tbl!logname from `..currlog where tbl in t)@\:t + }; + +/ day: all of today's logs; closed logs count 0W +getlogs[`day]:{[t] + lnames:select seq,tbls,logname,msgcount:0Wj from .stpm.metatable where any each tbls in\: t; + lnames:update msgcount:sum each .stplg.msgcount[tbls] from lnames where seq=.stplg.i; + flip value exec `long$msgcount,logname from lnames + }; + +/ open log for a table at the start of a logging period +openlog:{[multilog;dir;tab;p] + lname:logname[multilog][dir;tab;p]; + .z.m.log[`info][`openlog;"opening logfile: ",string lname]; + h:$[(notexists:not type key lname)or null h0:exec first handle from `..currlog where logname=lname; + [if[notexists;.[lname;();:;()]];hopen lname]; + h0 + ]; + `..currlog upsert (tab;lname;h); + }; + +/ error log for failed updates in error mode +openlogerr:{[dir] + lname:.[.stplg.logname.error;(dir;.stplg.errorlogname;.z.p+.z.m.eod.getdailyadj[]);{.z.m.log[`error][`openlogerr;"failed to make error log: ",x]}]; + if[not type key lname;.[lname;();:;()]]; + h:@[{hopen x};lname;{.z.m.log[`error][`openlogerr;"failed to open handle to error log with error: ",x]}]; + `..currlog upsert (errorlogname;lname;h); + }; + +badmsg:{[e;t;x] + .z.m.log[`info][`upd;"Bad message received, error: ",e]; + `..loghandles[errorlogname] enlist(`upderr;t;x); + }; + +closelog:{[tab] + if[null h:`..currlog[tab;`handle];.z.m.log[`info][`closelog;"no open handle to log file"];:()]; + .z.m.log[`info][`closelog;"closing log file ",string `..currlog[tab;`logname]]; + @[hclose;h;{.z.m.log[`error][`closelog;"handle already closed"]}]; + update handle:0N from `..currlog where tbl=tab; + }; + +/ roll all logs at the end of a logging period +rolllog:{[multilog;dir;tabs;p] + .stpm.updmeta[multilog][`close;tabs;p]; + closelog each tabs; + @[`.stplg.msgcount;tabs;:;0]; + {[m;d;t] + .[openlog;(m;d;t;currperiod); + {.z.m.log[`error][`stp;"failed to open log for table ",string[y],": ",x]}[;t]] + }[multilog;dir;]each tabs; + .stpm.updmeta[multilog][`open;tabs;p]; + }; + +/ process data sent at endofday/endofperiod +endofdaydata:@[value;`.stplg.endofdaydata;{ {`proctype`procname`tables!(.z.m.proctype;.z.m.procname;.stpps.t)} }]; + +/ chained end of period: pass on to subscribers; roll logs in create mode +endofperiod:{[currentpd;nextpd;data] + .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`endofperiod;"executing end of period for ",.Q.s1 `currentperiod`nextperiod!(currentpd;nextpd)]; + .stpps.endp[currentpd;nextpd;data]; + currperiod::nextpd; + if[.sctp.loggingmode=`create;periodrollover[data]] + }; + +/ end of period: send to subscribers; roll logs unless end of day is due +stpeoperiod:{[currentpd;nextpd;data;rolllogs] + .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`stpeoperiod;"passing on endofperiod message to subscribers"]; + .stpps.endp[currentpd;nextpd;data]; + currperiod::nextperiod; + if[(data`p)>nextperiod::multilogperiod+currperiod; + system"t 0";'"next period is in the past"]; + getnextendUTC[]; + if[rolllogs;periodrollover[data]]; + .z.m.log[`info][`stpeoperiod;"end of period complete, new values for current and next period are ",.Q.s1 (currentpd;nextpd)]; + } + +periodrollover:{[data] + i+::1; + rolllog[multilog;dldir;rolltabs;data`p]; + } + +/ end of day: send to subscribers and roll logs +endofday:{[date;data] + .z.m.log[`info][`endofday;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`endofday;"executing end of day for ",.Q.s1 .z.m.eod.getd[]]; + .stpps.end[date;data]; + dayrollover[data]; + } + +dayrollover:{[data] + .z.m.eod.setnextroll .z.m.eod.getroll data`p; + if[(data`p)>.z.m.eod.getnextroll[]; + system"t 0";'"next roll is in the past"]; + getnextendUTC[]; + .z.m.eod.setd 1+.z.m.eod.getd[]; + .stpm.updmeta[multilog][`close;logtabs;(data`p)+.z.m.eod.getdailyadj[]]; + .stpm.metatable:0#.stpm.metatable; + closelog each logtabs; + init[string .z.m.procname]; + .z.m.log[`info][`dayrollover;"end of day complete, new value for date is ",.Q.s1 .z.m.eod.getd[]]; + } + +getnextendUTC:{nextendUTC::-1+min(.z.m.eod.getnextroll[];nextperiod - .z.m.eod.getdailyadj[])} + +checkends:{ + if[nextendUTC > x; :()]; + if[nextperiod < x1:x+.z.m.eod.getdailyadj[]; stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; + if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;system"t 0";'"more than one day?"]; endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; + }; + +init:{[dbname] + t::tables[`.]except `currlog; + msgcount::rowcount::t!count[t]#0; + tmpmsgcount::tmprowcount::(`symbol$())!`long$(); + logtabs::$[multilog~`custom;key custommode;t]; + rolltabs::$[multilog~`custom;logtabs except where custommode in `tabular`singular;t]; + currperiod::multilogperiod xbar .z.p+.z.m.eod.getdailyadj[]; + nextperiod::multilogperiod+currperiod; + getnextendUTC[]; + i::1; + seqnum::0; + if[(value `..createlogs) or .sctp.loggingmode=`create; + createdld[dbname;.z.m.eod.getd[]]; + openlog[multilog;dldir;;.z.p+.z.m.eod.getdailyadj[]]each logtabs; + if[.stplg.errmode;openlogerr[dldir]]; + / read the meta table from disk and continue its sequence + .stpm.metatable:@[get;hsym`$string[.stplg.dldir],"/stpmeta";0#.stpm.metatable]; + i::1+ -1|exec max seq from .stpm.metatable; + .stpm.updmeta[multilog][`open;logtabs;.z.p+.z.m.eod.getdailyadj[]]; + ] + / chained and not creating logs: no log handles + if[.sctp.chainedtp and not .sctp.loggingmode=`create; + `..loghandles set t! (count t) # enlist (::) + ] + }; + +\d . diff --git a/di/torq/proc/segmentedtp/stpmeta.q b/di/torq/proc/segmentedtp/stpmeta.q new file mode 100644 index 00000000..4493d986 --- /dev/null +++ b/di/torq/proc/segmentedtp/stpmeta.q @@ -0,0 +1,44 @@ +/ log file metadata: logs opened, tables feeding each, message counts + +\d .stpm + +metatable:([]seq:`int$();logname:`$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()) + +/ meta update per logging mode, run on log open and close +updmeta:enlist[`]!enlist () + +updmeta[`tabperiod]:{[x;t;p] + getmeta[x;p;;]'[enlist each t;`..currlog[([]tbl:t)]`logname]; + setmeta[.stplg.dldir;metatable]; + }; + +updmeta[`singular]:{[x;t;p] + getmeta[x;p;t;`..currlog[first t]`logname]; + setmeta[.stplg.dldir;metatable]; + }; + +updmeta[`periodic]:updmeta[`singular] + +updmeta[`tabular]:updmeta[`tabperiod] + +updmeta[`custom]:{[x;t;p] + pertabs:where `periodic=.stplg.custommode; + updmeta[`periodic][x;t inter pertabs;p]; + updmeta[`tabular][x;t except pertabs;p] + }; + +/ name, start, tables and schema on open; end and message count on close +getmeta:{[x;p;t;ln] + if[x~`open; + s:((),t)!(),.stpps.schemas[t]; + `.stpm.metatable upsert (.stplg.i;ln;p;0Np;t;0;s;enlist ()!()); + ]; + if[x~`close; + update end:p,msgcount:sum .stplg.msgcount[t] from `.stpm.metatable where logname = ln + ] + }; + +setmeta:{[dir;mt] + t:(hsym`$string[dir],"/stpmeta"); + .[{x set y};(t;mt);{.z.m.log[`error][`setmeta;"Failed to set metatable with error: ",x]}]; + }; diff --git a/di/torq/proc/segmentedtp/stpps.q b/di/torq/proc/segmentedtp/stpps.q new file mode 100644 index 00000000..6ff79b3a --- /dev/null +++ b/di/torq/proc/segmentedtp/stpps.q @@ -0,0 +1,27 @@ +/ upd and zts wrapper functions + +/ check for end of day/period and call inner upd +.stpps.upd.def:{[t;x] + if[.stplg.nextendUTC1\"";columns:enlist\""sym,bid\"")]""; hb(`.u.upd;`quote;(`a`b;1 2f))",1,,filtered subscription with where and columns +true,0,0,q,"(`sym`bid;enlist`b)~(cols last first got;exec sym from last first got)",1,,only matching rows and columns published -comment,,,,,,,period and day rolls -true,0,0,q,periodroll[],1,,end of period closes the segment and rolls to a new file and notifies subscribers and lists the day -true,0,0,q,dayroll[],1,,end of day notifies subscribers and moves to the next day's directory and closes every segment +comment,,,,,,,memorybatch and tabular +run,0,0,q,"hc(`.u.upd;`trade;trd`a`b)",1,,send two trades +true,0,0,q,"(2;0)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"")",1,,held in memory and not logged +run,0,0,q,"hc"".z.ts .z.p""",1,,timer +true,0,0,q,"(0;1;1;2)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"";hc"".stplg.msgcount`trade"";hc"".stplg.rowcount`trade"")",1,,logged and counted on the timer +true,0,0,q,"(string hc""currlog[`trade;`logname]"") like ""*/stp3_trade2*""",1,,tabular log name -comment,,,,,,,subscriber surface / custom mode / lifecycle -true,0,0,q,subdetailsok[],1,,subdetails returns schemas and replay pairs and rowcounts and date and logdir -true,0,0,q,subbad[],1,,subdetails for only unknown tables throws -true,0,0,q,tablelistok[],1,,tablelist returns the publishable tables -true,0,0,q,readcsvok[],1,,readcustomcsv reads a table/mode csv from a string or symbol path -true,0,0,q,readcsvmissing[],1,,readcustomcsv rejects a missing file -true,0,0,q,readcsvbadmode[],1,,readcustomcsv rejects an unrecognised mode -true,0,0,q,readcsvbadheader[],1,,readcustomcsv rejects a csv without a table/mode header -true,0,0,q,setcustomok[],1,,setcustommode applies a new layout at runtime and reopens logs under it -true,0,0,q,setcustomnotcustom[],1,,setcustommode is rejected outside custom mode -true,0,0,q,setcustomunknown[],1,,setcustommode rejects tables that are not publishable -true,0,0,q,setcustombadmode[],1,,setcustommode rejects an unrecognised mode -true,0,0,q,exitok[],1,,a bad exit leaves logs alone and a clean exit flushes and closes them -true,0,0,q,teardownok[],1,,teardown flushes and closes every file and removes the job and handler -true,0,0,q,afterteardown[],1,,exported functions and the root upd reject calls after teardown +comment,,,,,,,chained +true,0,0,q,"(`quote`trade;1)~hs""(.stpps.t;count select from .sub.SUBSCRIPTIONS where table=`trade,active)""",1,,subscribed to the upstream +true,0,0,q,"waitfor {2=hs""count trade""}",1,,upstream publish arrives +true,0,0,q,"1 2~hs""(.stplg.updtab`trade)[1 2;3]""",1,,chained upd adds no time +run,0,0,q,"hs"".z.ts .z.p""",1,,timer +true,0,0,q,"(0;1;1)~hs""(count trade;.stplg.msgcount`trade;logcount:{-11!(-2;x)} currlog[`trade;`logname])""",1,,published and logged in create mode +true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z.d),""/sctp1_trade2*""",1,,own log in create mode +true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,parent mode replays the upstream logs +true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs -after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs +comment,,,,,,,end of period +run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; .z.ts .z.p""",1,,force the period end +true,0,0,q,"(1;`proctype`procname`tables`p;`stp1)~(count eops;key last last eops;(last last eops)`procname)",1,,endofperiod sent with process data +true,0,0,q,"(1;4;0)~ha""(.stplg.i;count .stpm.metatable;.stplg.msgcount`trade)""",1,,logs rolled and counts reset +true,0,0,q,"(0W;2)~ha""(first first r;count r:.stplg.replaylog`trade)""",1,,day replay lists the closed log as 0W +true,0,0,q,"1=count ha"".stplg.replayperiod:`period; r:.stplg.replaylog enlist`trade; .stplg.replayperiod:`day; r""",1,,period replay lists the current log only +true,0,0,q,"waitfor {1=hs"".stplg.i""}",1,,chained create mode rolls its logs + +comment,,,,,,,end of day +run,0,0,q,"eods:(); ha""(use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; .stplg.getnextendUTC[]; .z.ts .z.p""",1,,force the day end +true,0,0,q,"(1;.z.d;`stp1)~(count eods;first first eods;(last first eods)`procname)",1,,endofday sent with date and process data +true,0,0,q,"(.z.d+1;`$"":"",FIXDIR,""/a/stp1_"",string .z.d+1;2)~ha""((use`di.eodtime)[`getd][];.stplg.dldir;count .stpm.metatable)""",1,,date advanced and logs reopened +true,0,0,q,"ha"".z.p<(use`di.eodtime)[`getnextroll][]""",1,,next roll is in the future +true,0,0,q,"waitfor {(.z.d+1)=hs""(use`di.eodtime)[`getd][]""}",1,,chained passes end of day through + +comment,,,,,,,exit +run,0,0,q,"hc(`.u.upd;`trade;trd`x`y); cm:`$(string hc"".stplg.dldir""),""/stpmeta""; cl:hc""currlog[`trade;`logname]""; @[{neg[x]""exit 0"";neg[x][]};hc;()]",1,,send trades then exit cleanly +true,0,0,q,"waitfor {not alive PORTS`c}",1,,process exited +true,0,0,q,"(2;1b)~(logcount cl;all not null exec end from get cm)",1,,memorybatch flushed and logs closed on exit +run,0,0,q,"@[{neg[x]""exit 0"";neg[x][]};ha;()]",1,,upstream exits +true,0,0,q,"waitfor {not any alive each PORTS`s`p}",1,,chained processes exit when the upstream is lost + +after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index d6404df4..748c9212 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -1,633 +1,65 @@ -/ fixture helpers for di.torq.proc.segmentedtp's unit tests. Assumes cwd is the kdbx-modules repo root. -/ Uses REAL di.pubsub / di.eodtime / di.tplogmgr with a recording mock log, timer and handlers - the timer -/ never runs a cycle, so tick/rolls fire only when a test calls them. Each scenario helper inits the module -/ against its own log dir and returns 1b only if every named check passes; the per-check dict is left in LAST -/ so a failing row can be diagnosed with `show LAST`. Helpers live here because CSV fields cannot hold commas. - -BASE:"/tmp/di_segmentedtp_k4unit"; -MOD:`.m.di.0torq.0proc.0segmentedtp; - -/ read / write module state and reach internal functions -mv:{[n] get .Q.dd[MOD;n]}; -mset:{[n;v] .Q.dd[MOD;n] set v;}; - -chk:{[d] `LAST set d; all value d}; -errmsg:{[f] @[f;::;{x}]}; - -/ 1b only if f throws AND the error names the expected reason - a bare `fail` row would also pass on an -/ unrelated error (a fixture bug), proving nothing about the path under test -throws:{[f;s] r:errmsg f; (10h=type r) and 0",FIXDIR,"/",string[n],".log 2>&1 &"} +waitfor:{[f] d:.z.p+0D00:00:05; while[(.z.ptype c;c;first c]}; -cnt:{[t;col] ct:0!((st`getcounts)[])`tables; first (ct col) where ct[`tbl]=t}; -tf:{[] (mv`gentimeformat) mv`currperiod}; -dayerrname:{[] `$"stp_segmentederrorlogfile",(mv`gentimeformat)"p"$(mv[`eod]`getd)[]}; - -/ open file descriptors of this process pointing exactly at a file (0 once closed) -fdcount:{[f] count @[system;"ls -l /proc/",(string .z.i),"/fd 2>/dev/null | awk '$NF==\"",(1_string f),"\"'";{()}]}; - -/ feed n rows of table t through the published root upd (column-list form, one record each) -feed:{[t;n] {[t;i] upd[t;(`$"S",string i;$[t=`depth;i;1.0*i])]}[t] each til n;}; - -/ truncate a log mid-message -smash:{[f] n:hcount f; f 1: read1 (f;0;n-5);}; - -/ --- init validation --- - -initbadschema:{[] throws[{(st`init)[`kdbtplog`schemafile!("tplog/v";BASE,"/badschema.q");deps[]]};"no publishable tables"]}; -initnotdict:{[] throws[{(st`init)[cfg["tplog/v";()!()];(::)]};"deps must be a dict"]}; -initnolog:{[] throws[{(st`init)[cfg["tplog/v";()!()];`timer`handlers#deps[]]};"log dependency is required"]}; -initnotimer:{[] throws[{(st`init)[cfg["tplog/v";()!()];`log`handlers#deps[]]};"timer dependency is required"]}; -initnohandlers:{[] throws[{(st`init)[cfg["tplog/v";()!()];`log`timer#deps[]]};"handlers dependency is required"]}; -initlogkeys:{[] throws[{(st`init)[cfg["tplog/v";()!()];@[deps[];`log;:;`info`warn#mocklog[]]]};"missing error"]}; -initnokdbtplog:{[] throws[{(st`init)[enlist[`schemafile]!enlist BASE,"/database.q";deps[]]};"kdbtplog is required"]}; -initbad:{[k;v] resetmocks[]; (st`init)[cfg["tplog/v";enlist[k]!enlist v];deps[]]}; -initrejects:{[k;v;s] throws[{[k;v;x] initbad[k;v]}[k;v];s]}; - -badmsgnames:{[] - m:errmsg each ({initbad[`multilog;`hourly]};{initbad[`batchmode;`sometimes]};{initbad[`replayperiod;`prior]}); - all 0.z.p) - }; - -/ a TOML-style string offset is parsed and reaches di.eodtime; a value that cannot be parsed is dropped with a warning -tzstringok:{[] - doinit cfg["tplog/tzs";`rolltimezone`rolltimeoffset!("GMT";"0D10:00:00")]; - nr:(mv[`eod]`getnextroll)[]; - a:enlist[`stringoffset]!enlist 0D10:00=`timespan$(`long$"n"$nr) mod `long$1D; - doinit cfg["tplog/tzb";enlist[`rolltimeoffset]!enlist `notatimespan]; - chk a,`badignored`badwarned!(0D=`timespan$(`long$"n"$(mv[`eod]`getnextroll)[]) mod `long$1D;0abs .z.p-first trade`time; - 2020.01.01D00:00:00=trade[1;`time]; - `C`D~trade[2 3;`sym]; - `E~last trade`sym; - `F~first quote`sym) - }; - -errmodeok:{[] - doinit cfg["tplog/err";()!()]; - upd[`nosuch;(`A;1.0)]; - upd[`trade;(`A;"notafloat")]; - `ERRS set (); - -11!mv`errlog; - chk `twoerrs`unknowntable`badtype`warned!( - 2=count ERRS; - `nosuch~first first ERRS; - `trade~first last ERRS; - 2=count select from calls where lvl=`warn,ctx=`upd) - }; - -noerrmode:{[] - doinit cfg["tplog/noerr";`errmode`batchmode!(0b;`immediate)]; - throws[{upd[`nosuch;(`A;1.0)]};"not a publishable table"] - }; - -nologsok:{[] - doinit cfg["tplog/nologs";`createlogs`errmode`batchmode!(0b;0b;`immediate)]; - r:@[{feed[`trade;2];1b};::;{x}]; - chk `nothrow`counted`nodir`nologs!(1b~r;2=cnt[`trade;`msgcount];()~key hsym`$BASE,"/tplog/nologs";0=count mv`currlog) - }; - -unlistedok:{[] - doinit cfg["tplog/unlisted";`multilog`errmode`batchmode`customcsv!(`custom;0b;`immediate;"partial.csv")]; - r:@[{feed[`quote;2];1b};::;{x}]; - chk `nothrow`counted`noquotelog`tradelog!(1b~r;2=cnt[`quote;`msgcount];not `quote in exec tbl from mv`currlog;`trade in exec tbl from mv`currlog) - }; - -/ --- fixes --- - -fix1:{[] - dir:"tplog/fix1"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - feed[`trade;3]; - orig:fileof`trade; - (st`teardown)[]; - smash orig; - osize:hcount orig; - doinit c; - g:fileof`trade; - m:metaof dir; - a:`usesgood`goodcount`basecount`warned`origuntouched`metarenamed!( - g~(mv`goodname) orig; - 2=logcount g; - 2=(mv`basecount) g; - 0.z.p+(mv[`eod]`getdailyadj)[]) - }; - -fix3:{[] - dir:"tplog/fix3"; - doinit cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - olderr:mv`errlog; - oldtrade:fileof`trade; - olddir:daydir dir; - a:enlist[`erropen]!enlist 1=fdcount olderr; - (mv[`eod]`setnextroll)[.z.p-1]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - chk a,`errclosed`tradeclosed`newerropen`newerrfile`oldmetaclosed!( - 0=fdcount olderr; - 0=fdcount oldtrade; - 1=fdcount mv`errlog; - not olderr~mv`errlog; - all not null (get hsym`$olddir,"/stpmeta")`end) - }; - -fix4resume:{[] - dir:"tplog/fix4"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - feed[`trade;2]; - m0:metaof dir; - / an unclean exit: handles abandoned, segments never closed - (mv`releaselogs)[]; - mset[`initdone;0b]; - doinit c; - m:metaof dir; - chk `norowadded`stillopen`seqkept`countresumed!(count[m0]=count m;all null m`end;(m0`seq)~m`seq;2=cnt[`trade;`msgcount]+(mv`basecount) fileof`trade) - }; - -fix4orphan:{[] - dir:"tplog/fix4o"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - (st`teardown)[]; - ghost:hsym`$daydir[dir],"/stp_ghost20000101000000"; - m:metaof dir; - m:m,enlist `seq`logname`start`end`tbls`msgcount`schema`additional!(0i;ghost;.z.p;0Np;enlist`trade;5i;()!();()!()); - (hsym`$daydir[dir],"/stpmeta") set m; - doinit c; - n:metaof dir; - r:first select from n where logname=ghost; - chk `closed`nullcount`warned`othersresumed!( - not null r`end; - null r`msgcount; - 0ghost) - }; - -fix5:{[] - doinit cfg["tplog/fix5";`multilog`batchmode`replayperiod!(`singular;`immediate;`period)]; - feed[`trade;3]; - feed[`quote;2]; - f:fileof`trade; - both:(mv`getlogsperiod)`trade`quote; - one:(mv`getlogsperiod) enlist`trade; - sd:(st`subdetails)[enlist`trade;`]; - (use`di.pubsub)[`closesub][0]; - chk `sharedfile`onepair`summed`tradeonly`subdetails!( - f~fileof`quote; - 1=count both; - (5;f)~first both; - (5;f)~first one; - (enlist(5;f))~sd`logfilelist) - }; - -fix6:{[] - dir:"tplog/fix6"; - doinit cfg[dir;`multilog`batchmode`customcsv!(`custom;`immediate;"custom.csv")]; - m:metaof dir; - chk `tworows`shared`pertable!( - 2=count m; - 1=count select from m where {`quote`trade~asc x} each tbls; - 1=count select from m where {(enlist`depth)~x} each tbls) - }; - -/ --- rolls --- - -periodroll:{[] - dir:"tplog/proll"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;3]; - old:fileof`trade; - oldseq:mv`seq; - oldcp:mv`currperiod; - `EOP set (); - (st`subdetails)[`;`]; - np:.z.p+(mv[`eod]`getdailyadj)[]-0D00:00:01; - mset[`nextperiod;np]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - (use`di.pubsub)[`closesub][0]; - new:fileof`trade; - oldrow:first select from metaof[dir] where logname=old; - day:(mv`getlogsday) enlist`trade; - chk `newfile`oldclosed`oldcount`reset`seq`subscriber`daylist!( - not old~new; - not null oldrow`end; - 3i=oldrow`msgcount; - 0=cnt[`trade;`msgcount]; - (1i+oldseq)=mv`seq; - (oldcp;np)~2#EOP; - ((0W;old);(0;new))~day) - }; - -dayroll:{[] - dir:"tplog/droll"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;2]; - d0:(mv[`eod]`getd)[]; - olddir:daydir dir; - old:fileof`trade; - `EOD set 0Nd; - (st`subdetails)[`;`]; - (mv[`eod]`setnextroll)[.z.p-1]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - (use`di.pubsub)[`closesub][0]; - chk `subscriber`nextdate`newdir`oldclosed`reset`oldfdclosed!( - d0~EOD; - (d0+1)=(mv[`eod]`getd)[]; - not ()~key hsym`$daydir dir; - all not null (get hsym`$olddir,"/stpmeta")`end; - 0=cnt[`trade;`msgcount]; - 0=fdcount old) - }; - -/ --- subscriber surface, custom mode, lifecycle --- - -subdetailsok:{[] - dir:"tplog/subd"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;4]; - feed[`quote;1]; - sd:(st`subdetails)[`;`]; - (use`di.pubsub)[`closesub][0]; - chk `keys`schemas`rowcounts`pairs`tradepair`logdir`date!( - `schemalist`logfilelist`rowcounts`date`logdir~key sd; - (asc `trade`quote`depth)~asc first each sd`schemalist; - 4 1~sd[`rowcounts]`trade`quote; - all {(-7h=type x 0) and -11h=type x 1} each sd`logfilelist; - (4;fileof`trade) in sd`logfilelist; - (`$BASE,"/",dir)~sd`logdir; - (mv[`eod]`getd)[]~sd`date) - }; - -subbad:{[] - doinit cfg["tplog/subbad";()!()]; - throws[{(st`subdetails)[enlist`nosuch;`]};"not available"] - }; - -tablelistok:{[] - doinit cfg["tplog/tablelist";()!()]; - `depth`quote`trade~asc (st`tablelist)[] - }; - -readcsvok:{[] - ex:`trade`quote`depth!`singular`singular`tabperiod; - chk `string`symbol!(ex~(st`readcustomcsv) BASE,"/custom.csv";ex~(st`readcustomcsv) hsym`$BASE,"/custom.csv") - }; -readcsvmissing:{[] throws[{(st`readcustomcsv) BASE,"/nosuch.csv"};"not found"]}; -readcsvbadmode:{[] throws[{(st`readcustomcsv) BASE,"/badmode.csv"};"unrecognised mode"]}; -readcsvbadheader:{[] throws[{(st`readcustomcsv) BASE,"/badheader.csv"};"table,mode header"]}; - -setcustomok:{[] - dir:"tplog/setcustom"; - doinit cfg[dir;`multilog`batchmode!(`custom;`immediate)]; - a:`warned`nologs!(0/dev/null";{}]} each PIDS; - system "sleep 0.5"; - system "rm -rf ",IBASE; - }; - -/ ask the OS for a free port, then release it for the child to bind -freeport:{[] system"p 0W"; p:system"p"; system"p 0"; p}; - -tryopen:{[p] @[{hopen (`$":localhost:",string x;500)};p;0Ni]}; - -waitopen:{[p;n] - if[n<=0;:0Ni]; - if[not null h:tryopen p;:h]; - system "sleep 0.3"; - waitopen[p;n-1] - }; - -startchild:{[dir;args] - p:freeport[]; - cmd:QBIN," ",CHILD," -q -p ",(string p)," -kdbtplog ",dir," -schemafile ",IBASE,"/database.q ",args; - pid:"J"$first system cmd," >",IBASE,"/child.log 2>&1 & echo $!"; - `PIDS set PIDS,pid; - `pid`port`h!(pid;p;waitopen[p;40]) - }; - -kill9:{[c] - @[system;"kill -9 ",(string c`pid)," 2>/dev/null";{}]; - @[hclose;c`h;{}]; - system "sleep 0.5"; - }; - -/ n async updates then a sync round-trip, so every message has been processed before the helper returns -cfeed:{[c;t;n] - {[c;t;i] neg[c`h](`upd;t;(`$"S",string i;1.0*i))}[c;t] each til n; - c[`h]"::"; - }; - -cfile:{[c;t] c[`h] "exec first logname from ",SM,"currlog where tbl=`",string t}; -cpairs:{[c] c[`h] SM,"getlogsperiod`trade`quote"}; -cmetafile:{[c] hsym`$(c[`h] SM,"dldir"),"/stpmeta"}; - -smash:{[f] n:hcount f; f 1: read1 (f;0;n-5);}; - -/ open file descriptors of a process whose target contains a path -fdsfor:{[pid;f] c:@[system;"ls -l /proc/",(string pid),"/fd 2>/dev/null";{()}]; sum 0 di.torq.init -> settings cascade -> startbuiltin --- - -/ the kdbx-modules root that holds di/torq (two levels above the di.torq module dir) -torqxhome:{[] p:.Q.m.mp`di.torq; p:$[10h=type p;p;string p]; p:$[":"=first p;1_p;p]; "/" sv -2_"/" vs p}; - -stackapp:{[] - / a minimal app: schema, process.csv, and a proctype-tier toml with a string-valued timespan and booleans - / (singular forces the period to 1D whatever the toml says - the assertion below checks that too) - app:IBASE,"/app"; - system "mkdir -p ",app,"/appconfig/settings"; - (hsym`$app,"/database.q") 0: ( - "trade:([]time:`timestamp$();sym:`g#`symbol$();price:`float$())"; - "quote:([]time:`timestamp$();sym:`g#`symbol$();bid:`float$())"); - (hsym`$app,"/appconfig/settings/default.toml") 0: enlist "# app defaults"; - (hsym`$app,"/appconfig/settings/segmentedtp.toml") 0: ( - "kdbtplog = \"stplogs\"";"multilog = \"singular\"";"batchmode = \"immediate\""; - "multilogperiod = \"0D01:00:00\"";"errmode = true";"tickinterval = 1"); - app}; - -startstack:{[app;port] - / launch exactly as torqx.sh does: QINIT=torqx_init.q with explicit identity and a stack id - setenv[`TORQXHOME;torqxhome[]]; - setenv[`TORQXAPPCONFIG;app,"/appconfig"]; - setenv[`TORQXAPPHOME;app]; - setenv[`TORQXDATAHOME;app]; - (hsym`$app,"/appconfig/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string port),",segmentedtp,stp1"); - cmd:"QINIT=",torqxhome[],"/di/torq/bin/torqx_init.q ",QBIN," -q -p ",(string port)," -proctype segmentedtp -procname stp1 -torqxstackid itest"; - pid:"J"$first system cmd," >",IBASE,"/stack.log 2>&1 & echo $!"; - `PIDS set PIDS,pid; - `pid`port`h!(pid;port;waitopen[port;40])}; - -stackboot:{[] - / kdb-x abandons a QINIT script silently at the first error and leaves the process at its prompt, so a boot - / failure looks like a running process: assert the module's observable effects, never just "it came up" - app:stackapp[]; - c:startstack[app;freeport[]]; - if[null c`h;:chk enlist[`childup]!enlist 0b]; - a:`tptype`updpublished`identity`cascade`jobopts`exithandler!( - `segmented~c[`h]"tptype"; - c[`h]"`upd in key `."; - (`segmentedtp;`stp1)~c[`h]"(",SM,"proctype;",SM,"procname)"; - (`singular;`immediate;1D;1b)~c[`h]"(",SM,"multilog;",SM,"batchmode;",SM,"multilogperiod;",SM,"errmode)"; - 0b~c[`h]"exec first disableonfail from .m.di.0timer.jobs where id=`segmentedtp"; - `segmentedtp in c[`h]"exec name from (use`di.torq.handlers)[`list]`.z.exit"); - cfeed[c;`trade;3]; - cfeed[c;`quote;2]; - f:cfile[c;`trade]; - metaf:cmetafile c; - a:a,`shared`counted!(f~cfile[c;`quote];(enlist(5;f))~cpairs c); - @[c`h;"exit 0";{}]; - system "sleep 1"; - chk a,enlist[`cleanexitclosed]!enlist all not null (get metaf)`end - }; diff --git a/di/torq/proc/segmentedtp/test_integration_child.q b/di/torq/proc/segmentedtp/test_integration_child.q deleted file mode 100644 index c3839678..00000000 --- a/di/torq/proc/segmentedtp/test_integration_child.q +++ /dev/null @@ -1,24 +0,0 @@ -/ child process for test_integration.csv - not a test file itself; test_integration.q launches it. -/ Runs di.torq.proc.segmentedtp wired to the REAL di.timer, di.torq.handlers and di.util.log (built as di.torq -/ builds them). Every -flag value on the command line becomes a config setting as a STRING (as a .toml or a -/ command-line override would deliver it), so the module's own coercions are exercised: -kdbtplog -schemafile -/ -multilog -batchmode -multilogperiod -rolltimeoffset -replayperiod -tickinterval ... - -o:.Q.opt .z.x; -cfg:(key o)!first each value o; -if[not `tickinterval in key cfg;cfg[`tickinterval]:1]; -if[`rolltimeoffset in key cfg;cfg[`rolltimeoffset]:"N"$cfg`rolltimeoffset]; - -lg:use`di.util.log; -logdep:`info`warn`error!(lg`info;lg`warn;lg`error); - -tm:use`di.timer; -tm[`init][()!()]; -timerdep:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!((tm`addjob)`custom;tm`deletejobs;tm`enablejobs;tm`disablejobs;tm`getactivejobs); - -hz:use`di.torq.handlers; -hz[`init][enlist[`log]!enlist logdep]; -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list); - -sp:use`di.torq.proc.segmentedtp; -sp[`init][cfg;`log`timer`handlers!(logdep;timerdep;handlersdep)]; From feac8abf14f0b25af40b0c0f90115f29bb1df3b5 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 1 Oct 2026 16:07:12 +0100 Subject: [PATCH 21/42] di.torq.proc.tickerlogreplay 0.1.0: port TorQ's tickerlogreplay; di.dbwrite 0.2.0; di.tplog version tickerlogreplay is a one-to-one port of TorQ's code/processes/tickerlogreplay.q. It replays a plain tickerplant log, or a segmented tickerplant log directory (picked through stpmeta), into an hdb. tickerlogreplay.q holds the module init, then the TorQ helpers it calls that no di module provides, each defined if absent: the .os directory helpers (os.q:3-5,8,16), the .save section (dbwriteutils.q) and .merge.getextrapartitiontype (merge.q:8); then .replay. sort.csv is TorQ's config/sort.csv. Hard deps: di.tplog, di.merge, di.dbwrite. Ledger (the only deviations from TorQ's text): 1. .lg.o/.lg.e/.lg.w -> .z.m.log. 2. .err.ex/.err.exitifnull -> module-local ex/exitifnull: log TorQ's message, exit with TorQ's code. The usage text is not ported. 3. .tplog.check -> di.tplog check. 4. .sort.getsortcsv/sorttab -> di.dbwrite readcsv/sort; .gc.run -> di.dbwrite gc. With no sortcsv, init loads the shipped sort.csv (setconfig) in place of the config/sort.csv lookup. dbwrite rejects null tabname/column rows. 5. .merge.* -> di.merge, passing getextrapartitiontype[t] where TorQ passes the table name; .merge.partsizes -> trackpartition/getpartsizes; mergebybytelimit -> di.merge init config. getextrapartitiontype reads di.dbwrite getconfig[] for .sort.params. 6. .os helpers in the module, each guarded separately; no di.os. 7. .dotz.set of .z.zd -> set. 8. Settings: replay section onto .replay, merge section onto .merge and di.merge init. .replay.upd and the .save hooks are set before use. sortcsv from config. .proc switches not ported. 9. Load-time statements run in init, in TorQ's order: checks, schema load, the two realupd wrappers (fully qualified), sort csv, autoreplay. 10. Comments trimmed to one line. Kept quirks, tested: checklogfiles on a plain log replays .good, whose name has no date, so tables land at the hdb root; the segmented-mode firstmessage/lastmessage check never exits (its .err.ex call has two args). di.dbwrite 0.2.0 exports its existing gc (TorQ's .gc.run); rdb/wdb need >=0.1.0. di.tplog gains a VERSION file and version export (0.1.0) so a deps.toml entry can be checked. di.torq registers tickerlogreplay as a builtin proctype; torq.md's registry example and two stale known-gap notes are corrected. Tests: each replay runs in a fresh q; the fixture writes a plain log and runs a real segmentedtp to write a segmented log directory. 89/89 (x3). dbwrite 165/169 (the four failing rows need kx.log, not installed here), tplog 16/16, merge 226/226, rdb 4/4, wdb 4/4, segmentedtp 66/66, di.torq 57/57. Co-Authored-By: Claude Opus 5.5 --- di/dbwrite/VERSION | 2 +- di/dbwrite/dbwrite.md | 3 +- di/dbwrite/init.q | 2 +- di/dbwrite/test.csv | 5 + di/torq/proc/tickerlogreplay/VERSION | 1 + di/torq/proc/tickerlogreplay/deps.toml | 5 + di/torq/proc/tickerlogreplay/init.q | 8 + di/torq/proc/tickerlogreplay/sort.csv | 3 + di/torq/proc/tickerlogreplay/test.csv | 111 +++++ di/torq/proc/tickerlogreplay/test.q | 66 +++ .../proc/tickerlogreplay/tickerlogreplay.md | 89 ++++ .../proc/tickerlogreplay/tickerlogreplay.q | 432 ++++++++++++++++++ di/torq/torq.md | 11 +- di/torq/torq.q | 2 +- di/tplog/VERSION | 1 + di/tplog/init.q | 4 +- di/tplog/tplog.md | 2 +- 17 files changed, 734 insertions(+), 13 deletions(-) create mode 100644 di/torq/proc/tickerlogreplay/VERSION create mode 100644 di/torq/proc/tickerlogreplay/deps.toml create mode 100644 di/torq/proc/tickerlogreplay/init.q create mode 100644 di/torq/proc/tickerlogreplay/sort.csv create mode 100644 di/torq/proc/tickerlogreplay/test.csv create mode 100644 di/torq/proc/tickerlogreplay/test.q create mode 100644 di/torq/proc/tickerlogreplay/tickerlogreplay.md create mode 100644 di/torq/proc/tickerlogreplay/tickerlogreplay.q create mode 100644 di/tplog/VERSION diff --git a/di/dbwrite/VERSION b/di/dbwrite/VERSION index 6e8bf73a..0ea3a944 100644 --- a/di/dbwrite/VERSION +++ b/di/dbwrite/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0 diff --git a/di/dbwrite/dbwrite.md b/di/dbwrite/dbwrite.md index 1b0b4916..037087c4 100644 --- a/di/dbwrite/dbwrite.md +++ b/di/dbwrite/dbwrite.md @@ -69,6 +69,7 @@ default,,time,1 | `savedown[dir;part;tabname;data]` | Write an in-memory table to an HDB partition, sort it, then run gc | | `appenddown[dir;part;tabname;data]` | Append rows to an existing partition (no sort) | | `applyattr[dloc;colname;att]` | Apply a single kdb+ attribute to an on-disk column | +| `gc[]` | Run `.Q.gc[]` and log memory stats before and after | --- @@ -207,5 +208,5 @@ The suite injects binary mock loggers (`{[c;m] ...}`): a no-op logger, and a cap ## Exported symbols ```q -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc]) ``` diff --git a/di/dbwrite/init.q b/di/dbwrite/init.q index dcea6c10..115c2160 100644 --- a/di/dbwrite/init.q +++ b/di/dbwrite/init.q @@ -8,4 +8,4 @@ / BOTH the file (pre-load manifest walk) and this export (post-load session audit). version:first read0`:::VERSION -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;version]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc;version]) diff --git a/di/dbwrite/test.csv b/di/dbwrite/test.csv index f6df53fa..a61af3c1 100644 --- a/di/dbwrite/test.csv +++ b/di/dbwrite/test.csv @@ -190,6 +190,11 @@ true,0,0,q,"any caplog[`msg] like ""*read 3 sort config*""",1,1,readcsv logs the true,0,0,q,all not null (select from caplog where fn=`info)[`ctx],1,1,readcsv logs are tagged with a context symbol true,0,0,q,not any caplog[`fn]=`error,1,1,readcsv logs no errors on success +comment,,,,,,,log call verification - gc +run,0,0,q,caplog:0#caplog,1,1,reset log capture +run,0,0,q,dbwrite.gc[],1,1,gc runs +true,0,0,q,2=count select from caplog where ctx=`gc,1,1,gc logs before and after + comment,,,,,,,log call verification - readcsv error logging on file read failure run,0,0,q,caplog:0#caplog,1,1,reset log capture run,0,0,q,@[dbwrite.readcsv;`:nonexistent_file.csv;{x}],1,1,trigger file read error diff --git a/di/torq/proc/tickerlogreplay/VERSION b/di/torq/proc/tickerlogreplay/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/torq/proc/tickerlogreplay/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/torq/proc/tickerlogreplay/deps.toml b/di/torq/proc/tickerlogreplay/deps.toml new file mode 100644 index 00000000..47a1450e --- /dev/null +++ b/di/torq/proc/tickerlogreplay/deps.toml @@ -0,0 +1,5 @@ +# Peer modules di.torq.proc.tickerlogreplay `use`s (see di/torq/depcheck/depcheck.md). +[dependencies] +"di.tplog" = "0.1.0" +"di.merge" = "0.1.0" +"di.dbwrite" = "0.2.0" diff --git a/di/torq/proc/tickerlogreplay/init.q b/di/torq/proc/tickerlogreplay/init.q new file mode 100644 index 00000000..8abf82af --- /dev/null +++ b/di/torq/proc/tickerlogreplay/init.q @@ -0,0 +1,8 @@ +\l ::tickerlogreplay.q + +version:first read0`:::VERSION + +/ the default sort config +sortdefault:("SSSB";enlist",")0:read0`:::sort.csv + +export:([init;version]) diff --git a/di/torq/proc/tickerlogreplay/sort.csv b/di/torq/proc/tickerlogreplay/sort.csv new file mode 100644 index 00000000..8ab1b9c3 --- /dev/null +++ b/di/torq/proc/tickerlogreplay/sort.csv @@ -0,0 +1,3 @@ +tabname,att,column,sort +default,p,sym,1 +default,,time,1 diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv new file mode 100644 index 00000000..1585e36c --- /dev/null +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -0,0 +1,111 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,tlr:use`di.torq.proc.tickerlogreplay,1,,load module +before,0,0,q,"system ""l di/torq/proc/tickerlogreplay/test.q""",1,,load fixture helpers +before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmentedtp to write segmented logs + +comment,,,,,,,settings +true,0,0,q,"(0;1b;1b;0W;0W;enlist`all;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`part)~.replay`firstmessage`segmentedmode`autoreplay`lastmessage`messagechunks`tablelist`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`mergemethod",1,,replay defaults +true,0,0,q,`:tempmergedir~.replay.tempdir,1,,tempdir default +true,0,0,q,all `NT`Fex`pth`deldir`md in key .os,1,,os helpers defined +true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined +fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error + +comment,,,,,,,plain log +true,0,0,q,0=replay sect plain "()!()",1,,a full replay exits 0 +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,every message replayed into a date partition +true,0,0,q,`a`b`c~syms[D;`trade],1,,the default sort csv sorts by sym +true,0,0,q,`p~attr hdb[D;`trade]`sym,1,,and applies p# to sym +true,0,0,q,"logged ""*replayed data into tables with the following counts: trade = 3; quote = 1*""",1,,table counts logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`tablelist]!enlist enlist`trade",1,,replay one table +true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,other tables are not saved +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "`firstmessage`lastmessage!1 1",1,,replay message 1 only +true,0,0,q,(0;1)~(rows[D;`trade];rows[D;`quote]),1,,only the quote message replayed; trade saved empty +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`messagechunks]!enlist 1",1,,save every message +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,chunked saves append +true,0,0,q,"logged ""*has been exceeded. Saving down*""",1,,chunk saves logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`messagechunks]!enlist -1",1,,negative chunks only track +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,tables saved at the end +true,0,0,q,"logged ""*Total message count so far is 3*""",1,,progress logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`basicmode]!enlist 1b",1,,basic mode +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,saved with .Q.hdpf +run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay sect plain ""enlist[`sortcsv]!enlist "",hp""timesort.csv""",1,,replay with a sort csv +true,0,0,q,(`b`a`c;`)~(syms[D;`trade];attr hdb[D;`trade]`sym),1,,the sort csv sorts by time with no attribute +run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay sect plain ""enlist[`compression]!enlist 17 2 6""",1,,replay with compression +true,0,0,q,"0",FIXDIR,"/run.log 2>&1; echo $?"} +/ replay with q lines run before use and a config from a q expression; an init error exits 3 +replayp:{[pre;cfg] runq( + enlist["lg:`info`warn`error!({[c;m] -1 \"I \",string[c],\": \",m};{[c;m] -1 \"W \",string[c],\": \",m};{[c;m] -1 \"E \",string[c],\": \",m})"],pre,( + "r:use`di.torq.proc.tickerlogreplay"; + "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; + "exit 0"))} +replay:replayp[()] +/ replay settings for the plain log, with overrides +plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} +sect:{[x] "enlist[`replay]!enlist ",x} +ran:{[x] read0 fp"run.log"} +logged:{[s] any ran[] like s} +/ was a log named in the list of logs to replay +replayed:{[s] any (ran[] where ran[] like "*Replaying the following log*") like "*",s,"*"} + +/ an hdb table, or () if absent +hdb:{[p;t] @[get;fp"hdb/",p,"/",string[t],"/";()]} +rows:{[p;t] count hdb[p;t]} +syms:{[p;t] (get fp"hdb/sym") hdb[p;t]`sym} +clearhdb:{system "rm -rf ",FIXDIR,"/hdb ",FIXDIR,"/tmp"} + +setupfixture:{[] + system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; + fp["schema.q"] 0: ( + "trade:([]time:`timestamp$();sym:`g#`symbol$();price:`float$();size:`int$())"; + "quote:([]time:`timestamp$();sym:`g#`symbol$();bid:`float$())"); + / plain log: trade b a, quote a, trade c + h:hopen fp["tplog",D] set (); + h enlist(`upd;`trade;(2026.10.01D10:00:00 2026.10.01D10:00:01;`b`a;1 2f;10 20i)); + h enlist(`upd;`quote;(enlist 2026.10.01D10:00:02;enlist`a;enlist 3f)); + h enlist(`upd;`trade;(enlist 2026.10.01D10:00:03;enlist`c;enlist 4f;enlist 40i)); + hclose h; + / a sort csv sorting trade by time only, with no attributes + fp["timesort.csv"] 0: ("tabname,att,column,sort";"default,,time,1"); + / segmented logs written by a segmentedtp process + runq( + "nolog:`info`warn`error!3#{[c;m]}"; + "h:use`di.torq.handlers"; + "h.init enlist[`log]!enlist nolog"; + "seg:use`di.torq.proc.segmentedtp"; + "seg.init[`proctype`procname`schemafile`stplg!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";enlist[`kdbtplog]!enlist`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; + ".u.upd[`quote;(enlist`a;enlist 3f)]"; + ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; + "exit 0"); + `STPDIR`SD set' (FIXDIR,"/stp/",string first key fp"stp";string .z.d); + / a meta table naming logs from two dates + system "mkdir -p ",FIXDIR,"/mixed"; + fp["mixed/stpmeta"] set ([]seq:0 1i;logname:fp each ("mixed/stp1_trade20261001000000";"mixed/stp1_quote20261002000000");start:2#.z.p;end:2#0Np;tbls:(enlist`trade;enlist`quote);msgcount:2#0i;schema:(();());additional:(();())); + } + +/ replay settings for the segmentedtp logs, with overrides +seg:{[x] "(`schemafile`hdbdir`tplogdir!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",STPDIR,"\")),",x} + +teardownfixture:{[] system "rm -rf ",FIXDIR} diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md new file mode 100644 index 00000000..d2d80b79 --- /dev/null +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -0,0 +1,89 @@ +# di.torq.proc.tickerlogreplay + +Replays tickerplant log files into a date-, month- or year-partitioned HDB. It reads either one plain +tickerplant log or a directory of segmented tickerplant logs (`di.torq.proc.segmentedtp` output, picked through +its `stpmeta` table). It can replay all messages or a range of them, save in chunks, sort and apply attributes +at the end, or partition to a temporary directory and merge on disk. + +## Files + +`init.q` loads `tickerlogreplay.q`: the module `init`, then the `.os` directory helpers and the `.save` hooks +(`savedownmanipulation`, `manipulate`, `postreplay`), each defined if absent, `.merge.getextrapartitiontype`, and +`.replay`. `sort.csv` is the default sort config. + +## Surface + +| Name | What | +|---|---| +| `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | +| `.replay.initandrun[]` | replays every log, sorts or merges, runs `postreplay`, and exits if `exitwhencomplete` | +| `.replay.replaylog[logfile]` | replays one log and saves its tables | +| `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | +| `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | +| `.merge.getextrapartitiontype[t]` | the `p#` column(s) for a table from the sort config | + +## Settings + +A `replay` section, set onto `.replay.`: + +| Key | Default | +|---|---| +| `schemafile` | `` ` `` — required | +| `hdbdir` | `` ` `` — required | +| `tplogfile` / `tplogdir` | `` ` `` — one of them is required | +| `segmentedmode` | `1b` — `tplogdir` is a segmented tickerplant log directory | +| `tablelist` | `` enlist`all `` | +| `firstmessage` / `lastmessage` | `0` / `0W` — inclusive message indices | +| `messagechunks` | `0W` — messages per save; negative only logs progress | +| `partitiontype` | `` `date `` — `date`, `month` or `year` | +| `emptytables` | `1b` — create each table empty in the partition first | +| `sortafterreplay` | `1b` | +| `sortcsv` | `` ` `` — null uses `sort.csv` (`sym` then `time`, `p#` on `sym`) | +| `basicmode` | `0b` — replay everything, then save with `.Q.hdpf` | +| `checklogfiles` | `0b` — replay a good copy of a corrupt log | +| `clean` | `1b` — delete the date's existing data first | +| `compression` | `()` — `.z.zd` when three values | +| `partandmerge` / `tempdir` / `mergemethod` | `0b` / `` `:tempmergedir `` / `` `part `` (`part`, `col` or `hybrid`) | +| `mergenumrows` / `mergenumtab` / `mergenumbytes` | `10000000` / `` `quote`trade!10000 50000 `` / `500000000` | +| `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | + +A `merge` section (`mergebybytelimit`, `partlimit`) is set onto `.merge.` and passed to di.merge's `init`. + +## init[config;deps] + +Requires `log`. It: + +1. initialises di.dbwrite and di.merge, and applies the settings; +2. exits on a bad setting: + - code 1 for a null `schemafile`/`hdbdir`/log, an unknown `partitiontype`, `basicmode` with + `messagechunks`, or `partandmerge` into `hdbdir`; + - code 2 for zero `messagechunks` or a schema file that fails to load; +3. loads the schema file at root; +4. wraps `.replay.realupd` to filter on `tablelist` (plain logs) and to save every `messagechunks` messages; +5. loads `sortcsv`, or `sort.csv`, into di.dbwrite; +6. replays when `autoreplay`. + +## Behaviour to know + +- The replay process exits when complete unless `exitwhencomplete` is `0b`; call `init` once per process. +- Plain log dates come from the last ten characters of the file name (`YYYY.MM.DD`), segmented log dates from + their `_YYYYMMDDhhmmss` suffix. Segmented logs from more than one date are refused. +- With `checklogfiles` on a plain log, the repaired copy is named `.good`, so it has no date and its tables + are saved at the HDB root. +- In segmented mode, a non-default `firstmessage` or `lastmessage` doesn't stop the replay. +- `clean` deletes the whole date partition when `tablelist` is `all`, otherwise only the replayed tables. +- A table with no rows is still saved empty when `emptytables` is on. +- `partandmerge` turns `sortafterreplay` off and applies `p#` through the merge. + +## Testing + +```q +k4unit:use`di.k4unit +k4unit.moduletest`di.torq.proc.tickerlogreplay +``` + +`test.q`/`test.csv` write a plain log, run a segmentedtp process to write a segmented log directory, and run +each replay in a fresh q. The tests cover the settings, the init checks, full and table-filtered replays, +message ranges, chunked and track-only saves, basic mode, a custom sort csv, compression, clean, `upd`, +`savedownmanipulation` and `postreplay` overrides, all three merge methods, segmented replays (picking logs from +`stpmeta`, mixed dates refused), and `checklogfiles` on segmented and plain logs. diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q new file mode 100644 index 00000000..2a3e8a2f --- /dev/null +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -0,0 +1,432 @@ +/ di.torq.proc.tickerlogreplay - replay tickerplant log files into an hdb + +/ log the error and exit +ex:{[id;message;code] .z.m.log[`error][id;message]; exit code} + +/ exit if a variable is null +exitifnull:{[variable] + if[null value variable; + .z.m.log[`error][`init;"Variable ",(string variable)," is null but must be set"]; + exit 1]} + +init:{[config;deps] + if[not `log in key deps;'"di.torq.proc.tickerlogreplay: log dependency is required - see di.util.log"]; + .z.m.log:deps`log; + .z.m.tplog:use`di.tplog; + .z.m.dbw:use`di.dbwrite; + .z.m.dbw.init enlist[`log]!enlist deps`log; + {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `replay`merge; + .z.m.merge:use`di.merge; + .z.m.merge.init (enlist[`log]!enlist deps`log),$[`merge in key config;config`merge;()!()]; + / some variables must be set + exitifnull each `.replay.schemafile`.replay.hdbdir, $[all null .replay`tplogdir`tplogfile; `.replay.tplogfile; ()]; + if[.replay.basicmode and (.replay.messagechunks within (0;-1 + 0W)); + ex[`replayinit; "if using basic mode, messagechunks must not be used (it should be set to 0W). basicmode will use .Q.hdpf to overwrite tables at the end of the replay";1]]; + if[not .replay.partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; + if[.replay.messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; + if[.replay.segmentedmode and ((0<>.replay.firstmessage) or 0W<>.replay.lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode"];1]; + .replay.trackonly:.replay.messagechunks < 0; + if[.replay.trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; + .replay.messagechunks:abs .replay.messagechunks; + if[.replay.partandmerge and .replay.hdbdir = .replay.tempdir;ex[`replayinit;"if using partandmerge replay, tempdir must be set to a different directory than the hdb";1]]; + if[.replay.partandmerge and .replay.sortafterreplay;(.replay.sortafterreplay:0b; .z.m.log[`info][`replayinit;"Setting sortafterreplay to 0b"])]; + / load the schema + .z.m.log[`info][`replayinit;"loading schema file ",string .replay.schemafile]; + @[system;"l ",string .replay.schemafile;{ex[`replayinit;"failed to load replay file ",(string x)," - ",y;2]}[.replay.schemafile]]; + .z.m.log[`info][`replayinit;"hdb directory is set to ",string .replay.hdbdir:hsym .replay.hdbdir]; + .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .replay.tempdir:hsym .replay.tempdir]; + / filter on the table list + if[(not .replay.tablelist~enlist `all) and not .replay.segmentedmode; .replay.realupd:{[f;t;x] if[t in .replay.tablestoreplay; f[t;x]]}[.replay.realupd]]; + / chunked saves + if[.replay.messagechunks < 0W; .replay.realupd:{[f;t;x] f[t;x]; .replay.checkcount[.replay.hdbdir;.replay.replaydate;1;.replay.tempdir]}[.replay.realupd]]; + / load the sort csv and kick off replay if auto-running + $[null .replay.sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv .replay.sortcsv]; + if[.replay.autoreplay;.replay.initandrun[]]; + } + +/ os helpers, each defined if absent + +\d .os + +if[not `NT in key `.os;NT:.z.o in`w32`w64]; +if[not `Fex in key `.os;Fex:{not 0h~type key hsym$[10=type x;`$x;x]}]; +if[not `pth in key `.os;pth:{if[10h<>type x;x:string x]; if[NT;x:@[x;where"/"=x;:;"\\"]];$[":"=first x;1_x;x]}]; +if[not `deldir in key `.os;deldir:{system("rm -r ";"rd /s /q ")[NT],pth x}]; +if[not `md in key `.os;md:{if[not Fex x;system"mkdir \"",pth[x],"\""]}]; + +/ save down manipulation and post replay hook, each defined if absent + +\d .save + +/ table!function applied to a table before it is enumerated and saved +if[not `savedownmanipulation in key `.save;savedownmanipulation:@[value;`savedownmanipulation;()!()]]; + +/ manipulate a table at save down time +if[not `manipulate in key `.save;manipulate:{[t;x] + $[t in key savedownmanipulation; + @[savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; + x]}]; + +/ called after a log's tables are saved, with the directory and partition +if[not `postreplay in key `.save;postreplay:{[d;p] + + }]; + +/ parted column(s) for a table from the sort config + +\d .merge + +getextrapartitiontype:{[tablename] + sp:.z.m.dbw.getconfig[]; + tabparts:$[count tabparts:distinct exec column from sp where tabname=tablename,sort=1,att=`p; + [.z.m.log[`info][`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; + tabparts]; + count defaultparts:distinct exec column from sp where tabname=`default,sort=1,att=`p; + [.z.m.log[`info][`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table, using default instead"]; + defaultparts]; + [.z.m.log[`error][`getextraparttype;"parted attribute p not found in sort.csv for ", (string tablename)," table and default not defined"]] + ]; + tabparts + }; + +\d . + +.merge.mergebybytelimit:@[value;`.merge.mergebybytelimit;0b]; // merge limit configuration - default is 0b row count limit, 1b is bytesize limit + +\d .replay + +/ settings +firstmessage:@[value;`firstmessage;0] // the first message to execute +segmentedmode:@[value;`segmentedmode;1b] // segmented tickerplant logs +autoreplay:@[value;`autoreplay;1b] // replay tplogs automatically +lastmessage:@[value;`lastmessage;0W] // the last message to replay +messagechunks:@[value;`messagechunks;0W] // the number of messages to replay at once +schemafile:@[value;`schemafile;`] // the schema file to load data in to +tablelist:@[value;`tablelist;enlist `all] // the tables to replay into. `all means all +hdbdir:@[value;`hdbdir;`] // the hdb directory to write to +tplogfile:@[value;`tplogfile;`] // the tp log file to replay; this or tplogdir +tplogdir:@[value;`tplogdir;`] // the tp log directory to replay; this or tplogfile +partitiontype:@[value;`partitiontype;`date] // date, month or year +emptytables:@[value;`emptytables;1b] // whether to overwrite any tables at start up +sortafterreplay:@[value;`sortafterreplay;1b] // re-sort and apply attributes at the end of the replay +basicmode:@[value;`basicmode;0b] // replay everything, then save with .Q.hdpf +exitwhencomplete:@[value;`exitwhencomplete;1b] // exit when the replay is complete +checklogfiles:@[value;`checklogfiles;0b] // replay a "good" copy of a corrupt log +gc:@[value;`gc;1b] // garbage collect after each table save and each log +upd:@[value;`upd;{{[t;x] insert[t;x]}}] // default upd function used for replaying data +clean:@[value;`clean;1b] // clean existing folders on start up +sortcsv:@[value;`sortcsv;`] // location of sort csv file; null is the default sort.csv +compression:@[value;`compression;()]; // the compress level, empty list if not required +partandmerge:@[value;`partandmerge;0b]; // partition to tempdir, then merge on disk +tempdir:hsym @[value;`tempdir;`:tempmergedir]; // location to save data for partandmerge replay +mergenumrows:@[value;`mergenumrows;10000000]; // default number of rows for merge process +mergenumtab:@[value;`mergenumtab;`quote`trade!10000 50000]; // number of rows per table for merge process +mergenumbytes:@[value;`mergenumbytes;500000000]; // default number of bytes for merge process +mergemethod:@[value;`mergemethod;`part]; // part, col or hybrid + +/ save down settings +.save.savedownmanipulation:@[value;`savedownmanipulation;()!()] // table!function applied to a table at save +.save.postreplay:@[value;`postreplay;{{[d;p] }}] // invoked after a log's tables are saved + +// the path to the table to save +pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} + +// create empty tables - we need to make sure we only create them once +emptytabs:`symbol$() +createemptytable:{[h;p;t;td] + $[partandmerge;dest:td;dest:h]; + if[(not (path:pathtotable[dest;p;t]) in .replay.emptytabs) and .replay.emptytables; + .z.m.log[`info][`replay;"creating empty table ",(string t)," at ",string path]; + .replay.emptytabs,:path; + savetabdatatrapped[h;p;t;0#value t;0b;td]]} + +savetabdata:{[h;p;t;data;UPSERT;td] + $[partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; + if[not partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; + .replay.pathlist[t],:path; + $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + } + +savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} + +// this function should be invoked for saving tables +savetab:{[td;h;p;t] + if[not partandmerge;createemptytable[h;p;t;td]]; + if[count value t; + .z.m.log[`info][`replay;"saving ",(string t)," which has row count ",string count value t]; + savetabdatatrapped[h;p;t;value t;1b;td]; + delete from t; + if[gc;.z.m.dbw.gc[]]]} + +// apply the sorting and attributes at the end of the replay, from tablename!(list of paths) +applysortandattr:{[pathlist] + {.z.m.dbw.sort . x} each flip (key;value) @\: distinct each pathlist + }; + +// table names in count order, smallest first +tabsincountorder:{x iasc count each value each x} + +// check if the count has been exceeded, and save down if it has +currentcount:0 +totalcount:0 +checkcount:{[h;p;counter;td] + currentcount+::counter; + if[.replay.currentcount >= .replay.messagechunks; + $[.replay.trackonly; + [.replay.totalcount +: .replay.currentcount; + .z.m.log[`info][`replay;"replayed a chunk of ",(string .replay.messagechunks)," messages. Total message count so far is ",string .replay.totalcount]]; + [.z.m.log[`info][`replay;"number of messages to replay at once (",(string .replay.messagechunks),") has been exceeded. Saving down"]; + savetab[td;h;p] each tabsincountorder[.replay.tablestoreplay]; + .z.m.log[`info][`replay;"save complete- replaying next chunk of data"]]]; + .replay.currentcount:0]} + +// function used to finish off the replay +finishreplay:{[h;p;td] + // save down any tables which haven't been saved + savetab[td;h;p] each tabsincountorder[.replay.tablestoreplay]; + // invoke any user defined post replay function + .save.postreplay[h;p]; + } + +// takes in log file directories made with segmented tickerplant +expandstplogs:{[logdirectories] // always a list + {` sv'raze x,/:'key each x}$[`~tplogdir;{enlist first x};]hsym logdirectories + }; + +replaylog:{[logfile] + // set the upd function to be the initialupd function + .replay.msgcount:.replay.currentcount:.replay.totalcount:0; + // check if logfile is corrupt + if[checklogfiles; logfile: .z.m.tplog.check[logfile;lastmessage]]; + $[firstmessage>0; + [.z.m.log[`info][`replay;"skipping first ",(string firstmessage)," messages"]; + @[`.;`upd;:;.replay.initialupd]]; + @[`.;`upd;:;.replay.realupd]]; + .replay.tablecounts:.replay.errorcounts:()!(); + + // If not running in segmented mode, reset replay date and clean HDB directory on each loop + .replay.zipped:$[logfile like "*.gz";1b;0b]; + if[not .replay.segmentedmode; + // Pull out date from TP log file name - *YYYY.MM.DD (+ .gz if zipped) + .replay.replaydate:"D"$$[.replay.zipped;-3_-13#;-10#] string logfile; + if[.replay.clean;.replay.cleanhdb .replay.replaydate] + ]; + + if[lastmessage ",fifo," &"; + @[system;fifostr;{.z.m.log[`error][`replay;"Failed to read log into named pipe"]}]; + fifo + }; + +// upd functions down here +realupd:{[f;t;x] + // increment the tablecounts + tablecounts[t]+::count first x; + // run the supplied function in the error trap + .[f;(t;x);{[t;x;e] errorcounts[t]+::count first x}[t;x]]; + }[.replay.upd] + +initialupd:{[t;x] + // spin through the first X messages + $[msgcount < (firstmessage - 1); + msgcount+::1; + // Once we reach the correct message, reset the upd function + @[`.;`upd;:;.replay.realupd]] + } + +// extract user defined row counts +mergemaxrows:{[tabname] mergenumrows^mergenumtab[tabname]}; + +// post replay function for merge replay, invoked after all the tables have been written down for a given log file +postreplaymerge:{[td;p;h] + .os.md[.os.pth[string .Q.par[td;p;`]]]; // ensures directory exists before removed + mergelimits:(tabsincountorder[.replay.tablestoreplay],())!$[.merge.mergebybytelimit;(count tabsincountorder[.replay.tablestoreplay])#mergenumbytes;({[x] mergenumrows^mergemaxrows[x]}tabsincountorder[.replay.tablestoreplay])],(); + // merge the tables from each partition in the tempdir together + merge[td;p;;mergelimits;h] each tabsincountorder[.replay.tablestoreplay]; + .os.deldir .os.pth[string .Q.par[td;p;`]]; // delete the contents of tempdir after merge completion + } + +// function to upsert to specified directory +upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] + dirpar:.Q.par[dir;pt;`$string first expt]; + directory:` sv dirpar,tablename,`; + // make directories for tables if they don't exist + if[count tabpar:tabsincountorder[.replay.tablestoreplay] except key dirpar; + .z.m.log[`info][`dir;"creating directories under ",1_string dirpar]; + tabpar:tabpar except `heartbeat`logmsg; + .[{[d;h;t](` sv d,t,`) set .Q.en[h;0#value t]};] each dirpar,'h,'tabpar]; + .z.m.log[`info][`save;"saving ",(string tablename)," data to partition ",string directory]; + .[ + upsert; + (directory;r:update `sym!sym from ?[tabdata;{(x;y;(),z)}[in;;]'[expttype;expt];0b;()]); + {[e] .z.m.log[`error][`savetablesbypart;"Failed to save table to disk : ",e];'e}]; + /-key in partsizes are directory to partition, need to drop training slash in directory key + .z.m.merge.trackpartition[first ` vs directory;count r;-22!r]; + }; + +savetablesbypart:{[dir;pt;tablename;h] + arows: count value tablename; + .z.m.log[`info][`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; + // get additional partition(s) defined by parted attribute in sort.csv + extrapartitiontype:.merge.getextrapartitiontype[tablename]; + + // check each partition type actually is a column in the selected table + .z.m.merge.checkpartitiontype[tablename;extrapartitiontype]; + // enumerate data to be upserted + enumdata:update (`. `sym)?sym from .Q.en[h;value tablename]; + // get list of distinct combiniations for partition directories + extrapartitions:(`. `sym)?.z.m.merge.getextrapartitions[tablename;extrapartitiontype]; + + .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; + // upsert data to specific partition directory + upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; + // empty the table + .z.m.log[`info][`delete;"deleting ",(string tablename)," data from in-memory table"]; + @[`.;tablename;0#]; + // run a garbage collection (if enabled) + if[gc;.z.m.dbw.gc[]]; + }; + + +merge:{[dir;pt;tablename;mergelimits;h] + // get int partitions + intpars:asc key ` sv dir,`$string pt; // list of enumerated partitions 0 1 2 3... + k:key each intdir:.Q.par[hsym dir;pt] each intpars; // list of table names + if[0=count raze k inter\: tablename; :()]; + // get list of partition directories containing specified table + partdirs:` sv' (intdir,'parts) where not ()~/:parts:k inter\: tablename; // get each of the directories that hold the table + // permanent storage destination, where data being merged too + dest:.Q.par[h;pt;tablename]; + // exit function if no subdirectories are found + if[0=count partdirs; :()]; + // if no table data set empty table. If data to merge, merge with correct merge function + $[0 = count partdirs inter exec ptdir from .z.m.merge.getpartsizes[]; + [.z.m.log[`warn][`merge;"no records for ", string[tablename]]; + (` sv dest,`) set @[.Q.en[h;value tablename];.merge.getextrapartitiontype[tablename];`p#]; + ]; + [$[mergemethod~`part; + [dest:` sv .Q.par[h;pt;tablename],`; // provides path to where to move data to + /-get chunks to partitions to merge in batch + partchunks:.z.m.merge.getpartchunks[partdirs;mergelimits[tablename]]; + .z.m.merge.mergebypart[.merge.getextrapartitiontype[tablename];dest]'[partchunks]; + ]; + mergemethod~`col; + [.z.m.merge.mergebycol[(tablename;value tablename);dest]'[partdirs]; + /- merging data by column does not create .d file - set it here after merge + .z.m.log[`info][`merge;"setting .d file"]; + (` sv dest,`.d) set cols value tablename; + ]; + .z.m.merge.mergehybrid[.merge.getextrapartitiontype[tablename];(tablename;value tablename);dest;partdirs;mergelimits[tablename]] + ] + ] + ]; + .z.m.log[`info][`merge;"deleting ", string[tablename], " from temp storage"]; + .os.deldir each .os.pth each string partdirs; + // set the attributes + .z.m.log[`info][`merge;"setting attributes"]; + @[dest;;`p#] each .merge.getextrapartitiontype[tablename]; + .z.m.log[`info][`merge;"merge complete"]; + // run a garbage collection (if enabled) + if[gc;.z.m.dbw.gc[]]; + }; + +// Return log file if it exists and not in segmented mode +getlogfile:{ + if[.replay.segmentedmode;.z.m.log[`error][`getlogfile;m:"Segmented mode requires tplogdir."];'m]; + if[()~key hsym f:.replay.tplogfile;.z.m.log[`error][`getlogfile;m:"Specified tplogfile ",string[f]," does not exist"];'m]; + enlist hsym f + }; + +// Return contents of log directory if it exists +getlogdir:{ + if[()~key hsym d:.replay.tplogdir;.z.m.log[`error][`getlogdir;m:"Specified log directory ",string[d]," does not exist"];'m]; + if[d like "*.gz";.z.m.log[`error][`getlogdir;m:"Zipped log directories not supported."];'m]; + $[.replay.segmentedmode;.replay.getstplogs[d];.Q.dd[logdir;] each key logdir:hsym d] + }; + +// Use STP meta table and tplogdir to build log names +getstplogs:{[logdir] + // If trying to replay zipped files on Windows, error out + winzip:(.z.o like "w*") and z:`stpmeta.gz in key d:hsym logdir; + if[winzip;.z.m.log[`error][`replaylog;m:"Zipped log files cannot be directly replayed on Windows"];'m]; + + // If meta table is zipped, assume all other logs are zipped as well and build log names accordingly + if[z;system "gunzip ",1_string .Q.dd[d;`stpmeta.gz]]; + metatable:@[get;.Q.dd[d;`stpmeta];{.z.m.log[`error][`getstpmeta;m:"Log directory must contain valid STP meta table"];'m}]; + if[z;system "gzip ",1_string .Q.dd[d;`stpmeta]]; + names:exec distinct logname from metatable where any each tbls in .replay.tablestoreplay; + .Q.dd[d;] each $[z;.Q.dd[;`gz];::] each last each ` vs' names + }; + +// Set up log replay list and clean HDB if necessary, kick off replay +initandrun:{ + if[all not null .replay[`tplogfile`tplogdir];.z.m.log[`error][`getlogs;m:"Can't pass in log file and directory."];'m]; + + .z.m.log[`info][`initandrun;"Initialising replay settings."]; + .replay.tablestoreplay:$[`all~first .replay.tablelist;tables[];.replay.tablelist,()]; + .replay.logstoreplay:$[not null .replay.tplogfile;.replay.getlogfile[];.replay.getlogdir[]]; + if[not count r:.replay.logstoreplay;.z.m.log[`error][`initandrun;m:"No log files found"];'m]; + + // If in segmented mode, get replay date and clean HDB once + if[.replay.segmentedmode; + // Pull out the date from the STP log file name - *_YYYYMMDDhhmmss (+ .gz if zipped) + .replay.replaydate:first l:"D"$$[first[r] like "*.gz";-9_-17#;-6_-14#] each string r; + if[not 1=count distinct l;.z.m.log[`error][`replay;m:"Cannot replay logs from different dates in segmented mode!"];'m]; + if[.replay.clean;.replay.cleanhdb .replay.replaydate] + ]; + + + // Replay all logs and exit + .z.m.log[`info][`initandrun;"Replaying the following log(s): ",csv sv 1_'string .replay.logstoreplay]; + .replay.pathlist:()!(); + .replay.replaylog each .replay.logstoreplay; + if[sortafterreplay;applysortandattr[.replay.pathlist]]; + if[partandmerge;postreplaymerge[tempdir;.replay.replaydate;hdbdir]]; + .z.m.log[`info][`replay;"replay complete"]; + if[.replay.exitwhencomplete;exit 0]; + }; + +\d . diff --git a/di/torq/torq.md b/di/torq/torq.md index c85cbeed..353ea5eb 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -81,10 +81,12 @@ expects. ### Process-type dispatch -A small built-in registry maps proctype → module name: +A built-in registry maps proctype → module name, `` `x → `di.torq.proc.x `` for each of `hdb`, +`tickerplant`, `rdb`, `wdb`, `gateway`, `idb`, `segmentedtp`, `chainedtp`, `housekeeping`, `discovery` +and `tickerlogreplay`: ```q -builtin:(enlist`hdb)!enlist`di.torq.proc.hdb +builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay!`di.torq.proc.hdb`di.torq.proc.tickerplant ... ``` If `proctype` is in `builtin`, `startbuiltin` `use`-loads that module and calls its @@ -292,11 +294,6 @@ freshly-started process. tmux mode is for local development; production stays on - **Query logging (`[querylog]`) wraps `.z.*` by direct assignment.** If a phased event's `exec` is claimed after startup, logging for that event silently drops to zero with no error. See [Query logging](#query-logging-optional). -- The builtin registry has exactly one entry (`` `hdb ``) so far - every other - proctype in a real deployment would be custom, until more `di.*` process-type - modules exist. -- No `di.torq.depcheck`-style pre-flight dependency validation yet (next up per the - modularisation plan). - `autodetect`'s host-matching has no `-procfile` override and no FinSpace-specific host handling - deliberately out of scope, same scoping-down `di.torq.servers` applies to its own `process.csv` reading. diff --git a/di/torq/torq.q b/di/torq/torq.q index ddf205c7..728fe738 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -4,7 +4,7 @@ / same init[config;deps] calling convention. / built-in process type registry: proctype -> di.* module name -builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery +builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery`di.torq.proc.tickerlogreplay reqenv:{[e] v:getenv e; diff --git a/di/tplog/VERSION b/di/tplog/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/tplog/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/tplog/init.q b/di/tplog/init.q index 3220f689..ff02774c 100644 --- a/di/tplog/init.q +++ b/di/tplog/init.q @@ -68,5 +68,7 @@ repairover:{[logfile;goodlogh;d] :@[d;`start`size;:;(ns;chunk)]; }; -export:([check;repair]) +version:first read0`:::VERSION + +export:([check;repair;version]) diff --git a/di/tplog/tplog.md b/di/tplog/tplog.md index 25542e07..c96b4f52 100644 --- a/di/tplog/tplog.md +++ b/di/tplog/tplog.md @@ -205,6 +205,6 @@ test_repair_garbage_at_end[] The module exports: ```q -export:([check;repair]) +export:([check;repair;version]) ``` From 24afb7172f86b35bc448a0e4b08b1cd8736b9f78 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 2 Oct 2026 12:09:11 +0100 Subject: [PATCH 22/42] One subscription path: rdb, wdb and chainedtp subscribe through .sub TorQ's .sub.subscribe becomes the one way to subscribe: it handles every TorQ tickerplant type by tptype and is the only path with auto-resubscribe. Subscribers take TorQ's end-of-day entry points, .u.end[d] (classic tickerplant, chainedtp) and endofday[d;data] plus endofperiod (segmented tickerplant). - di.pubsub 0.4.0: callendofday sends (`.u.end;d). - di.torq.proc.tickerplant 0.2.0: TorQ's classic surface (u.q/tickerplant.q), read by .sub.subscribe: .u.w (table keys; the registry stays in di.pubsub), .u.i (replaces .z.m.msgcount), .u.icounts, .u.L, .u.d. .u.sub returns (table;schema), one pair per table for `, and flushes first in batched mode. Needs di.pubsub 0.4.0. - di.torq.proc.chainedtp 0.3.0: back to TorQ's text: .ctp.subscribe on .sub.getsubscriptionhandles/.sub.subscribe, root subdetails restored (chainedtp.q:10-14), .u.end sends (`.u.end;d) (chainedtp.q:188); the root endofday bridge is removed. .u.subdetails stays until the old path is retired. - di.torq.proc.rdb 0.4.0 / di.torq.proc.wdb 0.3.0, targeted lines only: 1. subscribe: .sub.subscribe[...;first .sub.getsubscriptionhandles[tpt;`;()!()]] (TorQ rdb.q:163-169) replaces gethandlebytype + di subscribe; sd`date -> sd`d. 2. set[`.u.end;endofday] replaces @[`.;`.u.end;:;endofday], which made a root key named .u.end. 3. root endofday:{[d;x] endofday d} feeds the existing one-argument logic. 4. root endofperiod: TorQ's log stub (rdb/endofperiod.q:2, wdb/writedown.q:52). Minimums: di.subscriptions 0.2.0, di.torq.servers 0.5.0. No new mock-init suite for rdb/wdb; the end-to-end run below is their check. Verified end to end with real processes (a scratch copy of TorqX-POC): tickerplant -> wdb and tickerplant -> chainedtp -> rdb subscribe via .sub, data and end of day flow; segmentedtp -> rdb (endofperiod logged, two-argument endofday saved the partition); with autoreconnect on, killing and restarting the tickerplant and chainedtp resubscribes wdb and rdb and new trades arrive. pubsub 121/121, tickerplant 39/39, chainedtp 67/67, subscriptions 45/45, segmentedtp 66/66, tickerlogreplay 89/89, di.torq 72/72, rdb 4/4, wdb 4/4. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/VERSION | 2 +- di/pubsub/pubsub.md | 2 +- di/pubsub/pubsub.q | 4 ++-- di/torq/proc/chainedtp/VERSION | 2 +- di/torq/proc/chainedtp/chainedtp.md | 26 ++++++++++++------------ di/torq/proc/chainedtp/chainedtp.q | 27 ++++++++++++++++--------- di/torq/proc/chainedtp/test.csv | 16 ++++++++------- di/torq/proc/chainedtp/test.q | 10 +++++---- di/torq/proc/rdb/VERSION | 2 +- di/torq/proc/rdb/deps.toml | 4 ++-- di/torq/proc/rdb/rdb.md | 10 +++------ di/torq/proc/rdb/rdb.q | 15 +++++++------- di/torq/proc/tickerplant/VERSION | 2 +- di/torq/proc/tickerplant/deps.toml | 2 +- di/torq/proc/tickerplant/test.csv | 6 ++++++ di/torq/proc/tickerplant/tickerplant.q | 28 +++++++++++++++++++------- di/torq/proc/wdb/VERSION | 2 +- di/torq/proc/wdb/deps.toml | 4 ++-- di/torq/proc/wdb/wdb.md | 4 ++-- di/torq/proc/wdb/wdb.q | 20 +++++++++--------- 20 files changed, 108 insertions(+), 80 deletions(-) diff --git a/di/pubsub/VERSION b/di/pubsub/VERSION index 0d91a54c..1d0ba9ea 100644 --- a/di/pubsub/VERSION +++ b/di/pubsub/VERSION @@ -1 +1 @@ -0.3.0 +0.4.0 diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 2ed33ec5..018b67da 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -49,7 +49,7 @@ publish data with/without filters. The function takes two arguments: t and x, wh | Function | Description | |---------------------------|------------------------------------------------------------------------------| | `pubsub.setsubtables` | Set a specified list of tables that are available for subscription. | -| `pubsub.callendofday` | Broadcast an end-of-day event to all subscribers (requires `endofday`). | +| `pubsub.callendofday` | Broadcast end of day to all subscribers as `.u.end[d]`. | | `pubsub.callendofperiod` | Broadcast an end-of-period event to all subscribers (requires `endofperiod`).| | `pubsub.closesub` | Remove handle upon connection close. Not bound to `.z.pc` by the module - the consumer binds it (see Notes). | | `pubsub.subclear` | Publish tables and clear up the contents. | diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 99513a7a..de3af60a 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -74,8 +74,8 @@ closesub:{[h] delete from .z.M.reqfilteredtbl where handle=h; }; -/ broadcast to all subscribers upon end of day, client needs to define endofday function -callendofday:{[d](neg getallhandles[])@\:(`endofday;d)}; +/ broadcast end of day to all subscribers as .u.end[d] +callendofday:{[d](neg getallhandles[])@\:(`.u.end;d)}; / broadcast to all subscribers upon end of period, client needs to define endofperiod function callendofperiod:{(neg getallhandles[])@\:(`endofperiod;x)}; diff --git a/di/torq/proc/chainedtp/VERSION b/di/torq/proc/chainedtp/VERSION index 0c62199f..0d91a54c 100644 --- a/di/torq/proc/chainedtp/VERSION +++ b/di/torq/proc/chainedtp/VERSION @@ -1 +1 @@ -0.2.1 +0.3.0 diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index 8902f215..1db368c9 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -1,8 +1,8 @@ # di.torq.proc.chainedtp -A chained tickerplant. It subscribes to an upstream tickerplant through `di.subscriptions`, -optionally writes what it receives to a log of its own, and republishes to its own subscribers, tick -by tick or in batches. +A chained tickerplant. It subscribes to an upstream tickerplant through `.sub`, optionally writes +what it receives to a log of its own, and republishes to its own subscribers, tick by tick or in +batches. ## Surface @@ -10,9 +10,9 @@ by tick or in batches. |---|---| | `tptype` | `` `chained `` | | `tablelist[]` | the published tables (`.stpps.t`) | +| `subdetails[tabs;instruments]` | subscribes the caller and returns `schemalist`, `logfilelist`, `rowcounts`, `date` | | `.u.subdetails[tabs;syms]` | root; subscribes the caller and returns `tables`, `schemas`, `logfile`, `rowcount`, `date` | -| `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`endofday;d) `` to subscribers | -| `endofday[d]` | root; calls `.u.end d` (the upstream's end-of-day message) | +| `.u.end[d]` | publishes and clears the batch, rolls to `d+1`, sends `` (`.u.end;d) `` to subscribers | | `upd` | set at root to `.ctp.upd` if no `upd` exists | | `.ctp.*` | settings, `subscribe`, `writetolog`, `tickpub`, `batchpub`, `publishalltables`, `cleartables`, `openlog`, `clearlog`, `refreshtp`, `createlogfilename`, `notpconnected`, `sub` | | `.u.i`/`.u.j`/`.u.icounts`/`.u.jcounts`/`.u.L`/`.u.l`/`.u.d` | publish and log counts, log file and handle, date | @@ -24,7 +24,7 @@ by tick or in batches. | Key | Default | |---|---| | `tickerplantname` | `` `tickerplant1 `` — procname(s) of the upstream | -| `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer | +| `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer. | | `tpconnsleep` / `tpcheckcycles` | `10` / `0W` — seconds between, and number of, upstream checks | | `createlogfile` / `logdir` / `clearlogonsubscription` | `0b` / `` `:tplogs `` / `0b` — log file `/_` | | `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms | @@ -40,8 +40,7 @@ Requires `log`, `timer` and `handlers`. It initialises `di.pubsub` (with the log 2. sets `.ctp.upd` from `createlogfile`/`pubinterval`, and root `upd` if absent; 3. `.ps.initialise[]`; 4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; -5. `.ctp.subscribe[]`: finds the upstream handle, `refreshtp`, subscribes through `di.subscriptions`, takes - `.u.d` from the reply; +5. `.ctp.subscribe[]`; 6. builds `.ctp.tableschemas`; 7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). @@ -51,14 +50,15 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th - The upstream is found by procname through `di.torq.servers` (with the default settings, through discovery). With `tpcheckcycles` `0W` it waits for it indefinitely. -- End of day follows the rdb/wdb convention: `endofday[d]` in, `` (`endofday;d) `` out. +- An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. +- `.u.icounts` values are one-item lists after an all-syms subscribe. - A corrupt own log is reported and opened anyway. - `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. ## Downstream subscribers -`.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub`, the protocol `di.subscriptions` -subscribers (di rdb/wdb) use. With `createlogfile` on, `logfile` is `.u.L` and `rowcount` `.u.i`, so +`subdetails` serves `.sub` subscribers. `.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub` for +`di.subscriptions` `subscribe`. With `createlogfile` on, `logfile` is `.u.L` and `rowcount` `.u.i`, so subscribers replay chainedtp's own log; otherwise `` ` `` and 0. Plain `.u.sub` subscribers are served by `di.pubsub`. @@ -69,7 +69,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.chainedtp ``` -`test.q`/`test.csv` run a real upstream (di tickerplant surface, found through `di.torq.servers`) and +`test.q`/`test.csv` run a real upstream (segmented tickerplant surface, found through `di.torq.servers`) and real `.u.sub` and `di.subscriptions` subscribers: subscribe and schema, tick-by-tick delivery, -`.u.subdetails`, `tablelist`, end of day, the own log, batch publish, `clearlogonsubscription`, a +`subdetails`, `.u.subdetails`, `tablelist`, `.u.end`, the own log, batch publish, `clearlogonsubscription`, a corrupt log, and a subscriber replaying the own log. diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index fce9f4fb..47c8d9e7 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -29,6 +29,11 @@ tptype:`chained; tablelist:{.stpps.t} +subdetails:{[tabs;instruments] + r:.ctp.sub[tabs;instruments]; + `schemalist`logfilelist`rowcounts`date!r@/:(`schema;$[r[`logfile]~();();enlist`i`logfile];`icounts;`d) + } + .u.subdetails:{[tabs;syms] r:.ctp.sub[tabs;syms]; s:r`schema; if[-11h=type first s;s:enlist s]; @@ -79,12 +84,17 @@ openlog:{[lgfile] subscribe:{[] s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; if[count s; - subproc:first s; - .ctp.tph:subproc`w; - refreshtp @[tph;".u.d";.z.D]; - .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; - r:(use`di.subscriptions)[`subscribe][tph;subscribeto;subscribesyms;replay]; - .u.d::r`date]; + subproc:first s; + .ctp.tph:subproc`w; + refreshtp @[tph;".u.d";.z.D]; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; + if[`d in key r;.u.d::r[`d]]; + if[(`icounts in key r) & (not createlogfile); + subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); + .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; + ] + ]; } writetolog:{[t;x] @@ -152,10 +162,7 @@ end:{[d] .z.m.log[`info][`end;"end of day invoked"]; .ctp.publishalltables[]; .ctp.refreshtp[d+1]; - (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`endofday;d) + (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`.u.end;d) } \d . - -endofday:{[d] .u.end d} - diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 930ec5ac..e13a60a0 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -15,16 +15,14 @@ comment,,,,,,,init - connect and subscribe run,0,0,q,ctp.init[cfg[];deps[]],1,,init true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root -true,0,0,q,.u.d~D,1,,date taken from the .u.subdetails reply -true,0,0,q,"1=count (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed through di.subscriptions +true,0,0,q,.u.d~D,1,,date taken from the upstream +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) true,0,0,q,`trade in .stpps.t,1,,trade is published -true,0,0,q,".ctp.tph~first exec handle from (use`di.subscriptions)[`getsubscriptions][]",1,,subscription is on the upstream handle -true,0,0,q,"`trade in first exec tabs from (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed to trade comment,,,,,,,tick by tick run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstream peer @@ -32,15 +30,17 @@ run,0,0,q,"r:dh""(.z.w)(`.u.sub;`trade;`)""",1,,downstream subscribes to trade true,0,0,q,`trade~first r,1,,.u.sub returns the table true,0,0,q,"dh in .stpps.subrequestall`trade",1,,downstream registered run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows -true,0,0,q,3=.u.icounts`trade,1,,icounts updated +true,0,0,q,(enlist 3)~.u.icounts`trade,1,,icounts updated (one-item list as the subscribe reshape leaves it) true,0,0,q,"(1;3)~dh""(count got;count last last got)""",1,,downstream received the 3 rows +true,0,0,q,"`schemalist`logfilelist`rowcounts`date~key dh""(.z.w)(`subdetails;`trade;`)""",1,,subdetails keys +true,0,0,q,"()~(dh""(.z.w)(`subdetails;`trade;`)"")`logfilelist",1,,no log file without createlogfile true,0,0,q,"`tables`schemas`logfile`rowcount`date~key dh""(.z.w)(`.u.subdetails;`trade;`)""",1,,.u.subdetails keys true,0,0,q,"(`;0)~(dh""(.z.w)(`.u.subdetails;`trade;`)"")`logfile`rowcount",1,,no log and no replay without createlogfile true,0,0,q,"`trade in dh""(.z.w)(`tablelist;`)""",1,,tablelist lists trade comment,,,,,,,end of day -run,0,0,q,endofday D,1,,end of day through root endofday -true,0,0,q,"(enlist D)~dh""ended""",1,,endofday passed to the downstream +run,0,0,q,.u.end D,1,,end of day +true,0,0,q,"(enlist D)~dh""ended""",1,,.u.end passed to the downstream true,0,0,q,.u.d=D+1,1,,date rolled true,0,0,q,0=count trade,1,,trade cleared @@ -58,6 +58,8 @@ run,0,0,q,.ctp.refreshtp D,1,,reopen the existing log true,0,0,q,1=.u.i,1,,existing messages counted run,0,0,q,".ctp.clearlogonsubscription:1b;.ctp.refreshtp D",1,,reopen with clearlogonsubscription true,0,0,q,0=.u.i,1,,log cleared +run,0,0,q,"r:subdetails[`trade;`]",1,,subdetails with a log +true,0,0,q,"(enlist(0;.u.L))~r`logfilelist",1,,logfilelist carries i and the log file run,0,0,q,"r:.u.subdetails[`trade;`]",1,,.u.subdetails with a log true,0,0,q,"(.u.L;.u.i)~r`logfile`rowcount",1,,logfile and rowcount are the own log and .u.i run,0,0,q,"bf:hsym`$FIXDIR,""/bad""; bf set (); lh:hopen bf; lh enlist(`upd;`trade;rows 1); hclose lh; bf 1: (read1 bf),0x0102030405",1,,write a log with one message and a bad tail diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 5557083a..4bd55aa4 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -1,4 +1,4 @@ -/ test helpers: recording mocks, a real upstream (di tickerplant surface) and real downstream subscribers +/ test helpers: recording mocks, a real upstream (segmented tickerplant surface) and real downstream subscribers logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()) mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}) @@ -15,14 +15,16 @@ isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.p0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.z.m.msgcount+:1]; + if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.u.i+:1]; + if[count .z.m.tplogdir;.u.icounts[t]+:count first x]; $[.z.m.publishmode=`batched; t insert x; (.z.m.ps`publish)[t;flip (cols value t)!$[0>type first x;enlist each x;x]] @@ -48,7 +49,13 @@ upd:{[t;x] / subscriber entry point (published at root as `.u.sub`). syms=` -> all data for the / table(s); a sym list -> a sym-filtered subscription. Delegates to di.pubsub, whose / .z.w-based registration sees the calling subscriber's handle. -sub:{[tabs;syms] (.z.m.ps`subscribe)[tabs;syms]} +sub:{[x;y] + if[x~`;:sub[;y] each .z.m.tables]; + if[not x in .z.m.tables;'x]; + / batched: flush first, so a replaying subscriber doesn't receive the buffer twice + if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + r:(.z.m.ps`subscribe)[x;y]; + (first r 0;first r 1)} / subscription-details call (published at root as `.u.subdetails`) for a replaying / subscriber - di.torq.proc.rdb via di.subscriptions. In ONE synchronous call it (a) registers the @@ -72,7 +79,7 @@ subdetails:{[tabs;syms] sub:(.z.m.ps`subscribe)[tabs;syms]; d:(.z.m.eod`getd)[]; lf:$[00;r:(.z.m.tp`roll)[.z.m.logh;.z.m.tplogdir;d];.z.m.logh:r 0;.z.m.msgcount:r 1]; - (.z.m.eod`setd)[d+1]; + if[.z.m.logh>0;r:(.z.m.tp`roll)[.z.m.logh;.z.m.tplogdir;d];.z.m.logh:r 0;.u.i:r 1;.u.L:(.z.m.tp`logname)[.z.m.tplogdir;d+1]]; + .u.icounts:(`symbol$())!0#0; + (.z.m.eod`setd)[.u.d:d+1]; (.z.m.eod`setnextroll)[(.z.m.eod`getroll)[.z.p]]; (.z.m.eod`setdailyadj)[(.z.m.eod`getdailyadjustment)[]]; .z.m.log[`info][`tickerplant;"end of day complete, rolled ",(string d)," -> ",string d+1]; @@ -149,7 +157,12 @@ init:{[config;deps] / tplog: prepared now; log opened after the root upd is published (replay needs it) .z.m.tp:use`di.tplogmgr; .z.m.logh:0; - .z.m.msgcount:0; + / classic tickerplant surface read by .sub.subscribe + .u.w:tabs!(count tabs)#(); + .u.i:0; + .u.icounts:(`symbol$())!0#0; + .u.L:`; + .u.d:(.z.m.eod`getd)[]; / publish the IPC surface at real root names (use mangles module code into a private / namespace, so a remote/replayed `upd`/`.u.sub` must resolve at root). Done BEFORE @@ -165,7 +178,8 @@ init:{[config;deps] system "mkdir -p ",.z.m.tplogdir; r:(.z.m.tp`open)[.z.m.tplogdir;(.z.m.eod`getd)[]]; .z.m.logh:r 0; - .z.m.msgcount:r 1; + .u.i:r 1; + .u.L:(.z.m.tp`logname)[.z.m.tplogdir;.u.d]; .z.m.log[`info][`tickerplant;"opened tp log, replayed ",(string r 1)," message(s)"]; ]; diff --git a/di/torq/proc/wdb/VERSION b/di/torq/proc/wdb/VERSION index 0ea3a944..0d91a54c 100644 --- a/di/torq/proc/wdb/VERSION +++ b/di/torq/proc/wdb/VERSION @@ -1 +1 @@ -0.2.0 +0.3.0 diff --git a/di/torq/proc/wdb/deps.toml b/di/torq/proc/wdb/deps.toml index cadf4f5f..485f7a5a 100644 --- a/di/torq/proc/wdb/deps.toml +++ b/di/torq/proc/wdb/deps.toml @@ -1,5 +1,5 @@ # Peer modules di.torq.proc.wdb `use`s (see di/torq/depcheck/depcheck.md for the manifest-graph mechanism). [dependencies] -"di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers) -"di.subscriptions" = "0.1.0" +"di.torq.servers" = "0.5.0" # requires the INJECTED-servers contract (deps`servers) +"di.subscriptions" = "0.2.0" "di.dbwrite" = "0.1.0" diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index b9236b15..5e4ca840 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -58,8 +58,8 @@ di.subscriptions defines the tables at root from what the TP returns. (`` .idb.intradayreload[] ``, async, no partition — the idb mounts the savedir root and finds the day itself) — an all-skipped tick (nothing over threshold) stays silent. This is unconditional on `reloadorder`; it only needs an idb to be connected. -- **End of day** (`endofday[date]`, published at root): the tickerplant - broadcasts `(`endofday;date)` at roll (the same trigger as di.torq.proc.rdb). di.torq.proc.wdb flushes what +- **End of day**: `.u.end[date]` (from a tickerplant or chainedtp) or root `endofday[date;data]` (from a + segmented tickerplant, which also calls the logging `endofperiod` stub). di.torq.proc.wdb flushes what remains, sorts each working partition (`di.dbwrite.sort` — driven by `sortcsv` or the time-asc default), **moves** each table dir into `hdbdir/date/` (skipping any that already exist, to never corrupt the hdb), then reloads downstream in `reloadorder`. The hdb and rdb are given the diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 78a13d32..abc7403c 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -175,8 +175,7 @@ doreload:{[pt] informgateway[`reloadend]; } -/ end of day: called by the tickerplant as endofday[pt] (di.pubsub's dated broadcast, same -/ trigger as di.torq.proc.rdb). Flush what remains, sort each working partition, move it into the hdb, then +/ end of day for a partition: .u.end[pt] (tickerplant, chainedtp) or endofday[pt;data] (segmented). Flush what remains, sort each working partition, move it into the hdb, then / reload downstream. Advance the partition for the new day. endofday:{[pt] .z.m.log[`info][`wdb;"end of day for partition ",string pt]; @@ -242,19 +241,20 @@ init:{[config;deps] tpt:first .z.m.tptypes; if[not (.z.m.svc`waitfortype)[tpt;timeout;500]; '"di.torq.proc.wdb: no ",(string tpt)," connection within ",(string timeout),"ms - cannot start wdb"]; - tph:(.z.m.svc`gethandlebytype)[tpt;`any]; .z.m.subs:use`di.subscriptions; (.z.m.subs`init)[config;deps]; - sd:(.z.m.subs`subscribe)[tph;subscribeto;subscribesyms;replaylog]; - if[not sd[`date]~.z.m.currentpartition; - .z.m.log[`warn][`wdb;"tp log date ",(string sd`date)," != partition ",(string .z.m.currentpartition),"; using log date (cross-date working-dir move is deferred - see wdb.md)"]; - .z.m.currentpartition:sd`date]; - .z.m.log[`info][`wdb;"subscribed; replayed ",(string sd`rowcount)," message(s), partition date ",string sd`date]; + sd:.sub.subscribe[subscribeto;subscribesyms;1b;replaylog;first .sub.getsubscriptionhandles[tpt;`;()!()]]; + if[not sd[`d]~.z.m.currentpartition; + .z.m.log[`warn][`wdb;"tp log date ",(string sd`d)," != partition ",(string .z.m.currentpartition),"; using log date (cross-date working-dir move is deferred - see wdb.md)"]; + .z.m.currentpartition:sd`d]; + .z.m.log[`info][`wdb;"subscribed, partition date ",string sd`d]; / swap to the live accumulate upd (the timer flushes over-threshold), publish EOD entries @[`.;`upd;:;updfn]; - @[`.;`endofday;:;endofday]; - @[`.;`.u.end;:;endofday]; + set[`.u.end;endofday]; + / segmented tickerplant entry points + @[`.;`endofday;:;{[d;x] endofday d}]; + @[`.;`endofperiod;:;{[currp;nextp;data] .z.m.log[`info][`endofperiod;"Received endofperiod. currentperiod, nextperiod and data are ",(string currp),", ", (string nextp),", ", .Q.s1 data]}]; / the idb reads these directly at startup, as legacy's setparametersfromwdb does. savedir and / hdbdir are fixed for the life of the process; currentpartition is republished whenever it / moves (see endofday), or the copy here goes stale from the first roll. From 4aa911de27e41e1c57e8793569035d7896cfeaa5 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 2 Oct 2026 12:09:28 +0100 Subject: [PATCH 23/42] di.torq: deferred init list; segmentedtp re-registers its tables after .ps.initialise Under di.torq a segmentedtp broke on its first timer tick: di.torq's .ps.initialise[] runs after the process module's init and registers every root table, currlog included; the defaultbatch timer's pubclear then reset currlog from a missing schemasnoattributes key (an empty copy of the first table), so the loghandles view failed and every update errored with 'handle. TorQ cannot hit this: segmentedtickerplant.q:90 queues its init with .proc.addinitlist, and torq.q runs the list (697) after .ps.initialise (671), so generateschemas always registers last. Confirmed against a real TorQ stp1 with FSP config: .stpps.t excludes currlog and currlog survives timer ticks. segmentedtickerplant.q is TorQ's only addinitlist user. - di.torq: .proc.initlist / .proc.addinitlist (torq.q:10-12), run after .ps.initialise and connections, then emptied (torq.q:693-697). Test rows: a queued function runs once; the list is emptied. - di.torq.proc.segmentedtp: queues generateschemas to run again under di.torq (guarded, so a direct start is unchanged). Ledger: one step re-run rather than TorQ's whole deferred init. Verified with segmentedtp started by torqx.sh: .stpps.t is the schema tables, currlog survives the timer, updates log, and a .sub rdb receives them. di.torq 74/74, segmentedtp 66/66. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/segmentedtp.md | 3 +++ di/torq/proc/segmentedtp/segmentedtp.q | 2 ++ di/torq/test.csv | 2 ++ di/torq/test.q | 3 +++ di/torq/torq.md | 3 +++ di/torq/torq.q | 5 +++++ 6 files changed, 18 insertions(+) diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 42bc2601..ea4353d1 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -64,6 +64,9 @@ Requires `log`, `timer` and `handlers`. It: 5. chained: initialises di.subscriptions, waits for the upstream and subscribes; otherwise loads `schemafile`; 6. strips attributes from the published tables and opens the logs. +Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs again after di.torq's +`.ps.initialise[]` and the published tables stay the schema tables. + ## Behaviour to know - End of period and end of day are checked on each update and each timer tick. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 64de8b0a..2c604830 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -41,6 +41,8 @@ init:{[config;deps] / chained: subscribe to the main STP; otherwise load the schema file $[.sctp.chainedtp;.sctp.init[];(`..loadschemas)[]]; (`..generateschemas)[]; + / again after di.torq's .ps.initialise, which registers every root table + if[`addinitlist in key `.proc;.proc.addinitlist(`generateschemas;`)]; .stplg.init[string .z.m.procname]; } diff --git a/di/torq/test.csv b/di/torq/test.csv index acabc0e7..c579cb54 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -40,6 +40,8 @@ true,0,0,q,TESTPROCNAME~r3`proctype,1,,identity resolved for the custom proctype true,0,0,q,`widget in key .k4unittestproc.capturedconfig,1,,config cascade reached the custom proctype's own settings file true,0,0,q,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed +true,0,0,q,1=.k4unittestproc.deferredcalled,1,,a function queued with .proc.addinitlist ran once after init +true,0,0,q,()~.proc.initlist,1,,the deferred init list is emptied run,0,0,q,r5:tq.init[TESTPROCNAME;`testinst;enlist[`norun]!enlist 1b],1,,re-init with the norun override set (this reloads the proctype file, resetting runcalled to 0) true,0,0,q,0=.k4unittestproc.runcalled,1,,-norun skipped the hook - count stayed at 0 instead of incrementing to 1 diff --git a/di/torq/test.q b/di/torq/test.q index 6403bde7..7cd47722 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -48,7 +48,10 @@ setupfixture:{[] writelines[TESTPROCFILE; ("\\d .",string TESTPROCNAME; "runcalled:0;"; + "deferredcalled:0;"; + "deferred:{[x] deferredcalled::deferredcalled+1};"; "init:{[config;deps]"; + " .proc.addinitlist(`.k4unittestproc.deferred;`);"; " capturedconfig::config;"; " captureddeps::deps;"; " deps[`log][`info][`",(string TESTPROCNAME),";\"custom proctype initialised\"];"; diff --git a/di/torq/torq.md b/di/torq/torq.md index 594f3f09..cd869a38 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -131,6 +131,9 @@ already uses for `code/processes/`. App code loads **after** the process module's `init` (so it can reference the module's tables and state) and **before** the `.run` hook (so an app file may define/override `` ..run ``). +After `.ps.initialise[]` and connections, `init` runs any functions a process queued with +`.proc.addinitlist[(func;arg)]` (`.proc.initlist`), then empties the list. + ### The `.run` post-init hook After starting the process type and loading app code, `init` calls `runhook[proctype;overrides]`: diff --git a/di/torq/torq.q b/di/torq/torq.q index 6547ce1e..04b3ea98 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -300,6 +300,9 @@ init:{[proctype;procname;overrides] / the rolled files too, matching torq.q's own ordering. lr:use`di.torq.logroll; (lr`init)[config;deps]; + / init functions a process defers until pubsub and connections are initialised + set[`.proc.initlist;()]; + set[`.proc.addinitlist;{[x] .proc.initlist,:enlist x}]; $[proctype in key builtin; startbuiltin[proctype;config;deps]; startcustom[proctype;config;deps] @@ -312,6 +315,8 @@ init:{[proctype;procname;overrides] if[@[value;`.ps.loaded;0b];.ps.initialise[]]; / initialise connections if[@[value;`.servers.STARTUP;0b];.servers.startup config]; + / run deferred init functions + if[count .proc.initlist;value each .proc.initlist;.proc.initlist:()]; / .z.* wrappers: clients, querylog, zpsignore last initclients[config;deps]; / optional query logging - a no-op unless [querylog] enabled=true. LAST of everything that binds .z.*, because From e5c175b337f69479580d56b4f8c709b59b2fb281 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Fri, 2 Oct 2026 16:09:35 +0100 Subject: [PATCH 24/42] di.torq: segmentedchainedtp proctype; torqx.sh honours startwithall - builtin `segmentedchainedtp -> di.torq.proc.segmentedtp: TorQ runs the chained segmented tickerplant as its own proctype (segmentedchainedtickerplant, -parentproctype segmentedtickerplant) so subscribers select it by type; di.torq has no parentproctype tier, so it is a second builtin key for the same module. - settings/segmentedchainedtp.q from TorQ config/settings/segmentedchainedtickerplant.q: createlogs 0b; sctp section (chainedtp 1b, loggingmode none, tickerplantname stp1, subscribeto/subscribesyms `, replay 0b, schema 1b); connections segmentedtp; the clients/zpsignore lines of segmentedtp.q. .proc/.timer/.subcut switches not ported. - torqx.sh: TorQ torq.sh's optional startwithall column (torq.sh:172-173); a bare start / start all skips rows with 0, a row can still be started by name. Files without the column behave as before; di.torq's ("SISS") process.csv read ignores it. - torq.md notes; test row: the builtin map resolves segmentedchainedtp. Verified in TorqX-POC (stp1 -> wdb1, stp1 -> sctp1 -> rdb1). di.torq 75/75, segmentedtp 66/66. Co-Authored-By: Claude Opus 5.5 --- di/torq/bin/torqx.sh | 13 +++++++++++-- di/torq/settings/segmentedchainedtp.q | 8 ++++++++ di/torq/test.csv | 1 + di/torq/torq.md | 8 +++++--- di/torq/torq.q | 2 +- 5 files changed, 26 insertions(+), 6 deletions(-) create mode 100644 di/torq/settings/segmentedchainedtp.q diff --git a/di/torq/bin/torqx.sh b/di/torq/bin/torqx.sh index 66574928..f93ce6d2 100755 --- a/di/torq/bin/torqx.sh +++ b/di/torq/bin/torqx.sh @@ -56,6 +56,11 @@ allprocnames() { awk -F, 'NR>1{print $4}' "$CSVPATH" } +startwithall() { + # $1 = procname -> false if its optional startwithall column is 0 + [ "$(getfield "$(findprocno "$1")" startwithall)" != "0" ] +} + findproc() { # $1 = proctype, $2 = procname -> prints matching pid(s), if any. # The token after -procname must be a SPACE or END-OF-LINE, not just a space: a @@ -274,7 +279,10 @@ foreachtarget() { # $1 = fn, $2 = target ("" or "all" means every row), remaining args passed through local fn="$1"; local target="$2"; shift 2 if [ -z "$target" ] || [ "$target" = "all" ]; then - for p in $(allprocnames); do "$fn" "$p" "$@"; done + for p in $(allprocnames); do + [ "$fn" = start_one ] && ! startwithall "$p" && continue + "$fn" "$p" "$@" + done else "$fn" "$target" "$@" fi @@ -283,7 +291,8 @@ foreachtarget() { usage() { cat >&2 < di.* module name -builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery`di.torq.proc.tickerlogreplay +builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay`segmentedchainedtp!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.discovery`di.torq.proc.tickerlogreplay`di.torq.proc.segmentedtp reqenv:{[e] v:getenv e; From e218a64014b095f913898c6a4f9e75771bbc5250 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 7 Oct 2026 13:57:53 +0100 Subject: [PATCH 25/42] di.torq.proc.segmentedtp: initialise di.subscriptions in every mode A non-chained segmentedtp failed di.torq's post-load depcheck on every start ("di.subscriptions requires minimum version 0.2.0, not found"): deps.toml declares di.subscriptions, but only .sctp.init (chained) loaded it. The raise at the end of di.torq.init skipped runhook and left torqx_init.q's result unset (INITFAILED); the process otherwise ran. TorQ loads common/subscriptions.q in every process, the STP included, registering .sub.pc on .z.pc and the checksubscriptions timer at load (subscriptions.q:168-172). So init now calls di.subscriptions' init unconditionally, moved from .sctp.init. Loading without init is not enough: di.subscriptions' own manifest declares di.tplogmgr, which only its init loads. .z.m.deps (read only by the moved line) dropped; segmentedtp.md init steps updated. Verified: segmentedtp 66/66; qlint findings unchanged on both files; scratch stack (clone + these files) cold start, sctp1 restart, and stp1 -> sctp1 restart all depcheck-clean with resubscribe and data flow; live TorqX-POC stp1 now sets result. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/sctp.q | 1 - di/torq/proc/segmentedtp/segmentedtp.md | 4 ++-- di/torq/proc/segmentedtp/segmentedtp.q | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/di/torq/proc/segmentedtp/sctp.q b/di/torq/proc/segmentedtp/sctp.q index 4d395822..68d5802f 100644 --- a/di/torq/proc/segmentedtp/sctp.q +++ b/di/torq/proc/segmentedtp/sctp.q @@ -28,7 +28,6 @@ subscribe:{[] / initialise chained STP init:{ - (use`di.subscriptions)[`init][.z.m.params;.z.m.deps]; `endofperiod set {[x;y;z] .stplg.endofperiod[x;y;z]}; `endofday set {[x;y] .stplg.endofday[x;y]}; .servers.startupdepnamecycles[.sctp.tickerplantname;.sctp.tpconnsleep;.sctp.tpcheckcycles]; diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index ea4353d1..8bcc51fd 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -54,14 +54,14 @@ Flat: `schemafile` (required unless chained), `createlogs` (`1b`). Requires `log`, `timer` and `handlers`. It: -1. initialises di.pubsub and di.eodtime, and registers `.stpps.closesub` on `.z.pc`; +1. initialises di.subscriptions, di.pubsub and di.eodtime, and registers `.stpps.closesub` on `.z.pc`; 2. applies the settings; `singular` and `tabular` set `multilogperiod` to `1D`; `custom` loads `customcsv`; `parent` makes `replaylog` ask the upstream; 3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush `memorybatch`, close the logs); 4. sets `.u.upd` from `batchmode`, wraps `.z.ts` (the existing handler, then the batch timer and the end checks), and sets `\t` to 1000 if it is off; -5. chained: initialises di.subscriptions, waits for the upstream and subscribes; otherwise loads `schemafile`; +5. chained: waits for the upstream and subscribes; otherwise loads `schemafile`; 6. strips attributes from the published tables and opens the logs. Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs again after di.torq's diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 2c604830..b182a736 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -8,7 +8,7 @@ init:{[config;deps] .z.m.procname:config`procname; .z.m.proctype:config`proctype; .z.m.params:config; - .z.m.deps:deps; + (use`di.subscriptions)[`init][config;deps]; (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; r:deps[`handlers]`register; r[`.z.pc;`;`stpps;0j;.stpps.closesub]; From 7e7cb980fa0e9260caf785e06612ac40184d365d Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 7 Oct 2026 19:04:04 +0100 Subject: [PATCH 26/42] Accept TOML-style settings in servers, chainedtp, segmentedtp and tickerlogreplay TOML has no symbol or timespan type, so settings these modules use as symbols, paths or timespans could only live in .q files. Each module now converts the string form straight after init loads its section: - di.torq.servers (0.5.0 -> 0.6.0): retry and discoveryretry from a timespan, a "0D00:00:10" string or a number of seconds. - di.torq.proc.chainedtp: pubinterval the same way; logdir from a path string. - di.torq.proc.segmentedtp: sctp loggingmode, tickerplantname, subscribeto and subscribesyms from strings (subscribesyms also a list of strings). - di.torq.proc.tickerlogreplay: replay schemafile, hdbdir and tplogdir from strings. The servers and chainedtp halves are c95ce2f from feature-torqx-poc-demo (its servers half was ported in f6788a9 and reverted in 55caea0 as out of scope then). TorqX-POC main already relies on them (4979217). The segmentedtp parent-mode test peer now runs on string settings. Suites: servers 56/56, chainedtp 69/69, segmentedtp 67/67, tickerlogreplay 92/92, di.torq 75/75. Verified on a scratch TorqX-POC stack with every affected setting in .toml. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.md | 4 ++-- di/torq/proc/chainedtp/chainedtp.q | 5 +++++ di/torq/proc/chainedtp/test.csv | 4 +++- di/torq/proc/segmentedtp/segmentedtp.md | 3 ++- di/torq/proc/segmentedtp/segmentedtp.q | 4 ++++ di/torq/proc/segmentedtp/test.csv | 1 + di/torq/proc/segmentedtp/test.q | 4 ++-- di/torq/proc/tickerlogreplay/test.csv | 3 +++ di/torq/proc/tickerlogreplay/tickerlogreplay.md | 2 ++ di/torq/proc/tickerlogreplay/tickerlogreplay.q | 4 ++++ di/torq/servers/VERSION | 3 +-- di/torq/servers/servers.md | 6 +++--- di/torq/servers/servers.q | 5 +++++ di/torq/servers/test.csv | 3 +++ 14 files changed, 40 insertions(+), 11 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index 1db368c9..5a9f1c79 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -24,9 +24,9 @@ batches. | Key | Default | |---|---| | `tickerplantname` | `` `tickerplant1 `` — procname(s) of the upstream | -| `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer. | +| `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer. Also a `"0D00:00:01"` string or seconds | | `tpconnsleep` / `tpcheckcycles` | `10` / `0W` — seconds between, and number of, upstream checks | -| `createlogfile` / `logdir` / `clearlogonsubscription` | `0b` / `` `:tplogs `` / `0b` — log file `/_` | +| `createlogfile` / `logdir` / `clearlogonsubscription` | `0b` / `` `:tplogs `` / `0b` — log file `/_`; `logdir` may be a path string | | `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms | | `replay` / `schema` | `0b` / `1b` | | `connections` / `startup` | `` `tickerplant `` / `1b` | diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 47c8d9e7..c9463713 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -1,5 +1,8 @@ / di.torq.proc.chainedtp - chained tickerplant +/ a timespan, a "0D00:00:01" string or a number of seconds (TOML has no timespan type) +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + init:{[config;deps] if[not `log in key deps;'"di.torq.proc.chainedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.chainedtp: timer dependency is required - see di.timer"]; @@ -10,6 +13,8 @@ init:{[config;deps] (deps[`handlers]`register)[`.z.pc;`;`stpps;0j;.stpps.closesub]; (use`di.subscriptions)[`init][config;deps]; {[config;k] if[k in key config;set[` sv `.ctp,k;config k]]}[config] each `tickerplantname`pubinterval`tpconnsleep`createlogfile`logdir`subscribeto`subscribesyms`replay`schema`clearlogonsubscription`tpcheckcycles; + .ctp.pubinterval:totimespan .ctp.pubinterval; + if[10h=type .ctp.logdir;.ctp.logdir:hsym`$.ctp.logdir]; if[0<>(`long$.ctp.pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[.ctp.tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .ctp.tickerplantname];exit 0]}]; .ctp.upd:$[.ctp.createlogfile; diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index e13a60a0..df1fec5e 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -12,7 +12,9 @@ fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1 fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe -run,0,0,q,ctp.init[cfg[];deps[]],1,,init +run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir!(""0D00:00:00"";""tplogs"");deps[]]",1,,init with toml-style pubinterval and logdir strings +true,0,0,q,0D~.ctp.pubinterval,1,,a pubinterval string becomes a timespan +true,0,0,q,`:tplogs~.ctp.logdir,1,,a logdir string becomes a file symbol true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root true,0,0,q,.u.d~D,1,,date taken from the upstream diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 8bcc51fd..643628d5 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -44,7 +44,8 @@ A `stplg` section, set onto `.stplg.`: A `sctp` section, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or `parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and -`subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). +`subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and +`subscribesyms` also take strings, so the section can live in a `.toml` file. An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index b182a736..825f6048 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -1,5 +1,8 @@ / di.torq.proc.segmentedtp - segmented tickerplant +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; + init:{[config;deps] if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; @@ -15,6 +18,7 @@ init:{[config;deps] .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `stplg`sctp; + @[`.sctp;`loggingmode`tickerplantname`subscribeto`subscribesyms;tosym]; if[`createlogs in key config;set[`createlogs;config`createlogs]]; / subscribers replay from the parent's logs if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index f1bd4090..15732569 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -65,6 +65,7 @@ true,0,0,q,"1 2~hs""(.stplg.updtab`trade)[1 2;3]""",1,,chained upd adds no time run,0,0,q,"hs"".z.ts .z.p""",1,,timer true,0,0,q,"(0;1;1)~hs""(count trade;.stplg.msgcount`trade;logcount:{-11!(-2;x)} currlog[`trade;`logname])""",1,,published and logged in create mode true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z.d),""/sctp1_trade2*""",1,,own log in create mode +true,0,0,q,"(`parent;`stp1;`)~hp"".sctp`loggingmode`tickerplantname`subscribeto""",1,,toml-style sctp strings become symbols true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,parent mode replays the upstream logs true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index 748c9212..ca3308e1 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -11,13 +11,13 @@ peer:{[p] hopen `$":localhost:",string p} alive:{[p] not isfree p} PORTS:`a`b`c`s`p!5#0N -/ a: defaultbatch, tabperiod; b: immediate, singular; c: memorybatch, tabular; s: chained, create; p: chained, parent +/ a: defaultbatch, tabperiod; b: immediate, singular; c: memorybatch, tabular; s: chained, create; p: chained, parent, TOML-style strings CFGS:`a`b`c`s`p!( "`procname`schemafile`stplg!(`stp1;FIXDIR,\"/schema.q\";enlist[`kdbtplog]!enlist`$FIXDIR,\"/a\")"; "`procname`schemafile`stplg!(`stp2;FIXDIR,\"/schema.q\";`kdbtplog`batchmode`multilog!(`$FIXDIR,\"/b\";`immediate;`singular))"; "`procname`schemafile`stplg!(`stp3;FIXDIR,\"/schema.q\";`kdbtplog`batchmode`multilog!(`$FIXDIR,\"/c\";`memorybatch;`tabular))"; "`procname`createlogs`autoreconnect`stplg`sctp!(`sctp1;0b;0b;enlist[`kdbtplog]!enlist`$FIXDIR,\"/s\";`chainedtp`loggingmode!(1b;`create))"; - "`procname`createlogs`autoreconnect`stplg`sctp!(`sctp2;0b;0b;enlist[`kdbtplog]!enlist`$FIXDIR,\"/p\";`chainedtp`loggingmode!(1b;`parent))") + "`procname`createlogs`autoreconnect`stplg`sctp!(`sctp2;0b;0b;enlist[`kdbtplog]!enlist`$FIXDIR,\"/p\";`chainedtp`loggingmode`tickerplantname`subscribeto!(1b;\"parent\";\"stp1\";\"\"))") setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index 1585e36c..8edfd101 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -86,6 +86,9 @@ true,0,0,q,0=replay sect seg "()!()",1,,replay a segmentedtp log directory true,0,0,q,(3;1)~(rows[SD;`trade];rows[SD;`quote]),1,,every table replayed into the logs' date true,0,0,q,`a`b`c~syms[SD;`trade],1,,sorted by sym run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay sect ""`schemafile`hdbdir`tplogdir!("",(-3!FIXDIR,""/schema.q""),"";"",(-3!FIXDIR,""/hdb""),"";"",(-3!STPDIR),"")""",1,,replay with toml-style string settings +true,0,0,q,(3;1)~(rows[SD;`trade];rows[SD;`quote]),1,,strings become the schema file and paths +run,0,0,q,clearhdb[],1,, true,0,0,q,0=replay sect seg "enlist[`tablelist]!enlist enlist`quote",1,,replay one table true,0,0,q,(0;1)~(rows[SD;`trade];rows[SD;`quote]),1,,only its logs are read from stpmeta true,0,0,q,"replayed ""stp1_quote""",1,,the quote log only diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index d2d80b79..23ece265 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -47,6 +47,8 @@ A `replay` section, set onto `.replay.`: | `mergenumrows` / `mergenumtab` / `mergenumbytes` | `10000000` / `` `quote`trade!10000 50000 `` / `500000000` | | `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | +`schemafile`, `hdbdir` and `tplogdir` also take strings, so the section can live in a `.toml` file. + A `merge` section (`mergebybytelimit`, `partlimit`) is set onto `.merge.` and passed to di.merge's `init`. ## init[config;deps] diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 2a3e8a2f..f3dc42f7 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -1,5 +1,8 @@ / di.torq.proc.tickerlogreplay - replay tickerplant log files into an hdb +/ a symbol or a string (TOML has no symbol type) +tosym:{[x] $[10h=abs type x;`$x;x]}; + / log the error and exit ex:{[id;message;code] .z.m.log[`error][id;message]; exit code} @@ -16,6 +19,7 @@ init:{[config;deps] .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `replay`merge; + @[`.replay;`schemafile`hdbdir`tplogdir;tosym]; .z.m.merge:use`di.merge; .z.m.merge.init (enlist[`log]!enlist deps`log),$[`merge in key config;config`merge;()!()]; / some variables must be set diff --git a/di/torq/servers/VERSION b/di/torq/servers/VERSION index 8ea2ddfc..a918a2aa 100644 --- a/di/torq/servers/VERSION +++ b/di/torq/servers/VERSION @@ -1,2 +1 @@ -0.5.0 - +0.6.0 diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 9400ddc3..0b33b6be 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -35,10 +35,10 @@ supplies the discovery process's values. | `discoveryregister` | `.servers.DISCOVERYREGISTER` | `1b` | | `connectionsfromdiscovery` | `.servers.CONNECTIONSFROMDISCOVERY` | `1b` | | `subscribetodiscovery` | `.servers.SUBSCRIBETODISCOVERY` | `1b` | -| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05` | +| `discoveryretry` | `.servers.DISCOVERYRETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | | `tracknontorqprocess` | `.servers.TRACKNONTORQPROCESS` | `0b` | | `hopentimeout` | `.servers.HOPENTIMEOUT` | `2000` | -| `retry` | `.servers.RETRY` | `0D00:05` | +| `retry` | `.servers.RETRY` | `0D00:05`; also a `"0D00:00:10"` string or seconds | | `retain` | `.servers.RETAIN` | `` `long$0D00:30 `` | | `autoclean` | `.servers.AUTOCLEAN` | `0b` | | `debug` | `.servers.DEBUG` | `1b` | @@ -153,7 +153,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (54 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (56 checks) spawn real q peers. They cover: - init validation, wiring and idempotency; - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index f14a8f00..bf4ef09a 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -32,6 +32,9 @@ raiseerror:{[ctx;msg] '"di.torq.servers: ",string[ctx],": ",msg; }; +/ a timespan, a "0D00:00:10" string or a number of seconds (TOML has no timespan type) +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + init:{[deps] / wire deps and config, publish root names, register .z.pc and retry timers once if[99h<>type deps; @@ -61,6 +64,8 @@ init:{[deps] @[value;`.servers.SERVERS;{set[`.servers.SERVERS;([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:())]}]; / config {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; + .servers.RETRY:totimespan .servers.RETRY; + .servers.DISCOVERYRETRY:totimespan .servers.DISCOVERYRETRY; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; / live-handle checks set[`.dotz.liveh;{x in key .z.W}]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index cff12a65..b38c30c7 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -58,6 +58,9 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names +comment,,,,,,,retry periods from toml +run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds +true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection From 050b7743efd959928541aa404f21cc0c092bde08 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 8 Oct 2026 00:10:08 +0100 Subject: [PATCH 27/42] Command-line overrides for section settings; tickerlogreplay takes -.replay. TorQ's tickerlogreplay is run with its settings on the command line (-.replay.tplogdir, -.replay.hdbdir, ...). Under di.torq those were silently skipped: di.torq.config's override layer only matched top-level settings, and tickerlogreplay's settings live in a replay section. - di.torq.config 0.1.0 -> 0.2.0: overrideconfig also takes a .section.key (or section.key) name for a key already in a dict-valued section, parsed by the same rules as a top-level setting. Top-level matching is unchanged. Internal helper settingpath; 4 test rows. - di/torq/settings/tickerlogreplay.q (new): a replay section declaring every basic-typed default, so each is overridable; a tickerlogreplay test checks it agrees with the module's defaults. - di.torq.proc.tickerlogreplay: string conversion covers every symbol setting (tplogfile, tablelist, partitiontype, sortcsv, tempdir, mergemethod as well), tablelist always a list, so a .toml replay section can carry them and a string override works. The usage text (-.replay.usage) is still not ported. An app replay section replaces the builtin one, so the app lists every key it wants overridable. Suites: tickerlogreplay 93/93, di.torq 75/75, di.torq.config new rows pass (run with private fixture paths: its /tmp/diconfigbuiltin is owned by another user here; the 8 kx.log rows fail the same on the previous commit, kx.log not installed). Scratch TorqX-POC: three replays driven only by -.replay.* switches, counts matching. Co-Authored-By: Claude Opus 5.5 --- di/torq/config/VERSION | 2 +- di/torq/config/config.md | 4 +-- di/torq/config/config.q | 25 +++++++++++++------ di/torq/config/test.csv | 5 ++++ di/torq/proc/tickerlogreplay/test.csv | 3 ++- .../proc/tickerlogreplay/tickerlogreplay.md | 5 +++- .../proc/tickerlogreplay/tickerlogreplay.q | 7 +++--- di/torq/settings/tickerlogreplay.q | 4 +++ 8 files changed, 40 insertions(+), 15 deletions(-) create mode 100644 di/torq/settings/tickerlogreplay.q diff --git a/di/torq/config/VERSION b/di/torq/config/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/torq/config/VERSION +++ b/di/torq/config/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/torq/config/config.md b/di/torq/config/config.md index 2b079ba1..cdee06af 100644 --- a/di/torq/config/config.md +++ b/di/torq/config/config.md @@ -103,11 +103,11 @@ first — di.torq.config does no wrapping. |---|---|---| | `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | -| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. Returns the **updated config dict**. Requires `init`. | +| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.replay.tplogdir x`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | | `getapimeta` | `getapimeta[]` | This module's API metadata — one `(name;public;descrip;params;return)` row per exported function, for `di.torq` to register with `di.api`. | -Internal helpers — `parsetier` (per-tier `.q`+`.toml` merge), `applyoverride`, +Internal helpers — `parsetier` (per-tier `.q`+`.toml` merge), `applyoverride`, `settingpath`, `parsefailed`, and `hexchars` — are deliberately not exported. ## Injectable dependencies diff --git a/di/torq/config/config.q b/di/torq/config/config.q index 9222f54b..89c7569b 100644 --- a/di/torq/config/config.q +++ b/di/torq/config/config.q @@ -153,16 +153,27 @@ overrideconfig:{[config;params] 'err; ]; ]; - defined:vars where vars in key config; - undefined:vars except defined; + paths:settingpath[config] each vars; + undefined:vars where 0=count each paths; if[count undefined; .z.m.logwarn[`overrideconfig;"skipping unknown setting(s): ",", " sv string undefined]; ]; - / fold each defined override into the config dict; a skipped/rejected one leaves it unchanged - :{[config;params;name] - res:applyoverride[name;config name;params name]; - $[res 0;@[config;name;:;res 1];config] - }[;params;]/[config;defined]; + / fold each override into the config dict at its path; a skipped/rejected one leaves it unchanged + w:where 0`: | `mergenumrows` / `mergenumtab` / `mergenumbytes` | `10000000` / `` `quote`trade!10000 50000 `` / `500000000` | | `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | -`schemafile`, `hdbdir` and `tplogdir` also take strings, so the section can live in a `.toml` file. +The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist`, `partitiontype`, `sortcsv`, +`tempdir`, `mergemethod`) also take strings, so the section can live in a `.toml` file. `di/torq/settings/tickerlogreplay.q` +declares every default, so any key can be given on the command line as `-.replay.`, as in TorQ; an app +`replay` section replaces it, so list there every key to override. A `merge` section (`mergebybytelimit`, `partlimit`) is set onto `.merge.` and passed to di.merge's `init`. diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index f3dc42f7..4fbe5ad5 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -1,7 +1,7 @@ / di.torq.proc.tickerlogreplay - replay tickerplant log files into an hdb -/ a symbol or a string (TOML has no symbol type) -tosym:{[x] $[10h=abs type x;`$x;x]}; +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; / log the error and exit ex:{[id;message;code] .z.m.log[`error][id;message]; exit code} @@ -19,7 +19,8 @@ init:{[config;deps] .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `replay`merge; - @[`.replay;`schemafile`hdbdir`tplogdir;tosym]; + @[`.replay;`schemafile`hdbdir`tplogdir`tplogfile`tablelist`partitiontype`sortcsv`tempdir`mergemethod;tosym]; + .replay.tablelist:(),.replay.tablelist; .z.m.merge:use`di.merge; .z.m.merge.init (enlist[`log]!enlist deps`log),$[`merge in key config;config`merge;()!()]; / some variables must be set diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q new file mode 100644 index 00000000..ace8fcf6 --- /dev/null +++ b/di/torq/settings/tickerlogreplay.q @@ -0,0 +1,4 @@ +/ tickerlogreplay settings +/ every basic-typed replay default, so each can be overridden from the command line (-.replay.); +/ must agree with the module's own defaults. An app replay section replaces this whole section +replay:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`tempdir`mergenumrows`mergenumbytes`mergemethod!(0;0W;0W;1b;1b;`;enlist`all;`;`;`;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`:tempmergedir;10000000;500000000;`part) From 937c217738a8dc4d6e69b75ff5c005b00855ef78 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 8 Oct 2026 11:48:15 +0100 Subject: [PATCH 28/42] di.torq.proc.tickerlogreplay: reject a message range in segmented mode The segmented-mode check called ex[id;message] with two of its three arguments, which only builds a projection: nothing was logged and init carried on, the trailing ;1 a dead statement. Segmented mode replays every log file with the same firstmessage/lastmessage, so a range such as -.replay.firstmessage 1000 silently skipped the first 1000 messages of every hourly segment. The exit code now goes inside the call, so init logs the reason and exits 1, like the checks around it. Deviation from TorQ: its code/processes/tickerlogreplay.q:94 has the same two-argument .err.ex call and never fires; the port copied it deliberately (feac8ab) and is now fixed instead. Tests: the row asserting no exit now expects exit 1; a lastmessage row and a logged-reason row added. tickerlogreplay 95/95; qlint unchanged; scratch run with -.replay.firstmessage 5 exits with the error, a default run still replays. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerlogreplay/test.csv | 4 +++- di/torq/proc/tickerlogreplay/tickerlogreplay.md | 4 ++-- di/torq/proc/tickerlogreplay/tickerlogreplay.q | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index 4ae12a9f..3ec570e8 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -95,7 +95,9 @@ true,0,0,q,(0;1)~(rows[SD;`trade];rows[SD;`quote]),1,,only its logs are read fro true,0,0,q,"replayed ""stp1_quote""",1,,the quote log only true,0,0,q,"not replayed ""stp1_trade""",1,, run,0,0,q,clearhdb[],1,, -true,0,0,q,0=replay sect seg "enlist[`firstmessage]!enlist 5",1,,the firstmessage check in segmented mode does not exit +true,0,0,q,1=replay sect seg "enlist[`firstmessage]!enlist 5",1,,a non-default firstmessage in segmented mode exits 1 +true,0,0,q,1=replay sect seg "enlist[`lastmessage]!enlist 5",1,,a non-default lastmessage in segmented mode exits 1 +true,0,0,q,"logged ""*firstmessage must be 0 and lastmessage must be 0W*""",1,,and says why true,0,0,q,"3=replay sect seg ""enlist[`tplogdir]!enlist "",hp""mixed""",1,,logs from two dates signal true,0,0,q,"logged ""*Cannot replay logs from different dates in segmented mode!*""",1,,and log why true,0,0,q,"3=replay sect seg ""enlist[`tplogfile]!enlist "",hp""tplog"",D",1,,a log file in segmented mode signals diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 06bb4f82..03c7fddd 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -61,7 +61,7 @@ Requires `log`. It: 1. initialises di.dbwrite and di.merge, and applies the settings; 2. exits on a bad setting: - code 1 for a null `schemafile`/`hdbdir`/log, an unknown `partitiontype`, `basicmode` with - `messagechunks`, or `partandmerge` into `hdbdir`; + `messagechunks`, a message range in segmented mode, or `partandmerge` into `hdbdir`; - code 2 for zero `messagechunks` or a schema file that fails to load; 3. loads the schema file at root; 4. wraps `.replay.realupd` to filter on `tablelist` (plain logs) and to save every `messagechunks` messages; @@ -75,7 +75,7 @@ Requires `log`. It: their `_YYYYMMDDhhmmss` suffix. Segmented logs from more than one date are refused. - With `checklogfiles` on a plain log, the repaired copy is named `.good`, so it has no date and its tables are saved at the HDB root. -- In segmented mode, a non-default `firstmessage` or `lastmessage` doesn't stop the replay. +- In segmented mode, a non-default `firstmessage` or `lastmessage` is rejected at init (exit 1). - `clean` deletes the whole date partition when `tablelist` is `all`, otherwise only the replayed tables. - A table with no rows is still saved empty when `emptytables` is on. - `partandmerge` turns `sortafterreplay` off and applies `p#` through the merge. diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 4fbe5ad5..6b4cfe2b 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -29,7 +29,7 @@ init:{[config;deps] ex[`replayinit; "if using basic mode, messagechunks must not be used (it should be set to 0W). basicmode will use .Q.hdpf to overwrite tables at the end of the replay";1]]; if[not .replay.partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; if[.replay.messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; - if[.replay.segmentedmode and ((0<>.replay.firstmessage) or 0W<>.replay.lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode"];1]; + if[.replay.segmentedmode and ((0<>.replay.firstmessage) or 0W<>.replay.lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode";1]]; .replay.trackonly:.replay.messagechunks < 0; if[.replay.trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; .replay.messagechunks:abs .replay.messagechunks; From bfc86db8bfdd9c77a0f7dabe27471ad02bda2957 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 13:21:16 +0100 Subject: [PATCH 29/42] segmentedtp, tickerlogreplay: no \d, no .os; .merge helpers move to di.merge segmentedtp and tickerlogreplay: - Remove every \d. Namespace members are written in full (.stplg, .sctp, .stpm, .replay, .save). Names that subscribers and the framework reach at root (upd, tptype, subdetails, tablelist, currlog, createlogs, setup, loadschemas, generateschemas) are published with @[`.;...]. loghandles stays a root view. - Remove the .os helpers. Call sites run mkdir -p / rm -r directly. di.merge 0.2.0: - Add getextrapartitiontype[sortconfig;tablename]. In TorQ it lives in code/common/merge.q and reads .sort.params; here the caller passes the sort config in, so di.merge still reads no sort config itself. - Add getmergebybytelimit[] and getpartlimit[]. tickerlogreplay calls these through .z.m.merge, no longer writes .merge.*, and requires di.merge 0.2.0. Settings: - settings/segmentedtp.q declares the stplg defaults (except kdbtplog, which comes from the environment) and the sctp defaults, so -.stplg. and -.sctp. overrides now apply. - settings/tickerlogreplay.q declares the merge section. - The module defaults stay as fallbacks. New test rows assert that each settings section agrees with the module. Tests: di.merge 238, segmentedtp 69, tickerlogreplay 95, all pass. Scratch stack run: stp1 -> sctp1 -> rdb1 with data flowing; -.stplg.multilog tabular takes effect; a segmented clean + partandmerge replay matches the logged counts, with p# on sym. Co-Authored-By: Claude Opus 5.5 --- di/merge/VERSION | 2 +- di/merge/init.q | 3 +- di/merge/merge.md | 15 +- di/merge/merge.q | 36 ++- di/merge/test.csv | 14 + di/torq/proc/segmentedtp/sctp.q | 38 ++- di/torq/proc/segmentedtp/segmentedtp.md | 6 +- di/torq/proc/segmentedtp/segmentedtp.q | 24 +- di/torq/proc/segmentedtp/stplog.q | 176 ++++++------ di/torq/proc/segmentedtp/stpmeta.q | 32 +-- di/torq/proc/segmentedtp/test.csv | 2 + di/torq/proc/tickerlogreplay/deps.toml | 2 +- di/torq/proc/tickerlogreplay/test.csv | 2 +- .../proc/tickerlogreplay/tickerlogreplay.md | 9 +- .../proc/tickerlogreplay/tickerlogreplay.q | 265 ++++++++---------- di/torq/settings/segmentedtp.q | 5 + di/torq/settings/tickerlogreplay.q | 3 + 17 files changed, 322 insertions(+), 312 deletions(-) diff --git a/di/merge/VERSION b/di/merge/VERSION index 6c6aa7cb..341cf11f 100644 --- a/di/merge/VERSION +++ b/di/merge/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 \ No newline at end of file diff --git a/di/merge/init.q b/di/merge/init.q index 89aaff43..6fb02598 100644 --- a/di/merge/init.q +++ b/di/merge/init.q @@ -18,4 +18,5 @@ if[0=count version;'"di.merge: VERSION file is empty"]; / public api - only the functions intended to be called externally are exported export:([init;checkpartitiontype;checkenumerabletype;getextrapartitions;getfirstcharpartitions; getpartchunks;mergebypart;mergebycol;mergehybrid;trackpartition;clearpartsizes; - getpartsizes;syncpartsizes;version;getapimeta]) + getpartsizes;syncpartsizes;getmergebybytelimit;getpartlimit;getextrapartitiontype; + version;getapimeta]) diff --git a/di/merge/merge.md b/di/merge/merge.md index 8ff328f6..2165b655 100644 --- a/di/merge/merge.md +++ b/di/merge/merge.md @@ -11,7 +11,7 @@ On-disk data-merging utilities for the write-down flow, extracted from TorQ's `c - Sync a partsizes table received from a peer process into local tracked state (`syncpartsizes`) - see "Cross-process partition-size sync" below - Re-sort a segment by its parted column(s) when the `p#` attribute cannot otherwise be applied, so the merged partition ends up correctly parted - Batch sizing bounded by both a data limit (rows or bytes, per `mergebybytelimit`) and a maximum partition count per batch (`partlimit`) -- Helpers to validate and enumerate a table's parted columns (`checkpartitiontype`, `checkenumerabletype`, `getextrapartitions`, `getfirstcharpartitions`) +- Helpers to validate and enumerate a table's parted columns (`checkpartitiontype`, `checkenumerabletype`, `getextrapartitions`, `getfirstcharpartitions`, `getextrapartitiontype`) - No hard module dependencies - logging is injected via `init`, and the parted column(s) a merge needs are passed in by the caller rather than read from sort config, so `di.merge` stays independent of `di.sort` --- @@ -24,7 +24,7 @@ On-disk data-merging utilities for the write-down flow, extracted from TorQ's `c **Hard dependency:** none - the only runtime dependency (`log`) is injected via `init`, so any module exporting the contracted signatures can be supplied. -The parted (`` `p# ``) column(s) for a table - `extrapartitiontype` in the function signatures below - are **passed in by the caller**. TorQ's original `merge.q` read these from the `.sort.params` global (populated from `sort.csv`); on extraction that coupling was removed so `di.merge` does not depend on `di.sort`. The caller (e.g. `di.wdb`) obtains the parted columns from its own sort configuration and passes them to `mergebypart` / `mergehybrid` / the check functions. +The parted (`` `p# ``) column(s) for a table - `extrapartitiontype` in the function signatures below - are **passed in by the caller**. TorQ's original `merge.q` read these from the `.sort.params` global (populated from `sort.csv`); on extraction that coupling was removed so `di.merge` does not depend on `di.sort`. The caller (e.g. `di.wdb`) obtains the parted columns from its own sort configuration and passes them to `mergebypart` / `mergehybrid` / the check functions. `getextrapartitiontype` looks them up in a sort config the caller passes in. **`tablename` must resolve as a real global/root table.** `checkpartitiontype`, `checkenumerabletype`, `getextrapartitions` and `getfirstcharpartitions` all take `tablename` and dereference it directly - `checkpartitiontype` via `cols get tablename`, the other three via `meta[tablename]` or a functional select (`` ?[tablename;...] ``). None of them accept an in-memory table value in place of a resolvable symbol; this matches legacy TorQ's own behaviour and is not a limitation introduced by this module. @@ -79,6 +79,9 @@ merge.trackpartition[`:tmp/2025.01.01/trade; count data; -22!data] ### `getpartsizes[]` Return the current tracked segment sizes (keyed on `ptdir`), e.g. to sync to sort-worker processes. +### `getmergebybytelimit[]` / `getpartlimit[]` +Return the `mergebybytelimit` and `partlimit` this module was initialised with. + ### `clearpartsizes[]` Drop all tracked segment sizes. Call once end-of-day merging is complete. @@ -118,6 +121,12 @@ Return the distinct combinations of the parted column values - one per partition ### `getfirstcharpartitions[tablename;extrapartitiontype]` Return the partition values grouped by the first character of the (single) parted column. +### `getextrapartitiontype[sortconfig;tablename]` +Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. Error-logs when neither is defined. +```q +merge.getextrapartitiontype[dbw.getconfig[]; `trade] +``` + ### `version` Module version string (from the `VERSION` file), for `di.depcheck` to check against dependants' minimum-version requirements. @@ -284,7 +293,7 @@ Mock loggers only check that a message was logged at the right level - they do n ## Notes -- Extracted from TorQ `code/common/merge.q`. The one behavioural change on extraction is the removal of the `.sort.params`/`sort.csv` lookup (`getextrapartitiontype`): the parted column(s) are now a parameter (`extrapartitiontype`) supplied by the caller, keeping the module standalone. All error/info messages that referenced `sort.csv` in the legacy source have been reworded accordingly. +- Extracted from TorQ `code/common/merge.q`. The one behavioural change on extraction is the removal of the `.sort.params`/`sort.csv` lookup (`getextrapartitiontype`): the parted column(s) are now a parameter (`extrapartitiontype`) supplied by the caller, and `getextrapartitiontype` takes the sort config as a parameter, keeping the module standalone. The other error/info messages that referenced `sort.csv` in the legacy source have been reworded accordingly. - `init` must be called before any other function - enforced by the `requireinit` guard on every other exported function, not just documented convention. - The `VERSION`-file read pattern (fail loud on missing/unreadable/empty, `trim` against trailing whitespace) follows `di.servers`, not `di.eodtime` (which has no `VERSION` handling at all). - The merge functions operate on on-disk paths (`get`/`set`/`upsert` against file symbols); they do not manage the segment or destination directory lifecycle - that remains the caller's responsibility. diff --git a/di/merge/merge.q b/di/merge/merge.q index adaf734e..298fcde0 100644 --- a/di/merge/merge.q +++ b/di/merge/merge.q @@ -5,8 +5,9 @@ / per partition by a row-count / byte-size limit / merging keeps memory flat - segments are read and upserted a batch at a time rather / than held in memory and written once at end-of-day -/ the parted (`p#) column(s) for a table are supplied by the caller as extrapartitiontype; -/ the module never reads sort config itself, so it stays independent of di.sort +/ the parted (`p#) column(s) for a table are supplied by the caller as extrapartitiontype, or +/ looked up by getextrapartitiontype in a sort config the caller passes in; the module never +/ reads sort config itself, so it stays independent of di.sort / config and the injected log dependency are passed to init in a single dictionary: config / keys (see merge.md) are optional with defaults; log is required and init errors / immediately if it is missing or does not provide info/error - see merge.md @@ -89,6 +90,17 @@ getpartsizes:{[] .z.m.partsizes }; +/ the configured mergebybytelimit and partlimit +getmergebybytelimit:{[] + requireinit[`getmergebybytelimit]; + .z.m.mergebybytelimit + }; + +getpartlimit:{[] + requireinit[`getpartlimit]; + .z.m.partlimit + }; + / upsert a partsizes-shaped table received from a peer process into local tracked state syncpartsizes:{[t] / t: a table shaped like getpartsizes[] (ptdir/rowcount/bytes), typically received over IPC @@ -253,6 +265,21 @@ getfirstcharpartitions:{[tablename;extrapartitiontype] group ?[tablename;();();({first each string x};(distinct;first extrapartitiontype))] }; +/ the parted column(s) for a table from a sort config (tabname/column/sort/att): the table's own +/ p# columns, else the default's +getextrapartitiontype:{[sortconfig;tablename] + requireinit[`getextrapartitiontype]; + tabparts:$[count tabparts:distinct exec column from sortconfig where tabname=tablename,sort=1,att=`p; + [.z.m.loginfo[`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; + tabparts]; + count defaultparts:distinct exec column from sortconfig where tabname=`default,sort=1,att=`p; + [.z.m.loginfo[`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table, using default instead"]; + defaultparts]; + [.z.m.logerr[`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table and default not defined"]] + ]; + tabparts + }; + / ============================================================ / initialisation / ============================================================ @@ -323,6 +350,11 @@ getapimeta:{[] "[symbol: ptdir; long: rowcount; long: bytes]";"null"); (`clearpartsizes;1b;"drop all tracked segment sizes";"[]";"null"); (`getpartsizes; 1b;"current tracked segment sizes";"[]";"table: ptdir/rowcount/bytes"); + (`getmergebybytelimit;1b;"the configured mergebybytelimit";"[]";"boolean"); + (`getpartlimit;1b;"the configured partlimit";"[]";"long"); + (`getextrapartitiontype; + 1b;"the parted column(s) for a table from a sort config, else the default's"; + "[table: sortconfig; symbol: tablename]";"symbol list: parted columns"); (`syncpartsizes; 1b;"upsert a partsizes table received from a peer process into local tracked state"; "[table: t]";"null"); diff --git a/di/merge/test.csv b/di/merge/test.csv index 4bf32797..afa116a9 100644 --- a/di/merge/test.csv +++ b/di/merge/test.csv @@ -24,6 +24,9 @@ fail,0,0,q,merge.checkpartitiontype[`t;enlist`sym],1,1,checkpartitiontype reject fail,0,0,q,merge.checkenumerabletype[`t;enlist`sym],1,1,checkenumerabletype rejected before init fail,0,0,q,merge.getextrapartitions[`t;enlist`sym],1,1,getextrapartitions rejected before init fail,0,0,q,merge.getfirstcharpartitions[`t;enlist`sym],1,1,getfirstcharpartitions rejected before init +fail,0,0,q,merge.getmergebybytelimit[],1,1,getmergebybytelimit rejected before init +fail,0,0,q,merge.getpartlimit[],1,1,getpartlimit rejected before init +fail,0,0,q,"merge.getextrapartitiontype[([]tabname:`$();column:`$();sort:`boolean$();att:`$());`t]",1,1,getextrapartitiontype rejected before init true,0,0,q,".[merge.trackpartition;(`:g1;1;1);{x}]~""di.merge: trackpartition: init must be called before any other function""",1,1,requireinit error message names the function and is precise comment,,,,,,,init - dependency injection validation (log is required with info and error keys) @@ -36,6 +39,7 @@ fail,0,0,q,merge.init[enlist[`log]!enlist(enlist[`info]!enlist mylog`info)],1,1, fail,0,0,q,merge.init[enlist[`log]!enlist(enlist[`error]!enlist mylog`error)],1,1,init rejects a log dict missing the info level true,0,0,q,"(8#@[merge.init;(::);{x}])~""di.merge""",1,1,error message is prefixed di.merge run,0,0,q,merge.init[enlist[`log]!enlist mylog],1,1,init with a valid minimal (info+error only) log dep +true,0,0,q,(0b;1000)~(merge.getmergebybytelimit[];merge.getpartlimit[]),1,1,mergebybytelimit and partlimit default to 0b and 1000 comment,,,,,,,version and getapimeta true,0,0,q,`version in key merge,1,1,version is still an export - di.depcheck reads it there @@ -95,6 +99,7 @@ run,0,0,q,merge.trackpartition[`:b1;1;100],1,1,track b1 with a small row count b run,0,0,q,merge.trackpartition[`:b2;1;100],1,1,track b2 run,0,0,q,merge.trackpartition[`:b3;1;100],1,1,track b3 true,0,0,q,merge.getpartchunks[`:b1`:b2`:b3;250]~(`:b1`:b2;enlist`:b3),1,1,batching uses bytes not row count (row count alone would fit all three) +true,0,0,q,merge.getmergebybytelimit[],1,1,getmergebybytelimit returns the configured value run,0,0,q,merge.init[enlist[`log]!enlist mylog],1,1,restore row-count batching (default) comment,,,,,,,getpartchunks splits a batch that exceeds partlimit partitions @@ -256,6 +261,15 @@ comment,,,,,,,getfirstcharpartitions groups partition values by first character run,0,0,q,fctbl:([]sym:`aa`ab`ba`bb`ac;px:1 2 3 4 5),1,1,table with symbol values sharing first characters true,0,0,q,merge.getfirstcharpartitions[`fctbl;enlist`sym]~(`aa`ab`ac;`ba`bb),1,1,values grouped by first character not by full value +comment,,,,,,,getextrapartitiontype reads the p# columns from the sort config passed in +run,0,0,q,"sc:([]tabname:`trade`trade`default;column:`sym`time`sym;sort:101b;att:`p``p)",1,1,sort config: trade parted on sym; default parted on sym +true,0,0,q,(enlist`sym)~merge.getextrapartitiontype[sc;`trade],1,1,the table's own p# column +true,0,0,q,(enlist`sym)~merge.getextrapartitiontype[sc;`quote],1,1,a table not in the config falls back to the default +run,0,0,q,merge.init[enlist[`log]!enlist logcap],1,1,init with the capturing logger +run,0,0,q,caplog:0#caplog,1,1,reset the capture +run,0,0,q,merge.getextrapartitiontype[delete from sc where tabname=`default;`quote],1,1,no table entry and no default +true,0,0,q,"any (exec msg from caplog where fn=`error) like ""*default not defined*""",1,1,is error-logged + comment,,,,,,,parted-column checks route through the injected logger and no longer reference sort.csv run,0,0,q,merge.init[enlist[`log]!enlist logcap],1,1,init with the capturing logger run,0,0,q,qtbl:([]a:1 2;b:3 4;f:1.0 2.0),1,1,table with long and float columns diff --git a/di/torq/proc/segmentedtp/sctp.q b/di/torq/proc/segmentedtp/sctp.q index 68d5802f..dae6209b 100644 --- a/di/torq/proc/segmentedtp/sctp.q +++ b/di/torq/proc/segmentedtp/sctp.q @@ -1,43 +1,39 @@ -\d .sctp - -chainedtp:@[value;`chainedtp;0b]; / switches between STP and SCTP -loggingmode:@[value;`loggingmode;`none]; / [none|create|parent] -tickerplantname:@[value;`tickerplantname;`stp1]; -tpconnsleep:@[value;`tpconnsleep;10]; -tpcheckcycles:@[value;`tpcheckcycles;0W]; -subscribeto:@[value;`subscribeto;`]; -subscribesyms:@[value;`subscribesyms;`]; -replay:@[value;`replay;0b]; -schema:@[value;`schema;1b]; +.sctp.chainedtp:@[value;`.sctp.chainedtp;0b]; / switches between STP and SCTP +.sctp.loggingmode:@[value;`.sctp.loggingmode;`none]; / [none|create|parent] +.sctp.tickerplantname:@[value;`.sctp.tickerplantname;`stp1]; +.sctp.tpconnsleep:@[value;`.sctp.tpconnsleep;10]; +.sctp.tpcheckcycles:@[value;`.sctp.tpcheckcycles;0W]; +.sctp.subscribeto:@[value;`.sctp.subscribeto;`]; +.sctp.subscribesyms:@[value;`.sctp.subscribesyms;`]; +.sctp.replay:@[value;`.sctp.replay;0b]; +.sctp.schema:@[value;`.sctp.schema;1b]; / subscribe to segmented tickerplant -subscribe:{[] - s:.sub.getsubscriptionhandles[`;tickerplantname;()!()]; +.sctp.subscribe:{[] + s:.sub.getsubscriptionhandles[`;.sctp.tickerplantname;()!()]; if[count s; subproc:first s; `.sctp.tph set subproc`w; .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; - r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; + r:.sub.subscribe[.sctp.subscribeto;.sctp.subscribesyms;.sctp.schema;.sctp.replay;subproc]; if[`d in key r;.u.d::r[`d]]; - if[(`icounts in key r) & (loggingmode<>`create); - subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); + if[(`icounts in key r) & (.sctp.loggingmode<>`create); + subtabs:$[.sctp.subscribeto~`;key r`icounts;.sctp.subscribeto],(); .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; ] ]; } / initialise chained STP -init:{ +.sctp.init:{ `endofperiod set {[x;y;z] .stplg.endofperiod[x;y;z]}; `endofday set {[x;y] .stplg.endofday[x;y]}; .servers.startupdepnamecycles[.sctp.tickerplantname;.sctp.tpconnsleep;.sctp.tpcheckcycles]; .sctp.subscribe[]; }; -\d . - / extract data from incoming table as a list -upd:{[t;x] +@[`.;`upd;:;{[t;x] x:value flip x; .u.upd[t;x] - } + }]; diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 643628d5..30a51819 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -7,7 +7,7 @@ tickerplant: it subscribes to another one and republishes what it receives. ## Files `init.q` loads, in order: `stpps.q` (`.stpps.upd`/`.stpps.zts`), `sctp.q` (`.sctp`, the chained mode), `stplog.q` -(`.stplg`, logging and batching, and the `.os` directory helpers if absent), `stpmeta.q` (`.stpm`, log metadata) and `segmentedtp.q` (the process and `init`). +(`.stplg`, logging and batching), `stpmeta.q` (`.stpm`, log metadata) and `segmentedtp.q` (the process and `init`). ## Surface @@ -47,6 +47,10 @@ A `sctp` section, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and `subscribesyms` also take strings, so the section can live in a `.toml` file. +`di/torq/settings/segmentedtp.q` declares every `stplg` default except `kdbtplog`, and every `sctp` default, so any of +them can be given on the command line as `-.stplg.` or `-.sctp.`; an app section replaces it, so list there +every key to override. + An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. Flat: `schemafile` (required unless chained), `createlogs` (`1b`). diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 825f6048..a9a2ebd3 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -50,23 +50,21 @@ init:{[config;deps] .stplg.init[string .z.m.procname]; } -\d . - / allow tickerplant to create a log file -createlogs:@[value;`createlogs;1b]; +@[`.;`createlogs;:;@[value;`createlogs;1b]]; / subscribers use this to determine what type of process they are talking to -tptype:`segmented +@[`.;`tptype;:;`segmented]; -tablelist:{.stpps.t} +@[`.;`tablelist;:;{.stpps.t}]; / subscribers who want to replay need this info -subdetails:{[tabs;instruments] +@[`.;`subdetails;:;{[tabs;instruments] `schemalist`logfilelist`rowcounts`date`logdir!(.ps.subscribe\:[tabs;instruments];.stplg.replaylog[tabs];tabs#.stplg `rowcount;.z.m.eod.getd[];.stplg.kdbtplog) - } + }]; / table and schema information and default table upd functions -generateschemas:{ +@[`.;`generateschemas;:;{ .stpps.init[tables[] except `currlog`heartbeat`logmsg`svrstoload]; .stpps.attrstrip[.stpps.t]; / table upd functions attach the current timestamp; chained they do nothing @@ -74,16 +72,16 @@ generateschemas:{ .stplg.updtab:(.stpps.t!(count .stpps.t)#{[x;y] x}),.stplg.updtab; .stplg.updtab:(.stpps.t!(count .stpps.t)#{(enlist(count first x)#y),x}),.stplg.updtab ] - } + }]; / load in schema file and kill proc if not present -loadschemas:{ +@[`.;`loadschemas;:;{ if[not `schemafile in key .z.m.params;.z.m.log[`error][`loadschema;"Schema file required!"];exit 1]; @[{system"l ",x};raze .z.m.params[`schemafile];{.z.m.log[`error][`loadschema;"Failed to load schema file!"];exit 1}]; - }; + }]; / upd and zts behaviour from the batch mode -setup:{[batch] +@[`.;`setup;:;{[batch] if[not all batch in/: key'[.stplg`upd`zts];'"mode ",(string batch)," must be defined in both .stplg.upd and .stplg.zts"]; chainmode:$[.sctp.chainedtp;`chained;`def]; .stplg.updmsg:.stplg.upd[batch]; @@ -96,4 +94,4 @@ setup:{[batch] .u.upd:{[t;x] .[.stp.upd;(t;x);{.stplg.badmsg[x;y;z]}[;t;x]]} ]; if[not system "t";.z.m.log[`info][`timer;"defaulting timer to 1000ms"];system"t 1000"]; - }; + }]; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q index a439a027..1d78b045 100644 --- a/di/torq/proc/segmentedtp/stplog.q +++ b/di/torq/proc/segmentedtp/stplog.q @@ -1,42 +1,30 @@ / periodic tp logging -\d . - / live logs and handles to logs for each table -currlog:([tbl:`symbol$()]logname:`symbol$();handle:`int$()) +@[`.;`currlog;:;([tbl:`symbol$()]logname:`symbol$();handle:`int$())]; / view of log file handles for faster lookups -loghandles::exec tbl!handle from currlog - -\d .os - -if[not `md in key `.os; - NT:.z.o in`w32`w64; - Fex:{not 0h~type key hsym$[10=type x;`$x;x]}; - pth:{if[10h<>type x;x:string x]; if[NT;x:@[x;where"/"=x;:;"\\"]];$[":"=first x;1_x;x]}; - md:{if[not Fex x;system"mkdir \"",pth[x],"\""]}]; - -\d .stplg +value"loghandles::exec tbl!handle from currlog"; / settings -multilog:`tabperiod / [tabperiod|none|periodic|tabular|custom] -multilogperiod:0D01 -errmode:1b -batchmode:`defaultbatch / [memorybatch|defaultbatch|immediate] -replayperiod:`day / [period|day|prior] -customcsv:` -kdbtplog:`$getenv`KDBTPLOG +.stplg.multilog:`tabperiod / [tabperiod|none|periodic|tabular|custom] +.stplg.multilogperiod:0D01 +.stplg.errmode:1b +.stplg.batchmode:`defaultbatch / [memorybatch|defaultbatch|immediate] +.stplg.replayperiod:`day / [period|day|prior] +.stplg.customcsv:` +.stplg.kdbtplog:`$getenv`KDBTPLOG -errorlogname:@[value;`.stplg.errorlogname;`segmentederrorlogfile] +.stplg.errorlogname:@[value;`.stplg.errorlogname;`segmentederrorlogfile] / create log directory `:stplogs/date/tabname_time -createdld:{[name;date] +.stplg.createdld:{[name;date] if[not count dir:hsym .stplg.kdbtplog;.z.m.log[`error][`stp;"log directory not defined"];exit 1]; - .os.md dir; - .os.md .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; + system"mkdir -p ",1_string dir; + system"mkdir -p ",1_string .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; }; -gentimeformat:{(raze string "dv"$x) except ".:"}; +.stplg.gentimeformat:{(raze string "dv"$x) except ".:"}; / tabperiod: one log per table, rolled periodically .stplg.logname.tabperiod:{[dir;tab;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";tab),.stplg.gentimeformat[p]) }; @@ -56,18 +44,18 @@ gentimeformat:{(raze string "dv"$x) except ".:"}; .stplg.logname.error:{[dir;ename;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";ename),.stplg.gentimeformat[p]) }; / upd and timer functions per batch mode; pre-existing definitions kept -upd:@[value;`.stplg.upd;enlist[`]!enlist ()]; -zts:@[value;`.stplg.zts;enlist[`]!enlist ()]; +.stplg.upd:@[value;`.stplg.upd;enlist[`]!enlist ()]; +.stplg.zts:@[value;`.stplg.zts;enlist[`]!enlist ()]; / functions to add columns on updates -updtab:@[value;`.stplg.updtab;enlist[`]!enlist {(enlist(count first x)#y),x}] +.stplg.updtab:@[value;`.stplg.updtab;enlist[`]!enlist {(enlist(count first x)#y),x}] / memorybatch: insert in memory; write, publish and count on the timer -upd[`memorybatch]:{[t;x;now] - t insert updtab[t] . (x;now); +.stplg.upd[`memorybatch]:{[t;x;now] + t insert .stplg.updtab[t] . (x;now); }; -zts[`memorybatch]:{ +.stplg.zts[`memorybatch]:{ {[t] if[count value t; `..loghandles[t] enlist (`upd;t;value flip value t); @@ -78,14 +66,14 @@ zts[`memorybatch]:{ }; / defaultbatch: write immediately, publish on the timer -upd[`defaultbatch]:{[t;x;now] +.stplg.upd[`defaultbatch]:{[t;x;now] t insert x:.stplg.updtab[t] . (x;now); `..loghandles[t] enlist(`upd;t;x); @[`.stplg.tmpmsgcount;t;+;1]; @[`.stplg.tmprowcount;t;+;count first x]; }; -zts[`defaultbatch]:{ +.stplg.zts[`defaultbatch]:{ .stpps.pubclear[.stpps.t]; .stplg.msgcount+:.stplg.tmpmsgcount; .stplg.rowcount+:.stplg.tmprowcount; @@ -93,8 +81,8 @@ zts[`defaultbatch]:{ }; / immediate: write and publish immediately -upd[`immediate]:{[t;x;now] - x:updtab[t] . (x;now); +.stplg.upd[`immediate]:{[t;x;now] + x:.stplg.updtab[t] . (x;now); `..loghandles[t] enlist(`upd;t;x); x:$[0h>type last x;enlist;flip] .stpps.tabcols[t]!x; @[`.stplg.msgcount;t;+;1]; @@ -102,30 +90,30 @@ upd[`immediate]:{[t;x;now] .stpps.pub[t;x] }; -zts[`immediate]:{} +.stplg.zts[`immediate]:{} / logcounts and lognames for client replay -replaylog:{[t] - getlogs[replayperiod][t] +.stplg.replaylog:{[t] + .stplg.getlogs[.stplg.replayperiod][t] } -getlogs:enlist[`]!enlist () +.stplg.getlogs:enlist[`]!enlist () / period: logs for the current logging period -getlogs[`period]:{[t] +.stplg.getlogs[`period]:{[t] distinct flip (.stplg.msgcount;exec tbl!logname from `..currlog where tbl in t)@\:t }; / day: all of today's logs; closed logs count 0W -getlogs[`day]:{[t] +.stplg.getlogs[`day]:{[t] lnames:select seq,tbls,logname,msgcount:0Wj from .stpm.metatable where any each tbls in\: t; lnames:update msgcount:sum each .stplg.msgcount[tbls] from lnames where seq=.stplg.i; flip value exec `long$msgcount,logname from lnames }; / open log for a table at the start of a logging period -openlog:{[multilog;dir;tab;p] - lname:logname[multilog][dir;tab;p]; +.stplg.openlog:{[multilog;dir;tab;p] + lname:.stplg.logname[multilog][dir;tab;p]; .z.m.log[`info][`openlog;"opening logfile: ",string lname]; h:$[(notexists:not type key lname)or null h0:exec first handle from `..currlog where logname=lname; [if[notexists;.[lname;();:;()]];hopen lname]; @@ -135,19 +123,19 @@ openlog:{[multilog;dir;tab;p] }; / error log for failed updates in error mode -openlogerr:{[dir] +.stplg.openlogerr:{[dir] lname:.[.stplg.logname.error;(dir;.stplg.errorlogname;.z.p+.z.m.eod.getdailyadj[]);{.z.m.log[`error][`openlogerr;"failed to make error log: ",x]}]; if[not type key lname;.[lname;();:;()]]; h:@[{hopen x};lname;{.z.m.log[`error][`openlogerr;"failed to open handle to error log with error: ",x]}]; - `..currlog upsert (errorlogname;lname;h); + `..currlog upsert (.stplg.errorlogname;lname;h); }; -badmsg:{[e;t;x] +.stplg.badmsg:{[e;t;x] .z.m.log[`info][`upd;"Bad message received, error: ",e]; - `..loghandles[errorlogname] enlist(`upderr;t;x); + `..loghandles[.stplg.errorlogname] enlist(`upderr;t;x); }; -closelog:{[tab] +.stplg.closelog:{[tab] if[null h:`..currlog[tab;`handle];.z.m.log[`info][`closelog;"no open handle to log file"];:()]; .z.m.log[`info][`closelog;"closing log file ",string `..currlog[tab;`logname]]; @[hclose;h;{.z.m.log[`error][`closelog;"handle already closed"]}]; @@ -155,103 +143,101 @@ closelog:{[tab] }; / roll all logs at the end of a logging period -rolllog:{[multilog;dir;tabs;p] +.stplg.rolllog:{[multilog;dir;tabs;p] .stpm.updmeta[multilog][`close;tabs;p]; - closelog each tabs; + .stplg.closelog each tabs; @[`.stplg.msgcount;tabs;:;0]; {[m;d;t] - .[openlog;(m;d;t;currperiod); + .[.stplg.openlog;(m;d;t;.stplg.currperiod); {.z.m.log[`error][`stp;"failed to open log for table ",string[y],": ",x]}[;t]] }[multilog;dir;]each tabs; .stpm.updmeta[multilog][`open;tabs;p]; }; / process data sent at endofday/endofperiod -endofdaydata:@[value;`.stplg.endofdaydata;{ {`proctype`procname`tables!(.z.m.proctype;.z.m.procname;.stpps.t)} }]; +.stplg.endofdaydata:@[value;`.stplg.endofdaydata;{ {`proctype`procname`tables!(.z.m.proctype;.z.m.procname;.stpps.t)} }]; / chained end of period: pass on to subscribers; roll logs in create mode -endofperiod:{[currentpd;nextpd;data] +.stplg.endofperiod:{[currentpd;nextpd;data] .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; .stpps.pubclear[.stplg.t]; .z.m.log[`info][`endofperiod;"executing end of period for ",.Q.s1 `currentperiod`nextperiod!(currentpd;nextpd)]; .stpps.endp[currentpd;nextpd;data]; - currperiod::nextpd; - if[.sctp.loggingmode=`create;periodrollover[data]] + .stplg.currperiod:nextpd; + if[.sctp.loggingmode=`create;.stplg.periodrollover[data]] }; / end of period: send to subscribers; roll logs unless end of day is due -stpeoperiod:{[currentpd;nextpd;data;rolllogs] +.stplg.stpeoperiod:{[currentpd;nextpd;data;rolllogs] .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; .stpps.pubclear[.stplg.t]; .z.m.log[`info][`stpeoperiod;"passing on endofperiod message to subscribers"]; .stpps.endp[currentpd;nextpd;data]; - currperiod::nextperiod; - if[(data`p)>nextperiod::multilogperiod+currperiod; + .stplg.currperiod:.stplg.nextperiod; + if[(data`p)>.stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; system"t 0";'"next period is in the past"]; - getnextendUTC[]; - if[rolllogs;periodrollover[data]]; + .stplg.getnextendUTC[]; + if[rolllogs;.stplg.periodrollover[data]]; .z.m.log[`info][`stpeoperiod;"end of period complete, new values for current and next period are ",.Q.s1 (currentpd;nextpd)]; } -periodrollover:{[data] - i+::1; - rolllog[multilog;dldir;rolltabs;data`p]; +.stplg.periodrollover:{[data] + .stplg.i+:1; + .stplg.rolllog[.stplg.multilog;.stplg.dldir;.stplg.rolltabs;data`p]; } / end of day: send to subscribers and roll logs -endofday:{[date;data] +.stplg.endofday:{[date;data] .z.m.log[`info][`endofday;"flushing remaining data to subscribers and clearing tables"]; .stpps.pubclear[.stplg.t]; .z.m.log[`info][`endofday;"executing end of day for ",.Q.s1 .z.m.eod.getd[]]; .stpps.end[date;data]; - dayrollover[data]; + .stplg.dayrollover[data]; } -dayrollover:{[data] +.stplg.dayrollover:{[data] .z.m.eod.setnextroll .z.m.eod.getroll data`p; if[(data`p)>.z.m.eod.getnextroll[]; system"t 0";'"next roll is in the past"]; - getnextendUTC[]; + .stplg.getnextendUTC[]; .z.m.eod.setd 1+.z.m.eod.getd[]; - .stpm.updmeta[multilog][`close;logtabs;(data`p)+.z.m.eod.getdailyadj[]]; + .stpm.updmeta[.stplg.multilog][`close;.stplg.logtabs;(data`p)+.z.m.eod.getdailyadj[]]; .stpm.metatable:0#.stpm.metatable; - closelog each logtabs; - init[string .z.m.procname]; + .stplg.closelog each .stplg.logtabs; + .stplg.init[string .z.m.procname]; .z.m.log[`info][`dayrollover;"end of day complete, new value for date is ",.Q.s1 .z.m.eod.getd[]]; } -getnextendUTC:{nextendUTC::-1+min(.z.m.eod.getnextroll[];nextperiod - .z.m.eod.getdailyadj[])} +.stplg.getnextendUTC:{.stplg.nextendUTC:-1+min(.z.m.eod.getnextroll[];.stplg.nextperiod - .z.m.eod.getdailyadj[])} -checkends:{ - if[nextendUTC > x; :()]; - if[nextperiod < x1:x+.z.m.eod.getdailyadj[]; stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; - if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;system"t 0";'"more than one day?"]; endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; +.stplg.checkends:{ + if[.stplg.nextendUTC > x; :()]; + if[.stplg.nextperiod < x1:x+.z.m.eod.getdailyadj[]; .stplg.stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; + if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;system"t 0";'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; }; -init:{[dbname] - t::tables[`.]except `currlog; - msgcount::rowcount::t!count[t]#0; - tmpmsgcount::tmprowcount::(`symbol$())!`long$(); - logtabs::$[multilog~`custom;key custommode;t]; - rolltabs::$[multilog~`custom;logtabs except where custommode in `tabular`singular;t]; - currperiod::multilogperiod xbar .z.p+.z.m.eod.getdailyadj[]; - nextperiod::multilogperiod+currperiod; - getnextendUTC[]; - i::1; - seqnum::0; +.stplg.init:{[dbname] + .stplg.t:tables[`.]except `currlog; + .stplg.msgcount:.stplg.rowcount:.stplg.t!count[.stplg.t]#0; + .stplg.tmpmsgcount:.stplg.tmprowcount:(`symbol$())!`long$(); + .stplg.logtabs:$[.stplg.multilog~`custom;key .stplg.custommode;.stplg.t]; + .stplg.rolltabs:$[.stplg.multilog~`custom;.stplg.logtabs except where .stplg.custommode in `tabular`singular;.stplg.t]; + .stplg.currperiod:.stplg.multilogperiod xbar .z.p+.z.m.eod.getdailyadj[]; + .stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; + .stplg.getnextendUTC[]; + .stplg.i:1; + .stplg.seqnum:0; if[(value `..createlogs) or .sctp.loggingmode=`create; - createdld[dbname;.z.m.eod.getd[]]; - openlog[multilog;dldir;;.z.p+.z.m.eod.getdailyadj[]]each logtabs; - if[.stplg.errmode;openlogerr[dldir]]; + .stplg.createdld[dbname;.z.m.eod.getd[]]; + .stplg.openlog[.stplg.multilog;.stplg.dldir;;.z.p+.z.m.eod.getdailyadj[]]each .stplg.logtabs; + if[.stplg.errmode;.stplg.openlogerr[.stplg.dldir]]; / read the meta table from disk and continue its sequence .stpm.metatable:@[get;hsym`$string[.stplg.dldir],"/stpmeta";0#.stpm.metatable]; - i::1+ -1|exec max seq from .stpm.metatable; - .stpm.updmeta[multilog][`open;logtabs;.z.p+.z.m.eod.getdailyadj[]]; + .stplg.i:1+ -1|exec max seq from .stpm.metatable; + .stpm.updmeta[.stplg.multilog][`open;.stplg.logtabs;.z.p+.z.m.eod.getdailyadj[]]; ] / chained and not creating logs: no log handles if[.sctp.chainedtp and not .sctp.loggingmode=`create; - `..loghandles set t! (count t) # enlist (::) + `..loghandles set .stplg.t! (count .stplg.t) # enlist (::) ] }; - -\d . diff --git a/di/torq/proc/segmentedtp/stpmeta.q b/di/torq/proc/segmentedtp/stpmeta.q index 4493d986..f6507db7 100644 --- a/di/torq/proc/segmentedtp/stpmeta.q +++ b/di/torq/proc/segmentedtp/stpmeta.q @@ -1,34 +1,32 @@ / log file metadata: logs opened, tables feeding each, message counts -\d .stpm - -metatable:([]seq:`int$();logname:`$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()) +.stpm.metatable:([]seq:`int$();logname:`$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()) / meta update per logging mode, run on log open and close -updmeta:enlist[`]!enlist () +.stpm.updmeta:enlist[`]!enlist () -updmeta[`tabperiod]:{[x;t;p] - getmeta[x;p;;]'[enlist each t;`..currlog[([]tbl:t)]`logname]; - setmeta[.stplg.dldir;metatable]; +.stpm.updmeta[`tabperiod]:{[x;t;p] + .stpm.getmeta[x;p;;]'[enlist each t;`..currlog[([]tbl:t)]`logname]; + .stpm.setmeta[.stplg.dldir;.stpm.metatable]; }; -updmeta[`singular]:{[x;t;p] - getmeta[x;p;t;`..currlog[first t]`logname]; - setmeta[.stplg.dldir;metatable]; +.stpm.updmeta[`singular]:{[x;t;p] + .stpm.getmeta[x;p;t;`..currlog[first t]`logname]; + .stpm.setmeta[.stplg.dldir;.stpm.metatable]; }; -updmeta[`periodic]:updmeta[`singular] +.stpm.updmeta[`periodic]:.stpm.updmeta[`singular] -updmeta[`tabular]:updmeta[`tabperiod] +.stpm.updmeta[`tabular]:.stpm.updmeta[`tabperiod] -updmeta[`custom]:{[x;t;p] +.stpm.updmeta[`custom]:{[x;t;p] pertabs:where `periodic=.stplg.custommode; - updmeta[`periodic][x;t inter pertabs;p]; - updmeta[`tabular][x;t except pertabs;p] + .stpm.updmeta[`periodic][x;t inter pertabs;p]; + .stpm.updmeta[`tabular][x;t except pertabs;p] }; / name, start, tables and schema on open; end and message count on close -getmeta:{[x;p;t;ln] +.stpm.getmeta:{[x;p;t;ln] if[x~`open; s:((),t)!(),.stpps.schemas[t]; `.stpm.metatable upsert (.stplg.i;ln;p;0Np;t;0;s;enlist ()!()); @@ -38,7 +36,7 @@ getmeta:{[x;p;t;ln] ] }; -setmeta:{[dir;mt] +.stpm.setmeta:{[dir;mt] t:(hsym`$string[dir],"/stpmeta"); .[{x set y};(t;mt);{.z.m.log[`error][`setmeta;"Failed to set metatable with error: ",x]}]; }; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 15732569..bb467fee 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -10,6 +10,8 @@ fail,0,0,q,"seg.init[()!();enlist[`log]!enlist nolog]",1,,init without timer mus fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]})]",1,,init without handlers must error true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~.stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv",1,,stplg defaults true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~.sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema",1,,sctp defaults +true,0,0,q,"{x~(key x)#.stplg}((use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]`stplg)",1,,the shipped stplg section declares the module's own defaults (so each is overridable from the command line) +true,0,0,q,"{x~(key x)#.sctp}((use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]`sctp)",1,,the shipped sctp section declares the module's own defaults true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,a stplg section overrides the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered diff --git a/di/torq/proc/tickerlogreplay/deps.toml b/di/torq/proc/tickerlogreplay/deps.toml index 47a1450e..246e0d5d 100644 --- a/di/torq/proc/tickerlogreplay/deps.toml +++ b/di/torq/proc/tickerlogreplay/deps.toml @@ -1,5 +1,5 @@ # Peer modules di.torq.proc.tickerlogreplay `use`s (see di/torq/depcheck/depcheck.md). [dependencies] "di.tplog" = "0.1.0" -"di.merge" = "0.1.0" +"di.merge" = "0.2.0" "di.dbwrite" = "0.2.0" diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index 3ec570e8..8cb4d46c 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -7,7 +7,7 @@ comment,,,,,,,settings true,0,0,q,"(0;1b;1b;0W;0W;enlist`all;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`part)~.replay`firstmessage`segmentedmode`autoreplay`lastmessage`messagechunks`tablelist`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`mergemethod",1,,replay defaults true,0,0,q,`:tempmergedir~.replay.tempdir,1,,tempdir default true,0,0,q,"{x~(key x)#.replay}((use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]`replay)",1,,the shipped replay section declares the module's own defaults (so each is overridable from the command line) -true,0,0,q,all `NT`Fex`pth`deldir`md in key .os,1,,os helpers defined +true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~value x}((use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]`merge)",1,,the shipped merge section declares di.merge's own defaults true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 03c7fddd..f5a6be39 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -7,9 +7,8 @@ at the end, or partition to a temporary directory and merge on disk. ## Files -`init.q` loads `tickerlogreplay.q`: the module `init`, then the `.os` directory helpers and the `.save` hooks -(`savedownmanipulation`, `manipulate`, `postreplay`), each defined if absent, `.merge.getextrapartitiontype`, and -`.replay`. `sort.csv` is the default sort config. +`init.q` loads `tickerlogreplay.q`: the module `init`, then the `.save` hooks (`savedownmanipulation`, +`manipulate`, `postreplay`), each defined if absent, and `.replay`. `sort.csv` is the default sort config. ## Surface @@ -20,7 +19,6 @@ at the end, or partition to a temporary directory and merge on disk. | `.replay.replaylog[logfile]` | replays one log and saves its tables | | `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | | `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | -| `.merge.getextrapartitiontype[t]` | the `p#` column(s) for a table from the sort config | ## Settings @@ -52,7 +50,8 @@ The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist declares every default, so any key can be given on the command line as `-.replay.`, as in TorQ; an app `replay` section replaces it, so list there every key to override. -A `merge` section (`mergebybytelimit`, `partlimit`) is set onto `.merge.` and passed to di.merge's `init`. +A `merge` section (`mergebybytelimit`, `partlimit`) is passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` +declares its defaults. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. ## init[config;deps] diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 6b4cfe2b..4b0dd265 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,7 +18,7 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `replay`merge; + {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each enlist`replay; @[`.replay;`schemafile`hdbdir`tplogdir`tplogfile`tablelist`partitiontype`sortcsv`tempdir`mergemethod;tosym]; .replay.tablelist:(),.replay.tablelist; .z.m.merge:use`di.merge; @@ -47,164 +47,129 @@ init:{[config;deps] / load the sort csv and kick off replay if auto-running $[null .replay.sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv .replay.sortcsv]; if[.replay.autoreplay;.replay.initandrun[]]; - } - -/ os helpers, each defined if absent - -\d .os - -if[not `NT in key `.os;NT:.z.o in`w32`w64]; -if[not `Fex in key `.os;Fex:{not 0h~type key hsym$[10=type x;`$x;x]}]; -if[not `pth in key `.os;pth:{if[10h<>type x;x:string x]; if[NT;x:@[x;where"/"=x;:;"\\"]];$[":"=first x;1_x;x]}]; -if[not `deldir in key `.os;deldir:{system("rm -r ";"rd /s /q ")[NT],pth x}]; -if[not `md in key `.os;md:{if[not Fex x;system"mkdir \"",pth[x],"\""]}]; + }; / save down manipulation and post replay hook, each defined if absent -\d .save - / table!function applied to a table before it is enumerated and saved -if[not `savedownmanipulation in key `.save;savedownmanipulation:@[value;`savedownmanipulation;()!()]]; +if[not `savedownmanipulation in key `.save;.save.savedownmanipulation:@[value;`.save.savedownmanipulation;()!()]]; / manipulate a table at save down time -if[not `manipulate in key `.save;manipulate:{[t;x] - $[t in key savedownmanipulation; - @[savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; +if[not `manipulate in key `.save;.save.manipulate:{[t;x] + $[t in key .save.savedownmanipulation; + @[.save.savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; x]}]; / called after a log's tables are saved, with the directory and partition -if[not `postreplay in key `.save;postreplay:{[d;p] +if[not `postreplay in key `.save;.save.postreplay:{[d;p] }]; -/ parted column(s) for a table from the sort config - -\d .merge - -getextrapartitiontype:{[tablename] - sp:.z.m.dbw.getconfig[]; - tabparts:$[count tabparts:distinct exec column from sp where tabname=tablename,sort=1,att=`p; - [.z.m.log[`info][`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; - tabparts]; - count defaultparts:distinct exec column from sp where tabname=`default,sort=1,att=`p; - [.z.m.log[`info][`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table, using default instead"]; - defaultparts]; - [.z.m.log[`error][`getextraparttype;"parted attribute p not found in sort.csv for ", (string tablename)," table and default not defined"]] - ]; - tabparts - }; - -\d . - -.merge.mergebybytelimit:@[value;`.merge.mergebybytelimit;0b]; // merge limit configuration - default is 0b row count limit, 1b is bytesize limit - -\d .replay - / settings -firstmessage:@[value;`firstmessage;0] // the first message to execute -segmentedmode:@[value;`segmentedmode;1b] // segmented tickerplant logs -autoreplay:@[value;`autoreplay;1b] // replay tplogs automatically -lastmessage:@[value;`lastmessage;0W] // the last message to replay -messagechunks:@[value;`messagechunks;0W] // the number of messages to replay at once -schemafile:@[value;`schemafile;`] // the schema file to load data in to -tablelist:@[value;`tablelist;enlist `all] // the tables to replay into. `all means all -hdbdir:@[value;`hdbdir;`] // the hdb directory to write to -tplogfile:@[value;`tplogfile;`] // the tp log file to replay; this or tplogdir -tplogdir:@[value;`tplogdir;`] // the tp log directory to replay; this or tplogfile -partitiontype:@[value;`partitiontype;`date] // date, month or year -emptytables:@[value;`emptytables;1b] // whether to overwrite any tables at start up -sortafterreplay:@[value;`sortafterreplay;1b] // re-sort and apply attributes at the end of the replay -basicmode:@[value;`basicmode;0b] // replay everything, then save with .Q.hdpf -exitwhencomplete:@[value;`exitwhencomplete;1b] // exit when the replay is complete -checklogfiles:@[value;`checklogfiles;0b] // replay a "good" copy of a corrupt log -gc:@[value;`gc;1b] // garbage collect after each table save and each log -upd:@[value;`upd;{{[t;x] insert[t;x]}}] // default upd function used for replaying data -clean:@[value;`clean;1b] // clean existing folders on start up -sortcsv:@[value;`sortcsv;`] // location of sort csv file; null is the default sort.csv -compression:@[value;`compression;()]; // the compress level, empty list if not required -partandmerge:@[value;`partandmerge;0b]; // partition to tempdir, then merge on disk -tempdir:hsym @[value;`tempdir;`:tempmergedir]; // location to save data for partandmerge replay -mergenumrows:@[value;`mergenumrows;10000000]; // default number of rows for merge process -mergenumtab:@[value;`mergenumtab;`quote`trade!10000 50000]; // number of rows per table for merge process -mergenumbytes:@[value;`mergenumbytes;500000000]; // default number of bytes for merge process -mergemethod:@[value;`mergemethod;`part]; // part, col or hybrid +.replay.firstmessage:@[value;`.replay.firstmessage;0] // the first message to execute +.replay.segmentedmode:@[value;`.replay.segmentedmode;1b] // segmented tickerplant logs +.replay.autoreplay:@[value;`.replay.autoreplay;1b] // replay tplogs automatically +.replay.lastmessage:@[value;`.replay.lastmessage;0W] // the last message to replay +.replay.messagechunks:@[value;`.replay.messagechunks;0W] // the number of messages to replay at once +.replay.schemafile:@[value;`.replay.schemafile;`] // the schema file to load data in to +.replay.tablelist:@[value;`.replay.tablelist;enlist `all] // the tables to replay into. `all means all +.replay.hdbdir:@[value;`.replay.hdbdir;`] // the hdb directory to write to +.replay.tplogfile:@[value;`.replay.tplogfile;`] // the tp log file to replay; this or tplogdir +.replay.tplogdir:@[value;`.replay.tplogdir;`] // the tp log directory to replay; this or tplogfile +.replay.partitiontype:@[value;`.replay.partitiontype;`date] // date, month or year +.replay.emptytables:@[value;`.replay.emptytables;1b] // whether to overwrite any tables at start up +.replay.sortafterreplay:@[value;`.replay.sortafterreplay;1b] // re-sort and apply attributes at the end of the replay +.replay.basicmode:@[value;`.replay.basicmode;0b] // replay everything, then save with .Q.hdpf +.replay.exitwhencomplete:@[value;`.replay.exitwhencomplete;1b] // exit when the replay is complete +.replay.checklogfiles:@[value;`.replay.checklogfiles;0b] // replay a "good" copy of a corrupt log +.replay.gc:@[value;`.replay.gc;1b] // garbage collect after each table save and each log +.replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] // default upd function used for replaying data +.replay.clean:@[value;`.replay.clean;1b] // clean existing folders on start up +.replay.sortcsv:@[value;`.replay.sortcsv;`] // location of sort csv file; null is the default sort.csv +.replay.compression:@[value;`.replay.compression;()]; // the compress level, empty list if not required +.replay.partandmerge:@[value;`.replay.partandmerge;0b]; // partition to tempdir, then merge on disk +.replay.tempdir:hsym @[value;`.replay.tempdir;`:tempmergedir]; // location to save data for partandmerge replay +.replay.mergenumrows:@[value;`.replay.mergenumrows;10000000]; // default number of rows for merge process +.replay.mergenumtab:@[value;`.replay.mergenumtab;`quote`trade!10000 50000]; // number of rows per table for merge process +.replay.mergenumbytes:@[value;`.replay.mergenumbytes;500000000]; // default number of bytes for merge process +.replay.mergemethod:@[value;`.replay.mergemethod;`part]; // part, col or hybrid / save down settings -.save.savedownmanipulation:@[value;`savedownmanipulation;()!()] // table!function applied to a table at save -.save.postreplay:@[value;`postreplay;{{[d;p] }}] // invoked after a log's tables are saved +.save.savedownmanipulation:@[value;`.replay.savedownmanipulation;()!()] // table!function applied to a table at save +.save.postreplay:@[value;`.replay.postreplay;{{[d;p] }}] // invoked after a log's tables are saved // the path to the table to save -pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} +.replay.pathtotable:{[h;p;t] `$(string .Q.par[h;.replay.partitiontype$p;t]),"/"} // create empty tables - we need to make sure we only create them once -emptytabs:`symbol$() -createemptytable:{[h;p;t;td] - $[partandmerge;dest:td;dest:h]; - if[(not (path:pathtotable[dest;p;t]) in .replay.emptytabs) and .replay.emptytables; +.replay.emptytabs:`symbol$() +.replay.createemptytable:{[h;p;t;td] + $[.replay.partandmerge;dest:td;dest:h]; + if[(not (path:.replay.pathtotable[dest;p;t]) in .replay.emptytabs) and .replay.emptytables; .z.m.log[`info][`replay;"creating empty table ",(string t)," at ",string path]; .replay.emptytabs,:path; - savetabdatatrapped[h;p;t;0#value t;0b;td]]} + .replay.savetabdatatrapped[h;p;t;0#value t;0b;td]]} -savetabdata:{[h;p;t;data;UPSERT;td] - $[partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; - if[not partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; +.replay.savetabdata:{[h;p;t;data;UPSERT;td] + $[.replay.partandmerge;path:.replay.pathtotable[td;p;t];path:.replay.pathtotable[h;p;t]]; + if[not .replay.partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; .replay.pathlist[t],:path; - $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + $[.replay.partandmerge;.replay.savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] } -savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} +.replay.savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[.replay.savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} // this function should be invoked for saving tables -savetab:{[td;h;p;t] - if[not partandmerge;createemptytable[h;p;t;td]]; +.replay.savetab:{[td;h;p;t] + if[not .replay.partandmerge;.replay.createemptytable[h;p;t;td]]; if[count value t; .z.m.log[`info][`replay;"saving ",(string t)," which has row count ",string count value t]; - savetabdatatrapped[h;p;t;value t;1b;td]; + .replay.savetabdatatrapped[h;p;t;value t;1b;td]; delete from t; - if[gc;.z.m.dbw.gc[]]]} + if[.replay.gc;.z.m.dbw.gc[]]]} // apply the sorting and attributes at the end of the replay, from tablename!(list of paths) -applysortandattr:{[pathlist] +.replay.applysortandattr:{[pathlist] {.z.m.dbw.sort . x} each flip (key;value) @\: distinct each pathlist }; // table names in count order, smallest first -tabsincountorder:{x iasc count each value each x} +.replay.tabsincountorder:{x iasc count each value each x} // check if the count has been exceeded, and save down if it has -currentcount:0 -totalcount:0 -checkcount:{[h;p;counter;td] - currentcount+::counter; +.replay.currentcount:0 +.replay.totalcount:0 +.replay.checkcount:{[h;p;counter;td] + .replay.currentcount+:counter; if[.replay.currentcount >= .replay.messagechunks; $[.replay.trackonly; [.replay.totalcount +: .replay.currentcount; .z.m.log[`info][`replay;"replayed a chunk of ",(string .replay.messagechunks)," messages. Total message count so far is ",string .replay.totalcount]]; [.z.m.log[`info][`replay;"number of messages to replay at once (",(string .replay.messagechunks),") has been exceeded. Saving down"]; - savetab[td;h;p] each tabsincountorder[.replay.tablestoreplay]; + .replay.savetab[td;h;p] each .replay.tabsincountorder[.replay.tablestoreplay]; .z.m.log[`info][`replay;"save complete- replaying next chunk of data"]]]; .replay.currentcount:0]} // function used to finish off the replay -finishreplay:{[h;p;td] +.replay.finishreplay:{[h;p;td] // save down any tables which haven't been saved - savetab[td;h;p] each tabsincountorder[.replay.tablestoreplay]; + .replay.savetab[td;h;p] each .replay.tabsincountorder[.replay.tablestoreplay]; // invoke any user defined post replay function .save.postreplay[h;p]; } // takes in log file directories made with segmented tickerplant -expandstplogs:{[logdirectories] // always a list - {` sv'raze x,/:'key each x}$[`~tplogdir;{enlist first x};]hsym logdirectories +.replay.expandstplogs:{[logdirectories] // always a list + {` sv'raze x,/:'key each x}$[`~.replay.tplogdir;{enlist first x};]hsym logdirectories }; -replaylog:{[logfile] +.replay.replaylog:{[logfile] // set the upd function to be the initialupd function .replay.msgcount:.replay.currentcount:.replay.totalcount:0; // check if logfile is corrupt - if[checklogfiles; logfile: .z.m.tplog.check[logfile;lastmessage]]; - $[firstmessage>0; - [.z.m.log[`info][`replay;"skipping first ",(string firstmessage)," messages"]; + if[.replay.checklogfiles; logfile: .z.m.tplog.check[logfile;.replay.lastmessage]]; + $[.replay.firstmessage>0; + [.z.m.log[`info][`replay;"skipping first ",(string .replay.firstmessage)," messages"]; @[`.;`upd;:;.replay.initialupd]]; @[`.;`upd;:;.replay.realupd]]; .replay.tablecounts:.replay.errorcounts:()!(); @@ -217,37 +182,37 @@ replaylog:{[logfile] if[.replay.clean;.replay.cleanhdb .replay.replaydate] ]; - if[lastmessage ",fifo," &"; @[system;fifostr;{.z.m.log[`error][`replay;"Failed to read log into named pipe"]}]; @@ -267,39 +232,39 @@ readintofifo:{[filename] }; // upd functions down here -realupd:{[f;t;x] +.replay.realupd:{[f;t;x] // increment the tablecounts - tablecounts[t]+::count first x; + .replay.tablecounts[t]+:count first x; // run the supplied function in the error trap - .[f;(t;x);{[t;x;e] errorcounts[t]+::count first x}[t;x]]; + .[f;(t;x);{[t;x;e] .replay.errorcounts[t]+:count first x}[t;x]]; }[.replay.upd] -initialupd:{[t;x] +.replay.initialupd:{[t;x] // spin through the first X messages - $[msgcount < (firstmessage - 1); - msgcount+::1; + $[.replay.msgcount < (.replay.firstmessage - 1); + .replay.msgcount+:1; // Once we reach the correct message, reset the upd function @[`.;`upd;:;.replay.realupd]] } // extract user defined row counts -mergemaxrows:{[tabname] mergenumrows^mergenumtab[tabname]}; +.replay.mergemaxrows:{[tabname] .replay.mergenumrows^.replay.mergenumtab[tabname]}; // post replay function for merge replay, invoked after all the tables have been written down for a given log file -postreplaymerge:{[td;p;h] - .os.md[.os.pth[string .Q.par[td;p;`]]]; // ensures directory exists before removed - mergelimits:(tabsincountorder[.replay.tablestoreplay],())!$[.merge.mergebybytelimit;(count tabsincountorder[.replay.tablestoreplay])#mergenumbytes;({[x] mergenumrows^mergemaxrows[x]}tabsincountorder[.replay.tablestoreplay])],(); +.replay.postreplaymerge:{[td;p;h] + system"mkdir -p ",1_string .Q.par[td;p;`]; // ensures directory exists before removed + mergelimits:(.replay.tabsincountorder[.replay.tablestoreplay],())!$[.z.m.merge.getmergebybytelimit[];(count .replay.tabsincountorder[.replay.tablestoreplay])#.replay.mergenumbytes;({[x] .replay.mergenumrows^.replay.mergemaxrows[x]}.replay.tabsincountorder[.replay.tablestoreplay])],(); // merge the tables from each partition in the tempdir together - merge[td;p;;mergelimits;h] each tabsincountorder[.replay.tablestoreplay]; - .os.deldir .os.pth[string .Q.par[td;p;`]]; // delete the contents of tempdir after merge completion + .replay.merge[td;p;;mergelimits;h] each .replay.tabsincountorder[.replay.tablestoreplay]; + system"rm -r ",1_string .Q.par[td;p;`]; // delete the contents of tempdir after merge completion } // function to upsert to specified directory -upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] +.replay.upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] dirpar:.Q.par[dir;pt;`$string first expt]; directory:` sv dirpar,tablename,`; // make directories for tables if they don't exist - if[count tabpar:tabsincountorder[.replay.tablestoreplay] except key dirpar; + if[count tabpar:.replay.tabsincountorder[.replay.tablestoreplay] except key dirpar; .z.m.log[`info][`dir;"creating directories under ",1_string dirpar]; tabpar:tabpar except `heartbeat`logmsg; .[{[d;h;t](` sv d,t,`) set .Q.en[h;0#value t]};] each dirpar,'h,'tabpar]; @@ -312,11 +277,11 @@ upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] .z.m.merge.trackpartition[first ` vs directory;count r;-22!r]; }; -savetablesbypart:{[dir;pt;tablename;h] +.replay.savetablesbypart:{[dir;pt;tablename;h] arows: count value tablename; .z.m.log[`info][`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; // get additional partition(s) defined by parted attribute in sort.csv - extrapartitiontype:.merge.getextrapartitiontype[tablename]; + extrapartitiontype:.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename]; // check each partition type actually is a column in the selected table .z.m.merge.checkpartitiontype[tablename;extrapartitiontype]; @@ -327,16 +292,16 @@ savetablesbypart:{[dir;pt;tablename;h] .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; // upsert data to specific partition directory - upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; + .replay.upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; // empty the table .z.m.log[`info][`delete;"deleting ",(string tablename)," data from in-memory table"]; @[`.;tablename;0#]; // run a garbage collection (if enabled) - if[gc;.z.m.dbw.gc[]]; + if[.replay.gc;.z.m.dbw.gc[]]; }; -merge:{[dir;pt;tablename;mergelimits;h] +.replay.merge:{[dir;pt;tablename;mergelimits;h] // get int partitions intpars:asc key ` sv dir,`$string pt; // list of enumerated partitions 0 1 2 3... k:key each intdir:.Q.par[hsym dir;pt] each intpars; // list of table names @@ -350,50 +315,50 @@ merge:{[dir;pt;tablename;mergelimits;h] // if no table data set empty table. If data to merge, merge with correct merge function $[0 = count partdirs inter exec ptdir from .z.m.merge.getpartsizes[]; [.z.m.log[`warn][`merge;"no records for ", string[tablename]]; - (` sv dest,`) set @[.Q.en[h;value tablename];.merge.getextrapartitiontype[tablename];`p#]; + (` sv dest,`) set @[.Q.en[h;value tablename];.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];`p#]; ]; - [$[mergemethod~`part; + [$[.replay.mergemethod~`part; [dest:` sv .Q.par[h;pt;tablename],`; // provides path to where to move data to /-get chunks to partitions to merge in batch partchunks:.z.m.merge.getpartchunks[partdirs;mergelimits[tablename]]; - .z.m.merge.mergebypart[.merge.getextrapartitiontype[tablename];dest]'[partchunks]; + .z.m.merge.mergebypart[.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];dest]'[partchunks]; ]; - mergemethod~`col; + .replay.mergemethod~`col; [.z.m.merge.mergebycol[(tablename;value tablename);dest]'[partdirs]; /- merging data by column does not create .d file - set it here after merge .z.m.log[`info][`merge;"setting .d file"]; (` sv dest,`.d) set cols value tablename; ]; - .z.m.merge.mergehybrid[.merge.getextrapartitiontype[tablename];(tablename;value tablename);dest;partdirs;mergelimits[tablename]] + .z.m.merge.mergehybrid[.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];(tablename;value tablename);dest;partdirs;mergelimits[tablename]] ] ] ]; .z.m.log[`info][`merge;"deleting ", string[tablename], " from temp storage"]; - .os.deldir each .os.pth each string partdirs; + {system"rm -r ",1_string x} each partdirs; // set the attributes .z.m.log[`info][`merge;"setting attributes"]; - @[dest;;`p#] each .merge.getextrapartitiontype[tablename]; + @[dest;;`p#] each .z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename]; .z.m.log[`info][`merge;"merge complete"]; // run a garbage collection (if enabled) - if[gc;.z.m.dbw.gc[]]; + if[.replay.gc;.z.m.dbw.gc[]]; }; // Return log file if it exists and not in segmented mode -getlogfile:{ +.replay.getlogfile:{ if[.replay.segmentedmode;.z.m.log[`error][`getlogfile;m:"Segmented mode requires tplogdir."];'m]; if[()~key hsym f:.replay.tplogfile;.z.m.log[`error][`getlogfile;m:"Specified tplogfile ",string[f]," does not exist"];'m]; enlist hsym f }; // Return contents of log directory if it exists -getlogdir:{ +.replay.getlogdir:{ if[()~key hsym d:.replay.tplogdir;.z.m.log[`error][`getlogdir;m:"Specified log directory ",string[d]," does not exist"];'m]; if[d like "*.gz";.z.m.log[`error][`getlogdir;m:"Zipped log directories not supported."];'m]; $[.replay.segmentedmode;.replay.getstplogs[d];.Q.dd[logdir;] each key logdir:hsym d] }; // Use STP meta table and tplogdir to build log names -getstplogs:{[logdir] +.replay.getstplogs:{[logdir] // If trying to replay zipped files on Windows, error out winzip:(.z.o like "w*") and z:`stpmeta.gz in key d:hsym logdir; if[winzip;.z.m.log[`error][`replaylog;m:"Zipped log files cannot be directly replayed on Windows"];'m]; @@ -407,7 +372,7 @@ getstplogs:{[logdir] }; // Set up log replay list and clean HDB if necessary, kick off replay -initandrun:{ +.replay.initandrun:{ if[all not null .replay[`tplogfile`tplogdir];.z.m.log[`error][`getlogs;m:"Can't pass in log file and directory."];'m]; .z.m.log[`info][`initandrun;"Initialising replay settings."]; @@ -428,10 +393,8 @@ initandrun:{ .z.m.log[`info][`initandrun;"Replaying the following log(s): ",csv sv 1_'string .replay.logstoreplay]; .replay.pathlist:()!(); .replay.replaylog each .replay.logstoreplay; - if[sortafterreplay;applysortandattr[.replay.pathlist]]; - if[partandmerge;postreplaymerge[tempdir;.replay.replaydate;hdbdir]]; + if[.replay.sortafterreplay;.replay.applysortandattr[.replay.pathlist]]; + if[.replay.partandmerge;.replay.postreplaymerge[.replay.tempdir;.replay.replaydate;.replay.hdbdir]]; .z.m.log[`info][`replay;"replay complete"]; if[.replay.exitwhencomplete;exit 0]; }; - -\d . diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 38b6064c..dfead683 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,3 +1,8 @@ / connections only; an app clients section replaces this whole section clients:(enlist`opencloseonly)!enlist 1b zpsignore:(enlist`enabled)!enlist 0b +/ every basic-typed stplg and sctp default, so each can be overridden from the command line +/ (-.stplg., -.sctp.); must agree with the module's own defaults. kdbtplog comes from +/ the environment. An app stplg or sctp section replaces that whole section +stplg:`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv`errorlogname!(`tabperiod;0D01;1b;`defaultbatch;`day;`;`segmentederrorlogfile) +sctp:`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema!(0b;`none;`stp1;10;0W;`;`;0b;1b) diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q index ace8fcf6..e8ca6a4d 100644 --- a/di/torq/settings/tickerlogreplay.q +++ b/di/torq/settings/tickerlogreplay.q @@ -2,3 +2,6 @@ / every basic-typed replay default, so each can be overridden from the command line (-.replay.); / must agree with the module's own defaults. An app replay section replaces this whole section replay:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`tempdir`mergenumrows`mergenumbytes`mergemethod!(0;0W;0W;1b;1b;`;enlist`all;`;`;`;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`:tempmergedir;10000000;500000000;`part) +/ di.merge's mergebybytelimit and partlimit, passed to its init; must agree with di.merge's own +/ defaults. An app merge section replaces this whole section +merge:`mergebybytelimit`partlimit!(0b;1000) From d776cc17d77cddc266694b75ad35c30e350b3421 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 14:55:54 +0100 Subject: [PATCH 30/42] Flat settings for segmentedtp and tickerlogreplay; module-private replay internals Settings: - settings/segmentedtp.q, segmentedchainedtp.q and tickerlogreplay.q declare flat ns.key:value lines instead of section dicts - init replaces the section-rebind loop with an explicit presence check per key; kdbtplog, compression and mergenumtab keep their config override although the settings files don't declare them - launch flags become -stplg., -sctp., -replay.; TOML uses quoted keys ("sctp.chainedtp" = true) - mergedeps is seeded with a sentinel key: enlist of a dict is a table, so the paste's enlist[`log]!enlist form broadcast mergebybytelimit into it and every partandmerge replay died with 'type tickerlogreplay internals: - internal .replay.* functions and state drop the prefix and become module-private; .replay.merge becomes mergetable (clashes with the .z.m.merge handle) - writes inside functions go through .z.m., as does the qsql read in getstplogs - the 27 settings, the savedownmanipulation/postreplay bridge, initandrun and replaylog are unchanged Tests: - fixtures flattened mechanically; sync rows compare each flat key with .ns.key - new row: partandmerge replay with the merge keys set Suites: segmentedtp 69, tickerlogreplay 98, di.merge 238, di.torq 75. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/segmentedtp.md | 9 +- di/torq/proc/segmentedtp/segmentedtp.q | 19 +- di/torq/proc/segmentedtp/test.csv | 6 +- di/torq/proc/segmentedtp/test.q | 10 +- di/torq/proc/tickerlogreplay/test.csv | 7 +- di/torq/proc/tickerlogreplay/test.q | 4 +- .../proc/tickerlogreplay/tickerlogreplay.md | 12 +- .../proc/tickerlogreplay/tickerlogreplay.q | 202 ++++++++++-------- di/torq/settings/segmentedchainedtp.q | 8 +- di/torq/settings/segmentedtp.q | 23 +- di/torq/settings/tickerlogreplay.q | 35 ++- 11 files changed, 211 insertions(+), 124 deletions(-) diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 30a51819..5e211892 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -29,7 +29,7 @@ Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;dat ## Settings -A `stplg` section, set onto `.stplg.`: +Flat `stplg.` settings, set onto `.stplg.`: | Key | Default | |---|---| @@ -42,14 +42,13 @@ A `stplg` section, set onto `.stplg.`: | `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_` | | `errorlogname` | `` `segmentederrorlogfile `` | -A `sctp` section, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +Flat `sctp.` settings, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or `parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and `subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and -`subscribesyms` also take strings, so the section can live in a `.toml` file. +`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctp.chainedtp" = true`). `di/torq/settings/segmentedtp.q` declares every `stplg` default except `kdbtplog`, and every `sctp` default, so any of -them can be given on the command line as `-.stplg.` or `-.sctp.`; an app section replaces it, so list there -every key to override. +them can be given on the command line as `-stplg.` or `-sctp.`; an app sets only the keys it overrides. An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index a9a2ebd3..e2ff6c5b 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -17,8 +17,23 @@ init:{[config;deps] r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; - {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each `stplg`sctp; - @[`.sctp;`loggingmode`tickerplantname`subscribeto`subscribesyms;tosym]; + if[`stplg.kdbtplog in key config;.stplg.kdbtplog:tosym config`stplg.kdbtplog]; + .stplg.multilog:$[`stplg.multilog in key config;tosym config`stplg.multilog;`tabperiod]; + .stplg.multilogperiod:$[`stplg.multilogperiod in key config;config`stplg.multilogperiod;0D01]; + .stplg.errmode:$[`stplg.errmode in key config;config`stplg.errmode;1b]; + .stplg.batchmode:$[`stplg.batchmode in key config;tosym config`stplg.batchmode;`defaultbatch]; + .stplg.replayperiod:$[`stplg.replayperiod in key config;tosym config`stplg.replayperiod;`day]; + .stplg.customcsv:$[`stplg.customcsv in key config;tosym config`stplg.customcsv;`]; + .stplg.errorlogname:$[`stplg.errorlogname in key config;tosym config`stplg.errorlogname;`segmentederrorlogfile]; + .sctp.chainedtp:$[`sctp.chainedtp in key config;config`sctp.chainedtp;0b]; + .sctp.loggingmode:$[`sctp.loggingmode in key config;tosym config`sctp.loggingmode;`none]; + .sctp.tickerplantname:$[`sctp.tickerplantname in key config;tosym config`sctp.tickerplantname;`stp1]; + .sctp.tpconnsleep:$[`sctp.tpconnsleep in key config;config`sctp.tpconnsleep;10]; + .sctp.tpcheckcycles:$[`sctp.tpcheckcycles in key config;config`sctp.tpcheckcycles;0W]; + .sctp.subscribeto:$[`sctp.subscribeto in key config;tosym config`sctp.subscribeto;`]; + .sctp.subscribesyms:$[`sctp.subscribesyms in key config;tosym config`sctp.subscribesyms;`]; + .sctp.replay:$[`sctp.replay in key config;config`sctp.replay;0b]; + .sctp.schema:$[`sctp.schema in key config;config`sctp.schema;1b]; if[`createlogs in key config;set[`createlogs;config`createlogs]]; / subscribers replay from the parent's logs if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index bb467fee..f8dc8a62 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -10,9 +10,9 @@ fail,0,0,q,"seg.init[()!();enlist[`log]!enlist nolog]",1,,init without timer mus fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]})]",1,,init without handlers must error true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~.stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv",1,,stplg defaults true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~.sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema",1,,sctp defaults -true,0,0,q,"{x~(key x)#.stplg}((use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]`stplg)",1,,the shipped stplg section declares the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{x~(key x)#.sctp}((use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]`sctp)",1,,the shipped sctp section declares the module's own defaults -true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,a stplg section overrides the defaults; singular rolls daily +true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""stplg.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped stplg keys declare the module's own defaults (so each is overridable from the command line) +true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""sctp.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped sctp keys declare the module's own defaults +true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered true,0,0,q,"`stplg in ha""exec name from h.list`.z.exit""",1,,.z.exit observer registered diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index ca3308e1..749ed292 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -13,11 +13,11 @@ PORTS:`a`b`c`s`p!5#0N / a: defaultbatch, tabperiod; b: immediate, singular; c: memorybatch, tabular; s: chained, create; p: chained, parent, TOML-style strings CFGS:`a`b`c`s`p!( - "`procname`schemafile`stplg!(`stp1;FIXDIR,\"/schema.q\";enlist[`kdbtplog]!enlist`$FIXDIR,\"/a\")"; - "`procname`schemafile`stplg!(`stp2;FIXDIR,\"/schema.q\";`kdbtplog`batchmode`multilog!(`$FIXDIR,\"/b\";`immediate;`singular))"; - "`procname`schemafile`stplg!(`stp3;FIXDIR,\"/schema.q\";`kdbtplog`batchmode`multilog!(`$FIXDIR,\"/c\";`memorybatch;`tabular))"; - "`procname`createlogs`autoreconnect`stplg`sctp!(`sctp1;0b;0b;enlist[`kdbtplog]!enlist`$FIXDIR,\"/s\";`chainedtp`loggingmode!(1b;`create))"; - "`procname`createlogs`autoreconnect`stplg`sctp!(`sctp2;0b;0b;enlist[`kdbtplog]!enlist`$FIXDIR,\"/p\";`chainedtp`loggingmode`tickerplantname`subscribeto!(1b;\"parent\";\"stp1\";\"\"))") + "`procname`schemafile`stplg.kdbtplog!(`stp1;FIXDIR,\"/schema.q\";`$FIXDIR,\"/a\")"; + "`procname`schemafile`stplg.kdbtplog`stplg.batchmode`stplg.multilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; + "`procname`schemafile`stplg.kdbtplog`stplg.batchmode`stplg.multilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; + "`procname`createlogs`autoreconnect`stplg.kdbtplog`sctp.chainedtp`sctp.loggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; + "`procname`createlogs`autoreconnect`stplg.kdbtplog`sctp.chainedtp`sctp.loggingmode`sctp.tickerplantname`sctp.subscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index 8cb4d46c..fea0bd76 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -6,8 +6,8 @@ before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmented comment,,,,,,,settings true,0,0,q,"(0;1b;1b;0W;0W;enlist`all;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`part)~.replay`firstmessage`segmentedmode`autoreplay`lastmessage`messagechunks`tablelist`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`mergemethod",1,,replay defaults true,0,0,q,`:tempmergedir~.replay.tempdir,1,,tempdir default -true,0,0,q,"{x~(key x)#.replay}((use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]`replay)",1,,the shipped replay section declares the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~value x}((use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]`merge)",1,,the shipped merge section declares di.merge's own defaults +true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""replay.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped replay keys declare the module's own defaults (so each is overridable from the command line) +true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~x`merge.mergebybytelimit`merge.partlimit}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped merge keys declare di.merge's own defaults true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error @@ -80,6 +80,9 @@ run,0,0,q,clearhdb[],1,, true,0,0,q,"0=replay sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`hybrid)""",1,,hybrid merge true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym true,0,0,q,"0=count key fp""tmp""",1,,the temp partition was removed +run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay ""("",(sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`part)""),""),`merge.mergebybytelimit`merge.partlimit!(0b;1000)""",1,,merge with the merge keys set +true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym comment,,,,,,,segmented logs run,0,0,q,clearhdb[],1,, diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index b76c2def..8e603c93 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -18,7 +18,7 @@ replayp:{[pre;cfg] runq( replay:replayp[()] / replay settings for the plain log, with overrides plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} -sect:{[x] "enlist[`replay]!enlist ",x} +sect:{[x] "{(`$\"replay.\",/:string key x)!value x}",x} ran:{[x] read0 fp"run.log"} logged:{[s] any ran[] like s} / was a log named in the list of logs to replay @@ -49,7 +49,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[`proctype`procname`schemafile`stplg!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";enlist[`kdbtplog]!enlist`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + "seg.init[`proctype`procname`schemafile`stplg.kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; ".u.upd[`quote;(enlist`a;enlist 3f)]"; ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index f5a6be39..e3ddeb97 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -22,7 +22,7 @@ at the end, or partition to a temporary directory and merge on disk. ## Settings -A `replay` section, set onto `.replay.`: +Flat `replay.` settings, set onto `.replay.`: | Key | Default | |---|---| @@ -46,11 +46,11 @@ A `replay` section, set onto `.replay.`: | `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist`, `partitiontype`, `sortcsv`, -`tempdir`, `mergemethod`) also take strings, so the section can live in a `.toml` file. `di/torq/settings/tickerlogreplay.q` -declares every default, so any key can be given on the command line as `-.replay.`, as in TorQ; an app -`replay` section replaces it, so list there every key to override. +`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file as quoted keys (`"replay.hdbdir" = "hdb"`). +`di/torq/settings/tickerlogreplay.q` declares every default except `compression` and `mergenumtab`, so any of them +can be given on the command line as `-replay.`; an app sets only the keys it overrides. -A `merge` section (`mergebybytelimit`, `partlimit`) is passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` +`merge.mergebybytelimit` and `merge.partlimit` are passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` declares its defaults. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. ## init[config;deps] @@ -63,7 +63,7 @@ Requires `log`. It: `messagechunks`, a message range in segmented mode, or `partandmerge` into `hdbdir`; - code 2 for zero `messagechunks` or a schema file that fails to load; 3. loads the schema file at root; -4. wraps `.replay.realupd` to filter on `tablelist` (plain logs) and to save every `messagechunks` messages; +4. wraps `realupd` to filter on `tablelist` (plain logs) and to save every `messagechunks` messages; 5. loads `sortcsv`, or `sort.csv`, into di.dbwrite; 6. replays when `autoreplay`. diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 4b0dd265..abaa73dc 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,11 +18,39 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - {[c;ns] if[ns in key c;(` sv' (`$".",string ns),'key c ns) set' value c ns]}[config] each enlist`replay; - @[`.replay;`schemafile`hdbdir`tplogdir`tplogfile`tablelist`partitiontype`sortcsv`tempdir`mergemethod;tosym]; + if[`replay.firstmessage in key config;.replay.firstmessage:config`replay.firstmessage]; + if[`replay.lastmessage in key config;.replay.lastmessage:config`replay.lastmessage]; + if[`replay.messagechunks in key config;.replay.messagechunks:config`replay.messagechunks]; + if[`replay.segmentedmode in key config;.replay.segmentedmode:config`replay.segmentedmode]; + if[`replay.autoreplay in key config;.replay.autoreplay:config`replay.autoreplay]; + if[`replay.schemafile in key config;.replay.schemafile:tosym config`replay.schemafile]; + if[`replay.tablelist in key config;.replay.tablelist:tosym config`replay.tablelist]; + if[`replay.hdbdir in key config;.replay.hdbdir:tosym config`replay.hdbdir]; + if[`replay.tplogfile in key config;.replay.tplogfile:tosym config`replay.tplogfile]; + if[`replay.tplogdir in key config;.replay.tplogdir:tosym config`replay.tplogdir]; + if[`replay.partitiontype in key config;.replay.partitiontype:tosym config`replay.partitiontype]; + if[`replay.emptytables in key config;.replay.emptytables:config`replay.emptytables]; + if[`replay.sortafterreplay in key config;.replay.sortafterreplay:config`replay.sortafterreplay]; + if[`replay.basicmode in key config;.replay.basicmode:config`replay.basicmode]; + if[`replay.exitwhencomplete in key config;.replay.exitwhencomplete:config`replay.exitwhencomplete]; + if[`replay.checklogfiles in key config;.replay.checklogfiles:config`replay.checklogfiles]; + if[`replay.gc in key config;.replay.gc:config`replay.gc]; + if[`replay.clean in key config;.replay.clean:config`replay.clean]; + if[`replay.sortcsv in key config;.replay.sortcsv:tosym config`replay.sortcsv]; + if[`replay.partandmerge in key config;.replay.partandmerge:config`replay.partandmerge]; + if[`replay.tempdir in key config;.replay.tempdir:tosym config`replay.tempdir]; + if[`replay.mergenumrows in key config;.replay.mergenumrows:config`replay.mergenumrows]; + if[`replay.mergenumbytes in key config;.replay.mergenumbytes:config`replay.mergenumbytes]; + if[`replay.mergemethod in key config;.replay.mergemethod:tosym config`replay.mergemethod]; + if[`replay.compression in key config;.replay.compression:config`replay.compression]; + if[`replay.mergenumtab in key config;.replay.mergenumtab:config`replay.mergenumtab]; .replay.tablelist:(),.replay.tablelist; .z.m.merge:use`di.merge; - .z.m.merge.init (enlist[`log]!enlist deps`log),$[`merge in key config;config`merge;()!()]; + / sentinel keeps the values general; enlist of a dict is a table + mergedeps:``log!(::;deps`log); + if[`merge.mergebybytelimit in key config;mergedeps[`mergebybytelimit]:config`merge.mergebybytelimit]; + if[`merge.partlimit in key config;mergedeps[`partlimit]:config`merge.partlimit]; + .z.m.merge.init mergedeps _ `; / some variables must be set exitifnull each `.replay.schemafile`.replay.hdbdir, $[all null .replay`tplogdir`tplogfile; `.replay.tplogfile; ()]; if[.replay.basicmode and (.replay.messagechunks within (0;-1 + 0W)); @@ -30,8 +58,8 @@ init:{[config;deps] if[not .replay.partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; if[.replay.messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; if[.replay.segmentedmode and ((0<>.replay.firstmessage) or 0W<>.replay.lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode";1]]; - .replay.trackonly:.replay.messagechunks < 0; - if[.replay.trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; + .z.m.trackonly:.replay.messagechunks < 0; + if[trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; .replay.messagechunks:abs .replay.messagechunks; if[.replay.partandmerge and .replay.hdbdir = .replay.tempdir;ex[`replayinit;"if using partandmerge replay, tempdir must be set to a different directory than the hdb";1]]; if[.replay.partandmerge and .replay.sortafterreplay;(.replay.sortafterreplay:0b; .z.m.log[`info][`replayinit;"Setting sortafterreplay to 0b"])]; @@ -41,9 +69,9 @@ init:{[config;deps] .z.m.log[`info][`replayinit;"hdb directory is set to ",string .replay.hdbdir:hsym .replay.hdbdir]; .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .replay.tempdir:hsym .replay.tempdir]; / filter on the table list - if[(not .replay.tablelist~enlist `all) and not .replay.segmentedmode; .replay.realupd:{[f;t;x] if[t in .replay.tablestoreplay; f[t;x]]}[.replay.realupd]]; + if[(not .replay.tablelist~enlist `all) and not .replay.segmentedmode; .z.m.realupd:{[f;t;x] if[t in tablestoreplay; f[t;x]]}[realupd]]; / chunked saves - if[.replay.messagechunks < 0W; .replay.realupd:{[f;t;x] f[t;x]; .replay.checkcount[.replay.hdbdir;.replay.replaydate;1;.replay.tempdir]}[.replay.realupd]]; + if[.replay.messagechunks < 0W; .z.m.realupd:{[f;t;x] f[t;x]; checkcount[.replay.hdbdir;replaydate;1;.replay.tempdir]}[realupd]]; / load the sort csv and kick off replay if auto-running $[null .replay.sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv .replay.sortcsv]; if[.replay.autoreplay;.replay.initandrun[]]; @@ -99,97 +127,97 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] .save.postreplay:@[value;`.replay.postreplay;{{[d;p] }}] // invoked after a log's tables are saved // the path to the table to save -.replay.pathtotable:{[h;p;t] `$(string .Q.par[h;.replay.partitiontype$p;t]),"/"} +pathtotable:{[h;p;t] `$(string .Q.par[h;.replay.partitiontype$p;t]),"/"} // create empty tables - we need to make sure we only create them once -.replay.emptytabs:`symbol$() -.replay.createemptytable:{[h;p;t;td] +emptytabs:`symbol$() +createemptytable:{[h;p;t;td] $[.replay.partandmerge;dest:td;dest:h]; - if[(not (path:.replay.pathtotable[dest;p;t]) in .replay.emptytabs) and .replay.emptytables; + if[(not (path:pathtotable[dest;p;t]) in emptytabs) and .replay.emptytables; .z.m.log[`info][`replay;"creating empty table ",(string t)," at ",string path]; - .replay.emptytabs,:path; - .replay.savetabdatatrapped[h;p;t;0#value t;0b;td]]} + .z.m.emptytabs,:path; + savetabdatatrapped[h;p;t;0#value t;0b;td]]} -.replay.savetabdata:{[h;p;t;data;UPSERT;td] - $[.replay.partandmerge;path:.replay.pathtotable[td;p;t];path:.replay.pathtotable[h;p;t]]; +savetabdata:{[h;p;t;data;UPSERT;td] + $[.replay.partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; if[not .replay.partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; - .replay.pathlist[t],:path; - $[.replay.partandmerge;.replay.savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + .z.m.pathlist[t],:path; + $[.replay.partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] } -.replay.savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[.replay.savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} +savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} // this function should be invoked for saving tables -.replay.savetab:{[td;h;p;t] - if[not .replay.partandmerge;.replay.createemptytable[h;p;t;td]]; +savetab:{[td;h;p;t] + if[not .replay.partandmerge;createemptytable[h;p;t;td]]; if[count value t; .z.m.log[`info][`replay;"saving ",(string t)," which has row count ",string count value t]; - .replay.savetabdatatrapped[h;p;t;value t;1b;td]; + savetabdatatrapped[h;p;t;value t;1b;td]; delete from t; if[.replay.gc;.z.m.dbw.gc[]]]} // apply the sorting and attributes at the end of the replay, from tablename!(list of paths) -.replay.applysortandattr:{[pathlist] +applysortandattr:{[pathlist] {.z.m.dbw.sort . x} each flip (key;value) @\: distinct each pathlist }; // table names in count order, smallest first -.replay.tabsincountorder:{x iasc count each value each x} +tabsincountorder:{x iasc count each value each x} // check if the count has been exceeded, and save down if it has -.replay.currentcount:0 -.replay.totalcount:0 -.replay.checkcount:{[h;p;counter;td] - .replay.currentcount+:counter; - if[.replay.currentcount >= .replay.messagechunks; - $[.replay.trackonly; - [.replay.totalcount +: .replay.currentcount; - .z.m.log[`info][`replay;"replayed a chunk of ",(string .replay.messagechunks)," messages. Total message count so far is ",string .replay.totalcount]]; +currentcount:0 +totalcount:0 +checkcount:{[h;p;counter;td] + .z.m.currentcount+:counter; + if[currentcount >= .replay.messagechunks; + $[trackonly; + [.z.m.totalcount +: currentcount; + .z.m.log[`info][`replay;"replayed a chunk of ",(string .replay.messagechunks)," messages. Total message count so far is ",string totalcount]]; [.z.m.log[`info][`replay;"number of messages to replay at once (",(string .replay.messagechunks),") has been exceeded. Saving down"]; - .replay.savetab[td;h;p] each .replay.tabsincountorder[.replay.tablestoreplay]; + savetab[td;h;p] each tabsincountorder[tablestoreplay]; .z.m.log[`info][`replay;"save complete- replaying next chunk of data"]]]; - .replay.currentcount:0]} + .z.m.currentcount:0]} // function used to finish off the replay -.replay.finishreplay:{[h;p;td] +finishreplay:{[h;p;td] // save down any tables which haven't been saved - .replay.savetab[td;h;p] each .replay.tabsincountorder[.replay.tablestoreplay]; + savetab[td;h;p] each tabsincountorder[tablestoreplay]; // invoke any user defined post replay function .save.postreplay[h;p]; } // takes in log file directories made with segmented tickerplant -.replay.expandstplogs:{[logdirectories] // always a list +expandstplogs:{[logdirectories] // always a list {` sv'raze x,/:'key each x}$[`~.replay.tplogdir;{enlist first x};]hsym logdirectories }; .replay.replaylog:{[logfile] // set the upd function to be the initialupd function - .replay.msgcount:.replay.currentcount:.replay.totalcount:0; + .z.m.msgcount:.z.m.currentcount:.z.m.totalcount:0; // check if logfile is corrupt if[.replay.checklogfiles; logfile: .z.m.tplog.check[logfile;.replay.lastmessage]]; $[.replay.firstmessage>0; [.z.m.log[`info][`replay;"skipping first ",(string .replay.firstmessage)," messages"]; - @[`.;`upd;:;.replay.initialupd]]; - @[`.;`upd;:;.replay.realupd]]; - .replay.tablecounts:.replay.errorcounts:()!(); + @[`.;`upd;:;initialupd]]; + @[`.;`upd;:;realupd]]; + .z.m.tablecounts:.z.m.errorcounts:()!(); // If not running in segmented mode, reset replay date and clean HDB directory on each loop - .replay.zipped:$[logfile like "*.gz";1b;0b]; + .z.m.zipped:$[logfile like "*.gz";1b;0b]; if[not .replay.segmentedmode; // Pull out date from TP log file name - *YYYY.MM.DD (+ .gz if zipped) - .replay.replaydate:"D"$$[.replay.zipped;-3_-13#;-10#] string logfile; - if[.replay.clean;.replay.cleanhdb .replay.replaydate] + .z.m.replaydate:"D"$$[zipped;-3_-13#;-10#] string logfile; + if[.replay.clean;cleanhdb replaydate] ]; if[.replay.lastmessage<.replay.firstmessage; .z.m.log[`info][`replay;"lastmessage (",(string .replay.lastmessage),") is less than firstmessage (",(string .replay.firstmessage),"). Not replaying log file"]; :()]; .z.m.log[`info][`replay;"replaying data from logfile ",(string logfile)," from message ",(string .replay.firstmessage)," to ",(string .replay.lastmessage),". Message indices are from 0 and inclusive - so both the first and last message will be replayed"]; // when we do the replay, need to move the indexing, otherwise we won't replay the last message correctly - .replay.replayinner[.replay.lastmessage+.replay.lastmessage<0W;logfile]; + replayinner[.replay.lastmessage+.replay.lastmessage<0W;logfile]; - .z.m.log[`info][`replay;"replayed data into tables with the following counts: ","; " sv {" = " sv string x}@'flip(key .replay.tablecounts;value .replay.tablecounts)]; - if[count .replay.errorcounts; - .z.m.log[`error][`replay;"errors were hit when replaying the following tables: ","; " sv {" = " sv string x}@'flip(key .replay.errorcounts;value .replay.errorcounts)]]; + .z.m.log[`info][`replay;"replayed data into tables with the following counts: ","; " sv {" = " sv string x}@'flip(key tablecounts;value tablecounts)]; + if[count errorcounts; + .z.m.log[`error][`replay;"errors were hit when replaying the following tables: ","; " sv {" = " sv string x}@'flip(key errorcounts;value errorcounts)]]; // set compression level if[3=count .replay.compression; .z.m.log[`info][`compression;"setting compression level to (",(";" sv string .replay.compression),")"]; @@ -198,33 +226,33 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] $[.replay.basicmode; [.z.m.log[`info][`replay;"basicmode set to true, saving down tables with .Q.hdpf"]; - .Q.hdpf[`::;.replay.hdbdir;.replay.partitiontype$.replay.replaydate;`sym]]; + .Q.hdpf[`::;.replay.hdbdir;.replay.partitiontype$replaydate;`sym]]; // if not in basic mode, then we need to finish off the replay - .replay.finishreplay[.replay.hdbdir;.replay.replaydate;.replay.tempdir]]; + finishreplay[.replay.hdbdir;replaydate;.replay.tempdir]]; if[.replay.gc;.z.m.dbw.gc[]]; } // If replay date in HDB, delete tables/partition from the HDB so no data is duplicated -.replay.cleanhdb:{[dt] +cleanhdb:{[dt] if[not (`$sd:string dt) in key .replay.hdbdir;.z.m.log[`info][`cleanhdb;"Date ",sd," not in HDB."];:()]; - delpaths:1_'string .Q.par[.replay.hdbdir;dt;] each $[`all~first .replay.tablelist;enlist `;.replay.tablestoreplay]; + delpaths:1_'string .Q.par[.replay.hdbdir;dt;] each $[`all~first .replay.tablelist;enlist `;tablestoreplay]; {.z.m.log[`info][`cleanhdb;"Deleting ",x," from HDB."];system"rm -r ",x} each delpaths; }; // Replay log file, if file is zipped and the kdb+ version is at least 4.0 then replay through named pipe -.replay.replayinner:{[msgnum;logfile] - if[not .replay.zipped;-11!(msgnum;logfile);:()]; +replayinner:{[msgnum;logfile] + if[not zipped;-11!(msgnum;logfile);:()]; if[not .z.o like "l*";.z.m.log[`error][`replaylog;m:"Zipped log files can only be directly replayed on Linux systems"];'m]; if[.z.K<4.0;.z.m.log[`error][`replaylog;m:"Zipped log files can only be directly replayed on kdb+ 4.0 or higher"];'m]; .z.m.log[`info][`replay;"Replaying logfile ",(f:1_string logfile)," over named pipe"]; - -11!(msgnum;hsym `$fifo:.replay.readintofifo f); + -11!(msgnum;hsym `$fifo:readintofifo f); system "rm -f ",fifo; - .replay.zipped:0b; + .z.m.zipped:0b; }; // Create FIFO and unzip file into it, return FIFO name -.replay.readintofifo:{[filename] +readintofifo:{[filename] fifo:"/tmp/logfifo",string .z.i; fifostr:"mkfifo ",fifo,";gunzip -cd ",filename," > ",fifo," &"; @[system;fifostr;{.z.m.log[`error][`replay;"Failed to read log into named pipe"]}]; @@ -232,39 +260,39 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] }; // upd functions down here -.replay.realupd:{[f;t;x] +realupd:{[f;t;x] // increment the tablecounts - .replay.tablecounts[t]+:count first x; + .z.m.tablecounts[t]+:count first x; // run the supplied function in the error trap - .[f;(t;x);{[t;x;e] .replay.errorcounts[t]+:count first x}[t;x]]; + .[f;(t;x);{[t;x;e] .z.m.errorcounts[t]+:count first x}[t;x]]; }[.replay.upd] -.replay.initialupd:{[t;x] +initialupd:{[t;x] // spin through the first X messages - $[.replay.msgcount < (.replay.firstmessage - 1); - .replay.msgcount+:1; + $[msgcount < (.replay.firstmessage - 1); + .z.m.msgcount+:1; // Once we reach the correct message, reset the upd function - @[`.;`upd;:;.replay.realupd]] + @[`.;`upd;:;realupd]] } // extract user defined row counts -.replay.mergemaxrows:{[tabname] .replay.mergenumrows^.replay.mergenumtab[tabname]}; +mergemaxrows:{[tabname] .replay.mergenumrows^.replay.mergenumtab[tabname]}; // post replay function for merge replay, invoked after all the tables have been written down for a given log file -.replay.postreplaymerge:{[td;p;h] +postreplaymerge:{[td;p;h] system"mkdir -p ",1_string .Q.par[td;p;`]; // ensures directory exists before removed - mergelimits:(.replay.tabsincountorder[.replay.tablestoreplay],())!$[.z.m.merge.getmergebybytelimit[];(count .replay.tabsincountorder[.replay.tablestoreplay])#.replay.mergenumbytes;({[x] .replay.mergenumrows^.replay.mergemaxrows[x]}.replay.tabsincountorder[.replay.tablestoreplay])],(); + mergelimits:(tabsincountorder[tablestoreplay],())!$[.z.m.merge.getmergebybytelimit[];(count tabsincountorder[tablestoreplay])#.replay.mergenumbytes;({[x] .replay.mergenumrows^mergemaxrows[x]}tabsincountorder[tablestoreplay])],(); // merge the tables from each partition in the tempdir together - .replay.merge[td;p;;mergelimits;h] each .replay.tabsincountorder[.replay.tablestoreplay]; + mergetable[td;p;;mergelimits;h] each tabsincountorder[tablestoreplay]; system"rm -r ",1_string .Q.par[td;p;`]; // delete the contents of tempdir after merge completion } // function to upsert to specified directory -.replay.upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] +upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] dirpar:.Q.par[dir;pt;`$string first expt]; directory:` sv dirpar,tablename,`; // make directories for tables if they don't exist - if[count tabpar:.replay.tabsincountorder[.replay.tablestoreplay] except key dirpar; + if[count tabpar:tabsincountorder[tablestoreplay] except key dirpar; .z.m.log[`info][`dir;"creating directories under ",1_string dirpar]; tabpar:tabpar except `heartbeat`logmsg; .[{[d;h;t](` sv d,t,`) set .Q.en[h;0#value t]};] each dirpar,'h,'tabpar]; @@ -277,7 +305,7 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] .z.m.merge.trackpartition[first ` vs directory;count r;-22!r]; }; -.replay.savetablesbypart:{[dir;pt;tablename;h] +savetablesbypart:{[dir;pt;tablename;h] arows: count value tablename; .z.m.log[`info][`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; // get additional partition(s) defined by parted attribute in sort.csv @@ -292,7 +320,7 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; // upsert data to specific partition directory - .replay.upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; + upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; // empty the table .z.m.log[`info][`delete;"deleting ",(string tablename)," data from in-memory table"]; @[`.;tablename;0#]; @@ -301,7 +329,7 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] }; -.replay.merge:{[dir;pt;tablename;mergelimits;h] +mergetable:{[dir;pt;tablename;mergelimits;h] // get int partitions intpars:asc key ` sv dir,`$string pt; // list of enumerated partitions 0 1 2 3... k:key each intdir:.Q.par[hsym dir;pt] each intpars; // list of table names @@ -344,21 +372,21 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] }; // Return log file if it exists and not in segmented mode -.replay.getlogfile:{ +getlogfile:{ if[.replay.segmentedmode;.z.m.log[`error][`getlogfile;m:"Segmented mode requires tplogdir."];'m]; if[()~key hsym f:.replay.tplogfile;.z.m.log[`error][`getlogfile;m:"Specified tplogfile ",string[f]," does not exist"];'m]; enlist hsym f }; // Return contents of log directory if it exists -.replay.getlogdir:{ +getlogdir:{ if[()~key hsym d:.replay.tplogdir;.z.m.log[`error][`getlogdir;m:"Specified log directory ",string[d]," does not exist"];'m]; if[d like "*.gz";.z.m.log[`error][`getlogdir;m:"Zipped log directories not supported."];'m]; - $[.replay.segmentedmode;.replay.getstplogs[d];.Q.dd[logdir;] each key logdir:hsym d] + $[.replay.segmentedmode;getstplogs[d];.Q.dd[logdir;] each key logdir:hsym d] }; // Use STP meta table and tplogdir to build log names -.replay.getstplogs:{[logdir] +getstplogs:{[logdir] // If trying to replay zipped files on Windows, error out winzip:(.z.o like "w*") and z:`stpmeta.gz in key d:hsym logdir; if[winzip;.z.m.log[`error][`replaylog;m:"Zipped log files cannot be directly replayed on Windows"];'m]; @@ -367,7 +395,7 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] if[z;system "gunzip ",1_string .Q.dd[d;`stpmeta.gz]]; metatable:@[get;.Q.dd[d;`stpmeta];{.z.m.log[`error][`getstpmeta;m:"Log directory must contain valid STP meta table"];'m}]; if[z;system "gzip ",1_string .Q.dd[d;`stpmeta]]; - names:exec distinct logname from metatable where any each tbls in .replay.tablestoreplay; + names:exec distinct logname from metatable where any each tbls in .z.m.tablestoreplay; .Q.dd[d;] each $[z;.Q.dd[;`gz];::] each last each ` vs' names }; @@ -376,25 +404,25 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] if[all not null .replay[`tplogfile`tplogdir];.z.m.log[`error][`getlogs;m:"Can't pass in log file and directory."];'m]; .z.m.log[`info][`initandrun;"Initialising replay settings."]; - .replay.tablestoreplay:$[`all~first .replay.tablelist;tables[];.replay.tablelist,()]; - .replay.logstoreplay:$[not null .replay.tplogfile;.replay.getlogfile[];.replay.getlogdir[]]; - if[not count r:.replay.logstoreplay;.z.m.log[`error][`initandrun;m:"No log files found"];'m]; + .z.m.tablestoreplay:$[`all~first .replay.tablelist;tables[];.replay.tablelist,()]; + .z.m.logstoreplay:$[not null .replay.tplogfile;getlogfile[];getlogdir[]]; + if[not count r:logstoreplay;.z.m.log[`error][`initandrun;m:"No log files found"];'m]; // If in segmented mode, get replay date and clean HDB once if[.replay.segmentedmode; // Pull out the date from the STP log file name - *_YYYYMMDDhhmmss (+ .gz if zipped) - .replay.replaydate:first l:"D"$$[first[r] like "*.gz";-9_-17#;-6_-14#] each string r; + .z.m.replaydate:first l:"D"$$[first[r] like "*.gz";-9_-17#;-6_-14#] each string r; if[not 1=count distinct l;.z.m.log[`error][`replay;m:"Cannot replay logs from different dates in segmented mode!"];'m]; - if[.replay.clean;.replay.cleanhdb .replay.replaydate] + if[.replay.clean;cleanhdb replaydate] ]; // Replay all logs and exit - .z.m.log[`info][`initandrun;"Replaying the following log(s): ",csv sv 1_'string .replay.logstoreplay]; - .replay.pathlist:()!(); - .replay.replaylog each .replay.logstoreplay; - if[.replay.sortafterreplay;.replay.applysortandattr[.replay.pathlist]]; - if[.replay.partandmerge;.replay.postreplaymerge[.replay.tempdir;.replay.replaydate;.replay.hdbdir]]; + .z.m.log[`info][`initandrun;"Replaying the following log(s): ",csv sv 1_'string logstoreplay]; + .z.m.pathlist:()!(); + .replay.replaylog each logstoreplay; + if[.replay.sortafterreplay;applysortandattr[pathlist]]; + if[.replay.partandmerge;postreplaymerge[.replay.tempdir;replaydate;.replay.hdbdir]]; .z.m.log[`info][`replay;"replay complete"]; if[.replay.exitwhencomplete;exit 0]; }; diff --git a/di/torq/settings/segmentedchainedtp.q b/di/torq/settings/segmentedchainedtp.q index 580c6bfd..2742020c 100644 --- a/di/torq/settings/segmentedchainedtp.q +++ b/di/torq/settings/segmentedchainedtp.q @@ -1,7 +1,13 @@ / chained segmented tickerplant settings / sctp logging is set by loggingmode, not createlogs createlogs:0b -sctp:`chainedtp`loggingmode`tickerplantname`subscribeto`subscribesyms`replay`schema!(1b;`none;`stp1;`;`;0b;1b) +sctp.chainedtp:1b +sctp.loggingmode:`none +sctp.tickerplantname:`stp1 +sctp.subscribeto:` +sctp.subscribesyms:` +sctp.replay:0b +sctp.schema:1b connections:enlist`segmentedtp / connections only; an app clients section replaces this whole section clients:(enlist`opencloseonly)!enlist 1b diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index dfead683..3d958e2d 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,8 +1,21 @@ / connections only; an app clients section replaces this whole section clients:(enlist`opencloseonly)!enlist 1b zpsignore:(enlist`enabled)!enlist 0b -/ every basic-typed stplg and sctp default, so each can be overridden from the command line -/ (-.stplg., -.sctp.); must agree with the module's own defaults. kdbtplog comes from -/ the environment. An app stplg or sctp section replaces that whole section -stplg:`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv`errorlogname!(`tabperiod;0D01;1b;`defaultbatch;`day;`;`segmentederrorlogfile) -sctp:`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema!(0b;`none;`stp1;10;0W;`;`;0b;1b) +/ every basic-typed stplg and sctp default as a flat key, so each can be overridden from the command line +/ (-stplg., -sctp.); must agree with the module's own defaults. kdbtplog comes from the environment +stplg.multilog:`tabperiod +stplg.multilogperiod:0D01 +stplg.errmode:1b +stplg.batchmode:`defaultbatch +stplg.replayperiod:`day +stplg.customcsv:` +stplg.errorlogname:`segmentederrorlogfile +sctp.chainedtp:0b +sctp.loggingmode:`none +sctp.tickerplantname:`stp1 +sctp.tpconnsleep:10 +sctp.tpcheckcycles:0W +sctp.subscribeto:` +sctp.subscribesyms:` +sctp.replay:0b +sctp.schema:1b diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q index e8ca6a4d..49dab626 100644 --- a/di/torq/settings/tickerlogreplay.q +++ b/di/torq/settings/tickerlogreplay.q @@ -1,7 +1,30 @@ / tickerlogreplay settings -/ every basic-typed replay default, so each can be overridden from the command line (-.replay.); -/ must agree with the module's own defaults. An app replay section replaces this whole section -replay:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`tempdir`mergenumrows`mergenumbytes`mergemethod!(0;0W;0W;1b;1b;`;enlist`all;`;`;`;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`:tempmergedir;10000000;500000000;`part) -/ di.merge's mergebybytelimit and partlimit, passed to its init; must agree with di.merge's own -/ defaults. An app merge section replaces this whole section -merge:`mergebybytelimit`partlimit!(0b;1000) +/ every basic-typed replay default as a flat key, so each can be overridden from the command line +/ (-replay.); must agree with the module's own defaults +replay.firstmessage:0 +replay.lastmessage:0W +replay.messagechunks:0W +replay.segmentedmode:1b +replay.autoreplay:1b +replay.schemafile:` +replay.tablelist:enlist`all +replay.hdbdir:` +replay.tplogfile:` +replay.tplogdir:` +replay.partitiontype:`date +replay.emptytables:1b +replay.sortafterreplay:1b +replay.basicmode:0b +replay.exitwhencomplete:1b +replay.checklogfiles:0b +replay.gc:1b +replay.clean:1b +replay.sortcsv:` +replay.partandmerge:0b +replay.tempdir:`:tempmergedir +replay.mergenumrows:10000000 +replay.mergenumbytes:500000000 +replay.mergemethod:`part +/ di.merge's mergebybytelimit and partlimit, passed to its init; must agree with di.merge's own defaults +merge.mergebybytelimit:0b +merge.partlimit:1000 From 1bcbf7628ab5e5702eb90e2ae31affc1e8360fe4 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 16:02:15 +0100 Subject: [PATCH 31/42] Underscore flat settings keys; segmentedchainedtp shares segmentedtp's settings tier Flat keys: - the flat settings keys use _ instead of . (stplg_multilog, sctp_chainedtp, replay_firstmessage, merge_partlimit), matching the single-token identifiers in the sibling settings files - launch flags are -stplg_, -sctp_, -replay_ - init checks, test fixtures, sync rows and docs follow; the .stplg/.sctp/.replay namespace paths are unchanged - the config.md .section.key example now uses an existing dict section Settings tier: - torq.q passes segmentedtp as the cascade proctype for segmentedchainedtp (both roots); dispatch and the identity stamp keep the real proctype - settings/segmentedchainedtp.q is deleted; the chained behaviour comes from the instance's own settings - torq.md updated di.torq.servers: - init converts CONNECTIONS to symbols, as startup already did. A TOML connections list arrives as strings, and processes that only reach startup through startupdepnamecycles (segmentedtp) kept them, so sctp1 never found stp1 - new test row Suites: di.torq 75, segmentedtp 69, tickerlogreplay 98, servers 58. Co-Authored-By: Claude Opus 5.5 --- di/torq/config/config.md | 2 +- di/torq/proc/segmentedtp/segmentedtp.md | 10 ++-- di/torq/proc/segmentedtp/segmentedtp.q | 34 +++++------ di/torq/proc/segmentedtp/test.csv | 4 +- di/torq/proc/segmentedtp/test.q | 10 ++-- di/torq/proc/tickerlogreplay/test.csv | 6 +- di/torq/proc/tickerlogreplay/test.q | 4 +- .../proc/tickerlogreplay/tickerlogreplay.md | 8 +-- .../proc/tickerlogreplay/tickerlogreplay.q | 56 +++++++++---------- di/torq/servers/servers.q | 2 + di/torq/servers/test.csv | 2 + di/torq/settings/segmentedchainedtp.q | 14 ----- di/torq/settings/segmentedtp.q | 34 +++++------ di/torq/settings/tickerlogreplay.q | 54 +++++++++--------- di/torq/torq.md | 5 +- di/torq/torq.q | 4 +- 16 files changed, 121 insertions(+), 128 deletions(-) delete mode 100644 di/torq/settings/segmentedchainedtp.q diff --git a/di/torq/config/config.md b/di/torq/config/config.md index cdee06af..3ee5a412 100644 --- a/di/torq/config/config.md +++ b/di/torq/config/config.md @@ -103,7 +103,7 @@ first — di.torq.config does no wrapping. |---|---|---| | `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | -| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.replay.tplogdir x`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | +| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.clients.opencloseonly 0`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | | `getapimeta` | `getapimeta[]` | This module's API metadata — one `(name;public;descrip;params;return)` row per exported function, for `di.torq` to register with `di.api`. | diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 5e211892..411b7793 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -1,7 +1,7 @@ # di.torq.proc.segmentedtp A segmented tickerplant. It stamps and logs incoming updates, per table and per period, and publishes them to -subscribers, filtered or not, immediately or in batches. With `sctp.chainedtp` on, it runs as a chained segmented +subscribers, filtered or not, immediately or in batches. With `sctp_chainedtp` on, it runs as a chained segmented tickerplant: it subscribes to another one and republishes what it receives. ## Files @@ -29,7 +29,7 @@ Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;dat ## Settings -Flat `stplg.` settings, set onto `.stplg.`: +Flat `stplg_` settings, set onto `.stplg.`: | Key | Default | |---|---| @@ -42,13 +42,13 @@ Flat `stplg.` settings, set onto `.stplg.`: | `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_` | | `errorlogname` | `` `segmentederrorlogfile `` | -Flat `sctp.` settings, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +Flat `sctp_` settings, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or `parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and `subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and -`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctp.chainedtp" = true`). +`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctp_chainedtp" = true`). `di/torq/settings/segmentedtp.q` declares every `stplg` default except `kdbtplog`, and every `sctp` default, so any of -them can be given on the command line as `-stplg.` or `-sctp.`; an app sets only the keys it overrides. +them can be given on the command line as `-stplg_` or `-sctp_`; an app sets only the keys it overrides. An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index e2ff6c5b..3284de7a 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -17,23 +17,23 @@ init:{[config;deps] r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; - if[`stplg.kdbtplog in key config;.stplg.kdbtplog:tosym config`stplg.kdbtplog]; - .stplg.multilog:$[`stplg.multilog in key config;tosym config`stplg.multilog;`tabperiod]; - .stplg.multilogperiod:$[`stplg.multilogperiod in key config;config`stplg.multilogperiod;0D01]; - .stplg.errmode:$[`stplg.errmode in key config;config`stplg.errmode;1b]; - .stplg.batchmode:$[`stplg.batchmode in key config;tosym config`stplg.batchmode;`defaultbatch]; - .stplg.replayperiod:$[`stplg.replayperiod in key config;tosym config`stplg.replayperiod;`day]; - .stplg.customcsv:$[`stplg.customcsv in key config;tosym config`stplg.customcsv;`]; - .stplg.errorlogname:$[`stplg.errorlogname in key config;tosym config`stplg.errorlogname;`segmentederrorlogfile]; - .sctp.chainedtp:$[`sctp.chainedtp in key config;config`sctp.chainedtp;0b]; - .sctp.loggingmode:$[`sctp.loggingmode in key config;tosym config`sctp.loggingmode;`none]; - .sctp.tickerplantname:$[`sctp.tickerplantname in key config;tosym config`sctp.tickerplantname;`stp1]; - .sctp.tpconnsleep:$[`sctp.tpconnsleep in key config;config`sctp.tpconnsleep;10]; - .sctp.tpcheckcycles:$[`sctp.tpcheckcycles in key config;config`sctp.tpcheckcycles;0W]; - .sctp.subscribeto:$[`sctp.subscribeto in key config;tosym config`sctp.subscribeto;`]; - .sctp.subscribesyms:$[`sctp.subscribesyms in key config;tosym config`sctp.subscribesyms;`]; - .sctp.replay:$[`sctp.replay in key config;config`sctp.replay;0b]; - .sctp.schema:$[`sctp.schema in key config;config`sctp.schema;1b]; + if[`stplg_kdbtplog in key config;.stplg.kdbtplog:tosym config`stplg_kdbtplog]; + .stplg.multilog:$[`stplg_multilog in key config;tosym config`stplg_multilog;`tabperiod]; + .stplg.multilogperiod:$[`stplg_multilogperiod in key config;config`stplg_multilogperiod;0D01]; + .stplg.errmode:$[`stplg_errmode in key config;config`stplg_errmode;1b]; + .stplg.batchmode:$[`stplg_batchmode in key config;tosym config`stplg_batchmode;`defaultbatch]; + .stplg.replayperiod:$[`stplg_replayperiod in key config;tosym config`stplg_replayperiod;`day]; + .stplg.customcsv:$[`stplg_customcsv in key config;tosym config`stplg_customcsv;`]; + .stplg.errorlogname:$[`stplg_errorlogname in key config;tosym config`stplg_errorlogname;`segmentederrorlogfile]; + .sctp.chainedtp:$[`sctp_chainedtp in key config;config`sctp_chainedtp;0b]; + .sctp.loggingmode:$[`sctp_loggingmode in key config;tosym config`sctp_loggingmode;`none]; + .sctp.tickerplantname:$[`sctp_tickerplantname in key config;tosym config`sctp_tickerplantname;`stp1]; + .sctp.tpconnsleep:$[`sctp_tpconnsleep in key config;config`sctp_tpconnsleep;10]; + .sctp.tpcheckcycles:$[`sctp_tpcheckcycles in key config;config`sctp_tpcheckcycles;0W]; + .sctp.subscribeto:$[`sctp_subscribeto in key config;tosym config`sctp_subscribeto;`]; + .sctp.subscribesyms:$[`sctp_subscribesyms in key config;tosym config`sctp_subscribesyms;`]; + .sctp.replay:$[`sctp_replay in key config;config`sctp_replay;0b]; + .sctp.schema:$[`sctp_schema in key config;config`sctp_schema;1b]; if[`createlogs in key config;set[`createlogs;config`createlogs]]; / subscribers replay from the parent's logs if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index f8dc8a62..5935a543 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -10,8 +10,8 @@ fail,0,0,q,"seg.init[()!();enlist[`log]!enlist nolog]",1,,init without timer mus fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]})]",1,,init without handlers must error true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~.stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv",1,,stplg defaults true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~.sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema",1,,sctp defaults -true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""stplg.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped stplg keys declare the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""sctp.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped sctp keys declare the module's own defaults +true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""stplg_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped stplg keys declare the module's own defaults (so each is overridable from the command line) +true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""sctp_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped sctp keys declare the module's own defaults true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index 749ed292..41d322da 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -13,11 +13,11 @@ PORTS:`a`b`c`s`p!5#0N / a: defaultbatch, tabperiod; b: immediate, singular; c: memorybatch, tabular; s: chained, create; p: chained, parent, TOML-style strings CFGS:`a`b`c`s`p!( - "`procname`schemafile`stplg.kdbtplog!(`stp1;FIXDIR,\"/schema.q\";`$FIXDIR,\"/a\")"; - "`procname`schemafile`stplg.kdbtplog`stplg.batchmode`stplg.multilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; - "`procname`schemafile`stplg.kdbtplog`stplg.batchmode`stplg.multilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; - "`procname`createlogs`autoreconnect`stplg.kdbtplog`sctp.chainedtp`sctp.loggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; - "`procname`createlogs`autoreconnect`stplg.kdbtplog`sctp.chainedtp`sctp.loggingmode`sctp.tickerplantname`sctp.subscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") + "`procname`schemafile`stplg_kdbtplog!(`stp1;FIXDIR,\"/schema.q\";`$FIXDIR,\"/a\")"; + "`procname`schemafile`stplg_kdbtplog`stplg_batchmode`stplg_multilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; + "`procname`schemafile`stplg_kdbtplog`stplg_batchmode`stplg_multilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; + "`procname`createlogs`autoreconnect`stplg_kdbtplog`sctp_chainedtp`sctp_loggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; + "`procname`createlogs`autoreconnect`stplg_kdbtplog`sctp_chainedtp`sctp_loggingmode`sctp_tickerplantname`sctp_subscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index fea0bd76..7752dd67 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -6,8 +6,8 @@ before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmented comment,,,,,,,settings true,0,0,q,"(0;1b;1b;0W;0W;enlist`all;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`part)~.replay`firstmessage`segmentedmode`autoreplay`lastmessage`messagechunks`tablelist`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`mergemethod",1,,replay defaults true,0,0,q,`:tempmergedir~.replay.tempdir,1,,tempdir default -true,0,0,q,"{all {[c;k] c[k]~get `$""."",string k}[x] each k where (k:key x) like ""replay.*""}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped replay keys declare the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~x`merge.mergebybytelimit`merge.partlimit}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped merge keys declare di.merge's own defaults +true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""replay_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped replay keys declare the module's own defaults (so each is overridable from the command line) +true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~x`merge_mergebybytelimit`merge_partlimit}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped merge keys declare di.merge's own defaults true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error @@ -81,7 +81,7 @@ true,0,0,q,"0=replay sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp["" true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym true,0,0,q,"0=count key fp""tmp""",1,,the temp partition was removed run,0,0,q,clearhdb[],1,, -true,0,0,q,"0=replay ""("",(sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`part)""),""),`merge.mergebybytelimit`merge.partlimit!(0b;1000)""",1,,merge with the merge keys set +true,0,0,q,"0=replay ""("",(sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`part)""),""),`merge_mergebybytelimit`merge_partlimit!(0b;1000)""",1,,merge with the merge keys set true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym comment,,,,,,,segmented logs diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index 8e603c93..06dc279e 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -18,7 +18,7 @@ replayp:{[pre;cfg] runq( replay:replayp[()] / replay settings for the plain log, with overrides plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} -sect:{[x] "{(`$\"replay.\",/:string key x)!value x}",x} +sect:{[x] "{(`$\"replay_\",/:string key x)!value x}",x} ran:{[x] read0 fp"run.log"} logged:{[s] any ran[] like s} / was a log named in the list of logs to replay @@ -49,7 +49,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[`proctype`procname`schemafile`stplg.kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + "seg.init[`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; ".u.upd[`quote;(enlist`a;enlist 3f)]"; ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index e3ddeb97..2b0728ac 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -22,7 +22,7 @@ at the end, or partition to a temporary directory and merge on disk. ## Settings -Flat `replay.` settings, set onto `.replay.`: +Flat `replay_` settings, set onto `.replay.`: | Key | Default | |---|---| @@ -46,11 +46,11 @@ Flat `replay.` settings, set onto `.replay.`: | `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist`, `partitiontype`, `sortcsv`, -`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file as quoted keys (`"replay.hdbdir" = "hdb"`). +`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file as quoted keys (`"replay_hdbdir" = "hdb"`). `di/torq/settings/tickerlogreplay.q` declares every default except `compression` and `mergenumtab`, so any of them -can be given on the command line as `-replay.`; an app sets only the keys it overrides. +can be given on the command line as `-replay_`; an app sets only the keys it overrides. -`merge.mergebybytelimit` and `merge.partlimit` are passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` +`merge_mergebybytelimit` and `merge_partlimit` are passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` declares its defaults. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. ## init[config;deps] diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index abaa73dc..021f0116 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,38 +18,38 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - if[`replay.firstmessage in key config;.replay.firstmessage:config`replay.firstmessage]; - if[`replay.lastmessage in key config;.replay.lastmessage:config`replay.lastmessage]; - if[`replay.messagechunks in key config;.replay.messagechunks:config`replay.messagechunks]; - if[`replay.segmentedmode in key config;.replay.segmentedmode:config`replay.segmentedmode]; - if[`replay.autoreplay in key config;.replay.autoreplay:config`replay.autoreplay]; - if[`replay.schemafile in key config;.replay.schemafile:tosym config`replay.schemafile]; - if[`replay.tablelist in key config;.replay.tablelist:tosym config`replay.tablelist]; - if[`replay.hdbdir in key config;.replay.hdbdir:tosym config`replay.hdbdir]; - if[`replay.tplogfile in key config;.replay.tplogfile:tosym config`replay.tplogfile]; - if[`replay.tplogdir in key config;.replay.tplogdir:tosym config`replay.tplogdir]; - if[`replay.partitiontype in key config;.replay.partitiontype:tosym config`replay.partitiontype]; - if[`replay.emptytables in key config;.replay.emptytables:config`replay.emptytables]; - if[`replay.sortafterreplay in key config;.replay.sortafterreplay:config`replay.sortafterreplay]; - if[`replay.basicmode in key config;.replay.basicmode:config`replay.basicmode]; - if[`replay.exitwhencomplete in key config;.replay.exitwhencomplete:config`replay.exitwhencomplete]; - if[`replay.checklogfiles in key config;.replay.checklogfiles:config`replay.checklogfiles]; - if[`replay.gc in key config;.replay.gc:config`replay.gc]; - if[`replay.clean in key config;.replay.clean:config`replay.clean]; - if[`replay.sortcsv in key config;.replay.sortcsv:tosym config`replay.sortcsv]; - if[`replay.partandmerge in key config;.replay.partandmerge:config`replay.partandmerge]; - if[`replay.tempdir in key config;.replay.tempdir:tosym config`replay.tempdir]; - if[`replay.mergenumrows in key config;.replay.mergenumrows:config`replay.mergenumrows]; - if[`replay.mergenumbytes in key config;.replay.mergenumbytes:config`replay.mergenumbytes]; - if[`replay.mergemethod in key config;.replay.mergemethod:tosym config`replay.mergemethod]; - if[`replay.compression in key config;.replay.compression:config`replay.compression]; - if[`replay.mergenumtab in key config;.replay.mergenumtab:config`replay.mergenumtab]; + if[`replay_firstmessage in key config;.replay.firstmessage:config`replay_firstmessage]; + if[`replay_lastmessage in key config;.replay.lastmessage:config`replay_lastmessage]; + if[`replay_messagechunks in key config;.replay.messagechunks:config`replay_messagechunks]; + if[`replay_segmentedmode in key config;.replay.segmentedmode:config`replay_segmentedmode]; + if[`replay_autoreplay in key config;.replay.autoreplay:config`replay_autoreplay]; + if[`replay_schemafile in key config;.replay.schemafile:tosym config`replay_schemafile]; + if[`replay_tablelist in key config;.replay.tablelist:tosym config`replay_tablelist]; + if[`replay_hdbdir in key config;.replay.hdbdir:tosym config`replay_hdbdir]; + if[`replay_tplogfile in key config;.replay.tplogfile:tosym config`replay_tplogfile]; + if[`replay_tplogdir in key config;.replay.tplogdir:tosym config`replay_tplogdir]; + if[`replay_partitiontype in key config;.replay.partitiontype:tosym config`replay_partitiontype]; + if[`replay_emptytables in key config;.replay.emptytables:config`replay_emptytables]; + if[`replay_sortafterreplay in key config;.replay.sortafterreplay:config`replay_sortafterreplay]; + if[`replay_basicmode in key config;.replay.basicmode:config`replay_basicmode]; + if[`replay_exitwhencomplete in key config;.replay.exitwhencomplete:config`replay_exitwhencomplete]; + if[`replay_checklogfiles in key config;.replay.checklogfiles:config`replay_checklogfiles]; + if[`replay_gc in key config;.replay.gc:config`replay_gc]; + if[`replay_clean in key config;.replay.clean:config`replay_clean]; + if[`replay_sortcsv in key config;.replay.sortcsv:tosym config`replay_sortcsv]; + if[`replay_partandmerge in key config;.replay.partandmerge:config`replay_partandmerge]; + if[`replay_tempdir in key config;.replay.tempdir:tosym config`replay_tempdir]; + if[`replay_mergenumrows in key config;.replay.mergenumrows:config`replay_mergenumrows]; + if[`replay_mergenumbytes in key config;.replay.mergenumbytes:config`replay_mergenumbytes]; + if[`replay_mergemethod in key config;.replay.mergemethod:tosym config`replay_mergemethod]; + if[`replay_compression in key config;.replay.compression:config`replay_compression]; + if[`replay_mergenumtab in key config;.replay.mergenumtab:config`replay_mergenumtab]; .replay.tablelist:(),.replay.tablelist; .z.m.merge:use`di.merge; / sentinel keeps the values general; enlist of a dict is a table mergedeps:``log!(::;deps`log); - if[`merge.mergebybytelimit in key config;mergedeps[`mergebybytelimit]:config`merge.mergebybytelimit]; - if[`merge.partlimit in key config;mergedeps[`partlimit]:config`merge.partlimit]; + if[`merge_mergebybytelimit in key config;mergedeps[`mergebybytelimit]:config`merge_mergebybytelimit]; + if[`merge_partlimit in key config;mergedeps[`partlimit]:config`merge_partlimit]; .z.m.merge.init mergedeps _ `; / some variables must be set exitifnull each `.replay.schemafile`.replay.hdbdir, $[all null .replay`tplogdir`tplogfile; `.replay.tplogfile; ()]; diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index bf4ef09a..3d673ce3 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -66,6 +66,8 @@ init:{[deps] {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; .servers.RETRY:totimespan .servers.RETRY; .servers.DISCOVERYRETRY:totimespan .servers.DISCOVERYRETRY; + / a string or a list of strings (TOML has no symbol type) + .servers.CONNECTIONS:$[11h=abs type c:.servers.CONNECTIONS;c;`$c]; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; / live-handle checks set[`.dotz.liveh;{x in key .z.W}]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index b38c30c7..d734dffa 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -61,6 +61,8 @@ true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery a comment,,,,,,,retry periods from toml run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans +run,0,0,q,"svc.init svrdeps enlist""otherproc""",1,1,connections as a list of strings +true,0,0,q,(enlist`otherproc)~.servers.CONNECTIONS,1,1,become symbols comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection diff --git a/di/torq/settings/segmentedchainedtp.q b/di/torq/settings/segmentedchainedtp.q deleted file mode 100644 index 2742020c..00000000 --- a/di/torq/settings/segmentedchainedtp.q +++ /dev/null @@ -1,14 +0,0 @@ -/ chained segmented tickerplant settings -/ sctp logging is set by loggingmode, not createlogs -createlogs:0b -sctp.chainedtp:1b -sctp.loggingmode:`none -sctp.tickerplantname:`stp1 -sctp.subscribeto:` -sctp.subscribesyms:` -sctp.replay:0b -sctp.schema:1b -connections:enlist`segmentedtp -/ connections only; an app clients section replaces this whole section -clients:(enlist`opencloseonly)!enlist 1b -zpsignore:(enlist`enabled)!enlist 0b diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 3d958e2d..aada54e0 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -2,20 +2,20 @@ clients:(enlist`opencloseonly)!enlist 1b zpsignore:(enlist`enabled)!enlist 0b / every basic-typed stplg and sctp default as a flat key, so each can be overridden from the command line -/ (-stplg., -sctp.); must agree with the module's own defaults. kdbtplog comes from the environment -stplg.multilog:`tabperiod -stplg.multilogperiod:0D01 -stplg.errmode:1b -stplg.batchmode:`defaultbatch -stplg.replayperiod:`day -stplg.customcsv:` -stplg.errorlogname:`segmentederrorlogfile -sctp.chainedtp:0b -sctp.loggingmode:`none -sctp.tickerplantname:`stp1 -sctp.tpconnsleep:10 -sctp.tpcheckcycles:0W -sctp.subscribeto:` -sctp.subscribesyms:` -sctp.replay:0b -sctp.schema:1b +/ (-stplg_, -sctp_); must agree with the module's own defaults. kdbtplog comes from the environment +stplg_multilog:`tabperiod +stplg_multilogperiod:0D01 +stplg_errmode:1b +stplg_batchmode:`defaultbatch +stplg_replayperiod:`day +stplg_customcsv:` +stplg_errorlogname:`segmentederrorlogfile +sctp_chainedtp:0b +sctp_loggingmode:`none +sctp_tickerplantname:`stp1 +sctp_tpconnsleep:10 +sctp_tpcheckcycles:0W +sctp_subscribeto:` +sctp_subscribesyms:` +sctp_replay:0b +sctp_schema:1b diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q index 49dab626..b782f49a 100644 --- a/di/torq/settings/tickerlogreplay.q +++ b/di/torq/settings/tickerlogreplay.q @@ -1,30 +1,30 @@ / tickerlogreplay settings / every basic-typed replay default as a flat key, so each can be overridden from the command line -/ (-replay.); must agree with the module's own defaults -replay.firstmessage:0 -replay.lastmessage:0W -replay.messagechunks:0W -replay.segmentedmode:1b -replay.autoreplay:1b -replay.schemafile:` -replay.tablelist:enlist`all -replay.hdbdir:` -replay.tplogfile:` -replay.tplogdir:` -replay.partitiontype:`date -replay.emptytables:1b -replay.sortafterreplay:1b -replay.basicmode:0b -replay.exitwhencomplete:1b -replay.checklogfiles:0b -replay.gc:1b -replay.clean:1b -replay.sortcsv:` -replay.partandmerge:0b -replay.tempdir:`:tempmergedir -replay.mergenumrows:10000000 -replay.mergenumbytes:500000000 -replay.mergemethod:`part +/ (-replay_); must agree with the module's own defaults +replay_firstmessage:0 +replay_lastmessage:0W +replay_messagechunks:0W +replay_segmentedmode:1b +replay_autoreplay:1b +replay_schemafile:` +replay_tablelist:enlist`all +replay_hdbdir:` +replay_tplogfile:` +replay_tplogdir:` +replay_partitiontype:`date +replay_emptytables:1b +replay_sortafterreplay:1b +replay_basicmode:0b +replay_exitwhencomplete:1b +replay_checklogfiles:0b +replay_gc:1b +replay_clean:1b +replay_sortcsv:` +replay_partandmerge:0b +replay_tempdir:`:tempmergedir +replay_mergenumrows:10000000 +replay_mergenumbytes:500000000 +replay_mergemethod:`part / di.merge's mergebybytelimit and partlimit, passed to its init; must agree with di.merge's own defaults -merge.mergebybytelimit:0b -merge.partlimit:1000 +merge_mergebybytelimit:0b +merge_partlimit:1000 diff --git a/di/torq/torq.md b/di/torq/torq.md index 53d745e7..611f150c 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -83,8 +83,9 @@ expects. A built-in registry maps proctype → module name, `` `x → `di.torq.proc.x `` for each of `hdb`, `tickerplant`, `rdb`, `wdb`, `gateway`, `idb`, `segmentedtp`, `chainedtp`, `housekeeping`, `discovery` -and `tickerlogreplay`; `segmentedchainedtp` also maps to `di.torq.proc.segmentedtp` (a chained segmented -tickerplant, set by its settings): +and `tickerlogreplay`; `segmentedchainedtp` also maps to `di.torq.proc.segmentedtp` and resolves the +`segmentedtp` settings tier (builtin and app root alike); its chained behaviour comes from the instance's own +settings, e.g. `sctp1.toml`, as any other per-instance distinction does: ```q builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay`segmentedchainedtp!`di.torq.proc.hdb`di.torq.proc.tickerplant ... diff --git a/di/torq/torq.q b/di/torq/torq.q index c8ef5745..a412485f 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -279,7 +279,9 @@ init:{[proctype;procname;overrides] logdep:buildlogdep[overrides]; cc:use`di.torq.config; (cc`init)[enlist[`log]!enlist logdep]; - config:(cc`cascade)[r 0;r 1;proctype;procname]; + / segmentedchainedtp shares segmentedtp's settings tier; dispatch keeps the real proctype + settingsproctype:$[proctype=`segmentedchainedtp;`segmentedtp;proctype]; + config:(cc`cascade)[r 0;r 1;settingsproctype;procname]; / command-line override layer - the TOP cascade tier. A launch flag matching a settings name / overrides it (parsed into that setting's type); reserved launcher/identity flags are excluded, / and a flag that doesn't name a real setting is skipped (see di.torq.config.overrideconfig). From cd6b4b1cc58241112f8abb821d84ecae59d5eee3 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 16:35:09 +0100 Subject: [PATCH 32/42] tickerlogreplay: no .replay namespace; settings only in the settings file Settings: - every setting is required in config (init signals "missing settings: ..."), kept module-private via .z.m and read bare; the module keeps no defaults of its own - the file-level settings block and the init fallbacks are gone - settings/tickerlogreplay.q declares them all with bare keys (firstmessage, tplogdir, mergebybytelimit, partlimit), now including compression and mergenumtab; flags are - Namespace: - .replay keeps only the caller hooks set before use: upd, savedownmanipulation, postreplay (and the .save bridge) - initandrun and replaylog are bare and exported - exitifnull takes name and value; namespace indexing becomes explicit reads - di.merge init gets a plain general dict (no sentinel needed) Tests: - build config from the shipped settings file plus overrides - dropped the four rows checking module-side defaults against the settings file - new rows: init without settings exits 3 and names the missing keys tickerlogreplay 96 rows, di.torq 75; scratch partandmerge replay with -tplogdir matches the logs' row counts. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerlogreplay/init.q | 2 +- di/torq/proc/tickerlogreplay/test.csv | 10 +- di/torq/proc/tickerlogreplay/test.q | 4 +- .../proc/tickerlogreplay/tickerlogreplay.md | 19 +- .../proc/tickerlogreplay/tickerlogreplay.q | 242 ++++++++---------- di/torq/settings/tickerlogreplay.q | 60 ++--- 6 files changed, 157 insertions(+), 180 deletions(-) diff --git a/di/torq/proc/tickerlogreplay/init.q b/di/torq/proc/tickerlogreplay/init.q index 8abf82af..8219d7c2 100644 --- a/di/torq/proc/tickerlogreplay/init.q +++ b/di/torq/proc/tickerlogreplay/init.q @@ -5,4 +5,4 @@ version:first read0`:::VERSION / the default sort config sortdefault:("SSSB";enlist",")0:read0`:::sort.csv -export:([init;version]) +export:([init;initandrun;replaylog;version]) diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv index 7752dd67..aea7fb3f 100644 --- a/di/torq/proc/tickerlogreplay/test.csv +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -4,10 +4,6 @@ before,0,0,q,"system ""l di/torq/proc/tickerlogreplay/test.q""",1,,load fixture before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmentedtp to write segmented logs comment,,,,,,,settings -true,0,0,q,"(0;1b;1b;0W;0W;enlist`all;`date;1b;1b;0b;1b;0b;1b;1b;`;0b;`part)~.replay`firstmessage`segmentedmode`autoreplay`lastmessage`messagechunks`tablelist`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`partandmerge`mergemethod",1,,replay defaults -true,0,0,q,`:tempmergedir~.replay.tempdir,1,,tempdir default -true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""replay_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped replay keys declare the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{m:use`di.merge; m[`init] enlist[`log]!enlist `info`error!2#{[c;msg]}; (m[`getmergebybytelimit][];m[`getpartlimit][])~x`merge_mergebybytelimit`merge_partlimit}(use`di.torq.config)[`parsefile][""di/torq/settings/tickerlogreplay.q""]",1,,the shipped merge keys declare di.merge's own defaults true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error @@ -59,8 +55,10 @@ true,0,0,q,"0=replayp[enlist""`.replay.upd set {[t;x] if[t~`trade;insert[t;x]]}" true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,the upd override decided what was inserted comment,,,,,,,checks at init +true,0,0,q,"3=replay ""()!()""",1,,init without the settings exits 3 +true,0,0,q,"logged ""*missing settings: firstmessage*""",1,,and names them true,0,0,q,"1=replay sect plain ""enlist[`schemafile]!enlist`""",1,,a null schemafile exits 1 -true,0,0,q,"logged ""*Variable .replay.schemafile is null but must be set*""",1,,and says which +true,0,0,q,"logged ""*Variable schemafile is null but must be set*""",1,,and says which true,0,0,q,"1=replay sect plain ""enlist[`partitiontype]!enlist`int""",1,,an unknown partitiontype exits 1 true,0,0,q,"2=replay sect plain ""enlist[`messagechunks]!enlist 0""",1,,zero messagechunks exits 2 true,0,0,q,"1=replay sect plain ""`basicmode`messagechunks!(1b;2)""",1,,basic mode with chunks exits 1 @@ -81,7 +79,7 @@ true,0,0,q,"0=replay sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp["" true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym true,0,0,q,"0=count key fp""tmp""",1,,the temp partition was removed run,0,0,q,clearhdb[],1,, -true,0,0,q,"0=replay ""("",(sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`part)""),""),`merge_mergebybytelimit`merge_partlimit!(0b;1000)""",1,,merge with the merge keys set +true,0,0,q,"0=replay ""("",(sect plain ""`partandmerge`tempdir`mergemethod!(1b;"",hp[""tmp""],"";`part)""),""),`mergebybytelimit`partlimit!(0b;1000)""",1,,merge with the merge keys set true,0,0,q,(3;1;`p)~(rows[D;`trade];rows[D;`quote];attr hdb[D;`trade]`sym),1,,merged with p# on sym comment,,,,,,,segmented logs diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index 06dc279e..12b008b0 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -16,9 +16,9 @@ replayp:{[pre;cfg] runq( "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; "exit 0"))} replay:replayp[()] -/ replay settings for the plain log, with overrides +/ replay settings for the plain log, with overrides; sect puts them over the shipped settings plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} -sect:{[x] "{(`$\"replay_\",/:string key x)!value x}",x} +sect:{[x] "((use`di.torq.config)[`parsefile] \"di/torq/settings/tickerlogreplay.q\"),",x} ran:{[x] read0 fp"run.log"} logged:{[s] any ran[] like s} / was a log named in the list of logs to replay diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 2b0728ac..717452e4 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -8,21 +8,22 @@ at the end, or partition to a temporary directory and merge on disk. ## Files `init.q` loads `tickerlogreplay.q`: the module `init`, then the `.save` hooks (`savedownmanipulation`, -`manipulate`, `postreplay`), each defined if absent, and `.replay`. `sort.csv` is the default sort config. +`manipulate`, `postreplay`), each defined if absent, and the `.replay.upd` hook. `sort.csv` is the default sort config. ## Surface | Name | What | |---|---| | `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | -| `.replay.initandrun[]` | replays every log, sorts or merges, runs `postreplay`, and exits if `exitwhencomplete` | -| `.replay.replaylog[logfile]` | replays one log and saves its tables | +| `initandrun[]` | replays every log, sorts or merges, runs `postreplay`, and exits if `exitwhencomplete` | +| `replaylog[logfile]` | replays one log and saves its tables | | `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | | `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | ## Settings -Flat `replay_` settings, set onto `.replay.`: +Every setting is required in `config` and kept module-private; `di/torq/settings/tickerlogreplay.q` declares +them all with these defaults: | Key | Default | |---|---| @@ -46,18 +47,16 @@ Flat `replay_` settings, set onto `.replay.`: | `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist`, `partitiontype`, `sortcsv`, -`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file as quoted keys (`"replay_hdbdir" = "hdb"`). -`di/torq/settings/tickerlogreplay.q` declares every default except `compression` and `mergenumtab`, so any of them -can be given on the command line as `-replay_`; an app sets only the keys it overrides. +`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file (`hdbdir = "hdb"`). Any +basic-typed setting can be given on the command line as `-`; an app sets only the keys it overrides. -`merge_mergebybytelimit` and `merge_partlimit` are passed to di.merge's `init`; `di/torq/settings/tickerlogreplay.q` -declares its defaults. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. +`mergebybytelimit` (`0b`) and `partlimit` (`1000`), also required, are passed to di.merge's `init`. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. ## init[config;deps] Requires `log`. It: -1. initialises di.dbwrite and di.merge, and applies the settings; +1. signals if any setting is missing, initialises di.dbwrite and di.merge, and applies the settings; 2. exits on a bad setting: - code 1 for a null `schemafile`/`hdbdir`/log, an unknown `partitiontype`, `basicmode` with `messagechunks`, a message range in segmented mode, or `partandmerge` into `hdbdir`; diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 021f0116..2536a0b6 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -6,10 +6,10 @@ tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; / log the error and exit ex:{[id;message;code] .z.m.log[`error][id;message]; exit code} -/ exit if a variable is null -exitifnull:{[variable] - if[null value variable; - .z.m.log[`error][`init;"Variable ",(string variable)," is null but must be set"]; +/ exit if a setting is null +exitifnull:{[name;val] + if[null val; + .z.m.log[`error][`init;"Variable ",(string name)," is null but must be set"]; exit 1]} init:{[config;deps] @@ -18,63 +18,67 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - if[`replay_firstmessage in key config;.replay.firstmessage:config`replay_firstmessage]; - if[`replay_lastmessage in key config;.replay.lastmessage:config`replay_lastmessage]; - if[`replay_messagechunks in key config;.replay.messagechunks:config`replay_messagechunks]; - if[`replay_segmentedmode in key config;.replay.segmentedmode:config`replay_segmentedmode]; - if[`replay_autoreplay in key config;.replay.autoreplay:config`replay_autoreplay]; - if[`replay_schemafile in key config;.replay.schemafile:tosym config`replay_schemafile]; - if[`replay_tablelist in key config;.replay.tablelist:tosym config`replay_tablelist]; - if[`replay_hdbdir in key config;.replay.hdbdir:tosym config`replay_hdbdir]; - if[`replay_tplogfile in key config;.replay.tplogfile:tosym config`replay_tplogfile]; - if[`replay_tplogdir in key config;.replay.tplogdir:tosym config`replay_tplogdir]; - if[`replay_partitiontype in key config;.replay.partitiontype:tosym config`replay_partitiontype]; - if[`replay_emptytables in key config;.replay.emptytables:config`replay_emptytables]; - if[`replay_sortafterreplay in key config;.replay.sortafterreplay:config`replay_sortafterreplay]; - if[`replay_basicmode in key config;.replay.basicmode:config`replay_basicmode]; - if[`replay_exitwhencomplete in key config;.replay.exitwhencomplete:config`replay_exitwhencomplete]; - if[`replay_checklogfiles in key config;.replay.checklogfiles:config`replay_checklogfiles]; - if[`replay_gc in key config;.replay.gc:config`replay_gc]; - if[`replay_clean in key config;.replay.clean:config`replay_clean]; - if[`replay_sortcsv in key config;.replay.sortcsv:tosym config`replay_sortcsv]; - if[`replay_partandmerge in key config;.replay.partandmerge:config`replay_partandmerge]; - if[`replay_tempdir in key config;.replay.tempdir:tosym config`replay_tempdir]; - if[`replay_mergenumrows in key config;.replay.mergenumrows:config`replay_mergenumrows]; - if[`replay_mergenumbytes in key config;.replay.mergenumbytes:config`replay_mergenumbytes]; - if[`replay_mergemethod in key config;.replay.mergemethod:tosym config`replay_mergemethod]; - if[`replay_compression in key config;.replay.compression:config`replay_compression]; - if[`replay_mergenumtab in key config;.replay.mergenumtab:config`replay_mergenumtab]; - .replay.tablelist:(),.replay.tablelist; + / every setting comes from config - di/torq/settings/tickerlogreplay.q declares them all + req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; + req,:`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`compression; + req,:`partandmerge`tempdir`mergenumrows`mergenumtab`mergenumbytes`mergemethod`mergebybytelimit`partlimit; + if[count m:req except key config; + '"di.torq.proc.tickerlogreplay: missing settings: ",", " sv string m]; + .z.m.firstmessage:config`firstmessage; + .z.m.lastmessage:config`lastmessage; + .z.m.messagechunks:config`messagechunks; + .z.m.segmentedmode:config`segmentedmode; + .z.m.autoreplay:config`autoreplay; + .z.m.schemafile:tosym config`schemafile; + .z.m.tablelist:tosym config`tablelist; + .z.m.hdbdir:tosym config`hdbdir; + .z.m.tplogfile:tosym config`tplogfile; + .z.m.tplogdir:tosym config`tplogdir; + .z.m.partitiontype:tosym config`partitiontype; + .z.m.emptytables:config`emptytables; + .z.m.sortafterreplay:config`sortafterreplay; + .z.m.basicmode:config`basicmode; + .z.m.exitwhencomplete:config`exitwhencomplete; + .z.m.checklogfiles:config`checklogfiles; + .z.m.gc:config`gc; + .z.m.clean:config`clean; + .z.m.sortcsv:tosym config`sortcsv; + .z.m.compression:config`compression; + .z.m.partandmerge:config`partandmerge; + .z.m.tempdir:tosym config`tempdir; + .z.m.mergenumrows:config`mergenumrows; + .z.m.mergenumtab:config`mergenumtab; + .z.m.mergenumbytes:config`mergenumbytes; + .z.m.mergemethod:tosym config`mergemethod; + .z.m.tablelist:(),tablelist; .z.m.merge:use`di.merge; - / sentinel keeps the values general; enlist of a dict is a table - mergedeps:``log!(::;deps`log); - if[`merge_mergebybytelimit in key config;mergedeps[`mergebybytelimit]:config`merge_mergebybytelimit]; - if[`merge_partlimit in key config;mergedeps[`partlimit]:config`merge_partlimit]; - .z.m.merge.init mergedeps _ `; + .z.m.merge.init `log`mergebybytelimit`partlimit!(deps`log;config`mergebybytelimit;config`partlimit); / some variables must be set - exitifnull each `.replay.schemafile`.replay.hdbdir, $[all null .replay`tplogdir`tplogfile; `.replay.tplogfile; ()]; - if[.replay.basicmode and (.replay.messagechunks within (0;-1 + 0W)); + exitifnull[`schemafile;schemafile]; + exitifnull[`hdbdir;hdbdir]; + if[all null (tplogdir;tplogfile);exitifnull[`tplogfile;tplogfile]]; + if[basicmode and (messagechunks within (0;-1 + 0W)); ex[`replayinit; "if using basic mode, messagechunks must not be used (it should be set to 0W). basicmode will use .Q.hdpf to overwrite tables at the end of the replay";1]]; - if[not .replay.partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; - if[.replay.messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; - if[.replay.segmentedmode and ((0<>.replay.firstmessage) or 0W<>.replay.lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode";1]]; - .z.m.trackonly:.replay.messagechunks < 0; + if[not partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; + if[messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; + if[segmentedmode and ((0<>firstmessage) or 0W<>lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode";1]]; + .z.m.trackonly:messagechunks < 0; if[trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; - .replay.messagechunks:abs .replay.messagechunks; - if[.replay.partandmerge and .replay.hdbdir = .replay.tempdir;ex[`replayinit;"if using partandmerge replay, tempdir must be set to a different directory than the hdb";1]]; - if[.replay.partandmerge and .replay.sortafterreplay;(.replay.sortafterreplay:0b; .z.m.log[`info][`replayinit;"Setting sortafterreplay to 0b"])]; + .z.m.messagechunks:abs messagechunks; + if[partandmerge and hdbdir = tempdir;ex[`replayinit;"if using partandmerge replay, tempdir must be set to a different directory than the hdb";1]]; + if[partandmerge and sortafterreplay;(.z.m.sortafterreplay:0b; .z.m.log[`info][`replayinit;"Setting sortafterreplay to 0b"])]; / load the schema - .z.m.log[`info][`replayinit;"loading schema file ",string .replay.schemafile]; - @[system;"l ",string .replay.schemafile;{ex[`replayinit;"failed to load replay file ",(string x)," - ",y;2]}[.replay.schemafile]]; - .z.m.log[`info][`replayinit;"hdb directory is set to ",string .replay.hdbdir:hsym .replay.hdbdir]; - .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .replay.tempdir:hsym .replay.tempdir]; + .z.m.log[`info][`replayinit;"loading schema file ",string schemafile]; + @[system;"l ",string schemafile;{ex[`replayinit;"failed to load replay file ",(string x)," - ",y;2]}[schemafile]]; + .z.m.log[`info][`replayinit;"hdb directory is set to ",string .z.m.hdbdir:hsym hdbdir]; + .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .z.m.tempdir:hsym tempdir]; / filter on the table list - if[(not .replay.tablelist~enlist `all) and not .replay.segmentedmode; .z.m.realupd:{[f;t;x] if[t in tablestoreplay; f[t;x]]}[realupd]]; + if[(not tablelist~enlist `all) and not segmentedmode; .z.m.realupd:{[f;t;x] if[t in tablestoreplay; f[t;x]]}[realupd]]; / chunked saves - if[.replay.messagechunks < 0W; .z.m.realupd:{[f;t;x] f[t;x]; checkcount[.replay.hdbdir;replaydate;1;.replay.tempdir]}[realupd]]; + if[messagechunks < 0W; .z.m.realupd:{[f;t;x] f[t;x]; checkcount[hdbdir;replaydate;1;tempdir]}[realupd]]; / load the sort csv and kick off replay if auto-running - $[null .replay.sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv .replay.sortcsv]; - if[.replay.autoreplay;.replay.initandrun[]]; + $[null sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv sortcsv]; + if[autoreplay;initandrun[]]; }; / save down manipulation and post replay hook, each defined if absent @@ -93,68 +97,42 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] }]; -/ settings -.replay.firstmessage:@[value;`.replay.firstmessage;0] // the first message to execute -.replay.segmentedmode:@[value;`.replay.segmentedmode;1b] // segmented tickerplant logs -.replay.autoreplay:@[value;`.replay.autoreplay;1b] // replay tplogs automatically -.replay.lastmessage:@[value;`.replay.lastmessage;0W] // the last message to replay -.replay.messagechunks:@[value;`.replay.messagechunks;0W] // the number of messages to replay at once -.replay.schemafile:@[value;`.replay.schemafile;`] // the schema file to load data in to -.replay.tablelist:@[value;`.replay.tablelist;enlist `all] // the tables to replay into. `all means all -.replay.hdbdir:@[value;`.replay.hdbdir;`] // the hdb directory to write to -.replay.tplogfile:@[value;`.replay.tplogfile;`] // the tp log file to replay; this or tplogdir -.replay.tplogdir:@[value;`.replay.tplogdir;`] // the tp log directory to replay; this or tplogfile -.replay.partitiontype:@[value;`.replay.partitiontype;`date] // date, month or year -.replay.emptytables:@[value;`.replay.emptytables;1b] // whether to overwrite any tables at start up -.replay.sortafterreplay:@[value;`.replay.sortafterreplay;1b] // re-sort and apply attributes at the end of the replay -.replay.basicmode:@[value;`.replay.basicmode;0b] // replay everything, then save with .Q.hdpf -.replay.exitwhencomplete:@[value;`.replay.exitwhencomplete;1b] // exit when the replay is complete -.replay.checklogfiles:@[value;`.replay.checklogfiles;0b] // replay a "good" copy of a corrupt log -.replay.gc:@[value;`.replay.gc;1b] // garbage collect after each table save and each log -.replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] // default upd function used for replaying data -.replay.clean:@[value;`.replay.clean;1b] // clean existing folders on start up -.replay.sortcsv:@[value;`.replay.sortcsv;`] // location of sort csv file; null is the default sort.csv -.replay.compression:@[value;`.replay.compression;()]; // the compress level, empty list if not required -.replay.partandmerge:@[value;`.replay.partandmerge;0b]; // partition to tempdir, then merge on disk -.replay.tempdir:hsym @[value;`.replay.tempdir;`:tempmergedir]; // location to save data for partandmerge replay -.replay.mergenumrows:@[value;`.replay.mergenumrows;10000000]; // default number of rows for merge process -.replay.mergenumtab:@[value;`.replay.mergenumtab;`quote`trade!10000 50000]; // number of rows per table for merge process -.replay.mergenumbytes:@[value;`.replay.mergenumbytes;500000000]; // default number of bytes for merge process -.replay.mergemethod:@[value;`.replay.mergemethod;`part]; // part, col or hybrid +/ default upd function used for replaying data; set .replay.upd before use to override +.replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] / save down settings .save.savedownmanipulation:@[value;`.replay.savedownmanipulation;()!()] // table!function applied to a table at save .save.postreplay:@[value;`.replay.postreplay;{{[d;p] }}] // invoked after a log's tables are saved // the path to the table to save -pathtotable:{[h;p;t] `$(string .Q.par[h;.replay.partitiontype$p;t]),"/"} +pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} // create empty tables - we need to make sure we only create them once emptytabs:`symbol$() createemptytable:{[h;p;t;td] - $[.replay.partandmerge;dest:td;dest:h]; - if[(not (path:pathtotable[dest;p;t]) in emptytabs) and .replay.emptytables; + $[partandmerge;dest:td;dest:h]; + if[(not (path:pathtotable[dest;p;t]) in emptytabs) and emptytables; .z.m.log[`info][`replay;"creating empty table ",(string t)," at ",string path]; .z.m.emptytabs,:path; savetabdatatrapped[h;p;t;0#value t;0b;td]]} savetabdata:{[h;p;t;data;UPSERT;td] - $[.replay.partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; - if[not .replay.partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; + $[partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; + if[not partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; .z.m.pathlist[t],:path; - $[.replay.partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] } savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} // this function should be invoked for saving tables savetab:{[td;h;p;t] - if[not .replay.partandmerge;createemptytable[h;p;t;td]]; + if[not partandmerge;createemptytable[h;p;t;td]]; if[count value t; .z.m.log[`info][`replay;"saving ",(string t)," which has row count ",string count value t]; savetabdatatrapped[h;p;t;value t;1b;td]; delete from t; - if[.replay.gc;.z.m.dbw.gc[]]]} + if[gc;.z.m.dbw.gc[]]]} // apply the sorting and attributes at the end of the replay, from tablename!(list of paths) applysortandattr:{[pathlist] @@ -169,11 +147,11 @@ currentcount:0 totalcount:0 checkcount:{[h;p;counter;td] .z.m.currentcount+:counter; - if[currentcount >= .replay.messagechunks; + if[currentcount >= messagechunks; $[trackonly; [.z.m.totalcount +: currentcount; - .z.m.log[`info][`replay;"replayed a chunk of ",(string .replay.messagechunks)," messages. Total message count so far is ",string totalcount]]; - [.z.m.log[`info][`replay;"number of messages to replay at once (",(string .replay.messagechunks),") has been exceeded. Saving down"]; + .z.m.log[`info][`replay;"replayed a chunk of ",(string messagechunks)," messages. Total message count so far is ",string totalcount]]; + [.z.m.log[`info][`replay;"number of messages to replay at once (",(string messagechunks),") has been exceeded. Saving down"]; savetab[td;h;p] each tabsincountorder[tablestoreplay]; .z.m.log[`info][`replay;"save complete- replaying next chunk of data"]]]; .z.m.currentcount:0]} @@ -188,54 +166,54 @@ finishreplay:{[h;p;td] // takes in log file directories made with segmented tickerplant expandstplogs:{[logdirectories] // always a list - {` sv'raze x,/:'key each x}$[`~.replay.tplogdir;{enlist first x};]hsym logdirectories + {` sv'raze x,/:'key each x}$[`~tplogdir;{enlist first x};]hsym logdirectories }; -.replay.replaylog:{[logfile] +replaylog:{[logfile] // set the upd function to be the initialupd function .z.m.msgcount:.z.m.currentcount:.z.m.totalcount:0; // check if logfile is corrupt - if[.replay.checklogfiles; logfile: .z.m.tplog.check[logfile;.replay.lastmessage]]; - $[.replay.firstmessage>0; - [.z.m.log[`info][`replay;"skipping first ",(string .replay.firstmessage)," messages"]; + if[checklogfiles; logfile: .z.m.tplog.check[logfile;lastmessage]]; + $[firstmessage>0; + [.z.m.log[`info][`replay;"skipping first ",(string firstmessage)," messages"]; @[`.;`upd;:;initialupd]]; @[`.;`upd;:;realupd]]; .z.m.tablecounts:.z.m.errorcounts:()!(); // If not running in segmented mode, reset replay date and clean HDB directory on each loop .z.m.zipped:$[logfile like "*.gz";1b;0b]; - if[not .replay.segmentedmode; + if[not segmentedmode; // Pull out date from TP log file name - *YYYY.MM.DD (+ .gz if zipped) .z.m.replaydate:"D"$$[zipped;-3_-13#;-10#] string logfile; - if[.replay.clean;cleanhdb replaydate] + if[clean;cleanhdb replaydate] ]; - if[.replay.lastmessage<.replay.firstmessage; .z.m.log[`info][`replay;"lastmessage (",(string .replay.lastmessage),") is less than firstmessage (",(string .replay.firstmessage),"). Not replaying log file"]; :()]; - .z.m.log[`info][`replay;"replaying data from logfile ",(string logfile)," from message ",(string .replay.firstmessage)," to ",(string .replay.lastmessage),". Message indices are from 0 and inclusive - so both the first and last message will be replayed"]; + if[lastmessage); must agree with the module's own defaults -replay_firstmessage:0 -replay_lastmessage:0W -replay_messagechunks:0W -replay_segmentedmode:1b -replay_autoreplay:1b -replay_schemafile:` -replay_tablelist:enlist`all -replay_hdbdir:` -replay_tplogfile:` -replay_tplogdir:` -replay_partitiontype:`date -replay_emptytables:1b -replay_sortafterreplay:1b -replay_basicmode:0b -replay_exitwhencomplete:1b -replay_checklogfiles:0b -replay_gc:1b -replay_clean:1b -replay_sortcsv:` -replay_partandmerge:0b -replay_tempdir:`:tempmergedir -replay_mergenumrows:10000000 -replay_mergenumbytes:500000000 -replay_mergemethod:`part -/ di.merge's mergebybytelimit and partlimit, passed to its init; must agree with di.merge's own defaults -merge_mergebybytelimit:0b -merge_partlimit:1000 +/ every setting and its default; init requires them all. Basic-typed ones can be overridden from the +/ command line (-) +firstmessage:0 +lastmessage:0W +messagechunks:0W +segmentedmode:1b +autoreplay:1b +schemafile:` +tablelist:enlist`all +hdbdir:` +tplogfile:` +tplogdir:` +partitiontype:`date +emptytables:1b +sortafterreplay:1b +basicmode:0b +exitwhencomplete:1b +checklogfiles:0b +gc:1b +clean:1b +sortcsv:` +partandmerge:0b +tempdir:`:tempmergedir +mergenumrows:10000000 +mergenumbytes:500000000 +mergemethod:`part +compression:() +mergenumtab:`quote`trade!10000 50000 +/ di.merge's mergebybytelimit and partlimit, passed to its init +mergebybytelimit:0b +partlimit:1000 From 386e6a5b162e6b84290f73359eb7e1566838bad0 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 16:52:12 +0100 Subject: [PATCH 33/42] tickerlogreplay: export only init and version initandrun and replaylog stay module-private; the replay runs from the command line through init (autoreplay), e.g. torqx.sh start tickerlogreplay1 -tplogdir -tablelist quote -hdbdir . Their rows come out of the docs' Surface table. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/tickerlogreplay/init.q | 2 +- di/torq/proc/tickerlogreplay/tickerlogreplay.md | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/di/torq/proc/tickerlogreplay/init.q b/di/torq/proc/tickerlogreplay/init.q index 8219d7c2..8abf82af 100644 --- a/di/torq/proc/tickerlogreplay/init.q +++ b/di/torq/proc/tickerlogreplay/init.q @@ -5,4 +5,4 @@ version:first read0`:::VERSION / the default sort config sortdefault:("SSSB";enlist",")0:read0`:::sort.csv -export:([init;initandrun;replaylog;version]) +export:([init;version]) diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 717452e4..70b13dfd 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -15,8 +15,6 @@ at the end, or partition to a temporary directory and merge on disk. | Name | What | |---|---| | `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | -| `initandrun[]` | replays every log, sorts or merges, runs `postreplay`, and exits if `exitwhencomplete` | -| `replaylog[logfile]` | replays one log and saves its tables | | `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | | `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | From 67cb646cbd5411a93a97835dbcef87de18c283c5 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 17:34:54 +0100 Subject: [PATCH 34/42] segmentedtp: settings only in the settings file Settings: - init requires every stplg_*/sctp_* setting and createlogs (signals "missing settings: ...") and reads each straight from config; the module keeps no defaults of its own - the default lines in stplog.q and sctp.q and the file-level createlogs default are gone - settings/segmentedtp.q declares them all, now including createlogs - kdbtplog (from KDBTPLOG, optional config override) and schemafile stay optional - the .stplg/.sctp namespaces are unchanged (IPC and root contracts) Tests: - the segmentedtp peers and tickerlogreplay's segmentedtp peer build their config from the shipped settings file plus their own keys - the defaults and sync rows read peer a, which ran a real init - new row: init without the settings errors segmentedtp 70 rows, tickerlogreplay 96; scratch stack stp1 -> sctp1 (chained) -> rdb1 with data flowing. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/sctp.q | 10 ------ di/torq/proc/segmentedtp/segmentedtp.md | 13 ++++---- di/torq/proc/segmentedtp/segmentedtp.q | 42 +++++++++++++------------ di/torq/proc/segmentedtp/stplog.q | 10 +----- di/torq/proc/segmentedtp/test.csv | 9 +++--- di/torq/proc/segmentedtp/test.q | 2 +- di/torq/proc/tickerlogreplay/test.q | 2 +- di/torq/settings/segmentedtp.q | 5 +-- 8 files changed, 40 insertions(+), 53 deletions(-) diff --git a/di/torq/proc/segmentedtp/sctp.q b/di/torq/proc/segmentedtp/sctp.q index dae6209b..ed2ce540 100644 --- a/di/torq/proc/segmentedtp/sctp.q +++ b/di/torq/proc/segmentedtp/sctp.q @@ -1,13 +1,3 @@ -.sctp.chainedtp:@[value;`.sctp.chainedtp;0b]; / switches between STP and SCTP -.sctp.loggingmode:@[value;`.sctp.loggingmode;`none]; / [none|create|parent] -.sctp.tickerplantname:@[value;`.sctp.tickerplantname;`stp1]; -.sctp.tpconnsleep:@[value;`.sctp.tpconnsleep;10]; -.sctp.tpcheckcycles:@[value;`.sctp.tpcheckcycles;0W]; -.sctp.subscribeto:@[value;`.sctp.subscribeto;`]; -.sctp.subscribesyms:@[value;`.sctp.subscribesyms;`]; -.sctp.replay:@[value;`.sctp.replay;0b]; -.sctp.schema:@[value;`.sctp.schema;1b]; - / subscribe to segmented tickerplant .sctp.subscribe:{[] s:.sub.getsubscriptionhandles[`;.sctp.tickerplantname;()!()]; diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 411b7793..f94bc710 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -29,7 +29,8 @@ Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;dat ## Settings -Flat `stplg_` settings, set onto `.stplg.`: +Every `stplg_` and `sctp_` setting and `createlogs` is required in `config`; the module keeps no defaults of +its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg_` settings are set onto `.stplg.`: | Key | Default | |---|---| @@ -39,20 +40,20 @@ Flat `stplg_` settings, set onto `.stplg.`: | `batchmode` | `` `defaultbatch `` — `immediate`, `defaultbatch` or `memorybatch` | | `replayperiod` | `` `day `` — `day` or `period` | | `customcsv` | `` ` `` — `table,mode` csv for `custom` | -| `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_` | +| `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_`; optional | | `errorlogname` | `` `segmentederrorlogfile `` | -Flat `sctp_` settings, set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +`sctp_` settings are set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or `parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and `subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and `subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctp_chainedtp" = true`). -`di/torq/settings/segmentedtp.q` declares every `stplg` default except `kdbtplog`, and every `sctp` default, so any of -them can be given on the command line as `-stplg_` or `-sctp_`; an app sets only the keys it overrides. +Any of them can be given on the command line as `-stplg_`, `-sctp_` or `-createlogs`; an app sets only the +keys it overrides. An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. -Flat: `schemafile` (required unless chained), `createlogs` (`1b`). +Flat: `schemafile` (required unless chained), `createlogs` (`1b`, required). ## init[config;deps] diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 3284de7a..84fa4827 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -7,6 +7,11 @@ init:{[config;deps] if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; if[not `handlers in key deps;'"di.torq.proc.segmentedtp: handlers dependency is required - see di.torq.handlers"]; + / every setting comes from config - di/torq/settings/segmentedtp.q declares them all + req:`stplg_multilog`stplg_multilogperiod`stplg_errmode`stplg_batchmode`stplg_replayperiod`stplg_customcsv`stplg_errorlogname; + req,:`sctp_chainedtp`sctp_loggingmode`sctp_tickerplantname`sctp_tpconnsleep`sctp_tpcheckcycles`sctp_subscribeto; + req,:`sctp_subscribesyms`sctp_replay`sctp_schema`createlogs; + if[count m:req except key config;'"di.torq.proc.segmentedtp: missing settings: ",", " sv string m]; .z.m.log:deps`log; .z.m.procname:config`procname; .z.m.proctype:config`proctype; @@ -18,23 +23,23 @@ init:{[config;deps] .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; if[`stplg_kdbtplog in key config;.stplg.kdbtplog:tosym config`stplg_kdbtplog]; - .stplg.multilog:$[`stplg_multilog in key config;tosym config`stplg_multilog;`tabperiod]; - .stplg.multilogperiod:$[`stplg_multilogperiod in key config;config`stplg_multilogperiod;0D01]; - .stplg.errmode:$[`stplg_errmode in key config;config`stplg_errmode;1b]; - .stplg.batchmode:$[`stplg_batchmode in key config;tosym config`stplg_batchmode;`defaultbatch]; - .stplg.replayperiod:$[`stplg_replayperiod in key config;tosym config`stplg_replayperiod;`day]; - .stplg.customcsv:$[`stplg_customcsv in key config;tosym config`stplg_customcsv;`]; - .stplg.errorlogname:$[`stplg_errorlogname in key config;tosym config`stplg_errorlogname;`segmentederrorlogfile]; - .sctp.chainedtp:$[`sctp_chainedtp in key config;config`sctp_chainedtp;0b]; - .sctp.loggingmode:$[`sctp_loggingmode in key config;tosym config`sctp_loggingmode;`none]; - .sctp.tickerplantname:$[`sctp_tickerplantname in key config;tosym config`sctp_tickerplantname;`stp1]; - .sctp.tpconnsleep:$[`sctp_tpconnsleep in key config;config`sctp_tpconnsleep;10]; - .sctp.tpcheckcycles:$[`sctp_tpcheckcycles in key config;config`sctp_tpcheckcycles;0W]; - .sctp.subscribeto:$[`sctp_subscribeto in key config;tosym config`sctp_subscribeto;`]; - .sctp.subscribesyms:$[`sctp_subscribesyms in key config;tosym config`sctp_subscribesyms;`]; - .sctp.replay:$[`sctp_replay in key config;config`sctp_replay;0b]; - .sctp.schema:$[`sctp_schema in key config;config`sctp_schema;1b]; - if[`createlogs in key config;set[`createlogs;config`createlogs]]; + .stplg.multilog:tosym config`stplg_multilog; + .stplg.multilogperiod:config`stplg_multilogperiod; + .stplg.errmode:config`stplg_errmode; + .stplg.batchmode:tosym config`stplg_batchmode; + .stplg.replayperiod:tosym config`stplg_replayperiod; + .stplg.customcsv:tosym config`stplg_customcsv; + .stplg.errorlogname:tosym config`stplg_errorlogname; + .sctp.chainedtp:config`sctp_chainedtp; + .sctp.loggingmode:tosym config`sctp_loggingmode; + .sctp.tickerplantname:tosym config`sctp_tickerplantname; + .sctp.tpconnsleep:config`sctp_tpconnsleep; + .sctp.tpcheckcycles:config`sctp_tpcheckcycles; + .sctp.subscribeto:tosym config`sctp_subscribeto; + .sctp.subscribesyms:tosym config`sctp_subscribesyms; + .sctp.replay:config`sctp_replay; + .sctp.schema:config`sctp_schema; + set[`createlogs;config`createlogs]; / subscribers replay from the parent's logs if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; / singular or tabular: no intraday roll @@ -65,9 +70,6 @@ init:{[config;deps] .stplg.init[string .z.m.procname]; } -/ allow tickerplant to create a log file -@[`.;`createlogs;:;@[value;`createlogs;1b]]; - / subscribers use this to determine what type of process they are talking to @[`.;`tptype;:;`segmented]; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q index 1d78b045..dc0949bb 100644 --- a/di/torq/proc/segmentedtp/stplog.q +++ b/di/torq/proc/segmentedtp/stplog.q @@ -6,17 +6,9 @@ / view of log file handles for faster lookups value"loghandles::exec tbl!handle from currlog"; -/ settings -.stplg.multilog:`tabperiod / [tabperiod|none|periodic|tabular|custom] -.stplg.multilogperiod:0D01 -.stplg.errmode:1b -.stplg.batchmode:`defaultbatch / [memorybatch|defaultbatch|immediate] -.stplg.replayperiod:`day / [period|day|prior] -.stplg.customcsv:` +/ log root; config stplg_kdbtplog overrides it .stplg.kdbtplog:`$getenv`KDBTPLOG -.stplg.errorlogname:@[value;`.stplg.errorlogname;`segmentederrorlogfile] - / create log directory `:stplogs/date/tabname_time .stplg.createdld:{[name;date] if[not count dir:hsym .stplg.kdbtplog;.z.m.log[`error][`stp;"log directory not defined"];exit 1]; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 5935a543..97cff7d4 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -8,10 +8,11 @@ comment,,,,,,,init and settings fail,0,0,q,"seg.init[()!();()!()]",1,,init without log must error fail,0,0,q,"seg.init[()!();enlist[`log]!enlist nolog]",1,,init without timer must error fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]})]",1,,init without handlers must error -true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~.stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv",1,,stplg defaults -true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~.sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema",1,,sctp defaults -true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""stplg_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped stplg keys declare the module's own defaults (so each is overridable from the command line) -true,0,0,q,"{all {[c;k] c[k]~get ` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""sctp_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,the shipped sctp keys declare the module's own defaults +fail,0,0,q,"seg.init[()!();`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};enlist[`register]!enlist {[a;b;c;d;e]})]",1,,init without the settings must error +true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~ha"".stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv""",1,,stplg defaults from the settings file +true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~ha"".sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema""",1,,sctp defaults from the settings file +true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""stplg_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped stplg key lands unchanged after init +true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""sctp_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped sctp key lands unchanged after init true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index 41d322da..a0a1fe9c 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -36,7 +36,7 @@ setupfixture:{[] $[n in `s`p;"(use`di.torq.servers)[`init][`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(nolog;notimer;hd;`segmentedtp;`",string[n],";FIXDIR,\"/process.csv\";`segmentedtp;0b;0b)]";""]; "system \"t 60000\""; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[(enlist[`proctype]!enlist`segmentedtp),",c,";`log`timer`handlers!(nolog;notimer;hd)]"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),(enlist[`proctype]!enlist`segmentedtp),",c,";`log`timer`handlers!(nolog;notimer;hd)]"; "(`$\":\",FIXDIR,\"/",string[n],".port\") 0: enlist string system \"p\"")}'[key CFGS;value CFGS]; start each `a`b`c; PORTS[`a`b`c]:waitport each `a`b`c; diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index 12b008b0..3305ae06 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -49,7 +49,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; ".u.upd[`quote;(enlist`a;enlist 3f)]"; ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index aada54e0..65b424d8 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,8 +1,8 @@ / connections only; an app clients section replaces this whole section clients:(enlist`opencloseonly)!enlist 1b zpsignore:(enlist`enabled)!enlist 0b -/ every basic-typed stplg and sctp default as a flat key, so each can be overridden from the command line -/ (-stplg_, -sctp_); must agree with the module's own defaults. kdbtplog comes from the environment +/ every setting and its default; init requires them all. Each can be overridden from the command line +/ (-stplg_, -sctp_, -createlogs). kdbtplog comes from the environment stplg_multilog:`tabperiod stplg_multilogperiod:0D01 stplg_errmode:1b @@ -19,3 +19,4 @@ sctp_subscribeto:` sctp_subscribesyms:` sctp_replay:0b sctp_schema:1b +createlogs:1b From 5495e2e53ceabf6c8f2f705b31ae48f2bd8cb468 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Tue, 13 Oct 2026 17:47:42 +0100 Subject: [PATCH 35/42] Trim comments in the segmentedtp/tickerlogreplay/merge work Comment-only: shortens the notes added in the recent settings and namespace changes (merge.q, both module inits, both settings files, torq.q, tickerlogreplay test.q). Co-Authored-By: Claude Opus 5.5 --- di/merge/merge.q | 7 ++----- di/torq/proc/segmentedtp/segmentedtp.q | 2 +- di/torq/proc/tickerlogreplay/test.q | 2 +- di/torq/proc/tickerlogreplay/tickerlogreplay.q | 4 ++-- di/torq/settings/segmentedtp.q | 3 +-- di/torq/settings/tickerlogreplay.q | 5 ++--- di/torq/torq.q | 2 +- 7 files changed, 10 insertions(+), 15 deletions(-) diff --git a/di/merge/merge.q b/di/merge/merge.q index 298fcde0..519c4181 100644 --- a/di/merge/merge.q +++ b/di/merge/merge.q @@ -5,9 +5,7 @@ / per partition by a row-count / byte-size limit / merging keeps memory flat - segments are read and upserted a batch at a time rather / than held in memory and written once at end-of-day -/ the parted (`p#) column(s) for a table are supplied by the caller as extrapartitiontype, or -/ looked up by getextrapartitiontype in a sort config the caller passes in; the module never -/ reads sort config itself, so it stays independent of di.sort +/ p# columns come from the caller, or from a sort config it passes in; never read here / config and the injected log dependency are passed to init in a single dictionary: config / keys (see merge.md) are optional with defaults; log is required and init errors / immediately if it is missing or does not provide info/error - see merge.md @@ -265,8 +263,7 @@ getfirstcharpartitions:{[tablename;extrapartitiontype] group ?[tablename;();();({first each string x};(distinct;first extrapartitiontype))] }; -/ the parted column(s) for a table from a sort config (tabname/column/sort/att): the table's own -/ p# columns, else the default's +/ a table's p# columns from a sort config, else the default's getextrapartitiontype:{[sortconfig;tablename] requireinit[`getextrapartitiontype]; tabparts:$[count tabparts:distinct exec column from sortconfig where tabname=tablename,sort=1,att=`p; diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 84fa4827..d23fc409 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -7,7 +7,7 @@ init:{[config;deps] if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; if[not `handlers in key deps;'"di.torq.proc.segmentedtp: handlers dependency is required - see di.torq.handlers"]; - / every setting comes from config - di/torq/settings/segmentedtp.q declares them all + / all settings required req:`stplg_multilog`stplg_multilogperiod`stplg_errmode`stplg_batchmode`stplg_replayperiod`stplg_customcsv`stplg_errorlogname; req,:`sctp_chainedtp`sctp_loggingmode`sctp_tickerplantname`sctp_tpconnsleep`sctp_tpcheckcycles`sctp_subscribeto; req,:`sctp_subscribesyms`sctp_replay`sctp_schema`createlogs; diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index 3305ae06..fbb3988c 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -16,7 +16,7 @@ replayp:{[pre;cfg] runq( "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; "exit 0"))} replay:replayp[()] -/ replay settings for the plain log, with overrides; sect puts them over the shipped settings +/ replay settings for the plain log, with overrides plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} sect:{[x] "((use`di.torq.config)[`parsefile] \"di/torq/settings/tickerlogreplay.q\"),",x} ran:{[x] read0 fp"run.log"} diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index 2536a0b6..a5bcd1d1 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,7 +18,7 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - / every setting comes from config - di/torq/settings/tickerlogreplay.q declares them all + / all settings required req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; req,:`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`compression; req,:`partandmerge`tempdir`mergenumrows`mergenumtab`mergenumbytes`mergemethod`mergebybytelimit`partlimit; @@ -97,7 +97,7 @@ if[not `postreplay in key `.save;.save.postreplay:{[d;p] }]; -/ default upd function used for replaying data; set .replay.upd before use to override +/ default upd; set .replay.upd before use to override .replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] / save down settings diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 65b424d8..07bd1429 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,8 +1,7 @@ / connections only; an app clients section replaces this whole section clients:(enlist`opencloseonly)!enlist 1b zpsignore:(enlist`enabled)!enlist 0b -/ every setting and its default; init requires them all. Each can be overridden from the command line -/ (-stplg_, -sctp_, -createlogs). kdbtplog comes from the environment +/ all required by init; override as -. kdbtplog comes from the environment stplg_multilog:`tabperiod stplg_multilogperiod:0D01 stplg_errmode:1b diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q index 2c00cbcd..c7576bef 100644 --- a/di/torq/settings/tickerlogreplay.q +++ b/di/torq/settings/tickerlogreplay.q @@ -1,6 +1,5 @@ / tickerlogreplay settings -/ every setting and its default; init requires them all. Basic-typed ones can be overridden from the -/ command line (-) +/ all required by init; override basic-typed ones as - firstmessage:0 lastmessage:0W messagechunks:0W @@ -27,6 +26,6 @@ mergenumbytes:500000000 mergemethod:`part compression:() mergenumtab:`quote`trade!10000 50000 -/ di.merge's mergebybytelimit and partlimit, passed to its init +/ passed to di.merge's init mergebybytelimit:0b partlimit:1000 diff --git a/di/torq/torq.q b/di/torq/torq.q index a412485f..70f08ab1 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -279,7 +279,7 @@ init:{[proctype;procname;overrides] logdep:buildlogdep[overrides]; cc:use`di.torq.config; (cc`init)[enlist[`log]!enlist logdep]; - / segmentedchainedtp shares segmentedtp's settings tier; dispatch keeps the real proctype + / segmentedchainedtp uses segmentedtp's settings settingsproctype:$[proctype=`segmentedchainedtp;`segmentedtp;proctype]; config:(cc`cascade)[r 0;r 1;settingsproctype;procname]; / command-line override layer - the TOP cascade tier. A launch flag matching a settings name From fecb69a96b52d242ddc8277a6d183a920dd055a4 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 14 Oct 2026 11:19:30 +0100 Subject: [PATCH 36/42] Namespace cleanup: no \d in clienttracking, servers, chainedtp, subscriptions, pubsub A name stays at true root only where something outside its file reaches it; everything else is module-private. Root names are explicit dotted names or @[`.;`x;:;v]. - clienttracking: root .clients.clients and .dotz.liveh/livehn/liveh0; the rest private. Settings become required clients_* keys in settings/default.q. - servers: root .servers.getservers (5-arg), connectcustom, startupdepnamecycles; attributematch, reqprocsnotconn, reqprocnamesnotconn, startupdepcyclestypename private. - chainedtp: .ctp gone; root tptype, tablelist, subdetails, upd, .u.subdetails, .u.end, .u.d, .u.icounts/jcounts (.u.i/j/l/L unchanged). The 11 settings are required from settings/chainedtp.q. - subscriptions: root .sub.subscribe, getsubscriptionhandles, SUBSCRIPTIONS; helpers private (autoreconnect fn renamed resubscribe). autoreconnect and checksubscriptionperiod are required from settings/default.q. - pubsub: root .stpps names used by segmentedtp/chainedtp, .u.sub/.u.pub, .ps.*, .ds.*; filtered registry and helpers private (clashing ones stp-prefixed). - Tests reach private state at .m.di.0.x; peer configs merge the settings files. Co-Authored-By: Claude Opus 5.5 --- di/clienttracking/clienttracking.md | 49 +++++++-------- di/clienttracking/clienttracking.q | 69 +++++++++----------- di/clienttracking/test.csv | 21 ++++--- di/clienttracking/test.q | 7 ++- di/pubsub/pubsub.md | 13 ++-- di/pubsub/pubsub.q | 97 ++++++++++++++--------------- di/pubsub/test.csv | 2 +- di/subscriptions/subscriptions.md | 15 ++--- di/subscriptions/subscriptions.q | 46 ++++++-------- di/subscriptions/test.csv | 23 +++---- di/subscriptions/test.q | 5 +- di/torq/proc/chainedtp/chainedtp.md | 20 +++--- di/torq/proc/chainedtp/chainedtp.q | 89 ++++++++++++-------------- di/torq/proc/chainedtp/test.csv | 31 ++++----- di/torq/proc/chainedtp/test.q | 7 ++- di/torq/proc/segmentedtp/test.q | 5 +- di/torq/proc/tickerlogreplay/test.q | 2 +- di/torq/servers/servers.md | 16 +++-- di/torq/servers/servers.q | 18 +++--- di/torq/servers/test.csv | 2 +- di/torq/settings/default.q | 11 +++- di/torq/settings/segmentedtp.q | 4 +- di/torq/settings/tickerplant.q | 4 +- di/torq/test.csv | 6 +- 24 files changed, 277 insertions(+), 285 deletions(-) diff --git a/di/clienttracking/clienttracking.md b/di/clienttracking/clienttracking.md index ca5ed538..134d0cbe 100644 --- a/di/clienttracking/clienttracking.md +++ b/di/clienttracking/clienttracking.md @@ -8,36 +8,34 @@ queries they sent, how many failed and how many bytes they were sent. | Name | What | |---|---| | `.clients.clients` | session table, keyed on `w`: `ipa u a k K c s o f pid port startp endp lastp hits errs sz` | -| `.clients.po[result;W]` / `.clients.wo[result;W]` | record a new connection / websocket | -| `.clients.pc[result;W]` | mark a closed connection: `w` becomes null, `endp` is set | -| `.clients.hit[x]` / `.clients.hite[x]` | count a query and its result bytes / count a failed query, then re-signal | -| `.clients.cleanup[]` | mark dead handles, close idle ones (`MAXIDLE`), purge old closed rows (`RETAIN`) | -| `.clients.addw[w]` | record handle `w` by hand | -| `.clients.unregistered[]` | see below | -| `.dotz.ipa` / `.dotz.liveh` / `.dotz.livehn` | host name lookup and live-handle checks, defined if absent | +| `.dotz.liveh` / `.dotz.livehn` / `.dotz.liveh0` | live-handle checks, defined if absent (di.torq.servers defines them too) | + +Everything else is module-private: `po`/`wo` record a new connection/websocket, `pc` marks a closed one +(`w` null, `endp` set), `hit`/`hite` count a query and its result bytes / a failed query, `cleanup` marks +dead handles, closes idle ones and purges old closed rows, `addw[w]` records a handle by hand. ## Settings -A `clients` section of the process config, set onto `.clients.`: +Required in `config`; `di/torq/settings/default.q` declares them all: | Key | Default | Meaning | |---|---|---| -| `enabled` | `1b` | track connections | -| `opencloseonly` | `0b` | track connections but not queries | -| `INTRUSIVE` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | -| `AUTOCLEAN` | `1b` | not read | -| `RETAIN` | `` `long$0D02 `` | nanoseconds to keep a closed row | -| `MAXIDLE` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | +| `clients_enabled` | `1b` | track connections | +| `clients_opencloseonly` | `0b` | track connections but not queries | +| `clients_intrusive` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | +| `clients_autoclean` | `1b` | not read | +| `clients_retain` | `` `long$0D02 `` | nanoseconds to keep a closed row | +| `clients_maxidle` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | ## init[config;deps] Requires `handlers` (`di.torq.handlers`). It: -1. applies the `clients` section; -2. registers `.clients.pc` on `.z.pc`, whether or not `enabled`; -3. when `enabled`, registers `.clients.po` on `.z.po`, `.clients.wo` on `.z.wo` and `.clients.pc` on `.z.wc`; -4. when `enabled` and not `opencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through - `di.torq.handlers`) with `{.clients.hit[@[x;y;.clients.hite]]}` around the current handler. +1. signals if any setting is missing, then applies them; +2. registers `pc` on `.z.pc`, whether or not `enabled`; +3. when `clients_enabled`, registers `po` on `.z.po`, `wo` on `.z.wo` and `pc` on `.z.wc`; +4. when `clients_enabled` and not `clients_opencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through + `di.torq.handlers`) with `{hit[@[x;y;hite]]}` around the current handler. An unset `.z.pg`/`.z.ps` is taken as `value`, and an unset `.z.ws` as an echo. Call `init` once: a second call wraps the query handlers again. An exec owner registered on those @@ -48,9 +46,9 @@ events through `di.torq.handlers` afterwards replaces the wrap. - `hits`, `errs` and `sz` count async (`.z.ps`) and websocket (`.z.ws`) messages too, including the bytes of results that are never sent back. - A closed row keeps its key with `w` set to null, so several closed rows share a null key. -- A handle closed by the `MAXIDLE` sweep still has a null `endp`, so the same sweep drops its row +- A handle closed by the `clients_maxidle` sweep still has a null `endp`, so the same sweep drops its row instead of marking it. -- `.clients.unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. +- The private `unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. - `hits` and `errs` are ints. ## Testing @@ -60,7 +58,8 @@ k4unit:use`di.k4unit k4unit.moduletest`di.clienttracking ``` -`test.q`/`test.csv` start four server peers (defaults, `opencloseonly`, disabled, and `INTRUSIVE` -with a one-second `MAXIDLE` and `RETAIN`) and connect to them. The tests cover the table and -defaults, connection rows, hits, bytes and errors, closing and `addw`, websocket rows, both -settings modes, the `INTRUSIVE` reply, idle closing and the `RETAIN` purge. +`test.q`/`test.csv` start four server peers, each configured from the settings file plus overrides +(defaults, `clients_opencloseonly`, disabled, and `clients_intrusive` with a one-second `clients_maxidle` +and `clients_retain`), and connect to them. The tests cover the settings, the table, the init checks, +the stored settings, connection rows, hits, bytes and errors, closing and `addw`, websocket rows, both +settings modes, the intrusive reply, idle closing and the retain purge. diff --git a/di/clienttracking/clienttracking.q b/di/clienttracking/clienttracking.q index a406a72a..afa14ffb 100644 --- a/di/clienttracking/clienttracking.q +++ b/di/clienttracking/clienttracking.q @@ -2,55 +2,50 @@ init:{[config;deps] if[not `handlers in key deps;'"di.clienttracking: handlers dependency is required - see di.torq.handlers"]; - {[s;k] set[` sv `.clients,k;s k]}[s] each key s:$[`clients in key config;config`clients;()!()]; + / all settings required + req:`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean`clients_retain`clients_maxidle; + if[count m:req except key config;'"di.clienttracking: missing settings: ",", " sv string m]; + .z.m.enabled:config`clients_enabled; + .z.m.opencloseonly:config`clients_opencloseonly; + .z.m.intrusive:config`clients_intrusive; + .z.m.autoclean:config`clients_autoclean; + .z.m.retain:config`clients_retain; + .z.m.maxidle:config`clients_maxidle; r:deps[`handlers]`register; - r[`.z.pc;`;`clients;0j;.clients.pc[::;]]; - if[.clients.enabled; - r[`.z.po;`;`clients;0j;.clients.po[::;]]; - r[`.z.wo;`;`clients;0j;.clients.wo[::;]]; - r[`.z.wc;`;`clients;0j;.clients.pc[::;]]; - if[not .clients.opencloseonly; - set[`.z.pg;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.pg;{.:}]]; - set[`.z.ps;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.ps;{.:}]]; - set[`.z.ws;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.ws;{{neg[.z.w]x;}}]]]]; + r[`.z.pc;`;`clients;0j;pc[::;]]; + if[enabled; + r[`.z.po;`;`clients;0j;po[::;]]; + r[`.z.wo;`;`clients;0j;wo[::;]]; + r[`.z.wc;`;`clients;0j;pc[::;]]; + if[not opencloseonly; + set[`.z.pg;{hit[@[x;y;hite]]}@[value;`.z.pg;{.:}]]; + set[`.z.ps;{hit[@[x;y;hite]]}@[value;`.z.ps;{.:}]]; + set[`.z.ws;{hit[@[x;y;hite]]}@[value;`.z.ws;{{neg[.z.w]x;}}]]]]; } -\d .dotz - -if[not `IPA in key `.dotz; - IPA:(.z.a,.Q.addr`localhost)!.z.h,`localhost; - ipa:{$[`~r:IPA x;IPA[x]:$[`~r:.Q.host x;`$"."sv string"i"$0x0 vs x;r];r]}]; +IPA:(.z.a,.Q.addr`localhost)!.z.h,`localhost; +ipa:{$[`~r:IPA x;.z.m.IPA[x]:$[`~r:.Q.host x;`$"."sv string"i"$0x0 vs x;r];r]}; +livehx:{y in x,key .z.W}; +/ live-handle checks, shared with di.torq.servers if[not `liveh in key `.dotz; - livehx:{y in x,key .z.W}; liveh:livehx(); livehn:livehx 0Ni; liveh0:livehx 0i]; - -\d .clients - -/ settings -enabled:1b -opencloseonly:0b -INTRUSIVE:0b -AUTOCLEAN:1b -RETAIN:`long$0D02 -MAXIDLE:`long$0D + .dotz.liveh:livehx(); .dotz.livehn:livehx 0Ni; .dotz.liveh0:livehx 0i]; -enabled:@[value;`enabled;1b] -opencloseonly:@[value;`opencloseonly;0b] - -clients:@[value;`clients;([w:`int$()]ipa:`symbol$();u:`symbol$();a:`int$();k:`date$();K:`float$();c:`int$();s:`int$();o:`symbol$();f:`symbol$();pid:`int$();port:`int$();startp:`timestamp$();endp:`timestamp$();lastp:`timestamp$();hits:`int$();errs:`int$();sz:`long$())] +/ root: queried remotely +.clients.clients:@[value;`.clients.clients;([w:`int$()]ipa:`symbol$();u:`symbol$();a:`int$();k:`date$();K:`float$();c:`int$();s:`int$();o:`symbol$();f:`symbol$();pid:`int$();port:`int$();startp:`timestamp$();endp:`timestamp$();lastp:`timestamp$();hits:`int$();errs:`int$();sz:`long$())]; unregistered:{except[key .z.W;exec w from`CLIENTS]} cleanup:{ if[count w0:exec w from`.clients.clients where not .dotz.livehn w; update endp:.z.p,w:0Ni from`.clients.clients where w in w0]; - if[.clients.MAXIDLE>0; - hclose each exec w from`.clients.clients where .dotz.liveh w,lastp<.z.p-.clients.MAXIDLE]; - delete from`.clients.clients where not .dotz.liveh w,endp<.z.p-.clients.RETAIN;} + if[maxidle>0; + hclose each exec w from`.clients.clients where .dotz.liveh w,lastp<.z.p-.z.m.maxidle]; + delete from`.clients.clients where not .dotz.liveh w,endp<.z.p-.z.m.retain;} hit:{update lastp:.z.p,hits:hits+1i,sz:sz+-22!x from`.clients.clients where w=.z.w;x} hite:{update lastp:.z.p,hits:hits+1i,errs:errs+1i from`.clients.clients where w=.z.w;'x} po:{[result;W] cleanup[]; - `.clients.clients upsert(W;.dotz.ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); - if[INTRUSIVE; + `.clients.clients upsert(W;ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); + if[intrusive; neg[W]"neg[.z.w]\"update k:\",(string .z.k),\",K:\",(-3!.z.K),\",c:\",(-3!.z.c),\",s:\",(-3!system\"s\"),\",o:\",(-3!.z.o),\",f:\",(-3!.z.f),\",pid:\",(-3!.z.i),\",port:\",(-3!system\"p\"),\" from`.clients.clients where w=.z.w\""]; result} addw:{po[x;x]} @@ -58,7 +53,5 @@ pc:{[result;W] update w:0Ni,endp:.z.p from`.clients.clients where w=W;cleanup[]; wo:{[result;W] cleanup[]; - `.clients.clients upsert(W;.dotz.ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); + `.clients.clients upsert(W;ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); result} - -\d . diff --git a/di/clienttracking/test.csv b/di/clienttracking/test.csv index 6e697b2c..5bd274c2 100644 --- a/di/clienttracking/test.csv +++ b/di/clienttracking/test.csv @@ -4,12 +4,14 @@ before,0,0,q,system "l di/clienttracking/test.q",1,,load fixture helpers before,0,0,q,setupfixture[],1,,start the server peers comment,,,,,,,settings and table -true,0,0,q,"(1b;0b;0b;1b)~.clients`enabled`opencloseonly`INTRUSIVE`AUTOCLEAN",1,,boolean defaults -true,0,0,q,"(`long$0D02;0)~.clients`RETAIN`MAXIDLE",1,,RETAIN two hours and MAXIDLE off +run,0,0,q,"S:(use`di.torq.config)[`parsefile] SETTINGS",1,,read the settings file +true,0,0,q,"(1b;0b;0b;1b)~S`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean",1,,boolean defaults +true,0,0,q,"(`long$0D02;0)~S`clients_retain`clients_maxidle",1,,retain two hours and maxidle off true,0,0,q,"(enlist`w)~keys .clients.clients",1,,table keyed on w true,0,0,q,"`ipa`u`a`k`K`c`s`o`f`pid`port`startp`endp`lastp`hits`errs`sz~cols value .clients.clients",1,,table columns true,0,0,q,"""iij""~exec t from meta .clients.clients where c in `hits`errs`sz",1,,hits and errs int; sz long fail,0,0,q,"ct.init[()!();()!()]",1,,init without handlers must error +fail,0,0,q,"ct.init[()!();enlist[`handlers]!enlist()!()]",1,,init without settings must error comment,,,,,,,connection lifecycle run,0,0,q,ha:peer PORTS`a,1,,connect to the default peer @@ -17,6 +19,7 @@ true,0,0,q,"1=ha""count select from .clients.clients where w=.z.w""",1,,a connec true,0,0,q,"(.z.u;`localhost;`int$.Q.addr`localhost)~(mine[ha;""u""];mine[ha;""ipa""];mine[ha;""a""])",1,,row records user and address true,0,0,q,"(mine[ha;""startp""]<=mine[ha;""lastp""]) and null mine[ha;""endp""]",1,,startp and lastp set; endp null while open true,0,0,q,"ha""all {`clients in exec name from h.list x} each `.z.po`.z.pc`.z.wo`.z.wc""",1,,open and close observers registered +true,0,0,q,"(S`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean`clients_retain`clients_maxidle)~ha"".m.di.0clienttracking`enabled`opencloseonly`intrusive`autoclean`retain`maxidle""",1,,init stores the settings comment,,,,,,,usage run,0,0,q,"n0:mine[ha;""hits""]; ha""1+1""; n1:mine[ha;""hits""]",1,,two sync queries @@ -31,10 +34,10 @@ comment,,,,,,,close and manual add run,0,0,q,"c0:ha""count select from .clients.clients where null w,not null endp""; hclose ha; hb:peer PORTS`a",1,,close and reconnect true,0,0,q,"(c0+1)=hb""count select from .clients.clients where null w,not null endp""",1,,a close nulls w and sets endp true,0,0,q,"1=hb""count select from .clients.clients where w=.z.w""",1,,the new connection has its own row -true,0,0,q,"0i=hb"".clients.addw .z.w; exec first hits from .clients.clients where w=.z.w""",1,,addw records the handle afresh -fail,0,0,q,"hb"".clients.unregistered[]""",1,,unregistered reads a CLIENTS table that does not exist -true,0,0,q,"hb"".clients.wo[::;999i]; 1=count select from .clients.clients where w=999i""",1,,a websocket open adds a row -true,0,0,q,"hb"".clients.pc[::;999i]; 0=count select from .clients.clients where w=999i""",1,,a websocket close nulls w +true,0,0,q,"0i=hb"".m.di.0clienttracking.addw .z.w; exec first hits from .clients.clients where w=.z.w""",1,,addw records the handle afresh +fail,0,0,q,"hb"".m.di.0clienttracking.unregistered[]""",1,,unregistered reads a CLIENTS table that does not exist +true,0,0,q,"hb"".m.di.0clienttracking.wo[::;999i]; 1=count select from .clients.clients where w=999i""",1,,a websocket open adds a row +true,0,0,q,"hb"".m.di.0clienttracking.pc[::;999i]; 0=count select from .clients.clients where w=999i""",1,,a websocket close nulls w comment,,,,,,,opencloseonly run,0,0,q,"hbb:peer PORTS`b; hbb""1+1""; hbb""1+1""",1,,connect and query the opencloseonly peer @@ -46,12 +49,12 @@ run,0,0,q,hc:peer PORTS`c,1,,connect to the disabled peer true,0,0,q,"0=hc""count .clients.clients""",1,,connections are not recorded true,0,0,q,"hc""(`clients in exec name from h.list`.z.pc) and not `clients in exec name from h.list`.z.po""",1,,.z.pc is still wired when disabled -comment,,,,,,,INTRUSIVE and settings section +comment,,,,,,,intrusive and settings overrides run,0,0,q,"hd:peer PORTS`d; hd""1""; hd""1""",1,,connect to the INTRUSIVE peer and let the reply arrive true,0,0,q,"(.z.i;.z.k;system""p"")~(mine[hd;""pid""];mine[hd;""k""];mine[hd;""port""])",1,,the client reported its pid and version and port -true,0,0,q,"(`long$0D00:00:01)~hd"".clients.MAXIDLE""",1,,a clients section overrides the defaults +true,0,0,q,"(`long$0D00:00:01)~hd"".m.di.0clienttracking.maxidle""",1,,settings override the defaults -comment,,,,,,,MAXIDLE and RETAIN +comment,,,,,,,maxidle and retain run,0,0,q,"hd2:peer PORTS`d; system ""sleep 1.5""; hd3:peer PORTS`d",1,,leave two connections idle past MAXIDLE then connect again true,0,0,q,"`closed~@[hd2;""1"";{`closed}]",1,,an idle connection is closed true,0,0,q,"1=hd3""count .clients.clients""",1,,closed idle connections and expired rows are dropped diff --git a/di/clienttracking/test.q b/di/clienttracking/test.q index dd2f56b6..86ba2416 100644 --- a/di/clienttracking/test.q +++ b/di/clienttracking/test.q @@ -8,7 +8,10 @@ peer:{[p] hopen `$":localhost:",string p} PORTS:`a`b`c`d!4#0N / a: defaults; b: opencloseonly; c: disabled; d: INTRUSIVE with a 1s MAXIDLE and RETAIN -CFGS:`a`b`c`d!("()!()";"enlist[`opencloseonly]!enlist 1b";"enlist[`enabled]!enlist 0b";"`INTRUSIVE`MAXIDLE`RETAIN!(1b;`long$0D00:00:01;`long$0D00:00:01)") +CFGS:`a`b`c`d!("()!()";"enlist[`clients_opencloseonly]!enlist 1b";"enlist[`clients_enabled]!enlist 0b";"`clients_intrusive`clients_maxidle`clients_retain!(1b;`long$0D00:00:01;`long$0D00:00:01)") + +/ the settings file, the base of every peer's config +SETTINGS:"di/torq/settings/default.q" setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; @@ -16,7 +19,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist `info`warn`error!3#{[c;m]}"; "ct:use`di.clienttracking"; - "ct.init[enlist[`clients]!enlist ",c,";enlist[`handlers]!enlist `register`remove`list#h]")}'[key CFGS;value CFGS]; + "ct.init[((use`di.torq.config)[`parsefile] \"",SETTINGS,"\"),",c,";enlist[`handlers]!enlist `register`remove`list#h]")}'[key CFGS;value CFGS]; p:40000+(`int$.z.i mod 20000)+til 500; p:p where isfree each p; PORTS::key[PORTS]!4#p; {system QBIN," ",FIXDIR,"/",string[x],".q -p ",(string y)," -q /dev/null 2>&1 &"}'[key PORTS;value PORTS]; diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 018b67da..9a8970b7 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -87,13 +87,12 @@ q)pubsub.subscribestrfilter["quote";"bid>50.0";"time,sym,bid"] ## `.stpps`, `.u.sub`, `.ps` -A second pub/sub API at root, in a `\d .stpps` section at the end of `pubsub.q`, with its own state, -A second pub/sub API at root, in a `\d .stpps` section at the end of `pubsub.q`, with its own state, -separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `.stpps.endp`/`end`, -`allsubhandles`, `suball`/`subfiltered`/`add`/`errparse`/`addfiltered`/`selfiltered`/`pub`/`pubclear`, -`delhandle`/`delhandlef`/`closesub`/`extractschema`/`attrstrip`/`init`, root `.u.sub`/`.u.pub`, -`.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`/`subtable`/`subtablefiltered`, and -`.ds.map`/`subreq`/`stripe`. +A second pub/sub API at root, with its own state, separate from the API above: `.stpps.t`/`subrequestall`/ +`schemas`/`tabcols`, `.stpps.endp`/`end`/`allsubhandles`/`pub`/`pubclear`/`closesub`/`attrstrip`/`init`, +root `.u.sub`/`.u.pub`, `.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`/`subtable`/`subtablefiltered`, +and `.ds.map`/`subreq`/`stripe`. Its filtered-subscription registry `subrequestfiltered`, +`schemasnoattributes` and the helpers `stpsuball`/`stpsubfiltered`/`stpadd`/`errparse`/`stpaddfiltered`/ +`selfiltered`/`stpdelhandle`/`stpdelhandlef`/`stpextractschema` are module-private. - `endp[cur;next;data]` and `end[date;data]` send `(`endofperiod;cur;next;data)` and `(`endofday;date;data)` to every subscriber. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index de3af60a..f3119682 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -131,108 +131,105 @@ init:{[deps] if[count tabcols;.z.m.initialized:1b]; }; -/ .stpps, .u.sub, .ps -\d .stpps +/ root, for segmentedtp and chainedtp: the stp pub/sub tables and subscribers +.stpps.t:`; +.stpps.subrequestall:enlist[`]!enlist (); +subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()); -t:` -subrequestall:enlist[`]!enlist () -subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()) - -endp:{ - (neg allsubhandles[])@\:(`endofperiod;x;y;z); +.stpps.endp:{ + (neg .stpps.allsubhandles[])@\:(`endofperiod;x;y;z); }; -end:{ - (neg allsubhandles[])@\:(`endofday;x;y); +.stpps.end:{ + (neg .stpps.allsubhandles[])@\:(`endofday;x;y); }; -allsubhandles:{ - distinct raze union/[value subrequestall;exec handle from .stpps.subrequestfiltered] +.stpps.allsubhandles:{ + distinct raze union/[value .stpps.subrequestall;exec handle from .z.m.subrequestfiltered] }; -suball:{ - delhandle[x;.z.w]; - add[x]; - :(x;schemas[x]); +stpsuball:{ + stpdelhandle[x;.z.w]; + stpadd[x]; + :(x;.stpps.schemas[x]); }; -subfiltered:{[x;y] - delhandlef[x;.z.w]; - val:![11 99h;(selfiltered;addfiltered)][type y] . (x;y); - $[all raze null val;(x;schemas[x]);val] +stpsubfiltered:{[x;y] + stpdelhandlef[x;.z.w]; + val:![11 99h;(selfiltered;stpaddfiltered)][type y] . (x;y); + $[all raze null val;(x;.stpps.schemas[x]);val] }; -add:{ - if[not (count subrequestall x)>i:subrequestall[x]?.z.w; - subrequestall[x],:.z.w]; +stpadd:{ + if[not (count .stpps.subrequestall x)>i:.stpps.subrequestall[x]?.z.w; + .stpps.subrequestall[x],:.z.w]; }; errparse:{.z.m.log[`error][`addfiltered;m:y," error: ",x];'m}; -addfiltered:{[x;y] - filters:$[all null f:y[x;`filters];();@[parse;"select from t where ",f;.stpps.errparse[;"Filter"]] 2]; - columns:last $[all null c:y[x;`columns];();@[parse;"select ",c," from t";.stpps.errparse[;"Column"]]]; - @[eval;(?;.stpps.schemas[x];filters;0b;columns);.stpps.errparse[;"Query"]]; - `.stpps.subrequestfiltered upsert (x;.z.w;filters;columns); +stpaddfiltered:{[x;y] + filters:$[all null f:y[x;`filters];();@[parse;"select from t where ",f;errparse[;"Filter"]] 2]; + columns:last $[all null c:y[x;`columns];();@[parse;"select ",c," from t";errparse[;"Column"]]]; + @[eval;(?;.stpps.schemas[x];filters;0b;columns);errparse[;"Query"]]; + .z.m.subrequestfiltered:.z.m.subrequestfiltered upsert (x;.z.w;filters;columns); }; selfiltered:{[x;y] filts:enlist enlist (in;`sym;enlist y); - @[eval;(?;.stpps.schemas[x];filts;0b;());.stpps.errparse[;"Query"]]; - `.stpps.subrequestfiltered upsert (x;.z.w;filts;()); + @[eval;(?;.stpps.schemas[x];filts;0b;());errparse[;"Query"]]; + .z.m.subrequestfiltered:.z.m.subrequestfiltered upsert (x;.z.w;filts;()); }; -pub:{[t;x] +.stpps.pub:{[t;x] if[not count x;:()]; - if[count h:subrequestall[t];-25!(h;(`upd;t;x))]; - if[t in .stpps.subrequestfiltered`tbl; + if[count h:.stpps.subrequestall[t];-25!(h;(`upd;t;x))]; + if[t in .z.m.subrequestfiltered`tbl; {[t;x;sels] data:eval(?;x;sels`filts;0b;sels`columns); if[count data;neg[sels`handle](`upd;t;data)]}[t;x;] - each select handle,filts,columns from .stpps.subrequestfiltered where tbl=t + each select handle,filts,columns from .z.m.subrequestfiltered where tbl=t ]; }; -pubclear:{ +.stpps.pubclear:{ .stpps.pub'[x;value each x,:()]; - @[`.;x;:;.stpps.schemasnoattributes[x]]; + @[`.;x;:;schemasnoattributes[x]]; } -delhandle:{[t;h] +stpdelhandle:{[t;h] @[`.stpps.subrequestall;t;except;h]; }; -delhandlef:{[t;h] - delete from `.stpps.subrequestfiltered where tbl=t,handle=h; +stpdelhandlef:{[t;h] + .z.m.subrequestfiltered:delete from .z.m.subrequestfiltered where tbl=t,handle=h; }; -closesub:{[h] - delhandle[;h]each t; - delhandlef[;h]each t; +.stpps.closesub:{[h] + stpdelhandle[;h]each .stpps.t; + stpdelhandlef[;h]each .stpps.t; }; -extractschema:{t:value x; $[.Q.qp t; t; 0#t]}; +stpextractschema:{t:value x; $[.Q.qp t; t; 0#t]}; -attrstrip:{[t] +.stpps.attrstrip:{[t] {@[x;cols x;`#]} each .stpps.t:t; - .stpps.schemasnoattributes:.stpps.t!extractschema each .stpps.t; + .z.m.schemasnoattributes:.stpps.t!stpextractschema each .stpps.t; }; -init:{[t] +.stpps.init:{[t] if[count b:t where not t in tables[];{.z.m.log[`error][`psinit;m:"Table ",string[x]," does not exist"];'m} each b]; .stpps.t:t except b; - .stpps.schemas:.stpps.t!extractschema each .stpps.t; + .stpps.schemas:.stpps.t!stpextractschema each .stpps.t; .stpps.tabcols:.stpps.t!cols each .stpps.t; }; -\d . - +/ root: the subscribe/publish entry points .u.sub:{[x;y] if[x~`;:.z.s[;y] each .stpps.t]; if[not x in .stpps.t; .z.m.log[`error][`sub;m:"Table ",string[x]," not in list of stp pub/sub tables"]; :(x;m) ]; - $[y~`;.stpps.suball[x];.stpps.subfiltered[x;y]] + $[y~`;stpsuball[x];stpsubfiltered[x;y]] }; .u.pub:.stpps.pub diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index e5aa98ff..a2bd252e 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -133,7 +133,7 @@ run,0,0,q,"r:h(`.u.sub;`nosuch;`)",1,,subscribe to a table that is not published true,0,0,q,`nosuch~first r,1,,.u.sub returns the table name true,0,0,q,"(`sub;""Table nosuch not in list of stp pub/sub tables"")~h""lastlog""",1,,and logs the error through the injected log run,0,0,q,"r:h(`.u.sub;`quote;enlist`IBM)",1,,sym-filtered subscription (a sym list) -true,0,0,q,"clt in h""exec handle from .stpps.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered +true,0,0,q,"clt in h""exec handle from .m.di.0pubsub.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered true,0,0,q,"clt in h"".stpps.allsubhandles[]""",1,,allsubhandles includes the client run,0,0,q,"h(`.stpps.closesub;clt)",1,,closesub for the client handle true,0,0,q,"not clt in h"".stpps.allsubhandles[]""",1,,client removed from both registries diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 95142638..74863a5b 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -17,7 +17,7 @@ classic standard-TP `.u.i`/`.u.L`/`.u.d` global reads. | Function | Description | |---|---| -| `init[config;deps]` | validate the deps, stash `log`, load di.tplogmgr, apply the `.sub` settings, register `.sub.pc` and the `checksubscriptions` job (once) | +| `init[config;deps]` | validate the deps, stash `log`, load di.tplogmgr, signal if a setting is missing, apply the settings, register `pc` and the `checksubscriptions` job (once) | | `subscribe[tph;tabs;syms;replay]` | subscribe over an open TP handle; returns the subdetails dict | | `subscribed[]` | `1b` if any subscription is active | | `getsubscriptions[]` | the active-subscriptions registry table | @@ -55,15 +55,16 @@ in di.tplogmgr's module context) lands in the module's *private* namespace, not ## `.sub` -A second subscription API at root `.sub`, in a `\d .sub` section at the end of `subscriptions.q`, with -its own state: `AUTORECONNECT`, `checksubscriptionperiod`, `SUBSCRIPTIONS`, `getsubscriptionhandles`, -`updatesubscriptions`, `reconnectinit`, `reducesubs`, `createtables`, `replay`, `subscribe`, -`replayupd`, `checksubscriptions`, `retrysubscription`, `autoreconnect`, `pc`. `subscribe` asks the +A second subscription API at root: `.sub.subscribe[tabs;instrs;setschema;replaylog;proc]`, +`.sub.getsubscriptionhandles[proctype;procname;attributes]` and its registry `.sub.SUBSCRIPTIONS`. It is +built on the module-private `updatesubscriptions`, `reconnectinit`, `reducesubs`, `createtables`, `replay`, +`replayupd`, `checksubscriptions`, `retrysubscription`, `resubscribe` and `pc`. `.sub.subscribe` asks the publisher for its `tptype` (`standard`, `chained` or `segmented`) and subscribes to match. It calls `.servers.getservers`, `.servers.enabled` and `.servers.connectcustom` from `di.torq.servers` 0.5.0. -- Settings (flat config): `autoreconnect` (default `0b`), `checksubscriptionperiod` (default `0D00:00:10`). -- `init` registers, once per process: `.sub.pc[::;]` on `.z.pc` through `handlers`, and +- Settings, both required; `di/torq/settings/default.q` declares them: `autoreconnect` (`0b`), + `checksubscriptionperiod` (`0D00:00:10`). +- `init` registers, once per process: `pc[::;]` on `.z.pc` through `handlers`, and `checksubscriptions` every `checksubscriptionperiod` (converted to seconds, timer mode 1) through `timer` when the period is above 0. diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 30d15561..8d1e2092 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -22,12 +22,13 @@ init:{[config;deps] if[not `handlers in key deps;'"di.subscriptions: handlers dependency is required - see di.torq.handlers"]; .z.m.log:deps`log; .z.m.tp:use`di.tplogmgr; / for replayupto (repair-aware, count-limited -11!) - / .sub settings - if[`autoreconnect in key config;.sub.AUTORECONNECT:config`autoreconnect]; - if[`checksubscriptionperiod in key config;.sub.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod]; + / all settings required + if[count m:`autoreconnect`checksubscriptionperiod except key config;'"di.subscriptions: missing settings: ",", " sv string m]; + .z.m.autoreconnect:config`autoreconnect; + .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod; if[not .z.m.registered; - (deps[`handlers]`register)[`.z.pc;`;`sub;0j;.sub.pc[::;]]; - if[.sub.checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;.sub.checksubscriptions;();`long$.sub.checksubscriptionperiod%0D00:00:01;1;()!()]]; + (deps[`handlers]`register)[`.z.pc;`;`sub;0j;pc[::;]]; + if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();`long$checksubscriptionperiod%0D00:00:01;1;()!()]]; .z.m.registered:1b]; } @@ -88,15 +89,10 @@ subscribed:{[] 0(`long$.ctp.pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; - (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[.ctp.tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .ctp.tickerplantname];exit 0]}]; - .ctp.upd:$[.ctp.createlogfile; - $[.ctp.pubinterval;{[t;x] .ctp.writetolog[t;x];.ctp.batchpub[t;x];};{[t;x] .ctp.writetolog[t;x];.ctp.tickpub[t;x];}]; - $[.ctp.pubinterval;.ctp.batchpub;.ctp.tickpub]]; - if[not `upd in key `.;set[`upd;.ctp.upd]]; + .z.m.tickerplantname:config`tickerplantname; + .z.m.pubinterval:totimespan config`pubinterval; + .z.m.tpconnsleep:config`tpconnsleep; + .z.m.createlogfile:config`createlogfile; + .z.m.logdir:$[10h=type l:config`logdir;hsym`$l;l]; + .z.m.subscribeto:config`subscribeto; + .z.m.subscribesyms:config`subscribesyms; + .z.m.replay:config`replay; + .z.m.schema:config`schema; + .z.m.clearlogonsubscription:config`clearlogonsubscription; + .z.m.tpcheckcycles:config`tpcheckcycles; + if[0<>(`long$pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; + (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string tickerplantname];exit 0]}]; + .z.m.upd:$[createlogfile; + $[pubinterval;{[t;x] writetolog[t;x];batchpub[t;x];};{[t;x] writetolog[t;x];tickpub[t;x];}]; + $[pubinterval;batchpub;tickpub]]; + if[not `upd in key `.;set[`upd;upd]]; .ps.initialise[]; - .servers.startupdepnamecycles[.ctp.tickerplantname;.ctp.tpconnsleep;.ctp.tpcheckcycles]; - .ctp.subscribe[]; - .ctp.tableschemas:{x!(0#)@'value@'x} (),$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto]; - if[.ctp.pubinterval;(deps[`timer]`addjob)[`publishalltables;.ctp.publishalltables;();`long$.ctp.pubinterval%0D00:00:01;2;()!()]]; + .servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]; + subscribe[]; + .z.m.tableschemas:{x!(0#)@'value@'x} (),$[any null subscribeto;tables[`.];subscribeto]; + if[pubinterval;(deps[`timer]`addjob)[`publishalltables;publishalltables;();`long$pubinterval%0D00:00:01;2;()!()]]; } -\d . +/ root: the subscriber contract +@[`.;`tptype;:;`chained]; -tptype:`chained; +@[`.;`tablelist;:;{.stpps.t}]; -tablelist:{.stpps.t} - -subdetails:{[tabs;instruments] - r:.ctp.sub[tabs;instruments]; +@[`.;`subdetails;:;{[tabs;instruments] + r:sub[tabs;instruments]; `schemalist`logfilelist`rowcounts`date!r@/:(`schema;$[r[`logfile]~();();enlist`i`logfile];`icounts;`d) - } + }]; .u.subdetails:{[tabs;syms] - r:.ctp.sub[tabs;syms]; s:r`schema; + r:sub[tabs;syms]; s:r`schema; if[-11h=type first s;s:enlist s]; - `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[.ctp.createlogfile;r`logfile;`];$[.ctp.createlogfile;r`i;0];.u.d) + `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[createlogfile;r`logfile;`];$[createlogfile;r`i;0];.u.d) } -\d .ctp - -tickerplantname:@[value;`tickerplantname;`tickerplant1]; -pubinterval:@[value;`pubinterval;0D00:00:00]; -tpconnsleep:@[value;`tpconnsleep;10]; -createlogfile:@[value;`createlogfile;0b]; -logdir:@[value;`logdir;`:tplogs]; -subscribeto:@[value;`subscribeto;`]; -subscribesyms:@[value;`subscribesyms;`]; -replay:@[value;`replay;0b]; -schema:@[value;`schema;1b]; -clearlogonsubscription:@[value;`clearlogonsubscription;0b]; -tpcheckcycles:@[value;`tpcheckcycles;0W]; - tph:0N; .u.icounts:.u.jcounts:(`symbol$())!0#0,(); .u.i:.u.j:0; @@ -87,10 +83,10 @@ openlog:{[lgfile] } subscribe:{[] - s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; + s:.sub.getsubscriptionhandles[`;tickerplantname;()!()]; if[count s; subproc:first s; - .ctp.tph:subproc`w; + .z.m.tph:subproc`w; refreshtp @[tph;".u.d";.z.D]; .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; @@ -120,7 +116,7 @@ batchpub:{[t;x] } publishalltables:{[] - pubtables:$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto],(); + pubtables:$[any null subscribeto;tables[`.];subscribeto],(); .ps.publish'[pubtables;value each pubtables]; cleartables[pubtables]; .u.i:.u.j; @@ -134,7 +130,7 @@ cleartables:{[t] } createlogfilename:{[d] - ` sv (.ctp.logdir;`$string[.z.m.procname],"_",string d) + ` sv (logdir;`$string[.z.m.procname],"_",string d) } refreshtp:{[d] @@ -150,7 +146,7 @@ refreshtp:{[d] } notpconnected:{[] - 0 = count select from .sub.SUBSCRIPTIONS where procname in .ctp.tickerplantname, active} + 0 = count select from .sub.SUBSCRIPTIONS where procname in .z.m.tickerplantname, active} sub:{[subtabs;subsyms] r:(`schema`icounts`i`logfile`d)!(); @@ -161,13 +157,10 @@ sub:{[subtabs;subsyms] r } -\d .u - -end:{[d] +/ root: the upstream ends the day +.u.end:{[d] .z.m.log[`info][`end;"end of day invoked"]; - .ctp.publishalltables[]; - .ctp.refreshtp[d+1]; + publishalltables[]; + refreshtp[d+1]; (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`.u.end;d) } - -\d . diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index df1fec5e..5fc813c5 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -8,21 +8,22 @@ comment,,,,,,,init - dependencies fail,0,0,q,"ctp.init[cfg[];enlist[`log]!enlist mocklog]",1,,init without timer must error fail,0,0,q,"ctp.init[cfg[];`log`timer!(mocklog;mocktimer)]",1,,init without handlers must error fail,0,0,q,"ctp.init[cfg[];`timer`handlers!(mocktimer;mockhandlers)]",1,,init without log must error +fail,0,0,q,"ctp.init[`proctype`procname!(`chainedtp;`chainedtp1);deps[]]",1,,init without settings must error fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,a sub-second pubinterval must error fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir!(""0D00:00:00"";""tplogs"");deps[]]",1,,init with toml-style pubinterval and logdir strings -true,0,0,q,0D~.ctp.pubinterval,1,,a pubinterval string becomes a timespan -true,0,0,q,`:tplogs~.ctp.logdir,1,,a logdir string becomes a file symbol -true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle +true,0,0,q,0D~.m.di.0torq.0proc.0chainedtp.pubinterval,1,,a pubinterval string becomes a timespan +true,0,0,q,`:tplogs~.m.di.0torq.0proc.0chainedtp.logdir,1,,a logdir string becomes a file symbol +true,0,0,q,".m.di.0torq.0proc.0chainedtp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root true,0,0,q,.u.d~D,1,,date taken from the upstream true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered -true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade +true,0,0,q,`trade in key .m.di.0torq.0proc.0chainedtp.tableschemas,1,,tableschemas holds trade true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 -true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish +true,0,0,q,upd~.m.di.0torq.0proc.0chainedtp.tickpub,1,,root upd is tick-by-tick publish run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) true,0,0,q,`trade in .stpps.t,1,,trade is published @@ -31,7 +32,7 @@ run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstrea run,0,0,q,"r:dh""(.z.w)(`.u.sub;`trade;`)""",1,,downstream subscribes to trade true,0,0,q,`trade~first r,1,,.u.sub returns the table true,0,0,q,"dh in .stpps.subrequestall`trade",1,,downstream registered -run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows +run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows true,0,0,q,(enlist 3)~.u.icounts`trade,1,,icounts updated (one-item list as the subscribe reshape leaves it) true,0,0,q,"(1;3)~dh""(count got;count last last got)""",1,,downstream received the 3 rows true,0,0,q,"`schemalist`logfilelist`rowcounts`date~key dh""(.z.w)(`subdetails;`trade;`)""",1,,subdetails keys @@ -47,32 +48,32 @@ true,0,0,q,.u.d=D+1,1,,date rolled true,0,0,q,0=count trade,1,,trade cleared comment,,,,,,,own log and batch publish -run,0,0,q,".ctp.createlogfile:1b;.ctp.logdir:hsym`$FIXDIR;.ctp.refreshtp D",1,,create a log for D +run,0,0,q,".m.di.0torq.0proc.0chainedtp.createlogfile:1b;.m.di.0torq.0proc.0chainedtp.logdir:hsym`$FIXDIR;.m.di.0torq.0proc.0chainedtp.refreshtp D",1,,create a log for D true,0,0,q,".u.L~hsym`$FIXDIR,""/chainedtp1_"",string D",1,,log named /_ -run,0,0,q,.ctp.writetolog[`trade;rows 2],1,,write one message +run,0,0,q,.m.di.0torq.0proc.0chainedtp.writetolog[`trade;rows 2],1,,write one message true,0,0,q,"(1;1)~(.u.j;-11!(-2;.u.L))",1,,one message counted and on disk -run,0,0,q,.ctp.batchpub[`trade;rows 2],1,,batch 2 rows +run,0,0,q,.m.di.0torq.0proc.0chainedtp.batchpub[`trade;rows 2],1,,batch 2 rows true,0,0,q,2=count trade,1,,batched in the root table -run,0,0,q,.ctp.publishalltables[],1,,publish the batch +run,0,0,q,.m.di.0torq.0proc.0chainedtp.publishalltables[],1,,publish the batch true,0,0,q,"(2;2)~dh""(count got;count last last got)""",1,,downstream received the batch true,0,0,q,"(0;1)~(count trade;.u.i)",1,,trade cleared and .u.i caught up -run,0,0,q,.ctp.refreshtp D,1,,reopen the existing log +run,0,0,q,.m.di.0torq.0proc.0chainedtp.refreshtp D,1,,reopen the existing log true,0,0,q,1=.u.i,1,,existing messages counted -run,0,0,q,".ctp.clearlogonsubscription:1b;.ctp.refreshtp D",1,,reopen with clearlogonsubscription +run,0,0,q,".m.di.0torq.0proc.0chainedtp.clearlogonsubscription:1b;.m.di.0torq.0proc.0chainedtp.refreshtp D",1,,reopen with clearlogonsubscription true,0,0,q,0=.u.i,1,,log cleared run,0,0,q,"r:subdetails[`trade;`]",1,,subdetails with a log true,0,0,q,"(enlist(0;.u.L))~r`logfilelist",1,,logfilelist carries i and the log file run,0,0,q,"r:.u.subdetails[`trade;`]",1,,.u.subdetails with a log true,0,0,q,"(.u.L;.u.i)~r`logfile`rowcount",1,,logfile and rowcount are the own log and .u.i run,0,0,q,"bf:hsym`$FIXDIR,""/bad""; bf set (); lh:hopen bf; lh enlist(`upd;`trade;rows 1); hclose lh; bf 1: (read1 bf),0x0102030405",1,,write a log with one message and a bad tail -run,0,0,q,bh:.ctp.openlog bf,1,,open it +run,0,0,q,bh:.m.di.0torq.0proc.0chainedtp.openlog bf,1,,open it true,0,0,q,"errlogged""is corrupt""",1,,corruption reported true,0,0,q,-6h=type bh,1,,and the log opened anyway true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 comment,,,,,,,di.subscriptions subscriber downstream run,0,0,q,.stpps.closesub 0i,1,,drop handle 0 left by the local .u.subdetails call -run,0,0,q,".ctp.refreshtp D;.ctp.writetolog[`trade;rows 3];.ctp.tickpub[`trade;rows 3]",1,,fresh log with one 3-row message before the peer subscribes +run,0,0,q,".m.di.0torq.0proc.0chainedtp.refreshtp D;.m.di.0torq.0proc.0chainedtp.writetolog[`trade;rows 3];.m.di.0torq.0proc.0chainedtp.tickpub[`trade;rows 3]",1,,fresh log with one 3-row message before the peer subscribes run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,connect to the di.subscriptions peer run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,peer subscribes to trade through .u.subdetails true,0,0,q,(enlist`trade)~sd`tables,1,,tables is a symbol list for one table @@ -82,7 +83,7 @@ true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,schema for trade true,0,0,q,"sh""`trade in tables[]""",1,,trade defined at root on the peer true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,peer recorded the subscription true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `trade in sd2`tables",1,,tables is a symbol list for all tables -run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows +run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,peer received the rows after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 4bd55aa4..57bf48d3 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -29,7 +29,7 @@ setupfixture:{[] (`$":",FIXDIR,"/dsub.q") 0: ( "subs:use`di.subscriptions"; "nolog:`info`warn`error!3#{[c;m]}"; - "subs.init[()!();`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list!({[a;b;c;d;e]};{[a;b;c]};{[a]}))]"; + "subs.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list!({[a;b;c;d;e]};{[a;b;c]};{[a]}))]"; "got:()";"ended:()";"upd:{[t;x] got::got,enlist(t;x)}";"endofday:{ended::ended,x}"); p:30000+(`int$.z.i mod 20000)+til 500; p:p where isfree each p; `UPPORT`DNPORT`DSPORT set' 3#p; @@ -41,9 +41,10 @@ setupfixture:{[] svc:use`di.torq.servers initservers:{[] svc.init[`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(mocklog;mocktimer;mockhandlers;`chainedtp;`chainedtp1;FIXDIR,"/process.csv";`tickerplant;0b;0b)]} -cfg:{[] `proctype`procname`autoreconnect`pubinterval!(`chainedtp;`chainedtp1;0b;0D)} +/ the settings files plus the fixture's identity +cfg:{[] ((use`di.torq.config)[`parsefile] "di/torq/settings/default.q"),((use`di.torq.config)[`parsefile] "di/torq/settings/chainedtp.q"),`proctype`procname`autoreconnect`pubinterval!(`chainedtp;`chainedtp1;0b;0D)} deps:{[] `log`timer`handlers!(mocklog;mocktimer;mockhandlers)} rows:{[n] ([]time:n#.z.p;sym:n#`a`b;price:`float$til n)} -teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each (.ctp.tph;dh;sh); system "sleep 0.3"; system "rm -rf ",FIXDIR;} +teardownfixture:{[] {@[{(neg x)"exit 0";(neg x)[]};x;()]} each (.m.di.0torq.0proc.0chainedtp.tph;dh;sh); system "sleep 0.3"; system "rm -rf ",FIXDIR;} diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index a0a1fe9c..5711cb4d 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -36,7 +36,7 @@ setupfixture:{[] $[n in `s`p;"(use`di.torq.servers)[`init][`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(nolog;notimer;hd;`segmentedtp;`",string[n],";FIXDIR,\"/process.csv\";`segmentedtp;0b;0b)]";""]; "system \"t 60000\""; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),(enlist[`proctype]!enlist`segmentedtp),",c,";`log`timer`handlers!(nolog;notimer;hd)]"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\"),((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),(enlist[`proctype]!enlist`segmentedtp),",c,";`log`timer`handlers!(nolog;notimer;hd)]"; "(`$\":\",FIXDIR,\"/",string[n],".port\") 0: enlist string system \"p\"")}'[key CFGS;value CFGS]; start each `a`b`c; PORTS[`a`b`c]:waitport each `a`b`c; @@ -54,8 +54,7 @@ endofday:{[d;x] eods::eods,enlist(d;x)} endofperiod:{[c;n;d] eops::eops,enlist(c;n;d)} nolog:`info`warn`error!3#{[c;m]} subs:use`di.subscriptions -subs.init[enlist[`autoreconnect]!enlist 0b;`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list!({[a;b;c;d;e]};{[a;b;c]};{[a]}))] -.sub.AUTORECONNECT:0b +subs.init[((use`di.torq.config)[`parsefile] "di/torq/settings/default.q"),enlist[`autoreconnect]!enlist 0b;`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list!({[a;b;c;d;e]};{[a;b;c]};{[a]}))] subto:{[h;n;tabs;syms] .sub.subscribe[tabs;syms;1b;0b;`procname`proctype`w!(n;`segmentedtp;h)]} / feed rows: list of columns, time added by the tickerplant diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index fbb3988c..af9f7d8d 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -49,7 +49,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\"),((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; ".u.upd[`quote;(enlist`a;enlist 3f)]"; ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 0b33b6be..f5d3441a 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -105,15 +105,13 @@ Published at root by `init`, same bodies as legacy: | `.servers.pc` | l.383, run on `.z.pc` | | timers `discoveryretry` / `serversretry` | l.387–389 | -Defined directly at root in a `\d .servers` section, for legacy `.sub` and chainedtp: +Also defined at root, for di.subscriptions' `.sub` and the tickerplants' startup waits: +- `.servers.getservers` (5-arg; the exported 1-arg `getservers` is separate); +- `.servers.connectcustom` (called by `retryrows`); +- `.servers.startupdepnamecycles`. -| Name | trackservers.q | -|---|---| -| `.servers.attributematch` | l.64–68 | -| `.servers.getservers` (legacy 5-arg; the exported 1-arg `getservers` is separate) | l.75–89 | -| `.servers.connectcustom` (called by `retryrows`) | l.198 | -| `.servers.reqprocsnotconn` / `.servers.reqprocnamesnotconn` | l.348–351, l.357 | -| `.servers.startupdepcyclestypename` / `.servers.startupdepnamecycles` | l.360–373, l.379 | +They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqprocnamesnotconn` and +`startupdepcyclestypename`. The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, `startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to @@ -158,7 +156,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; - `waitfortype`, including a discovery stub that comes up after `startup`; -- the root `.servers` functions (`attributematch`, 5-arg `getservers`, `startupdepnamecycles`); +- `attributematch`, the root 5-arg `.servers.getservers` and `.servers.startupdepnamecycles`; - input validation and `getapimeta`. The rest of the discovery protocol is covered by `di.torq.proc.discovery`'s suite. Run in a fresh diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 3d673ce3..80bf783c 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -331,17 +331,14 @@ getapimeta:{[] (`waitfortype; 1b; "block until a proctype connects or timeout elapses"; "[symbol: proctype; long: timeoutms; long: pollms]"; "boolean: 1b connected, 0b timed out")); }; -/ root .servers functions for .sub and startup waits -\d .servers - / match required attributes against advertised ones attributematch:{[req;avail] vals:key[req] inter key avail; notpresent:noval!(count noval:key[req] except key avail)#enlist(0b;()); notpresent,vals!{($[0>type y;x~y;all x in y];(x,()) inter y,())}'[req vals;avail vals]} -/ servers matching types or names, optionally reopening closed handles -getservers:{[nameortype;lookups;req;autoopen;onlyone] +/ root, for .sub: servers matching types or names, optionally reopening closed handles +.servers.getservers:{[nameortype;lookups;req;autoopen;onlyone] r:$[`~lookups; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS; nameortype~`proctype; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where proctype in lookups; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where procname in lookups]; @@ -352,10 +349,10 @@ getservers:{[nameortype;lookups;req;autoopen;onlyone] if[(alivecount=0) or (not onlyone) or (any not exec max alive by agg:?[nameortype~`proctype;proctype;procname] from r); retryrows exec index from r where not alive; r:select procname,proctype,lastp,w,hpup,attributes,alive:.dotz.liveh w from .servers.SERVERS where i in r`index]]]; - select procname,proctype,lastp,w,hpup,attributes,attribmatch:.servers.attributematch[req]each attributes from r where alive} + select procname,proctype,lastp,w,hpup,attributes,attribmatch:.z.m.attributematch[req]each attributes from r where alive} -/ run on (re)connected SERVERS rows -connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}] +/ root, for .sub: run on (re)connected SERVERS rows +.servers.connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}]; / are any required processes not connected reqprocsnotconn:{[requiredprocs;typeorname] @@ -380,6 +377,5 @@ startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles] ]; }; -startupdepnamecycles:startupdepcyclestypename[;.servers.reqprocnamesnotconn;;]; - -\d . \ No newline at end of file +/ root, for chainedtp and segmentedtp +.servers.startupdepnamecycles:startupdepcyclestypename[;reqprocnamesnotconn;;]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index d734dffa..85f2ed3d 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -44,7 +44,7 @@ comment,,,,,,,waitfortype - connected vs timeout true,0,0,q,svc.waitfortype[`otherproc;2000;200],1,1,returns 1b immediately for an already-connected proctype true,0,0,q,0b~svc.waitfortype[`deadproc;700;200],1,1,returns 0b on timeout for a proctype that never comes up comment,,,,,,,root .servers functions -true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values +true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.m.di.0torq.0servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values true,0,0,q,"(enlist`otherproc)~exec proctype from .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,5-arg getservers returns the live row true,0,0,q,"`attribmatch in cols .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,getservers adds attribmatch true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,getservers drops dead rows diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index fc24ba06..79affe11 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1,4 +1,4 @@ -/ built-in framework defaults: the .servers and .sub settings +/ built-in framework defaults: the servers, subscriptions and clienttracking settings / discovery - off unless the app turns it on discoveryregister:0b / register with the discovery service @@ -20,4 +20,11 @@ autoclean:0b / drop expired records when a connection clo / subscriptions autoreconnect:0b / resubscribe to processes previously subscribed to -checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never \ No newline at end of file +checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never +/ client tracking +clients_enabled:1b / track connections +clients_opencloseonly:0b / track connections but not queries +clients_intrusive:0b / ask each new kdb+ client for its details +clients_autoclean:1b / not read +clients_retain:`long$0D02 / nanoseconds to keep a closed row +clients_maxidle:`long$0D / nanoseconds of idleness before a handle is closed; 0 means never diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 07bd1429..d1465767 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,5 +1,5 @@ -/ connections only; an app clients section replaces this whole section -clients:(enlist`opencloseonly)!enlist 1b +/ track connections only +clients_opencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b / all required by init; override as -. kdbtplog comes from the environment stplg_multilog:`tabperiod diff --git a/di/torq/settings/tickerplant.q b/di/torq/settings/tickerplant.q index 38b6064c..3723ee87 100644 --- a/di/torq/settings/tickerplant.q +++ b/di/torq/settings/tickerplant.q @@ -1,3 +1,3 @@ -/ connections only; an app clients section replaces this whole section -clients:(enlist`opencloseonly)!enlist 1b +/ track connections only +clients_opencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b diff --git a/di/torq/test.csv b/di/torq/test.csv index 6960533c..db892d4a 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -17,7 +17,7 @@ true,0,0,q,000b~(r`config)`discoveryregister`connectionsfromdiscovery`debug,1,,b true,0,0,q,`widgets in tables[],1,,the built-in hdb module actually mounted the fixture hdb dir true,0,0,q,(`handlers`log`servers`timer)~asc key r`deps,1,,all four core deps (incl injected servers) were built and passed through true,0,0,q,99h=type .clients.clients,1,,init wired client tracking (.clients.clients exists) -run,0,0,q,"ctorig:(.clients.hit;.clients.hite); .clients.hit:{HITS+::1;x}; .clients.hite:{HITE+::1;'x}; HITS::HITE::UPD::0; tgt:{[x] x}; upd:{[t;x] UPD+::1}; .u.upd:upd",1,,count client-tracking hits and upd calls +run,0,0,q,"ctorig:(.m.di.0clienttracking.hit;.m.di.0clienttracking.hite); .m.di.0clienttracking.hit:{HITS+::1;x}; .m.di.0clienttracking.hite:{HITE+::1;'x}; HITS::HITE::UPD::0; tgt:{[x] x}; upd:{[t;x] UPD+::1}; .u.upd:upd",1,,count client-tracking hits and upd calls run,0,0,q,.z.ps (`tgt;1),1,,a non-upd async message true,0,0,q,"(1;0)~(HITS;UPD)",1,,is counted by client tracking run,0,0,q,.z.ps (`upd;`trade;()),1,,an upd async message @@ -28,9 +28,9 @@ run,0,0,q,".z.ps ""upd[`trade;()]""",1,,a string upd message true,0,0,q,"(2;3)~(HITS;UPD)",1,,is not skipped: the ignorelist check only matches list heads run,0,0,q,"zps:.z.ps; .m.di.0torq.zpsignorewired:0b; .m.di.0torq.initzpsignore[enlist[`zpsignore]!enlist enlist[`enabled]!enlist 0b]",1,,zpsignore with enabled 0b true,0,0,q,zps~.z.ps,1,,leaves .z.ps untouched -run,0,0,q,".clients.hit:first ctorig; .clients.hite:last ctorig",1,,restore client tracking +run,0,0,q,".m.di.0clienttracking.hit:first ctorig; .m.di.0clienttracking.hite:last ctorig",1,,restore client tracking run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],x,`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings -true,0,0,q,"all {(1b;0b)~((x`clients)`opencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore +true,0,0,q,"all {(1b;0b)~(x`clients_opencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works true,0,0,q,`hdb~r2`proctype,1,,override path still resolves the same identity From 6a03d873ad05bf8f7f033949f2996d80a61ef38d Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 14 Oct 2026 11:37:54 +0100 Subject: [PATCH 37/42] chainedtp: tickerplantname, subscribeto and subscribesyms accept TOML strings Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.md | 4 ++-- di/torq/proc/chainedtp/chainedtp.q | 9 ++++++--- di/torq/proc/chainedtp/test.csv | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index e347e041..ed835206 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -26,11 +26,11 @@ Every setting is required in `config`; `di/torq/settings/chainedtp.q` declares t | Key | Default | |---|---| -| `tickerplantname` | `` `tickerplant1 `` — procname(s) of the upstream | +| `tickerplantname` | `` `tickerplant1 `` — procname(s) of the upstream; also a string or list of strings | | `pubinterval` | `0D00:00:00` — tick by tick; above 0, batches published on a timer. Also a `"0D00:00:01"` string or seconds | | `tpconnsleep` / `tpcheckcycles` | `10` / `0W` — seconds between, and number of, upstream checks | | `createlogfile` / `logdir` / `clearlogonsubscription` | `0b` / `` `:tplogs `` / `0b` — log file `/_`; `logdir` may be a path string | -| `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms | +| `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms; also strings, `""` for all | | `replay` / `schema` | `0b` / `1b` | | `connections` / `startup` | `` `tickerplant `` / `1b` | diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index abe9534a..38e39113 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -3,6 +3,9 @@ / a timespan, a "0D00:00:01" string or a number of seconds (TOML has no timespan type) totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; + init:{[config;deps] if[not `log in key deps;'"di.torq.proc.chainedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.chainedtp: timer dependency is required - see di.timer"]; @@ -15,13 +18,13 @@ init:{[config;deps] (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; (deps[`handlers]`register)[`.z.pc;`;`stpps;0j;.stpps.closesub]; (use`di.subscriptions)[`init][config;deps]; - .z.m.tickerplantname:config`tickerplantname; + .z.m.tickerplantname:tosym config`tickerplantname; .z.m.pubinterval:totimespan config`pubinterval; .z.m.tpconnsleep:config`tpconnsleep; .z.m.createlogfile:config`createlogfile; .z.m.logdir:$[10h=type l:config`logdir;hsym`$l;l]; - .z.m.subscribeto:config`subscribeto; - .z.m.subscribesyms:config`subscribesyms; + .z.m.subscribeto:tosym config`subscribeto; + .z.m.subscribesyms:tosym config`subscribesyms; .z.m.replay:config`replay; .z.m.schema:config`schema; .z.m.clearlogonsubscription:config`clearlogonsubscription; diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 5fc813c5..66806a44 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -13,7 +13,8 @@ fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1 fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe -run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir!(""0D00:00:00"";""tplogs"");deps[]]",1,,init with toml-style pubinterval and logdir strings +run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir`tickerplantname`subscribeto`subscribesyms!(""0D00:00:00"";""tplogs"";""tickerplant1"";"""";"""");deps[]]",1,,init with toml-style strings +true,0,0,q,"(`tickerplant1;`;`)~.m.di.0torq.0proc.0chainedtp.tickerplantname,.m.di.0torq.0proc.0chainedtp.subscribeto,.m.di.0torq.0proc.0chainedtp.subscribesyms",1,,symbol settings strings become symbols; empty means all true,0,0,q,0D~.m.di.0torq.0proc.0chainedtp.pubinterval,1,,a pubinterval string becomes a timespan true,0,0,q,`:tplogs~.m.di.0torq.0proc.0chainedtp.logdir,1,,a logdir string becomes a file symbol true,0,0,q,".m.di.0torq.0proc.0chainedtp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle From 74eaa9ab0d20e1d79792dc903c04f4ac86bf80ca Mon Sep 17 00:00:00 2001 From: alowrydi Date: Wed, 14 Oct 2026 11:50:38 +0100 Subject: [PATCH 38/42] chainedtp: read procname bare in createlogfilename Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/chainedtp/chainedtp.q | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 38e39113..d9bb8dd6 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -133,7 +133,7 @@ cleartables:{[t] } createlogfilename:{[d] - ` sv (logdir;`$string[.z.m.procname],"_",string d) + ` sv (logdir;`$string[procname],"_",string d) } refreshtp:{[d] From 268450527d22df5ea5b93789cc545b05aa00ffe4 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 15 Oct 2026 10:34:42 +0100 Subject: [PATCH 39/42] Run the STP tick as a di.timer job, exit on init failure, drop underscores from settings keys - segmentedtp: store the injected timer and run the batch timer and end checks as the 1s di.timer job stpzts instead of wrapping .z.ts. The end-of-period, end-of-day and more-than-one-day guards disable only that job instead of system"t 0", so other timer jobs (servers retry, subscription checks) keep running. - torqx_init.q: an init error logs "torqx: init failed: ..." and exits 3 rather than leaving a half-started process listening. - Settings keys lose their underscores: clients_* -> clients*, stplg_* -> stplg*, sctp_* -> sctp* (settings files, modules, docs, tests). Old names in app settings or -flag overrides are no longer read. Co-Authored-By: Claude Opus 5.5 --- di/clienttracking/clienttracking.md | 22 ++++++------ di/clienttracking/clienttracking.q | 14 ++++---- di/clienttracking/test.csv | 6 ++-- di/clienttracking/test.q | 2 +- di/torq/bin/torqx_init.q | 3 +- di/torq/proc/segmentedtp/segmentedtp.md | 18 +++++----- di/torq/proc/segmentedtp/segmentedtp.q | 45 +++++++++++++------------ di/torq/proc/segmentedtp/stplog.q | 8 ++--- di/torq/proc/segmentedtp/test.csv | 17 ++++++---- di/torq/proc/segmentedtp/test.q | 13 +++---- di/torq/proc/tickerlogreplay/test.q | 2 +- di/torq/settings/default.q | 12 +++---- di/torq/settings/segmentedtp.q | 34 +++++++++---------- di/torq/settings/tickerplant.q | 2 +- di/torq/test.csv | 2 +- 15 files changed, 104 insertions(+), 96 deletions(-) diff --git a/di/clienttracking/clienttracking.md b/di/clienttracking/clienttracking.md index 134d0cbe..45df3f10 100644 --- a/di/clienttracking/clienttracking.md +++ b/di/clienttracking/clienttracking.md @@ -20,12 +20,12 @@ Required in `config`; `di/torq/settings/default.q` declares them all: | Key | Default | Meaning | |---|---|---| -| `clients_enabled` | `1b` | track connections | -| `clients_opencloseonly` | `0b` | track connections but not queries | -| `clients_intrusive` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | -| `clients_autoclean` | `1b` | not read | -| `clients_retain` | `` `long$0D02 `` | nanoseconds to keep a closed row | -| `clients_maxidle` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | +| `clientsenabled` | `1b` | track connections | +| `clientsopencloseonly` | `0b` | track connections but not queries | +| `clientsintrusive` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | +| `clientsautoclean` | `1b` | not read | +| `clientsretain` | `` `long$0D02 `` | nanoseconds to keep a closed row | +| `clientsmaxidle` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | ## init[config;deps] @@ -33,8 +33,8 @@ Requires `handlers` (`di.torq.handlers`). It: 1. signals if any setting is missing, then applies them; 2. registers `pc` on `.z.pc`, whether or not `enabled`; -3. when `clients_enabled`, registers `po` on `.z.po`, `wo` on `.z.wo` and `pc` on `.z.wc`; -4. when `clients_enabled` and not `clients_opencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through +3. when `clientsenabled`, registers `po` on `.z.po`, `wo` on `.z.wo` and `pc` on `.z.wc`; +4. when `clientsenabled` and not `clientsopencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through `di.torq.handlers`) with `{hit[@[x;y;hite]]}` around the current handler. An unset `.z.pg`/`.z.ps` is taken as `value`, and an unset `.z.ws` as an echo. @@ -46,7 +46,7 @@ events through `di.torq.handlers` afterwards replaces the wrap. - `hits`, `errs` and `sz` count async (`.z.ps`) and websocket (`.z.ws`) messages too, including the bytes of results that are never sent back. - A closed row keeps its key with `w` set to null, so several closed rows share a null key. -- A handle closed by the `clients_maxidle` sweep still has a null `endp`, so the same sweep drops its row +- A handle closed by the `clientsmaxidle` sweep still has a null `endp`, so the same sweep drops its row instead of marking it. - The private `unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. - `hits` and `errs` are ints. @@ -59,7 +59,7 @@ k4unit.moduletest`di.clienttracking ``` `test.q`/`test.csv` start four server peers, each configured from the settings file plus overrides -(defaults, `clients_opencloseonly`, disabled, and `clients_intrusive` with a one-second `clients_maxidle` -and `clients_retain`), and connect to them. The tests cover the settings, the table, the init checks, +(defaults, `clientsopencloseonly`, disabled, and `clientsintrusive` with a one-second `clientsmaxidle` +and `clientsretain`), and connect to them. The tests cover the settings, the table, the init checks, the stored settings, connection rows, hits, bytes and errors, closing and `addw`, websocket rows, both settings modes, the intrusive reply, idle closing and the retain purge. diff --git a/di/clienttracking/clienttracking.q b/di/clienttracking/clienttracking.q index afa14ffb..76047c2d 100644 --- a/di/clienttracking/clienttracking.q +++ b/di/clienttracking/clienttracking.q @@ -3,14 +3,14 @@ init:{[config;deps] if[not `handlers in key deps;'"di.clienttracking: handlers dependency is required - see di.torq.handlers"]; / all settings required - req:`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean`clients_retain`clients_maxidle; + req:`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean`clientsretain`clientsmaxidle; if[count m:req except key config;'"di.clienttracking: missing settings: ",", " sv string m]; - .z.m.enabled:config`clients_enabled; - .z.m.opencloseonly:config`clients_opencloseonly; - .z.m.intrusive:config`clients_intrusive; - .z.m.autoclean:config`clients_autoclean; - .z.m.retain:config`clients_retain; - .z.m.maxidle:config`clients_maxidle; + .z.m.enabled:config`clientsenabled; + .z.m.opencloseonly:config`clientsopencloseonly; + .z.m.intrusive:config`clientsintrusive; + .z.m.autoclean:config`clientsautoclean; + .z.m.retain:config`clientsretain; + .z.m.maxidle:config`clientsmaxidle; r:deps[`handlers]`register; r[`.z.pc;`;`clients;0j;pc[::;]]; if[enabled; diff --git a/di/clienttracking/test.csv b/di/clienttracking/test.csv index 5bd274c2..fa77aa94 100644 --- a/di/clienttracking/test.csv +++ b/di/clienttracking/test.csv @@ -5,8 +5,8 @@ before,0,0,q,setupfixture[],1,,start the server peers comment,,,,,,,settings and table run,0,0,q,"S:(use`di.torq.config)[`parsefile] SETTINGS",1,,read the settings file -true,0,0,q,"(1b;0b;0b;1b)~S`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean",1,,boolean defaults -true,0,0,q,"(`long$0D02;0)~S`clients_retain`clients_maxidle",1,,retain two hours and maxidle off +true,0,0,q,"(1b;0b;0b;1b)~S`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean",1,,boolean defaults +true,0,0,q,"(`long$0D02;0)~S`clientsretain`clientsmaxidle",1,,retain two hours and maxidle off true,0,0,q,"(enlist`w)~keys .clients.clients",1,,table keyed on w true,0,0,q,"`ipa`u`a`k`K`c`s`o`f`pid`port`startp`endp`lastp`hits`errs`sz~cols value .clients.clients",1,,table columns true,0,0,q,"""iij""~exec t from meta .clients.clients where c in `hits`errs`sz",1,,hits and errs int; sz long @@ -19,7 +19,7 @@ true,0,0,q,"1=ha""count select from .clients.clients where w=.z.w""",1,,a connec true,0,0,q,"(.z.u;`localhost;`int$.Q.addr`localhost)~(mine[ha;""u""];mine[ha;""ipa""];mine[ha;""a""])",1,,row records user and address true,0,0,q,"(mine[ha;""startp""]<=mine[ha;""lastp""]) and null mine[ha;""endp""]",1,,startp and lastp set; endp null while open true,0,0,q,"ha""all {`clients in exec name from h.list x} each `.z.po`.z.pc`.z.wo`.z.wc""",1,,open and close observers registered -true,0,0,q,"(S`clients_enabled`clients_opencloseonly`clients_intrusive`clients_autoclean`clients_retain`clients_maxidle)~ha"".m.di.0clienttracking`enabled`opencloseonly`intrusive`autoclean`retain`maxidle""",1,,init stores the settings +true,0,0,q,"(S`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean`clientsretain`clientsmaxidle)~ha"".m.di.0clienttracking`enabled`opencloseonly`intrusive`autoclean`retain`maxidle""",1,,init stores the settings comment,,,,,,,usage run,0,0,q,"n0:mine[ha;""hits""]; ha""1+1""; n1:mine[ha;""hits""]",1,,two sync queries diff --git a/di/clienttracking/test.q b/di/clienttracking/test.q index 86ba2416..ba9f7a13 100644 --- a/di/clienttracking/test.q +++ b/di/clienttracking/test.q @@ -8,7 +8,7 @@ peer:{[p] hopen `$":localhost:",string p} PORTS:`a`b`c`d!4#0N / a: defaults; b: opencloseonly; c: disabled; d: INTRUSIVE with a 1s MAXIDLE and RETAIN -CFGS:`a`b`c`d!("()!()";"enlist[`clients_opencloseonly]!enlist 1b";"enlist[`clients_enabled]!enlist 0b";"`clients_intrusive`clients_maxidle`clients_retain!(1b;`long$0D00:00:01;`long$0D00:00:01)") +CFGS:`a`b`c`d!("()!()";"enlist[`clientsopencloseonly]!enlist 1b";"enlist[`clientsenabled]!enlist 0b";"`clientsintrusive`clientsmaxidle`clientsretain!(1b;`long$0D00:00:01;`long$0D00:00:01)") / the settings file, the base of every peer's config SETTINGS:"di/torq/settings/default.q" diff --git a/di/torq/bin/torqx_init.q b/di/torq/bin/torqx_init.q index b81c25ac..d1403e14 100644 --- a/di/torq/bin/torqx_init.q +++ b/di/torq/bin/torqx_init.q @@ -21,6 +21,7 @@ norun:`norun in key params; tq:use`di.torq; overrides:$[norun;enlist[`norun]!enlist 1b;()!()]; -result:tq.init[proctype;procname;overrides]; +/ an init error is fatal: exit 3 rather than leave a half-started process listening +result:.[tq.init;(proctype;procname;overrides);{-2 "torqx: init failed: ",x;exit 3}]; -1 "torqx: started ",(string result`proctype)," ",string result`procname; diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index f94bc710..e5fc882f 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -1,7 +1,7 @@ # di.torq.proc.segmentedtp A segmented tickerplant. It stamps and logs incoming updates, per table and per period, and publishes them to -subscribers, filtered or not, immediately or in batches. With `sctp_chainedtp` on, it runs as a chained segmented +subscribers, filtered or not, immediately or in batches. With `sctpchainedtp` on, it runs as a chained segmented tickerplant: it subscribes to another one and republishes what it receives. ## Files @@ -29,8 +29,8 @@ Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;dat ## Settings -Every `stplg_` and `sctp_` setting and `createlogs` is required in `config`; the module keeps no defaults of -its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg_` settings are set onto `.stplg.`: +Every `stplg` and `sctp` setting and `createlogs` is required in `config`; the module keeps no defaults of +its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg` settings are set onto `.stplg.`: | Key | Default | |---|---| @@ -43,12 +43,12 @@ its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg_` s | `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_`; optional | | `errorlogname` | `` `segmentederrorlogfile `` | -`sctp_` settings are set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +`sctp` settings are set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or `parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and `subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and -`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctp_chainedtp" = true`). +`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctpchainedtp" = true`). -Any of them can be given on the command line as `-stplg_`, `-sctp_` or `-createlogs`; an app sets only the +Any of them can be given on the command line as `-stplg`, `-sctp` or `-createlogs`; an app sets only the keys it overrides. An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. @@ -64,8 +64,8 @@ Requires `log`, `timer` and `handlers`. It: `parent` makes `replaylog` ask the upstream; 3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush `memorybatch`, close the logs); -4. sets `.u.upd` from `batchmode`, wraps `.z.ts` (the existing handler, then the batch timer and the end checks), - and sets `\t` to 1000 if it is off; +4. sets `.u.upd` from `batchmode` and adds the `stpzts` timer job (the batch timer and the end checks, every + second); 5. chained: waits for the upstream and subscribes; otherwise loads `schemafile`; 6. strips attributes from the published tables and opens the logs. @@ -75,6 +75,8 @@ Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs ## Behaviour to know - End of period and end of day are checked on each update and each timer tick. +- If the next period or roll is already past, or more than a day has gone by, the `stpzts` job is disabled and + the check signals; other timer jobs keep running. - The first logs of a day have `seq` 0, and each period roll adds 1. - After an end of period, `currperiod` becomes the old `nextperiod`. - `period` replay returns `distinct` count and log pairs for the tables asked for; `day` replay returns every log of diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index d23fc409..ff70c163 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -8,11 +8,12 @@ init:{[config;deps] if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; if[not `handlers in key deps;'"di.torq.proc.segmentedtp: handlers dependency is required - see di.torq.handlers"]; / all settings required - req:`stplg_multilog`stplg_multilogperiod`stplg_errmode`stplg_batchmode`stplg_replayperiod`stplg_customcsv`stplg_errorlogname; - req,:`sctp_chainedtp`sctp_loggingmode`sctp_tickerplantname`sctp_tpconnsleep`sctp_tpcheckcycles`sctp_subscribeto; - req,:`sctp_subscribesyms`sctp_replay`sctp_schema`createlogs; + req:`stplgmultilog`stplgmultilogperiod`stplgerrmode`stplgbatchmode`stplgreplayperiod`stplgcustomcsv`stplgerrorlogname; + req,:`sctpchainedtp`sctploggingmode`sctptickerplantname`sctptpconnsleep`sctptpcheckcycles`sctpsubscribeto; + req,:`sctpsubscribesyms`sctpreplay`sctpschema`createlogs; if[count m:req except key config;'"di.torq.proc.segmentedtp: missing settings: ",", " sv string m]; .z.m.log:deps`log; + .z.m.timer:deps`timer; .z.m.procname:config`procname; .z.m.proctype:config`proctype; .z.m.params:config; @@ -22,23 +23,23 @@ init:{[config;deps] r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; - if[`stplg_kdbtplog in key config;.stplg.kdbtplog:tosym config`stplg_kdbtplog]; - .stplg.multilog:tosym config`stplg_multilog; - .stplg.multilogperiod:config`stplg_multilogperiod; - .stplg.errmode:config`stplg_errmode; - .stplg.batchmode:tosym config`stplg_batchmode; - .stplg.replayperiod:tosym config`stplg_replayperiod; - .stplg.customcsv:tosym config`stplg_customcsv; - .stplg.errorlogname:tosym config`stplg_errorlogname; - .sctp.chainedtp:config`sctp_chainedtp; - .sctp.loggingmode:tosym config`sctp_loggingmode; - .sctp.tickerplantname:tosym config`sctp_tickerplantname; - .sctp.tpconnsleep:config`sctp_tpconnsleep; - .sctp.tpcheckcycles:config`sctp_tpcheckcycles; - .sctp.subscribeto:tosym config`sctp_subscribeto; - .sctp.subscribesyms:tosym config`sctp_subscribesyms; - .sctp.replay:config`sctp_replay; - .sctp.schema:config`sctp_schema; + if[`stplgkdbtplog in key config;.stplg.kdbtplog:tosym config`stplgkdbtplog]; + .stplg.multilog:tosym config`stplgmultilog; + .stplg.multilogperiod:config`stplgmultilogperiod; + .stplg.errmode:config`stplgerrmode; + .stplg.batchmode:tosym config`stplgbatchmode; + .stplg.replayperiod:tosym config`stplgreplayperiod; + .stplg.customcsv:tosym config`stplgcustomcsv; + .stplg.errorlogname:tosym config`stplgerrorlogname; + .sctp.chainedtp:config`sctpchainedtp; + .sctp.loggingmode:tosym config`sctploggingmode; + .sctp.tickerplantname:tosym config`sctptickerplantname; + .sctp.tpconnsleep:config`sctptpconnsleep; + .sctp.tpcheckcycles:config`sctptpcheckcycles; + .sctp.subscribeto:tosym config`sctpsubscribeto; + .sctp.subscribesyms:tosym config`sctpsubscribesyms; + .sctp.replay:config`sctpreplay; + .sctp.schema:config`sctpschema; set[`createlogs;config`createlogs]; / subscribers replay from the parent's logs if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; @@ -104,11 +105,11 @@ init:{[config;deps] .stplg.updmsg:.stplg.upd[batch]; .stplg.ts:.stplg.zts[batch]; .u.upd:.stpps.upd[chainmode]; - set[`.z.ts;{[f;x] @[;x;()]each f}(@[value;`.z.ts;{{}}];.stpps.zts[chainmode])]; + / the batch timer and end checks run as a 1s di.timer job; the end guards disable only this job + .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();1;1;()!()]; / error mode: failed updates go to a separate log if[.stplg.errmode; .stp.upd:.u.upd; .u.upd:{[t;x] .[.stp.upd;(t;x);{.stplg.badmsg[x;y;z]}[;t;x]]} ]; - if[not system "t";.z.m.log[`info][`timer;"defaulting timer to 1000ms"];system"t 1000"]; }]; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q index dc0949bb..b6a4ab19 100644 --- a/di/torq/proc/segmentedtp/stplog.q +++ b/di/torq/proc/segmentedtp/stplog.q @@ -6,7 +6,7 @@ / view of log file handles for faster lookups value"loghandles::exec tbl!handle from currlog"; -/ log root; config stplg_kdbtplog overrides it +/ log root; config stplgkdbtplog overrides it .stplg.kdbtplog:`$getenv`KDBTPLOG / create log directory `:stplogs/date/tabname_time @@ -167,7 +167,7 @@ value"loghandles::exec tbl!handle from currlog"; .stpps.endp[currentpd;nextpd;data]; .stplg.currperiod:.stplg.nextperiod; if[(data`p)>.stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; - system"t 0";'"next period is in the past"]; + .z.m.timer[`disablejobs]`stpzts;'"next period is in the past"]; .stplg.getnextendUTC[]; if[rolllogs;.stplg.periodrollover[data]]; .z.m.log[`info][`stpeoperiod;"end of period complete, new values for current and next period are ",.Q.s1 (currentpd;nextpd)]; @@ -190,7 +190,7 @@ value"loghandles::exec tbl!handle from currlog"; .stplg.dayrollover:{[data] .z.m.eod.setnextroll .z.m.eod.getroll data`p; if[(data`p)>.z.m.eod.getnextroll[]; - system"t 0";'"next roll is in the past"]; + .z.m.timer[`disablejobs]`stpzts;'"next roll is in the past"]; .stplg.getnextendUTC[]; .z.m.eod.setd 1+.z.m.eod.getd[]; .stpm.updmeta[.stplg.multilog][`close;.stplg.logtabs;(data`p)+.z.m.eod.getdailyadj[]]; @@ -205,7 +205,7 @@ value"loghandles::exec tbl!handle from currlog"; .stplg.checkends:{ if[.stplg.nextendUTC > x; :()]; if[.stplg.nextperiod < x1:x+.z.m.eod.getdailyadj[]; .stplg.stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; - if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;system"t 0";'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; + if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;.z.m.timer[`disablejobs]`stpzts;'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; }; .stplg.init:{[dbname] diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 97cff7d4..69b4af0d 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -11,12 +11,13 @@ fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e; fail,0,0,q,"seg.init[()!();`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};enlist[`register]!enlist {[a;b;c;d;e]})]",1,,init without the settings must error true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~ha"".stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv""",1,,stplg defaults from the settings file true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~ha"".sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema""",1,,sctp defaults from the settings file -true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""stplg_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped stplg key lands unchanged after init -true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv `,`$""_"" vs string k}[x] each k where (k:key x) like ""sctp_*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped sctp key lands unchanged after init +true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``stplg,`$5_string k}[x] each k where (k:key x) like ""stplg*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped stplg key lands unchanged after init +true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``sctp,`$4_string k}[x] each k where (k:key x) like ""sctp*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped sctp key lands unchanged after init true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered true,0,0,q,"`stplg in ha""exec name from h.list`.z.exit""",1,,.z.exit observer registered +true,0,0,q,"(`stpzts;1;1)~ha""tickjob""",1,,batch timer added as a 1s timer job comment,,,,,,,subscribe handshake true,0,0,q,"`segmented~ha""tptype""",1,,tptype is segmented @@ -32,7 +33,7 @@ run,0,0,q,"ha(`.u.upd;`trade;trd`a`b)",1,,send two trades true,0,0,q,"(2;0)~(ha""count trade"";count got)",1,,held in memory and not yet published true,0,0,q,"1=logcount ha""currlog[`trade;`logname]""",1,,written to the log immediately true,0,0,q,"(`trade;1;0)~ha""(first key .stplg.tmpmsgcount;.stplg.tmpmsgcount`trade;.stplg.msgcount`trade)""",1,,counted as pending -run,0,0,q,"ha"".z.ts .z.p""",1,,timer +run,0,0,q,"ha""tick[]""",1,,timer true,0,0,q,"(1;`trade)~(count got;first first got)",1,,published on the timer true,0,0,q,"(`time`sym`price`size;`a`b)~(cols last first got;exec sym from last first got)",1,,time added and rows intact true,0,0,q,"(0;1;2;0)~ha""(count trade;.stplg.msgcount`trade;.stplg.rowcount`trade;count .stplg.tmpmsgcount)""",1,,table cleared and counts moved @@ -53,11 +54,13 @@ true,0,0,q,"1=count distinct hb""exec logname from currlog where tbl in `trade`q true,0,0,q,"(string hb""currlog[`trade;`logname]"") like ""*/stp2_2*""",1,,singular log name run,0,0,q,"got:(); hb"".u.sub[`quote;1!([]tbl:enlist`quote;filters:enlist\""bid>1\"";columns:enlist\""sym,bid\"")]""; hb(`.u.upd;`quote;(`a`b;1 2f))",1,,filtered subscription with where and columns true,0,0,q,"(`sym`bid;enlist`b)~(cols last first got;exec sym from last first got)",1,,only matching rows and columns published +true,0,0,q,"""next period is in the past""~hb""@[{.stplg.nextperiod:.z.p-2D; .stplg.getnextendUTC[]; .stplg.checkends .z.p};::;::]""",1,,a past next period signals +true,0,0,q,"(enlist`stpzts;60000i)~hb""(stopped;system\""t\"")""",1,,only the tick job is disabled; the process timer is untouched comment,,,,,,,memorybatch and tabular run,0,0,q,"hc(`.u.upd;`trade;trd`a`b)",1,,send two trades true,0,0,q,"(2;0)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"")",1,,held in memory and not logged -run,0,0,q,"hc"".z.ts .z.p""",1,,timer +run,0,0,q,"hc""tick[]""",1,,timer true,0,0,q,"(0;1;1;2)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"";hc"".stplg.msgcount`trade"";hc"".stplg.rowcount`trade"")",1,,logged and counted on the timer true,0,0,q,"(string hc""currlog[`trade;`logname]"") like ""*/stp3_trade2*""",1,,tabular log name @@ -65,7 +68,7 @@ comment,,,,,,,chained true,0,0,q,"(`quote`trade;1)~hs""(.stpps.t;count select from .sub.SUBSCRIPTIONS where table=`trade,active)""",1,,subscribed to the upstream true,0,0,q,"waitfor {2=hs""count trade""}",1,,upstream publish arrives true,0,0,q,"1 2~hs""(.stplg.updtab`trade)[1 2;3]""",1,,chained upd adds no time -run,0,0,q,"hs"".z.ts .z.p""",1,,timer +run,0,0,q,"hs""tick[]""",1,,timer true,0,0,q,"(0;1;1)~hs""(count trade;.stplg.msgcount`trade;logcount:{-11!(-2;x)} currlog[`trade;`logname])""",1,,published and logged in create mode true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z.d),""/sctp1_trade2*""",1,,own log in create mode true,0,0,q,"(`parent;`stp1;`)~hp"".sctp`loggingmode`tickerplantname`subscribeto""",1,,toml-style sctp strings become symbols @@ -73,7 +76,7 @@ true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,pare true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs comment,,,,,,,end of period -run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; .z.ts .z.p""",1,,force the period end +run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the period end true,0,0,q,"(1;`proctype`procname`tables`p;`stp1)~(count eops;key last last eops;(last last eops)`procname)",1,,endofperiod sent with process data true,0,0,q,"(1;4;0)~ha""(.stplg.i;count .stpm.metatable;.stplg.msgcount`trade)""",1,,logs rolled and counts reset true,0,0,q,"(0W;2)~ha""(first first r;count r:.stplg.replaylog`trade)""",1,,day replay lists the closed log as 0W @@ -81,7 +84,7 @@ true,0,0,q,"1=count ha"".stplg.replayperiod:`period; r:.stplg.replaylog enlist`t true,0,0,q,"waitfor {1=hs"".stplg.i""}",1,,chained create mode rolls its logs comment,,,,,,,end of day -run,0,0,q,"eods:(); ha""(use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; .stplg.getnextendUTC[]; .z.ts .z.p""",1,,force the day end +run,0,0,q,"eods:(); ha""(use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the day end true,0,0,q,"(1;.z.d;`stp1)~(count eods;first first eods;(last first eods)`procname)",1,,endofday sent with date and process data true,0,0,q,"(.z.d+1;`$"":"",FIXDIR,""/a/stp1_"",string .z.d+1;2)~ha""((use`di.eodtime)[`getd][];.stplg.dldir;count .stpm.metatable)""",1,,date advanced and logs reopened true,0,0,q,"ha"".z.p<(use`di.eodtime)[`getnextroll][]""",1,,next roll is in the future diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index 5711cb4d..088d0fef 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -13,11 +13,11 @@ PORTS:`a`b`c`s`p!5#0N / a: defaultbatch, tabperiod; b: immediate, singular; c: memorybatch, tabular; s: chained, create; p: chained, parent, TOML-style strings CFGS:`a`b`c`s`p!( - "`procname`schemafile`stplg_kdbtplog!(`stp1;FIXDIR,\"/schema.q\";`$FIXDIR,\"/a\")"; - "`procname`schemafile`stplg_kdbtplog`stplg_batchmode`stplg_multilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; - "`procname`schemafile`stplg_kdbtplog`stplg_batchmode`stplg_multilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; - "`procname`createlogs`autoreconnect`stplg_kdbtplog`sctp_chainedtp`sctp_loggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; - "`procname`createlogs`autoreconnect`stplg_kdbtplog`sctp_chainedtp`sctp_loggingmode`sctp_tickerplantname`sctp_subscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") + "`procname`schemafile`stplgkdbtplog!(`stp1;FIXDIR,\"/schema.q\";`$FIXDIR,\"/a\")"; + "`procname`schemafile`stplgkdbtplog`stplgbatchmode`stplgmultilog!(`stp2;FIXDIR,\"/schema.q\";`$FIXDIR,\"/b\";`immediate;`singular)"; + "`procname`schemafile`stplgkdbtplog`stplgbatchmode`stplgmultilog!(`stp3;FIXDIR,\"/schema.q\";`$FIXDIR,\"/c\";`memorybatch;`tabular)"; + "`procname`createlogs`autoreconnect`stplgkdbtplog`sctpchainedtp`sctploggingmode!(`sctp1;0b;0b;`$FIXDIR,\"/s\";1b;`create)"; + "`procname`createlogs`autoreconnect`stplgkdbtplog`sctpchainedtp`sctploggingmode`sctptickerplantname`sctpsubscribeto!(`sctp2;0b;0b;`$FIXDIR,\"/p\";1b;\"parent\";\"stp1\";\"\")") setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; @@ -29,7 +29,8 @@ setupfixture:{[] "system \"p 0W\""; "errs:()"; "nolog:`info`warn`error!({[c;m]};{[c;m]};{[c;m] errs::errs,enlist m})"; - "notimer:enlist[`addjob]!enlist {[a;b;c;d;e;f]}"; + "stopped:`symbol$()"; + "notimer:`addjob`disablejobs!({[a;b;c;d;e;f] if[a~`stpzts;tickjob::(a;d;e);tick::b]};{[x] stopped::stopped,x})"; "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "hd:`register`remove`list#h"; diff --git a/di/torq/proc/tickerlogreplay/test.q b/di/torq/proc/tickerlogreplay/test.q index af9f7d8d..63ceb8cc 100644 --- a/di/torq/proc/tickerlogreplay/test.q +++ b/di/torq/proc/tickerlogreplay/test.q @@ -49,7 +49,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "seg:use`di.torq.proc.segmentedtp"; - "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\"),((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplg_kdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\"),((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplgkdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; ".u.upd[`quote;(enlist`a;enlist 3f)]"; ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index 79affe11..5f2c4af9 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -22,9 +22,9 @@ autoclean:0b / drop expired records when a connection clo autoreconnect:0b / resubscribe to processes previously subscribed to checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never / client tracking -clients_enabled:1b / track connections -clients_opencloseonly:0b / track connections but not queries -clients_intrusive:0b / ask each new kdb+ client for its details -clients_autoclean:1b / not read -clients_retain:`long$0D02 / nanoseconds to keep a closed row -clients_maxidle:`long$0D / nanoseconds of idleness before a handle is closed; 0 means never +clientsenabled:1b / track connections +clientsopencloseonly:0b / track connections but not queries +clientsintrusive:0b / ask each new kdb+ client for its details +clientsautoclean:1b / not read +clientsretain:`long$0D02 / nanoseconds to keep a closed row +clientsmaxidle:`long$0D / nanoseconds of idleness before a handle is closed; 0 means never diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index d1465767..6721d167 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,21 +1,21 @@ / track connections only -clients_opencloseonly:1b +clientsopencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b / all required by init; override as -. kdbtplog comes from the environment -stplg_multilog:`tabperiod -stplg_multilogperiod:0D01 -stplg_errmode:1b -stplg_batchmode:`defaultbatch -stplg_replayperiod:`day -stplg_customcsv:` -stplg_errorlogname:`segmentederrorlogfile -sctp_chainedtp:0b -sctp_loggingmode:`none -sctp_tickerplantname:`stp1 -sctp_tpconnsleep:10 -sctp_tpcheckcycles:0W -sctp_subscribeto:` -sctp_subscribesyms:` -sctp_replay:0b -sctp_schema:1b +stplgmultilog:`tabperiod +stplgmultilogperiod:0D01 +stplgerrmode:1b +stplgbatchmode:`defaultbatch +stplgreplayperiod:`day +stplgcustomcsv:` +stplgerrorlogname:`segmentederrorlogfile +sctpchainedtp:0b +sctploggingmode:`none +sctptickerplantname:`stp1 +sctptpconnsleep:10 +sctptpcheckcycles:0W +sctpsubscribeto:` +sctpsubscribesyms:` +sctpreplay:0b +sctpschema:1b createlogs:1b diff --git a/di/torq/settings/tickerplant.q b/di/torq/settings/tickerplant.q index 3723ee87..d3929c35 100644 --- a/di/torq/settings/tickerplant.q +++ b/di/torq/settings/tickerplant.q @@ -1,3 +1,3 @@ / track connections only -clients_opencloseonly:1b +clientsopencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b diff --git a/di/torq/test.csv b/di/torq/test.csv index db892d4a..37138ab3 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -30,7 +30,7 @@ run,0,0,q,"zps:.z.ps; .m.di.0torq.zpsignorewired:0b; .m.di.0torq.initzpsignore[e true,0,0,q,zps~.z.ps,1,,leaves .z.ps untouched run,0,0,q,".m.di.0clienttracking.hit:first ctorig; .m.di.0clienttracking.hite:last ctorig",1,,restore client tracking run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],x,`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings -true,0,0,q,"all {(1b;0b)~(x`clients_opencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore +true,0,0,q,"all {(1b;0b)~(x`clientsopencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works true,0,0,q,`hdb~r2`proctype,1,,override path still resolves the same identity From a4888b277516a1a170653308396020fe70e858ba Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 15 Oct 2026 11:28:15 +0100 Subject: [PATCH 40/42] Address review: customcsv default, di.os mkdir, triadic callendofperiod, rdb guard - segmentedtp: stplgcustomcsv defaults to appconfig/stpcustom.csv under TORQXAPPHOME (TorQ's app config dir); an unreadable csv fails init with a clear message instead of a later 'custommode. - segmentedtp createdld and tickerlogreplay postreplaymerge make directories through di.os mkdir (TorQ's .os.md); di.os is used, not in deps.toml as it has no VERSION. - tickerlogreplay: drop the .save savedownmanipulation/postreplay guards that were always overwritten from .replay.*; .save.manipulate stays. - rdb: skip the subscribe log line when re-init returns nothing, as wdb does. - pubsub: callendofperiod sends (`endofperiod;currp;nextp;data), as TorQ's endp. - tickerplant: .u.w comment says it holds table names only. - segmentedtp.md: server tracking kept on for discovery; heartbeat/usage off; segmentedchainedtp has no subscriber cutoff. Co-Authored-By: Claude Opus 5.5 --- di/pubsub/pubsub.md | 2 +- di/pubsub/pubsub.q | 2 +- di/pubsub/test.csv | 1 + di/torq/proc/rdb/rdb.q | 2 +- di/torq/proc/segmentedtp/segmentedtp.md | 5 ++++- di/torq/proc/segmentedtp/segmentedtp.q | 10 ++++++++-- di/torq/proc/segmentedtp/stplog.q | 4 ++-- di/torq/proc/segmentedtp/test.csv | 7 +++++-- di/torq/proc/tickerlogreplay/tickerlogreplay.md | 5 +++-- di/torq/proc/tickerlogreplay/tickerlogreplay.q | 16 ++++------------ di/torq/proc/tickerplant/tickerplant.q | 2 +- di/torq/settings/segmentedtp.q | 2 +- 12 files changed, 32 insertions(+), 26 deletions(-) diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 9a8970b7..1cc0a7b4 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -50,7 +50,7 @@ publish data with/without filters. The function takes two arguments: t and x, wh |---------------------------|------------------------------------------------------------------------------| | `pubsub.setsubtables` | Set a specified list of tables that are available for subscription. | | `pubsub.callendofday` | Broadcast end of day to all subscribers as `.u.end[d]`. | -| `pubsub.callendofperiod` | Broadcast an end-of-period event to all subscribers (requires `endofperiod`).| +| `pubsub.callendofperiod` | Broadcast end of period to all subscribers as `endofperiod[currp;nextp;data]`.| | `pubsub.closesub` | Remove handle upon connection close. Not bound to `.z.pc` by the module - the consumer binds it (see Notes). | | `pubsub.subclear` | Publish tables and clear up the contents. | | `pubsub.init` | Initialize variables - run before calling pub/sub functions to populate required state (e.g., tables/schemas). Takes a deps dict with a required `log`. | diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index f3119682..daba39f9 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -78,7 +78,7 @@ closesub:{[h] callendofday:{[d](neg getallhandles[])@\:(`.u.end;d)}; / broadcast to all subscribers upon end of period, client needs to define endofperiod function -callendofperiod:{(neg getallhandles[])@\:(`endofperiod;x)}; +callendofperiod:{[currp;nextp;data] (neg getallhandles[])@\:(`endofperiod;currp;nextp;data)}; / get table schema extractschema:{[table]0#value table}; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index a2bd252e..4f7b23cb 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -139,6 +139,7 @@ run,0,0,q,"h(`.stpps.closesub;clt)",1,,closesub for the client handle true,0,0,q,"not clt in h"".stpps.allsubhandles[]""",1,,client removed from both registries true,0,0,q,"""Table nosuchtable does not exist""~h""@[.stpps.init;enlist`nosuchtable;{x}]""",1,,init signals on a missing table true,0,0,q,"(`psinit;""Table nosuchtable does not exist"")~h""lastlog""",1,,and logs it through the injected log +true,0,0,q,"`currp`nextp`data~h""(value pubsub.callendofperiod)1""",1,,callendofperiod takes the three endofperiod arguments run,0,0,q,neg[h](exit;0);neg[h](::),1,,close background process and flush run,0,0,q,hclose h,1,,close handle diff --git a/di/torq/proc/rdb/rdb.q b/di/torq/proc/rdb/rdb.q index 44ff71b3..8fb3c2c4 100644 --- a/di/torq/proc/rdb/rdb.q +++ b/di/torq/proc/rdb/rdb.q @@ -134,7 +134,7 @@ init:{[config;deps] .z.m.subs:use`di.subscriptions; (.z.m.subs`init)[config;deps]; sd:.sub.subscribe[subscribeto;subscribesyms;1b;replaylog;first .sub.getsubscriptionhandles[tpt;`;()!()]]; - .z.m.log[`info][`rdb;"subscribed, partition date ",string sd`d]; + if[count sd;.z.m.log[`info][`rdb;"subscribed, partition date ",string sd`d]]; / di.dbwrite for savedown (optional sort.csv sort/attr config). Takes the injected binary / (ctx;msg) log dep directly - no adapter, since di.dbwrite now uses the same contract. diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index e5fc882f..87e7a821 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -39,7 +39,7 @@ its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg` se | `errmode` | `1b` — failed updates go to an error log | | `batchmode` | `` `defaultbatch `` — `immediate`, `defaultbatch` or `memorybatch` | | `replayperiod` | `` `day `` — `day` or `period` | -| `customcsv` | `` ` `` — `table,mode` csv for `custom` | +| `customcsv` | `"appconfig/stpcustom.csv"` — `table,mode` csv for `custom`; a relative path is under `TORQXAPPHOME`; unreadable fails `init` | | `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_`; optional | | `errorlogname` | `` `segmentederrorlogfile `` | @@ -77,6 +77,9 @@ Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs - End of period and end of day are checked on each update and each timer tick. - If the next period or roll is already past, or more than a day has gone by, the `stpzts` job is disabled and the check signals; other timer jobs keep running. +- Server tracking stays on (TorQ's STP turns it off), so the process can register with discovery. Heartbeating is + not wired and query logging is off unless `[querylog]` is enabled, as in TorQ's STP. +- `segmentedchainedtp` has no subscriber cutoff (TorQ's `.subcut`): slow subscribers are not disconnected. - The first logs of a day have `seq` 0, and each period roll adds 1. - After an end of period, `currperiod` becomes the old `nextperiod`. - `period` replay returns `distinct` count and log pairs for the tables asked for; `day` replay returns every log of diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index ff70c163..876ee8fc 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -3,6 +3,9 @@ / a symbol, a string or a list of strings (TOML has no symbol type) tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; +/ a relative path is under the app home (TorQ's app config dir) +apppath:{[x] s:$[":"=first s:string x;1_s;s]; hsym`$$[("/"=first s) or 0=count h:getenv`TORQXAPPHOME;s;h,"/",s]}; + init:{[config;deps] if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; @@ -21,6 +24,8 @@ init:{[config;deps] (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; r:deps[`handlers]`register; r[`.z.pc;`;`stpps;0j;.stpps.closesub]; + / not in deps.toml: di.os has no VERSION, which fails depcheck + .z.m.os:use`di.os; .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; if[`stplgkdbtplog in key config;.stplg.kdbtplog:tosym config`stplgkdbtplog]; @@ -29,7 +34,7 @@ init:{[config;deps] .stplg.errmode:config`stplgerrmode; .stplg.batchmode:tosym config`stplgbatchmode; .stplg.replayperiod:tosym config`stplgreplayperiod; - .stplg.customcsv:tosym config`stplgcustomcsv; + .stplg.customcsv:apppath tosym config`stplgcustomcsv; .stplg.errorlogname:tosym config`stplgerrorlogname; .sctp.chainedtp:config`sctpchainedtp; .sctp.loggingmode:tosym config`sctploggingmode; @@ -47,7 +52,8 @@ init:{[config;deps] if[.stplg.multilog in `singular`tabular;.stplg.multilogperiod:1D]; / custom: logging mode per table if[.stplg.multilog~`custom; - @[{.stplg.custommode:1_(!) . ("SS";",")0: x};.stplg.customcsv;{.z.m.log[`error][`stp;"failed to load custom mode csv"]}]]; + @[{.stplg.custommode:1_(!) . ("SS";",")0: x};.stplg.customcsv; + {.z.m.log[`error][`stp;m:"failed to load custom mode csv ",string .stplg.customcsv];'"di.torq.proc.segmentedtp: ",m}]]; / die if the main STP dies r[`.z.pc;`;`sctp;0j;{[x] if[.sctp.chainedtp;if[.sctp.tph=x;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .sctp.tickerplantname];exit 1]]}]; / close logs on clean exit diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q index b6a4ab19..c59194f4 100644 --- a/di/torq/proc/segmentedtp/stplog.q +++ b/di/torq/proc/segmentedtp/stplog.q @@ -12,8 +12,8 @@ value"loghandles::exec tbl!handle from currlog"; / create log directory `:stplogs/date/tabname_time .stplg.createdld:{[name;date] if[not count dir:hsym .stplg.kdbtplog;.z.m.log[`error][`stp;"log directory not defined"];exit 1]; - system"mkdir -p ",1_string dir; - system"mkdir -p ",1_string .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; + .z.m.os[`mkdir] dir; + .z.m.os[`mkdir] .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; }; .stplg.gentimeformat:{(raze string "dv"$x) except ".:"}; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index 69b4af0d..ff6aa75c 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -9,10 +9,13 @@ fail,0,0,q,"seg.init[()!();()!()]",1,,init without log must error fail,0,0,q,"seg.init[()!();enlist[`log]!enlist nolog]",1,,init without timer must error fail,0,0,q,"seg.init[()!();`log`timer!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]})]",1,,init without handlers must error fail,0,0,q,"seg.init[()!();`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};enlist[`register]!enlist {[a;b;c;d;e]})]",1,,init without the settings must error -true,0,0,q,"(`tabperiod;0D01;1b;`defaultbatch;`day;`)~ha"".stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv""",1,,stplg defaults from the settings file +true,0,0,q,"((`tabperiod;0D01;1b;`defaultbatch;`day),hsym`$$[count h:getenv`TORQXAPPHOME;h,""/"";""""],""appconfig/stpcustom.csv"")~ha"".stplg`multilog`multilogperiod`errmode`batchmode`replayperiod`customcsv""",1,,stplg defaults from the settings file; customcsv under the app home true,0,0,q,"(0b;`none;`stp1;10;0W;`;`;0b;1b)~ha"".sctp`chainedtp`loggingmode`tickerplantname`tpconnsleep`tpcheckcycles`subscribeto`subscribesyms`replay`schema""",1,,sctp defaults from the settings file -true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``stplg,`$5_string k}[x] each k where (k:key x) like ""stplg*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped stplg key lands unchanged after init +true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``stplg,`$5_string k}[x] each k where (k:key[x] except `stplgcustomcsv) like ""stplg*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every other shipped stplg key lands unchanged after init true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``sctp,`$4_string k}[x] each k where (k:key x) like ""sctp*""}(use`di.torq.config)[`parsefile][""di/torq/settings/segmentedtp.q""]",1,,every shipped sctp key lands unchanged after init +true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`$""/x/c.csv""",1,,an absolute customcsv is kept +true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`:/x/c.csv",1,,an hsym customcsv is kept +true,0,0,q,"(hsym`$$[count h:getenv`TORQXAPPHOME;h,""/"";""""],""a/c.csv"")~.m.di.0torq.0proc.0segmentedtp.apppath`$""a/c.csv""",1,,a relative customcsv is under the app home true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md index 70b13dfd..a238c6fe 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.md +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -7,8 +7,9 @@ at the end, or partition to a temporary directory and merge on disk. ## Files -`init.q` loads `tickerlogreplay.q`: the module `init`, then the `.save` hooks (`savedownmanipulation`, -`manipulate`, `postreplay`), each defined if absent, and the `.replay.upd` hook. `sort.csv` is the default sort config. +`init.q` loads `tickerlogreplay.q`: the module `init`, then `.save.manipulate` (defined if absent), the `.replay.upd` +hook, and `.save.savedownmanipulation` / `.save.postreplay` from their `.replay` names. `sort.csv` is the default sort +config. ## Surface diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index a5bcd1d1..baa16f8c 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,6 +18,8 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; + / not in deps.toml: di.os has no VERSION, which fails depcheck + .z.m.os:use`di.os; / all settings required req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; req,:`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`compression; @@ -81,22 +83,12 @@ init:{[config;deps] if[autoreplay;initandrun[]]; }; -/ save down manipulation and post replay hook, each defined if absent - -/ table!function applied to a table before it is enumerated and saved -if[not `savedownmanipulation in key `.save;.save.savedownmanipulation:@[value;`.save.savedownmanipulation;()!()]]; - -/ manipulate a table at save down time +/ manipulate a table at save down time, defined if absent if[not `manipulate in key `.save;.save.manipulate:{[t;x] $[t in key .save.savedownmanipulation; @[.save.savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; x]}]; -/ called after a log's tables are saved, with the directory and partition -if[not `postreplay in key `.save;.save.postreplay:{[d;p] - - }]; - / default upd; set .replay.upd before use to override .replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] @@ -258,7 +250,7 @@ mergemaxrows:{[tabname] mergenumrows^mergenumtab[tabname]}; // post replay function for merge replay, invoked after all the tables have been written down for a given log file postreplaymerge:{[td;p;h] - system"mkdir -p ",1_string .Q.par[td;p;`]; // ensures directory exists before removed + .z.m.os[`mkdir] .Q.par[td;p;`]; // ensures directory exists before removed mergelimits:(tabsincountorder[tablestoreplay],())!$[.z.m.merge.getmergebybytelimit[];(count tabsincountorder[tablestoreplay])#mergenumbytes;({[x] mergenumrows^mergemaxrows[x]}tabsincountorder[tablestoreplay])],(); // merge the tables from each partition in the tempdir together mergetable[td;p;;mergelimits;h] each tabsincountorder[tablestoreplay]; diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 026d7364..36ce4928 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -157,7 +157,7 @@ init:{[config;deps] / tplog: prepared now; log opened after the root upd is published (replay needs it) .z.m.tp:use`di.tplogmgr; .z.m.logh:0; - / classic tickerplant surface read by .sub.subscribe + / table names only, read by .sub.subscribe; di.pubsub holds the subscribers .u.w:tabs!(count tabs)#(); .u.i:0; .u.icounts:(`symbol$())!0#0; diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 6721d167..9fd67ccd 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -7,7 +7,7 @@ stplgmultilogperiod:0D01 stplgerrmode:1b stplgbatchmode:`defaultbatch stplgreplayperiod:`day -stplgcustomcsv:` +stplgcustomcsv:"appconfig/stpcustom.csv" stplgerrorlogname:`segmentederrorlogfile sctpchainedtp:0b sctploggingmode:`none From d490797fff68371c85f347e0f7f2793448f2d3e9 Mon Sep 17 00:00:00 2001 From: alowrydi Date: Thu, 15 Oct 2026 13:21:41 +0100 Subject: [PATCH 41/42] Version di.os and declare it in deps.toml di.os gets a VERSION (0.1.0) and exports version. segmentedtp, tickerlogreplay, wdb and housekeeping declare it as a hard dependency; housekeeping gains a deps.toml. Drops the notes explaining why it was undeclared. Co-Authored-By: Claude Opus 5.5 --- di/os/VERSION | 1 + di/os/init.q | 2 ++ di/os/os.md | 2 ++ di/os/test.csv | 1 + di/torq/proc/housekeeping/deps.toml | 3 +++ di/torq/proc/housekeeping/housekeeping.md | 9 +-------- di/torq/proc/housekeeping/housekeeping.q | 4 +--- di/torq/proc/segmentedtp/deps.toml | 1 + di/torq/proc/segmentedtp/segmentedtp.q | 1 - di/torq/proc/tickerlogreplay/deps.toml | 1 + di/torq/proc/tickerlogreplay/tickerlogreplay.q | 1 - di/torq/proc/wdb/deps.toml | 1 + di/torq/proc/wdb/wdb.md | 2 +- di/torq/proc/wdb/wdb.q | 1 - 14 files changed, 15 insertions(+), 15 deletions(-) create mode 100644 di/os/VERSION create mode 100644 di/torq/proc/housekeeping/deps.toml diff --git a/di/os/VERSION b/di/os/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/os/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/os/init.q b/di/os/init.q index 65fd437a..0f28d521 100644 --- a/di/os/init.q +++ b/di/os/init.q @@ -166,4 +166,6 @@ setdrysyscalls:{[on] cleardrysyscalls[] +version:first read0`:::VERSION + export:`syscall`drysyscall _ .z.m diff --git a/di/os/os.md b/di/os/os.md index 66e93852..b10b9cd5 100644 --- a/di/os/os.md +++ b/di/os/os.md @@ -6,6 +6,8 @@ Designed to work on both **Linux/Unix** and **Windows**, functions automatically **All functions that accept path arguments can accept string or hsym paths.** +`version` holds the module version, read from its `VERSION` file. + --- ## :desktop_computer: OS Detection diff --git a/di/os/test.csv b/di/os/test.csv index c41bf302..017c83bd 100644 --- a/di/os/test.csv +++ b/di/os/test.csv @@ -2,6 +2,7 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,os:use`di.os,1,,Initialize module before,0,0,q,"system ""l "", os.abspath[""di/os/test.q""]",1,1,load additional testing functions / dependencies true,0,0,q,-1h=type .m.di.0os.iswindows,1,1, +true,0,0,q,os.version~first read0`:di/os/VERSION,1,1,version read from the VERSION file run,0,0,q,k4unit.mock[`.m.di.0os.iswindows;0b],1,1, true,0,0,q,enlist["path"]~distinct os.topath each .testos.pathvars"path",1,1, diff --git a/di/torq/proc/housekeeping/deps.toml b/di/torq/proc/housekeeping/deps.toml new file mode 100644 index 00000000..f68f841e --- /dev/null +++ b/di/torq/proc/housekeeping/deps.toml @@ -0,0 +1,3 @@ +# Peer modules di.torq.proc.housekeeping `use`s (see di/torq/depcheck/depcheck.md). +[dependencies] +"di.os" = "0.1.0" diff --git a/di/torq/proc/housekeeping/housekeeping.md b/di/torq/proc/housekeeping/housekeeping.md index 717473f8..99217ae3 100644 --- a/di/torq/proc/housekeeping/housekeeping.md +++ b/di/torq/proc/housekeeping/housekeeping.md @@ -15,12 +15,7 @@ policy ("old `out_`/`err_` files accumulate forever… external housekeeping is - **Injected** (from di.torq): `log`, `timer`. - **`use`-imported**: `di.os` (for the `rm` action — it picks the right call for a file vs a - directory, and its dry-run mode makes a destructive action testable). - -> **No `deps.toml`.** `di.os` ships no `VERSION` file, and `di.torq.depcheck`'s manifest walk -> fails outright on a declared dependency it can't read a version for. Declaring `di.os` today -> would break every housekeeping start with a `DEPENDENCY CHECK FAILED … has no VERSION file`. -> Add the declaration once `di.os` carries a `VERSION`. + directory, and its dry-run mode makes a destructive action testable); declared in `deps.toml`. ## Config @@ -196,8 +191,6 @@ Roughly in the order they'd pay off: - **A run summary worth monitoring.** Counts and bytes reclaimed per job, kept as a table (like `di.compression`'s stats) so a dashboard or heartbeat can see that housekeeping is actually keeping up, rather than reading log lines. -- **`deps.toml` declaring `di.os`** — blocked purely on `di.os` shipping a `VERSION` file (see - Dependencies above). - **Windows.** The `.win` branch, if TorqX ever needs it. - **Malformed-header reporting.** `0:` pads a too-short header with invented names, so the error says `has columns wrong, header, entirely, x, x1, x2, x3`. Reporting the raw header line would diff --git a/di/torq/proc/housekeeping/housekeeping.q b/di/torq/proc/housekeeping/housekeeping.q index a600d0c3..e665f027 100644 --- a/di/torq/proc/housekeeping/housekeeping.q +++ b/di/torq/proc/housekeeping/housekeeping.q @@ -228,9 +228,7 @@ init:{[config;deps] / runtimes:02:00:00 in settings and a dead 12:00 in code - with its -hkusage text quoting 12:00. .z.m.runtimes:$[`runtimes in key config;astimespans config`runtimes;enlist 0D02:00:00]; / di.os for the rm action - it picks file vs directory, and its dry-run mode is what lets the - / tests assert on a destructive action without destroying anything. Deliberately NOT declared - / in a deps.toml: di.os ships no VERSION file, so declaring it would fail di.torq.depcheck's - / manifest walk outright (see housekeeping.md). Add the declaration once di.os carries one. + / tests assert on a destructive action without destroying anything .z.m.os:use`di.os; / publish the IPC-callable surface at a real root-level name - use-loading this file compiles / it into a private namespace (see di.torq.proc.hdb.init's identical note), so a remote or diff --git a/di/torq/proc/segmentedtp/deps.toml b/di/torq/proc/segmentedtp/deps.toml index 8b8eb97f..2eb9276d 100644 --- a/di/torq/proc/segmentedtp/deps.toml +++ b/di/torq/proc/segmentedtp/deps.toml @@ -4,3 +4,4 @@ "di.eodtime" = "0.1.0" "di.subscriptions" = "0.2.0" "di.torq.servers" = "0.5.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 876ee8fc..63fd0976 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -24,7 +24,6 @@ init:{[config;deps] (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; r:deps[`handlers]`register; r[`.z.pc;`;`stpps;0j;.stpps.closesub]; - / not in deps.toml: di.os has no VERSION, which fails depcheck .z.m.os:use`di.os; .z.m.eod:use`di.eodtime; .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; diff --git a/di/torq/proc/tickerlogreplay/deps.toml b/di/torq/proc/tickerlogreplay/deps.toml index 246e0d5d..8181643f 100644 --- a/di/torq/proc/tickerlogreplay/deps.toml +++ b/di/torq/proc/tickerlogreplay/deps.toml @@ -3,3 +3,4 @@ "di.tplog" = "0.1.0" "di.merge" = "0.2.0" "di.dbwrite" = "0.2.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q index baa16f8c..c182194b 100644 --- a/di/torq/proc/tickerlogreplay/tickerlogreplay.q +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -18,7 +18,6 @@ init:{[config;deps] .z.m.tplog:use`di.tplog; .z.m.dbw:use`di.dbwrite; .z.m.dbw.init enlist[`log]!enlist deps`log; - / not in deps.toml: di.os has no VERSION, which fails depcheck .z.m.os:use`di.os; / all settings required req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; diff --git a/di/torq/proc/wdb/deps.toml b/di/torq/proc/wdb/deps.toml index ec544356..02792cec 100644 --- a/di/torq/proc/wdb/deps.toml +++ b/di/torq/proc/wdb/deps.toml @@ -4,3 +4,4 @@ "di.subscriptions" = "0.2.0" "di.dbwrite" = "0.1.0" "di.merge" = "0.1.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index 802ced71..7c0056c2 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -17,7 +17,7 @@ merge over sortworkers. See "Modes" and "Sortworkers" below. - **Injected** (from di.torq): `log`, `timer`, `servers`. - **Hard** (`use`-imported): `di.subscriptions` (`.sub.subscribe`: subscribe + replay), `di.dbwrite` (the sort and attributes), `di.merge` (partition-size tracking and the EOD merge), `di.os` (moving and deleting - directories; not in `deps.toml`, as it has no VERSION for depcheck), `di.tplogmgr` (via + directories), `di.tplogmgr` (via di.subscriptions). `di.dbwrite` takes the injected **binary** `di.util.log` dep directly — same contract, no adapter diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index c322f69e..5ca52d55 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -707,7 +707,6 @@ init:{[config;deps] / legacy passes -s -N on the command line; torqx.sh has no per-process flags, so it is a setting if[0 Date: Fri, 16 Oct 2026 09:58:07 +0100 Subject: [PATCH 42/42] segmentedtp: retry the tick on error; stop it via a flag The stpzts job is added with disableonfail:0b, so an unrelated error in the tick is retried on the next one. The three end guards set .stplg.stopped, which .stpps.zts checks first, instead of calling disablejobs: di.timer's runandschedule writes its copy of the job row back after the run, so those calls never had a lasting effect and the stop only worked through disableonfail. Co-Authored-By: Claude Opus 5.5 --- di/torq/proc/segmentedtp/segmentedtp.md | 5 +++-- di/torq/proc/segmentedtp/segmentedtp.q | 3 ++- di/torq/proc/segmentedtp/stplog.q | 6 +++--- di/torq/proc/segmentedtp/stpps.q | 2 ++ di/torq/proc/segmentedtp/test.csv | 5 +++-- di/torq/proc/segmentedtp/test.q | 2 +- 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 87e7a821..9750a5f2 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -75,8 +75,9 @@ Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs ## Behaviour to know - End of period and end of day are checked on each update and each timer tick. -- If the next period or roll is already past, or more than a day has gone by, the `stpzts` job is disabled and - the check signals; other timer jobs keep running. +- If the next period or roll is already past, or more than a day has gone by, the tick stops + (`.stplg.stopped`) and the check signals; other timer jobs keep running. Any other error in the tick is retried + on the next tick. - Server tracking stays on (TorQ's STP turns it off), so the process can register with discovery. Heartbeating is not wired and query logging is off unless `[querylog]` is enabled, as in TorQ's STP. - `segmentedchainedtp` has no subscriber cutoff (TorQ's `.subcut`): slow subscribers are not disconnected. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 63fd0976..35b19db1 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -73,6 +73,7 @@ init:{[config;deps] (`..generateschemas)[]; / again after di.torq's .ps.initialise, which registers every root table if[`addinitlist in key `.proc;.proc.addinitlist(`generateschemas;`)]; + .stplg.stopped:0b; .stplg.init[string .z.m.procname]; } @@ -111,7 +112,7 @@ init:{[config;deps] .stplg.ts:.stplg.zts[batch]; .u.upd:.stpps.upd[chainmode]; / the batch timer and end checks run as a 1s di.timer job; the end guards disable only this job - .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();1;1;()!()]; + .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();1;1;(enlist`disableonfail)!enlist 0b]; / error mode: failed updates go to a separate log if[.stplg.errmode; .stp.upd:.u.upd; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q index c59194f4..78c6c741 100644 --- a/di/torq/proc/segmentedtp/stplog.q +++ b/di/torq/proc/segmentedtp/stplog.q @@ -167,7 +167,7 @@ value"loghandles::exec tbl!handle from currlog"; .stpps.endp[currentpd;nextpd;data]; .stplg.currperiod:.stplg.nextperiod; if[(data`p)>.stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; - .z.m.timer[`disablejobs]`stpzts;'"next period is in the past"]; + .stplg.stopped:1b;'"next period is in the past"]; .stplg.getnextendUTC[]; if[rolllogs;.stplg.periodrollover[data]]; .z.m.log[`info][`stpeoperiod;"end of period complete, new values for current and next period are ",.Q.s1 (currentpd;nextpd)]; @@ -190,7 +190,7 @@ value"loghandles::exec tbl!handle from currlog"; .stplg.dayrollover:{[data] .z.m.eod.setnextroll .z.m.eod.getroll data`p; if[(data`p)>.z.m.eod.getnextroll[]; - .z.m.timer[`disablejobs]`stpzts;'"next roll is in the past"]; + .stplg.stopped:1b;'"next roll is in the past"]; .stplg.getnextendUTC[]; .z.m.eod.setd 1+.z.m.eod.getd[]; .stpm.updmeta[.stplg.multilog][`close;.stplg.logtabs;(data`p)+.z.m.eod.getdailyadj[]]; @@ -205,7 +205,7 @@ value"loghandles::exec tbl!handle from currlog"; .stplg.checkends:{ if[.stplg.nextendUTC > x; :()]; if[.stplg.nextperiod < x1:x+.z.m.eod.getdailyadj[]; .stplg.stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; - if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;.z.m.timer[`disablejobs]`stpzts;'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; + if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;.stplg.stopped:1b;'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; }; .stplg.init:{[dbname] diff --git a/di/torq/proc/segmentedtp/stpps.q b/di/torq/proc/segmentedtp/stpps.q index 6ff79b3a..1705ae99 100644 --- a/di/torq/proc/segmentedtp/stpps.q +++ b/di/torq/proc/segmentedtp/stpps.q @@ -17,11 +17,13 @@ / call inner zts and check for end of day/period .stpps.zts.def:{ + if[.stplg.stopped;:()]; .stplg.ts now:.z.p; .stplg.checkends now }; / chained: no period/day end check .stpps.zts.chained:{ + if[.stplg.stopped;:()]; .stplg.ts now:.z.p }; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index ff6aa75c..f86f9675 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -20,7 +20,7 @@ true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperi true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered true,0,0,q,"`stplg in ha""exec name from h.list`.z.exit""",1,,.z.exit observer registered -true,0,0,q,"(`stpzts;1;1)~ha""tickjob""",1,,batch timer added as a 1s timer job +true,0,0,q,"(`stpzts;1;1;(enlist`disableonfail)!enlist 0b)~ha""tickjob""",1,,batch timer added as a 1s timer job that retries on failure comment,,,,,,,subscribe handshake true,0,0,q,"`segmented~ha""tptype""",1,,tptype is segmented @@ -58,7 +58,8 @@ true,0,0,q,"(string hb""currlog[`trade;`logname]"") like ""*/stp2_2*""",1,,singu run,0,0,q,"got:(); hb"".u.sub[`quote;1!([]tbl:enlist`quote;filters:enlist\""bid>1\"";columns:enlist\""sym,bid\"")]""; hb(`.u.upd;`quote;(`a`b;1 2f))",1,,filtered subscription with where and columns true,0,0,q,"(`sym`bid;enlist`b)~(cols last first got;exec sym from last first got)",1,,only matching rows and columns published true,0,0,q,"""next period is in the past""~hb""@[{.stplg.nextperiod:.z.p-2D; .stplg.getnextendUTC[]; .stplg.checkends .z.p};::;::]""",1,,a past next period signals -true,0,0,q,"(enlist`stpzts;60000i)~hb""(stopped;system\""t\"")""",1,,only the tick job is disabled; the process timer is untouched +true,0,0,q,"(1b;`symbol$();60000i)~hb""(.stplg.stopped;stopped;system\""t\"")""",1,,the tick is stopped by flag; no jobs disabled; the process timer is untouched +true,0,0,q,"hb""n:.stplg.nextperiod; tick[]; n~.stplg.nextperiod""",1,,a stopped tick does nothing comment,,,,,,,memorybatch and tabular run,0,0,q,"hc(`.u.upd;`trade;trd`a`b)",1,,send two trades diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index 088d0fef..a9d02c13 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -30,7 +30,7 @@ setupfixture:{[] "errs:()"; "nolog:`info`warn`error!({[c;m]};{[c;m]};{[c;m] errs::errs,enlist m})"; "stopped:`symbol$()"; - "notimer:`addjob`disablejobs!({[a;b;c;d;e;f] if[a~`stpzts;tickjob::(a;d;e);tick::b]};{[x] stopped::stopped,x})"; + "notimer:`addjob`disablejobs!({[a;b;c;d;e;f] if[a~`stpzts;tickjob::(a;d;e;f);tick::b]};{[x] stopped::stopped,x})"; "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist nolog"; "hd:`register`remove`list#h";