From ba9954d35e1fe621c4f8445f11886e2ef891ed46 Mon Sep 17 00:00:00 2001 From: Peter Kaiser Date: Wed, 30 Sep 2026 10:40:58 +0100 Subject: [PATCH 01/15] di.torq.proc.wdb 0.3.0: port legacy wdb, with sort and sortworker modes; idb writedown-mode port wdb: - all four writedown modes (default, partbyattr, partbyenum, partbyfirstchar) and the end-of-day merge (part, col, hybrid) via di.merge - modes saveandsort, save and sort; proctypes sort and sortworker run this module with settings/sort.q and settings/sortworker.q, as legacy loads wdb.q for both - end-of-day sort, move to hdb, reloads and sortworker peach ported from legacy wdb.q; workers setting stands in for -s -N - legacy upd (insert, configurable), movetohdb, clearwdbdata, manipulate, reloadproc helpers; filesystem calls through di.os; sort.csv defaults to $TORQXAPPCONFIG/sort.csv - publishes .wdb.writedownmode for the idb idb: mounts savedir or savedir/ by writedown mode, as legacy; loadsym/loadidb/ loaddb, partitioncounthaschanged, clearrowcountcache, maptoint/mapfctoint at root. Co-Authored-By: Claude Opus 5.5 (1M context) --- di/torq/proc/idb/idb.md | 273 +++-------- di/torq/proc/idb/idb.q | 150 +++--- di/torq/proc/idb/test.csv | 29 +- di/torq/proc/idb/test.q | 22 +- di/torq/proc/wdb/VERSION | 2 +- di/torq/proc/wdb/deps.toml | 1 + di/torq/proc/wdb/init.q | 2 +- di/torq/proc/wdb/test.csv | 81 +++- di/torq/proc/wdb/test.q | 249 ++++++++++ di/torq/proc/wdb/testsort.q | 362 ++++++++++++++ di/torq/proc/wdb/wdb.md | 160 +++++-- di/torq/proc/wdb/wdb.q | 877 +++++++++++++++++++++++++--------- di/torq/settings/sort.q | 1 + di/torq/settings/sortworker.q | 9 + di/torq/torq.md | 3 +- di/torq/torq.q | 5 +- 16 files changed, 1668 insertions(+), 558 deletions(-) create mode 100644 di/torq/proc/wdb/test.q create mode 100644 di/torq/proc/wdb/testsort.q create mode 100644 di/torq/settings/sort.q create mode 100644 di/torq/settings/sortworker.q diff --git a/di/torq/proc/idb/idb.md b/di/torq/proc/idb/idb.md index 32d0fec4..6090f147 100644 --- a/di/torq/proc/idb/idb.md +++ b/di/torq/proc/idb/idb.md @@ -1,136 +1,67 @@ # di.torq.proc.idb -The intraday database process type: mounts the **wdb's working directory** (the same -`savedir` that `di.torq.proc.wdb` incrementally writes/appends into during the day, before its -end-of-day sort + move into the hdb), independently loads the **hdb's sym domain** so the -mounted tables' symbol columns resolve correctly, and exposes a remotely-triggerable reload - -so queries can see today's data before it lands in the hdb. Started by `di.torq` through the -same `init[config;deps]` convention as every other built-in proctype. - -## Design - -### Why point at the wdb's working directory, not the hdb - -`di.torq.proc.wdb` deliberately writes through a permanent working directory and only **moves** -each table into the hdb once it is complete and sorted (see wdb.md, "Why a separate working -dir + move"). That move is what keeps the hdb always either absent-or-complete for a given -partition — a mid-day crash can't leave partial data there. The trade-off is that the hdb -alone can't answer "what happened so far today"; `di.torq.proc.idb` fills that gap by mounting -the wdb's working dir directly, accepting that data there may be unsorted and can, in the -narrow window of an in-flight flush, be incompletely appended (see "Known gaps"). - -### `.z.m.symfilepath` / `loadsym[]` - -The wdb enumerates every flushed table's symbol columns against **its `hdbdir`**, not -`savedir` (`di.torq.proc.wdb`'s `flushtable`, `` .Q.en[.z.m.hdbdir;...] ``) - live, on every -flush, not just at EOD. So the working-partition tables idb mounts carry symbol columns that -are true kdb+ enumerations (foreign keys) against `hdbdir/sym`, and reading them back -correctly requires that **same** `sym` domain to exist in idb's own session - without it, a -symbol column reads back as raw integer indices instead of symbols. `.z.m.symfilepath` is the fixed -path to that file, derived once in `setparametersfromwdb[]` from the `hdbdir` the wdb reported, -as legacy sets its `symfilepath`. It is not partition-scoped: the wdb enumerates every -day against the same one. `loadsym[]` reads it into the root `sym`, -called from `init` (always) and from `intradayreload[]` (only when the file has changed - see -`symfilehaschanged[]` below), in both cases before `domount[]`, matching legacy TorQ's own -`loadsym`-before-`loadidb` order in `loaddb`. - -### `symfilehaschanged[]` - -The wdb calls `.idb.intradayreload[]` after **every** intraday flush that wrote anything, but `.Q.en` -only rewrites `hdbdir/sym` when it meets a symbol the domain doesn't already have. On a busy -day the overwhelming majority of those reloads therefore have nothing new to read, so -**`intradayreload[]` gates its `loadsym[]` call** on `symfilehaschanged[]` - after legacy TorQ's function -of the same name (`TorQ/code/processes/idb.q`). It turns the common case from a full read of a -domain that grows all day into a `hcount` stat. - -Unlike legacy, the check is a **pure predicate**: the new size is recorded by `readsym[]`, only -once the `load` has actually succeeded. Legacy stamps the size the moment it detects a change, so -a read that then fails is never retried and root `sym` stays stale until the file changes again. -Recording on success instead means a failed read leaves `symsize` alone and the next reload tries -again. - -The gate lives in the **caller**, not in `loadsym[]`, which stays an unconditional force-load - -the same split legacy TorQ has between `loaddb` (force: startup and rollover) and -`intradayreload` (gated). `init` additionally clears `symsize` before force-loading: a size -recorded against a previous `init`'s `hdbdir` says nothing about the file this one was handed, -and since a failed read records nothing, it could otherwise carry over indefinitely. - -One consequence worth knowing: if a read fails and the file is later restored to **exactly** the -size of the last good one, the reload is skipped. That is harmless - a failed `load` never -modifies root `sym`, so the domain still in memory is the one that file holds. `domount[]` is -*not* gated - see "Mounting" below. - -It compares **size**, not modification time: the sym file only ever grows (`.Q.en` appends), so -a size change is exactly a content change, while mtime granularity can miss two writes within -the same second. `hcount` is trapped to `0` rather than left to throw, and the guard is checked -*after* `loadsym[]`'s existence test - so a sym file appearing for the first time is always -read, since a missing file stats as `0`, which is also `symsize`'s initial value. - -`init` calls `loadsym[]` directly, so it always reads the file it has just been pointed at -rather than trusting a size recorded against a previous init's `hdbdir`. - -`loadsym[]` uses legacy TorQ's plain `load`, which **replaces** root `sym` with the file's -contents rather than merging into it. The file is the enumeration domain and the on-disk columns -are integer positions in it, so root `sym` has to match its order exactly; a union against a `sym` -that had drifted out of step would keep the wrong order and resolve every symbol column to the -wrong value, silently. - -`load` is one of the few writes that does **not** need the `` @[`.;...] `` root anchoring the rest -of this tier uses - it names the variable after the file, and lands at root even when called from -inside a `use`-loaded module (verified directly; `sym` never appears in the module's private -namespace). - -### Mounting - -`domount[]` mounts **`savedir` itself** with a plain `\l`, as a partitioned database - the same -thing legacy TorQ's idb does in `default` writedown mode (`idbdir::.Q.dd[savedir;`]`). The tables -therefore carry a virtual `date` column, and the idb never has to know which date the wdb is on: a -new day's partition simply appears under the root and the next reload sees it. - -That matters because the wdb's partition and the wall clock are not the same thing. At end of day -the wdb moves to `pt+1` while `.z.d` is still `pt`, so any idb that derived its own date from the -clock would spend the rest of the day mounting a directory that had just been moved into the hdb. -Mounting the root sidesteps it entirely, with no date on the wire and no wdb handshake. - -The remount is unconditional. Measured on a root mount: rows appended to an existing partition are -**not** visible without one, and neither is a new partition directory - so there is nothing to gate -on. Legacy gates `loadidb` with `partitioncounthaschanged[]` and leans on `clearrowcountcache[]` -(`.Q.pn` reset) for the append case; that does not hold up here - clearing `.Q.pn` left `count` -stale, and only a remount refreshed it. `\l` of one directory is cheap and a reload is driven by -the wdb, not a timer. - -`loadsym[]` (see above), then `domount[]`, which mounts `savedir` **only if it currently exists** -- otherwise it logs a warning and leaves whatever was already loaded in place. It legitimately -does not exist at idb startup, if the idb comes up before the wdb has flushed anything at all. -Without the guard, `system "l"` on a missing directory throws, which would crash `init` before it -reached `` set[`.idb.intradayreload;intradayreload] `` - leaving no entry point to recover with. -Guarding it means `init` always finishes and publishes, so the very next `intradayreload[]` (once -the wdb produces data) picks it up normally. - -`intradayreload` and `rollover` are published at real root names for the same reason -`di.torq.proc.hdb` publishes `.hdb.reload` - `use`-loading this module compiles it into a private, -mangled namespace, so a remote `` .idb.intradayreload[] `` call needs a plain root-level entry -point to exist (torq-developer skill, Rule E3). +The intraday database process type, ported from TorQ's `code/processes/idb.q`. It mounts the +**wdb's working directory** and the **hdb's sym file**, so today's data can be queried before the +wdb's end of day moves it into the hdb. Started by `di.torq` through the same +`init[config;deps]` convention as every other built-in proctype. + +## How it works + +At `init` the idb asks the wdb where it is writing (`setparametersfromwdb`), then force-loads the +sym file and the db (`loaddb`). After that it only reacts to the wdb: + +| Call | From | Does | +|---|---|---| +| `.idb.intradayreload[]` | the wdb, after a flush that wrote something | reloads the sym file if it grew, remounts if the partition count changed, clears the `.Q.pn` row-count cache | +| `.idb.rollover[pt]` | the wdb or sort process, at end of day | sets the current partition, moves the mount for it, force-loads the db | + +### What gets mounted + +As legacy, the mount depends on the wdb's writedown mode: + +| `writedownmode` | `idbdir` | Mounted as | +|---|---|---| +| `default` | `savedir` | a date-partitioned db, with a virtual `date` column | +| `partbyenum`, `partbyfirstchar` | `savedir/` | an int-partitioned db, one partition per enumerated value / first character | + +`partbyattr` gets the `savedir/` mount too, but as in legacy the wdb never sends +it a reload, so it is not served intraday. + +For querying the int-partitioned modes, `maptoint` and `mapfctoint` are published at root, as in +legacy: they map a sym (or int) value, or a sym's first character, to its int partition. + +### Reloads + +`intradayreload` only remounts when `partitioncounthaschanged[]`. Rows appended to a partition +that is already mounted are seen by a `select` without a remount; only `count` is cached, in +`.Q.pn`, which `clearrowcountcache[]` resets. In `default` mode a single partition never needs a +remount at all. + +### The sym file + +The wdb enumerates against the hdb's `sym`, so the idb loads that file into root `sym` +(`loadsym`). It is reloaded only when its size changes (`symfilehaschanged[]`), since `.Q.en` only +ever appends. + +Two differences from legacy: +- **The size is recorded only after a successful load.** Legacy records it as soon as it sees a + change, so a load that then fails is never retried. +- **`hcount` is trapped.** The sym file does not exist until the wdb's first `.Q.en`, so the idb + can start before it. + +A missing `savedir` at startup is logged as an error by `loadidb`, as legacy, and does not stop +`init`; the next reload after the wdb has written picks it up. ## The wdb handshake -`savedir` and `hdbdir` must resolve to the **same directories the wdb uses**. Rather than leave -that to two config files kept in step by hand, `init` asks the wdb — `setparametersfromwdb[]`, -named after legacy's function of the same job. It calls `servers` `startup` with a `wdbtypes` -connection, blocks on `waitfortype`, then reads the wdb's own root variables: +`setparametersfromwdb` connects to a `wdbtypes` process, waits for it, and reads: ```q -(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition) +(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode) ``` -exactly as legacy reads `.wdb.savedir` and friends. It sets `savedir`, `symfilepath` and -`partition` from the answer; nothing else in the module derives them. - -`savedir`/`hdbdir` are not settings the idb reads at all — the wdb is the only source — so -`di/torq/settings/idb.q` is gone rather than empty. - -Failing to reach a wdb within the timeout **fails init**, naming the proctype. That is a real -startup dependency the module did not previously have. +The idb takes `savedir` and `hdbdir` from the wdb, never from its own config. Failing to reach a +wdb within `connecttimeoutms` fails `init`. ## Dependencies @@ -141,94 +72,24 @@ startup dependency the module did not previously have. | key | meaning | |---|---| -| `wdbtypes` | proctype(s) to ask for `savedir`/`hdbdir`. Default `` `wdb ``. | +| `wdbtypes` | proctype to ask for its directories and writedown mode. Default `` `wdb ``. | | `connecttimeoutms` | how long to wait for a wdb before failing init. Default 30000. | -## Usage - -```q -q)idb:use`di.torq.proc.idb -q)lg:use`di.util.log -q)logdep:`info`warn`error!(lg`info;lg`warn;lg`error) -q)cfg:`savedir`hdbdir!(`$":/tmp/di_idb_readme_demo";`$":/tmp/di_idb_readme_hdb_demo") -q)idb[`init][cfg;enlist[`log]!enlist logdep] -2026.07.09D12:41:24.703763000 INFO init mounting idb from :/tmp/di_idb_readme_demo/2026.07.09 -2026.07.09D12:41:24.703850000 WARN loadsym no sym file at /tmp/di_idb_readme_hdb_demo/sym yet - symbol columns may not resolve -2026.07.09D12:41:24.703897000 INFO domount loaded tables: trade -q)tables[] -,`trade -q)delete trade from `. -q).idb.intradayreload[] -2026.07.09D12:41:24.703928000 INFO reload reloading idb from :/tmp/di_idb_readme_demo/2026.07.09 -q)tables[] -,`trade -``` +## Not ported -(Called via `idb[`init]`, not `idb.init` - dot-syntax on a module dict returned by a `use` call -in the same session/frame is unreliable in this kdb-x build; see `test.csv`'s comment and -`di.torq`'s own `buildlogdep` note for the same caveat elsewhere. `.idb.intradayreload[]` is unaffected -- it's a plain root function, not accessed through the module dict.) - -In the real sample app, `di.torq` builds `config`/`deps` from the settings cascade and calls -`(m`init)[config;deps]` itself (`torq.q`'s `startbuiltin` - bracket-indexed, same reasoning as -above) when `proctype` is `` `idb ``. Pointing an idb's `savedir` at -the **same** directory as a running wdb's `savedir` (matching config value, resolved to the -same absolute path) is what makes it see that wdb's intraday writes. - -## Known gaps (v1) - -- **No `writedownmode` awareness in the handshake.** `setparametersfromwdb[]` takes `savedir` and `hdbdir` - from the wdb and records `currentpartition`, which nothing consumes yet - the root mount needs - no date. It is kept for gateway routing and for the partition-scoped writedown modes below, - either of which makes it load-bearing. It does not ask for `writedownmode`, which legacy uses - to choose between mounting the root and mounting a single partition. Moot while only `default` - writedown exists. -- **No self-registration or attribute-based gateway routing.** Legacy TorQ's idb registers - itself with the wdb (`` .servers.registerfromdiscovery ``) and publishes - `` .proc.getattributes `` (`` `partition`tables!(partition;tables[]) ``) so a - gateway can route queries to whichever idb currently holds the relevant partition/tables. - `di.torq.proc.idb` does neither: the wdb finds it the same static way it finds every other - peer (`process.csv` + `idbtypes` in `CONNECTIONS`), and there is nothing to register with a - gateway anyway - `di.torq.proc.gateway` v1 has no backend attribute-reporting plumbing yet - for *any* backend type, not just idb (see gateway.q's "EMPTY attributes" note). -- **`writedownmode`-aware layout, and the `partbyenum`/`partbyfirstchar` query-mapping - helpers** (`maptoint`/`mapfctoint` in `TorQ/code/processes/idb.q`). Legacy TorQ's idb picks - its mount directory differently depending on the wdb's active writedown mode, and ships - helpers for querying a `partbyenum`/`partbyfirstchar`-mapped sym column. Moot while - `di.torq.proc.wdb` only implements the classic `default` writedown mode (see wdb.md, "Not - included") - would need porting together if wdb ever grows the advanced modes. -- **No sort/attribute awareness.** The idb mounts whatever is on disk, unsorted, exactly as the - wdb wrote it (matching `di.dbwrite`'s appended-not-sorted intraday writes). -- **`domount[]` is never gated**, unlike legacy TorQ's `loadidb`, and there is no `.Q.pn` - row-count-cache reset. Both follow from mounting a single date directory of splayed tables - see "Mounting" above - a remount is the only thing that refreshes either, so there is nothing - to gate on. -- **Read-during-write race.** The wdb's per-table flush (create-or-append) is not atomic - from a reader's point of view; a reload that lands mid-flush could see a partially - appended table. Same class of risk legacy TorQ's idb accepts for intraday data - only the - hdb (post-move) is guaranteed complete-or-absent. -- **One directory, one mount** - no multi-database layout beyond what a plain `` \l `` already - gives (matching `di.torq.proc.hdb`'s equivalent gap). +- **Registering with the wdb** (`` .servers.registerfromdiscovery ``). The wdb finds the idb + through `process.csv` and `idbtypes`, like any other peer. +- **`.proc.getattributes`**, for gateway routing. `di.torq.proc.gateway` has no attribute + reporting for any backend yet. +- **A root `reload`.** The sort process calls `.idb.intradayreload[]` by name. ## Testing -`test.csv`/`test.q` (k4unit) cover: init failing without a `log` or `servers` dependency, init -failing when no wdb answers within the timeout, the handshake being made and its `savedir`/ -`hdbdir`/`currentpartition` taken, `savedir`/`hdbdir` still set in config being ignored rather -than used, the mount being partitioned with a virtual `date` column and both dated fixture -partitions visible, the loaded root `sym` matching the fixture domain and the fixture's -genuinely-enumerated `name` column resolving to real symbols (not raw indices - the exact failure -mode `loadsym[]` exists to prevent), the published `.idb.intradayreload[]` actually remounting -after a table is dropped, `.idb.rollover[pt]` recording the new partition and remounting, and a -wdb reporting a `savedir` that is not on disk (must warn, not throw, and recover on the next -reload once data appears). The fixture's `widgets` table is -built with `.Q.en` and written with a trailing-slash path (`` ` sv (path;`) ``, matching -`di.torq.proc.wdb`'s own `flushtable`) so it's a genuine splayed, enumerated table on disk, not -a flat serialised file - a bare `` `:dir/widgets `` (no trailing slash) silently "worked" with -the old non-enumerated fixture but throws `'type` on mount for a real enum column. Every -`idb[...]` call in `test.csv` is bracket-indexed, not `idb.xxx` - see the Usage section above. -Run in a fresh q session (this suite calls `setenv`, so don't interleave it with other -modules' tests in one shared process): +`test.csv`/`test.q` (k4unit) cover the dependency checks, the wdb handshake (including a wdb that +does not publish each variable), the default and `partbyenum` mounts, rollover moving the mount, +reloads remounting only when the partition count changes, the sym-file change detection and +retry, and a missing `savedir`. Every `idb[...]` call is bracket-indexed, not `idb.xxx`. Run in a +fresh q session, as the suite calls `setenv`: ```q q)k4unit:use`di.k4unit diff --git a/di/torq/proc/idb/idb.q b/di/torq/proc/idb/idb.q index 01626b63..0a478108 100644 --- a/di/torq/proc/idb/idb.q +++ b/di/torq/proc/idb/idb.q @@ -1,85 +1,61 @@ -/ di.torq.proc.idb - intraday database process type. Mounts the WDB's *working* directory (the -/ same `savedir` the wdb writes/appends into during the day, before EOD sort+move into the -/ hdb - see di.torq.proc.wdb) so queries can see today's not-yet-persisted-to-hdb data intraday. -/ --- -/ v1 is a minimal, di.torq.proc.hdb-shaped mount + remount: di.torq.proc.idb only exposes a -/ remotely-triggerable `.idb.intradayreload[]`, same shape as di.torq.proc.hdb's `.hdb.reload[]` - -/ something else has to call it after data changes on disk. idb itself never polls or pushes; -/ that something else is the wdb, which calls `.idb.intradayreload[]` on every idbtypes connection two -/ ways - after any intraday flush that actually wrote something (unconditional), and again at -/ EOD if `idb` is opted into `reloadorder` (see di.torq.proc.wdb's wdb.q/wdb.md). -/ --- -/ It mounts savedir ITSELF, as a partitioned database, exactly as legacy TorQ's idb does in -/ default writedown mode (idbdir::.Q.dd[savedir;`]). So the tables carry a virtual `date` column -/ and the idb never needs to know which date the wdb is on - a new day's partition simply appears -/ under the root and the next reload picks it up. Mounting a single date directory instead would -/ mean tracking the wdb's partition, which wall-clock .z.d gets wrong for any end of day that is -/ not at midnight. -/ --- -/ The wdb enumerates every flushed table against ITS hdbdir, not against savedir (see -/ di.torq.proc.wdb's flushtable, `.Q.en[.z.m.hdbdir;...]`) - live, on every flush, not just at -/ EOD (`.Q.en` extends the domain AND rewrites hdbdir/sym on disk whenever it sees a symbol -/ that domain doesn't already have). So the mounted working-partition tables' symbol columns -/ are enumerated (foreign-keyed) against that SAME hdbdir/sym, not anything under savedir - -/ idb needs `hdbdir` as its own config, purely to load that file into its own session's root -/ `sym`, independently of mounting savedir. Without it, `` `sym `` never exists in the idb's -/ session and a symbol column reads back as raw enum indices instead of symbols. +/ di.torq.proc.idb - ported from TorQ's idb.q +/ mounts the wdb's working directory so today's data can be queried before it reaches the hdb astz:{[x] $[11h=abs type x;x;`$(),x]} tolong:{[x] $[10h=abs type x;"J"$(),x;"j"$x]} -/ legacy TorQ's symfilehaschanged. Size, not mtime: .Q.en only ever appends. -/ hcount is trapped where legacy calls it bare: the wdb creates hdb/sym on its first .Q.en, so a -/ wdb that is up but has not flushed yet leaves us statting a file that is not there. -symfilehaschanged:{[] - .z.m.symsize<>@[hcount;.z.m.symfilepath;0] - } - -/ legacy TorQ's `load symfilepath` - it names the variable after the file, so it sets root `sym` -/ even from inside a use-loaded module (verified). REPLACES rather than merges: the file is the -/ enumeration domain and the on-disk columns are positions in it, so root sym must match its order -/ exactly - a union against a reordered sym resolves every symbol column to the wrong value. -readsym:{[f] - load f; - .z.m.log[`info][`loadsym;"loaded sym domain (",(string count get `sym),") from ",string f]; - .z.m.symsize:@[hcount;f;0]; +/ force loads sym file; the size is only recorded once the load succeeds, so a failed read is retried +loadsym:{[] + .z.m.log[`info][`load;"loading the sym file"]; + @[{load x;.z.m.symsize:@[hcount;x;0]};.z.m.symfilepath;{.z.m.log[`error][`load;"failed to load sym file: ",(string .z.m.symfilepath)," error: ",x]}]; } -/ force-load the sym domain; the caller decides whether to skip, as legacy splits loaddb from -/ intradayreload. A missing file is logged and survived - symsize stays 0 so the next reload -/ picks it up once a wdb has flushed. -loadsym:{[] - .z.m.log[`info][`loadsym;"loading the sym file"]; - @[readsym;.z.m.symfilepath;{.z.m.log[`error][`loadsym;"failed to load sym file: ",(1_string .z.m.symfilepath),", with error: ",x]}]; +/ force loads IDB +loadidb:{[] + .z.m.log[`info][`load;"loading the db"]; + @[system;"l ",1_string .z.m.idbdir;{.z.m.log[`error][`load;"failed to load IDB: ",(string .z.m.idbdir)," error: ",x]}]; + .z.m.partitionsize:count key .z.m.idbdir; } -/ (re)mount savedir as a partitioned db. Empty or absent is normal - the wdb creates it on its -/ first flush - so warn and leave what is loaded rather than let system "l" take the process down. -domount:{[] - d:1_string .z.m.savedir; - $[count key .z.m.savedir; - [system "l ",d; .z.m.log[`info][`domount;"loaded tables: ",", " sv string tables[]]]; - .z.m.log[`warn][`domount;"no working directory at ",d," yet - nothing to mount"]]; +/ force loads the idb and the sym file +loaddb:{[] + starttime:.z.t; + loadsym[]; + loadidb[]; + .z.m.log[`info][`load;"IDB load has been finished for partition: ",(string .z.m.currentpartition),". Time taken(ms): ",string .z.t-starttime]; } -/ the wdb has rolled to a new day (legacy's .idb.rollover). The root mount finds the new day by -/ itself, so .z.m.partition drives nothing today - it is kept for the two things that will need it: -/ gateway routing (legacy's .proc.getattributes) and the partition-scoped writedown modes, where -/ the mount is savedir/ rather than the root. Not exposed until one of them lands. +/ sets current partition and force loads the idb and the sym file. Called by the wdb after EOD. rollover:{[pt] - .z.m.partition:pt; - .z.m.log[`info][`rollover;"wdb rolled to partition ",string pt]; - intradayreload[]; + .z.m.currentpartition:pt; + .z.m.idbdir:.Q.dd[.z.m.savedir;$[.z.m.writedownmode~`default;`;pt]]; + .z.m.log[`info][`rollover;"IDB folder has been set to: ",string .z.m.idbdir]; + loaddb[]; } +/ reloads the db. Called by the wdb after an intraday flush. intradayreload:{[] - .z.m.log[`info][`reload;"reloading idb from ",1_string .z.m.savedir]; + starttime:.z.t; if[symfilehaschanged[];loadsym[]]; - domount[]; + if[partitioncounthaschanged[];loadidb[]]; + clearrowcountcache[]; + .z.m.log[`info][`intradayreload;"IDB reload has been finished for partition: ",(string .z.m.currentpartition),". Time taken(ms): ",string .z.t-starttime]; } -/ ask the wdb where it is writing and set our state from it - same name and job as legacy's. -/ The two must agree on savedir and hdbdir, and config on both sides drifts apart. +/ checks if sym file has changed since last load of the IDB; hcount trapped as hdb/sym is absent until the wdb's first .Q.en +symfilehaschanged:{[] .z.m.symsize<>@[hcount;.z.m.symfilepath;0]} + +/ checks if count of partitions has changed since last reload of the IDB. Records new partition count if changed. +/ the default writedown method doesn't need db reloading as no new directory is being created there. +partitioncounthaschanged:{[] + if[(1j~.z.m.partitionsize) and .z.m.writedownmode~`default;:0b]; + $[.z.m.partitionsize<>c:count key .z.m.idbdir;[.z.m.partitionsize:c;1b];0b] + } + +/ this makes sure running "count trade" queries will return correct row count +clearrowcountcache:{[] set[`.Q.pn;.Q.pt!(count .Q.pt)#()]} + +/ reads savedir, hdbdir, the current partition and the writedown mode from the wdb setparametersfromwdb:{[config] wt:$[`wdbtypes in key config;astz config`wdbtypes;`wdb]; t:$[`connecttimeoutms in key config;tolong config`connecttimeoutms;30000]; @@ -87,31 +63,43 @@ setparametersfromwdb:{[config] if[not (.z.m.svc`waitfortype)[wt;t;500]; '"di.torq.proc.idb: no ",(string wt)," connection within ",(string t),"ms - cannot resolve savedir/hdbdir"]; h:(.z.m.svc`gethandlebytype)[wt;`any]; - / the error carries the offending name, so it needs no interpolation of our own - p:@[h;(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition);{'"di.torq.proc.idb: could not read from the wdb: ",x}]; - / the wdb's paths are already hsyms; keep them as such and build the sym path with .Q.dd, as - / legacy's symfilepath does. It is never partition-scoped - every day enumerates against the one. - .z.m.savedir:p 0; - .z.m.symfilepath:.Q.dd[p 1;`sym]; - .z.m.partition:p 2; - .z.m.log[`info][`setparametersfromwdb;"savedir=",(1_string .z.m.savedir),", partition=",string .z.m.partition]; + .z.m.log[`info][`init;"querying WDB, HDB locations, current partition and writedown mode from WDB"]; + params:@[h;(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode);{'"di.torq.proc.idb: could not read from the wdb: ",x}]; + .z.m.savedir:hsym params 0; + .z.m.currentpartition:params 2; + .z.m.symfilepath:.Q.dd[hsym params 1;`sym]; + .z.m.writedownmode:params 3; + .z.m.idbdir:.Q.dd[.z.m.savedir;$[.z.m.writedownmode~`default;`;.z.m.currentpartition]]; + .z.m.log[`info][`init;"Current settings: db folder: ",(string .z.m.idbdir),", sym file: ",(string .z.m.symfilepath),", writedownmode: ",string .z.m.writedownmode]; + } + +/ helper function to support queries against the sym column +maptoint:{[val] + $[(abs type val) in 5 6 7h; + / if using an integer column, clamp value between 0 and max int (null maps to 0) + 0|2147483647&`long$val; + / if using a symbol column, enumerate against the hdb sym file + (`. `sym)?`TORQNULLSYMBOL^val] } +/ helper function to support queries against the sym column in partbyfirstchar +mapfctoint:{[val] .Q.an?$[0 otherwise +run,0,0,q,setupfixture[],1,,fixture on disk +run,0,0,q,setwdbparams[],1,,a default-mode wdb +run,0,0,q,idb[`init][cfg[];mockdeps[]],1,,init in default mode +true,0,0,q,rootmounted[],1,,default mode mounts the savedir root +run,0,0,q,resetcalls[],1,,reset call log +run,0,0,q,.idb.intradayreload[],1,,an intraday reload with the partition count unchanged +true,0,0,q,not 0 +true,0,0,q,6=count widgets,1,,both int partitions are visible - 3 rows each +true,0,0,q,`int in .Q.pf,1,,the mount is int-partitioned +run,0,0,q,.idb.rollover[TESTDATE+1],1,,the wdb rolls the idb to the next day +true,0,0,q,datemounted TESTDATE+1,1,,rollover moves the mount to the new partition +true,0,0,q,0 5~maptoint 0N 5,1,,maptoint is published at root and maps a null int to 0 +true,0,0,q,(.Q.an?"b")~mapfctoint`bob,1,,mapfctoint is published at root +run,0,0,q,set[`.wdb.writedownmode;`default],1,,restore default mode after,0,0,q,teardownfixture[],1,,remove the temp fixture directory diff --git a/di/torq/proc/idb/test.q b/di/torq/proc/idb/test.q index 5500a336..ed6aef58 100644 --- a/di/torq/proc/idb/test.q +++ b/di/torq/proc/idb/test.q @@ -25,7 +25,7 @@ mockservers:{[] `startup`getservers`gethandlebytype`waitfortype!(mockstartup;moc mockdeps:{[] `log`servers!(`info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;]);mockservers[])} / the root variables a real wdb publishes, which the evaluated query reads -setwdb:{[sd] set[`.wdb.savedir;sd]; set[`.wdb.hdbdir;hsym `$FIXTUREHDBDIR]; set[`.wdb.currentpartition;TESTDATE];} +setwdb:{[sd] set[`.wdb.savedir;sd]; set[`.wdb.hdbdir;hsym `$FIXTUREHDBDIR]; set[`.wdb.currentpartition;TESTDATE]; set[`.wdb.writedownmode;`default];} setwdbparams:{[] setwdb hsym `$FIXTUREDIR;} / the wdb reports a savedir that is not on disk - the window before its first flush @@ -49,7 +49,7 @@ initnovar:{[v] askedwdb:{[] `waitfortype in exec fn from scalls} / the query the idb actually sent, captured by the mock handle -askedforvars:{[] LASTQ~(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition)} +askedforvars:{[] LASTQ~(each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode)} resetservercalls:{[] `scalls set ([]fn:`symbol$();arg:()); `WAITOK set 1b; `LASTQ set ();} FIXTUREDIR:"/tmp/di_idb_k4unit_fixture" @@ -104,7 +104,7 @@ stalecfg:{[] `wdbtypes`savedir`hdbdir!(`wdb;`$":",FIXTUREDIR;`$":",FIXTUREHDBDIR / an unchanged sym file is silent, so a skip is proven by the absence of the entry log symattempted:{[] 0//, as the wdb's partbyenum writes +setupenumfixture:{[] + system "rm -rf ",FIXTUREDIR; + widgets:.Q.en[hsym `$FIXTUREHDBDIR;([]id:1 2 3;name:`a`b`c)]; + {[w;i] (` sv (hsym `$FIXTUREDIR,"/",(string TESTDATE),"/",(string i),"/widgets";`)) set w}[widgets] each 0 1; + set[`.wdb.writedownmode;`partbyenum]; + } 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..ecd0c78e 100644 --- a/di/torq/proc/wdb/deps.toml +++ b/di/torq/proc/wdb/deps.toml @@ -3,3 +3,4 @@ "di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers) "di.subscriptions" = "0.1.0" "di.dbwrite" = "0.1.0" +"di.merge" = "0.1.0" diff --git a/di/torq/proc/wdb/init.q b/di/torq/proc/wdb/init.q index 24eb5f85..be39c627 100644 --- a/di/torq/proc/wdb/init.q +++ b/di/torq/proc/wdb/init.q @@ -2,4 +2,4 @@ version:first read0`:::VERSION -export:([init;endofday;version]) +export:([init;endofday;endofdaysort;version]) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index bd357106..80d0e501 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -1,9 +1,88 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,wdb:use`di.torq.proc.wdb,1,,load module before,0,0,q,mlog:`info`warn`error!(3#enlist {[c;m]}),1,,a minimal (dyadic) log dep dict +before,0,0,q,mtimer:`addjob`deletejobs!(2#enlist {[x]}),1,,a minimal timer dep dict +before,0,0,q,mservers:`startup`getservers`gethandlebytype`waitfortype!(4#enlist {[x]}),1,,a minimal servers dep dict +before,0,0,q,"alldeps:`log`timer`servers!(mlog;mtimer;mservers)",1,,every injected dep the wdb requires +before,0,0,q,"initerr:{[c] @[{[x] wdb.init[x;alldeps]};c;{x}]}",1,,run init for a config and return the error string fail,0,0,q,wdb.init[()!();()!()],1,,init without the log dependency must error fail,0,0,q,wdb.init[()!();(enlist`log)!enlist mlog],1,,init with log but no timer dependency must error -true,0,0,q,`init`endofday`version~key wdb,1,,module exports init/endofday/version +true,0,0,q,`init`endofday`endofdaysort`version~key wdb,1,,module exports init/endofday/endofdaysort/version true,0,0,q,0/dev/null 2>&1 &"; + n:0; + while[(null TPH) and 50>n+:1;`TPH set @[hopen;(`$"::",string TPPORT;200);{0Ni}];if[null TPH;system "sleep 0.1"]]; + }; + +stoptp:{[] @[{neg[x](exit;0);neg[x][]};TPH;::]; @[hclose;TPH;::]; `TPH set 0Ni;}; + +setup:{[] + system "rm -rf ",BASE; + system "mkdir -p ",BASE,"/appconfig"; + setenv[`TORQXDATAHOME;BASE]; + setenv[`TORQXAPPHOME;BASE]; + setenv[`TORQXAPPCONFIG;BASE,"/appconfig"]; + (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,p,sym,1";"default,,time,1"); + starttp[]; + }; + +cfg:{[] `savedir`hdbdir`sortcsv`numrows`eodwaittime`reloadorder`ignorelist!("wdb";"hdb";"appconfig/sort.csv";100000;0;`hdb;`heartbeat`logmsg`calls)}; + +today:{[] .z.D}; +hdbpart:{[t] hsym `$BASE,"/hdb/",(string today[]),"/",string t}; +wdbpart:{[] hsym `$BASE,"/wdb/",string today[]}; + +freshwdb:{[c] + `calls set 0#calls; + system "rm -rf ",BASE,"/wdb ",BASE,"/hdb"; + wdb.init[c;recdeps[]]; + }; + +/ 8 trades over three syms, fed in two batches so a partitioned mode writes more than one segment +feed:{[] + upd[`trade;([]time:.z.D+0D09 0D12 0D10 0D11;sym:`ibm`msft`ibm`aapl;price:4?100f)]; + upd[`quote;([]time:.z.D+0D09 0D08;sym:`ibm`msft;bid:2?10f)]; + .m.di.0torq.0proc.0wdb.savetodisk[]; + upd[`trade;([]time:.z.D+0D15 0D14 0D13 0D16;sym:`msft`aapl`ibm`msft;price:4?100f)]; + }; + +/ the whole day ends up in the hdb, grouped by sym with p# applied, and the working partition is gone +eodok:{[c] + freshwdb c; + feed[]; + endofday today[]; + t:select from get hdbpart`trade; + s:value t`sym; + chk `rows`psym`grouped`quote`wdbgone!( + 8=count t; + `p=attr (get hdbpart`trade)`sym; + (count distinct s)=sum differ s; + 2=count get hdbpart`quote; + 0=count key wdbpart[]) + }; + +defaultmode:{[] eodok cfg[]}; +partbyattr:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyattr;m)}; +partbyenum:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyenum;m)}; +partbyfirstchar:{[m] eodok cfg[],`writedownmode`mergemode!(`partbyfirstchar;m)}; + +/ each intraday flush writes one segment per parted value, and the sizes are tracked for the merge +segments:{[] + freshwdb cfg[],`writedownmode`immediate!(`partbyattr;1b); + feed[]; + ps:(use`di.merge)[`getpartsizes][]; + chk `segs`tracked!( + `aapl`ibm`msft~asc key hsym `$(1_string wdbpart[]),"/trade"; + 3=count select from ps where ptdir like "*trade*") + }; + +/ startup writes empty schemas into the working partition for the idb +missingtables:{[] + freshwdb cfg[]; + chk `trade`quote!(0=count get ` sv (wdbpart[];`trade;`);0=count get ` sv (wdbpart[];`quote;`)) + }; + +tabsizes:{[] + freshwdb cfg[],(enlist`immediate)!enlist 1b; + upd[`quote;([]time:.z.D+0D01*til 5;sym:5#`ibm;bid:5?10f)]; + upd[`trade;([]time:.z.D+0D01*til 2;sym:2#`ibm;price:2?10f)]; + .m.di.0torq.0proc.0wdb.savetodisk[]; + `quote`trade~2#.m.di.0torq.0proc.0wdb.tablelist[] + }; + +manipulation:{[] + freshwdb cfg[],(enlist`savedownmanipulation)!enlist (enlist`trade)!enlist {update price:2*price from x}; + upd[`trade;([]time:enlist .z.D+0D01;sym:enlist`ibm;price:enlist 5f)]; + endofday today[]; + 10f~first (get hdbpart`trade)`price + }; + +postreplay:{[] + `POST set (); + freshwdb cfg[],(enlist`postreplay)!enlist {[d;p] `POST set (d;p)}; + feed[]; + endofday today[]; + (last POST)~today[] + }; + +compression:{[] + freshwdb cfg[],(enlist`compression)!enlist 17 2 6; + feed[]; + endofday today[]; + chk `compressed`reset!( + 0/dev/null 2>&1 &"; + h:0Ni;n:0; + while[(null h) and 50>n+:1;h:@[hopen;(`$"::",string port;200);{0Ni}];if[null h;system "sleep 0.1"]]; + `PEERH set PEERH,h; + h + }; + +stoppeers:{[] + {@[{neg[x](exit;0);neg[x][]};x;::];@[hclose;x;::]} each PEERH; + `PEERH set `int$(); + `PEERS set (`symbol$())!(); + }; + +/ a saveandsort wdb started with a negative -s merges on its sortworkers +workermerge:{[] + `PEERS set enlist[`sortworker]!enlist h:startpeer each `sortworker`sortworker; + system "s -2"; + r:eodok cfg[],`writedownmode`mergemode!(`partbyattr;`hybrid); + system "s 0"; + merged:{[h] count h"select from LOGS where ctx=`merge,msg like \"*merge complete\""} each h; + stoppeers[]; + r and all 0/dev/null 2>&1 &"; + h:0Ni;n:0; + while[(null h) and 50>n+:1;h:@[hopen;(`$"::",string port;200);{0Ni}];if[null h;system "sleep 0.1"]]; + h + }; + +startworkers:{[kinds] `WORKERS set kinds startworker' NEXTPORT+til count kinds;`NEXTPORT set NEXTPORT+count kinds;}; + +stopworkers:{[] + {@[{neg[x](exit;0);neg[x][]};x;::];@[hclose;x;::]} each WORKERS; + `WORKERS set `int$(); + system "s 0"; + }; + +workersorted:{[h] exec msg from h"LOGS" where ctx=`sort,msg like "finished*"}; + +/ with -s negative, each of two workers sorts one table +fanoutok:{[] + startworkers`real`real; + system "s -2"; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + tr:hdbtable`trade; + r:chk `sorted`moved`bothworked`logged!( + tr[`time]~asc tr`time; + `quote`trade~partitiontables hdbdir[]; + all 1=count each workersorted each WORKERS; + loggedlike[`info;"sorting on worker sort*"]); + stopworkers[]; + r + }; + +/ a worker sorts to its own sortcsv, as legacy's did +workersortcsv:{[] + system "mkdir -p ",BASE,"/appconfig"; + (hsym `$BASE,"/appconfig/sym.csv") 0: ("tabname,att,column,sort";"default,,sym,1"); + startworkers`symsort`symsort; + system "s -2"; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + tr:hdbtable`trade; + r:chk `sortedbysym`nottimesorted!((tr`sym)~asc tr`sym;not (tr`time)~asc tr`time); + stopworkers[]; + r + }; + +/ without a negative -s, connected workers are not used +noworkers:{[] + startworkers`real`real; + freshwire config[]; + tail[savedir[];PDATE;`trade`quote]; + r:chk `main`idle!(loggedlike[`info;"sorting on main sort"];all 0=count each workersorted each WORKERS); + stopworkers[]; + r + }; + +/ a failing worker makes the tail throw before the move +workerfails:{[] + startworkers enlist`bare; + system "s -1"; + freshwire config[]; + r:chk `threw`notmoved!( + 0 e.g. 17 2 6, applied (.z.zd) while sorting/merging, then reset to 16 0 0 +# savedownmanipulation (optional, .q settings) -> table!function applied before each write +# upd (optional, .q settings) -> {[t;x]} the live upd, and the one the replay calls; default insert +# postreplay (optional, .q settings) -> {[hdbdir;pt]} called after the move, before the reload # subscribeto / subscribesyms omitted -> all tables, all syms # ignorelist omitted -> `heartbeat`logmsg (not written) # numtab (optional) -> per-table row thresholds; overrides numrows for those tables -# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (time asc) +# sortcsv (optional) -> di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else time asc ``` The schema comes from the **tickerplant** (via `subdetails`), not a local `database.q` — @@ -50,37 +74,40 @@ di.subscriptions defines the tables at root from what the TP returns. - **Startup**: connect (TP/HDB/RDB) via di.torq.servers; clear any stale working-partition data; install a **flushing replay `upd`** at root; block until a TP is up; subscribe + replay. The replay runs through that flushing `upd`, so it writes to disk past `numrows` and never holds a - whole day in RAM. After replay the root `upd` is swapped to a plain accumulate. + whole day in RAM. After replay the root `upd` is swapped to `insert`, or the configured `upd`. - **Intraday** (`savetodisk`, timer job every `settimer`s): flush any table over its threshold (or every table, if `immediate`) to the working partition — **create on first write, append after**, enumerating syms against the **HDB** sym file, then clear it in memory. If that - flushed at least one table, every connected `idbtypes` process is notified - (`` .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 + flushed at least one table, the partition is filled (`filldb`) and every connected `idbtypes` process is notified + (`` .idb.intradayreload[] ``, async) — 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 - 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 - date just **closed**; an `idb` entry in `reloadorder` instead gets - `` .idb.rollover[date+1] `` — the partition the wdb has moved **on** to — which records the new - day and remounts. Both idb legs go through the one `notifyidbs[func;params]`, as legacy TorQ. + remains, then runs `endofdaysort` — `saveandsort` in-process, `save` by an async + `.wdb.endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]` to each + connected sort process. With no sort process connected, `save` + logs an error and runs the tail here anyway rather than stranding the day's data in the working + directory. The tail's `idbreload` then initialises the next partition and sends + `` .idb.rollover[date+1] `` to every idb. The intraday `.idb.intradayreload` leg stays in the wdb + (`notifyidbs`), and after each flush that wrote something the partition is filled with `.Q.chk` + (`filldb`) first. ## What the wdb publishes for the idb -`init` publishes three root variables the idb reads at startup, the way legacy TorQ's +`init` publishes four root variables the idb reads at startup, the way legacy TorQ's `setparametersfromwdb` reads `.wdb.savedir` and friends: ```q set[`.wdb.savedir;.z.m.savedir]; set[`.wdb.hdbdir;.z.m.hdbdir]; set[`.wdb.currentpartition;.z.m.currentpartition]; +set[`.wdb.writedownmode;.z.m.writedownmode]; ``` -They are read with `` (each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition) ``, so the idb -is not configured with the two directories by hand — one source of truth, no pair to keep in step. -`endofday` republishes `currentpartition` after it advances; the other two are fixed for the life +They are read with `` (each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode) ``, +so the idb is not configured with the two directories by hand — one source of truth, no pair to keep in step. +The writedown mode decides whether the idb mounts `savedir` or `savedir/`. +`endofday` republishes `currentpartition` after it advances; the other three are fixed for the life of the process. ## RDB / WDB interaction @@ -112,20 +139,65 @@ enumerate dir == the write dir) don't fit the write path — the create-or-appen wdb-local; di.dbwrite is reused only for the EOD `sort`/`applyattr`. (A future di.dbwrite could grow an optional enum-dir param and absorb this.) -## Not included (future / other-process / deprecated) - -- **Sort / sortworker as separate processes** (`mode` = `save`/`sort`, `.z.pd` worker fan-out). - v1 is `saveandsort` in-process only. -- **Advanced writedown modes** (`partbyattr`/`partbyenum`/`partbyfirstchar`) and all of - `merge.q`. v1 is `default` writedown only. -- **`filldb`/`initmissingtables`** (legacy TorQ's other `notifyidbs`-adjacent EOD helpers - an - idb here just remounts its savedir wholesale on reload, see `di.torq.proc.idb`, so there is no - separate "fill" step to port). Per-flush notify itself **is** ported - see "Intraday" above. -- **Compression** (`.z.zd`). -- **Cross-date replay** (`fixpartition` — moving already-written temp data when the tp log date - differs from today). v1 assumes same-day start; it logs a warning and uses the log date, but - does not relocate data already written under the wrong partition. -- **Gateway** block/unblock is a no-op until a gateway is connected (di.torq.proc.gateway not built). +## Modes + +| `mode` | behaviour | +| --- | --- | +| `saveandsort` (default) | subscribe, save, and run the EOD sort in this process | +| `save` | subscribe and save; hand the EOD sort to a `sorttypes` process over IPC | +| `sort` | no tickerplant: wait for `.wdb.endofdaysort` from a `save`-mode wdb | + +Proctypes `sort` and `sortworker` run this module with framework settings +`di/torq/settings/sort.q` and `sortworker.q`, which set `mode:`sort`. That is legacy's +arrangement, where both loaded `wdb.q` with `-parentproctype wdb`. A sort process connects to the +hdb, rdb, idb, gateway, sortworker and wdb types. `endofdaysort`'s `dir`, `tablist` and +`hdbsettings` can be null, meaning this process's own `savedir`, the tables in the working +partition, and its own `hdbdir`/`compression`. + +If a `save`-mode wdb finds no sort process connected it logs an error and sorts the day itself, +as legacy does. + +## Sortworkers + +`settings/sortworker.q` empties every connection type, so a sortworker dials nothing and waits. +`init` defines `.z.pd` to return the connected `sortworkertypes` handles, and the per-table sort +or merge goes to the workers when some are connected **and** the process has a negative `-s`, +from the command line or the `workers` setting. Each worker is first sent the sym file to reload +and, for the `part` and `hybrid` merges, the partition sizes. The work is legacy's `peach` +lambdas, calling root names every mode publishes: `.sort.sorttab`, `.wdb.merge`, +`.wdb.setcompression`, `.wdb.reloadsymfile` and `.wdb.gc`. A worker sorts to its own `sortcsv`, +which defaults to the app's `sort.csv`. + +An error on a worker propagates out of the `peach` and stops the sort before the move, leaving the +working copy in place. As legacy, a new hdb partition is moved in with one rename; if the hdb +partition already exists and any table is in both, the whole move is aborted and logged, so nothing +is overwritten. + +## Writedown modes + +| `writedownmode` | intraday layout | end of day | +| --- | --- | --- | +| `default` | `//
/` | sort each table, move into the hdb | +| `partbyattr` | `//
//` | merge the segments into the hdb | +| `partbyenum` | `///
/` | merge the segments into the hdb | +| `partbyfirstchar` | `///
/` | sort each segment, then merge | + +The parted column comes from the `p` attribute in `sortcsv`; init reports an error if the +partitioned modes find no `default` row with one. Each segment's size is tracked in `di.merge` so +the merge can batch by `mergenumrows` / `mergenumbytes`. In `save` mode the sizes are sent to the +sort process with `.merge.syncpartsizes` before the hand-off. + +## Startup + +- The working partition is cleared, the log replayed with the `replaynumrows` threshold, and, if + the tickerplant log date differs from the current partition, the replayed data is moved to the + log's date (`fixpartition`). +- In `default` and `partbyenum` modes empty table schemas are written into the working partition + (`initmissingtables`), so an idb can mount it. `.wdb.initmissingtables` is published at root for a + sort process to call at end of day. + +## Not included (deprecated) + - **FinSpace/AWS** and the `endofperiod` STP stub — stripped. ## Module-namespace notes @@ -136,8 +208,18 @@ replay) lands in the module's private namespace. The replay `upd` is therefore r ## Testing -`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`) and the -export surface. The full subscribe → replay-to-disk → intraday-append → EOD sort+move → hdb +`test.csv` + `test.q` (k4unit) cover the dependency contract, the export surface and `mode` +validation. They also run the wdb end to end against a spawned process standing in for the +tickerplant: every writedown mode with every merge method, segment tracking, `initmissingtables`, +`tabsizes`, `savedownmanipulation`, `postreplay`, compression, `fixpartition`, the tickerplant retry +cycles, the `p`-attribute check, replay thresholds, merging on real sortworkers, `save` mode handing +off to a real sort process, and the `eodwaittime` reload handshake against a spawned hdb. +`testsort.q` covers sort mode against an unsorted working partition on disk: the sort and move, +table discovery, the `savedir` fallback, the no-overwrite rule, `permitreload` and `reloadorder`, +string settings, the `sortcsv` default, the sort process's connections, and fanning out to real +sortworker processes. + +The full subscribe → replay-to-disk → intraday-append → EOD sort+move → hdb reload + rdb `dropfirstnrows` flow is proven in the **TorqX-POC end-to-end** (`torqx.sh start tickerplant1 hdb feed1 rdb1 wdb1`, with `rdb1` in `reloadenabled` mode). diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 78a13d32..bb91182a 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -1,268 +1,709 @@ -/ di.torq.proc.wdb - the write database. Subscribes to a tickerplant (via di.subscriptions), replays -/ the day's tp log (flushing to disk as it goes so a full day never sits in RAM), then during -/ the day incrementally writes each in-memory table to a working partition when it exceeds a row -/ threshold. At end of day it flushes what remains, sorts each table on disk, MOVES the working -/ partition into the hdb, and triggers a reload of the hdb(s) and rdb(s). Ported from the -/ CRITICAL path of TorQ/code/processes/wdb.q (+ code/wdb/writedown.q). -/ --- -/ Scope (v1, classic saveandsort, in-process, `default` writedown mode - see the wdb.q -/ Chesterton's-Fence audit). NOT included (future/other-process): sort/sortworker as -/ separate processes (mode save/sort, .z.pd fan-out); advanced writedown modes -/ (partbyattr/partbyenum/partbyfirstchar) and all of merge.q; compression. REMOVED -/ (deprecated): finspace/aws and the .z.pd tempfix guards; the endofperiod STP stub. -/ --- -/ idb (di.torq.proc.idb) is notified through notifyidbs, as legacy TorQ: .idb.intradayreload after any -/ intraday flush that wrote something, and .idb.rollover with the new partition at EOD (opt in by -/ putting idb in reloadorder). No partition on the intraday leg - the idb mounts the savedir root. -/ --- -/ Why a working dir + move (not write-straight-to-hdb): the hdb partition only ever appears -/ complete AND sorted, after the move - a mid-day crash can't leave partial/unsorted data in -/ the hdb, and (later) an idb can read the working partition intraday. Enumeration is against -/ the HDB sym file (so the moved partition's enum indices already match hdb/sym), which is -/ also why di.dbwrite.savedown/appenddown (single enum==write dir) don't fit the write path; -/ we reuse di.dbwrite only for the EOD sort/attr. When a wdb is present the rdb must run -/ reloadenabled=1b (it then does NOT enumerate) so only ONE process writes hdb/sym. -/ --- -/ Module-namespace notes (see di.subscriptions): root tables are READ via bare `value t` -/ (bare reads fall through to root) but WRITTEN/cleared via @[`.;..] (a bare write from a -/ use-loaded module, or under -11! replay, lands in the module's private namespace). - -/ config coercion (values are symbols from .q settings or strings from .toml) +/ di.torq.proc.wdb - ported from TorQ's wdb.q +/ subscribes to the tickerplant and appends data to disk after the in-memory table exceeds a specified number of rows +/ at eod the on-disk data is sorted and attributes applied as specified in the sort.csv file +/ modes: saveandsort, save (the sort is handed to a sort process) and sort (proctypes sort and sortworker) + +/ config coercion: toml and command-line values arrive as strings, which must be parsed not cast assym:{[x] $[11h=abs type x;x;`$x]} aslist:{[x] $[0>type x;enlist x;x]} +tolong:{[x] + r:$[10h=abs type x;"J"$(),x;"j"$x]; + if[null r;'"di.torq.proc.wdb: could not parse \"",$[10h=abs type x;x;string x],"\" as a number"]; + r + } +tobool:{[x] $[-1h=type x;x;10h=abs type x;(lower (),x) in ("true";(),"1";(),"t";(),"y";"yes");`boolean$x]} +astimespan:{[x] $[10h=abs type x;"N"$(),x;-16h=type x;x;`timespan$1000000000*x]} -/ a token-list config (e.g. reloadorder): accept a space-separated string ("hdb rdb"), a -/ single symbol, a symbol list, or a list of strings -> always a symbol list. +/ a token-list config (e.g. reloadorder) as a symbol list astoklist:{[x] $[10h=type x;`$" " vs x;-11h=type x;enlist x;11h=type x;x;`$x]} -/ base dirs: CODE/CONFIG under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falls back to -/ TORQXAPPHOME when unset - fine for a sample app where they coincide). +/ 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` +/ resolves a possibly-relative dir setting to an absolute path string under base resolvedir:{[base;dir] dir:$[10h=abs type dir;dir;string dir]; dir:$[(0 updfn. -replayupd:{[t;x] updfn[t;x]; if[maxrows[t] < count value t;flushtable[0b;t]];} - -/ create-or-append one root table's rows into its working partition, then clear it in memory. -/ force=1b writes regardless of count (EOD flush); else only when over maxrows. Enumerates -/ against the HDB sym file (NOT the working dir) so the partition can later move into the hdb. -flushtable:{[force;t] - n:count value t; - if[not force; if[not maxrows[t] < n; :0b]]; - if[0=n; :0b]; - data:.Q.en[.z.m.hdbdir;0!value t]; / enumerate syms vs hdb/sym (persists it) - path:` sv (.Q.par[.z.m.savedir;.z.m.currentpartition;t];`); - $[count @[key;path;{`$()}]; - .[path;();,;data]; / append to existing splayed partition - path set data]; / create the partition - @[`.;t;0#]; / clear the in-memory table (root-safe) - .z.m.log[`info][`wdb;"flushed ",(string n)," rows of ",(string t)," to ",string path]; - 1b - } - -/ timer job: flush every table over threshold (or all of them when immediate), then notify any -/ connected idb(s) IF that actually changed something on disk (flushtable returns 1b per table -/ it wrote, 0b for one it skipped as empty/under-threshold) - an all-skipped tick stays silent, -/ so an idle wdb doesn't spam idb reloads. This is the per-flush leg from the header note above; -/ notifyidbs no-ops when no idb is connected, so this is safe to call unconditionally. +/ saves a table split by its extra partition once over its row limit +savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] + / check row count and save if maxrows exceeded + / forcesave will flush the data to disk irrespective of counts + if[forcesave or maxrows[tablename] < 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:getextrapartitiontype[tablename]; + if[(writedownmode in `partbyenum`partbyfirstchar) and 1 lmt; + .z.m.log[`info][`replayupd;"row limit (",(string lmt),") exceeded for ",(string t),". Table count is : ",(string rpc),". Flushing table to disk..."]; + savetab[.z.m.savedir;getpartition[];0b;t]]; + } + +/ will check on each upd to determine where data should be flushed to disk (if max row limit has been exceeded) +replayupd:{[t;x] .z.m.upd[t;x]; replaymaxrowcheck[t;replaymaxrows t];} + +/ saves each table over its row limit, then notifies the idbs savetodisk:{[] - changes:flushtable[.z.m.immediate;] each tablelist[]; - if[any changes;notifyidbs[`.idb.intradayreload;enlist()]]; + changes:savetab[.z.m.savedir;getpartition[];.z.m.immediate;] each tablelist[]; + / we have to let the idbs know of the changes in the wdbhdb. using filldb[] to make sure it is a db with all the tables + if[any[changes] and .z.m.writedownmode in `partbyenum`partbyfirstchar`default; + filldb getpartition[]; + notifyidbs[`.idb.intradayreload;enlist()]]; } -/ remove any pre-existing working data for the current partition before replay (replay rebuilds -/ it from the log, so stale data from a previous run would be double-counted). Scoped to the -/ wdb's own working partition dir. +/ if there is data in the wdb directory for the partition remove it before replay clearwdbdata:{[] - pdir:.Q.par[.z.m.savedir;.z.m.currentpartition;`]; - if[count key pdir; - d:1_string pdir; - system "rm -rf ",d; - .z.m.log[`info][`wdb;"cleared existing wdb working data at ",d]]; - } - -/ EOD sort: sort + apply attributes on the working partition for table t (di.dbwrite, driven by -/ the sort config / its time-asc default). In-process, so the sym file this process enumerated -/ against is already current - no reloadsymfile needed (that is a separate-sort-worker concern). -sortpart:{[pt;t] - dir:` sv (.Q.par[.z.m.savedir;pt;t];`); - if[count key dir;(.z.m.dbw`sort)[t;dir]]; - } - -/ move the working partition into the hdb, one table dir at a time. A table already present in the -/ hdb partition is skipped (never overwrite - that would corrupt the hdb), mirroring TorQ. -movetohdb:{[pt] - src:.Q.par[.z.m.savedir;pt;`]; - if[not count key src;.z.m.log[`warn][`wdb;"no working partition to move for ",string pt];:()]; - dst:.Q.par[.z.m.hdbdir;pt;`]; - srcs:1_string src; dsts:1_string dst; - system "mkdir -p ",dsts; - {[srcs;dsts;t] - s:srcs,"/",string t; d:dsts,"/",string t; - $[count key hsym `$d; - .z.m.log[`error][`wdb;"table ",(string t)," already in hdb partition ",dsts," - skipped to avoid corruption"]; - [system "mv ",s," ",d;.z.m.log[`info][`wdb;"moved ",(string t)," -> ",d]]]; - }[srcs;dsts;] each key src; - if[0=count key src;system "rm -rf ",srcs]; - } - -/ inform the gateway(s) that a reload is starting/ending. POC has no gateway (and di.torq.proc.gateway -/ is not built yet), so this is a no-op when none is connected - the hook is kept for when it -/ lands. TorQ's protocol is (`reloadstart;`) / (`reloadend;`) to block/unblock in-flight queries. -informgateway:{[msg] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.gatewaytypes; - if[0=count h;:()]; - {[wh;msg] @[neg wh;(`.gw.reload;msg);{[e] .z.m.log[`error][`wdb;"gateway inform failed: ",e]}]}[;msg] each h; + $[not ()~key wdbpart:.Q.par[.z.m.savedir;getpartition[];`]; + [.z.m.log[`info][`deletewdbdata;"removing wdb data (",(delstrg:1_string wdbpart),") prior to log replay"]; + @[.z.m.os`deldir;delstrg;{[e] .z.m.log[`error][`deletewdbdata;"Failed to delete existing wdb data. Error was : ",e];'e}]; + .z.m.log[`info][`deletewdbdata;"finished removing wdb data prior to log replay"]]; + .z.m.log[`info][`deletewdbdata;"no directory found at ",1_string wdbpart]]; } -/ tell every hdb of these types to reload (pick up the just-moved partition). `pt` (the -/ partition being reloaded) is unused - kept so the doreload dispatch below can call every -/ reload*[pt] uniformly. -reloadhdbs:{[pt] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.hdbtypes; - {[wh] @[wh;".hdb.reload[]";{[e] .z.m.log[`error][`wdb;"hdb reload failed: ",e]}]} each h; +/ function to rectify data written to wrong partition +fixpartition:{[tplogdate] + / check if the tp logdate matches current date + if[not tplogdate~orig:.z.m.currentpartition; + .z.m.log[`info][`fixpartition;"Current partition date does not match the ticker plant log date"]; + / set the current partition date to the log date + .z.m.currentpartition:tplogdate; + / move the data that has been written to correct partition + pth1:1_string .Q.par[.z.m.savedir;orig;`]; + pth2:1_string .Q.par[.z.m.savedir;tplogdate;`]; + if[count key hsym `$pth1; + / delete any data in the current partition directory + clearwdbdata[]; + .z.m.log[`info][`fixpartition;"Moving data from partition ",pth1," to partition ",pth2]; + .[.z.m.os`mv;(pth1;pth2);{[p1;p2;e] .z.m.log[`error][`fixpartition;"Failed to move data from wdb partition ",p1," to wdb partition ",p2," : ",e]}[pth1;pth2]]]]; } -/ tell every rdb of these types to reload[pt] (drop the prior day it was holding in memory). -/ async - the rdb's root reload[pt] does the dropfirstnrows (see di.torq.proc.rdb, reloadenabled=1b). -reloadrdbs:{[pt] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.rdbtypes; - {[wh;pt] @[neg wh;(`reload;pt);{[e] .z.m.log[`error][`wdb;"rdb reload send failed: ",e]}]}[;pt] each h; +/ fills missing tables in the partition so it is usable intraday +filldb:{[pt] .Q.chk .Q.par[.z.m.savedir;pt;`];} + +/ initialises table t in db with its schema in part +inittable:{[t;pt] + tdir:` sv $[.z.m.writedownmode in `partbyenum`partbyfirstchar;.Q.par[.Q.dd[.z.m.savedir;pt];0;t];.Q.par[.z.m.savedir;pt;t]],`; + if[()~key tdir;tdir set .Q.en[.z.m.hdbdir;0#value t]]; } -/ one path for both idb notifications, as legacy's notifyidbs. Async: the intraday leg fires after -/ every flush, so it must not block; the trap therefore only sees send failures. -notifyidbs:{[func;params] - h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.idbtypes; - if[0=count h;:()]; - .z.m.log[`info][`notifyidbs;"notifying ",(string count h)," idb(s) with ",string func]; - {[wh;func;params] @[neg wh;enlist[func],params;{[e] .z.m.log[`error][`wdb;"idb notify send failed: ",e]}]}[;func;params] each h; - } - -/ reload downstream in the configured order (default `hdb`rdb: hdb first so it sees the new -/ partition, then rdb so it drops the prior day), bracketed by the gateway block/unblock. -/ `idb` is a valid reloadorder entry too (opt in by adding it, e.g. "hdb rdb idb") but is not -/ in the default order - existing apps that don't run an idb see no behaviour change here (the -/ separate, always-on intraday notify leg in savetodisk is unaffected by reloadorder either way). -/ pt is the day just closed - the hdb and rdb want that; the idb wants the one now being written +/ makes sure partition 0/currentpartition has all the tables for partbyenum/partbyfirstchar/default +initmissingtables:{[pt] + .z.m.log[`info][`fixpartition;"Adding missing tables(empty) to partition ",string pt]; + inittable[;pt] each tablelist[]; + filldb pt; + } + +/ eod - flush remaining data to disk +endofdaysave:{[dir;pt] + / save remaining table rows to disk + .z.m.log[`info][`save;"saving the ",(", " sv string tl:tablelist[],())," table(s) to disk"]; + savetab[dir;pt;1b;] each tl; + .z.m.log[`info][`savefinish;"finished saving data to disk"]; + } + +/ add entries to table of callbacks. if timeout has expired or d now contains all expected rows then it releases each waiting process +handler:{[x] + .z.m.reloadsummary[.z.w]:x; + .z.m.log[`info][`reloadproc;"the ",(string x 0)," process ",string x 2]; + if[(.z.p>.z.m.timeouttime) or count[.z.m.reloadsummary]=.z.m.countreload; + .z.m.log[`info][`handler;"releasing processes"]; + .z.m.log[`info][`reload;(string count select from .z.m.reloadsummary where status)," out of ",(string count .z.m.reloadsummary)," processes successfully reloaded"]; + flushend[]; + .z.m.reloadsummary:0#.z.m.reloadsummary]; + } + +/ evaluate contents of d dictionary asynchronously; notify the gateway that we are done +flushend:{[] + if[not .z.m.reloadcomplete; + if[.z.m.eodwaittime>0;@[{neg[x]"";neg[x][]};;()] each key .z.m.reloadsummary]; + informgateway`reloadend; + .z.m.log[`info][`sort;"end of day sort is now complete"]; + .z.m.reloadcomplete:1b]; + / run a garbage collection (if enabled) + if[.z.m.gc;.Q.gc[]]; + } + +/ triggers the reload of each reloadorder type in turn doreload:{[pt] - informgateway[`reloadstart]; - {[pt;ptype] - $[ptype in .z.m.hdbtypes;reloadhdbs[pt]; - ptype in .z.m.rdbtypes;reloadrdbs[pt]; - ptype in .z.m.idbtypes;notifyidbs[`.idb.rollover;pt+1]; - .z.m.log[`warn][`wdb;"reloadorder entry ",(string ptype)," is neither an hdb, rdb, nor idb type - skipped"]] - }[pt;] each .z.m.reloadorder; - 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 -/ reload downstream. Advance the partition for the new day. + .z.m.reloadcomplete:0b; + / inform gateway of reload start + informgateway`reloadstart; + ro:.z.m.reloadorder inter knowntypes[]; + .z.m.countreload:sum {count (.z.m.svc`getservers) x} each ro where not (::)~/:reloadexpr each ro; + .z.m.timeouttime:.z.p+.z.m.eodwaittime; + getprocs[;pt] each ro; + $[.z.m.eodwaittime>0; + [@[.z.m.timer`deletejobs;`sortflushend;{}]; + (.z.m.timer`addjob)[`sortflushend;flushend;();1;1h;`startattime`maxruns!(.z.m.timeouttime;1)]]; + flushend[]]; + } + +/ set .z.zd to control how data gets compressed +setcompression:{[compression] + if[3=count compression; + .z.m.log[`info][`compression;$[compression~16 0 0;"resetting";"setting"]," compression level to (",(";" sv string compression),")"]; + @[`.z;`zd;:;compression]]; + } + +resetcompression:{[] setcompression 16 0 0} + +/ check if the hdb directory contains current partition +/ if yes check if partition is empty and if it is not see if any of the tables exist in both the +/ temporary partition and the hdb partition. If there is a clash abort operation otherwise copy +/ each table to the hdb partition +movetohdb:{[dw;hw;pt] + $[not (`$string pt) in key hsym `$(neg count string pt)_hw; + .[.z.m.os`mv;(dw;hw);{[dw;hw;e] .z.m.log[`error][`mvtohdb;"Failed to move data from wdb ",dw," to hdb directory ",hw," : ",e]}[dw;hw]]; + not any a[dw] in (a:{key hsym `$x}) hw; + [{[y;x] + $[not (b:`$last "/" vs x) in key y; + [.[.z.m.os`mv;(x;y);{[x;y;e] .z.m.log[`error][`mvtohdb;"Table ",(string x)," has failed to copy to ",(string y)," with error: ",e]}[b;y]]; + .z.m.log[`info][`mvtohdb;"Table ",(string b)," has been successfully moved to ",string y]]; + .z.m.log[`error][`mvtohdb;"Table ",(string b)," was skipped because it already exists in ",string y]]; + }[hsym `$hw]'[dw,/:"/",/:string key hsym `$dw]; + if[0=count key hsym `$dw;@[.z.m.os`deldir;dw;{[x;y] .z.m.log[`error][`mvtohdb;"Failed to delete folder ",x," with error: ",y]}[dw]]]]; + .z.m.log[`error][`mvtohdb;raze "Table(s) ",string[(key hsym `$hw) inter key hsym `$dw]," is present in both location. Operation will be aborted to avoid corrupting the hdb"]] + } + +/ root sym is set with @[`.;...]: a bare load from a use-loaded module lands in its private namespace +reloadsymfile:{[symfilepath] + if[not count key symfilepath; + .z.m.log[`warn][`reloadsymfile;"no sym file at ",(1_string symfilepath)," - nothing to load"]; + :()]; + .z.m.log[`info][`reloadsymfile;"reloading the sym file from ",1_string symfilepath]; + @[{@[`.;`sym;:;get x]};symfilepath;{[e] .z.m.log[`error][`sort;"failed to reload sym file: ",e]}] + } + +/ legacy's .sort.sorttab: x is (table;dir) +sorttab:{[x] (.z.m.dbw`sort)[x 0;x 1]} + +/ as legacy, workers are only used when this process was started with a negative -s +useworkers:{[] (0system"s"} + +/ sends each worker the sym file to reload, async then flushed +reloadworkersym:{[hdbsettings] {(neg x)(`.wdb.reloadsymfile;y);(neg x)(::)}[;.Q.dd[hdbsettings`hdbdir;`sym]] each .z.pd[]} + +/ sorts each (table;dir), on the sortworkers when there are any +sortall:{[tnds;hdbsettings] + $[useworkers[]; + [.z.m.log[`info][`sort;"sorting on worker sort ",string .z.p]; + reloadworkersym hdbsettings; + / sort the table and garbage collect (if enabled) + {[x;compression] .wdb.setcompression compression;.sort.sorttab x;if[.wdb.gc;.Q.gc[]]}[;hdbsettings`compression] peach tnds]; + [.z.m.log[`info][`sort;"sorting on main sort"]; + reloadsymfile .Q.dd[hdbsettings`hdbdir;`sym]; + {[x] sorttab x;if[.z.m.gc;.Q.gc[]]} each tnds]]; + } + +/ sorts the working partition, moves it into the hdb and reloads +endofdaysortdate:{[dir;pt;tablist;hdbsettings] + / sort permitted tables in database + .z.m.log[`info][`sort;"starting to sort data"]; + sortall[tablist,'.Q.par[dir;pt;] each tablist;hdbsettings]; + .z.m.log[`info][`sort;"finished sorting data"]; + / move data into hdb + .z.m.log[`info][`mvtohdb;"Moving partition from the temp wdb ",(dw:(.z.m.os`topath) -1_string .Q.par[dir;pt;`])," directory to the hdb directory ",hw:(.z.m.os`topath) -1_string .Q.par[hdbsettings`hdbdir;pt;`]]; + .z.m.log[`info][`mvtohdb;"Attempting to move ",(", " sv string key hsym `$dw)," from ",dw," to ",hw]; + .[movetohdb;(dw;hw;pt);{[e] .z.m.log[`error][`mvtohdb;"Function movetohdb failed with error: ",e]}]; + / call the posteod function + postreplay[hdbsettings`hdbdir;pt]; + if[.z.m.permitreload;doreload pt]; + } + +/ post eod function, invoked after all the tables have been written down +postreplay:{[hdbdir;pt] + @[.z.m.posteod .;(hdbdir;pt);{[e] .z.m.log[`error][`postreplay;"postreplay failed: ",e]}]; + } + +/ the parted column(s) for a table from the sort config, falling back to the default row +getextrapartitiontype:{[tablename] + params:$[(::)~c:(.z.m.dbw`getconfig)[];();c]; + if[count tabparts:distinct exec column from params where tabname=tablename,sort,att=`p; + .z.m.log[`info][`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; + :tabparts]; + if[count defaultparts:distinct exec column from params where tabname=`default,sort,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"]; + `symbol$() + } + +/ merges one table's segments into the hdb partition +merge:{[dir;pt;tableinfo;mergelimits;hdbsettings;mergemethod;writedownmode] + setcompression hdbsettings`compression; + / get tablename + tabname:tableinfo 0; + ep:getextrapartitiontype tabname; + / get list of partition directories for specified table - partbyenum & partbyfirstchar use different folder structures vs partbyattr/default + partdirs:$[writedownmode in `partbyenum`partbyfirstchar; + p where 0//
+/ this function deletes
folder or the whole if it only has one element +removetablefromenumdir:{[partdir] + enumdir:` sv -1_` vs partdir; + (.z.m.os`deldir) $[1=count key enumdir;enumdir;partdir]; + } + +/ merges each table into the hdb, on the sortworkers when there are any, then reloads +endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode] + / merge data from partitions + ti:flip (key tablist;value tablist); + $[useworkers[]; + [.z.m.log[`info][`merge;"merging on worker"]; + reloadworkersym hdbsettings; + / upsert .merge.partsize data to sort workers, only needed for part and hybrid method + if[.z.m.mergemode in `hybrid`part; + {(neg x)(`.merge.syncpartsizes;y);(neg x)(::)}[;(.z.m.mrg`getpartsizes)[]] each .z.pd[]]; + {[dir;pt;ml;hs;mm;wm;x] .wdb.merge[dir;pt;x;ml;hs;mm;wm]}[dir;pt;mergelimits;hdbsettings;mergemethod;writedownmode] peach ti; + / clear out in memory table, .merge.partsizes, and call sort worker processes to do the same + .z.m.log[`info][`eod;"Delete from partsizes"]; + (.z.m.mrg`clearpartsizes)[]; + {(neg x)({[x] .merge.clearpartsizes[];if[.wdb.gc;.Q.gc[]]};`);(neg x)(::)} each .z.pd[]]; + [.z.m.log[`info][`merge;"merging on main"]; + reloadsymfile .Q.dd[hdbsettings`hdbdir;`sym]; + merge[dir;pt;;mergelimits;hdbsettings;mergemethod;writedownmode] each ti; + .z.m.log[`info][`eod;"Delete from partsizes"]; + (.z.m.mrg`clearpartsizes)[]]]; + / if path exists, delete it + if[count key p:.Q.par[dir;pt;`]; + .z.m.log[`info][`merge;"attempting to delete temp storage directory"]; + @[.z.m.os`deldir;p;{[p;e] .z.m.log[`info][`eod;"could not delete directory: ",(1_string p)," - maybe something(IDB?) gets hold of it."]}[p]]]; + / call the posteod function + postreplay[hdbsettings`hdbdir;pt]; + $[.z.m.permitreload;doreload pt;if[.z.m.gc;.Q.gc[]]]; + } + +/ end of day sort and merge only used by writedown mode partbyfirstchar, requiring sort pre-merge +endofdaysortandmerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode] + / sort permitted tables in database + .z.m.log[`info][`sort;"starting to sort data"]; + tnds:raze {y,/:.Q.dd[x;] each key[x],\:y}[.Q.dd[dir;pt]] each key tablist; + tnds:tnds where tnds[;1] in exec ptdir from (.z.m.mrg`getpartsizes)[]; + if[count tnds;sortall[tnds;hdbsettings]]; + .z.m.log[`info][`sort;"finished sorting data"]; + endofdaymerge[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode]; + } + +/ end of day sort [depends on writedown mode]; dir, tablist and hdbsettings may be null to use this process's own config +endofdaysort:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] + sd:$[0=count s:$[10h=abs type dir;(),dir;string dir];.z.m.savedirs;resolvedir[datahome[];s]]; + dir:hsym `$sd; + if[not 99h=type hdbsettings;hdbsettings:()!()]; + hdbsettings:.z.m.hdbsettings,hdbsettings; + hdbsettings[`hdbdir]:hsym `$resolvedir[datahome[];hdbsettings`hdbdir]; + if[not 99h=type tablist; + t:(),tablist; + t:$[(0=count t) or t~enlist`;key .Q.par[dir;pt;`];t]; + tablist:t!(count t)#enlist ()]; + writedownmode:$[null writedownmode;`default;assym writedownmode]; + mergemethod:$[null mergemethod;.z.m.mergemode;assym mergemethod]; + .z.m.log[`info][`endofdaysort;"starting for partition ",(string pt)," in ",sd,": ",$[count tablist;", " sv string key tablist;"no tables"]]; + / set compression level (.z.zd) + setcompression hdbsettings`compression; + $[writedownmode in .z.m.partwritemodes; + $[writedownmode~`partbyfirstchar;endofdaysortandmerge;endofdaymerge][dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode]; + endofdaysortdate[dir;pt;key tablist;hdbsettings]]; + / reset compression level (.z.zd) + resetcompression[]; + / run steps to rollover idb + idbreload[pt+1;writedownmode]; + .z.m.log[`info][`endofdaysort;"complete for partition ",string pt]; + } + +/ the call each reloadorder type makes on the far side +reloadexpr:{[ptype] + $[ptype in .z.m.hdbtypes;{[d] .hdb.reload[]}; + ptype in .z.m.rdbtypes;{[d] `. [`reload] d}; + ptype in .z.m.idbtypes;{[d] .idb.intradayreload[]}; + (::)] + } + +/ function to send reload message to rdbs/hdbs/idbs +reloadproc:{[h;d;ptype;f] + / async call back function executed when eodwaittime>0 + sendfunc:{[x;y;ptype] @[neg y;x;{[ptype;e] .z.m.log[`error][`reloadproc;"failed to reload the ",string ptype]}[ptype]]}; + / reload function sent to processes by sendfunc; runs there, so it calls back .wdb.handler with the outcome + reloadfunc:{[f;d;ptype] r:@[{(1b;x y)}[f];d;{(0b;x)}]; + (neg .z.w)(`.wdb.handler;(ptype;first r;$[first r;`$"reloaded successfully";`$"reload failed with error ",last r]));(neg .z.w)[]}; + / reload function to be executed if eodwaitime = 0 - sync message processes to reload and log if reload was successful or failed + syncreloadfunc:{[h;f;d;ptype] r:@[h;({[f;d] (1b;f d)};f;d);{[ptype;e] .z.m.log[`error][`reloadproc;"failed to reload the ",(string ptype),". The error was : ",e];(0b;e)}[ptype]]; + .z.m.log[`info][`reloadproc;"the ",(string ptype)," ",$[first r;"successfully reloaded";"failed to reload"]]}; + .z.m.log[`info][`reloadproc;"sending reload call to ",string ptype]; + $[.z.m.eodwaittime>0;sendfunc[(reloadfunc;f;d;ptype);h;ptype];syncreloadfunc[h;f;d;ptype]]; + } + +/ function to discover rdbs/hdbs and attempt to reconnect +getprocs:{[x;y] + if[(::)~f:reloadexpr x; + .z.m.log[`warn][`doreload;"reloadorder entry ",(string x)," is neither an hdb, rdb, nor idb type - skipped"]; + :()]; + a:exec w from (.z.m.svc`getservers) x; + / exit if no valid handle + if[0=count a;.z.m.log[`error][`connection;"no connection to the ",(string x)," could be established... failed to reload ",string x];:()]; + .z.m.log[`info][`connection;"connection to the ",(string x)," has been located"]; + / send message along each handle + reloadproc[;y;x;f] each a; + } + +/ the proctypes in the phone book, or the reloadorder when the servers dep cannot list them +knowntypes:{[] $[`getallservers in key .z.m.svc;exec distinct proctype from (.z.m.svc`getallservers)[];.z.m.reloadorder]} + +/ function to send messages to gateway +informgateway:{[msg] + .z.m.log[`info][`informgateway;"sending message to gateway(s)"]; + if[0=count h:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.gatewaytypes; + :.z.m.log[`error][`informgateway;"can't connect to the gateway - no gateway detected"]]; + {[wh;msg] @[neg wh;(`.gw.reload;msg);{[e] .z.m.log[`error][`informgateway;"unable to run command on gateway: ",e]}]}[;msg] each h; + .z.m.log[`info][`informgateway;"the message - ",(.Q.s1 msg)," was sent to the gateways"]; + } + +/ function to call that will cause sort & reload process to sort data and reload rdb and hdbs; async so the wdb can take the new day +informsortandreload:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] + .z.m.log[`info][`informsortandreload;"attempting to contact sort process to initiate data ",$[writedownmode~`default;"sort";"merge"]]; + if[0=count h:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sorttypes; + .z.m.log[`error][`informsortandreload;"can't connect to the sortandreload - no sortandreload process detected"]; + / try to run the sort locally + :endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]]; + / for part and hybrid method sort procs need access to partsizes table data + if[mergemethod in `hybrid`part; + {[p;h] neg[h](`.merge.syncpartsizes;p);neg[h][]}[(.z.m.mrg`getpartsizes)[]] each h]; + msg:(`.wdb.endofdaysort;dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod); + {[msg;wh] @[{[msg;wh] neg[wh] msg;neg[wh][]}[msg];wh;{[e] .z.m.log[`error][`informsortandreload;"unable to run command on sort and reload process: ",e]}]}[msg] each h; + } + +/ send an intraday reload message to idbs +notifyidbs:{[func;params] + ws:raze {exec w from x} each (.z.m.svc`getservers) each .z.m.idbtypes; + .z.m.log[`info][`reload;"found ",(string count ws)," idb(s) to trigger reload with function ",string func]; + / send async message along each handle + {[w;func;params] @[neg w;enlist[func],params;{[e] .z.m.log[`error][`notifyidbs;"idb notify send failed: ",e]}]}[;func;params] each ws; + } + +/ triggers idb reload steps; a sort process asks the wdb(s) to run initmissingtables +idbreload:{[pt;writedownmode] + .z.m.log[`info][`idb;"starting idb reload"]; + if[writedownmode in `partbyenum`default`partbyfirstchar; + .z.m.log[`info][`eod;"initialising wdbhdb for partition: ",string pt]; + $[.z.m.mode~`sort; + {[pt;w] @[w;(`.wdb.initmissingtables;pt);{[e] .z.m.log[`error][`idb;"initmissingtables failed on the wdb: ",e]}]}[pt] each raze {exec w from x} each (.z.m.svc`getservers) each .z.m.wdbtypes; + @[initmissingtables;pt;{[e] .z.m.log[`error][`idb;"initmissingtables failed: ",e]}]]; + .z.m.log[`info][`eod;"notifying idbs for newly created partition"]; + notifyidbs[`.idb.rollover;enlist pt]]; + .z.m.log[`info][`idb;"idb reload complete"]; + } + +/ flushes, sorts or hands off the partition, and advances to the next endofday:{[pt] - .z.m.log[`info][`wdb;"end of day for partition ",string pt]; - flushtable[1b;] each tablelist[]; / flush all remaining rows - st:tablelist[]; - sortpart[pt] each st; - movetohdb[pt]; - doreload[pt]; + .z.m.log[`info][`eod;"end of day message received - ",string pt]; + / set what type of merge method to be used + mergemethod:.z.m.mergemode; + / create a dictionary of tables and merge limits, byte or row count limit depending on settings + .z.m.log[`info][`merge;"merging partitions by ",$[.z.m.mergebybytelimit;"byte estimate";"row count"]," limit"]; + tl:tablelist[],(); + mergelimits:tl!$[.z.m.mergebybytelimit;(count tl)#.z.m.mergenumbytes;mergemaxrows each tl],(); + tablist:tl!{0#value x} each tl; + / if save mode is enabled then flush all data to disk + if[.z.m.saveenabled; + endofdaysave[.z.m.savedir;pt]; + / if sort mode enable call endofdaysort within the process, else inform the sort and reload process to do it + $[.z.m.sortenabled;endofdaysort;informsortandreload] . (.z.m.savedirs;pt;tablist;.z.m.writedownmode;mergelimits;.z.m.hdbsettings;mergemethod)]; + .z.m.log[`info][`eod;"deleting data from ",$[r:.z.m.writedownmode in .z.m.partwritemodes;"partsizes";"tabsizes"]]; + $[r;(.z.m.mrg`clearpartsizes)[];.z.m.tabsizes:0#.z.m.tabsizes]; .z.m.currentpartition:pt+1; set[`.wdb.currentpartition;.z.m.currentpartition]; - .z.m.log[`info][`wdb;"end of day complete, wrote+moved: ",(", " sv string st)]; + .z.m.log[`info][`eod;"end of day is now complete"]; } -init:{[config;deps] - if[not `log in key deps;'"di.torq.proc.wdb: log dependency is required - see di.util.log"]; - if[not `timer in key deps;'"di.torq.proc.wdb: timer dependency is required - see di.timer"]; - if[not `servers in key deps;'"di.torq.proc.wdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; - .z.m.log:deps`log; - .z.m.timer:deps`timer; +/ checks sort.csv sets the p attribute every partitioned writedown mode needs +checksortparams:{[] + if[not .z.m.writedownmode in .z.m.partwritemodes;:()]; + params:$[(::)~c:(.z.m.dbw`getconfig)[];();c]; + / check that default table is defined + $[count exec distinct tabname from params where tabname=`default,att=`p,sort; + .z.m.log[`info][`init;"default table defined in sort.csv and with at least one `p attribute and sort=1b"]; + .z.m.log[`error][`init;"default table not defined in sort.csv with at least one `p attribute and sort=1b"]]; + / check for `p attributes + $[count notparted:distinct params[`tabname] except distinct exec tabname from params where att in `p; + .z.m.log[`error][`init;"parted attribute p not set at least once in sort.csv for table(s): ",", " sv string notparted]; + .z.m.log[`info][`init;"parted attribute p set at least once for each table in sort.csv"]]; + } + +/ reads the sort.csv, as legacy the app's sort.csv when no sortcsv is set +initdbwrite:{[config;deps] + .z.m.dbw:use`di.dbwrite; + (.z.m.dbw`init)[enlist[`log]!enlist deps`log]; + f:$[`sortcsv in key config;resolvedir[apphome[];config`sortcsv];getenv[`TORQXAPPCONFIG],"/sort.csv"]; + if[(`sortcsv in key config) or count key hsym `$f;(.z.m.dbw`readcsv) f]; + } + +/ reads every setting from config into the module +setconfig:{[config] .z.m.tptypes:$[`tickerplanttypes in key config;aslist assym config`tickerplanttypes;enlist`tickerplant]; .z.m.hdbtypes:$[`hdbtypes in key config;aslist assym config`hdbtypes;enlist`hdb]; .z.m.rdbtypes:$[`rdbtypes in key config;aslist assym config`rdbtypes;enlist`rdb]; .z.m.idbtypes:$[`idbtypes in key config;aslist assym config`idbtypes;enlist`idb]; .z.m.gatewaytypes:$[`gatewaytypes in key config;aslist assym config`gatewaytypes;enlist`gateway]; - .z.m.reloadorder:$[`reloadorder in key config;astoklist config`reloadorder;`hdb`rdb]; + .z.m.sorttypes:$[`sorttypes in key config;aslist assym config`sorttypes;enlist`sort]; + .z.m.sortworkertypes:$[`sortworkertypes in key config;aslist assym config`sortworkertypes;enlist`sortworker]; + .z.m.wdbtypes:$[`wdbtypes in key config;aslist assym config`wdbtypes;enlist`wdb]; .z.m.ignorelist:$[`ignorelist in key config;aslist assym config`ignorelist;`heartbeat`logmsg]; .z.m.hdbdir:hsym `$$[`hdbdir in key config;resolvedir[datahome[];config`hdbdir];datahome[],"/hdb"]; .z.m.savedir:hsym `$$[`savedir in key config;resolvedir[datahome[];config`savedir];datahome[],"/wdb"]; - .z.m.numrows:$[`numrows in key config;"j"$config`numrows;100000]; + .z.m.savedirs:1_string .z.m.savedir; + .z.m.mode:$[`mode in key config;assym config`mode;`saveandsort]; + if[not .z.m.mode in `saveandsort`save`sort;'"di.torq.proc.wdb: mode must be saveandsort, save or sort, got ",string .z.m.mode]; + .z.m.saveenabled:.z.m.mode in `save`saveandsort; + .z.m.sortenabled:.z.m.mode in `saveandsort`sort; + .z.m.writedownmode:$[`writedownmode in key config;assym config`writedownmode;`default]; + if[not .z.m.writedownmode in `default,.z.m.partwritemodes; + '"di.torq.proc.wdb: writedownmode must be default, partbyattr, partbyenum or partbyfirstchar, got ",string .z.m.writedownmode]; + .z.m.mergemode:$[`mergemode in key config;assym config`mergemode;`part]; + if[not .z.m.mergemode in `part`col`hybrid;'"di.torq.proc.wdb: mergemode must be part, col or hybrid, got ",string .z.m.mergemode]; + .z.m.mergebybytelimit:$[`mergebybytelimit in key config;tobool config`mergebybytelimit;0b]; + .z.m.mergenumbytes:$[`mergenumbytes in key config;tolong config`mergenumbytes;500000000]; + .z.m.mergenumrows:$[`mergenumrows in key config;tolong config`mergenumrows;100000]; + .z.m.mergenumtab:$[`mergenumtab in key config;config`mergenumtab;`quote`trade!10000 50000]; + .z.m.numrows:$[`numrows in key config;tolong config`numrows;100000]; .z.m.numtab:$[`numtab in key config;config`numtab;(`symbol$())!`long$()]; - .z.m.immediate:$[`immediate in key config;`boolean$config`immediate;0b]; - settimer:$[`settimer in key config;"j"$config`settimer;10]; - subscribeto:$[`subscribeto in key config;assym config`subscribeto;`]; - subscribesyms:$[`subscribesyms in key config;assym config`subscribesyms;`]; - replaylog:$[`replaylog in key config;`boolean$config`replaylog;1b]; - timeout:$[`tpwaittimeout in key config;"j"$config`tpwaittimeout;30000]; - - / v1 uses today's date as the partition; the tp log date is checked against it after - / subscribe. Cross-date replay (log date != today, needing the written working data moved to - / the right partition - TorQ's fixpartition) is deferred; the POC runs same-day. - .z.m.currentpartition:.z.D; - system "mkdir -p ",1_string .z.m.savedir; - clearwdbdata[]; + .z.m.replaynumrows:$[`replaynumrows in key config;tolong config`replaynumrows;.z.m.numrows]; + .z.m.replaynumtab:$[`replaynumtab in key config;config`replaynumtab;.z.m.numtab]; + .z.m.immediate:$[`immediate in key config;tobool config`immediate;0b]; + .z.m.gc:$[`gc in key config;tobool config`gc;1b]; + .z.m.partitiontype:$[`partitiontype in key config;assym config`partitiontype;`date]; + .z.m.savedownmanipulation:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + .z.m.upd:$[`upd in key config;config`upd;insert]; + .z.m.posteod:$[`postreplay in key config;config`postreplay;{[d;p]}]; + .z.m.reloadorder:$[`reloadorder in key config;astoklist config`reloadorder;`hdb`rdb`idb]; + .z.m.permitreload:$[`permitreload in key config;tobool config`permitreload;1b]; + .z.m.eodwaittime:$[`eodwaittime in key config;astimespan config`eodwaittime;0D00:00:10]; + .z.m.hdbsettings:`compression`hdbdir!($[`compression in key config;config`compression;()];.z.m.hdbdir); + .z.m.tabsizes:([tablename:`symbol$()] rowcount:`long$(); bytes:`long$()); + .z.m.settimer:$[`settimer in key config;tolong config`settimer;10]; + .z.m.subscribeto:$[`subscribeto in key config;assym config`subscribeto;`]; + .z.m.subscribesyms:$[`subscribesyms in key config;assym config`subscribesyms;`]; + .z.m.replaylog:$[`replaylog in key config;tobool config`replaylog;1b]; + .z.m.tpwaittimeout:$[`tpwaittimeout in key config;tolong config`tpwaittimeout;30000]; + .z.m.currentpartition:0N; + } - / di.dbwrite for the EOD sort/attr (optional sort.csv config). Takes the injected binary - / (ctx;msg) log dep directly - no adapter, since di.dbwrite now uses the same contract. - .z.m.dbw:use`di.dbwrite; - (.z.m.dbw`init)[enlist[`log]!enlist deps`log]; - if[`sortcsv in key config;(.z.m.dbw`readcsv)[resolvedir[apphome[];config`sortcsv]]]; +/ publishes the root names other processes and legacy's peach lambdas call +setroot:{[] + set[`.wdb.endofdaysort;endofdaysort]; + set[`.wdb.handler;handler]; + set[`.wdb.reloadsymfile;reloadsymfile]; + set[`.wdb.setcompression;setcompression]; + set[`.wdb.merge;merge]; + set[`.wdb.gc;.z.m.gc]; + set[`.wdb.initmissingtables;initmissingtables]; + set[`.sort.sorttab;sorttab]; + set[`.merge.syncpartsizes;.z.m.mrg`syncpartsizes]; + set[`.merge.clearpartsizes;.z.m.mrg`clearpartsizes]; + / define .z.pd in order to connect to any worker processes + @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; + @[`.;`upd;:;.z.m.upd]; + @[`.;`endofday;:;endofday]; + @[`.;`.u.end;:;endofday]; + / the idb reads these at startup; currentpartition is republished at each end of day + set[`.wdb.savedir;.z.m.savedir]; + set[`.wdb.hdbdir;.z.m.hdbdir]; + set[`.wdb.currentpartition;.z.m.currentpartition]; + set[`.wdb.writedownmode;.z.m.writedownmode]; + } - / connect to the tickerplant + hdb(s) + rdb(s) (+ gateway) via the INJECTED di.torq.servers - / (di.torq already ran init - shared once-init'd registry); we call only startup with our - / own connection list, and use the lookup fns off the same injected instance. +/ reads deps and config; a save mode then connects, subscribes and replays the tp log, a sort mode waits to be called +init:{[config;deps] + if[not `log in key deps;'"di.torq.proc.wdb: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.torq.proc.wdb: timer dependency is required - see di.timer"]; + if[not `servers in key deps;'"di.torq.proc.wdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; + .z.m.log:deps`log; + .z.m.timer:deps`timer; .z.m.svc:deps`servers; - sconfig:config,(enlist`connections)!enlist distinct .z.m.tptypes,.z.m.hdbtypes,.z.m.rdbtypes,.z.m.idbtypes,.z.m.gatewaytypes; - (.z.m.svc`startup)[sconfig]; + setconfig config; + / legacy passes -s -N on the command line; torqx.sh has no per-process flags, so it is a setting + if[0.z.m.replaynumrows; + {replaymaxrowcheck[x;maxrows x]} each tablelist[]]; - / timer job: check/flush to disk every settimer seconds (di.timer mode 1h period is seconds) - (.z.m.timer`addjob)[`wdbsave;savetodisk;();settimer;1h;()!()]; - .z.m.log[`info][`wdb;"initialised, savedir=",(1_string .z.m.savedir),", hdbdir=",(1_string .z.m.hdbdir),", flush every ",(string settimer),"s"]; + setroot[]; + (.z.m.timer`addjob)[`wdbsave;savetodisk;();.z.m.settimer;1h;()!()]; + msg:"initialised, mode=",(string .z.m.mode),", writedownmode=",(string .z.m.writedownmode),", savedir=",.z.m.savedirs; + msg,:", hdbdir=",(1_string .z.m.hdbdir),", flush every ",(string .z.m.settimer),"s"; + .z.m.log[`info][`wdb;msg,$[.z.m.sortenabled;"";", sort handed to ",", " sv string .z.m.sorttypes]]; } diff --git a/di/torq/settings/sort.q b/di/torq/settings/sort.q new file mode 100644 index 00000000..a451986f --- /dev/null +++ b/di/torq/settings/sort.q @@ -0,0 +1 @@ +mode:`sort diff --git a/di/torq/settings/sortworker.q b/di/torq/settings/sortworker.q new file mode 100644 index 00000000..efc619bc --- /dev/null +++ b/di/torq/settings/sortworker.q @@ -0,0 +1,9 @@ +mode:`sort +tickerplanttypes:`symbol$() +hdbtypes:`symbol$() +rdbtypes:`symbol$() +idbtypes:`symbol$() +gatewaytypes:`symbol$() +sorttypes:`symbol$() +sortworkertypes:`symbol$() +wdbtypes:`symbol$() diff --git a/di/torq/torq.md b/di/torq/torq.md index c85cbeed..b2a7438c 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -115,7 +115,8 @@ So **yes, it supports per-procname customisation** just like the config cascade as in TorQ (`.proc.loadnamecode` defaults `0b`), the procname tier is **off by default** and opt-in via `loadnamecode:1b` in that process's settings. Each flag is read from the merged config (so it's overridable per-process in settings). `parentproctype` (TorQ's 4th tier, for -sharing code between a WDB and its sort workers) is omitted — there is no sort-worker tier yet. +sharing code between a WDB and its sort workers) is omitted: proctypes `sort` and `sortworker` are +built in and run `di.torq.proc.wdb` itself, with `settings/sort.q` and `settings/sortworker.q`. Within a directory, files load in this order: an optional `order.txt` (one filename per line) is loaded first, then the remaining `*.q`/`*.k` files alphabetically — matching TorQ's `loaddir`. diff --git a/di/torq/torq.q b/di/torq/torq.q index 214e1b7b..4ace6fa4 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`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`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.wdb reqenv:{[e] v:getenv e; @@ -147,7 +147,8 @@ startcustom:{[proctype;config;deps] / plain `system "l"` lets each file's definitions land at the namespace ITS OWN \d directives / choose - a bare app query file like code/rdb/examplequeries.q (no \d) lands at ROOT, callable as / countbysym[...]. This is the same load mechanism startcustom already uses for code/processes/. -/ (parentproctype - torq.q's 4th tier, for wdb/sort sharing - is omitted: no sort-worker tier yet.) +/ (parentproctype - torq.q's 4th tier, which existed so a sort process could load the wdb's code - +/ is omitted: proctypes sort and sortworker map to di.torq.proc.wdb itself. See wdb.md.) optflag:{[config;k;dflt] $[k in key config;`boolean$config k;dflt]} / load every q/k file in one dir at root: an optional order.txt lists files to load first, then From 3296bc346871fd14da7ef7a431c935eb89a9f2b2 Mon Sep 17 00:00:00 2001 From: Peter Kaiser Date: Wed, 30 Sep 2026 10:54:09 +0100 Subject: [PATCH 02/15] di.torq.proc.wdb: fixes from review - astimespan reads a string of digits as seconds, like a number ("N"$ read it as hours) - sortparams: an empty sort config table when none is loaded, so the partitioned-mode sort.csv checks log instead of throwing 'type - movetohdb creates the hdb root before the move - setroot defines .u.end with set, not as a root key named `.u.end - flushend flushes the reloaded processes' handles, not the keyed table's rows Co-Authored-By: Claude Opus 5.5 (1M context) --- di/torq/proc/wdb/test.csv | 5 +++++ di/torq/proc/wdb/wdb.q | 16 ++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 80d0e501..cef191a5 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -18,6 +18,9 @@ true,0,0,q,30000~.m.di.0torq.0proc.0wdb.tolong 30000,1,,tolong passes a native l true,0,0,q,1b~.m.di.0torq.0proc.0wdb.tobool "true",1,,tobool parses a string setting to a boolean ATOM (`boolean$ would give a list) true,0,0,q,0b~.m.di.0torq.0proc.0wdb.tobool "false",1,,tobool parses a false string true,0,0,q,1b~.m.di.0torq.0proc.0wdb.tobool 1b,1,,tobool passes a native boolean through unchanged +true,0,0,q,0D00:00:10~.m.di.0torq.0proc.0wdb.astimespan "10",1,,astimespan reads a string of digits as seconds, like a number +true,0,0,q,0D00:00:10~.m.di.0torq.0proc.0wdb.astimespan "0D00:00:10",1,,astimespan parses timespan text +true,0,0,q,0D00:00:10~.m.di.0torq.0proc.0wdb.astimespan 10,1,,astimespan reads a number as seconds fail,0,0,q,.m.di.0torq.0proc.0wdb.tolong "not-a-number",1,,tolong rejects unparseable text rather than returning null (a null period silently busy-loops di.timer) fail,0,0,q,.m.di.0torq.0proc.0wdb.tolong "",1,,tolong rejects an empty string @@ -31,6 +34,8 @@ comment,,,,,,,end to end - a spawned process answers .u.subdetails as the ticker run,0,0,q,"system ""l di/torq/proc/wdb/test.q""",1,,load fixture helpers run,0,0,q,setup[],1,,fixture dirs and the fake tickerplant true,0,0,q,defaultmode[],1,,default writedown: flushed, sorted into the hdb with p# on sym, working partition gone +true,0,0,q,100h=type get `.u.end,1,,.u.end is defined at root as the end of day entry point +true,0,0,q,98h=type .m.di.0torq.0proc.0wdb.sortparams[],1,,sortparams is always a table so the sort.csv checks can query it true,0,0,q,partbyattr`part,1,,partbyattr merged by whole partition true,0,0,q,partbyattr`col,1,,partbyattr merged column by column true,0,0,q,partbyattr`hybrid,1,,partbyattr merged by the hybrid method diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index bb91182a..bd215e31 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -12,7 +12,7 @@ tolong:{[x] r } tobool:{[x] $[-1h=type x;x;10h=abs type x;(lower (),x) in ("true";(),"1";(),"t";(),"y";"yes");`boolean$x]} -astimespan:{[x] $[10h=abs type x;"N"$(),x;-16h=type x;x;`timespan$1000000000*x]} +astimespan:{[x] $[10h=abs type x;$[any ((),x) in "D:";"N"$(),x;`timespan$1000000000*"J"$(),x];-16h=type x;x;`timespan$1000000000*x]} / a token-list config (e.g. reloadorder) as a symbol list astoklist:{[x] $[10h=type x;`$" " vs x;-11h=type x;enlist x;11h=type x;x;`$x]} @@ -228,7 +228,7 @@ handler:{[x] / evaluate contents of d dictionary asynchronously; notify the gateway that we are done flushend:{[] if[not .z.m.reloadcomplete; - if[.z.m.eodwaittime>0;@[{neg[x]"";neg[x][]};;()] each key .z.m.reloadsummary]; + if[.z.m.eodwaittime>0;@[{neg[x]"";neg[x][]};;()] each exec handle from .z.m.reloadsummary]; informgateway`reloadend; .z.m.log[`info][`sort;"end of day sort is now complete"]; .z.m.reloadcomplete:1b]; @@ -265,7 +265,8 @@ resetcompression:{[] setcompression 16 0 0} / temporary partition and the hdb partition. If there is a clash abort operation otherwise copy / each table to the hdb partition movetohdb:{[dw;hw;pt] - $[not (`$string pt) in key hsym `$(neg count string pt)_hw; + (.z.m.os`mkdir) hdbroot:(neg count string pt)_hw; + $[not (`$string pt) in key hsym `$hdbroot; .[.z.m.os`mv;(dw;hw);{[dw;hw;e] .z.m.log[`error][`mvtohdb;"Failed to move data from wdb ",dw," to hdb directory ",hw," : ",e]}[dw;hw]]; not any a[dw] in (a:{key hsym `$x}) hw; [{[y;x] @@ -328,9 +329,12 @@ postreplay:{[hdbdir;pt] @[.z.m.posteod .;(hdbdir;pt);{[e] .z.m.log[`error][`postreplay;"postreplay failed: ",e]}]; } +/ the loaded sort config, or an empty one as legacy's .sort.params +sortparams:{[] $[(::)~c:(.z.m.dbw`getconfig)[];([] tabname:`symbol$(); att:`symbol$(); column:`symbol$(); sort:`boolean$());c]} + / the parted column(s) for a table from the sort config, falling back to the default row getextrapartitiontype:{[tablename] - params:$[(::)~c:(.z.m.dbw`getconfig)[];();c]; + params:sortparams[]; if[count tabparts:distinct exec column from params where tabname=tablename,sort,att=`p; .z.m.log[`info][`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; :tabparts]; @@ -561,7 +565,7 @@ endofday:{[pt] / checks sort.csv sets the p attribute every partitioned writedown mode needs checksortparams:{[] if[not .z.m.writedownmode in .z.m.partwritemodes;:()]; - params:$[(::)~c:(.z.m.dbw`getconfig)[];();c]; + params:sortparams[]; / check that default table is defined $[count exec distinct tabname from params where tabname=`default,att=`p,sort; .z.m.log[`info][`init;"default table defined in sort.csv and with at least one `p attribute and sort=1b"]; @@ -646,7 +650,7 @@ setroot:{[] @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; @[`.;`upd;:;.z.m.upd]; @[`.;`endofday;:;endofday]; - @[`.;`.u.end;:;endofday]; + set[`.u.end;endofday]; / the idb reads these at startup; currentpartition is republished at each end of day set[`.wdb.savedir;.z.m.savedir]; set[`.wdb.hdbdir;.z.m.hdbdir]; From fa89281d9a1284305382fb64bb5f5302db38ed23 Mon Sep 17 00:00:00 2001 From: Dexter Date: Thu, 8 Oct 2026 11:19:19 +0800 Subject: [PATCH 03/15] Merge branch 'main' into feature/wdb-module Resolve the builtin process-type registry conflict as a union: keep the branch's sort/sortworker entries and main's discovery entry. Co-Authored-By: Claude Opus 5 --- di/clienttracking/VERSION | 2 +- di/clienttracking/clienttracking.md | 363 ++-------- di/clienttracking/clienttracking.q | 329 ++------- di/clienttracking/deps.toml | 1 + di/clienttracking/init.q | 8 +- di/clienttracking/test.csv | 241 ++----- di/clienttracking/test.q | 29 + di/clienttracking/test_integration.csv | 82 --- di/pubsub/VERSION | 2 +- di/pubsub/pubsub.md | 17 +- di/pubsub/pubsub.q | 97 ++- di/pubsub/test.csv | 28 +- 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/chainedtp/VERSION | 2 +- di/torq/proc/chainedtp/chainedtp.md | 372 ++-------- di/torq/proc/chainedtp/chainedtp.q | 629 +++++------------ di/torq/proc/chainedtp/deps.toml | 6 +- di/torq/proc/chainedtp/init.q | 2 +- di/torq/proc/chainedtp/test.csv | 146 ++-- di/torq/proc/chainedtp/test.q | 648 ++---------------- 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 - 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 | 65 ++ di/torq/proc/tickerplant/tickerplant.q | 2 +- di/torq/servers/VERSION | 3 +- di/torq/servers/servers.md | 218 +++--- di/torq/servers/servers.q | 371 ++++++---- di/torq/servers/test.csv | 33 +- di/torq/servers/test.q | 42 +- di/torq/servers/test_enabled.q | 6 + di/torq/settings/chainedtp.q | 27 + di/torq/settings/default.q | 24 +- di/torq/settings/discovery.q | 23 + di/torq/settings/hdb.q | 2 + di/torq/settings/segmentedtp.q | 3 + di/torq/settings/tickerplant.q | 3 + di/torq/test.csv | 16 + di/torq/torq.md | 32 +- di/torq/torq.q | 27 +- 54 files changed, 1775 insertions(+), 3093 deletions(-) create mode 100644 di/clienttracking/deps.toml create mode 100644 di/clienttracking/test.q delete mode 100644 di/clienttracking/test_integration.csv 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 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/servers/test_enabled.q create mode 100644 di/torq/settings/chainedtp.q create mode 100644 di/torq/settings/discovery.q create mode 100644 di/torq/settings/segmentedtp.q create mode 100644 di/torq/settings/tickerplant.q diff --git a/di/clienttracking/VERSION b/di/clienttracking/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/clienttracking/VERSION +++ b/di/clienttracking/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/clienttracking/clienttracking.md b/di/clienttracking/clienttracking.md index 8946bf7f..ca5ed538 100644 --- a/di/clienttracking/clienttracking.md +++ b/di/clienttracking/clienttracking.md @@ -1,335 +1,66 @@ # di.clienttracking -Tracks the client sessions connected to a KDB-X process in an in-memory session table: who -connected, from where, when, when they went away, and (once a query owner exists) how many -requests each one made and roughly how many bytes it was sent. A port of TorQ's -`code/handlers/trackclients.q` (`.clients.*`), rebuilt on `di.torq.handlers` so it never assigns a -`.z.*` handler itself. +Tracks the client sessions of a process in `.clients.clients`: who connected, when, how many +queries they sent, how many failed and how many bytes they were sent. -## Features +## Surface -- One row per client session, opened from `.z.po`/`.z.wo` and closed from `.z.pc`/`.z.wc`. -- Per-request usage counting (`hits`, `lastp`, and for sync queries `sz`) as a `post` watcher on - `.z.pg`/`.z.ps`/`.z.ws`, measuring the **final** result the caller received (see - [Design decisions](#design-decisions--rationale)). -- Sweeps that reap sessions whose handle has vanished, optionally force-close idle handles (only - while usage counting is live — see [Configuration](#configuration)), and purge closed rows past a - retention window. -- `enabled`/`trackusage` switches in config, matching TorQ's `.clients.enabled`/`opencloseonly`. +| 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 | -## Dependencies +## Settings -Both dependencies are **injected** through `init`; the module `use`s nothing. +A `clients` section of the process config, set onto `.clients.`: -| Dependency | Key | Required | Contract | -|---|---|---|---| -| logger | `` `log `` | **yes** | dict with `` `info`warn`error ``, each `{[ctx;msg]}` — `di.util.log`'s `logdict` is ready-made | -| handler registry | `` `handlers `` | **yes** | dict with `` `register`remove`list `` — the surface `di.torq` builds from `di.torq.handlers` | - -Anything else in `deps` (`` `timer ``, `` `servers `` — the rest of what `di.torq` injects) is accepted and -ignored. A missing or malformed required dependency makes `init` signal immediately; there is no -fallback. - -**Why `handlers` is injected rather than `use`d.** `di.torq.handlers` owns the one root `.z.*` -binding per process, so there must be exactly one instance and its `init` must run exactly once. -That is the definition of an injected singleton in `consistency.md` ("inject cross-cutting -singletons; `use` libraries"). The modularisation plan's dependency tree lists -`di.clienttracking → di.handlers`, but that is a role grouping, not a hard import — the same -resolution already applied to `di.permissions`. - -**No `deps.toml`.** The module has zero `use` dependencies, so it ships no manifest at all — -matching `di.serverselect` and `consistency.md` ("a missing `deps.toml` is a silent no-op … -adoption is incremental"). An explicit empty manifest would only be noise. - -## Initialisation - -```q -ct:use`di.clienttracking - -/ log dep - the same shape di.torq builds (di.util.log's flat info/warn/error); logging.logdict`log -/ (its createlog-based instance) also satisfies the contract but prints in a different format -logging:use`di.util.log -logdep:`info`warn`error!(logging`info;logging`warn;logging`error) - -/ handlers dep - di.torq builds this from di.torq.handlers; standalone you build it the same way -hz:use`di.torq.handlers -hz[`init][enlist[`log]!enlist logdep] -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list) - -/ config carries this module's settings under a `clienttracking section; an absent section = defaults -config:enlist[`clienttracking]!enlist `maxidle`retain!(0D00:30:00;0D01:00:00) - -ct.init[config;`log`handlers!(logdep;handlersdep)] -``` - -> If you start from `logging.logdict` instead, join it with a **multi-key** dict -> (`` logging.logdict,`handlers`timer!(handlersdep;::) ``). `logdict,enlist[`handlers]!enlist handlersdep` -> throws `'mismatch` — a one-element list of dicts is a table, and two such value sides with -> different columns cannot be joined. - -`init` takes **two arguments, `config` then `deps`** — the shape `consistency.md` prescribes for -modules with per-process settings, and the one `di.permissions` (the sibling handlers consumer), -`di.subscriptions` and `di.torq.logroll` use. `config` is the whole process config dict; only its -`` `clienttracking `` section is read. - -> **A two-argument `init` called with one dict does not throw** — q returns a projection. So "`init` -> didn't error" proves nothing; wire it with both arguments and assert an observable effect -> (registrations on `handlers.list`). The suite pins the arity with `2=count (value ct.init) 1`. - -`init` must be called before any other function (there is no default logger). It is -**idempotent**: a re-init re-wires the dependencies and config, reclaims the same registrations -in place, and leaves the session table intact. Re-initialising with `enabled:0b` removes every -registration this module made and stops; a later enabled re-init puts them back. - -> **Nothing in `di.torq` wires this module yet.** Unlike `di.querylog` (which `di.torq` switches on -> from a `[querylog]` settings section), a host process wires `di.clienttracking` itself. Until -> `di.torq` grows a `[clienttracking]` hook (a one-liner in its `init`, after `loadappcode` — the -> module already takes the standard `init[config;deps]` and `deps` is exactly what `di.torq` builds), -> an app can wire it from a `code/common/clienttracking.q` app-code file: `use` the same -> `di.torq.handlers` instance (`use` returns the loaded singleton, so the registrations land in the -> live dispatchers alongside `servers`/`pubsub`/`gateway`), build `deps` as above, and pass a -> config dict. This is how the module was smoke-tested on every process of the TorqX-POC stack. - -### Configuration - -All keys live under the `` `clienttracking `` section. Defaults are TorQ's **effective** ones from -`config/settings/default.q` — not the `dotz.q` fallbacks, which that file always overrides. - -| Key | Type | Default | Description | -|---|---|---|---| -| `enabled` | boolean | `1b` | register the lifecycle observers at all. `0b` wires the log, unhooks anything a previous init registered, and stops | -| `maxidle` | timespan, or string `"nDhh:mm:ss"` (the `D` is mandatory — `"900"` is rejected, not read as 9 hours) | `0D` | force-close a live handle whose `lastp` is older than this. `0D` (the default) disables reaping — see the warning below | -| `retain` | timespan, or string `"nDhh:mm:ss"` (same rule) | `0D02:00:00` | delete a closed session this long after its `endp`. `0D` does **not** mean "keep forever" — see below | -| `trackusage` | boolean | `1b` | attach the usage watcher to `.z.pg`/`.z.ps`/`.z.ws`. `0b` is TorQ's `opencloseonly` | - -The two timespans may also be given as **strings in q's `nDhh:mm:ss` literal form** (`"0D00:15:00"`, -`"1D"`) — TOML has no timespan type, so that is the only way a `.toml` settings file can carry -them. The `D` is mandatory: `"N"$` would silently read `"900"` as nine *hours* and `"15:00"` as -fifteen hours, so bare numbers are rejected. Both must be finite and non-negative (a null, `0Wn` or -negative value is rejected). Every wrong value is logged at error and signalled by name -(`di.clienttracking: init: config key maxidle must be a timespan, or its string form such as "0D00:15:00"`). -Unknown keys are ignored. A per-process section replaces the app-default section wholesale — the -config cascade does not deep-merge sections. - -> **Idle reaping only runs while usage counting is live.** `lastp` advances only when the usage -> watcher counts a request, and the watcher can only attach to a query event that has an `exec` -> owner. Until it is live on at least one event (`trackusage:0b`, or no owner registered yet), -> every session would look idle and a positive `maxidle` would close *every* connection on the -> process — so `cleanup` suspends the idle-reap branch instead, and `init`/`enableusage` log a -> warning saying so. Today **no `di.torq` process type registers an `exec` owner** (the gateway, -> rdb, hdb and tickerplant all run on the built-in `.z.pg`/`.z.ps`), so on a stock TorqX stack -> `maxidle` is inert until a `di.permissions`-style owner (or `di.torq`) claims `exec`. -> -> **Even with counting live, `maxidle` reaps quiet clients.** A client that only *receives* — a -> pub/sub subscriber on a tickerplant, a wdb's control connection to a gateway — never bumps -> `lastp`. Observed on the POC stack with `maxidle` set on the gateway: the first sweep after -> counting went live force-closed `wdb1`'s idle connection, `di.torq.servers` on the wdb reopened it -> ten seconds later, and the pair would have churned every sweep. That is TorQ's `MAXIDLE` -> semantics faithfully reproduced, and why the default is `0D`. Set `maxidle` only on processes -> whose clients all make requests. -> -> **`retain:0D` does not mean "keep forever" — unlike `maxidle:0D`, it is not a disable value.** -> `cleanup` purges with `delete from … where not null endp,endp condition reduces to `endp next sweep runs. So `retain:0D` means "purge a closed session on the very next `cleanup` sweep", -> not "never purge". (`maxidle:0D` really does disable idle reaping — that branch is explicitly -> gated on `0D retains closed rows indefinitely; set `retain` to something very large if that is what you want. - -## The session table - -`getclients[]` returns an **unkeyed** table (type `98h`), one row per session: - -| Column | Type | Meaning | +| Key | Default | Meaning | |---|---|---| -| `w` | int (`` `g# ``) | connection handle (`.z.w` at open) | -| `ipa` | symbol | client IP, dotted-decimal | -| `u` | symbol | client user (`.z.u` at open) | -| `a` | int | client IP as the raw `.z.a` int | -| `startp` | timestamp | session open | -| `endp` | timestamp | session close; **null while open** | -| `lastp` | timestamp | last counted request (initially `startp`) | -| `hits` | long | requests counted for this session (`.z.pg`, `.z.ps` and `.z.ws`) | -| `sz` | long | total `-22!` size of the results actually **returned** — sync (`.z.pg`) requests only; see below | - -Handles are reused by the OS, so the same `w` can appear in several rows over time — the open one -has a null `endp`. Compared with TorQ's `.clients.clients` the table drops `k`/`K`/`c`/`s`/`o`/`f`/ -`pid`/`port` (only ever filled by the removed INTRUSIVE probe) and `errs` (see below); `hits` and -`sz` are longs. - -## Exported functions - -### `init[config;deps]` -Wire dependencies and config, register the observers. See [Initialisation](#initialisation). - -### `getclients[]` -The session table above. Returns the live module state — copy it if you intend to mutate. - -### `addclient[handle]` -Record `handle` (an int) as an open session from the current `.z` context — TorQ's `addw`. For a -handle that was open before `init` ran, or one opened by this process (`hopen`) that you want -tracked. Runs a sweep first. Signals on a non-int. - -### `cleanup[]` -One sweep: stamp `endp` on any open row whose handle is no longer in `.z.W`; if `maxidle>0D` and -usage counting is live, `hclose` live handles idle longer than that and stamp them; delete closed -rows older than `retain`. Runs automatically on every open and close; exported so a host can also -drive it from a timer (a process that sees no connection churn never sweeps otherwise — a client -that goes idle after the last open/close is not reaped until the next one). - -The handle a `cleanup[]` call arrives on (`.z.w`) is never reaped by that call: it is mid-request, -not idle — its `lastp` is only bumped by the usage watcher *after* the call returns. Without that -guard a stale client calling `cleanup[]` over IPC had its own handle closed under it and got -`'close handle` instead of a reply (reproduced with a real socket before the guard went in). - -### `enableusage[]` -(Re)attach the usage watcher as a `post` handler on each of `.z.pg`, `.z.ps`, `.z.ws` that -currently has an `exec` owner; logs (at info — no owner is the normal state of a stock `di.torq` -process) each one it had to defer, and warns only if `maxidle` is configured but cannot run. `init` calls it when -`trackusage` is `1b`, but a `post` cannot attach before an `exec` owner exists, so **call it again -after the query owner (gateway, permissions, app code) registers**. Idempotent. - -### `getapimeta[]` -This module's rows for `di.api`, one per callable export (`getclients`, `addclient`, `cleanup`, -`enableusage`). `init`, `getapimeta` and `version` are plumbing and are not listed. +| `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 | -### `version` -The contents of the `VERSION` file (semver string). `di.torq.depcheck` reads it from the export. +## init[config;deps] -## Events managed +Requires `handlers` (`di.torq.handlers`). It: -All through `di.torq.handlers`, under the name `` `clienttracking `` at priority `0`. +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. + An unset `.z.pg`/`.z.ps` is taken as `value`, and an unset `.z.ws` as an echo. -| Event | Model | Phase | Handler | -|---|---|---|---| -| `.z.po`, `.z.wo` | simple | `` ` `` | open a session row (after a sweep) | -| `.z.pc`, `.z.wc` | simple | `` ` `` | stamp `endp` on the open row for that handle (then sweep) | -| `.z.pg` | phased | `post` | bump `hits`/`lastp` and add `-22!` of the result to `sz` for `.z.w` | -| `.z.ps`, `.z.ws` | phased | `post` | bump `hits`/`lastp` for `.z.w` — no bytes, nothing is returned to the client | +Call `init` once: a second call wraps the query handlers again. An exec owner registered on those +events through `di.torq.handlers` afterwards replaces the wrap. -`.z.pi`, `.z.pp`, `.z.ph` and `.z.pw` are not counted (TorQ did not count them either). +## Behaviour to know -### Usage counting measures the final, post-transform result - -`di.torq.handlers` threads a phased event `pre → exec → transform → post` -(`dispatchphased`, `handlers.q`): the transform chain rewrites the owner's result, every `post` -handler is then called with **that** value, and that same value is what the dispatcher returns to -the caller. So `sz` accumulates `-22!` of exactly what the client received — a transform that -wraps, filters or redacts the result is reflected in the byte count. The suite proves it by -registering a wrapping transform and asserting `sz` grew by the size of the wrapped result, not -the bare one. (`handlers.md` predates the transform phase and does not mention it; the -authoritative source is `dispatchphased` itself.) - -## Design decisions & rationale - -- **Usage counting is deferred, not eager.** A `post` cannot be registered before an `exec` owner - exists. TorQ's `trackclients.q` had no such constraint because it wrapped whatever was in `.z.pg` - at load time. Here `init` attaches to whichever query events already have an owner and warns - about the rest; `enableusage[]` is exported so the host can complete the wiring after its owner - registers. Ordering is the host's responsibility and the warning makes a miss visible. -- **`sz` counts sync results only.** kdb+ discards the return value of a `.z.ps` (async) or `.z.ws` - handler — nothing goes back to the client — so adding `-22!` of it to `sz` (as TorQ did for all - three events) inflates the column with bytes that were never transferred, e.g. an rdb's `upd` - return value for every tickerplant update. Only `.z.pg` measures bytes; the other two watchers - count hits and freshen `lastp`. -- **A handle being opened closes any open row it already has.** `.z.po` for handle `h` means the - previous session on `h` is over, whether or not this module saw its `.z.pc` (registered late, - disabled at the time, `addclient` called twice). The stale row is stamped closed before the new - one is inserted, so the OS reusing a handle number can never leave two open rows both counting - the same requests. TorQ's keyed table got this for free by overwriting; an unkeyed table has to - do it explicitly. -- **No `errs` column.** TorQ's `hite` counted a failed request by wrapping the handler in a - protected apply and re-signalling. A `post` runs only after a successful `exec` — a throw in - `exec` propagates before any `post` fires — so this module cannot observe failures. Adding an - `exec`-phase wrapper to count them would make this module the query owner, which it must not be. - Failed requests are therefore not counted anywhere here; `di.querylog` records them. -- **Unkeyed table.** TorQ keyed on `w` and nulled it on close, so a reconnecting handle overwrote - the previous session's history. An unkeyed table keeps one row per session; the open one is - `null endp`. -- **INTRUSIVE mode removed.** TorQ could send each new client an async query asking for its - `.z.K`/`.z.c`/`.z.i`/… and write the answers back. It is off by default in TorQ, is documented - there as unsafe with non-kdb+ clients, and requires the module to issue outbound queries on - someone else's handle. Dropped along with the eight columns only it populated. -- **`.z.p` rather than TorQ's `.proc.cp[]`.** All timestamps are UTC; there is no localtime switch. -- **`enabled` restored, defaults taken from `default.q`.** The earlier draft omitted TorQ's - `enabled` switch and took `maxidle`/`retain` from `dotz.q` (15 min / 5 min). Every TorQ process - loads `config/settings/default.q`, which sets `MAXIDLE:0D` ("0 means no clean up") and - `RETAIN:0D02`, so those are the behaviour a TorQ user actually gets — and reaping-on-by-default - would silently close every push-only subscriber (an RDB on a tickerplant) after 15 minutes. -- **`init[config;deps]` with a `` `clienttracking `` section**, following `di.permissions`, - `di.subscriptions` and `di.torq.logroll` (`consistency.md`, "framework & DI conventions"). -- **`disabled` re-init unhooks.** `di.permissions` stops without touching registrations; this - module removes its observers and watchers so a re-init to `enabled:0b` actually stops tracking. - The session table is kept. -- **Sweep on every open/close, no `AUTOCLEAN` switch.** TorQ's `AUTOCLEAN` defaulted to `1b`; the - off setting was never used in shipped config and was dropped. -- **The session table is amended by name, not reassigned.** Every write goes through - `.z.M.clients` (the module-qualified name of `.z.m.clients`), so `update`/`delete`/`upsert` amend - in place as TorQ's `` `.clients.clients `` did. The per-request `hitpost` is the hot path: a - by-value `.z.m.clients:update … from .z.m.clients` copies three columns of the whole table on - every query — measured 24× slower (83 µs vs 3.4 µs per request) with 50k retained rows, and it - grows with `retain`. Reading state is still `.z.m.clients`; only the write target uses the name view. -- **Log storage** is the three-flat-vars form (`.z.m.loginfo/logwarn/logerr`), as in - `di.torq.handlers` and `consistency.md`'s base example. Post-`init` errors go through - `raiseerror` (log at error, then signal); `init`'s own dependency validation signals plainly - because the log is not wired yet. - -## Known limitations - -- **`'noupdate` under multithreaded input.** With a negative `\p` the `post` handler runs off the - main thread and its global update throws `'noupdate`; `di.torq.handlers` isolates and logs it - at warn, so usage is not counted on such processes. Session open/close still works. -- **Failed requests are not counted** — see the `errs` decision above. -- **`.z.ph` (HTTP GET) is not counted.** Its `exec` owner replaces the built-in handler wholesale - and `.h.val` is outside `di.torq.handlers`' scope; HTTP usage is left to whoever owns that. -- **`sz` costs a serialisation walk per request.** `-22!` computes the IPC size of the result; on a - process returning very large results, set `trackusage:0b` if that overhead matters. -- **A request from a handle with no open row is silently uncounted** (opened before `init`, or - reaped). Use `addclient` to register such a handle. -- **No timer of its own.** Without connection churn the table is not swept; drive `cleanup[]` - from `di.timer` if idle reaping or retention matter on a quiet process. -- **Usage counting is inert on a stock TorqX stack.** Smoke-tested on every process of the - TorqX-POC (`tickerplant`, `hdb`, `rdb`, `wdb`, `gateway`, `feed`): sessions, `.z.po`/`.z.pc`, - IPs and users are all tracked, but `hits` stays `0` everywhere because no `di.torq` process type - claims an `exec` owner and a `post` cannot attach without one. Registering an owner (a - `{value x}` passthrough via the handlers singleton, as the smoke did on the gateway) makes - counting live immediately. Either `di.torq.handlers` needs a default-owner notion for events - that only have watchers, or `di.torq` should claim a passthrough `exec` — a follow-up in those - modules, not here. -- **`di.querylog` and an `exec` owner do not mix** (a `di.torq` limitation, observed here): once - any owner claims `.z.pg`/`.z.ps` through `di.torq.handlers`, the dispatcher replaces the wrapper - `di.querylog` installed by direct assignment and query logging on those events silently stops, - while this module keeps counting. Reproduced on the POC gateway with `[querylog] enabled=true`. -- **A `[clienttracking]` TOML section cannot share a file with another section today** — - `di.util.toml` builds sections with `` d,(enlist k)!enlist v ``, so a file with two sections of - different keys throws `'mismatch` at parse time (`[logroll]` + `[clienttracking]` in one - `hdb.toml`, say). A single-section file, or `.q` settings, work. Bug in `di.util.toml`. - -## Running tests - -Unit suite (hermetic — drives the real `di.torq.handlers` dispatchers with synthetic handles and -the console handle `0i`): - -```q -q)k4unit:use`di.k4unit -q)k4unit.moduletest`di.clienttracking -``` +- `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 + instead of marking it. +- `.clients.unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. +- `hits` and `errs` are ints. -Integration suite (`test_integration.csv`) — stands up a child q process on an OS-assigned port and -runs two legs over real sockets. Inbound: the child loads and `init`s its **own** instance of the -module over IPC and this process is its client — a second `hopen` is seen as a real `.z.po` with -the right IP and user, requests are counted, a `cleanup[]` call made over an idle handle does not -close that handle, and the other idle session is force-closed. Outbound: the tracked handle to the -child is reaped as idle here. (The child hosts the instance because a process blocked in a sync -call does not accept connections, so a dial-back into the test process would deadlock.) Needs a -q/kdb-x binary reachable via `QHOME` (or `q` on `PATH`); skips cleanly if the child never comes up. -Run it in a **fresh** session (`moduletest` only loads `test.csv`): +## Testing ```q -q).m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.clienttracking;`test_integration.csv] -q).m.di.0k4unit.KUrt[] -q)k4unit.getresults[] +k4unit:use`di.k4unit +k4unit.moduletest`di.clienttracking ``` -Both suites pass on KDB-X `0.1.2/2025.11.17` and `5.0/2026.07.23` with -`QPATH` pointing at the modules root. +`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. diff --git a/di/clienttracking/clienttracking.q b/di/clienttracking/clienttracking.q index dae28d48..a406a72a 100644 --- a/di/clienttracking/clienttracking.q +++ b/di/clienttracking/clienttracking.q @@ -1,269 +1,64 @@ -/ track the client sessions connected to a KDB-X process in a session table -/ consumes di.torq.handlers (injected) to observe connection open/close and, once a query owner -/ exists, to count per-request usage - it never assigns .z.* directly -/ NB the exported `version` is defined in init.q (read from the VERSION file), not here - -/ ============================================================ -/ constants (load-time) -/ ============================================================ - -/ session table schema - one row per client session; an open session has a null endp -/ w is grouped for fast per-handle lookup; hits/sz are longs -clientschema:([] - w:`g#`int$(); / connection handle (.z.w at open) - ipa:`symbol$(); / client ip address, dotted-decimal - u:`symbol$(); / client user (.z.u at open) - a:`int$(); / client ip address, raw int (.z.a at open) - startp:`timestamp$(); / session start - connection open time - endp:`timestamp$(); / session end - connection close time; null while open - lastp:`timestamp$(); / time of the last request seen from this client - hits:`long$(); / number of requests served for this client - sz:`long$()); / total (approximate) bytes of results returned to this client - -/ this module's settings, read from the `clienttracking section of the process config; an absent -/ section (or key) takes the default. defaults are TorQ's EFFECTIVE ones from config/settings/default.q -/ (.clients.enabled/opencloseonly/MAXIDLE/RETAIN), not the dotz.q fallbacks that file always overrides -configdefaults:`enabled`maxidle`retain`trackusage!( - 1b; / register the lifecycle observers at all; 0b wires the log and registers nothing - 0D; / force-close a live handle idle for longer than this; 0D (the default) disables reaping - 0D02:00:00; / purge a closed session this long after it ended - 1b); / count per-request usage (hits/sz/lastp) - the inverse of TorQ's opencloseonly - -/ priority used when registering with di.torq.handlers - lower runs first; 0 is a neutral default -handlerpriority:0; - -/ the simple connection-lifecycle events observed, and the observer each one gets -lifecycleevents:`.z.po`.z.pc`.z.wo`.z.wc; - -/ the phased query events usage counting attaches to (as post-phase watchers). post fires AFTER -/ di.torq.handlers' own transform phase (pre -> exec -> transform -> post), so the result a post -/ handler sees is the same, final, post-transform value the dispatcher returns to the caller - -/ see hitpost below and clienttracking.md's "Design decisions" for why that matters here -usageevents:`.z.pg`.z.ps`.z.ws; - -/ ============================================================ -/ internal helpers -/ ============================================================ - -ipa:{[a] - / format a raw .z.a int ip address as a dotted-decimal symbol - / .z.a is a signed int32 (high ips are negative); 0x0 vs takes its two's-complement bytes and - / "i"$ casts each byte UNSIGNED (0-255), so octets >= 128 render correctly (e.g. 192.168.0.1) - :`$"." sv string "i"$0x0 vs a; - }; - -raiseerror:{[ctx;msg] - / internal - log an error under ctx then signal it, so failures are observable as well as thrown - .z.m.logerr[ctx;msg]; - '"di.clienttracking: ",string[ctx],": ",msg; - }; - -track:{[h] - / record a newly-seen client handle - sweep first, then append an open session row for h - / a handle being opened cannot still have a genuinely open session, so any open row already carrying h - / (a close this module never saw - registered late, disabled at the time, or addclient called twice) is - / closed first; otherwise the OS reusing the handle number would leave two open rows both counting hits - cleanup[]; - update endp:.z.p from .z.M.clients where w=h,null endp; - .z.M.clients upsert (h;ipa .z.a;.z.u;.z.a;.z.p;0Np;.z.p;0j;0j); - }; - -closeclient:{[h] - / mark the open session for handle h as closed, then sweep - update endp:.z.p from .z.M.clients where w=h,null endp; - cleanup[]; - }; - -hitpost:{[countsz;result;args] - / usage post-handler - registered as the projection hitpost[countsz], since di.torq.handlers calls - / post[result;args]; args is unused. bumps the request count (and lastp) for the calling client (.z.w) - / countsz: add -22!result to sz. only .z.pg actually sends its handler's return value back to the - / client; an async (.z.ps) or websocket (.z.ws) handler's return value is discarded by kdb+, so - / counting it would inflate sz with bytes that were never transferred (TorQ counted all three) - / runs only on a successful exec (di.torq.handlers post fires after transform, once the owner has - / returned), so it cannot see errors; on a multithreaded (negative \p) process a global write here - / hits 'noupdate and is isolated/logged by di.torq.handlers rather than counting - / amended BY NAME (.z.M.clients is the module-qualified name of .z.m.clients): this is the per-request - / hot path, and a by-value update would copy three columns of the whole session table every request - / (measured 24x slower at 50k retained rows) - bytes:$[countsz;-22!result;0j]; - update lastp:.z.p,hits:hits+1,sz:sz+bytes from .z.M.clients where w=.z.w,null endp; - }; - -disableusage:{[] - / remove any usage post-handlers this module registered (idempotent - di.torq.handlers no-ops an unknown name) - .z.m.handlers[`remove][;`post;`clienttracking] each usageevents; - .z.m.usageactive:0b; - }; - -reapstatus:{[] - / say so when idle reaping is configured but cannot run: lastp only advances through the usage - / watcher, so until it is live on at least one query event every session looks idle and cleanup - / suspends the reap rather than closing every connection on the process - if[(0D<.z.m.maxidle) and not .z.m.usageactive; - .z.m.logwarn[`cleanup;"maxidle is ",string[.z.m.maxidle]," but usage counting is not live on any query event", - " - idle reaping is suspended until enableusage[] attaches to an exec owner (lastp cannot advance otherwise)"]]; - }; - -registerlifecycle:{[] - / register the connection and websocket open/close observers (idempotent - di.torq.handlers replaces in place) - .z.m.handlers[`register][`.z.po;`;`clienttracking;handlerpriority;track]; - .z.m.handlers[`register][`.z.pc;`;`clienttracking;handlerpriority;closeclient]; - .z.m.handlers[`register][`.z.wo;`;`clienttracking;handlerpriority;track]; - .z.m.handlers[`register][`.z.wc;`;`clienttracking;handlerpriority;closeclient]; - }; - -removelifecycle:{[] - / remove the lifecycle observers (idempotent - di.torq.handlers no-ops an unknown name) - .z.m.handlers[`remove][;`;`clienttracking] each lifecycleevents; - }; - -validatedeps:{[deps] - / strict up-front validation of the injected dependencies - plain signals, the log is not wired yet - if[99h<>type deps; - '"di.clienttracking: deps must be a dict with `log and `handlers keys"]; - if[not `log in key deps; - '"di.clienttracking: log dependency is required; pass `info`warn`error functions keyed on `log"]; - if[99h<>type deps`log; - '"di.clienttracking: log value must be a dict; pass `info`warn`error functions"]; - if[not all `info`warn`error in key deps`log; - '"di.clienttracking: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; - if[not `handlers in key deps; - '"di.clienttracking: handlers dependency is required; pass di.torq.handlers register/remove/list keyed on `handlers"]; - if[99h<>type deps`handlers; - '"di.clienttracking: handlers value must be a dict; pass register/remove/list functions"]; - if[not all `register`remove`list in key deps`handlers; - '"di.clienttracking: handlers dict must have `register`remove`list keys; got: ",(", " sv string key deps`handlers)]; - }; - -resolveconfig:{[config] - / take this module's `clienttracking section of the process config and merge it over the defaults - / an absent section means every default; unknown keys in the section are ignored - if[99h<>type config; - raiseerror[`init;"config must be a dict (the process config); clienttracking settings live under its `clienttracking key"]]; - sect:$[`clienttracking in key config;config`clienttracking;()!()]; - if[99h<>type sect; - raiseerror[`init;"the `clienttracking config section must be a dict"]]; - :configdefaults,(key[configdefaults] inter key sect)#sect; - }; - -coercespan:{[k;v] - / a timespan setting: accept a timespan atom, or - TOML has no timespan type, so a .toml settings file - / can only carry a string - its string form in q's nDhh:mm:ss literal shape. the D is required because - / "N"$ reads a bare "900" as 09:00 (hours) and "15:00" as fifteen hours, silently - if[10h=type v;v:$["D" in v;"N"$v;0Nn]]; - if[not -16h=type v; - raiseerror[`init;"config key ",string[k]," must be a timespan, or its string form such as \"0D00:15:00\""]]; - if[(null v) or (v<0D) or v=0Wn; - raiseerror[`init;"config key ",string[k]," must be a finite, non-negative timespan"]]; - :v; - }; - -validateconfig:{[cfg] - / type-check every setting, returning the normalised dict - nested ifs, so a wrong type is reported - / by name rather than as a raw 'type - if[not -1h=type cfg`enabled;raiseerror[`init;"config key enabled must be a boolean"]]; - if[not -1h=type cfg`trackusage;raiseerror[`init;"config key trackusage must be a boolean"]]; - cfg[`maxidle]:coercespan[`maxidle;cfg`maxidle]; - cfg[`retain]:coercespan[`retain;cfg`retain]; - :cfg; - }; - -/ ============================================================ -/ public api -/ ============================================================ +/ di.clienttracking - track client sessions in .clients.clients init:{[config;deps] - / wire the required dependencies (log, handlers), resolve this module's config section, then register - / the lifecycle observers and (when trackusage) the usage watchers - idempotent, a re-init reclaims the - / same registrations and leaves the session table intact - / config: the process config dict; settings live under its `clienttracking key (see configdefaults) - - / an absent section means every default - / deps: `log (required, `info`warn`error binary {[c;m]} funcs) and `handlers (required, di.torq.handlers - / register/remove/list); other injectables di.torq passes (`timer, `servers) are accepted and unused - / example: ct.init[enlist[`clienttracking]!enlist enlist[`maxidle]!enlist 0D01:00:00;`log`handlers!(logdep;hdep)] - validatedeps deps; - .z.m.loginfo:(deps`log)`info; - .z.m.logwarn:(deps`log)`warn; - .z.m.logerr:(deps`log)`error; - .z.m.handlers:deps`handlers; - cfg:validateconfig resolveconfig config; - / one explicit write per key - greppable, and a missing write is visible rather than silently unset - .z.m.enabled:cfg`enabled; - .z.m.maxidle:cfg`maxidle; - .z.m.retain:cfg`retain; - .z.m.trackusage:cfg`trackusage; - / whether the usage watcher is live on any query event - set by enableusage/disableusage below; gates idle reaping - .z.m.usageactive:0b; - / create the session table on first init only; a re-init must leave the existing table intact - if[not `clients in key .z.m;.z.m.clients:clientschema]; - / disabled: unhook anything a previous (enabled) init registered, then stop - nothing else is touched - if[not .z.m.enabled; - removelifecycle[]; - disableusage[]; - .z.m.loginfo[`init;"di.clienttracking loaded but disabled - no handlers registered"]; - :(::)]; - registerlifecycle[]; - $[.z.m.trackusage;enableusage[];disableusage[]]; - if[not .z.m.trackusage;reapstatus[]]; - .z.m.loginfo[`init;"di.clienttracking initialised - maxidle ",string[.z.m.maxidle],", retain ",string[.z.m.retain]]; - }; - -getclients:{[] - / the current client-session tracking table - one row per session (open rows have a null endp) - :.z.m.clients; - }; - -addclient:{[h] - / manually record a client handle in the tracking table using the current .z context (like TorQ's addw) - if[not -6h=type h;raiseerror[`addclient;"handle must be an int"]]; - track h; - }; - -cleanup:{[] - / reap sessions whose handle has gone, force-close idle live handles, purge expired closed rows - / runs automatically on every open/close; also exported so a host can drive it periodically (di.timer) - / idle reaping needs the usage watcher live (see reapstatus) - lastp cannot advance without it - / .z.w is never reaped: the handle this call arrived on is mid-request, not idle - its lastp is only - / bumped by the post watcher AFTER this returns, so without the guard a client calling cleanup[] over - / IPC while stale would have its own handle closed under it and never see the reply - now:.z.p; - update endp:now from .z.M.clients where null endp,not w in key .z.W; - if[(0D<.z.m.maxidle) and .z.m.usageactive; - idle:exec w from .z.m.clients where null endp,w in key .z.W,w<>.z.w,lastp0; + 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;} +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; + 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]} +pc:{[result;W] update w:0Ni,endp:.z.p from`.clients.clients where w=W;cleanup[];result} + +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); + result} + +\d . diff --git a/di/clienttracking/deps.toml b/di/clienttracking/deps.toml new file mode 100644 index 00000000..61a252c2 --- /dev/null +++ b/di/clienttracking/deps.toml @@ -0,0 +1 @@ +[dependencies] diff --git a/di/clienttracking/init.q b/di/clienttracking/init.q index cc79a9c8..9f5c0306 100644 --- a/di/clienttracking/init.q +++ b/di/clienttracking/init.q @@ -1,7 +1,5 @@ -/ di.clienttracking - track connected client sessions via di.torq.handlers connection-lifecycle events \l ::clienttracking.q -/ module version, read from the VERSION file (one plain-text file to bump per release). read -/ module-relative at load (`:::` resolves to di/clienttracking) and BEFORE export, since export:([...]) -/ evaluates each name; version stays in the export so di.torq.depcheck reads it from the export dict + version:first read0`:::VERSION -export:([init;getclients;addclient;cleanup;enableusage;getapimeta;version]) + +export:([init;version]) diff --git a/di/clienttracking/test.csv b/di/clienttracking/test.csv index 0af835a1..6e697b2c 100644 --- a/di/clienttracking/test.csv +++ b/di/clienttracking/test.csv @@ -1,180 +1,63 @@ action,ms,bytes,lang,code,repeat,minver,comment -comment,,,,,,,setup - load di.torq.handlers + di.clienttracking and init against the real di.util.log + di.torq.handlers -before,0,0,q,handlers:use`di.torq.handlers,1,1,load the real di.torq.handlers module -before,0,0,q,ct:use`di.clienttracking,1,1,load di.clienttracking module -before,0,0,q,logger:use`di.util.log,1,1,load the real di.util.log module -before,0,0,q,logdep:logger.logdict`log,1,1,di.util.log's info..fatal level dict (superset of info/warn/error) -before,0,0,q,handlers.init[enlist[`log]!enlist logdep],1,1,init di.torq.handlers with the real di.util.log -before,0,0,q,"hdep:`register`remove`list!(handlers.register;handlers.remove;handlers.list)",1,1,build the handlers injectable dict -before,0,0,q,"deps:`log`handlers!(logdep;hdep)",1,1,the standard deps dict -before,0,0,q,.ct.c:{enlist[`clienttracking]!enlist x},1,1,helper - wrap a settings dict under the module's config section -before,0,0,q,"ct.init[()!();deps]",1,1,init di.clienttracking with an empty config and the real log + handlers deps - -comment,,,,,,,init - signature and dependency validation -true,0,0,q,2=count (value ct.init) 1,1,1,init is init[config;deps] - a one-arg call would return a projection silently -fail,0,0,q,"ct.init[()!();(::)]",1,1,init rejects a non-dict deps -fail,0,0,q,"ct.init[()!();()!()]",1,1,init rejects missing log key -fail,0,0,q,"ct.init[()!();enlist[`log]!enlist 42]",1,1,init rejects a non-dict log value -fail,0,0,q,"ct.init[()!();enlist[`log]!enlist `info`warn!(logdep`info;logdep`warn)]",1,1,init rejects a log dict missing the error key -fail,0,0,q,"ct.init[()!();enlist[`log]!enlist logdep]",1,1,init rejects missing handlers key -fail,0,0,q,"ct.init[()!();`log`handlers!(logdep;42)]",1,1,init rejects a non-dict handlers value -fail,0,0,q,"ct.init[()!();`log`handlers!(logdep;enlist[`register]!enlist{})]",1,1,init rejects a handlers dict missing remove/list keys -run,0,0,q,".ct.errstr:@[{ct.init[()!();(::)]};(::);{x}]",1,1,capture the error string from a bad init -true,0,0,q,.ct.errstr like "di.clienttracking:*",1,1,init error is prefixed di.clienttracking: -run,0,0,q,"ct.init[()!();`log`handlers`timer!(logdep;hdep;42)]",1,1,init accepts and ignores other injectables di.torq passes (timer/servers) - -comment,,,,,,,init - config section validation -fail,0,0,q,"ct.init[(::);deps]",1,1,init rejects a non-dict config -fail,0,0,q,"ct.init[enlist[`clienttracking]!enlist 42;deps]",1,1,init rejects a non-dict clienttracking section -fail,0,0,q,"ct.init[.ct.c enlist[`maxidle]!enlist 5;deps]",1,1,init rejects a non-timespan maxidle -fail,0,0,q,"ct.init[.ct.c enlist[`retain]!enlist 5;deps]",1,1,init rejects a non-timespan retain -fail,0,0,q,"ct.init[.ct.c enlist[`trackusage]!enlist 1;deps]",1,1,init rejects a non-boolean trackusage -fail,0,0,q,"ct.init[.ct.c enlist[`enabled]!enlist 1;deps]",1,1,init rejects a non-boolean enabled -run,0,0,q,"ct.init[()!();deps]",1,1,re-init cleanly for the remaining tests - -comment,,,,,,,init - an absent config section means every default and every key reaches module state -true,0,0,q,"all (key .m.di.0clienttracking.configdefaults) in key .m.di.0clienttracking",1,1,every config key reached module state -true,0,0,q,.m.di.0clienttracking.enabled,1,1,enabled defaults to 1b (TorQ's .clients.enabled) -true,0,0,q,0D~.m.di.0clienttracking.maxidle,1,1,maxidle defaults to 0D - idle reaping OFF (TorQ's config/settings/default.q MAXIDLE) -true,0,0,q,0D02:00:00~.m.di.0clienttracking.retain,1,1,retain defaults to 2 hours (TorQ's config/settings/default.q RETAIN) -true,0,0,q,.m.di.0clienttracking.trackusage,1,1,trackusage defaults to 1b (TorQ's opencloseonly:0b) -run,0,0,q,"ct.init[.ct.c `maxidle`retain!(0D01:00:00;0D00:00:30);deps]",1,1,re-init with an explicit section -true,0,0,q,0D01:00:00~.m.di.0clienttracking.maxidle,1,1,a section value overrides the maxidle default -true,0,0,q,0D00:00:30~.m.di.0clienttracking.retain,1,1,a section value overrides the retain default -run,0,0,q,"ct.init[.ct.c enlist[`unknownkey]!enlist 1;deps]",1,1,an unrecognised section key is ignored rather than rejected -run,0,0,q,"ct.init[()!();deps]",1,1,restore the defaults for the remaining tests - -comment,,,,,,,idle reaping is suspended (with a warning) until the usage watcher is live - lastp cannot advance otherwise -before,0,0,q,"warns:([]ctx:`symbol$();msg:())",1,1,capture table for warn-level log calls -before,0,0,q,"caplog:logdep,enlist[`warn]!enlist {[c;m] `warns insert (c;m)}",1,1,a logger whose warn captures into the table -run,0,0,q,"ct.init[.ct.c `maxidle`trackusage!(0D00:15:00;0b);`log`handlers!(caplog;hdep)]",1,1,init with reaping on and usage counting off -true,0,0,q,"0szbefore+(-22!4)",1,1,recorded bytes reflect the wrapped (post-transform) result not the bare exec result -true,0,0,q,"(first exec sz from ct.getclients[] where w=0i,null endp)=szbefore+(-22!`wrapped`payload!(1b;4))",1,1,recorded bytes equal the serialised size of exactly what the caller received -run,0,0,q,handlers.remove[`.z.pg;`transform;`envelope],1,1,remove the transform handler again - -comment,,,,,,,re-init preserves the existing session table (first-init guard) -run,0,0,q,ct.addclient[7007i],1,1,record a client before re-init -run,0,0,q,"ct.init[()!();deps]",1,1,re-init the module -true,0,0,q,"1=count select from ct.getclients[] where w=7007i,null endp",1,1,the existing session survived the re-init -true,0,0,q,1=count select from handlers.list[`.z.po] where name=`clienttracking,1,1,re-init reclaimed the observer in place rather than registering a second one - -comment,,,,,,,re-init with trackusage:0b removes the usage post-handlers -run,0,0,q,"ct.init[.ct.c enlist[`trackusage]!enlist 0b;deps]",1,1,re-init with usage tracking disabled -true,0,0,q,0=count select from handlers.list[`.z.pg] where name=`clienttracking,1,1,usage post handler removed on re-init -true,0,0,q,`clienttracking in exec name from handlers.list[`.z.po],1,1,the lifecycle observers stay registered with usage off -run,0,0,q,"ct.init[()!();deps]",1,1,restore the default init for the remaining tests -true,0,0,q,`clienttracking in exec name from handlers.list[`.z.pg] where phase=`post,1,1,usage post handler comes back on a default re-init - -comment,,,,,,,re-init with enabled:0b unhooks everything and a later default re-init hooks it all back -run,0,0,q,"ct.init[.ct.c enlist[`enabled]!enlist 0b;deps]",1,1,re-init disabled -true,0,0,q,not .m.di.0clienttracking.enabled,1,1,enabled reached module state as 0b -true,0,0,q,0=count select from handlers.list[`.z.po] where name=`clienttracking,1,1,disabled init removed the .z.po observer -true,0,0,q,0=count select from handlers.list[`.z.pc] where name=`clienttracking,1,1,disabled init removed the .z.pc observer -true,0,0,q,0=count select from handlers.list[`.z.pg] where name=`clienttracking,1,1,disabled init removed the usage post handler -true,0,0,q,"1=count select from ct.getclients[] where w=7007i,null endp",1,1,the session table is left intact when disabled -run,0,0,q,"ct.init[()!();deps]",1,1,re-init enabled again -true,0,0,q,`clienttracking in exec name from handlers.list[`.z.po],1,1,observers registered again after re-enabling -true,0,0,q,`clienttracking in exec name from handlers.list[`.z.pg] where phase=`post,1,1,usage post handler registered again after re-enabling - -comment,,,,,,,api metadata - callable exports documented and plumbing omitted -true,0,0,q,"(asc (key ct) except `init`getapimeta`version)~asc exec name from ct.getapimeta[]",1,1,getapimeta documents exactly the callable exports (plumbing/version omitted) -true,0,0,q,not any `init`getapimeta`version in exec name from ct.getapimeta[],1,1,framework plumbing/version is not registered in the api -true,0,0,q,`name`public`descrip`params`return~cols ct.getapimeta[],1,1,getapimeta rows carry the registry columns +before,0,0,q,ct:use`di.clienttracking,1,,load module +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 +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 + +comment,,,,,,,connection lifecycle +run,0,0,q,ha:peer PORTS`a,1,,connect to the default peer +true,0,0,q,"1=ha""count select from .clients.clients where w=.z.w""",1,,a connection adds a row +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 + +comment,,,,,,,usage +run,0,0,q,"n0:mine[ha;""hits""]; ha""1+1""; n1:mine[ha;""hits""]",1,,two sync queries +true,0,0,q,n1=n0+2i,1,,each sync query counts a hit +run,0,0,q,"s0:mine[ha;""sz""]; neg[ha]""til 10""; s1:mine[ha;""sz""]",1,,an async query between two reads +true,0,0,q,s1=s0+(-22!s0)+-22!til 10,1,,sz counts the bytes of sync and async results +run,0,0,q,"e0:mine[ha;""errs""]; n0:mine[ha;""hits""]; r:@[ha;""1+`a"";::]; e1:mine[ha;""errs""]; n1:mine[ha;""hits""]",1,,a failing query +true,0,0,q,"r~""type""",1,,the error reaches the client +true,0,0,q,(e1=e0+1i) and n1=n0+3i,1,,a failing query counts an error and a hit + +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 + +comment,,,,,,,opencloseonly +run,0,0,q,"hbb:peer PORTS`b; hbb""1+1""; hbb""1+1""",1,,connect and query the opencloseonly peer +true,0,0,q,"1=hbb""count select from .clients.clients where w=.z.w""",1,,connections are still recorded +true,0,0,q,"0i=mine[hbb;""hits""]",1,,queries are not counted + +comment,,,,,,,disabled +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 +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 + +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 +run,0,0,q,hclose hd3; hd4:peer PORTS`d,1,,close a connection normally +true,0,0,q,"1=hd4""count select from .clients.clients where null w,not null endp""",1,,a closed row is kept within RETAIN +run,0,0,q,"system ""sleep 1.5""; hd5:peer PORTS`d",1,,wait past RETAIN then connect again +true,0,0,q,"0=hd5""count select from .clients.clients where null w""",1,,closed rows are purged after RETAIN + +after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/clienttracking/test.q b/di/clienttracking/test.q new file mode 100644 index 00000000..dd2f56b6 --- /dev/null +++ b/di/clienttracking/test.q @@ -0,0 +1,29 @@ +/ test helpers: server peers running di.clienttracking under different settings + +FIXDIR:"/tmp/dictracktest" +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:05; while[(.z.p/dev/null 2>&1 &"}'[key PORTS;value PORTS]; + if[not all waitlisten each value PORTS;'"test: peers failed to listen"]; + } + +/ one field of this connection's row on the server +mine:{[h;c] h"exec first ",c," from .clients.clients where w=.z.w"} + +teardownfixture:{[] {@[{h:peer x;(neg h)"exit 0";(neg h)[]};x;()]} each value PORTS; system "sleep 0.3"; system "rm -rf ",FIXDIR;} diff --git a/di/clienttracking/test_integration.csv b/di/clienttracking/test_integration.csv deleted file mode 100644 index a2a624f5..00000000 --- a/di/clienttracking/test_integration.csv +++ /dev/null @@ -1,82 +0,0 @@ -action,ms,bytes,lang,code,repeat,minver,comment -comment,,,,,,,integration test - exercises the idle-reap branch (force-close + endp stamp) on a REAL live handle -comment,,,,,,,this is the one path the hermetic suite cannot cover - it needs a handle actually in .z.W -comment,,,,,,,stands up a child q server, tracks the outgoing handle to it, then reaps it as idle -comment,,,,,,,requires a q binary via QHOME (or q on PATH); skips cleanly if the child never comes up -comment,,,,,,,child self-exits when its connection drops and is also killed by PID - robust to mid-suite failure - -before,0,0,q,handlers:use`di.torq.handlers,1,1,load di.torq.handlers -before,0,0,q,ct:use`di.clienttracking,1,1,load di.clienttracking -before,0,0,q,logger:use`di.util.log,1,1,load the real di.util.log -before,0,0,q,logdep:logger.logdict`log,1,1,di.util.log level dict -before,0,0,q,handlers.init[enlist[`log]!enlist logdep],1,1,init di.torq.handlers -before,0,0,q,"hdep:`register`remove`list!(handlers.register;handlers.remove;handlers.list)",1,1,handlers injectable -before,0,0,q,"deps:`log`handlers!(logdep;hdep)",1,1,the standard deps dict -before,0,0,q,"ct.init[()!();deps]",1,1,init di.clienttracking with default settings -before,0,0,q,qcands:$[count qh:getenv[`QHOME];(raze(qh;"/bin/q");raze(qh;"/";string .z.o;"/q"));()],1,1,candidate q binary locations -before,0,0,q,qbin:$[count ex:qcands where {not ()~key hsym `$x} each qcands;first ex;"q"],1,1,pick an existing binary else q on PATH -before,0,0,q,.it.wait:{[p;n] $[n<=0;0Ni;not null h:@[{hopen(`$"" sv (":localhost:";string x);500)};p;0Ni];h;[system"sleep 0.3";.it.wait[p;n-1]]]},1,1,poll for the child to accept -before,0,0,q,.it.spawn:{[qbin;n] if[n<=0;:(0Ni;0N;0N)];system"p 0W";p:system"p";system"p 0";pid:"J"$last system "" sv (qbin;" -q -p ";string p;" /dev/null 2>&1 & echo $!");h:.it.wait[p;20];ok:$[null h;0b;pid=@[h;".z.i";{0N}]];$[ok;(h;pid;p);[if[not null h;@[hclose;h;::]];@[{system "" sv ("kill -9 ";string pid)};::;{}];.it.spawn[qbin;n-1]]]},1,1,bind a free port and confirm via PID we reached our own child (retries past a stolen port) -before,0,0,q,sp:.it.spawn[qbin;5],1,1,spawn the child with up to five attempts -before,0,0,q,h:sp 0,1,1,the confirmed outgoing handle to the child -before,0,0,q,cpid:sp 1,1,1,the confirmed child PID -before,0,0,q,if[null h;exit 0],1,1,skip cleanly if no confirmed child came up -before,0,0,q,@[{h ".z.pc:{exit 0}"};::;{x}],1,1,backstop - child self-exits when its connection drops -before,0,0,q,roundtrip:@[{4=h"2+2"};::;{0b}],1,1,a real synchronous round-trip works -comment,,,,,,,inbound leg - the CHILD hosts a second instance of the module and THIS process is its real client -comment,,,,,,,(the child services its event loop between our calls; this process cannot - a dial-back would deadlock in a sync wait) -before,0,0,q,"cinit:@[{h ""hz:use`di.torq.handlers;lg:use`di.util.log;hz[`init][lg`logdict];ct:use`di.clienttracking"";1b};::;{0b}]",1,1,load handlers/log/clienttracking in the child over IPC -before,0,0,q,"cinit2:@[{h ""ct[`init][()!();`log`handlers!(lg[`logdict]`log;`register`remove`list!(hz`register;hz`remove;hz`list))]"";1b};::;{0b}]",1,1,init the child's instance with default settings -before,0,0,q,"cowner:@[{h ""hz[`register][`.z.pg;`exec;`owner;0;{value x}];ct[`enableusage][]"";1b};::;{0b}]",1,1,give the child's .z.pg an exec owner so its usage watcher goes live -before,0,0,q,"@[{h ""ct[`addclient][.z.w]""};::;{x}]",1,1,our handle predates the child's init so register it there by hand (.z.w is our handle on the child) -before,0,0,q,"h2:@[hopen;hsym `$"":localhost:"",string sp 2;0Ni]",1,1,a second connection - a REAL .z.po on the child -before,0,0,q,"crows:@[{h ""select w,ipa,u,hits from ct[`getclients][] where null endp""};::;{0#([]w:`int$();ipa:`symbol$();u:`symbol$();hits:`long$())}]",1,1,the child's open sessions as it sees them -before,0,0,q,"cmaxidle:@[{h ""ct[`init][enlist[`clienttracking]!enlist enlist[`maxidle]!enlist 0D00:00:00.000000001;`log`handlers!(lg[`logdict]`log;`register`remove`list!(hz`register;hz`remove;hz`list))]"";1b};::;{0b}]",1,1,re-init the child's instance with a 1ns idle threshold - every session there is now idle -before,0,0,q,system"sleep 0.2",1,1,let time pass beyond the idle threshold -before,0,0,q,"selfreap:@[{(::)~h ""ct[`cleanup][]""};::;{0b}]",1,1,call cleanup[] on the child over our own (idle) handle - it must not be closed under us -before,0,0,q,"stillopen:@[{h ""1=count select from ct[`getclients][] where w=.z.w,null endp""};::;{0b}]",1,1,our session on the child is still open after that sweep -before,0,0,q,"h2reaped:@[{h ""not null first exec endp from ct[`getclients][] where w<>.z.w,w>0i""};::;{0b}]",1,1,the other (genuinely idle) session was reaped by that same sweep -before,0,0,q,"h2closed:@[{h ""not any (exec w from ct[`getclients][] where w<>.z.w,w>0i) in key .z.W""};::;{0b}]",1,1,and the child really did hclose it - that handle is gone from the child's .z.W -before,0,0,q,"@[hclose;h2;::]",1,1,tidy the second handle either way -comment,,,,,,,outbound leg - the idle-reap branch on the real outgoing handle -before,0,0,q,"ct.init[enlist[`clienttracking]!enlist enlist[`maxidle]!enlist 0D00:00:00.000000001;deps]",1,1,re-init this process's instance with a 1ns idle threshold - but nothing owns .z.pg here yet -before,0,0,q,ct.addclient[h],1,1,track the real live outbound handle -before,0,0,q,system"sleep 0.2",1,1,let time pass beyond the idle threshold -before,0,0,q,ct.cleanup[],1,1,sweep while usage counting is NOT live - the idle-reap branch must be suspended -before,0,0,q,"suspended:(h in key .z.W) and 050.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 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. + +## `.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`. + +- `.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 41993ffd..16b1f328 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -121,9 +121,104 @@ setsubtables`; initialized:0b; -init:{ +init:{[deps] + 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; if[count tabcols;.z.m.initialized:1b]; }; + +/ .stpps, .u.sub, .ps +\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..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 @@ -114,5 +114,31 @@ 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,,,,,,,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 +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 +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 +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,,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 +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 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/_` — 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 `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 + +| Name | What | +|---|---| +| `tptype` | `` `chained `` | +| `tablelist[]` | the published tables (`.stpps.t`) | +| `.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 | +| `.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[]`: 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). + +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. +- End of day follows the rdb/wdb convention: `endofday[d]` in, `` (`endofday;d) `` out. +- 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 +subscribers replay chainedtp's own log; otherwise `` ` `` and 0. Plain `.u.sub` subscribers are served +by `di.pubsub`. + +## 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 (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/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 2b562174..fce9f4fb 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -1,476 +1,161 @@ -/ 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} + +.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 + +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 + } + +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]; + } + +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;()]])@\:(`endofday;d) + } + +\d . + +endofday:{[d] .u.end d} -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")); - }; 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..930ec5ac 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -1,78 +1,84 @@ 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 .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 +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,,,,,,,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,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,"`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,,,,,,,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,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 -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:.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,,,,,,,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,,,,,,,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 -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..5557083a 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -1,603 +1,47 @@ -/ 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 (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)}) +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";"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"); + } + +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;sh); 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 - }; 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..17344598 --- /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}]; + } \ No newline at end of file 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..ae15c411 --- /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 \ No newline at end of file diff --git a/di/torq/proc/discovery/test.q b/di/torq/proc/discovery/test.q new file mode 100644 index 00000000..42ea6079 --- /dev/null +++ b/di/torq/proc/discovery/test.q @@ -0,0 +1,65 @@ +/ 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)}); + +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/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/VERSION b/di/torq/servers/VERSION index 9325c3cc..8ea2ddfc 100644 --- a/di/torq/servers/VERSION +++ b/di/torq/servers/VERSION @@ -1 +1,2 @@ -0.3.0 \ No newline at end of file +0.5.0 + diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index 3cbc748c..9400ddc3 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -1,23 +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`), 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`. - -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 root names (`.servers.*`, +`.dotz.liveh*`); the registry and settings are 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, 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. +`init[deps]` takes the injectables and this process's config in one dict (di.torq merges them). +It sets the `.servers.*` globals, publishes the 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: @@ -26,14 +19,36 @@ 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 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 | +|---|---|---| +| `enabled` | `.servers.enabled` | `1b` — gates the `discoveryretry`/`serversretry` timer jobs | +| `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,89 +57,114 @@ 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. | +| `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`. | -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 -```q -SERVERS:([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$()) -``` - -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. - -## `.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: +Legacy's `.servers.SERVERS` (l.10), at that root name: ```q -(handlers[`register])[`.z.pc;`;`servers;0j;pcfunc] +.servers.SERVERS:([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$();attributes:()) ``` -`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. - -## 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`). +`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 | + +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`. + +**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]`, mode 3 (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`. +- `.proc.getconfigfile` becomes `nontorqprocessfile`. +- In `startupdepcyclestypename`, `.servers.startup[]` becomes `.servers.startup ()!()` (the stored + globals), `.proc.procname` becomes init's identity, and `.os.sleep` becomes `system "sleep "`. +- 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`); +- `getserverbytype`/`gethpbytype`; +- `names`/`types`/`unregistered`/`checkw`/`reset`; +- the `addprocscustom` hook; +- `refreshattributes`; +- `reqproctypesnotconn`/`startupdepcycles`/`startupdependent`. + +**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`. +- With `connectionsfromdiscovery` on (off by default), `startup` dials only discovery rows and + learns the rest from 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` (54 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`; +- the root `.servers` functions (`attributematch`, 5-arg `getservers`, `startupdepnamecycles`); +- input validation and `getapimeta`. + +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 k4unit.moduletest`di.torq.servers -``` +``` \ No newline at end of file diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 5d7dcb21..f14a8f00 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -1,36 +1,29 @@ -/ 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. -/ 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 - connection management; registry, config and protocol functions at root .servers.*. See servers.md / --- 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 -/ 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; +/ 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;`); + (`.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 @@ -40,11 +33,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, 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. + / 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; @@ -67,39 +56,35 @@ 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;""]; + / registry + @[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; + 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}]; + 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;()!()]; + / .z.pc + (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pc]; + / 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;()!()]]]; .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]]; + 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 +98,171 @@ 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] + 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]]; + 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; + 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:{$[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; + if[count connectedrows:select from`.servers.SERVERS where i in rows,.dotz.liveh0 w; + .servers.connectcustom[connectedrows]]} -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; + if[connect; + $[`discovery=proc;retrydiscovery[];retry[]]]}; + +/ 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,()]; + 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]} + +/ 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"]; :()]; + 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]; + res:select from connectiontab where not ([]procname;proctype;hpup) in select procname,proctype,hpup from .servers.SERVERS; + 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]]; + 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:{[] + notwin:not .z.o like "w*"; + 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; + 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; + ]; + 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 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]; + .servers.procstab:procs:formatprocs readprocesscsv pf; + .servers.nontorqprocesstab:formatprocs $[count key .servers.NONTORQPROCESSFILE;readprocesscsv 1_string .servers.NONTORQPROCESSFILE;0#procs]; + 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)]]; + 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[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]]; + 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 +275,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] @@ -209,18 +297,14 @@ 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. - / 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)"]]; 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.ptype 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 . \ No newline at end of file diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 117ad8c7..cff12a65 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -13,13 +13,17 @@ 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 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 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 -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,14 +33,31 @@ 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,".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 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 +run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - the discovery row is registered dead +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,,,,,,,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 @@ -45,4 +66,4 @@ fail,0,0,q,"svc.init[`log`timer`handlers`proctype`procname!(mocklog;mocktimer;mo true,0,0,q,(asc (key svc) except `init`getapimeta)~asc exec name from svc.getapimeta[],1,1,getapimeta documents exactly the callable exports (plumbing omitted) true,0,0,q,not any `init`getapimeta in exec name from svc.getapimeta[],1,1,getapimeta omits plumbing (init/getapimeta not registered) true,0,0,q,`name`public`descrip`params`return~cols svc.getapimeta[],1,1,getapimeta rows carry the registry columns -after,0,0,q,teardownfixture[],1,1,kill the peer and remove the fixture dir +after,0,0,q,teardownfixture[],1,1,kill the peer and remove the fixture dir \ No newline at end of file diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 0b1b2a8b..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:()); @@ -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-> @@ -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"; @@ -64,7 +65,32 @@ setupfixture:{[] "localhost,",string[DEADPORT],",deadproc,deadinst"); }; -teardownfixture:{[] killpeer[]; system "rm -rf ",FIXDIR;}; +teardownfixture:{[] killpeer[]; killdisc[]; system "rm -rf ",FIXDIR;}; + +/ --- discovery-later fixture: a discovery stub naming one tpproc peer, started after startup --- +DISCPORT:0N; TPPORT:0N; DISCPIDS:`long$(); + +/ 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; + TPPORT::pickport DISCPORT+1; + (`$":",FIXDIR,"/process.csv") 0: (read0 `$":",FIXDIR,"/process.csv"),enlist "localhost,",string[DISCPORT],",discovery,discinst"; + (`$":",FIXDIR,"/disc.q") 0: ( + "register:{}"; + "getservices:{[p;s] ([]procname:enlist`tpinst;proctype:enlist`tpproc;hpup:enlist`$\":localhost:",string[TPPORT],"\";attributes:enlist()!())}"); + }; + +spawnq:{[args;port] + system QBIN," ",args," -p ",string[port]," -q /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. -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/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/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/settings/default.q b/di/torq/settings/default.q index 09f96f7f..fc24ba06 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1 +1,23 @@ -/ built-in framework defaults - empty for v0 +/ 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 + +/ 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 + +/ server records +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 \ No newline at end of file diff --git a/di/torq/settings/discovery.q b/di/torq/settings/discovery.q new file mode 100644 index 00000000..3749fad3 --- /dev/null +++ b/di/torq/settings/discovery.q @@ -0,0 +1,23 @@ +/ discovery service settings +/ 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 +/ whether the retry timers run; off, since retry and discoveryretry below are already 0 +enabled:0b +/ 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 \ No newline at end of file diff --git a/di/torq/settings/hdb.q b/di/torq/settings/hdb.q index 8369fe78..af766f0f 100644 --- a/di/torq/settings/hdb.q +++ b/di/torq/settings/hdb.q @@ -1 +1,3 @@ dir:`:hdb +/ create connections +startup:1b \ No newline at end of file diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q new file mode 100644 index 00000000..38b6064c --- /dev/null +++ b/di/torq/settings/segmentedtp.q @@ -0,0 +1,3 @@ +/ 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/tickerplant.q b/di/torq/settings/tickerplant.q new file mode 100644 index 00000000..38b6064c --- /dev/null +++ b/di/torq/settings/tickerplant.q @@ -0,0 +1,3 @@ +/ 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/test.csv b/di/torq/test.csv index 578b8f71..acabc0e7 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -13,8 +13,24 @@ 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 +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,.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 +true,0,0,q,"(1;1)~(HITS;UPD)",1,,skips client tracking (zpsignore) and still runs +run,0,0,q,.z.ps (`.u.upd;`trade;()),1,,a .u.upd async message +true,0,0,q,"(1;2)~(HITS;UPD)",1,,also skips client tracking +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,"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 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 diff --git a/di/torq/torq.md b/di/torq/torq.md index b2a7438c..c3bae0ce 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -157,7 +157,8 @@ an extra call after `init` that hdb processes don't. Skipped entirely if > ⚠️ **Known limitation — read this before adding anything that binds `.z.*`.** Query logging wraps the `.z.*` handlers > by **direct assignment**, because that is how `di.querylog` (used unmodified from kdbx-modules > `main`) works; it does not register through `di.torq.handlers`. `di.torq.init` therefore wires it -> **last**, after the process module and app code have bound their handlers. That works today +> after the process module, app code and client tracking have bound their handlers, and before +> zpsignore (see below). That works today > because no built-in process type owns `.z.pg` or `.z.ps`. > > **If anything claims a phased event's `exec` after startup, logging for that event silently drops @@ -209,6 +210,35 @@ flushinterval = 1800 # seconds between flushes (a job on the injected timer - **Differences from TorQ's `.usage`:** off by default (TorQ turns it on), no `proctype`/`procname` columns, `.z.pi` not logged, and no daily disk-log roll. +### Client tracking and zpsignore + +`di.torq.init` binds `.z.*` in this order, each step wrapping whatever the step before it left: + +1. `di.clienttracking` runs on **every** process: `.clients.clients` gets a row per inbound + connection. Unless `clients.opencloseonly` is set, `.z.pg`, `.z.ps` and `.z.ws` are wrapped to + count queries, errors and bytes. The only switch is the module's own `clients` section + (`enabled`, `opencloseonly`, ...; see `di/clienttracking/clienttracking.md`). +2. Query logging, if on (above). +3. **zpsignore**: `.z.ps` is wrapped once more, outermost. An async message whose head is in the + ignorelist runs with `value` and skips every wrapper beneath it. By default those heads are + `` `upd ``, `` `.u.upd `` and their string forms, which covers the `` (`upd;t;x) `` stream into + chainedtp, rdb and wdb. querylog already filters these heads itself, so in practice zpsignore + keeps ticks out of client tracking. The check is `first` of the message, so a message sent as a + string (`"upd[...]"`) is **not** skipped: its first element is a character. + +```toml +[zpsignore] +enabled = true # default true +ignorelist = ["upd", ".u.upd"] # default; each name matches its symbol and string head +``` + +Both run once per process; a second `di.torq.init` skips them. The builtin `tickerplant` and +`segmentedtp` settings set `clients` `opencloseonly` to true and `zpsignore` `enabled` to false, +so a tickerplant records connections only and its `.z.ps` stays unwrapped. An app `clients` +section **replaces the whole builtin section, not just the keys it sets**. An app that adds +`[clients]` to a tickerplant for any reason (to change `RETAIN`, say) must restate +`opencloseonly = true`, or the tickerplant's publish path goes back through client tracking. + ## Usage ```q diff --git a/di/torq/torq.q b/di/torq/torq.q index 4ace6fa4..e676b63f 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`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`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.wdb +builtin:`hdb`tickerplant`rdb`wdb`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`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.wdb`di.torq.proc.discovery reqenv:{[e] v:getenv e; @@ -183,11 +183,15 @@ runhook:{[proctype;overrides] if[`run in key ns;(get `$".",(string proctype),".run")[]]; } +/ client tracking, every process +clientswired:0b +initclients:{[config;deps] if[.z.m.clientswired;:()]; ((use`di.clienttracking)`init)[config;deps]; .z.m.clientswired:1b;} + / --- optional query logging --------------------------------------------------------------- / Wires di.querylog (kdbx-modules main, consumed unmodified) behind a [querylog] settings section - a silent / no-op unless enabled=true, same convention as di.torq.logroll. di.querylog wraps the .z.* handlers by DIRECT -/ assignment, not through di.torq.handlers, so init calls this LAST - after the process module and app code -/ have bound theirs. KNOWN LIMITATION (torq.md "Query logging"): an exec owner claimed on .z.pg/.z.ps/etc. +/ assignment, not through di.torq.handlers, so init calls this after the process module and app code +/ have bound theirs, and before zpsignore. KNOWN LIMITATION (torq.md "Query logging"): an exec owner claimed on .z.pg/.z.ps/etc. / AFTER this - e.g. a later permissions/auth layer - silently replaces the wrapper; that event's logging / drops to zero with no error. querylogwired:0b @@ -232,6 +236,16 @@ initquerylog:{[config;deps] deps[`log][`info][`torq;msg," - di.querylog wraps .z.* directly; see torq.md Query logging"]; } +/ zpsignore: ignorelisted async messages skip the .z.ps wrappers +zpsignorewired:0b +initzpsignore:{[config] + if[.z.m.zpsignorewired;:()]; + s:$[`zpsignore in key config;config`zpsignore;()!()]; + if[$[`enabled in key s;`boolean$s`enabled;1b]; + .z.ps:{[il;f;y] $[any first[y]~/:il;value y;f y]}[qlignore $[`ignorelist in key s;s`ignorelist;`upd`.u.upd];@[value;`.z.ps;{value}]]]; + .z.m.zpsignorewired:1b; + } + / reserved launcher/identity flags parsed from the command line - consumed by the launcher and by / di.torq itself (identity, stack id, port, norun), NOT config settings. Everything else on the / command line is a candidate config override. @@ -295,9 +309,16 @@ 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]; + / .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 / di.querylog wraps whatever is bound at this moment by direct assignment (see initquerylog / torq.md) initquerylog[config;deps]; + initzpsignore config; / post-load session audit (di.torq.depcheck.init): now that every module is loaded, introspect the live / session - core-dependency contract shapes (log/timer/handlers), .z.ts ownership, and an optional minimum / kdb-x engine version (config`minkdbxversion). Complements the pre-load VERSION graph above, which validated From 801983445eede8e9c105e3ee89c26f6763f03cab Mon Sep 17 00:00:00 2001 From: Dexter Date: Thu, 8 Oct 2026 11:39:29 +0800 Subject: [PATCH 04/15] di.torq.proc.wdb: init subscriptions only on the save path, and fix the suite di.subscriptions now requires a handlers dep, so wdb's init failed for every caller that did not pass one. A sort-mode wdb never subscribes - .z.m.subs is only read on the save path - so move the init below the sort-mode early return rather than widen wdb's required deps. Test fixture: - add a handlers mock to test.csv and test.q, needed on the save path - eodok/feedok took the sym column with `value`, which resolves symbols as variable names. select resolves the on-disk enum once the sym domain is loaded, so with sortworker peers the column arrives as plain symbols and the check threw 'aapl. Take the column as-is; distinct/differ handle both types. Suite goes from 7 failures to 71/71. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.csv | 3 ++- di/torq/proc/wdb/test.q | 10 +++++++--- di/torq/proc/wdb/wdb.q | 4 ++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index cef191a5..bc7949de 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -3,7 +3,8 @@ before,0,0,q,wdb:use`di.torq.proc.wdb,1,,load module before,0,0,q,mlog:`info`warn`error!(3#enlist {[c;m]}),1,,a minimal (dyadic) log dep dict before,0,0,q,mtimer:`addjob`deletejobs!(2#enlist {[x]}),1,,a minimal timer dep dict before,0,0,q,mservers:`startup`getservers`gethandlebytype`waitfortype!(4#enlist {[x]}),1,,a minimal servers dep dict -before,0,0,q,"alldeps:`log`timer`servers!(mlog;mtimer;mservers)",1,,every injected dep the wdb requires +before,0,0,q,"mhandlers:`register`remove`list!({[ev;ph;nm;pri;fn]};{[ev;ph;nm]};{[ev]})",1,,a minimal handlers dep dict - di.subscriptions requires it +before,0,0,q,"alldeps:`log`timer`servers`handlers!(mlog;mtimer;mservers;mhandlers)",1,,every injected dep the wdb requires before,0,0,q,"initerr:{[c] @[{[x] wdb.init[x;alldeps]};c;{x}]}",1,,run init for a config and return the error string fail,0,0,q,wdb.init[()!();()!()],1,,init without the log dependency must error diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 437a37c3..cfc4b8e1 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -19,7 +19,9 @@ servers:{[] `startup`getservers`gethandlebytype`waitfortype!( {[pt] ([]w:`int$(),$[pt in key PEERS;PEERS pt;()])}; {[pt;sel] TPH}; {[pt;t;p] TPUP})}; -recdeps:{[] `log`timer`servers!(reclog;`addjob`deletejobs!({[a;b;c;d;e;f]};{[x]});servers[])}; +/ handlers is required by di.subscriptions, which the wdb inits with its own deps +rechandlers:`register`remove`list!({[ev;ph;nm;pri;fn]};{[ev;ph;nm]};{[ev]}); +recdeps:{[] `log`timer`servers`handlers!(reclog;`addjob`deletejobs!({[a;b;c;d;e;f]};{[x]});servers[];rechandlers)}; starttp:{[] f:BASE,"/faketp.q"; @@ -68,7 +70,8 @@ eodok:{[c] feed[]; endofday today[]; t:select from get hdbpart`trade; - s:value t`sym; + / enum on disk, but select resolves it once the sym domain is loaded - take the column as-is + s:t`sym; chk `rows`psym`grouped`quote`wdbgone!( 8=count t; `p=attr (get hdbpart`trade)`sym; @@ -213,7 +216,8 @@ eodok:{[c] endofday today[]; if[`sort in key PEERS;(first PEERS`sort)""]; t:select from get hdbpart`trade; - s:value t`sym; + / enum on disk, but select resolves it once the sym domain is loaded - take the column as-is + s:t`sym; chk `rows`psym`grouped`quote`wdbgone!( 8=count t; `p=attr (get hdbpart`trade)`sym; diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index bd215e31..defbbe30 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -673,8 +673,6 @@ init:{[config;deps] / not in deps.toml: di.os has no VERSION, which fails depcheck .z.m.os:use`di.os; initdbwrite[config;deps]; - .z.m.subs:use`di.subscriptions; - (.z.m.subs`init)[config;deps]; .z.m.mrg:use`di.merge; (.z.m.mrg`init)[`log`mergebybytelimit!(deps`log;.z.m.mergebybytelimit)]; checksortparams[]; @@ -686,6 +684,8 @@ init:{[config;deps] .z.m.log[`info][`init;"initialised, mode=sort, savedir=",.z.m.savedirs,", hdbdir=",(1_string .z.m.hdbdir),", waiting to be called at .wdb.endofdaysort"]; :()]; + .z.m.subs:use`di.subscriptions; + (.z.m.subs`init)[config;deps]; .z.m.currentpartition:getpartition[]; (.z.m.os`mkdir) .z.m.savedir; clearwdbdata[]; From 562d15985e11b042f5cfb2ea1a687a1cfa5bcc46 Mon Sep 17 00:00:00 2001 From: Dexter Date: Thu, 8 Oct 2026 11:48:21 +0800 Subject: [PATCH 05/15] di.torq.proc.wdb: address the review findings tabsizes (wdb.q:62, wdb.q:122): tablelist[] orders by bytes from tabsizes, but only savetables populated it - savetablesbypart tracked partsizes instead. In a partitioned writedown every table therefore ordered on zero bytes and the largest was not flushed first. Track it in savetablesbypart too, and clear it at end of day in every mode, not just the default one. informgateway (wdb.q:229): an absent gateway is a normal deployment, and informgateway runs on every end-of-day reload, so it logged an error each time. Log it at info. movetohdb (wdb.q:381): the per-table branch logged each failed move and carried on, leaving tables split across the wdb and the hdb with no rollback and no signal. A multi-table move cannot be made atomic, so fail on the first error the way savetables does, and report a source directory left non-empty. Tests: tabsizestracked, tabsizescleared and nogatewayquiet - each verified to fail without the corresponding fix. Suite 74/74. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.csv | 5 +++++ di/torq/proc/wdb/test.q | 35 +++++++++++++++++++++++++++++++++++ di/torq/proc/wdb/wdb.q | 15 ++++++++++----- 3 files changed, 50 insertions(+), 5 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index bc7949de..4cf54a79 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -62,6 +62,11 @@ true,0,0,q,savemode`partbyattr,1,,a save-mode wdb hands a partbyattr day and its true,0,0,q,savemode`partbyfirstchar,1,,a save-mode wdb hands a partbyfirstchar day to the sort process true,0,0,q,handshake[],1,,with eodwaittime the hdb reloads async and calls back before the release true,0,0,q,syncreload[],1,,with eodwaittime 0 the reload is a sync call +comment,,,,,,,review fixes - tabsizes tracking and the absent-gateway log level +true,0,0,q,tabsizestracked[],1,,a partitioned writedown tracks tabsizes so tablelist flushes the largest table first +true,0,0,q,tabsizescleared[],1,,end of day clears tabsizes in a partitioned mode too +true,0,0,q,nogatewayquiet[],1,,no gateway is a normal state and must not log an error + run,0,0,q,stoptp[],1,,stop the fake tickerplant comment,,,,,,,sort mode - proctypes sort and sortworker diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index cfc4b8e1..10e03fbd 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -6,6 +6,10 @@ TPPORT:25961; chk:{[d] `LAST set d; all value d}; +/ module-local state and internals, for the checks that cannot go through the export dict +MOD:`.m.di.0torq.0proc.0wdb; +mv:{[n] get .Q.dd[MOD;n]}; + calls:([]lvl:`symbol$();ctx:`symbol$();msg:()); mocklogfn:{[lvl;ctx;msg] `calls upsert `lvl`ctx`msg!(lvl;ctx;msg);}; reclog:`info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;]); @@ -251,3 +255,34 @@ syncreload:{[] stoppeers[]; r }; + +/ tablelist[] orders by bytes from tabsizes, so a partitioned writedown must populate it too +tabsizestracked:{[] + freshwdb cfg[],`writedownmode`mergemode`numrows!(`partbyattr;`part;1); + feed[]; + (mv`savetodisk)[]; + ts:mv`tabsizes; + chk `populated`bothtables`bytespositive`largestfirst!( + 0 Date: Thu, 8 Oct 2026 12:00:50 +0800 Subject: [PATCH 06/15] di.torq.proc.wdb: close two gaps against legacy wdb Checked the module against TorQ 5.2.19 code/processes/wdb.q, code/wdb/{origstartup, writedown}.q, code/common/merge.q and config/settings/{wdb,sort,sortworker}.q. endofperiod: legacy defined a log-only stub in code/wdb/writedown.q and the port dropped it as STP-only. di.torq.proc.segmentedtp now exists and broadcasts end of period through di.pubsub.callendofperiod, which sends the (current;next;data) triple as ONE argument, so a subscriber without the callback fails the publish. Define it at root, monadic. getpartition: legacy exposed it as an overridable setting so a deployment could decide its own partition value; the port hard-coded it. Read it from config, defaulting to the built-in - the same pattern upd and savedownmanipulation use. Tests: getpartitionoverride and endofperiodcallback, both verified to fail without the fix. Suite 76/76. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.csv | 4 ++++ di/torq/proc/wdb/test.q | 17 +++++++++++++++++ di/torq/proc/wdb/wdb.md | 11 ++++++++++- di/torq/proc/wdb/wdb.q | 11 ++++++++++- 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 4cf54a79..9c8011d4 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -67,6 +67,10 @@ true,0,0,q,tabsizestracked[],1,,a partitioned writedown tracks tabsizes so table true,0,0,q,tabsizescleared[],1,,end of day clears tabsizes in a partitioned mode too true,0,0,q,nogatewayquiet[],1,,no gateway is a normal state and must not log an error +comment,,,,,,,parity with legacy wdb - overridable getpartition and the endofperiod callback +true,0,0,q,getpartitionoverride[],1,,a getpartition supplied in config replaces the built-in +true,0,0,q,endofperiodcallback[],1,,endofperiod exists at root and takes the triple as one argument + run,0,0,q,stoptp[],1,,stop the fake tickerplant comment,,,,,,,sort mode - proctypes sort and sortworker diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 10e03fbd..6f16df5a 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -286,3 +286,20 @@ nogatewayquiet:{[] endofday today[]; chk `noerror`saidso!(not loggedlike[`error;"*gateway*"];loggedlike[`info;"no gateway detected*"]) }; + +/ legacy exposed getpartition as an overridable setting, so a config value must win over the default +getpartitionoverride:{[] + freshwdb cfg[],(enlist`getpartition)!enlist {[] 2001.09.11}; + chk `used`notthedefault!(2001.09.11~(mv`getpartition)[];not 2001.09.11~(mv`defaultgetpartition)[]) + }; + +/ di.pubsub sends the (current;next;data) triple as one argument, so the callback must be monadic +endofperiodcallback:{[] + freshwdb cfg[]; + r:@[{get[`endofperiod] x};(2026.01.01D12:00;2026.01.01D13:00;`p`t!(2026.01.01D13:00;.z.p));{`$"ERR:",x}]; + chk `defined`atroot`monadic`logged!( + 100h=type get`endofperiod; + `endofperiod in key `.; + not 10h=type r; + loggedlike[`info;"received endofperiod*"]) + }; diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index 0f70edb7..6e6c9959 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -58,6 +58,7 @@ eodwaittime = 10 # seconds to wait for reload callbacks before permitreload = true # false: sort and move, but leave downstream alone # compression (optional) -> e.g. 17 2 6, applied (.z.zd) while sorting/merging, then reset to 16 0 0 # savedownmanipulation (optional, .q settings) -> table!function applied before each write +# getpartition (optional, .q settings) -> niladic function returning the partition value # upd (optional, .q settings) -> {[t;x]} the live upd, and the one the replay calls; default insert # postreplay (optional, .q settings) -> {[hdbdir;pt]} called after the move, before the reload # subscribeto / subscribesyms omitted -> all tables, all syms @@ -110,6 +111,14 @@ The writedown mode decides whether the idb mounts `savedir` or `savedir/ Date: Thu, 8 Oct 2026 12:12:02 +0800 Subject: [PATCH 07/15] di.subscriptions: install the default endofperiod callback there, not in the wdb The callback has to exist in the process that RECEIVES the publish. di.pubsub is the publisher half - it runs in the tickerplant and the wdb never loads it - so the default belongs with the subscriber half, which already owns root upd and the root table schemas. One place covers di.torq.proc.wdb, di.torq.proc.rdb and di.torq.proc.chainedtp; rdb had the same latent failure. Installed only when root endofperiod is not already defined, the rule chainedtp uses for upd, so a subscriber that forwards the roll downstream keeps its own. Tests: endofperioddefault (verified to fail without the install) and endofperiodnotclobbered. The wdb's endofperiodcallback now covers the same path through di.subscriptions. Suites 47/47 and 76/76. Co-Authored-By: Claude Opus 5 --- di/subscriptions/subscriptions.md | 13 +++++++++++++ di/subscriptions/subscriptions.q | 7 +++++++ di/subscriptions/test.csv | 4 ++++ di/subscriptions/test.q | 23 +++++++++++++++++++++++ di/torq/proc/wdb/wdb.md | 9 ++++----- di/torq/proc/wdb/wdb.q | 6 ------ 6 files changed, 51 insertions(+), 11 deletions(-) diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 95142638..506bc0db 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -53,6 +53,19 @@ 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.) +## Root `endofperiod` + +A segmented tickerplant (di.torq.proc.segmentedtp) broadcasts end of period through +`di.pubsub.callendofperiod`, which sends the `(current;next;data)` triple as a **single** +argument — not three. The subscribing process must have a root `endofperiod` or the publish +fails on this side, so `init` installs a monadic default that logs and returns. + +It is installed **only when root `endofperiod` is not already defined**, the same rule +di.torq.proc.chainedtp uses for `upd`. A subscriber with real work to do on a period roll — +forwarding downstream, for instance — defines its own before calling `init` and keeps it. +di.torq.proc.wdb and di.torq.proc.rdb both rely on the default: their partitions only advance +at end of day. + ## `.sub` A second subscription API at root `.sub`, in a `\d .sub` section at the end of `subscriptions.q`, with diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 30d15561..825f15a4 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -10,6 +10,11 @@ / reads the TP log file directly, same filesystem - the classic tick assumption). Not yet: / auto-reconnect/resubscribe, filtered-column subscriptions, remote-log streaming. +/ a segmented tickerplant broadcasts end of period through di.pubsub.callendofperiod, which sends +/ the (current;next;data) triple as ONE argument. Every subscriber needs the callback to exist or +/ the publish fails on this side; a subscriber that has real work to do defines its own. +endofperiod:{[x] .z.m.log[`info][`endofperiod;"received endofperiod, (current;next;data) is ",.Q.s1 x];} + / registry of active subscriptions - for health checks now, reconnect later. SUBSCRIPTIONS:([]handle:`int$();tabs:();syms:();subtime:`timestamp$()) @@ -25,6 +30,8 @@ init:{[config;deps] / .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]; + / as chainedtp does for upd, only install the default when the consumer has not defined its own + if[not `endofperiod in key `.;@[`.;`endofperiod;:;endofperiod]]; 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;()!()]]; diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index c31534b1..47f8eeaa 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -55,3 +55,7 @@ true,0,0,q,.sub.reconnectinit,1,,subscribe wrapped .servers.connectcustom for au 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 + +comment,,,,,,,endofperiod - the callback every subscriber needs for a segmented tickerplant +true,0,0,q,endofperioddefault[],1,,init installs a monadic root endofperiod when none is defined +true,0,0,q,endofperiodnotclobbered[],1,,a consumer's own endofperiod survives init and receives the triple diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index 7267302b..f2821ed9 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -80,3 +80,26 @@ pcclosecheck:{[] } teardownfixture:{[] @[{(neg x)"exit 0";(neg x)[]};tph;()]; system "sleep 0.3"; system "rm -rf ",BASE; } + +/ the (current;next;data) triple a segmented tp publishes, as di.pubsub sends it - one argument +EOPMSG:(2026.01.01D12:00;2026.01.01D13:00;`p`t!(2026.01.01D13:00;2026.01.01D12:59)); +dropeop:{[] if[`endofperiod in key `.;![`.;();0b;enlist`endofperiod]];}; + +/ di.pubsub.callendofperiod sends that triple as ONE argument, so every subscriber needs a monadic +/ root endofperiod or the publish fails on this side +endofperioddefault:{[] + dropeop[]; + sub.init[()!();deps[]]; + all(`endofperiod in key `.; + not 10h=type @[{get[`endofperiod] x};EOPMSG;{`$"ERR:",x}]) + }; + +/ a consumer that defines its own keeps it - the same rule chainedtp uses for upd +endofperiodnotclobbered:{[] + dropeop[]; + @[`.;`endofperiod;:;{[x] `EOPMARK set x;}]; + sub.init[()!();deps[]]; + @[`.;`EOPMARK;:;::]; + get[`endofperiod] EOPMSG; + EOPMSG~get`EOPMARK + }; diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index 6e6c9959..2ff8d553 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -113,11 +113,10 @@ of the process. ## End of period -A segmented tickerplant (di.torq.proc.segmentedtp) broadcasts end of period to its subscribers -through `di.pubsub.callendofperiod`, which sends the `(current;next;data)` triple as a **single** -argument. The wdb has nothing to do on a period roll — its partition only advances at end of day — -but the callback has to exist at root or the publish fails on the subscriber, so `setroot` defines -a monadic `endofperiod` that logs and returns. +A segmented tickerplant broadcasts end of period to its subscribers, and the callback has to exist +at root or the publish fails on this side. The wdb has nothing to do on a period roll — its +partition only advances at end of day — so it relies on the default `endofperiod` that +di.subscriptions installs. See di.subscriptions for the contract. ## RDB / WDB interaction diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 02289a98..2987d574 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -255,11 +255,6 @@ doreload:{[pt] flushend[]]; } -/ a segmented tickerplant broadcasts end of period to its subscribers through di.pubsub, which -/ sends the (current;next;data) triple as ONE argument - the wdb has nothing to do on a period -/ roll, but the callback has to exist or the publish fails -endofperiod:{[x] .z.m.log[`info][`endofperiod;"received endofperiod, (current;next;data) is ",.Q.s1 x];} - / set .z.zd to control how data gets compressed setcompression:{[compression] if[3=count compression; @@ -663,7 +658,6 @@ setroot:{[] @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; @[`.;`upd;:;.z.m.upd]; @[`.;`endofday;:;endofday]; - @[`.;`endofperiod;:;endofperiod]; set[`.u.end;endofday]; / the idb reads these at startup; currentpartition is republished at each end of day set[`.wdb.savedir;.z.m.savedir]; From c7521b2f83e92e9fd018d3d0f047dca046a653ea Mon Sep 17 00:00:00 2001 From: Dexter Date: Thu, 8 Oct 2026 12:36:16 +0800 Subject: [PATCH 08/15] Revert the endofperiod work - feature-segmentedtp owns it Dropped from this PR entirely: di/subscriptions is back to main, and the wdb keeps the stub stripped as the original port had it. upstream/feature-segmentedtp already defines endofperiod in both the rdb and the wdb, and that branch is where the segmented tickerplant work belongs. Two PRs editing di/subscriptions at once would only collide. getpartition and the review fixes are unaffected. Co-Authored-By: Claude Opus 5 --- di/email/manual_tests.q | 264 ++++++++++++++++++++++++++++++ di/subscriptions/subscriptions.md | 13 -- di/subscriptions/subscriptions.q | 7 - di/subscriptions/test.csv | 4 - di/subscriptions/test.q | 23 --- di/torq/proc/wdb/test.csv | 3 +- di/torq/proc/wdb/test.q | 10 -- di/torq/proc/wdb/wdb.md | 9 +- 8 files changed, 266 insertions(+), 67 deletions(-) create mode 100644 di/email/manual_tests.q diff --git a/di/email/manual_tests.q b/di/email/manual_tests.q new file mode 100644 index 00000000..8130e761 --- /dev/null +++ b/di/email/manual_tests.q @@ -0,0 +1,264 @@ +// ========================================================== +// di.email manual test script +// run in a q session after: email:use`di.email +// then call init with your smtp config before the send tests +// ========================================================== + +// helpers +chk:{[label;result] -1 ($[result;"PASS: ";"FAIL: "],label);}; +has:{$[10h=type x;0 tag"; has[t;"

"; "

"~-4#t]; + +h1:.m.di.0email.mailheading["1";"title"]; +chk["mailheading h1 opens"; "

"~-5#h1]; + +h3:.m.di.0email.mailheading["3";"small"]; +chk["mailheading h3 tag"; "

"~-5#h3]; + +b:.m.di.0email.mailbold "bold text"; +chk["mailbold opens "; ""; ""~-4#b]; + +i:.m.di.0email.mailitalic "italic text"; +chk["mailitalic opens "; ""; ""~-4#i]; + +chk["mailstring on string"; "hello"~.m.di.0email.mailstring "hello"]; +chk["mailstring on int"; has[.m.di.0email.mailstring 1;"1"]]; // "1" or "1i" depending on version +chk["mailstring on float"; "1.5"~.m.di.0email.mailstring 1.5]; +chk["mailstring on symbol"; "abc"~.m.di.0email.mailstring `abc]; + +// ========================================================== +// section 2: color and style helpers +// ========================================================== +-1 "\n--- section 2: color and style helpers ---"; + +ac:.m.di.0email.addcolor["red";"colored text"]; +chk["addcolor contains color:red"; has[ac;"color:red"]]; +chk["addcolor no font-size:px bug"; not has[ac;"font-size:px"]]; + +ms:.m.di.0email.mailsize["20";"sized text"]; +chk["mailsize contains font-size"; has[ms;"font-size:20px"]]; +chk["mailsize no spurious color"; not has[ms;"color:;"]]; + +bg:.m.di.0email.mailbgcolor["#ffff00";"highlighted"]; +chk["mailbgcolor sets background"; has[bg;"background-color:#ffff00"]]; + +mc:.m.di.0email.mailcolors["blue";"#eeeeee";"14";"full"]; +chk["mailcolors sets color"; has[mc;"color:blue"]]; +chk["mailcolors sets background"; has[mc;"background-color:#eeeeee"]]; +chk["mailcolors sets font-size"; has[mc;"font-size:14px"]]; +chk["mailcolors sets display"; has[mc;"display:inline"]]; + +// ========================================================== +// section 3: links and bookmarks +// ========================================================== +-1 "\n--- section 3: links and bookmarks ---"; + +u:.m.di.0email.mailurl["https://example.com";"click here"]; +chk["mailurl contains href"; has[u;"href=\"https://example.com\""]]; +chk["mailurl contains link text"; has[u;"click here"]]; +chk["mailurl uses tag"; has[u;""; ""~-4#u]; + +bm:.m.di.0email.setbookmark "section1"; +chk["setbookmark has name attr"; has[bm;"name=\"section1\""]]; + +gbm:.m.di.0email.getbookmark["section1";"go to section"]; +chk["getbookmark links to anchor"; has[gbm;"href=\"#section1\""]]; +chk["getbookmark has link text"; has[gbm;"go to section"]]; + +// ========================================================== +// section 4: tables and dicts +// ========================================================== +-1 "\n--- section 4: tables and dicts ---"; + +t:([]sym:`a`b`c;price:1.1 2.2 3.3;vol:100 200 300); + +mt:.m.di.0email.mailtable[t]; +chk["mailtable returns list"; 0h=type mt]; +chk["mailtable has

open"; has[first mt;"
close"; "
"~last mt]; +chk["mailtable has header row"; hasa[mt;" open"; any ""~/:tmpl]; +chk["template0 has close"; ""~last tmpl]; +chk["template0 has tag"; hasa[tmpl;""~/:tmpl; +chk["blank line after subject"; sepidx>subidx]; +chk["blank line before html"; sepidx0;(deps[`timer]`addjob)[`checksubscriptions;.sub.checksubscriptions;();`long$.sub.checksubscriptionperiod%0D00:00:01;1;()!()]]; diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index 47f8eeaa..c31534b1 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -55,7 +55,3 @@ true,0,0,q,.sub.reconnectinit,1,,subscribe wrapped .servers.connectcustom for au 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 - -comment,,,,,,,endofperiod - the callback every subscriber needs for a segmented tickerplant -true,0,0,q,endofperioddefault[],1,,init installs a monadic root endofperiod when none is defined -true,0,0,q,endofperiodnotclobbered[],1,,a consumer's own endofperiod survives init and receives the triple diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index f2821ed9..7267302b 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -80,26 +80,3 @@ pcclosecheck:{[] } teardownfixture:{[] @[{(neg x)"exit 0";(neg x)[]};tph;()]; system "sleep 0.3"; system "rm -rf ",BASE; } - -/ the (current;next;data) triple a segmented tp publishes, as di.pubsub sends it - one argument -EOPMSG:(2026.01.01D12:00;2026.01.01D13:00;`p`t!(2026.01.01D13:00;2026.01.01D12:59)); -dropeop:{[] if[`endofperiod in key `.;![`.;();0b;enlist`endofperiod]];}; - -/ di.pubsub.callendofperiod sends that triple as ONE argument, so every subscriber needs a monadic -/ root endofperiod or the publish fails on this side -endofperioddefault:{[] - dropeop[]; - sub.init[()!();deps[]]; - all(`endofperiod in key `.; - not 10h=type @[{get[`endofperiod] x};EOPMSG;{`$"ERR:",x}]) - }; - -/ a consumer that defines its own keeps it - the same rule chainedtp uses for upd -endofperiodnotclobbered:{[] - dropeop[]; - @[`.;`endofperiod;:;{[x] `EOPMARK set x;}]; - sub.init[()!();deps[]]; - @[`.;`EOPMARK;:;::]; - get[`endofperiod] EOPMSG; - EOPMSG~get`EOPMARK - }; diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 9c8011d4..78575f7c 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -67,9 +67,8 @@ true,0,0,q,tabsizestracked[],1,,a partitioned writedown tracks tabsizes so table true,0,0,q,tabsizescleared[],1,,end of day clears tabsizes in a partitioned mode too true,0,0,q,nogatewayquiet[],1,,no gateway is a normal state and must not log an error -comment,,,,,,,parity with legacy wdb - overridable getpartition and the endofperiod callback +comment,,,,,,,parity with legacy wdb - overridable getpartition true,0,0,q,getpartitionoverride[],1,,a getpartition supplied in config replaces the built-in -true,0,0,q,endofperiodcallback[],1,,endofperiod exists at root and takes the triple as one argument run,0,0,q,stoptp[],1,,stop the fake tickerplant diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 6f16df5a..7a1c7576 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -293,13 +293,3 @@ getpartitionoverride:{[] chk `used`notthedefault!(2001.09.11~(mv`getpartition)[];not 2001.09.11~(mv`defaultgetpartition)[]) }; -/ di.pubsub sends the (current;next;data) triple as one argument, so the callback must be monadic -endofperiodcallback:{[] - freshwdb cfg[]; - r:@[{get[`endofperiod] x};(2026.01.01D12:00;2026.01.01D13:00;`p`t!(2026.01.01D13:00;.z.p));{`$"ERR:",x}]; - chk `defined`atroot`monadic`logged!( - 100h=type get`endofperiod; - `endofperiod in key `.; - not 10h=type r; - loggedlike[`info;"received endofperiod*"]) - }; diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index 2ff8d553..a8605c6a 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -111,13 +111,6 @@ The writedown mode decides whether the idb mounts `savedir` or `savedir/ Date: Thu, 8 Oct 2026 13:14:24 +0800 Subject: [PATCH 09/15] Drop the stray email file; strip the hsym colon from idb path logging di/email/manual_tests.q was swept in by a `git add -A` and has nothing to do with this PR. Removed from the branch; it stays on disk for the email work. idb: the port changed the sym-load error from `1_string` to `string`, so the path printed with its leading colon. Restored, and applied to the other three path log lines in the file so they agree. Co-Authored-By: Claude Opus 5 --- di/email/manual_tests.q | 264 ---------------------------------------- di/torq/proc/idb/idb.q | 8 +- 2 files changed, 4 insertions(+), 268 deletions(-) delete mode 100644 di/email/manual_tests.q diff --git a/di/email/manual_tests.q b/di/email/manual_tests.q deleted file mode 100644 index 8130e761..00000000 --- a/di/email/manual_tests.q +++ /dev/null @@ -1,264 +0,0 @@ -// ========================================================== -// di.email manual test script -// run in a q session after: email:use`di.email -// then call init with your smtp config before the send tests -// ========================================================== - -// helpers -chk:{[label;result] -1 ($[result;"PASS: ";"FAIL: "],label);}; -has:{$[10h=type x;0 tag"; has[t;"

"; "

"~-4#t]; - -h1:.m.di.0email.mailheading["1";"title"]; -chk["mailheading h1 opens"; "

"~-5#h1]; - -h3:.m.di.0email.mailheading["3";"small"]; -chk["mailheading h3 tag"; "

"~-5#h3]; - -b:.m.di.0email.mailbold "bold text"; -chk["mailbold opens "; ""; ""~-4#b]; - -i:.m.di.0email.mailitalic "italic text"; -chk["mailitalic opens "; ""; ""~-4#i]; - -chk["mailstring on string"; "hello"~.m.di.0email.mailstring "hello"]; -chk["mailstring on int"; has[.m.di.0email.mailstring 1;"1"]]; // "1" or "1i" depending on version -chk["mailstring on float"; "1.5"~.m.di.0email.mailstring 1.5]; -chk["mailstring on symbol"; "abc"~.m.di.0email.mailstring `abc]; - -// ========================================================== -// section 2: color and style helpers -// ========================================================== --1 "\n--- section 2: color and style helpers ---"; - -ac:.m.di.0email.addcolor["red";"colored text"]; -chk["addcolor contains color:red"; has[ac;"color:red"]]; -chk["addcolor no font-size:px bug"; not has[ac;"font-size:px"]]; - -ms:.m.di.0email.mailsize["20";"sized text"]; -chk["mailsize contains font-size"; has[ms;"font-size:20px"]]; -chk["mailsize no spurious color"; not has[ms;"color:;"]]; - -bg:.m.di.0email.mailbgcolor["#ffff00";"highlighted"]; -chk["mailbgcolor sets background"; has[bg;"background-color:#ffff00"]]; - -mc:.m.di.0email.mailcolors["blue";"#eeeeee";"14";"full"]; -chk["mailcolors sets color"; has[mc;"color:blue"]]; -chk["mailcolors sets background"; has[mc;"background-color:#eeeeee"]]; -chk["mailcolors sets font-size"; has[mc;"font-size:14px"]]; -chk["mailcolors sets display"; has[mc;"display:inline"]]; - -// ========================================================== -// section 3: links and bookmarks -// ========================================================== --1 "\n--- section 3: links and bookmarks ---"; - -u:.m.di.0email.mailurl["https://example.com";"click here"]; -chk["mailurl contains href"; has[u;"href=\"https://example.com\""]]; -chk["mailurl contains link text"; has[u;"click here"]]; -chk["mailurl uses tag"; has[u;""; ""~-4#u]; - -bm:.m.di.0email.setbookmark "section1"; -chk["setbookmark has name attr"; has[bm;"name=\"section1\""]]; - -gbm:.m.di.0email.getbookmark["section1";"go to section"]; -chk["getbookmark links to anchor"; has[gbm;"href=\"#section1\""]]; -chk["getbookmark has link text"; has[gbm;"go to section"]]; - -// ========================================================== -// section 4: tables and dicts -// ========================================================== --1 "\n--- section 4: tables and dicts ---"; - -t:([]sym:`a`b`c;price:1.1 2.2 3.3;vol:100 200 300); - -mt:.m.di.0email.mailtable[t]; -chk["mailtable returns list"; 0h=type mt]; -chk["mailtable has open"; has[first mt;"
close"; "
"~last mt]; -chk["mailtable has header row"; hasa[mt;" open"; any ""~/:tmpl]; -chk["template0 has close"; ""~last tmpl]; -chk["template0 has tag"; hasa[tmpl;""~/:tmpl; -chk["blank line after subject"; sepidx>subidx]; -chk["blank line before html"; sepidx Date: Fri, 9 Oct 2026 11:39:48 +0800 Subject: [PATCH 10/15] di.torq.proc.wdb: stop the sort fixture's table leaking into a re-run testsort.q creates a root table `scalls` to record mock server calls, and it is still there when the suite finishes. tablelist[] returns every root table except the ignorelist, so a second moduletest in the same process tried to write down `scalls` - which has no sym column - and the partitioned writedown tests threw 'length. `calls` was already in the ignorelist for exactly this reason; add `scalls`. Reported by Eoghan: a second run in the same q session failed ~19 checks. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.q | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 7a1c7576..dad20fc9 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -48,7 +48,7 @@ setup:{[] starttp[]; }; -cfg:{[] `savedir`hdbdir`sortcsv`numrows`eodwaittime`reloadorder`ignorelist!("wdb";"hdb";"appconfig/sort.csv";100000;0;`hdb;`heartbeat`logmsg`calls)}; +cfg:{[] `savedir`hdbdir`sortcsv`numrows`eodwaittime`reloadorder`ignorelist!("wdb";"hdb";"appconfig/sort.csv";100000;0;`hdb;`heartbeat`logmsg`calls`scalls)}; today:{[] .z.D}; hdbpart:{[t] hsym `$BASE,"/hdb/",(string today[]),"/",string t}; From 921247cd1a5d197c3afb60461794c2c91b7fec75 Mon Sep 17 00:00:00 2001 From: Dexter Date: Fri, 9 Oct 2026 11:42:59 +0800 Subject: [PATCH 11/15] di.torq.proc.wdb: silence the shell for the deliberately failing move emptypartition[] asks for a partition that was never written, so the mv fails - that is the point of the check. mv writes to stderr, which q does not capture, so the suite printed "mv: cannot stat ..." on every run and read as a problem. Run that one call with di.os's swappable syscall wrapped to drop stderr, and restore it afterwards. The module's own error log still fires, which is what the check asserts, and a real shell error anywhere else is still printed. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/testsort.q | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/di/torq/proc/wdb/testsort.q b/di/torq/proc/wdb/testsort.q index 431cb1a0..c64a8797 100644 --- a/di/torq/proc/wdb/testsort.q +++ b/di/torq/proc/wdb/testsort.q @@ -6,6 +6,7 @@ / a failing row can be diagnosed with `show LAST`. Helpers live here because CSV fields cannot hold commas. BASE:"/tmp/di_sort_k4unit"; +OSSYSCALL:`.m.di.0os.syscall; PDATE:2026.01.05; chk:{[d] `LAST set d; all value d}; @@ -203,10 +204,21 @@ idbreloadorder:{[] not loggedlike[`warn;"*is neither*"]) }; +/ run f with di.os's shell calls silenced: a deliberately failing mv writes to stderr, which q does +/ not capture, so the suite prints it even though the failure is the point. The module's own error +/ log still fires, which is what the check below asserts. +quietshell:{[f] + o:get OSSYSCALL; + OSSYSCALL set {system x," 2>/dev/null"}; + r:@[f;::;{x}]; + OSSYSCALL set o; + r + }; + / a date with no working partition logs the failed move rather than throwing emptypartition:{[] freshwire config[]; - tail[savedir[];PDATE+10;`]; + quietshell {tail[savedir[];PDATE+10;`]}; chk `logged`nothdb!( loggedlike[`error;"Failed to move data from wdb*"]; 0=count key hsym `$hdbdir[],"/",string PDATE+10) From 9c2f6877488ab94f813aecc7e70333e4a105666e Mon Sep 17 00:00:00 2001 From: Dexter Date: Fri, 9 Oct 2026 11:46:38 +0800 Subject: [PATCH 12/15] di.torq.proc.wdb: quietshell must not swallow a throw The first version trapped f and returned the error as a value, so a genuine failure inside the silenced call no longer reached the suite - the bare call it replaced would have raised it. Restore the syscall, then re-signal. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/testsort.q | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/di/torq/proc/wdb/testsort.q b/di/torq/proc/wdb/testsort.q index c64a8797..104223ec 100644 --- a/di/torq/proc/wdb/testsort.q +++ b/di/torq/proc/wdb/testsort.q @@ -210,9 +210,9 @@ idbreloadorder:{[] quietshell:{[f] o:get OSSYSCALL; OSSYSCALL set {system x," 2>/dev/null"}; - r:@[f;::;{x}]; + r:@[{(1b;x[])};f;{(0b;x)}]; OSSYSCALL set o; - r + $[first r;last r;'last r] }; / a date with no working partition logs the failed move rather than throwing From f3d91487ee728f5e9129a85e0f1a0408cd5e1d0b Mon Sep 17 00:00:00 2001 From: Dexter Date: Mon, 12 Oct 2026 11:32:54 +0800 Subject: [PATCH 13/15] di.torq.proc.wdb: restore legacy reload, endofperiod stub and numtab default From Eoghan's port-parity review on PR #137. All three narrowings confirmed against TorQ 5.2.19 before changing anything. reloadorder: TorQ's reloadfunc called root `reload` on whatever proctype was listed (code/processes/wdb.q, `. `reload x). reloadexpr only recognised hdbtypes, rdbtypes and idbtypes and returned (::) for anything else, which getprocs skipped with a warning, so a custom proctype in reloadorder was never reloaded. The default branch is now legacy's root `reload` - which is exactly what the rdb branch already did, so that branch collapses into it - and the dead (::) guard is gone. customreload[] proves it with a real connected peer of a custom proctype; it fails without this change. endofperiod: legacy shipped a logging stub in code/wdb/writedown.q. di.pubsub.callendofperiod broadcasts (`endofperiod;(current;next;data)) to every subscriber on each period roll, so without the stub a wdb pointed at a segmented tickerplant raises 'endofperiod every period. Restored and published at root. Note it is monadic, matching callendofperiod, which sends the triple as one argument - legacy's three-parameter stub would have been applied to one argument and silently become a projection. numtab: legacy defaults to `quote`trade!10000 50000 (writedown.q), the module defaulted to an empty dict, so quote and trade flushed at numrows instead of 10k/50k. mergenumtab had kept the legacy default, so the two disagreed. Restored. The test fixture now pins numtab/replaynumtab empty, since those tests want numrows to govern, and numtabdefault[] covers the shipped default. Also from the same review: partlimit is now passed through to di.merge init when configured (omitted, di.merge keeps its own default of 1000), and wdb.md gains a migration section for the TorQ settings that were renamed or dropped (subtabs, subsyms, replay, tpconnsleepintv/tpcheckcycles, schema) plus the settimer seconds-not-timespan change, which were silently ignored before. Suite is 79 checks, green, and clean on a second run in the same process. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.csv | 4 +++ di/torq/proc/wdb/test.q | 49 +++++++++++++++++++++++++++++++++++-- di/torq/proc/wdb/testsort.q | 4 +-- di/torq/proc/wdb/wdb.md | 29 ++++++++++++++++++++-- di/torq/proc/wdb/wdb.q | 21 ++++++++++------ 5 files changed, 94 insertions(+), 13 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index 78575f7c..f14cecea 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -56,6 +56,10 @@ true,0,0,q,fixpartition[],1,,data replayed into the wrong partition is moved to true,0,0,q,tpretry[],1,,init fails when no tickerplant connects within tpwaittimeout true,0,0,q,pattrcheck[],1,,a partitioned writedown mode without a default p attribute is reported true,0,0,q,replaythreshold[],1,,replay uses replaynumrows while live flushing uses numrows +true,0,0,q,numtabdefault[],1,,numtab defaults to legacy quote/trade thresholds and replaynumtab follows it +true,0,0,q,endofperiodstub[],1,,a root endofperiod stub is published so an stp period roll does not raise +true,0,0,q,customreload[],1,,a custom proctype in reloadorder is reloaded with legacy root reload +true,0,0,q,partlimitpassed[],1,,partlimit from wdb config reaches di.merge and falls back to its default true,0,0,q,workermerge[],1,,a saveandsort wdb merges on its sortworkers true,0,0,q,savemode`default,1,,a save-mode wdb hands a default-mode day to the sort process true,0,0,q,savemode`partbyattr,1,,a save-mode wdb hands a partbyattr day and its partsizes to the sort process diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index dad20fc9..28465e76 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -48,7 +48,11 @@ setup:{[] starttp[]; }; -cfg:{[] `savedir`hdbdir`sortcsv`numrows`eodwaittime`reloadorder`ignorelist!("wdb";"hdb";"appconfig/sort.csv";100000;0;`hdb;`heartbeat`logmsg`calls`scalls)}; +/ numtab is pinned empty so numrows governs every table; the shipped default is covered by numtabdefault[] +cfg:{[] + `savedir`hdbdir`sortcsv`numrows`numtab`replaynumtab`eodwaittime`reloadorder`ignorelist! + ("wdb";"hdb";"appconfig/sort.csv";100000;(`symbol$())!`long$();(`symbol$())!`long$();0;`hdb;`heartbeat`logmsg`calls`scalls) + }; today:{[] .z.D}; hdbpart:{[t] hsym `$BASE,"/hdb/",(string today[]),"/",string t}; @@ -159,6 +163,27 @@ pattrcheck:{[] loggedlike[`error;"default table not defined in sort.csv*"] }; +numtabdefault:{[] + / legacy wdb/writedown.q defaults numtab to `quote`trade!10000 50000, and replaynumtab follows it + freshwdb (cfg[] _ `numtab) _ `replaynumtab; + chk `quote`trade`other`replayfollows!( + 10000=.m.di.0torq.0proc.0wdb.maxrows`quote; + 50000=.m.di.0torq.0proc.0wdb.maxrows`trade; + 100000=.m.di.0torq.0proc.0wdb.maxrows`heartbeat; + 50000=.m.di.0torq.0proc.0wdb.replaymaxrows`trade) + }; + +endofperiodstub:{[] + / legacy shipped a logging endofperiod so an stp's period roll does not raise in the wdb + / di.pubsub.callendofperiod sends (`endofperiod;(curr;next;data)) - one argument, so the stub is monadic + freshwdb cfg[]; + r:@[{(1b;`. [`endofperiod] x)};(09:00;10:00;enlist[`p]!enlist 10:00);{(0b;x)}]; + chk `published`callable`logged!( + `endofperiod in key `.; + first r; + loggedlike[`info;"received endofperiod*"]) + }; + replaythreshold:{[] freshwdb cfg[],`replaynumrows`numrows!(2;100000); chk `replay`live!(2=.m.di.0torq.0proc.0wdb.replaymaxrows`trade;100000=.m.di.0torq.0proc.0wdb.maxrows`trade) @@ -175,7 +200,8 @@ logq:("LOGS:([]lvl:`symbol$();ctx:`symbol$();msg:());";"lg:{[l;c;m] `LOGS upsert peerscript:(!) . flip ( (`sortworker;logq,("w:use`di.torq.proc.wdb;";"w.init[(((enlist`mode)!enlist`sort),`tickerplanttypes`hdbtypes`rdbtypes`idbtypes`gatewaytypes`sorttypes`sortworkertypes`wdbtypes!8#enlist`symbol$()),(enlist`sortcsv)!enlist \"appconfig/sort.csv\";`log`timer`servers!(ld;(`symbol$())!();",mockserversq,")];")); (`sort;logq,("s:use`di.torq.proc.wdb;";"s.init[`mode`savedir`hdbdir`sortcsv`eodwaittime`reloadorder!(`sort;\"wdb\";\"hdb\";\"appconfig/sort.csv\";0;`hdb);`log`timer`servers!(ld;(`symbol$())!();",mockserversq,")];")); - (`hdb;enlist "RELOADS:0;.hdb.reload:{[] RELOADS+:1;};")); + (`hdb;enlist "RELOADS:0;.hdb.reload:{[] RELOADS+:1;};"); + (`custom;enlist "RELOADS:0;reload:{[d] RELOADS+:1;};")); startpeer:{[kind] port:NEXTPORT;`NEXTPORT set NEXTPORT+1; @@ -230,6 +256,25 @@ eodok:{[c] 0=count key wdbpart[]) }; +/ partlimit is a di.merge setting, reachable from wdb config; omitted, di.merge keeps its own default +partlimitpassed:{[] + freshwdb cfg[],(enlist`partlimit)!enlist 7; + set7:.m.di.0merge.partlimit; + freshwdb cfg[]; + chk `passed`defaulted!(7=set7;1000=.m.di.0merge.partlimit) + }; + +/ legacy called root `reload` on any proctype in reloadorder, not just hdb/rdb/idb +customreload:{[] + `PEERS set enlist[`custom]!enlist enlist h:startpeer`custom; + freshwdb cfg[],(enlist`reloadorder)!enlist `custom; + feed[]; + endofday today[]; + r:chk `reloaded`noerror!(1=h"RELOADS";not loggedlike[`error;"*custom*"]); + stoppeers[]; + r + }; + / with eodwaittime on, the hdb reloads asynchronously and calls .wdb.handler back handshake:{[] `PEERS set enlist[`hdb]!enlist enlist h:startpeer`hdb; diff --git a/di/torq/proc/wdb/testsort.q b/di/torq/proc/wdb/testsort.q index 104223ec..21f59d45 100644 --- a/di/torq/proc/wdb/testsort.q +++ b/di/torq/proc/wdb/testsort.q @@ -186,12 +186,12 @@ reloadattempted:{[] loggedlike[`error;"no connection to the hdb*"]) }; -/ an unknown reloadorder entry is reported rather than silently skipped +/ an unknown reloadorder entry gets the root `reload` call and simply has nothing connected badreloadorder:{[] freshwire config[],(enlist`reloadorder)!enlist `hdb`nosuchtype; tail[savedir[];PDATE;`trade`quote]; chk `warned`stillmoved!( - loggedlike[`warn;"*is neither an hdb, rdb, nor idb type*"]; + loggedlike[`error;"*no connection to the nosuchtype*"]; `quote`trade~partitiontables hdbdir[]) }; diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index a8605c6a..c714807e 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -33,6 +33,7 @@ mergemode = "part" # part | col | hybrid (partitioned writedown mergebybytelimit = false # true: merge limits are byte estimates (mergenumbytes), not rows mergenumrows = 100000 # default rows per merge batch; mergenumtab overrides per table mergenumbytes = 500000000 # bytes per merge batch when mergebybytelimit is true +partlimit = 1000 # max partitions di.merge batches together (passed to di.merge init) tickerplanttypes = "tickerplant" # proctype(s) to subscribe to sorttypes = "sort" # proctype(s) to hand the tail to in save mode sortworkertypes = "sortworker" # proctype(s) to fan the sort out to (needs a negative -s) @@ -53,7 +54,8 @@ settimer = 10 # seconds between flush checks (di.timer mode immediate = false # true: flush every table on every timer tick (ignore numrows) replaylog = true # replay the tp log on startup tpwaittimeout = 30000 # ms to wait for the tickerplant at startup before init fails -reloadorder = "hdb rdb idb" # order to reload at EOD +reloadorder = "hdb rdb idb" # order to reload at EOD; an hdb gets .hdb.reload[], an idb + # .idb.intradayreload[], anything else legacy's root `reload` eodwaittime = 10 # seconds to wait for reload callbacks before releasing (0: sync reloads) permitreload = true # false: sort and move, but leave downstream alone # compression (optional) -> e.g. 17 2 6, applied (.z.zd) while sorting/merging, then reset to 16 0 0 @@ -199,7 +201,30 @@ sort process with `.merge.syncpartsizes` before the hand-off. ## Not included (deprecated) -- **FinSpace/AWS** and the `endofperiod` STP stub — stripped. +- **FinSpace/AWS** — stripped. + +The `endofperiod` stub legacy shipped in `writedown.q` **is** kept: `di.pubsub.callendofperiod` +broadcasts `` (`endofperiod;(current;next;data)) `` to every subscriber on each period roll, so a wdb +pointed at a segmented tickerplant would otherwise raise `'endofperiod` every period. The stub is +published at root by `init` and only logs. It is **monadic**, matching `callendofperiod`, which +sends the triple as a single argument. + +## Migrating a TorQ wdb settings file + +Config comes from the merged config dictionary, not `@[value;...]`, so a setting this module does +not know is **ignored silently**. These TorQ names changed: + +| TorQ setting | this module | +| --- | --- | +| `subtabs` | `subscribeto` | +| `subsyms` | `subscribesyms` | +| `replay` | `replaylog` | +| `tpconnsleepintv`, `tpcheckcycles` | `tpwaittimeout` (a single ms budget) | +| `schema` | dropped — the schema always comes from the tickerplant's `subdetails` | + +`settimer` is a **number of seconds**, not a timespan: a TorQ-style `0D00:00:10` throws. `numtab` +and `mergenumtab` keep legacy's `` `quote`trade!10000 50000 `` default, so `numrows` / +`mergenumrows` do **not** apply to those two tables unless you override `numtab` / `mergenumtab`. ## Module-namespace notes diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 2987d574..8ea5b4b3 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -465,11 +465,11 @@ endofdaysort:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] } / the call each reloadorder type makes on the far side +/ anything other than an hdb or idb gets legacy's root `reload`, which is what the rdb exposes reloadexpr:{[ptype] $[ptype in .z.m.hdbtypes;{[d] .hdb.reload[]}; - ptype in .z.m.rdbtypes;{[d] `. [`reload] d}; ptype in .z.m.idbtypes;{[d] .idb.intradayreload[]}; - (::)] + {[d] `. [`reload] d}] } / function to send reload message to rdbs/hdbs/idbs @@ -488,9 +488,7 @@ reloadproc:{[h;d;ptype;f] / function to discover rdbs/hdbs and attempt to reconnect getprocs:{[x;y] - if[(::)~f:reloadexpr x; - .z.m.log[`warn][`doreload;"reloadorder entry ",(string x)," is neither an hdb, rdb, nor idb type - skipped"]; - :()]; + f:reloadexpr x; a:exec w from (.z.m.svc`getservers) x; / exit if no valid handle if[0=count a;.z.m.log[`error][`connection;"no connection to the ",(string x)," could be established... failed to reload ",string x];:()]; @@ -619,7 +617,7 @@ setconfig:{[config] .z.m.mergenumrows:$[`mergenumrows in key config;tolong config`mergenumrows;100000]; .z.m.mergenumtab:$[`mergenumtab in key config;config`mergenumtab;`quote`trade!10000 50000]; .z.m.numrows:$[`numrows in key config;tolong config`numrows;100000]; - .z.m.numtab:$[`numtab in key config;config`numtab;(`symbol$())!`long$()]; + .z.m.numtab:$[`numtab in key config;config`numtab;`quote`trade!10000 50000]; .z.m.replaynumrows:$[`replaynumrows in key config;tolong config`replaynumrows;.z.m.numrows]; .z.m.replaynumtab:$[`replaynumtab in key config;config`replaynumtab;.z.m.numtab]; .z.m.immediate:$[`immediate in key config;tobool config`immediate;0b]; @@ -642,6 +640,12 @@ setconfig:{[config] .z.m.currentpartition:0N; } +/ logging stub for the period roll, as legacy's writedown.q shipped +/ monadic: di.pubsub.callendofperiod sends (`endofperiod;(currentpd;nextpd;data)) as one argument +endofperiod:{[x] + .z.m.log[`info][`endofperiod;"received endofperiod ",.Q.s1 x]; + } + / publishes the root names other processes and legacy's peach lambdas call setroot:{[] set[`.wdb.endofdaysort;endofdaysort]; @@ -658,6 +662,7 @@ setroot:{[] @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; @[`.;`upd;:;.z.m.upd]; @[`.;`endofday;:;endofday]; + @[`.;`endofperiod;:;endofperiod]; set[`.u.end;endofday]; / the idb reads these at startup; currentpartition is republished at each end of day set[`.wdb.savedir;.z.m.savedir]; @@ -682,7 +687,9 @@ init:{[config;deps] .z.m.os:use`di.os; initdbwrite[config;deps]; .z.m.mrg:use`di.merge; - (.z.m.mrg`init)[`log`mergebybytelimit!(deps`log;.z.m.mergebybytelimit)]; + mrgdeps:`log`mergebybytelimit!(deps`log;.z.m.mergebybytelimit); + if[`partlimit in key config;mrgdeps[`partlimit]:tolong config`partlimit]; + (.z.m.mrg`init)[mrgdeps]; checksortparams[]; if[.z.m.mode~`sort; From 0552a8c2212c27aefe01ab872a4c8cebd8f60657 Mon Sep 17 00:00:00 2001 From: Dexter Date: Mon, 12 Oct 2026 11:38:43 +0800 Subject: [PATCH 14/15] di.torq.proc.wdb: document the numtab upgrade, stop restating di.merge's default From the second DIReview pass on PR #137. The numtab point is fair: main ships wdb 0.2.0, which defaults numtab to an empty dictionary, so merging this changes flush thresholds for quote and trade on any config without a numtab key. wdb.md now carries an explicit "Upgrading from 0.2.0" note with the way to keep the old behaviour. The accompanying claim that the test fixture diverging from production is a footgun does not hold - pinning a config value is what makes those tests deterministic, and numtabdefault[] asserts the shipped default directly. On partlimit the review suggested resolving the default in the wdb and always passing it. That is the thing that drifts: it would put the number 1000 in two modules. Fixed the other way instead - di.merge owns the default, wdb.md no longer restates it, and the test asserts the fallback against di.merge's own partlimitdefault rather than a literal. Suite is 79 checks, green, clean on a second run in the same process. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.q | 3 ++- di/torq/proc/wdb/wdb.md | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 28465e76..9b693f4f 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -261,7 +261,8 @@ partlimitpassed:{[] freshwdb cfg[],(enlist`partlimit)!enlist 7; set7:.m.di.0merge.partlimit; freshwdb cfg[]; - chk `passed`defaulted!(7=set7;1000=.m.di.0merge.partlimit) + / compare against di.merge's own default rather than a literal, so the two cannot drift apart + chk `passed`defaulted!(7=set7;.m.di.0merge.partlimitdefault=.m.di.0merge.partlimit) }; / legacy called root `reload` on any proctype in reloadorder, not just hdb/rdb/idb diff --git a/di/torq/proc/wdb/wdb.md b/di/torq/proc/wdb/wdb.md index c714807e..5eee22d5 100644 --- a/di/torq/proc/wdb/wdb.md +++ b/di/torq/proc/wdb/wdb.md @@ -33,7 +33,8 @@ mergemode = "part" # part | col | hybrid (partitioned writedown mergebybytelimit = false # true: merge limits are byte estimates (mergenumbytes), not rows mergenumrows = 100000 # default rows per merge batch; mergenumtab overrides per table mergenumbytes = 500000000 # bytes per merge batch when mergebybytelimit is true -partlimit = 1000 # max partitions di.merge batches together (passed to di.merge init) +partlimit = 1000 # max partitions di.merge batches together; omitted, di.merge's + # own default applies - this module does not restate it tickerplanttypes = "tickerplant" # proctype(s) to subscribe to sorttypes = "sort" # proctype(s) to hand the tail to in save mode sortworkertypes = "sortworker" # proctype(s) to fan the sort out to (needs a negative -s) @@ -226,6 +227,18 @@ not know is **ignored silently**. These TorQ names changed: and `mergenumtab` keep legacy's `` `quote`trade!10000 50000 `` default, so `numrows` / `mergenumrows` do **not** apply to those two tables unless you override `numtab` / `mergenumtab`. +### Upgrading from 0.2.0 — behaviour change + +**`numtab` now defaults to `` `quote`trade!10000 50000 ``; 0.2.0 defaulted it to an empty +dictionary.** A config with no `numtab` key therefore flushes `quote` at 10,000 rows and `trade` +at 50,000 instead of at `numrows`, so those two tables write down more often than they did on +0.2.0. This restores TorQ's default (`code/wdb/writedown.q`) and matches `mergenumtab`, which +already shipped it. To keep 0.2.0's behaviour, set `numtab` explicitly: + +```toml +numtab = {} # every table uses numrows, as in 0.2.0 +``` + ## Module-namespace notes Root tables are **read** with bare `value t` (bare reads fall through to root) but **written** From a164edccb432b9b9243fd83641f4442050927c5d Mon Sep 17 00:00:00 2001 From: Dexter Date: Mon, 12 Oct 2026 14:56:53 +0800 Subject: [PATCH 15/15] di.torq.proc.wdb: close three gaps against the module standards in PR #142 Audited the module against the definition-of-done checklist in the torq-module-extraction skill (PR #142, still open). Three items did not hold. Line length: style.md caps lines at 150 characters. Twelve lines were over, eleven of them introduced by this branch. All are long log messages or chained calls, now split. No behaviour change; the suite is unchanged at 79 green before the new test below. init idempotency: the checklist asks that init be idempotent where it registers anything. It registers a timer job, and di.timer raises on an id that already exists (init.q:31), so a second init threw. Fixed with the delete-then-add the end of day path already uses for sortflushend, rather than introducing a registered flag - same outcome, consistent with the surrounding code, no extra state. This needed a test to be worth anything. The fixture's timer mock is a pair of no-op lambdas and never detected a duplicate, so initidempotent[] installs a mock that mirrors di.timer and calls init twice. Removing the guard makes it fail. deps validation: a non-dict deps reached `key deps` and raised a bare 'type rather than saying what was wrong. init now checks the type first and names what it wants, which is the pattern the skill gives and what di.email already did. Left alone deliberately: the two direct .z.* assignments, .z.zd for compression and .z.pd for the sort workers. That rule is about event handlers going through the injected handlers dependency; neither of these is an event handler and no contract covers them. Suite is 80 checks, green, and clean on a second run in the same process. Co-Authored-By: Claude Opus 5 --- di/torq/proc/wdb/test.csv | 1 + di/torq/proc/wdb/test.q | 15 +++++++++++ di/torq/proc/wdb/wdb.q | 52 ++++++++++++++++++++++++++++++--------- 3 files changed, 56 insertions(+), 12 deletions(-) diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index f14cecea..d1600882 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -56,6 +56,7 @@ true,0,0,q,fixpartition[],1,,data replayed into the wrong partition is moved to true,0,0,q,tpretry[],1,,init fails when no tickerplant connects within tpwaittimeout true,0,0,q,pattrcheck[],1,,a partitioned writedown mode without a default p attribute is reported true,0,0,q,replaythreshold[],1,,replay uses replaynumrows while live flushing uses numrows +true,0,0,q,initidempotent[],1,,init can be called twice without colliding on its timer job true,0,0,q,numtabdefault[],1,,numtab defaults to legacy quote/trade thresholds and replaynumtab follows it true,0,0,q,endofperiodstub[],1,,a root endofperiod stub is published so an stp period roll does not raise true,0,0,q,customreload[],1,,a custom proctype in reloadorder is reloaded with legacy root reload diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 9b693f4f..88bbf24d 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -163,6 +163,21 @@ pattrcheck:{[] loggedlike[`error;"default table not defined in sort.csv*"] }; +/ di.timer's addjob raises on an id that already exists, so a second init must not collide +initidempotent:{[] + `calls set 0#calls; + system "rm -rf ",BASE,"/wdb ",BASE,"/hdb"; + `tjobs set `symbol$(); + d:recdeps[]; + d[`timer]:`addjob`deletejobs!( + {[a;b;c;e;f;g] if[a in tjobs;'"duplicate job id ",string a];`tjobs set tjobs,a;}; + {[x] `tjobs set tjobs except x;}); + wdb.init[cfg[];d]; + added:`wdbsave in tjobs; + again:@[{[c;dd] wdb.init[c;dd];1b}[cfg[]];d;{0b}]; + chk `registered`reinitok`noduplicate!(added;again;1=sum tjobs=`wdbsave) + }; + numtabdefault:{[] / legacy wdb/writedown.q defaults numtab to `quote`trade!10000 50000, and replaynumtab follows it freshwdb (cfg[] _ `numtab) _ `replaynumtab; diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 8ea5b4b3..a02e2af1 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -68,7 +68,9 @@ savetables:{[dir;pt;forcesave;tabname] .z.m.log[`info][`rowcheck;"the ",(string tabname)," table consists of ",(string arows)," rows"]; .z.m.log[`info][`save;"saving ",(string tabname)," data to partition ",string pt]; / upsert data to partition - .[upsert;(` sv .Q.par[dir;pt;tabname],`;.Q.en[.z.m.hdbdir;r:0!manipulate[tabname;`. tabname]]);{[e] .z.m.log[`error][`savetables;"Failed to save table to disk : ",e];'e}]; + .[upsert; + (` sv .Q.par[dir;pt;tabname],`;.Q.en[.z.m.hdbdir;r:0!manipulate[tabname;`. tabname]]); + {[e] .z.m.log[`error][`savetables;"Failed to save table to disk : ",e];'e}]; / make addition to tabsizes .z.m.log[`info][`track;"appending table details to tabsizes"]; .z.m.tabsizes+:([tablename:enlist tabname]rowcount:enlist arows;bytes:enlist -22!r); @@ -123,7 +125,9 @@ savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] / get additional partition(s) defined by parted attribute in sort.csv extrapartitiontype:getextrapartitiontype[tablename]; if[(writedownmode in `partbyenum`partbyfirstchar) and 1 lmt; - .z.m.log[`info][`replayupd;"row limit (",(string lmt),") exceeded for ",(string t),". Table count is : ",(string rpc),". Flushing table to disk..."]; + .z.m.log[`info][`replayupd; + "row limit (",(string lmt),") exceeded for ",(string t), + ". Table count is : ",(string rpc),". Flushing table to disk..."]; savetab[.z.m.savedir;getpartition[];0b;t]]; } @@ -191,7 +197,10 @@ fixpartition:{[tplogdate] / delete any data in the current partition directory clearwdbdata[]; .z.m.log[`info][`fixpartition;"Moving data from partition ",pth1," to partition ",pth2]; - .[.z.m.os`mv;(pth1;pth2);{[p1;p2;e] .z.m.log[`error][`fixpartition;"Failed to move data from wdb partition ",p1," to wdb partition ",p2," : ",e]}[pth1;pth2]]]]; + .[.z.m.os`mv; + (pth1;pth2); + {[p1;p2;e] .z.m.log[`error][`fixpartition; + "Failed to move data from wdb partition ",p1," to wdb partition ",p2," : ",e]}[pth1;pth2]]]]; } / fills missing tables in the partition so it is usable intraday @@ -224,7 +233,9 @@ handler:{[x] .z.m.log[`info][`reloadproc;"the ",(string x 0)," process ",string x 2]; if[(.z.p>.z.m.timeouttime) or count[.z.m.reloadsummary]=.z.m.countreload; .z.m.log[`info][`handler;"releasing processes"]; - .z.m.log[`info][`reload;(string count select from .z.m.reloadsummary where status)," out of ",(string count .z.m.reloadsummary)," processes successfully reloaded"]; + .z.m.log[`info][`reload; + (string count select from .z.m.reloadsummary where status)," out of ", + (string count .z.m.reloadsummary)," processes successfully reloaded"]; flushend[]; .z.m.reloadsummary:0#.z.m.reloadsummary]; } @@ -281,8 +292,12 @@ movetohdb:{[dw;hw;pt] }[hsym `$hw]'[dw,/:"/",/:string key hsym `$dw]; $[0=count key hsym `$dw; @[.z.m.os`deldir;dw;{[x;y] .z.m.log[`error][`mvtohdb;"Failed to delete folder ",x," with error: ",y]}[dw]]; - .z.m.log[`error][`mvtohdb;"Table(s) ",(", " sv string key hsym `$dw)," are still in ",dw," - the partition is split across the wdb and the hdb"]]]; - .z.m.log[`error][`mvtohdb;raze "Table(s) ",string[(key hsym `$hw) inter key hsym `$dw]," is present in both location. Operation will be aborted to avoid corrupting the hdb"]] + .z.m.log[`error][`mvtohdb; + "Table(s) ",(", " sv string key hsym `$dw)," are still in ",dw, + " - the partition is split across the wdb and the hdb"]]]; + .z.m.log[`error][`mvtohdb; + raze "Table(s) ",string[(key hsym `$hw) inter key hsym `$dw], + " is present in both location. Operation will be aborted to avoid corrupting the hdb"]] } / root sym is set with @[`.;...]: a bare load from a use-loaded module lands in its private namespace @@ -322,7 +337,9 @@ endofdaysortdate:{[dir;pt;tablist;hdbsettings] sortall[tablist,'.Q.par[dir;pt;] each tablist;hdbsettings]; .z.m.log[`info][`sort;"finished sorting data"]; / move data into hdb - .z.m.log[`info][`mvtohdb;"Moving partition from the temp wdb ",(dw:(.z.m.os`topath) -1_string .Q.par[dir;pt;`])," directory to the hdb directory ",hw:(.z.m.os`topath) -1_string .Q.par[hdbsettings`hdbdir;pt;`]]; + .z.m.log[`info][`mvtohdb; + "Moving partition from the temp wdb ",(dw:(.z.m.os`topath) -1_string .Q.par[dir;pt;`]), + " directory to the hdb directory ",hw:(.z.m.os`topath) -1_string .Q.par[hdbsettings`hdbdir;pt;`]]; .z.m.log[`info][`mvtohdb;"Attempting to move ",(", " sv string key hsym `$dw)," from ",dw," to ",hw]; .[movetohdb;(dw;hw;pt);{[e] .z.m.log[`error][`mvtohdb;"Function movetohdb failed with error: ",e]}]; / call the posteod function @@ -480,7 +497,10 @@ reloadproc:{[h;d;ptype;f] reloadfunc:{[f;d;ptype] r:@[{(1b;x y)}[f];d;{(0b;x)}]; (neg .z.w)(`.wdb.handler;(ptype;first r;$[first r;`$"reloaded successfully";`$"reload failed with error ",last r]));(neg .z.w)[]}; / reload function to be executed if eodwaitime = 0 - sync message processes to reload and log if reload was successful or failed - syncreloadfunc:{[h;f;d;ptype] r:@[h;({[f;d] (1b;f d)};f;d);{[ptype;e] .z.m.log[`error][`reloadproc;"failed to reload the ",(string ptype),". The error was : ",e];(0b;e)}[ptype]]; + syncreloadfunc:{[h;f;d;ptype] + r:@[h;({[f;d] (1b;f d)};f;d); + {[ptype;e] .z.m.log[`error][`reloadproc; + "failed to reload the ",(string ptype),". The error was : ",e];(0b;e)}[ptype]]; .z.m.log[`info][`reloadproc;"the ",(string ptype)," ",$[first r;"successfully reloaded";"failed to reload"]]}; .z.m.log[`info][`reloadproc;"sending reload call to ",string ptype]; $[.z.m.eodwaittime>0;sendfunc[(reloadfunc;f;d;ptype);h;ptype];syncreloadfunc[h;f;d;ptype]]; @@ -520,7 +540,8 @@ informsortandreload:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;merge if[mergemethod in `hybrid`part; {[p;h] neg[h](`.merge.syncpartsizes;p);neg[h][]}[(.z.m.mrg`getpartsizes)[]] each h]; msg:(`.wdb.endofdaysort;dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod); - {[msg;wh] @[{[msg;wh] neg[wh] msg;neg[wh][]}[msg];wh;{[e] .z.m.log[`error][`informsortandreload;"unable to run command on sort and reload process: ",e]}]}[msg] each h; + {[msg;wh] @[{[msg;wh] neg[wh] msg;neg[wh][]}[msg];wh; + {[e] .z.m.log[`error][`informsortandreload;"unable to run command on sort and reload process: ",e]}]}[msg] each h; } / send an intraday reload message to idbs @@ -537,7 +558,9 @@ idbreload:{[pt;writedownmode] if[writedownmode in `partbyenum`default`partbyfirstchar; .z.m.log[`info][`eod;"initialising wdbhdb for partition: ",string pt]; $[.z.m.mode~`sort; - {[pt;w] @[w;(`.wdb.initmissingtables;pt);{[e] .z.m.log[`error][`idb;"initmissingtables failed on the wdb: ",e]}]}[pt] each raze {exec w from x} each (.z.m.svc`getservers) each .z.m.wdbtypes; + {[pt;w] @[w;(`.wdb.initmissingtables;pt); + {[e] .z.m.log[`error][`idb;"initmissingtables failed on the wdb: ",e]}]}[pt] each + raze {exec w from x} each (.z.m.svc`getservers) each .z.m.wdbtypes; @[initmissingtables;pt;{[e] .z.m.log[`error][`idb;"initmissingtables failed: ",e]}]]; .z.m.log[`info][`eod;"notifying idbs for newly created partition"]; notifyidbs[`.idb.rollover;enlist pt]]; @@ -673,6 +696,7 @@ setroot:{[] / reads deps and config; a save mode then connects, subscribes and replays the tp log, a sort mode waits to be called init:{[config;deps] + if[99h<>type deps;'"di.torq.proc.wdb: deps must be a dictionary of `log`timer`servers - injected by di.torq"]; if[not `log in key deps;'"di.torq.proc.wdb: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.wdb: timer dependency is required - see di.timer"]; if[not `servers in key deps;'"di.torq.proc.wdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; @@ -696,7 +720,9 @@ init:{[config;deps] conns:distinct .z.m.hdbtypes,.z.m.rdbtypes,.z.m.idbtypes,.z.m.gatewaytypes,.z.m.sortworkertypes,.z.m.wdbtypes; (.z.m.svc`startup)[config,(enlist`connections)!enlist conns]; setroot[]; - .z.m.log[`info][`init;"initialised, mode=sort, savedir=",.z.m.savedirs,", hdbdir=",(1_string .z.m.hdbdir),", waiting to be called at .wdb.endofdaysort"]; + .z.m.log[`info][`init; + "initialised, mode=sort, savedir=",.z.m.savedirs,", hdbdir=",(1_string .z.m.hdbdir), + ", waiting to be called at .wdb.endofdaysort"]; :()]; .z.m.subs:use`di.subscriptions; @@ -721,6 +747,8 @@ init:{[config;deps] {replaymaxrowcheck[x;maxrows x]} each tablelist[]]; setroot[]; + / addjob raises on an id that already exists, so clear any job a previous init left + @[.z.m.timer`deletejobs;`wdbsave;{}]; (.z.m.timer`addjob)[`wdbsave;savetodisk;();.z.m.settimer;1h;()!()]; msg:"initialised, mode=",(string .z.m.mode),", writedownmode=",(string .z.m.writedownmode),", savedir=",.z.m.savedirs; msg,:", hdbdir=",(1_string .z.m.hdbdir),", flush every ",(string .z.m.settimer),"s";