diff --git a/di/asyncdispatch/asyncdispatch.md b/di/asyncdispatch/asyncdispatch.md index 869aea4f0..fdcdad77c 100644 --- a/di/asyncdispatch/asyncdispatch.md +++ b/di/asyncdispatch/asyncdispatch.md @@ -127,28 +127,28 @@ ad.execqueryto[0Ni;shardquery;servertypes;raze;(`da.shardresult;reqid);0Wn;0b] Scan the queue for queries past their timeout, send a timeout error to each client, and mark them complete. Wire into your gateway's timer — every few seconds is typical. ```q // in gateway timer -timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();0D00:00:05;1] ``` ### `removequeries[age]` Purge completed `queryqueue` rows older than `age`. Prevents unbounded growth. ```q // default age is querykeeptime (0D00:30) -timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();0D00:05;1] ``` ### `removeinactive[age]` Purge `servers` rows for backends that have been disconnected longer than `age`. Prevents unbounded growth. ```q // default age is clearinactivetime (0D01:00) -timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();0D00:05;1] ``` ### `removeclients[age]` Purge `clients` rows older than `age`. The `clients` table is appended to on every client connect (`addclientdetails`) for audit and is not otherwise pruned, so wire this into the timer to prevent unbounded growth. Choose `age` to match your audit retention requirements. ```q // retain one day of client audit history -timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();0D00:05;1] ``` ### `setformatresponse[f]` @@ -210,10 +210,10 @@ ad.addserver[hopen`:backend2:5002;`hdb] .z.pc:{ad.removeserverhandle[.z.w];ad.removeclienthandle[.z.w]} // wire housekeeping into the gateway timer -timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] -timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] -timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] -timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();0D00:00:05;1] +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();0D00:05;1] +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();0D00:05;1] +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();0D00:05;1] // a client calls this asynchronously: // execquery dispatches to rdb and hdb in parallel, razes results, replies to client diff --git a/di/compression/compression.md b/di/compression/compression.md index 65165809c..3fc274a23 100644 --- a/di/compression/compression.md +++ b/di/compression/compression.md @@ -15,6 +15,7 @@ - Flexibility to compress different tables/columns with different compression parameters - Preview available before compression to display files to be compressed and how - Summary statistics for each file returned after compression/decompression complete +- With worker threads (`-s` above 0) files compress in parallel; with worker processes (`-s` below 0) each worker compresses and verifies one table, as TorQ --- @@ -69,6 +70,7 @@ depth, 10,default, 1, 17, 8 |`compressmaxage` | Compress files according to config up to the specified max age | |`docompression` | Compress all files in hdb according to compressioncsv config | |`getstatstab` | get function to retrieve summary stats post compression | +|`compress` | `[file;algo;blocksize;level;size]` compress (algo 0: decompress) one file to `file_kdbtempzip`, leaving the original in place | --- diff --git a/di/compression/compression.q b/di/compression/compression.q index 848b3a68b..8bf568395 100644 --- a/di/compression/compression.q +++ b/di/compression/compression.q @@ -86,12 +86,12 @@ showcomp:{[hdbpath;csvpath;maxage] compressfromtable:{[table] statstab::([] file:`$(); algo:`int$(); compressedLength:`long$();uncompressedLength:`long$()); - / Check if process is single threaded - if multi then compress in parallel then clean up after + / Check if process is single threaded - if multi then compress in parallel then clean up after; worker processes (s<0) take a table each, as TorQ #732 / Add metrics on any files due to be compressed to be used afterwards for comparison table:update compressionvaluepre:{(-21!x)`compressedLength}'[fullpath] from table; $[0= system"s"; singlethreadcompress[table]; - multithreadcompress[table]]; + $[0/dev/null 2>&1 &"} each 1 2; + / wait up to 10s for both port files + {[x] system "sleep 0.1"; x+1}/[{(x<100) and 2>count portfiles[]};0]; + `WPORTS set "J"$first each read0 each portfiles[]; + `WH set hopen each WPORTS; + }; + +/ compress the hdb with \s -2 over the workers, counting cleancompressed calls on this process +CLEANS:0; +workerrun:{[] + mkworkerhdb[]; + orig:.m.di.0compression.cleancompressed; + .m.di.0compression.cleancompressed:{[o;f;a] @[`.;`CLEANS;+;1]; o[f;a]}[orig]; + .z.pd:{`u#WH}; + system "s -2"; + r:@[{cmp.docompression[hsym`$WDIR,"/hdb";hsym`$WDIR,"/params.csv"];`ok};::;{x}]; + system "s 0"; + .m.di.0compression.cleancompressed:orig; + f:raze {p:.Q.par[hsym`$WDIR,"/hdb";2026.01.01;x]; ` sv/: p,/:key[p] except `.d} each `trade`quote; + `result`mainclean`algos`stats!(r;CLEANS;{(-21!x)`algorithm} each f;count cmp.getstatstab[]) + }; + +stopworkers:{[] + {neg[x] "exit 0"; neg[x][]} each WH; + system "rm -rf ",WDIR; + }; + +/ the single-file compress legacy housekeeping's kdbzip calls: .cmp.compress[f;2;17;4;hcount f] (housekeeping.q:64) +onefile:{[] + f:hsym`$WDIR,"_one"; + f set v:100000?100f; + cmp.compress[f;2;17;4;hcount f]; + t:hsym`$(string f),"_kdbtempzip"; + r:`original`temp`same!(0=count -21!f;2 17 4i~(-21!t)`algorithm`logicalBlockSize`zipLevel;v~get t); + hdel each (f;t); + r + }; diff --git a/di/dataaccess/dataaccess.q b/di/dataaccess/dataaccess.q index bf73c6860..174e64a9f 100644 --- a/di/dataaccess/dataaccess.q +++ b/di/dataaccess/dataaccess.q @@ -341,5 +341,5 @@ init:{[deps] set[`.dataaccess.shardresult;shardresult]; set[`.dataaccess.sharderror;sharderror]; .z.m.log[`info][`init;"di.dataaccess initialised"]; - (.z.m.timer`addjob)[`dataaccesspurge;removerequests;enlist .z.m.requestkeeptime;1800;1h;()!()]; + (.z.m.timer`addjob)[`dataaccesspurge;removerequests;enlist .z.m.requestkeeptime;0D00:30;1h;()!()]; }; diff --git a/di/dbwrite/dbwrite.md b/di/dbwrite/dbwrite.md index 037087c44..e55132248 100644 --- a/di/dbwrite/dbwrite.md +++ b/di/dbwrite/dbwrite.md @@ -2,7 +2,7 @@ Write, sort, and attribute utilities for kdb+ processes that persist data to disk (rdb, wdb, tickerlogreplay). -A **config table** (`tabname`,`att`,`column`,`sort`) drives which columns are sorted and which attributes are applied per table. Load it once with `readcsv` (from a CSV) or `setconfig` (from an in-memory table); `sort` and `savedown` read from module state automatically. A table with no explicit entry falls back to a `default` row; if no config has been loaded, the built-in default (sort every table by `time` ascending) applies. +A **config table** (`tabname`,`att`,`column`,`sort`) drives which columns are sorted and which attributes are applied per table. Load it once with `readcsv` (from a CSV) or `setconfig` (from an in-memory table); `sort` and `savedown` read from module state automatically. A table with no explicit entry falls back to a `default` row; if no config has been loaded, the built-in default (`p#` on `sym`, sorted by `sym` then `time`) applies. --- @@ -68,6 +68,8 @@ default,,time,1 | `sort[tabname;dirs]` | Sort on-disk partition(s) for a table and apply attributes per stored config | | `savedown[dir;part;tabname;data]` | Write an in-memory table to an HDB partition, sort it, then run gc | | `appenddown[dir;part;tabname;data]` | Append rows to an existing partition (no sort) | +| `manipulate[t;x]` | Apply the table's `savedownmanipulation` function, as TorQ's `.save.manipulate`; keeps `x` if it fails | +| `postreplay[d;p]` | Call the `postreplay` hook after a partition is written, as TorQ's `.save.postreplay` | | `applyattr[dloc;colname;att]` | Apply a single kdb+ attribute to an on-disk column | | `gc[]` | Run `.Q.gc[]` and log memory stats before and after | @@ -77,6 +79,8 @@ default,,time,1 Wire injected dependencies. Must be called before any other function. Also resets the stored sort config to `(::)`. +Optional keys, as TorQ's `.save` hooks: `savedownmanipulation` (dict of table!function, applied to the data before `savedown`/`appenddown` enumerate it) and `postreplay` (`{[d;p]}`, called by writers through `postreplay` once a partition is written). Each is set only when its key is passed, so a later `init` without it keeps the hook; the defaults are `()!()` and `{[d;p]}`. + | Arg | Type | Description | |---|---|---| | `deps` | dict | Must contain `` `log `` → `` `info`warn`error!(infofn;warnfn;errfn) `` | @@ -128,7 +132,7 @@ dbwrite.getconfig[] ### `sort[tabname;dirs]` -Sort and apply attributes to the on-disk partition(s) for one table, using the config stored by `readcsv` or `setconfig`. Falls back to the built-in default (sort by `time` ascending) if no config has been loaded. +Sort and apply attributes to the on-disk partition(s) for one table, using the config stored by `readcsv` or `setconfig`. Falls back to the built-in default, TorQ's `config/sort.csv` (`p#` on `sym`, sorted by `sym` then `time`), if no config has been loaded. A table without `sym` logs the sort and attribute errors and is written unsorted, as in TorQ. | Parameter | Type | Description | |---|---|---| @@ -208,5 +212,5 @@ The suite injects binary mock loggers (`{[c;m] ...}`): a no-op logger, and a cap ## Exported symbols ```q -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;manipulate;postreplay;gc;version]) ``` diff --git a/di/dbwrite/dbwrite.q b/di/dbwrite/dbwrite.q index 28c000ea3..d58ccd4f5 100644 --- a/di/dbwrite/dbwrite.q +++ b/di/dbwrite/dbwrite.q @@ -4,8 +4,12 @@ / attributes that may legitimately appear in a config (empty leaves a column unattributed) validatts:``p`s`g`u; -/ built-in fallback config - sort every table by time ascending when no config is supplied -defaultparams:([] tabname:enlist`default; att:enlist`; column:enlist`time; sort:enlist 1b); +/ built-in fallback config, TorQ's config/sort.csv: p# on sym, sorted by sym then time +defaultparams:([] tabname:`default`default; att:`p`; column:`sym`time; sort:11b); + +/ save down hooks, as TorQ's .save.savedownmanipulation and .save.postreplay; init sets them only when passed +savedownmanipulation:()!(); +posthook:{[d;p]}; init:{[deps] / wire the injected logger - required, no silent fallback. deps: a dict with a `log key @@ -24,8 +28,20 @@ init:{[deps] .z.m.logwarn:deps[`log]`warn; .z.m.logerr:deps[`log]`error; .z.m.sortconfig:(::); + if[`savedownmanipulation in key deps;.z.m.savedownmanipulation:deps`savedownmanipulation]; + if[`postreplay in key deps;.z.m.posthook:deps`postreplay]; + }; + +/ apply the table's savedownmanipulation, if any, keeping the data on failure, as TorQ's .save.manipulate +manipulate:{[t;x] + $[t in key .z.m.savedownmanipulation; + @[.z.m.savedownmanipulation t;x;{[x;e] .z.m.logerr[`manipulate;"save down manipulation failed : ",e];x}[x]]; + x] }; +/ call the postreplay hook after a partition is written, as TorQ's .save.postreplay +postreplay:{[d;p] .z.m.posthook[d;p]}; + readcsv:{[file] / read a sort-config csv and store it in .z.m.sortconfig; used by sort and savedown / the csv must have the columns tabname,att,column,sort (in any order) @@ -196,7 +212,7 @@ savedown:{[dir;part;tabname;data] / enumerates syms against the hdb sym file; sorting and attributes are driven by .z.m.sortconfig .z.m.loginfo[`savedown;"saving ",string[tabname]," partition ",string[part]," to ",string dir]; path:` sv (.Q.par[dir;part;tabname];`); - path set .Q.en[dir;data]; + path set .Q.en[dir;manipulate[tabname;data]]; sort[tabname;path]; .z.m.loginfo[`savedown;"finished saving ",string tabname]; gc[]; @@ -212,7 +228,7 @@ appenddown:{[dir;part;tabname;data] .z.m.logerr[`appenddown;err:"di.dbwrite: appenddown partition does not exist at ",string path]; 'err; ]; - .[path;();,;.Q.en[dir;data]]; + .[path;();,;.Q.en[dir;manipulate[tabname;data]]]; .z.m.loginfo[`appenddown;"finished appending ",string tabname]; }; diff --git a/di/dbwrite/init.q b/di/dbwrite/init.q index 115c2160e..5478b07df 100644 --- a/di/dbwrite/init.q +++ b/di/dbwrite/init.q @@ -8,4 +8,4 @@ / BOTH the file (pre-load manifest walk) and this export (post-load session audit). version:first read0`:::VERSION -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc;version]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;manipulate;postreplay;gc;version]) diff --git a/di/dbwrite/test.csv b/di/dbwrite/test.csv index a61af3c11..ba1a4f498 100644 --- a/di/dbwrite/test.csv +++ b/di/dbwrite/test.csv @@ -160,7 +160,7 @@ true,0,0,q,3=count get sdpath,1,1,three rows on disk after appenddown true,0,0,q,not (asc exec time from get sdpath)~exec time from get sdpath,1,1,rows not auto-sorted by appenddown run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,reset sortconfig to (::) for default-config sort run,0,0,q,dbwrite.sort[`trade;sdpath],1,1,sort the partition explicitly after appending -true,0,0,q,(asc exec time from get sdpath)~exec time from get sdpath,1,1,sorted by time after the explicit sort +true,0,0,q,"(update `#sym from `sym`time xasc t)~update `#sym from t:select from get sdpath",1,1,sorted by sym then time after the explicit sort (default config) fail,0,0,q,dbwrite.appenddown[`:dbw_hdb;2099.01.01;`nope;sdtbl],1,1,appenddown into a non-existent partition errors comment,,,,,,,integration - savedown realistic (repeated/unsorted sym) data builds a valid queryable partition @@ -176,7 +176,7 @@ true,0,0,q,1=count select from ip where sym=`AAPL,1,1,p# lookup is correct - one run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,reset sortconfig to (::) for default-config savedown run,0,0,q,dbwrite.savedown[`:dbw_ihdb;2024.01.02;`trade;rd],1,1,savedown repeated-sym data with the default (time) config must not crash true,0,0,q,(asc x)~x:exec time from get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`),1,1,default-config partition sorted by time -true,0,0,q,`=attr (get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`))`sym,1,1,default-config leaves sym unattributed (not falsely parted) +true,0,0,q,`p=attr (get ` sv (.Q.par[`:dbw_ihdb;2024.01.02;`trade];`))`sym,1,1,default config parts sym (TorQ's config/sort.csv) comment,,,,,,,log call verification - switch to capturing logger run,0,0,q,dbwrite.init[enlist[`log]!enlist logcap],1,1,re-init with capturing logger @@ -245,7 +245,39 @@ after,0,0,q,rmrf`:dbw_sort_tp,1,1,cleanup sort partition after,0,0,q,rmrf`:dbw_def_tp,1,1,cleanup default partition after,0,0,q,rmrf`:dbw_md1,1,1,cleanup md1 partition after,0,0,q,rmrf`:dbw_md2,1,1,cleanup md2 partition +comment,,,,,,,round 2 - savedown hooks, as TorQ's dbwriteutils.q .save.manipulate and .save.postreplay +run,0,0,q,"dpath:{[d;p;t] ` sv (.Q.par[d;p;t];`)};htbl:([]time:2024.01.01D09:00 2024.01.01D08:00;sym:`IBM`AAPL;price:100 200f)",1,1,partition path helper and a test table +run,0,0,q,"dbwrite.init[`log`savedownmanipulation!(mylog;enlist[`trade]!enlist {update price:2*price from x})]",1,1,init with a trade manipulation +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.01;`trade;htbl]",1,1,savedown applies the manipulation before writing +true,0,0,q,"200 400f~asc exec price from get dpath[`:dbw_hook;2024.01.01;`trade]",1,1,the prices on disk are doubled +run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,a later init without the hook (as #762: a default must not overwrite a supplied hook) +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.02;`trade;htbl]",1,1,savedown again +true,0,0,q,"200 400f~asc exec price from get dpath[`:dbw_hook;2024.01.02;`trade]",1,1,the supplied hook still applies +run,0,0,q,"caplog:0#caplog;dbwrite.init[`log`savedownmanipulation!(logcap;enlist[`trade]!enlist {'`boom})]",1,1,init with a failing manipulation +run,0,0,q,"dbwrite.savedown[`:dbw_hook;2024.01.03;`trade;htbl]",1,1,savedown with the failing hook +true,0,0,q,"(update sym:`#sym from `sym`time xasc htbl)~update sym:`#value sym from select from get dpath[`:dbw_hook;2024.01.03;`trade]",1,1,the original rows are written unchanged (as legacy .save.manipulate returns x on failure) +true,0,0,q,"any (exec msg from caplog where fn=`error,ctx=`manipulate) like ""*boom*""",1,1,the failure is logged at error level +run,0,0,q,"dbwrite.postreplay[`:dbw_hook;2024.01.01]",1,1,the default postreplay {[d;p]} runs without 'rank +run,0,0,q,"dbwrite.init[`log`postreplay!(mylog;{[d;p] `prcalled set (d;p)})];dbwrite.postreplay[`:dbw_hook;2024.01.01]",1,1,a configured postreplay is called +true,0,0,q,"(`:dbw_hook;2024.01.01)~prcalled",1,1,with the hdb dir and partition +run,0,0,q,"dbwrite.init[`log`savedownmanipulation`postreplay!(mylog;()!();{[d;p]})]",1,1,reset the hooks for later rows + +comment,,,,,,,round 2 - default sort is TorQ's config/sort.csv: p# on sym, sorted by sym then time +run,0,0,q,dbwrite.init[enlist[`log]!enlist mylog],1,1,no sort config set +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.01;`trade;htbl]",1,1,savedown with the default config +true,0,0,q,"`p~attr (get dpath[`:dbw_dsort;2024.01.01;`trade])`sym",1,1,sym has p# on disk +true,0,0,q,"`AAPL`IBM~value exec sym from get dpath[`:dbw_dsort;2024.01.01;`trade]",1,1,rows are sorted by sym +run,0,0,q,"dbwrite.setconfig ([]tabname:enlist`trade;att:enlist`;column:enlist`time;sort:enlist 1b)",1,1,a user config with a trade row and no default row +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.02;`trade;htbl];dbwrite.savedown[`:dbw_dsort;2024.01.02;`quote;htbl]",1,1,savedown trade and a table missing from the config +true,0,0,q,"`~attr (get dpath[`:dbw_dsort;2024.01.02;`trade])`sym",1,1,the user's trade row overrides the default (no p#) +true,0,0,q,"`~attr (get dpath[`:dbw_dsort;2024.01.02;`quote])`sym",1,1,a table missing from a config with no default row is not sorted (as legacy sorttab) +run,0,0,q,"dbwrite.setconfig ([]tabname:`trade`default`default;att:``p`;column:`time`sym`time;sort:111b)",1,1,a user config with a default row +run,0,0,q,"dbwrite.savedown[`:dbw_dsort;2024.01.03;`quote;htbl]",1,1,savedown a table missing from the config +true,0,0,q,"`p~attr (get dpath[`:dbw_dsort;2024.01.03;`quote])`sym",1,1,it gets the config's default row (p# on sym) + after,0,0,q,rmrf`:dbw_good,1,1,cleanup good partition +after,0,0,q,rmrf`:dbw_hook,1,1,cleanup hook hdb tree +after,0,0,q,rmrf`:dbw_dsort,1,1,cleanup default-sort hdb tree after,0,0,q,rmrf`:dbw_attr_tp,1,1,cleanup attr partition after,0,0,q,rmrf`:dbw_hdb,1,1,cleanup savedown hdb tree after,0,0,q,rmrf`:dbw_ihdb,1,1,cleanup integration hdb tree diff --git a/di/eodtime/eodtime.md b/di/eodtime/eodtime.md index ff53355ce..fae4e9017 100644 --- a/di/eodtime/eodtime.md +++ b/di/eodtime/eodtime.md @@ -77,6 +77,15 @@ eodtime.getdailyadj[] / 0D01:00:00.000000000 ``` +### `getrolltimezone[]` / `getdatatimezone[]` / `getrolltimeoffset[]` +Return the settings `init` applied: the roll timezone, the data timezone and the roll offset. Legacy callers read +these as `.eodtime.rolltimezone`, `.eodtime.datatimezone` and `.eodtime.rolltimeoffset` (e.g. TorQ's +`dataaccessutils.q:11`, which fills them into its table properties). +```q +eodtime.getrolltimezone[] +/ `Europe/London +``` + ### `getdailyadjustment[]` **Recompute** the UTC offset for the data timezone at the current time. Call after an EOD roll to get a fresh offset - important when the data timezone observes DST. ```q diff --git a/di/eodtime/eodtime.q b/di/eodtime/eodtime.q index 7bb3e64cd..f7f31f8fc 100644 --- a/di/eodtime/eodtime.q +++ b/di/eodtime/eodtime.q @@ -48,7 +48,9 @@ getday:{[p]"d"$(p+adjtime[p])-rolltimeoffset}; getdailyadjustment:{ / utc-equivalent timezones have zero offset if[datatimezone in utczones;:0D]; - `timespan$tz.gmttolocal[datatimezone;.z.p]-.z.p + / one clock read, so the offset is exact + p:.z.p; + `timespan$tz.gmttolocal[datatimezone;p]-p }; / returns normalised roll time-of-day (utc) for the zone offset at timestamp p, wrapped to [0D,1D) @@ -66,6 +68,10 @@ getroll:{[p] getd:{d}; getnextroll:{nextroll}; getdailyadj:{dailyadj}; +/ the settings, as legacy's .eodtime.rolltimezone/datatimezone/rolltimeoffset (read by dataaccessutils.q:11) +getrolltimezone:{rolltimezone}; +getdatatimezone:{datatimezone}; +getrolltimeoffset:{rolltimeoffset}; / state setters setnextroll:{.z.m.nextroll:x}; diff --git a/di/eodtime/init.q b/di/eodtime/init.q index bb21a7586..d6e2991ca 100644 --- a/di/eodtime/init.q +++ b/di/eodtime/init.q @@ -9,4 +9,4 @@ tz:use`di.tz / (pre-load manifest walk) and this export (post-load session audit of a loaded, declared peer). version:first read0`:::VERSION -export:([init;getd;getnextroll;getdailyadj;getroll;getdailyadjustment;setnextroll;setdailyadj;setd;version]) +export:([init;getd;getnextroll;getdailyadj;getrolltimezone;getdatatimezone;getrolltimeoffset;getroll;getdailyadjustment;setnextroll;setdailyadj;setd;version]) diff --git a/di/eodtime/test.csv b/di/eodtime/test.csv index 2f91097fa..94b39d3e8 100644 --- a/di/eodtime/test.csv +++ b/di/eodtime/test.csv @@ -61,6 +61,11 @@ run,0,0,q,eodtime.init[`rolltimezone`datatimezone`rolltimeoffset`log!(`$"GMT";`$ true,0,0,q,-16h=type eodtime.getdailyadjustment[],1,1,Europe/London datatimezone returns timespan type true,0,0,q,0D<=eodtime.getdailyadjustment[],1,1,Europe/London datatimezone returns non-negative offset +comment,,,,,,,the daily adjustment is an exact offset (Asia/Tokyo is +9h with no DST) +run,0,0,q,eodtime.init[`rolltimezone`datatimezone`rolltimeoffset`log!(`$"GMT";`$"Asia/Tokyo";0D00:00:00.000;logdep)],1,1,reinit with Tokyo datatimezone +true,0,0,q,0D09=eodtime.getdailyadj[],1,1,the adjustment stored at init is exactly 9 hours +true,0,0,q,all 0D09={eodtime.getdailyadjustment[]} each til 100,1,1,every computed adjustment is exactly 9 hours + comment,,,,,,,init - empty config (just log dep) applies all defaults run,0,0,q,eodtime.init[enlist[`log]!enlist logdep],1,1,init with just log dep applies all defaults true,0,0,q,0D=eodtime.getdailyadj[],1,1,default datatimezone (GMT) produces zero daily adjustment @@ -84,6 +89,14 @@ comment,,,,,,,init - accepts any dict already shaped to the binary {[c;m]} contr run,0,0,q,sixlvllog:`trace`debug`info`warn`error`fatal!({[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]}),1,1,hand-built six-level dict matching di.util.log's logdict shape run,0,0,q,eodtime.init[`log`rolltimezone!(sixlvllog;`$"GMT")],1,1,superset log dict accepted as-is - only info/warn/error are used +comment,,,,,,,settings readers (legacy .eodtime.rolltimezone/datatimezone/rolltimeoffset) +run,0,0,q,"eodtime.init[`log`rolltimezone`datatimezone`rolltimeoffset!(logdep;`$""Europe/London"";`$""America/New_York"";0D17:00:00.000)]",1,1,init with non-default settings +true,0,0,q,"(`$""Europe/London"")~eodtime.getrolltimezone[]",1,1,getrolltimezone returns the roll timezone init applied +true,0,0,q,"(`$""America/New_York"")~eodtime.getdatatimezone[]",1,1,getdatatimezone returns the data timezone init applied +true,0,0,q,0D17:00:00.000~eodtime.getrolltimeoffset[],1,1,getrolltimeoffset returns the roll offset init applied +run,0,0,q,eodtime.init[enlist[`log]!enlist logdep],1,1,init with defaults only +true,0,0,q,"((`$""GMT"");(`$""GMT"");0D)~(eodtime.getrolltimezone[];eodtime.getdatatimezone[];eodtime.getrolltimeoffset[])",1,1,the readers give legacy's defaults (GMT; GMT; 0D) + comment,,,,,,,log call verification - capturing logger sees init message with binary {[c;m]} args run,0,0,q,caplog:`info`warn`error!({[c;m] `.test.cap upsert(`info;m)};{[c;m] `.test.cap upsert(`warn;m)};{[c;m] `.test.cap upsert(`error;m)}),1,1,capturing log mock - binary {[c;m]} run,0,0,q,.test.cap:([] fn:`symbol$();msg:()),1,1,initialise log capture table diff --git a/di/merge/merge.md b/di/merge/merge.md index 2165b6554..830db67d1 100644 --- a/di/merge/merge.md +++ b/di/merge/merge.md @@ -95,7 +95,7 @@ merge.getpartchunks[partdirs; 1000000] ``` ### `mergebypart[extrapartitiontype;dest;partchunks]` -Merge one batch of whole partition segments into destination partition `dest`, re-sorting by the parted column(s) `extrapartitiontype` first if the `p#` attribute cannot otherwise be applied. Typically iterated over the output of `getpartchunks`. Each segment in `partchunks` is read individually and protected: a missing or corrupt segment file is error-logged and dropped, it does not take its batch-mates down with it - the rest of the batch still merges. If every segment in the batch fails to read, nothing is upserted and that is error-logged too. +Merge one batch of whole partition segments into destination partition `dest`, re-sorting by the parted column(s) `extrapartitiontype` first if the `p#` attribute cannot otherwise be applied. Typically iterated over the output of `getpartchunks`. As in TorQ, the segments are read unprotected: a missing or corrupt segment fails the batch before anything is upserted. A failed upsert is error-logged and then signalled. Either way the error reaches the caller, which therefore does not go on to delete the segments. ```q merge.mergebypart[`sym; ` sv dest,`] each merge.getpartchunks[partdirs;lim] ``` @@ -107,13 +107,13 @@ merge.mergebycol[(`trade;schema); dest] each partdirs ``` ### `mergehybrid[extrapartitiontype;tableinfo;dest;partdirs;mergelimit]` -Merge `partdirs` using whichever method fits each: whole-partition for those within `mergelimit`, column-by-column for any single partition over it (creating the `.d` file if column-by-column merging produced none). If `extrapartitiontype` is non-empty, once both paths have finished it re-sorts and re-applies the `p#` attribute to `dest` as a whole - see "The parted attribute is applied once, on the whole destination" below for why that happens here rather than per-batch. +Merge `partdirs` using whichever method fits each: whole-partition for those within `mergelimit`, column-by-column for any single partition over it (creating the `.d` file if column-by-column merging produced none). As in TorQ, `dest` is not re-sorted or re-attributed; the callers apply `p#` after merging (di.torq.proc.wdb, di.torq.proc.tickerlogreplay). ### `checkpartitiontype[tablename;extrapartitiontype]` Error-log any parted column supplied for the table that is absent from it. ### `checkenumerabletype[tablename;extrapartitiontype]` -Confirm every parted column has an enumerable type (`h`/`i`/`j`/`s`) so it can key a partition; error-logs otherwise. +Confirm every parted column has an enumerable type (`h`/`i`/`j`/`s`) so it can key a partition. Otherwise it error-logs and signals. ### `getextrapartitions[tablename;extrapartitiontype]` Return the distinct combinations of the parted column values - one per partition directory. @@ -122,7 +122,7 @@ Return the distinct combinations of the parted column values - one per partition Return the partition values grouped by the first character of the (single) parted column. ### `getextrapartitiontype[sortconfig;tablename]` -Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. Error-logs when neither is defined. +Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. When neither is defined it error-logs and returns `()`, as TorQ does. ```q merge.getextrapartitiontype[dbw.getconfig[]; `trade] ``` @@ -182,56 +182,11 @@ unmerged with no trace. When `init` finds pre-existing tracked partitions it say the log rather than something a future debugger has to discover by reading source. A fresh, first-ever `init` (nothing tracked yet) logs the plain `"di.merge initialised"` with no such claim. -**`mergebycol` deliberately keeps failing uncaught on a missing/corrupt segment column; `mergebypart` -does not.** These are not equivalent failure modes, so making them match would not obviously be the -safer choice - it might be the wrong one. `mergebypart` reads each segment in a batch individually and -protected: a missing/corrupt segment file is error-logged and dropped without disturbing its -batch-mates, which still merge. The remaining, surviving segments in the batch are then joined and -upserted as one unit - if *that* upsert itself fails (e.g. a schema mismatch), the whole batch's data -is lost together, which is incomplete but still internally consistent: `dest` simply doesn't get that -batch's data yet, nothing else in `dest` is disturbed. `mergebycol` merges one column at a time into -the *same* `dest`; if a swallowed failure let it carry on past a bad column, `dest` would end up with -some columns reflecting the new data and others silently stale - a genuinely worse, -silently-inconsistent partition, not just a delayed merge. So `mergebycol`'s column read is -intentionally left unprotected: a missing or unreadable segment column throws straight out of -`mergebycol`/`mergehybrid`'s column-by-column path, by design, rather than risking a half-updated -destination. (This also happens to match the legacy TorQ source and Olly's draft, both of which have -the same unprotected-read structure - but the reason to keep it here is the partial-column-write risk -above, not merely that it matches prior behaviour.) - ---- - -## The parted attribute is applied once, on the whole destination - -A full write-down-and-merge smoke test (real segments, real `di.log`, both of TorQ's `partbyenum` -and `partbyfirstchar` write patterns) found that `mergehybrid` never actually left `dest` with the -`p#` attribute set, even when every batch merged cleanly - `mergebypart`'s own resort logic decides -*whether* `p#` could apply and reorders rows accordingly, but applying the attribute to an in-memory -batch and then `upsert`-ing it to disk does not persist the attribute: `upsert` appends raw values -onto the on-disk column, it does not carry an in-memory attribute through to the file. Confirmed -empirically (`meta` on the merged destination showed no attribute on the parted column, in a -mergebypart-only scenario with nothing left to resort). - -Worse, `mergebycol` never even tries: for TorQ's `partbyfirstchar` write mode, a single segment can -hold *several* parted-column values in arrival order, not one. If that segment is large enough to -route through `mergebycol` instead of `mergebypart`, its rows are appended as-is - the destination -ends up genuinely unsorted and non-contiguous by the parted column. Confirmed empirically too: after -merging first-character-grouped segments through `mergehybrid`, the destination's parted column was -neither sorted nor grouped on disk. - -Trying to fix this per-batch (inside `mergebypart`, or per-column inside `mergebycol`) cannot give a -real guarantee either way: a batch that is already correctly grouped in isolation can still land next -to a *different* batch's values on disk, and `upsert` does not re-validate the combined result. -The only way to genuinely guarantee `` `p# `` on `dest` is to look at the whole thing at once. So -`mergehybrid` does that as a final step, after every whole-partition batch and every column-by-column -segment has been merged: it reads `dest` back, re-sorts it by `extrapartitiontype`, re-applies the -attribute, and writes the whole table back. This is a deliberate, necessary departure from this -module's "keeps memory flat" design goal (see the file header) for that one final step - the -alternative is a `dest` that is silently never truly parted, which is worse. Batch-by-batch merging -into `dest` still only ever holds one batch/column in memory at a time; only this last step reads -`dest` in full, once, per `mergehybrid` call. `mergebypart` called standalone in a caller-driven loop -(bypassing `mergehybrid` - see its usage example above) does **not** get this guarantee automatically; -route through `mergehybrid` if a properly parted `dest` matters. +**A failed merge is signalled, as in TorQ.** A missing or unreadable segment fails `mergebypart` (whole +batch) or `mergebycol` (that column) before the data reaches `dest`. A failed `mergebypart` upsert is +error-logged and then signalled. In each case the caller's merge stops before it deletes the segments, +so the data can be merged again. One difference remains: a failed per-column upsert in `mergebycol` is +error-logged and the merge continues. Legacy swallowed it silently, because its handler was never called. --- @@ -285,7 +240,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.merge ``` -The test suite injects a no-op binary mock logger (and a capturing logger for the log-path assertions). It covers: dependency validation (non-dict deps / missing / non-dict / incomplete `log` all throw, with the `di.merge` error prefix); the `requireinit` guard rejecting every exported function before `init` has run; config application via row-count vs byte-size batching, defaults and overrides; `trackpartition`/`getpartsizes`/`clearpartsizes`/`syncpartsizes`; the `getpartchunks` batching and `partlimit` splitting logic; `version`/`getapimeta` shape; end-to-end `mergebypart`, `mergebycol` and `mergehybrid` against real on-disk segments written to a scratch directory (cleaned up afterwards); `mergebypart` isolating one missing segment from healthy batch-mates in the same batch; and `mergehybrid` re-sorting and re-attributing the whole destination once both merge paths have run. +The test suite injects a no-op binary mock logger (and a capturing logger for the log-path assertions). It covers: dependency validation (non-dict deps / missing / non-dict / incomplete `log` all throw, with the `di.merge` error prefix); the `requireinit` guard rejecting every exported function before `init` has run; config application via row-count vs byte-size batching, defaults and overrides; `trackpartition`/`getpartsizes`/`clearpartsizes`/`syncpartsizes`; the `getpartchunks` batching and `partlimit` splitting logic; `version`/`getapimeta` shape; end-to-end `mergebypart`, `mergebycol` and `mergehybrid` against real on-disk segments written to a scratch directory (cleaned up afterwards); `mergebypart` failing the batch on a missing segment and signalling a failed upsert; `mergehybrid` leaving the destination in write order with no attribute; `getextrapartitiontype` returning `()` when no row applies; and `checkenumerabletype` signalling a non-enumerable column. Mock loggers only check that a message was logged at the right level - they do not process the message content the way a real logger does, so they cannot catch a malformed message (a list where a flat string was expected, for instance). Where a message's *shape* matters, not just that it fired, the test asserts on structure too (e.g. `10h=type` on the captured message) rather than relying on the mock alone. @@ -297,4 +252,4 @@ Mock loggers only check that a message was logged at the right level - they do n - `init` must be called before any other function - enforced by the `requireinit` guard on every other exported function, not just documented convention. - The `VERSION`-file read pattern (fail loud on missing/unreadable/empty, `trim` against trailing whitespace) follows `di.servers`, not `di.eodtime` (which has no `VERSION` handling at all). - The merge functions operate on on-disk paths (`get`/`set`/`upsert` against file symbols); they do not manage the segment or destination directory lifecycle - that remains the caller's responsibility. -- A real-logger smoke test (see "The parted attribute is applied once, on the whole destination" above) also caught `checkenumerabletype`'s error-message construction building a malformed list instead of a flat string for a multi-symbol `extrapartitiontype` - the k4unit mock loggers don't process message content, so this was invisible there. Fixed to match `checkpartitiontype`'s already-correct `", " sv string ...` pattern, with a regression test that checks the message's shape (`10h=type`), not just that it fired. +- A real-logger smoke test also caught `checkenumerabletype`'s error-message construction building a malformed list instead of a flat string for a multi-symbol `extrapartitiontype` - the k4unit mock loggers don't process message content, so this was invisible there. Fixed to match `checkpartitiontype`'s already-correct `", " sv string ...` pattern, with a regression test that checks the message's shape (`10h=type`), not just that it fired. diff --git a/di/merge/merge.q b/di/merge/merge.q index 519c41819..76bde63e1 100644 --- a/di/merge/merge.q +++ b/di/merge/merge.q @@ -141,38 +141,21 @@ mergebypart:{[extrapartitiontype;dest;partchunks] / re-sorts the batch by the parted column(s) first if the p# attribute cannot otherwise be applied requireinit[`mergebypart]; .z.m.loginfo[`merge;"reading partition/partitions ",", " sv string partchunks]; - / read each segment separately and protected, so one missing/corrupt segment file does not take - / its batch-mates down with it - a bare get each/join here would fail the whole batch together - reads:{[p] @[get;p;{[p;e] .z.m.logerr[`merge;"failed to read segment ",(string p), - ", not merged this batch - error is - ",e];(::)}[p;]]} each partchunks; - ok:98h=type each reads; - if[not all ok; - .z.m.logerr[`merge;"skipping ",string[sum not ok]," of ",string[count partchunks], - " segment(s) in this batch that failed to read"]]; - chunks:reads where ok; - if[0=count chunks; - .z.m.logerr[`merge;"no segments in this batch read successfully, nothing upserted to ",string dest]; - :(::)]; + / an unreadable segment fails the batch before anything is upserted, so the segments are kept + chunks:get each partchunks; / a single segment reads back as a table; multiple read back as a list of tables to join if[98<>type chunks;chunks:(,/)chunks]; .z.m.loginfo[`resort;"checking that the contents of this subpartition conform"]; / can the p# attribute be applied as-is? if not, the data must be re-sorted by the parted column - / applying p# here would not survive the upsert below - upsert appends raw values onto the - / on-disk column and does not persist an in-memory attribute, so this only orders the rows - / within this batch; mergehybrid applies the real, persisted attribute once across the whole - / destination after every batch (and any mergebycol columns) have been upserted pattrtest:@[{@[x;y;`p#];0b}[chunks;];extrapartitiontype;{1b}]; if[pattrtest; .z.m.loginfo[`resort;"re-sorting contents of subpartition"]; chunks:xasc[extrapartitiontype;chunks]; ]; .z.m.loginfo[`merge;"upserting ",(string count chunks)," rows to ",string dest]; - / append the merged rows to permanent storage, logging (not throwing) on failure - / e arrives already a string from the protected-apply mechanism - do not re-stringify it: string - / of an already-string value maps over each char individually, corrupting the message and making - / this handler itself throw, which defeats the log-not-throw contract this line exists to provide + / append the merged rows to permanent storage; a failure is logged and signalled so the caller keeps the segments .[upsert;(dest;chunks); - {[e;d;p] .z.m.logerr[`merge;"failed to merge to ",string[d]," from segments ",(", " sv string p)," Error is - ",e]}[;dest;partchunks]]; + {[e;d;p] .z.m.logerr[`merge;"failed to merge to ",string[d]," from segments ",(", " sv string p)," Error is - ",e];'e}[;dest;partchunks]]; }; / merge one segment into the destination partition a column at a time @@ -206,25 +189,6 @@ mergehybrid:{[extrapartitiontype;tableinfo;dest;partdirs;mergelimit] (` sv dest,`.d) set cols tableinfo[1]; ]; ]; - / mergebypart applies p# per batch and mergebycol applies none at all, so neither guarantees the - / full destination ends up grouped once multiple batches and/or both methods have all appended - / to it - re-sort and re-apply the attribute to the whole destination once, here, after every - / path above has finished, rather than leaving that guarantee split across per-batch calls - if[0100,bid<200"); columns:("time,sym,price";"")) +q)conditions:([tabname:`trade`quote] filters:("";"bid>100,bid<200"); columns:("time,sym,price";"")) q)pubsub.subscribe[`;conditions] q)pubsub.subscribestr["trade";"GOOG,AAPL"] diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index daba39f9e..baab6ec90 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -52,7 +52,7 @@ subfiltered:{[table;filters] addfiltered:{[table;cond] / subscribe to tables with custom conditions / if either filters or columns parsing fails, subscription should not be logged as no half query should be created - filters:$[all null f:cond[table;`filts];();@[parse;"select from t where ",f;{'"incorrect filters for parsing"}][2]]; + filters:$[all null f:cond[table;`filters];();@[parse;"select from t where ",f;{'"incorrect filters for parsing"}][2]]; columns:$[all null c:cond[table;`columns];();@[parse;"select ",c," from t";{'"incorrect columns for parsing"}][4]]; @[eval;(?;schemas table;filters;0b;columns);{'"incorrect query with filters-",.Q.s1[y]," columns-",.Q.s1[z]," error-",x}[;filters;columns]]; @[.z.M;`reqfilteredtbl;upsert;(table;.z.w;filters;columns)] @@ -111,7 +111,7 @@ subscribestr:{[table;syms] subscribestrfilter:{[table;filters;columns] / allow non-kdb+ process to subscribe to tables with custom conditions - res:subscribe[`$table;1!enlist `table`filts`columns!(`$table;filters;columns)]; + res:subscribe[`$table;1!enlist `table`filters`columns!(`$table;filters;columns)]; :$[10h~type last res;'last res;res]; }; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index 4f7b23cb3..4fe04d3ac 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -74,7 +74,7 @@ run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table in `trade", 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(in;`sym;enlist `AAPL`GOOG),1,, test symbols are listed under filters -run,0,0,q,"conditions:([tabname:`trade`quote]filts:("""";""bid>100,bid<200"");columns:(""time,sym,price"";""""))",1,,create custom conditions for subscription +run,0,0,q,"conditions:([tabname:`trade`quote]filters:("""";""bid>100,bid<200"");columns:(""time,sym,price"";""""))",1,,create custom conditions for subscription run,0,0,q,res:h(`pubsub.subscribe;`;conditions),1,,test subscribe with custom conditions true,0,0,q,`trade`quote~res[0],1,,client receives subscribed table confirmation true,0,0,q,98h~type res[1;0],1,,client receives table schema @@ -114,6 +114,18 @@ 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 +run,0,0,q,"tconds:([tabname:enlist`trade]filters:enlist""price>10"";columns:enlist""sym,price"")",1,,conditions in TorQ's tabname/filters/columns shape +run,0,0,q,res:h(`pubsub.subscribe;`trade;tconds),1,,subscribe trade with TorQ-shaped conditions +run,0,0,q,res:h"select from .m.di.0pubsub.reqfilteredtbl where table=`trade",1,,check filtered table for the subscription +run,0,0,q,res:select from res where handle=clt,1,,check filtered table for the subscription +true,0,0,q,(enlist enlist enlist(>;`price;10))~res`filts,1,,filters column is parsed into the where clause +true,0,0,q,(enlist`sym`price!`sym`price)~res`columns,1,,columns are parsed into the column list +run,0,0,q,delete from `trade,1,,clear the local trade table +run,0,0,q,"h(`pubsub.publish;`trade;([]time:3#.z.p;sym:`IBM`AAPL`IBM;price:5 20 30f;tsize:1 2 3i))",1,,publish rows either side of the filter +true,0,0,q,20 30f~trade`price,1,,only rows meeting the filter are received +true,0,0,q,all null trade`tsize,1,,only the selected columns are received +fail,0,0,q,"h(`pubsub.subscribe;`trade;([tabname:enlist`trade]filters:enlist""price>>"";columns:enlist""""))",1,,an invalid filter is rejected + 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 diff --git a/di/serverselect/serverselect.md b/di/serverselect/serverselect.md index dd3ace3ad..aaf0b2b96 100644 --- a/di/serverselect/serverselect.md +++ b/di/serverselect/serverselect.md @@ -102,6 +102,9 @@ srvsel.addserversfromtable[`rdb`hdb; .servers.SERVERS] | `gethandlebytype[ptype;sel]` | Convenience projection of `getserverbytype` returning `handle` | | `gethpbytype[ptype;sel]` | Convenience projection of `getserverbytype` returning `hpup` | +These share their names with di.torq.servers' root `.servers.getserverbytype`/`.servers.gethpbytype` (TorQ's +`trackservers.q`), but read a different registry: this module's server pool, not `.servers.SERVERS`. + `getservers` returns a table including an `attribmatch` column — a dictionary of `attrname!(complete_match_bool;matched_values)` per attribute key in `req`. When `lookups` is not `` ` ``, `nameortype` must be `` `servertype `` or `` `procname ``; any other value throws (and logs) a `di.serverselect:` error rather than silently falling through to a `procname` lookup. All `di.serverselect:` error conditions — including the input-type checks on `addserverfull`/`setserveractive` and the connection-table column check on `addserversfromtable` — are logged via `.z.m.logerr` before being signalled. diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 74863a5b7..d2bc71c91 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -65,7 +65,7 @@ publisher for its `tptype` (`standard`, `chained` or `segmented`) and subscribes - Settings, both required; `di/torq/settings/default.q` declares them: `autoreconnect` (`0b`), `checksubscriptionperiod` (`0D00:00:10`). - `init` registers, once per process: `pc[::;]` on `.z.pc` through `handlers`, and - `checksubscriptions` every `checksubscriptionperiod` (converted to seconds, timer mode 1) through + `checksubscriptions` every `checksubscriptionperiod` (a timespan, timer mode 1) through `timer` when the period is above 0. ## Not yet (future) diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 8d1e20926..fb33c95fb 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -16,6 +16,9 @@ SUBSCRIPTIONS:([]handle:`int$();tabs:();syms:();subtime:`timestamp$()) / .sub .z.pc handler and check job are registered once registered:0b +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + init:{[config;deps] if[not `log in key deps;'"di.subscriptions: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.subscriptions: timer dependency is required - see di.timer"]; @@ -25,10 +28,12 @@ init:{[config;deps] / all settings required if[count m:`autoreconnect`checksubscriptionperiod except key config;'"di.subscriptions: missing settings: ",", " sv string m]; .z.m.autoreconnect:config`autoreconnect; - .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod; + p:totimespan config`checksubscriptionperiod; + if[null p;'"di.subscriptions: checksubscriptionperiod must be a timespan"]; + .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*p; if[not .z.m.registered; (deps[`handlers]`register)[`.z.pc;`;`sub;0j;pc[::;]]; - if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();`long$checksubscriptionperiod%0D00:00:01;1;()!()]]; + if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();checksubscriptionperiod;1;()!()]]; .z.m.registered:1b]; } diff --git a/di/subscriptions/test.csv b/di/subscriptions/test.csv index ee5269d14..52be2c0c4 100644 --- a/di/subscriptions/test.csv +++ b/di/subscriptions/test.csv @@ -26,7 +26,7 @@ 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 pc on .z.pc -true,0,0,q,"(enlist(`checksubscriptions;10;1))~flip value flip timercalls",1,,init registered checksubscriptions every 10s +true,0,0,q,"(enlist(`checksubscriptions;0D00:00:10;1))~flip value flip timercalls",1,,init registered checksubscriptions every 10s run,0,0,q,sub.init[subcfg ()!();deps[]],1,,init again true,0,0,q,"(1;1)~(count handlercalls;count timercalls)",1,,second init registers nothing new true,0,0,q,"((subcfg ()!())`autoreconnect`checksubscriptionperiod)~.m.di.0subscriptions.autoreconnect,.m.di.0subscriptions.checksubscriptionperiod",1,,init stores the settings file values @@ -54,5 +54,9 @@ run,0,0,q,".servers.enabled:1b;.servers.connectcustom:{[r]};.m.di.0subscriptions run,0,0,q,".sub.subscribe[`trade;`;0b;0b;peerproc[]]",1,,subscribe true,0,0,q,.m.di.0subscriptions.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) +comment,,,,,,,checksubscriptionperiod from TOML values +true,0,0,q,"(enlist(`checksubscriptions;0D00:00:10;1))~periodinit ""0D00:00:10""",1,,a string period registers a timespan job +true,0,0,q,(enlist(`checksubscriptions;0D00:00:10;1))~periodinit 10,1,,a number of seconds registers a timespan job +fail,0,0,q,"periodinit ""junk""",1,,an unparseable period errors after,0,0,q,teardownfixture[],1,,remove the temp log dir diff --git a/di/subscriptions/test.q b/di/subscriptions/test.q index 0717e1ccc..30decdf4d 100644 --- a/di/subscriptions/test.q +++ b/di/subscriptions/test.q @@ -17,8 +17,8 @@ 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;;])} -timercalls:([]id:`symbol$();period:`long$();mode:`long$()) -mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;`long$period;`long$mode);} +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;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)} @@ -82,4 +82,7 @@ pcclosecheck:{[] (a;b) } +/ a fresh init with checksubscriptionperiod p; returns the timer jobs it registered +periodinit:{[p] .m.di.0subscriptions.registered:0b; delete from `timercalls; sub.init[subcfg enlist[`checksubscriptionperiod]!enlist p;deps[]]; flip value flip timercalls} + teardownfixture:{[] @[{(neg x)"exit 0";(neg x)[]};tph;()]; system "sleep 0.3"; system "rm -rf ",BASE; } diff --git a/di/timer/init.q b/di/timer/init.q index 3259377eb..6db9344bf 100644 --- a/di/timer/init.q +++ b/di/timer/init.q @@ -9,7 +9,7 @@ jobs:( func:(); / function to be ran, can be passed as symbol reference or as a function itself params:(); / function parameters to be passed to function at execution created:`timestamp$(); / timestamp of function initiation - period:`int$(); / time period to base timer scheduling on + period:`timespan$(); / time period to base timer scheduling on mode:`short$(); / mode to base scheduling logic on prevstart:`timestamp$(); / scheduled start timestamp of previous run actualstart:`timestamp$(); / start timestamp of previous run @@ -20,18 +20,32 @@ jobs:( maxruns:`int$(); / optional flag to disable time function after number of runs maxtime:`timestamp$(); / optional flag to disable job after timestamp disableonfail:`boolean$(); / if job fails will disable future runs - startattime:`timestamp$() / optional custom start time to run for the first time + startattime:`timestamp$(); / optional custom start time to run for the first time + description:() / free text description, as TorQ's timer ); / job functions for adding new functions to be scheduled and executed -addjob.opts:(`maxruns`maxtime`disableonfail`startattime)!(0Wi;0Wp;1b;0Np); +addjob.opts:(`maxruns`maxtime`disableonfail`startattime`dupcheck`description)!(0Wi;0Wp;1b;0Np;1b;""); + +/ jobs running function f with parameters p +fpjobs:{[f;p] select from jobs where (f~/:func)&((),p)~/:params}; addjob.custom:{[id;func;params;period;mode;opts] / fully configurable base version of adding a timer job to in memory table if[id in key .z.M.jobs;'"Cannot add id : ",(string id)," already exists in jobs"]; + / as TorQ's .timer.rep, the period is a timespan and the mode one of the scheduling modes + if[-16h<>type period;'"period must be a timespan"]; + if[not (mode:`short$mode) in key nextstart;'"mode can only be one of ",-3!key nextstart]; if[-11h=type func;get func]; opts:addjob.opts,opts; - .z.M.jobs insert (id;func;params;cp[];`int$period;`short$mode;0Np;0Np;0Np;0Np;0i;1b;`int$(opts`maxruns);opts`maxtime;opts`disableonfail;opts`startattime); + / as TorQ's timer check, a duplicate function and parameters is rejected unless dupcheck is off + if[opts[`dupcheck]&0/di/torq/bin/torqx.sh start # # Deliberately thin: reads process.csv only to ENUMERATE rows (which processes # exist, for "start all"/"status all") and to look up a named row's proctype/port. @@ -27,7 +27,9 @@ else exit 1 fi -: "${TORQXHOME:?TORQXHOME must be set (see setenv.sh)}" +# torqx_init.q's directory: $TORQXHOME/di/torq/bin if set, else this script's own directory +TORQXBIN="${TORQXHOME:+$TORQXHOME/di/torq/bin}" +: "${TORQXBIN:=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" : "${TORQXAPPCONFIG:?TORQXAPPCONFIG must be set (see setenv.sh)}" : "${TORQXAPPHOME:?TORQXAPPHOME must be set (see setenv.sh)}" : "${TORQXSTACKID:?TORQXSTACKID must be set (see setenv.sh)}" @@ -126,7 +128,7 @@ start_one() { return fi echo "starting $procname ($PROCTYPE)... log: $logfile" - QINIT="$TORQXHOME/di/torq/bin/torqx_init.q" nohup $QCMD \ + QINIT="$TORQXBIN/torqx_init.q" nohup $QCMD \ -torqxstackid "$TORQXSTACKID" -proctype "$PROCTYPE" -procname "$procname" \ $portarg "$@" > "$logfile" 2>&1 & disown @@ -157,7 +159,7 @@ start_one_tmux() { # a single bash -c string), then env applies the QHOME/QLIC policy above before exec'ing q. local extra="$*" tmux new-session -d -s "$sess" -c "$PWD" \ - "bash -c 'source \"$SETENV\" && exec env $uflags QINIT=\"\$TORQXHOME/di/torq/bin/torqx_init.q\" $aflags \$QCMD -torqxstackid \"\$TORQXSTACKID\" -proctype \"$PROCTYPE\" -procname \"$procname\" $portarg $extra'" + "bash -c 'source \"$SETENV\" && exec env $uflags QINIT=\"$TORQXBIN/torqx_init.q\" $aflags \$QCMD -torqxstackid \"\$TORQXSTACKID\" -proctype \"$PROCTYPE\" -procname \"$procname\" $portarg $extra'" # keep a crashed process's pane (and its stack trace) visible instead of the session vanishing tmux set-option -t "$sess" remain-on-exit on >/dev/null # tee the pane to the usual logfile so logs still exist in tmux mode @@ -207,7 +209,7 @@ After=network.target [Service] Type=simple WorkingDirectory=${TORQXAPPHOME} -ExecStart=/bin/bash -lc 'source "${TORQXAPPHOME}/setenv.sh" && exec env QINIT="\$TORQXHOME/di/torq/bin/torqx_init.q" \$QCMD -torqxstackid "\$TORQXSTACKID" -proctype ${PROCTYPE} -procname ${procname} ${portarg}' +ExecStart=/bin/bash -lc 'source "${TORQXAPPHOME}/setenv.sh" && exec env QINIT="${TORQXBIN}/torqx_init.q" \$QCMD -torqxstackid "\$TORQXSTACKID" -proctype ${PROCTYPE} -procname ${procname} ${portarg}' Restart=on-failure RestartSec=2 diff --git a/di/torq/bin/torqx_init.q b/di/torq/bin/torqx_init.q index d1403e144..47a77fb75 100644 --- a/di/torq/bin/torqx_init.q +++ b/di/torq/bin/torqx_init.q @@ -2,7 +2,7 @@ / project. Turns this q session into a TorqX process. Replaces per-process / start_.q launcher files. / - -/ Usage (via an alias such as `alias torqx='QINIT=$TORQXHOME/di/torq/bin/torqx_init.q $QCMD'`, +/ Usage (via an alias such as `alias torqx='QINIT=/di/torq/bin/torqx_init.q $QCMD'`, / see TorqX-POC/setenv.sh, or invoked directly by bin/torqx.sh): / torqx -proctype hdb -procname hdb1 (explicit identity) / torqx -p 5560 (auto-detect identity from process.csv) diff --git a/di/torq/config/config.md b/di/torq/config/config.md index 3ee5a4121..ed9d5e298 100644 --- a/di/torq/config/config.md +++ b/di/torq/config/config.md @@ -14,7 +14,7 @@ files into namespaces or hold any global store. This is the shape `di.torq` cons ```q config:use`di.torq.config -cfg:config.cascade[builtinroot;approot;`rdb;`rdb1] / -> `subscribeto`rows`... !(...) +cfg:config.cascade[builtinroot;approot;`;`rdb;`rdb1] / -> `subscribeto`rows`... !(...); ` = no parentproctype / di.torq stamps identity and hands the whole dict to each module's init: cfg:cfg,`proctype`procname!(`rdb;`rdb1) rdb.init[cfg;`log`timer!(logdep;timerdep)] @@ -27,8 +27,9 @@ requires `init`. ## Precedence -The cascade is resolved over **two roots** (`builtinroot`, `approot`) × a **three-tier -name sequence** (`default` → `{proctype}` → `{procname}`). Precedence is **name-major**: +The cascade is resolved over **two roots** (`builtinroot`, `approot`) × a **name sequence** +(`default` → `{parentproctype}` → `{proctype}` → `{procname}`, as TorQ's `torq.q:593`; the +`{parentproctype}` tier only when one is given, a null symbol meaning none). Precedence is **name-major**: 1. A more specific **name** always wins — `{procname}` beats `{proctype}` beats `default`. 2. **Within a name**, the later (app) root overrides the builtin root. @@ -40,8 +41,8 @@ proctype** value, not the app default (name beats root). Effective load order, l priority: ``` -builtin/default(.q,.toml) → app/default → builtin/{proctype} → app/{proctype} - → builtin/{procname} → app/{procname} (each tier: .toml overrides .q) +builtin/default(.q,.toml) → app/default → [builtin/{parentproctype} → app/{parentproctype}] + → builtin/{proctype} → app/{proctype} → builtin/{procname} → app/{procname} (each tier: .toml overrides .q) ``` `overrideconfig` sits on **top** of all of this — the command-line layer (see below). @@ -101,7 +102,9 @@ first — di.torq.config does no wrapping. | Function | Signature | Description | |---|---|---| -| `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | +| `cascade` | `cascade[builtinroot;approot;parentproctype;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{parentproctype}`/`{proctype}`/`{procname}` name sequence (`parentproctype` a null symbol for none) and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | +| `getconfig` | `getconfig[builtinroot;approot;path;level]` | The config file(s) for `path` (relative to a root), as TorQ's `.proc.getconfig`. App before builtin. Level `0`: the first that exists, else the builtin path; `1`: the app path if it exists, then the builtin path; `2`: both, whether or not they exist. An empty `approot` is an unset app root. Returns a symbol list, as legacy. Pure: the roots are arguments, nothing is read from the environment. TorQ's middle `$KDBSERVCONFIG` tier has no port equivalent (two roots), so it is not searched. | +| `getconfigfile` | `getconfigfile[builtinroot;approot;path]` | `getconfig` at level 0, as TorQ's `.proc.getconfigfile`. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | | `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.clients.opencloseonly 0`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | diff --git a/di/torq/config/config.q b/di/torq/config/config.q index 89c7569b5..b0db366aa 100644 --- a/di/torq/config/config.q +++ b/di/torq/config/config.q @@ -61,8 +61,8 @@ parsetier:{[base] (parsefile base,".q"),parsefile base,".toml" }; -cascade:{[builtinroot;approot;proctype;procname] - / resolve the cascade over the two roots x (default;proctype;procname) and RETURN the merged flat +cascade:{[builtinroot;approot;parentproctype;proctype;procname] + / resolve the cascade over the two roots x (default;parentproctype;proctype;procname) and RETURN the merged flat / dict. pure (no init/logger/globals). name-major: a more specific NAME wins over the root layer, / and within a name the app root wins (parsetier gives .toml>.q within a tier). the accumulator is / seeded with a sentinel (`)!(::) key so its value list stays general from the first merge (a @@ -70,20 +70,34 @@ cascade:{[builtinroot;approot;proctype;procname] / proctype/procname must be non-null symbol atoms: string`` is "", which would build a bogus / "/" base and read a file named ".q"/".toml". a null means identity resolution failed, so / surface it. (a null symbol is still type -11h, so the null check is separate from the type check.) - if[not all -11h=type each (proctype;procname); - '"di.torq.config: cascade requires proctype and procname to be symbol atoms"]; + if[not all -11h=type each (parentproctype;proctype;procname); + '"di.torq.config: cascade requires parentproctype, proctype and procname to be symbol atoms"]; if[(null proctype)|null procname; '"di.torq.config: cascade requires non-null proctype and procname; got ",(-3!proctype)," and ",-3!procname]; dirs:(builtinroot;approot); / dedup (distinct keeps first-occurrence order, preserving least->most-specific). without it a / repeated name re-applies its tier at a LATER slot: procname~proctype is redundant, but / procname~`default would put default LAST and wrongly override proctype. - names:distinct `default,proctype,procname; + / a null parentproctype is none; when set its tier sits between default and proctype, as TorQ's torq.q:593 + names:distinct (`default,parentproctype,proctype,procname) except `; bases:raze {[ds;nm] ds,\:"/",string nm}[dirs;] each names; acc:{[a;b] a,parsetier b}/[(enlist `)!enlist(::);bases]; acc _ ` }; +/ the config file(s) for a path relative to the two roots, app before builtin, as TorQ's .proc.getconfig (torq.q:149-172): +/ level 0 the first existing (else the builtin path), 1 each existing app path then the builtin path, 2 both regardless. +/ an empty approot is an unset app root, as an unset $KDBAPPCONFIG. pure: no env read. +getconfig:{[builtinroot;approot;path;level] + appconf:$[count approot;`$approot,"/",path;()]; + if[(level<2) and $[count appconf;()~key hsym appconf;0b];appconf:()]; + conf:`$builtinroot,"/",path; + (),$[level;appconf,conf;first appconf,conf] + }; + +/ the first config file for a path, as TorQ's .proc.getconfigfile (torq.q:174) +getconfigfile:getconfig[;;;0]; + / --- command-line override layer (top of the cascade) --- hexchars:"0123456789abcdefABCDEF"; @@ -181,8 +195,10 @@ getapimeta:{[] / names are bare (di.torq qualifies them). one (name;public;descrip;params;return) row per line. :flip `name`public`descrip`params`return!flip( (`init; 0b; "wire the injected logger (required by overrideconfig)"; "[dict: deps with a `log key]"; "null"); - (`cascade; 1b; "resolve the settings cascade over two roots -> merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); + (`cascade; 1b; "resolve the settings cascade over two roots -> merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: parentproctype (` if none); symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); (`overrideconfig; 1b; "apply the command-line override layer onto a resolved config dict"; "[dict: resolved config; dict: setting name (symbol) -> string or list of strings]"; "dict: updated config"); + (`getconfig; 1b; "the config file(s) for a path over the two roots, app before builtin (TorQ .proc.getconfig)"; "[string: builtinroot; string: approot (empty if unset); string: path; long: level 0/1/2]"; "symbol list: config file path(s)"); + (`getconfigfile; 1b; "the first config file for a path over the two roots (TorQ .proc.getconfigfile)"; "[string: builtinroot; string: approot; string: path]"; "symbol list: one config file path"); (`parsefile; 1b; "parse one .q or .toml settings file into a flat dict"; "[string: file path (.q flat name:value, or .toml via di.util.toml)]"; "dict: setting -> value (empty if the file is missing)"); (`getapimeta; 0b; "this module's api metadata rows"; "[]"; "table: metadata rows")); }; diff --git a/di/torq/config/init.q b/di/torq/config/init.q index 2e06d0141..81c1054ff 100644 --- a/di/torq/config/init.q +++ b/di/torq/config/init.q @@ -1,3 +1,3 @@ / configuration loading and cascade resolution for the modular torq world. \l ::config.q -export:([init;cascade;overrideconfig;parsefile;getapimeta]) +export:([init;cascade;getconfig;getconfigfile;overrideconfig;parsefile;getapimeta]) diff --git a/di/torq/config/test.csv b/di/torq/config/test.csv index 712c95b44..8517888cb 100644 --- a/di/torq/config/test.csv +++ b/di/torq/config/test.csv @@ -1,45 +1,51 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,cfg:use`di.torq.config,1,1,load the module +before,0,0,q,"TD:""/tmp/diconfig_"",(string .z.i),""/""",1,1,per-run fixture root so concurrent or other-user runs never collide before,0,0,q,"logtab:([]lvl:`symbol$();ctx:`symbol$();msg:())",1,1,capturing log table before,0,0,q,"mocklog:`info`warn`error!({[c;m]`logtab upsert(`info;c;m)};{[c;m]`logtab upsert(`warn;c;m)};{[c;m]`logtab upsert(`error;c;m)})",1,1,define a capturing binary logger before,0,0,q,cfg.init[enlist[`log]!enlist mocklog],1,1,init with the required log dependency -before,0,0,q,"system""mkdir -p /tmp/diconfigbuiltin""",1,1,builtin root for the cascade -before,0,0,q,"system""mkdir -p /tmp/diconfigapp""",1,1,app root for the cascade -before,0,0,q,"(`:/tmp/diconfigbuiltin/default.q) 0: (""diconfiga:1"";""diconfigb:1"")",1,1,builtin/default flat name:value (two settings) -before,0,0,q,"(`:/tmp/diconfigbuiltin/rdb.q) 0: enlist ""diconfigb:10""",1,1,builtin/rdb proctype tier sets diconfigb -before,0,0,q,"(`:/tmp/diconfigapp/default.q) 0: (""diconfiga:100"";""diconfigb:5"")",1,1,app/default flat name:value (two settings) -before,0,0,q,"(`:/tmp/diconfigapp/rdb1.q) 0: enlist ""diconfiga:999""",1,1,app/rdb1 procname tier sets diconfiga +before,0,0,q,"system ""mkdir -p "",TD,""builtin""",1,1,builtin root for the cascade +before,0,0,q,"system ""mkdir -p "",TD,""app""",1,1,app root for the cascade +before,0,0,q,"(hsym`$TD,""builtin/default.q"") 0: (""diconfiga:1"";""diconfigb:1"")",1,1,builtin/default flat name:value (two settings) +before,0,0,q,"(hsym`$TD,""builtin/rdb.q"") 0: enlist ""diconfigb:10""",1,1,builtin/rdb proctype tier sets diconfigb +before,0,0,q,"(hsym`$TD,""app/default.q"") 0: (""diconfiga:100"";""diconfigb:5"")",1,1,app/default flat name:value (two settings) +before,0,0,q,"(hsym`$TD,""app/pptp.q"") 0: (""diconfigb:3"";""diconfigc:7"")",1,1,app/pptp parentproctype tier sets diconfigb and diconfigc +before,0,0,q,"(hsym`$TD,""app/rdb1.q"") 0: enlist ""diconfiga:999""",1,1,app/rdb1 procname tier sets diconfiga before,0,0,q,"basecfg:`enabled`rows`syms`tab`byte`str!(0b;100;`a`b;([]a:`long$());0x01;"":olddb"")",1,1,base config dict for the overrideconfig tests (str is a char-string setting, as a .toml value would be) -before,0,0,q,"system""mkdir -p /tmp/diconfigskip""",1,1,dir for the malformed-line skip test -before,0,0,q,"(`:/tmp/diconfigskip/default.q) 0: (""a:1"";"""";""/ a comment"";""straynocolon"";""b:2"")",1,1,a .q file mixing valid pairs with blank/comment/no-colon lines -before,0,0,q,"system""mkdir -p /tmp/diconfigtoml""",1,1,dir for the toml-guard test -before,0,0,q,"(`:/tmp/diconfigtoml/present.toml) 0: enlist ""a = 1""",1,1,a .toml file that config parses by delegating to the reconciled di.util.toml (present on QPATH) +before,0,0,q,"system ""mkdir -p "",TD,""skip""",1,1,dir for the malformed-line skip test +before,0,0,q,"(hsym`$TD,""skip/default.q"") 0: (""a:1"";"""";""/ a comment"";""straynocolon"";""b:2"")",1,1,a .q file mixing valid pairs with blank/comment/no-colon lines +before,0,0,q,"system ""mkdir -p "",TD,""toml""",1,1,dir for the toml-guard test +before,0,0,q,"(hsym`$TD,""toml/present.toml"") 0: enlist ""a = 1""",1,1,a .toml file that config parses by delegating to the reconciled di.util.toml (present on QPATH) comment,,,,,,,init - dependency validation fail,0,0,q,cfg.init[(::)],1,1,init rejects a non-dictionary deps fail,0,0,q,cfg.init[enlist[`foo]!enlist 1],1,1,init rejects deps without a log key fail,0,0,q,cfg.init[enlist[`log]!enlist 42],1,1,init rejects a non-dict log value fail,0,0,q,cfg.init[enlist[`log]!enlist ((enlist`info)!enlist {[c;m]})],1,1,init rejects a log dict missing warn/error comment,,,,,,,parsefile - parse one flat .q settings file into a dict (.toml delegated to di.util.toml) -true,0,0,q,"1~cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]`diconfiga",1,1,parsefile reads a flat name:value .q file into a dict -true,0,0,q,"2=count cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]",1,1,parsefile returns every setting in the file -true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/default.q""]",1,1,parsefile returns an empty dict for a missing .q file -true,0,0,q,"(`a`b!1 2)~cfg.parsefile[""/tmp/diconfigskip/default.q""]",1,1,parsefile skips blank/comment/no-colon lines and returns only valid pairs (no-colon line must not crash the split) +true,0,0,q,"1~cfg.parsefile[(TD,""builtin/default.q"")]`diconfiga",1,1,parsefile reads a flat name:value .q file into a dict +true,0,0,q,"2=count cfg.parsefile[(TD,""builtin/default.q"")]",1,1,parsefile returns every setting in the file +true,0,0,q,"0=count cfg.parsefile[(TD,""nope/default.q"")]",1,1,parsefile returns an empty dict for a missing .q file +true,0,0,q,"(`a`b!1 2)~cfg.parsefile[(TD,""skip/default.q"")]",1,1,parsefile skips blank/comment/no-colon lines and returns only valid pairs (no-colon line must not crash the split) comment,,,,,,,parsefile - .toml integration with the reconciled di.util.toml (existence guarded first; existing .toml delegated) -true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/absent.toml""]",1,1,a MISSING .toml contributes nothing and does NOT require di.util.toml (existence checked before delegation) -true,0,0,q,"1j~(cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) -true,0,0,q,"-7h=type (cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile +true,0,0,q,"0=count cfg.parsefile[(TD,""nope/absent.toml"")]",1,1,a MISSING .toml contributes nothing and does NOT require di.util.toml (existence checked before delegation) +true,0,0,q,"1j~(cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) +true,0,0,q,"-7h=type (cfg.parsefile[(TD,""toml/present.toml"")])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile comment,,,,,,,cascade - merged flat dict over two roots x default/proctype/procname (name-major; .toml>.q within a tier) -true,0,0,q,"100~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) -true,0,0,q,"999~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) -true,0,0,q,"not (`) in key cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict -true,0,0,q,"0=count cfg.cascade[""/tmp/diconfignope1"";""/tmp/diconfignope2"";`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict -true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) -true,0,0,q,"100~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";(`);`rdb1]",1,1,cascade rejects a null proctype -fail,0,0,q,"cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) +true,0,0,q,"999~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1])`diconfiga",1,1,name-major: the procname tier (app/rdb1) wins over every less-specific name +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1])`diconfigb",1,1,a key absent from the procname tier keeps its most-specific set value (builtin proctype) +true,0,0,q,"7~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdb1])`diconfigc",1,1,parentproctype: its tier is read (app/pptp) +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdb1])`diconfigb",1,1,parentproctype: the proctype tier beats it (builtin/rdb 10 over app/pptp 3) as TorQ default->parentproctype->proctype->procname +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");`pptp;`rdb;`rdbnofile])`diconfiga",1,1,parentproctype: it beats default (app/default 100 stays; pptp sets no diconfiga) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");""pptp"";`rdb;`rdb1]",1,1,cascade rejects a non-symbol parentproctype +true,0,0,q,"not (`) in key cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb1]",1,1,the sentinel merge key is dropped from the returned dict +true,0,0,q,"0=count cfg.cascade[(TD,""nope1"");(TD,""nope2"");(`);`rdb;`rdb1]",1,1,an all-missing cascade resolves to an empty dict +true,0,0,q,"10~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`default])`diconfigb",1,1,dedup: procname=`default must NOT re-apply the default tier last and override proctype (would be 5 without distinct) +true,0,0,q,"100~(cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;`rdb])`diconfiga",1,1,dedup: proctype~procname resolves correctly (each tier once) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);`rdb;(`)]",1,1,cascade rejects a null procname (else it resolves a bogus root/.q tier) +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);(`);`rdb1]",1,1,cascade rejects a null proctype +fail,0,0,q,"cfg.cascade[(TD,""builtin"");(TD,""app"");(`);""rdb"";`rdb1]",1,1,cascade rejects a non-symbol (string) proctype comment,,,,,,,overrideconfig - command-line override layer applied onto a resolved config dict true,0,0,q,"1b~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`enabled",1,1,bool parsed and set from string true,0,0,q,"500~(cfg.overrideconfig[basecfg;`enabled`rows!(enlist""1"";enlist""500"")])`rows",1,1,long parsed and set from string @@ -67,6 +73,16 @@ true,0,0,q,"""new""~(cfg.overrideconfig[seccfg;enlist[`.replay.dir]!enlist ""new true,0,0,q,"7~(cfg.overrideconfig[seccfg;enlist[`replay.first]!enlist enlist""7""])[`replay;`first]",1,1,section.key (no leading dot) works and parses into the key's type true,0,0,q,"`xx`yy~(cfg.overrideconfig[seccfg;enlist[`.replay.tabs]!enlist (""xx"";""yy"")])[`replay;`tabs]",1,1,a vector key of a section takes several values true,0,0,q,"seccfg~cfg.overrideconfig[seccfg;`.replay.nope`.rows.x`.replay.a.b!3#enlist enlist""1""]",1,1,an unknown section key or a non-dict section or a deeper name is skipped +comment,,,,,,,getconfig / getconfigfile - TorQ's .proc.getconfig levels over the two roots (app before builtin) +run,0,0,q,"(hsym each `$TD,/:(""app/proc.csv"";""builtin/proc.csv"";""builtin/only.csv"")) 0:\: enlist ""a,b""",1,1,proc.csv in both roots; only.csv in builtin only +true,0,0,q,"(enlist`$TD,""app/proc.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";0]",1,1,level 0: the app file when it exists +true,0,0,q,"(enlist`$TD,""builtin/only.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";0]",1,1,level 0: the builtin file when the app one is missing +true,0,0,q,"(enlist`$TD,""builtin/none.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""none.csv"";0]",1,1,level 0: the builtin path even when neither exists (as legacy) +true,0,0,q,"(enlist`$TD,""builtin/proc.csv"")~cfg.getconfig[TD,""builtin"";"""";""proc.csv"";0]",1,1,level 0: an empty approot is an unset app root +true,0,0,q,"(`$TD,/:(""app/proc.csv"";""builtin/proc.csv""))~cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";1]",1,1,level 1: the existing app file then the builtin file +true,0,0,q,"(enlist`$TD,""builtin/only.csv"")~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";1]",1,1,level 1: a missing app file is left out +true,0,0,q,"(`$TD,/:(""app/only.csv"";""builtin/only.csv""))~cfg.getconfig[TD,""builtin"";TD,""app"";""only.csv"";2]",1,1,level 2: both paths whether or not they exist +true,0,0,q,"cfg.getconfig[TD,""builtin"";TD,""app"";""proc.csv"";0]~cfg.getconfigfile[TD,""builtin"";TD,""app"";""proc.csv""]",1,1,getconfigfile is getconfig at level 0 comment,,,,,,,getapimeta - module api metadata true,0,0,q,(asc key cfg)~asc exec name from cfg.getapimeta[],1,1,getapimeta documents exactly the module's exports true,0,0,q,`name`public`descrip`params`return~cols cfg.getapimeta[],1,1,getapimeta rows carry the registry columns @@ -75,12 +91,13 @@ true,0,0,q,0b~(1!cfg.getapimeta[])[`init]`public,1,1,framework plumbing (init) i comment,,,,,,,logger emission - real logger via a caller-side binary wrapper (must run last; re-inits cfg) run,0,0,q,kxlogger:use`kx.log,1,1,load the kx.log module run,0,0,q,kxinst:kxlogger.createLog[],1,1,create a real kx.log instance -run,0,0,q,kxh:hopen `:/tmp/diconfigkxsink.txt,1,1,open a file sink to capture output +run,0,0,q,"kxh:hopen hsym`$TD,""kxsink.txt""",1,1,open a file sink to capture output run,0,0,q,kxinst.add[kxh;`info],1,1,route info-level output to the file sink run,0,0,q,"kxbinary:`info`warn`error!({[c;m]kxinst[`info][string[c],"": "",m]};{[c;m]kxinst[`warn][string[c],"": "",m]};{[c;m]kxinst[`error][string[c],"": "",m]})",1,1,wrap the monadic logger into the binary {[c;m]} contract run,0,0,q,cfg.init[enlist[`log]!enlist kxbinary],1,1,re-init di.torq.config with the conforming binary logger run,0,0,q,"kxres:cfg.overrideconfig[enlist[`kxrows]!enlist 5;enlist[`kxrows]!enlist enlist""7""]",1,1,drive a real info-level log through the wrapped logger run,0,0,q,hclose kxh,1,1,flush and close the file sink true,0,0,q,7~kxres`kxrows,1,1,the override was applied (returned dict carries the new value) -true,0,0,q,"any (read0 `:/tmp/diconfigkxsink.txt) like ""*overrideconfig: setting*""",1,1,the override emitted an info line through the real logger -true,0,0,q,"any (read0 `:/tmp/diconfigkxsink.txt) like ""*kxrows*""",1,1,emitted message names the overridden setting +true,0,0,q,"any (read0 hsym`$TD,""kxsink.txt"") like ""*overrideconfig: setting*""",1,1,the override emitted an info line through the real logger +true,0,0,q,"any (read0 hsym`$TD,""kxsink.txt"") like ""*kxrows*""",1,1,emitted message names the overridden setting +after,0,0,q,"system ""rm -rf "",TD",1,1,remove this run's fixture root diff --git a/di/torq/logroll/logroll.md b/di/torq/logroll/logroll.md index d0621fa6a..af03b9a51 100644 --- a/di/torq/logroll/logroll.md +++ b/di/torq/logroll/logroll.md @@ -78,8 +78,8 @@ an interactive session. Requires `log` and `timer` in the injected `deps` (same validation style as `di/torq/proc/hdb/hdb.q:21`). When enabled: calls `rollnow[]` once immediately, then -schedules the recurring roll via the injected timer contract - `period=86400` -(seconds/day), `mode=1h` (`kdbx-modules` `di.timer`'s "x seconds after previously +schedules the recurring roll via the injected timer contract - `period=1D` +(one day), `mode=1h` (`kdbx-modules` `di.timer`'s "one period after previously scheduled start" - fixed-rate, no drift), with `opts.startattime` overriding just the first fire to next UTC midnight (`` `timestamp$1+`date$.z.p ``), so the very first roll happens at the next real day boundary rather than 24h after whenever the diff --git a/di/torq/logroll/logroll.q b/di/torq/logroll/logroll.q index 6bb0034f9..d70ac19f8 100644 --- a/di/torq/logroll/logroll.q +++ b/di/torq/logroll/logroll.q @@ -93,5 +93,5 @@ init:{[config;deps] set[`.logroll.rollnow;rollnow]; rollnow[]; starttime:`timestamp$1+`date$.z.p; - (deps[`timer][`addjob])[`logroll;rollnow;();86400;1h;enlist[`startattime]!enlist starttime]; + (deps[`timer][`addjob])[`logroll;rollnow;();1D;1h;enlist[`startattime]!enlist starttime]; } diff --git a/di/torq/logroll/test.csv b/di/torq/logroll/test.csv index 814d5bbdc..1322a2819 100644 --- a/di/torq/logroll/test.csv +++ b/di/torq/logroll/test.csv @@ -24,7 +24,7 @@ true,0,0,q,1=errfilecount[],1,,exactly one err_ file created true,0,0,q,outaliasexists[],1,,out_ alias symlink created by default true,0,0,q,erraliasexists[],1,,err_ alias symlink created by default true,0,0,q,1=addjobcount[],1,,exactly one timer job scheduled -true,0,0,q,86400=addjobperiod[],1,,scheduled with a 1-day period +true,0,0,q,1D=addjobperiod[],1,,scheduled with a 1-day period true,0,0,q,1h=addjobmode[],1,,scheduled with fixed-rate mode 1h true,0,0,q,addjobhasstartattime[],1,,scheduled with an explicit first-fire startattime diff --git a/di/torq/proc/chainedtp/chainedtp.md b/di/torq/proc/chainedtp/chainedtp.md index ed8352066..64070faac 100644 --- a/di/torq/proc/chainedtp/chainedtp.md +++ b/di/torq/proc/chainedtp/chainedtp.md @@ -46,7 +46,7 @@ missing), then: 4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; 5. `subscribe[]`; 6. builds `tableschemas`; -7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). +7. when `pubinterval` is above 0, adds the `publishalltables` job (every `pubinterval`, timer mode 2). di.torq runs `.ps.initialise[]` again after the module loads, which publishes the subscribed tables. @@ -57,7 +57,6 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th - An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. - `.u.icounts` values are one-item lists after an all-syms subscribe. - A corrupt own log is reported and opened anyway. -- `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. ## Downstream subscribers diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index d9bb8dd64..de3d702a2 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -29,7 +29,6 @@ init:{[config;deps] .z.m.schema:config`schema; .z.m.clearlogonsubscription:config`clearlogonsubscription; .z.m.tpcheckcycles:config`tpcheckcycles; - if[0<>(`long$pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string tickerplantname];exit 0]}]; .z.m.upd:$[createlogfile; $[pubinterval;{[t;x] writetolog[t;x];batchpub[t;x];};{[t;x] writetolog[t;x];tickpub[t;x];}]; @@ -39,7 +38,7 @@ init:{[config;deps] .servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]; subscribe[]; .z.m.tableschemas:{x!(0#)@'value@'x} (),$[any null subscribeto;tables[`.];subscribeto]; - if[pubinterval;(deps[`timer]`addjob)[`publishalltables;publishalltables;();`long$pubinterval%0D00:00:01;2;()!()]]; + if[pubinterval;(deps[`timer]`addjob)[`publishalltables;publishalltables;();pubinterval;2;()!()]]; } / root: the subscriber contract diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 66806a44e..4eb02e827 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -9,8 +9,6 @@ fail,0,0,q,"ctp.init[cfg[];enlist[`log]!enlist mocklog]",1,,init without timer m fail,0,0,q,"ctp.init[cfg[];`log`timer!(mocklog;mocktimer)]",1,,init without handlers must error fail,0,0,q,"ctp.init[cfg[];`timer`handlers!(mocktimer;mockhandlers)]",1,,init without log must error fail,0,0,q,"ctp.init[`proctype`procname!(`chainedtp;`chainedtp1);deps[]]",1,,init without settings must error -fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,a sub-second pubinterval must error -fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir`tickerplantname`subscribeto`subscribesyms!(""0D00:00:00"";""tplogs"";""tickerplant1"";"""";"""");deps[]]",1,,init with toml-style strings @@ -87,4 +85,9 @@ true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `tra run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,peer received the rows +comment,,,,,,,a sub-second pubinterval batches on a timer job at that period, as TorQ's .timer.rep with .ctp.pubinterval +run,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,re-init with a 500ms pubinterval is accepted +true,0,0,q,"(0D00:00:00.5;2)~last each exec (period;mode) from timercalls where id=`publishalltables",1,,the batch job runs every 500ms in mode 2 (legacy mode 1h) +true,0,0,q,.m.di.0torq.0proc.0chainedtp.upd~.m.di.0torq.0proc.0chainedtp.batchpub,1,,the module's upd batches (root upd is kept from the first init) + 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 57bf48d3a..8b1dc9f61 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -2,8 +2,8 @@ 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);} +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()) +mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] `timercalls upsert (id;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,"*"} diff --git a/di/torq/proc/gateway/gateway.md b/di/torq/proc/gateway/gateway.md index 20d347463..0ce25bfa8 100644 --- a/di/torq/proc/gateway/gateway.md +++ b/di/torq/proc/gateway/gateway.md @@ -45,8 +45,11 @@ di.serverselect — see the scope note). `query` is any value passed to `value` The wdb calls `(`.gw.reload;`reloadstart)` before moving its partition into the hdb and `(`.gw.reload;`reloadend)` after the hdb/rdb have reloaded (di.torq.proc.wdb's `informgateway` already sends -these — building this module makes that loop live). While gated, new queries are rejected with a -retry message so none straddle the rdb-drop / hdb-reload window; `reloadend` clears the gate and +these — building this module makes that loop live). While gated, a new query spanning more than one server type +(`asyncexec`, `asyncexecjpt`, or a `getdata` whose range covers more than one partition; one helper, `ineod`, as +TorQ's `checkeod`) is rejected with a retry message so none straddle the rdb-drop / hdb-reload window, while a +single-type query runs, as legacy. Legacy also holds multi-type async queries until `reloadend` and errors those +in flight at `reloadstart`; the port does not (backlog); `reloadend` clears the gate and refreshes the backend registry. ## How it wires together (init) diff --git a/di/torq/proc/gateway/gateway.q b/di/torq/proc/gateway/gateway.q index f70c21624..1fe2632c7 100644 --- a/di/torq/proc/gateway/gateway.q +++ b/di/torq/proc/gateway/gateway.q @@ -49,6 +49,16 @@ registerbackends:{[] .z.m.log[`info][`gateway;"registered ",(string count ct)," backend server(s): ",", " sv string exec distinct proctype from ct]]; } +/ the reload rule for every client entry point, as TorQ's checkeod (gateway.q:93): during an eod reload a query +/ spanning more than one server type is rejected with an error reply (returns 1b; the caller returns); one type runs +ineod:{[types] r:.z.m.eod and 1=starttime;:()]; + (.z.m.da`getdata)[tablename;starttime;endtime;by;aggs]} + / --- permission hooks (di.permissions) --------------------------------------------------- / di.permissions publishes .pm.allowed and .pm.execas at root when it is loaded and enabled. / Both are tested for presence, as TorQ's gateway does, so a gateway running without the module @@ -74,7 +84,7 @@ checkpermissioned:{[] / protected so a routing/dispatch error becomes a formatted reply to the client rather than an / uncaught error on the async handler. asyncexecjpt:{[query;servertype;join;postback;timeout] - if[.z.m.eod;@[neg .z.w;.z.m.errorprefix,"gateway in eod reload - retry shortly";()];:()]; + if[ineod @[resolvetypes;servertype;()];:()]; u:.z.u; if[.z.m.permissioned; if[not permitted[u;query]; @@ -97,9 +107,9 @@ asyncexec:{[query;servertype] asyncexecjpt[query;servertype;raze;();0Wn]} / window. v1 rejects rather than queues-and-resumes; on reloadend it refreshes the backend registry. reload:{[msg] $[msg~`reloadstart; - [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - holding new queries"]]; + [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - rejecting multi-type queries until reloadend"]]; msg~`reloadend; - [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; + [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[.z.m.partitions:buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; .z.m.log[`warn][`gateway;"unknown .gw.reload message: ",string msg]]; } @@ -124,9 +134,10 @@ init:{[config;deps] / callbacks at root .gw.* and tell it to reply to those names (baked into the shipped executor by / the vendor patch, so backends need no cooperating code). .z.m.ad:use`di.asyncdispatch; - adcfg:enlist[`log]!enlist deps`log; - if[`synccallsallowed in key config;adcfg[`synccallsallowed]:`boolean$config`synccallsallowed]; - (.z.m.ad`init)[adcfg]; + adcfg:()!(); + if[`synccallsallowed in key config;adcfg:adcfg,enlist[`synccallsallowed]!enlist`boolean$config`synccallsallowed]; + / joins not amends, log last: amending a log-valued dict makes each new value a row of the log dict + (.z.m.ad`init)[(enlist[`log]!enlist deps`log),adcfg]; / NB: param is `sel`, NOT `ss` - `ss` is the built-in string-search function and q would / resolve ss[...] to the builtin instead of the projected serverselect dict (throws 'match). (.z.m.ad`setavailableservers)[{[sel;excludeinuse] select handle,servertype from sel[`getserverstable][] where active}[.z.m.srvsel]]; @@ -151,7 +162,7 @@ init:{[config;deps] / coverage for routing is built from .z.d (buildpartitions) and refreshed at EOD reloadend via / (.z.m.da`setpartitions), so post-roll queries for the just-saved day route to the hdb not the rdb. .z.m.da:use`di.dataaccess; - (.z.m.da`init)[`log`timer`partitions!(deps`log;deps`timer;buildpartitions[])]; + (.z.m.da`init)[`log`timer`partitions!(deps`log;deps`timer;.z.m.partitions:buildpartitions[])]; / handler callbacks via the injected handlers dep (di.torq.handlers): track client connect, and on any / handle close clean up whichever role it was - backend (asyncdispatch in-flight cleanup + @@ -165,14 +176,15 @@ init:{[config;deps] / normalised query layer (di.dataaccess); the raw asyncexec/asyncexecjpt route query strings. set[`.gw.asyncexec;asyncexec]; set[`.gw.asyncexecjpt;asyncexecjpt]; - set[`.gw.getdata;.z.m.da`getdata]; + set[`.gw.getdata;getdata]; set[`.gw.reload;reload]; - / housekeeping timers (asyncdispatch leaves scheduling to the caller). mode 1h period = seconds. - (.z.m.timer`addjob)[`gwtimeout;{(.z.m.ad`checktimeout)[]};();5;1h;()!()]; - (.z.m.timer`addjob)[`gwrmqueries;{(.z.m.ad`removequeries)[0D00:30]};();60;1h;()!()]; - (.z.m.timer`addjob)[`gwrminactive;{(.z.m.ad`removeinactive)[0D01:00]};();300;1h;()!()]; - (.z.m.timer`addjob)[`gwrmclients;{(.z.m.ad`removeclients)[0D01:00]};();300;1h;()!()]; + / housekeeping timers (asyncdispatch leaves scheduling to the caller), period as a timespan. + / mode 3h reschedules from the end of the previous run, as TorQ's .timer.repeat does + (.z.m.timer`addjob)[`gwtimeout;{(.z.m.ad`checktimeout)[]};();0D00:00:05;3h;()!()]; + (.z.m.timer`addjob)[`gwrmqueries;{(.z.m.ad`removequeries)[0D00:30]};();0D00:01;3h;()!()]; + (.z.m.timer`addjob)[`gwrminactive;{(.z.m.ad`removeinactive)[0D01:00]};();0D00:05;3h;()!()]; + (.z.m.timer`addjob)[`gwrmclients;{(.z.m.ad`removeclients)[0D01:00]};();0D00:05;1h;()!()]; / di.torq calls .gateway.run[] after every module, the rule cascade and app code have loaded, / which is the earliest point at which di.permissions' root names are observable - init itself diff --git a/di/torq/proc/gateway/test.csv b/di/torq/proc/gateway/test.csv index 630a5fbd6..1ce5e005e 100644 --- a/di/torq/proc/gateway/test.csv +++ b/di/torq/proc/gateway/test.csv @@ -8,6 +8,15 @@ fail,0,0,q,gw.init[()!();(enlist`log)!enlist mlog],1,,init with log but no timer true,0,0,q,`init`asyncexec`asyncexecjpt`reload`version~key gw,1,,module exports init/asyncexec/asyncexecjpt/reload/version true,0,0,q,0.port; wait for it and return the port +/ (no port picking: a port with no listener can still be unbindable, which made picked ports flaky) +gwspawn:{[script;name] + pf:GWDIR,"/",name,".port"; + system GWQ," ",GWDIR,"/",script," -p 0W -q ",GWDIR,"/",name,".log 2>&1 &"; + {[pf;x] system "sleep 0.05"; x+1}[pf]/[{[pf;x] (x<100) and ()~key hsym`$pf}[pf];0]; + if[()~key hsym`$pf;'"test: ",name," did not start (see ",GWDIR,"/",name,".log)"]; + "J"$first read0 hsym`$pf}; +/ the port and identity line each spawned q writes once it is listening +gwportline:{[name] "(hsym`$\"",GWDIR,"/",name,".port\") 0: enlist string system\"p\"; GWNAME:`",name,";"}; +startgwfixture:{[] + system "rm -rf ",GWDIR; system "mkdir -p ",GWDIR; + {(hsym`$GWDIR,"/",x,".q") 0: ("trade:([]date:2#.z.d-1 0;time:`timestamp$.z.d-1 0;sym:`a`b;price:1 2f);";"SENT:0; .z.ps:{`SENT set SENT+1; value x};";gwportline x)} each ("rdb1";"hdb1"); + bp:gwspawn'[("rdb1.q";"hdb1.q");("rdb1";"hdb1")]; + (hsym`$GWDIR,"/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string bp 0),",rdb,rdb1";"localhost,",(string bp 1),",hdb,hdb1"); + (hsym`$GWDIR,"/gw.q") 0: ( + "lg:`info`warn`error!3#enlist {[c;m]};"; + "tm:use`di.timer; tm.init enlist[`log]!enlist lg;"; + "td:`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 lg; hd:`register`remove`list!(hz.register;hz.remove;hz.list);"; + "svc:use`di.torq.servers; svc.init[`log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(lg;td;hd;`gateway;`gateway1;\"",GWDIR,"/process.csv\";`rdb`hdb;0b;0b)];"; + "gw:use`di.torq.proc.gateway; gw.init[enlist[`backendtypes]!enlist`rdb`hdb;`log`timer`handlers`servers!(lg;td;hd;svc)];"; + gwportline "gw"); + gp:gwspawn["gw.q";"gw"]; + `GWH set hopen `$":localhost:",string gp; + `GWBH set {hopen `$":localhost:",string x} each bp; + / the listeners are the processes this fixture spawned + if[not (`gw`rdb1`hdb1)~{x"GWNAME"} each GWH,GWBH;'"test: a port answered for a process this fixture did not spawn"]; + .z.ps:{`GWREPLIES set GWREPLIES,enlist x}; + }; +/ send one async message to the gateway; returns the replies and what each backend (rdb;hdb) was sent +gwask:{[m] + {x"SENT:0"} each GWBH; + neg[GWH] m; neg[GWH][]; + system "sleep 1"; GWH"1"; + r:GWREPLIES; `GWREPLIES set (); + `replies`sent!(r;{x"SENT"} each GWBH)}; +/ a getdata spanning yesterday and today (an rdb and an hdb shard) +gwgetdata:{[] gwask (`.gw.getdata;`trade;`timestamp$.z.d-1;.z.p;`;())}; +/ a getdata over today only (the rdb partition alone) +gwgetdatatoday:{[] gwask (`.gw.getdata;`trade;`timestamp$.z.d;.z.p;`;())}; +/ asyncexec to the given server types +gwasync:{[t] gwask (`.gw.asyncexec;"count trade";t)}; +stopgwfixture:{[] + {@[{neg[x]"exit 0";neg[x][]};x;()]} each GWH,GWBH; + system "sleep 0.3"; system "rm -rf ",GWDIR; + }; + + / the gateway's post-init hook, which di.torq calls as .gateway.run[] once everything has loaded runhook:{[] (value `.gateway.run)[]} warned:{[] 0 its 0: type char, in order. Deliberately ONE structure -/ rather than a name list beside a "S***ISB" literal - they have to agree positionally, and -/ nothing but care keeps two parallel lists in step when a column is added. -/ NOT a setting, despite looking like config: these names are compiled into the field accesses -/ in findmatches/applyjob (j`action, j`path, ...), so an operator who renamed one would get a -/ csv that passes the header check and then fails on first use. Renamed from legacy TorQ's -/ function/agemin/checkfordirectory for clarity; housekeeping.md has the migration mapping. -jobschema:`action`path`match`exclude`age`unit`dirs!"S***ISB" - -/ read the job list. Re-read on every run rather than cached at init, so an operator can edit -/ the csv without bouncing the process (legacy read it per run too). All columns are required - -/ legacy allowed trailing optional ones and needed a fragile rename dance to cope; a strict -/ header with a clear error is easier to get right than to debug. +/ read the job list, as legacy housekeeping.q:44-51; re-read on every run so the csv can be edited without a restart readjobs:{[path] f:hsym `$path; if[not count key f;'"job csv not found at ",path]; - t:(value jobschema;enlist ",") 0: f; - if[not (key jobschema)~cols t; - '"job csv ",path," has columns ",(", " sv string cols t),"; expected ",", " sv string key jobschema]; - t + t:("S***IBB";enlist ",") 0: f; + / columns 6 and 7 are named by position; a 5-column csv gets them as 0b + t:@[cols t;5 6;:;`agemin`checkfordirectory] xcol t; + if[not all `function`path`match`exclude`age`agemin`checkfordirectory in cols t;'"job csv ",path," has incorrect layout"]; + / rows with a null function or age are skipped + if[any n:null[t`function] or null t`age;.z.m.log[`info][`readjobs;"Null values found in file, skipping line(s) ",", " sv string where n]]; + t where not n } / locate the paths one job matches. Shells out to find because kdb has no native stat, so file @@ -106,32 +97,34 @@ readjobs:{[path] / values reach the shell - they are quoted, but a csv is not a place to accept untrusted input. findmatches:{[j] p:expandenv j`path; - flag:$[j`dirs;"d";"f"]; - agearg:$[`m=j`unit;"-mmin";"-mtime"]; + flag:$[j`checkfordirectory;"d";"f"]; + agearg:$[j`agemin;"-mmin";"-mtime"]; cmd:"find \"",p,"\" -maxdepth 1 -type ",flag," -name \"",(j`match),"\" ",agearg," +",string j`age; if[count j`exclude;cmd,:" ! -name \"",(j`exclude),"\""]; @[system;cmd;{[e] .z.m.log[`error][`findmatches;"find failed: ",e];()}] } -/ one handler per action, dispatched by the csv's `action` column. rm goes through di.os so it -/ picks the right call for a file vs a directory (and honours di.os's dry-run mode); gzip/tar -/ have no di.os equivalent and shell out directly - part of why this module is unix-only. +/ one handler per action, dispatched by the csv's `function` column, named as legacy's rm/zip/tardir. rm goes through +/ di.os (and honours its dry-run mode); zip/tardir have no di.os equivalent and shell out directly - part of why this +/ module is unix-only. / None of these traps its own work: applyjob traps every action per match, so a handler here reads / the same as one an app registers. actions:()!() actions[`rm]:{[f] + / a directory is skipped and logged, as legacy's rm -f fails on one + if[(.z.m.os`isdir)f;'"cannot remove ",f,": Is a directory"]; .z.m.log[`info][`rm;"removing ",f]; - ($[(.z.m.os`isdir)f;.z.m.os`deldir;.z.m.os`del]) f; + (.z.m.os`del) f; } -actions[`gzip]:{[f] - .z.m.log[`info][`gzip;"compressing ",f]; +actions[`zip]:{[f] + .z.m.log[`info][`zip;"compressing ",f]; system "gzip \"",f,"\""; } -actions[`tar]:{[f] - .z.m.log[`info][`tar;"archiving ",f]; +actions[`tardir]:{[f] + .z.m.log[`info][`tardir;"archiving ",f]; system "tar -czf \"",f,".tar.gz\" \"",f,"\" --remove-files"; } @@ -158,9 +151,9 @@ addaction:{[name;handler] requireinit[`addaction]; if[not -11h=type name;'"di.torq.proc.housekeeping: addaction name must be a symbol"]; if[not 100h=type handler;'"di.torq.proc.housekeeping: addaction handler must be a function taking one matched path"]; - / refuse to shadow a built-in: silently swapping rm/gzip/tar out from under a job csv that + / refuse to shadow a built-in: silently swapping rm/zip/tardir out from under a job csv that / already names them is a footgun no caller wants, and a typo'd name should say so loudly - if[name in `rm`gzip`tar; + if[name in `rm`zip`tardir; '"di.torq.proc.housekeeping: cannot redefine the built-in action ",string name]; if[name in key actions; .z.m.log[`warn][`addaction;"replacing already-registered action ",string name]]; @@ -177,12 +170,12 @@ addaction:{[name;handler] / process's housekeeping job for good - and silently, as di.timer only logs that when its debug is / set. A custom handler registered via addaction must not be able to cost every later run. applyjob:{[j] - if[not (j`action) in key actions; - .z.m.log[`error][`applyjob;"unknown action ",(string j`action),"; expected one of ",", " sv string key actions]; + if[not (j`function) in key actions; + .z.m.log[`error][`applyjob;"unknown action ",(string j`function),"; expected one of ",", " sv string key actions]; :()]; m:findmatches j; - .z.m.log[`info][`applyjob;(string j`action)," ",(j`match)," in ",(expandenv j`path),": ",(string count m)," match(es)"]; - {[a;f] @[actions a;f;{[a;f;e] .z.m.log[`error][`applyjob;"action ",(string a)," failed on ",f,": ",e]}[a;f]]}[j`action;] each m; + .z.m.log[`info][`applyjob;(string j`function)," ",(j`match)," in ",(expandenv j`path),": ",(string count m)," match(es)"]; + {[a;f] @[actions a;f;{[a;f;e] .z.m.log[`error][`applyjob;"action ",(string a)," failed on ",f,": ",e]}[a;f]]}[j`function;] each m; } / run every job in the csv once. Called by the timer, by runnow at startup, and by an operator @@ -194,7 +187,7 @@ runjobs:{[] .z.m.log[`info][`runjobs;"housekeeping starting, reading ",.z.m.jobcsv]; jobs:@[readjobs;.z.m.jobcsv;{[e] .z.m.log[`error][`runjobs;"cannot read job csv: ",e];()}]; if[not count jobs;:()]; - {[j] @[applyjob;j;{[j;e] .z.m.log[`error][`runjobs;"job ",(string j`action)," failed: ",e]}[j]]} each jobs; + {[j] @[applyjob;j;{[j;e] .z.m.log[`error][`runjobs;"job ",(string j`function)," failed: ",e]}[j]]} each jobs; .z.m.log[`info][`runjobs;"housekeeping complete, ran ",(string count jobs)," job(s)"]; } @@ -205,7 +198,7 @@ runjobs:{[] schedule:{[] {[i;t] id:`$"housekeeping",string i; - (.z.m.timer`addjob)[id;runjobs;();86400;1h;enlist[`startattime]!enlist f:nextfire t]; + (.z.m.timer`addjob)[id;runjobs;();1D;1h;`startattime`dupcheck!(f:nextfire t;0b)]; .z.m.log[`info][`schedule;"scheduled ",(string id)," first run at ",string f]; }'[til count .z.m.runtimes;.z.m.runtimes]; } @@ -227,8 +220,7 @@ init:{[config;deps] / tier). Tests assert both halves, because a silently disagreeing pair is how legacy TorQ shipped / runtimes:02:00:00 in settings and a dead 12:00 in code - with its -hkusage text quoting 12:00. .z.m.runtimes:$[`runtimes in key config;astimespans config`runtimes;enlist 0D02:00:00]; - / di.os for the rm action - it picks file vs directory, and its dry-run mode is what lets the - / tests assert on a destructive action without destroying anything + / di.os for the rm action - its dry-run mode is what lets the tests assert on a destructive action without destroying anything .z.m.os:use`di.os; / publish the IPC-callable surface at a real root-level name - use-loading this file compiles / it into a private namespace (see di.torq.proc.hdb.init's identical note), so a remote or diff --git a/di/torq/proc/housekeeping/test.csv b/di/torq/proc/housekeeping/test.csv index 391dcd631..2ec80bb43 100644 --- a/di/torq/proc/housekeeping/test.csv +++ b/di/torq/proc/housekeeping/test.csv @@ -20,7 +20,7 @@ run,0,0,q,hk[`init][basecfg[];mockdeps[]],1,,init with a jobcsv - bracket-indexe true,0,0,q,`runjobs in key `.housekeeping,1,,init published runjobs at the real root namespace .housekeeping - NOT run, which di.torq would auto-fire at startup true,0,0,q,not `run in key `.housekeeping,1,,nothing is published at .housekeeping.run - di.torq's runhook fires that name after init, which would make every process start do a destructive cleanup pass true,0,0,q,1=count scheduled,1,,one runtime configured means one scheduled job -true,0,0,q,86400=first exec period from scheduled,1,,the scheduled job repeats daily +true,0,0,q,1D=first exec period from scheduled,1,,the scheduled job repeats daily true,0,0,q,1h=first exec mode from scheduled,1,,mode 1h pins reruns to the scheduled time not the finish time true,0,0,q,not null first exec opts[;`startattime] from scheduled,1,,the first fire is pinned to a start time rather than firing immediately true,0,0,q,expectedfire[02:00:00]~first exec opts[;`startattime] from scheduled,1,,the first fire is computed on di.timer's UTC clock not local time - a local-time startattime fires late by the UTC offset @@ -50,15 +50,15 @@ true,0,0,q,`recent.log in survivors[],1,,a matching file newer than the age thre true,0,0,q,`excluded.log in survivors[],1,,a matching old file named in exclude was left alone run,0,0,q,resetcalls[],1,,reset call log -run,0,0,q,writegzipcsv[],1,,switch the csv to a gzip job -run,0,0,q,.housekeeping.runjobs[],1,,run the gzip action +run,0,0,q,writegzipcsv[],1,,switch the csv to a zip job +run,0,0,q,.housekeeping.runjobs[],1,,run the zip action true,0,0,q,`old1.log.gz in gzfiles[],1,,gzip produced a .gz for the first matching old file true,0,0,q,`old2.log.gz in gzfiles[],1,,gzip produced a .gz for the second one too true,0,0,q,not `old1.log in gzfiles[],1,,gzip consumed the original rather than leaving both copies run,0,0,q,resetcalls[],1,,reset call log -run,0,0,q,writetarcsv[],1,,switch the csv to a tar job matching directories not files -run,0,0,q,.housekeeping.runjobs[],1,,run the tar action +run,0,0,q,writetarcsv[],1,,switch the csv to a tardir job matching directories not files +run,0,0,q,.housekeeping.runjobs[],1,,run the tardir action true,0,0,q,`olddir.tar.gz in archfiles[],1,,tar archived the matched directory true,0,0,q,not `olddir in archfiles[],1,,tar --remove-files deleted the original directory - the most destructive thing this module does @@ -68,11 +68,26 @@ run,0,0,q,.housekeeping.runjobs[],1,,run the minutes-based job - exercises find' true,0,0,q,not `stale.log in minfiles[],1,,a file older than the 2 minute threshold was removed true,0,0,q,`justnow.log in minfiles[],1,,a file newer than the 2 minute threshold was left alone -true,0,0,q,`rm`gzip`tar~(hk`actionnames)[],1,,the built-in action set before any app registers anything +comment,,,,,,,legacy csv layouts (housekeeping.q:44-51) and rm on a directory +run,0,0,q,writefivecsv[],1,,switch to TorQ's own 5-column csv +run,0,0,q,.housekeeping.runjobs[],1,,run it +true,0,0,q,"not `old.log in dirfiles""five""",1,,a 5-column csv runs: agemin and checkfordirectory default to false +run,0,0,q,resetcalls[],1,,clear the log capture +run,0,0,q,writenullcsv[],1,,a csv whose first row has a null age +run,0,0,q,.housekeeping.runjobs[],1,,run it +true,0,0,q,"0 all tables, all syms # ignorelist omitted -> `heartbeat`logmsg (not saved at EOD) -# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (time asc) +# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (sym then time, p# on sym) +# savedownmanipulation (optional, .q settings) -> table!function applied before each table is saved +# postreplay (optional, .q settings) -> {[hdbdir;date]} called after the save, clear and attribute reapply, before the hdb reload; an error stops end of day, as TorQ ``` Set `reloadenabled = true` **only** when a wdb is present in the stack — otherwise the EOD @@ -52,7 +54,8 @@ di.subscriptions defines the tables at root from what the TP returns. - **End of day**: `.u.end[date]` (from a tickerplant or chainedtp) or root `endofday[date;data]` (from a segmented tickerplant, which also calls the logging `endofperiod` stub). Behaviour depends on `reloadenabled`: - **standalone** (`0b`, default): saves every non-ignored root table to `hdbdir` for `date` - (`di.dbwrite.savedown` — enumerate, splay, sort, attr, gc), clears each (`@[`.;t;0#]`), + (`di.dbwrite.savedown` — manipulate, enumerate, splay, sort, attr, gc), clears each (`@[`.;t;0#]`), + reapplies the in-memory attributes the clear drops (`` `g# `` on sym), calls `postreplay[hdbdir;date]`, then tells every connected HDB to `.hdb.reload[]`. - **wdb-fronted** (`1b`): a wdb owns the writedown, so di.torq.proc.rdb only **snapshots** the per-table row counts (`.z.m.eodtabcount`) and escapes — the data stays live and @@ -104,8 +107,9 @@ and **clears** target root explicitly via `@[`.;…]`, and its `upd` is root-saf ## Testing -`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`) and -the export surface. The full subscribe → replay → live-capture → EOD-save → HDB-reload +`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`), the +export surface, and standalone end of day (`test.q`: `init` runs to the tickerplant wait against +mocked servers): attributes kept, the save down hooks, and the `reloadenabled` escape. The full subscribe → replay → live-capture → EOD-save → HDB-reload flow is proven in the **TorqX-POC end-to-end** (`torqx.sh start tickerplant1 hdb feed1 rdb1`): the RDB replays the tp log on startup, accumulates live trade/quote, and on a forced tickerplant `endofday` writes the partition to the HDB (verified on disk), clears, diff --git a/di/torq/proc/rdb/rdb.q b/di/torq/proc/rdb/rdb.q index 8fb3c2c4a..3b3d281d3 100644 --- a/di/torq/proc/rdb/rdb.q +++ b/di/torq/proc/rdb/rdb.q @@ -65,8 +65,12 @@ endofday:{[date] .z.m.eodtabcount:st!count each value each st; .z.m.log[`info][`rdb;"reload enabled - wdb owns writedown; snapshotted EOD row counts: ",.Q.s1 .z.m.eodtabcount]; :()]; + attrs:st!grabattrs each st; / capture before the clear wipes them, as legacy rdb.q:104 savefn[.z.m.hdbdir;date] each st; @[`.;;0#] each st; / clear the saved tables (root) + reapplyattrs'[st;attrs st]; + / call the postreplay hook, unprotected as TorQ's rdb.q:118 + (.z.m.dbw`postreplay)[hsym`$.z.m.hdbdir;date]; notifyhdbs[]; .z.m.log[`info][`rdb;"end of day complete, saved+cleared: ",(", " sv string st)]; } @@ -116,6 +120,14 @@ init:{[config;deps] replaylog:$[`replaylog in key config;`boolean$config`replaylog;1b]; timeout:$[`tpwaittimeout in key config;"j"$config`tpwaittimeout;30000]; + / di.dbwrite for savedown (optional sort.csv sort/attr config), set before the tickerplant wait as legacy reads its hooks at load + .z.m.dbw:use`di.dbwrite; + / the save down hooks from config, defaulting as TorQ's rdb.q:42-43, go to di.dbwrite + sdm:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + pr:$[`postreplay in key config;config`postreplay;{[d;p]}]; + (.z.m.dbw`init)[`log`savedownmanipulation`postreplay!(deps`log;sdm;pr)]; + if[`sortcsv in key config;(.z.m.dbw`readcsv)[resolvedir[apphome[];config`sortcsv]]]; + / publish the root-safe upd BEFORE subscribing (replay drives it too) @[`.;`upd;:;updfn]; @@ -136,12 +148,6 @@ init:{[config;deps] sd:.sub.subscribe[subscribeto;subscribesyms;1b;replaylog;first .sub.getsubscriptionhandles[tpt;`;()!()]]; if[count sd;.z.m.log[`info][`rdb;"subscribed, partition date ",string sd`d]]; - / di.dbwrite for savedown (optional sort.csv sort/attr config). Takes the injected binary - / (ctx;msg) log dep directly - no adapter, since di.dbwrite now uses the same contract. - .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]]]; - / publish the EOD entry points at root. / reload[date] is the wdb's IPC entry point when reloadenabled (harmless if never called). set[`.u.end;endofday]; diff --git a/di/torq/proc/rdb/test.csv b/di/torq/proc/rdb/test.csv index 044f94cdb..be24f036f 100644 --- a/di/torq/proc/rdb/test.csv +++ b/di/torq/proc/rdb/test.csv @@ -7,3 +7,12 @@ fail,0,0,q,rdb.init[()!();(enlist`log)!enlist mlog],1,,init with log but no time true,0,0,q,`init`endofday`reload`version~key rdb,1,,module exports init/endofday/reload/version true,0,0,q,0` se Any of them can be given on the command line as `-stplg`, `-sctp` or `-createlogs`; an app sets only the keys it overrides. -An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. +An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. Timezone +strings become symbols and a `rolltimeoffset` string or number of seconds becomes a timespan; an unconvertible offset +errors at init. Flat: `schemafile` (required unless chained), `createlogs` (`1b`, required). @@ -65,7 +67,7 @@ Requires `log`, `timer` and `handlers`. It: 3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush `memorybatch`, close the logs); 4. sets `.u.upd` from `batchmode` and adds the `stpzts` timer job (the batch timer and the end checks, every - second); + `-t` milliseconds from the q command line, or every second without `-t`, as TorQ's `.z.ts`); 5. chained: waits for the upstream and subscribes; otherwise loads `schemafile`; 6. strips attributes from the published tables and opens the logs. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index 35b19db15..fd66a29da 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -2,6 +2,19 @@ / a symbol, a string or a list of strings (TOML has no symbol type) tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; + +/ di.eodtime settings from an [eodtime] section: timezones as symbols, rolltimeoffset as a timespan +eodconfig:{[s] + d:()!(); + if[`rolltimezone in key s;d:d,enlist[`rolltimezone]!enlist tosym s`rolltimezone]; + if[`datatimezone in key s;d:d,enlist[`datatimezone]!enlist tosym s`datatimezone]; + if[`rolltimeoffset in key s; + if[null o:totimespan s`rolltimeoffset;'"di.torq.proc.segmentedtp: rolltimeoffset must be a timespan"]; + d:d,enlist[`rolltimeoffset]!enlist o]; + d + }; / a relative path is under the app home (TorQ's app config dir) apppath:{[x] s:$[":"=first s:string x;1_s;s]; hsym`$$[("/"=first s) or 0=count h:getenv`TORQXAPPHOME;s;h,"/",s]}; @@ -26,7 +39,7 @@ init:{[config;deps] r[`.z.pc;`;`stpps;0j;.stpps.closesub]; .z.m.os:use`di.os; .z.m.eod:use`di.eodtime; - .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; + .z.m.eod.init[(enlist[`log]!enlist deps`log),eodconfig $[`eodtime in key config;config`eodtime;()!()]]; if[`stplgkdbtplog in key config;.stplg.kdbtplog:tosym config`stplgkdbtplog]; .stplg.multilog:tosym config`stplgmultilog; .stplg.multilogperiod:config`stplgmultilogperiod; @@ -111,8 +124,9 @@ init:{[config;deps] .stplg.updmsg:.stplg.upd[batch]; .stplg.ts:.stplg.zts[batch]; .u.upd:.stpps.upd[chainmode]; - / the batch timer and end checks run as a 1s di.timer job; the end guards disable only this job - .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();1;1;(enlist`disableonfail)!enlist 0b]; + / the batch timer and end checks run every -t ms (config timerms, 1000 if unset), as TorQ's .z.ts; the end guards disable only this job + ms:$[`timerms in key .z.m.params;.z.m.params`timerms;0N]; + .z.m.timer[`addjob][`stpzts;.stpps.zts[chainmode];();0D00:00:00.001*$[ms>0;ms;1000];1;(enlist`disableonfail)!enlist 0b]; / error mode: failed updates go to a separate log if[.stplg.errmode; .stp.upd:.u.upd; diff --git a/di/torq/proc/segmentedtp/test.csv b/di/torq/proc/segmentedtp/test.csv index f86f96750..31b34327f 100644 --- a/di/torq/proc/segmentedtp/test.csv +++ b/di/torq/proc/segmentedtp/test.csv @@ -16,11 +16,18 @@ true,0,0,q,"{all {[c;k] c[k]~ha ""get "",-3!` sv ``sctp,`$4_string k}[x] each k true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`$""/x/c.csv""",1,,an absolute customcsv is kept true,0,0,q,"`:/x/c.csv~.m.di.0torq.0proc.0segmentedtp.apppath`:/x/c.csv",1,,an hsym customcsv is kept true,0,0,q,"(hsym`$$[count h:getenv`TORQXAPPHOME;h,""/"";""""],""a/c.csv"")~.m.di.0torq.0proc.0segmentedtp.apppath`$""a/c.csv""",1,,a relative customcsv is under the app home +true,0,0,q,"((`$""America/New_York"");`$""Asia/Tokyo"";0D17:00:00)~eodinit`rolltimezone`datatimezone`rolltimeoffset!(""America/New_York"";""Asia/Tokyo"";""0D17:00:00"")",1,,an [eodtime] section of strings reaches di.eodtime as symbols and a timespan +true,0,0,q,"(`GMT;`GMT;0D01)~eodinit enlist[`rolltimeoffset]!enlist""0D01:00:00""",1,,a string rolltimeoffset alone reaches di.eodtime as a timespan +true,0,0,q,"(`$""Asia/Tokyo"";`GMT;0D)~eodinit enlist[`rolltimezone]!enlist""Asia/Tokyo""",1,,a string rolltimezone alone reaches di.eodtime as a symbol +fail,0,0,q,"eodinit enlist[`rolltimeoffset]!enlist""junk""",1,,an unparseable rolltimeoffset errors true,0,0,q,"(`immediate;`singular;1D)~hb"".stplg`batchmode`multilog`multilogperiod""",1,,stplg keys override the defaults; singular rolls daily true,0,0,q,"1D~hc"".stplg.multilogperiod""",1,,tabular rolls daily true,0,0,q,"all `stpps`sctp in ha""exec name from h.list`.z.pc""",1,,.z.pc observers registered true,0,0,q,"`stplg in ha""exec name from h.list`.z.exit""",1,,.z.exit observer registered -true,0,0,q,"(`stpzts;1;1;(enlist`disableonfail)!enlist 0b)~ha""tickjob""",1,,batch timer added as a 1s timer job that retries on failure +true,0,0,q,"(`stpzts;0D00:00:01;1;(enlist`disableonfail)!enlist 0b)~ha""tickjob""",1,,batch timer added as a 1s timer job that retries on failure (no -t: 1000ms as legacy) +true,0,0,q,"(`stpzts;0D00:00:00.2;1;(enlist`disableonfail)!enlist 0b)~hb""tickjob""",1,,batch timer period follows -t (b started with -t 200 then sets its own \t 60000) as legacy .z.ts runs at -t +true,0,0,q,"(`stpzts;0D00:00:01;1;(enlist`disableonfail)!enlist 0b)~hc""tickjob""",1,,-t 0 falls back to 1000ms as legacy (system t 1000 when t is unset) +true,0,0,q,"(`stpzts;0D00:00:00.3;1;(enlist`disableonfail)!enlist 0b)~hs""tickjob""",1,,a segmentedchainedtp (s) started with -t 300 batches every 300ms comment,,,,,,,subscribe handshake true,0,0,q,"`segmented~ha""tptype""",1,,tptype is segmented @@ -78,6 +85,7 @@ true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z true,0,0,q,"(`parent;`stp1;`)~hp"".sctp`loggingmode`tickerplantname`subscribeto""",1,,toml-style sctp strings become symbols true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,parent mode replays the upstream logs true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs +true,0,0,q,"(`GMT;0D)~hp""e:use`di.eodtime;(e[`getrolltimezone][];e[`getrolltimeoffset][])""",1,,toml-style eodtime strings reach di.eodtime comment,,,,,,,end of period run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the period end diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index a9d02c13a..ebdf6424d 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -5,7 +5,9 @@ QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} / a peer writes its port once initialised waitport:{[n] f:hsym`$FIXDIR,"/",string[n],".port"; d:.z.p+0D00:00:10; while[(.z.p",FIXDIR,"/",string[n],".log 2>&1 &"} +/ extra q flags per peer: b, c and s start with -t so their batch periods can be checked +TFLAGS:(`a`b`c`s`p!5#enlist""),`b`c`s!(" -t 200";" -t 0";" -t 300") +start:{[n] system QBIN," ",FIXDIR,"/",string[n],".q",(TFLAGS n)," -q ",FIXDIR,"/",string[n],".log 2>&1 &"} waitfor:{[f] d:.z.p+0D00:00:05; while[(.z.ptype c;c;first c / assertion helpers factored here because they contain raw commas (which split CSV fields) loghas:{[sub;n] n=logcount[BASE,"/",sub]} -flushperiodok:{[] 2=first exec period from timercalls where id=`tpflush} +flushperiodok:{[] 0D00:00:02=first exec period from timercalls where id=`tpflush} rolledfile:{[sub;date] not ()~key hsym`$BASE,"/",sub,"/tp",string date} +/ an upd arriving after the roll time: put the roll 1s in the past, send one trade (stamped by the feed or not), +/ return (date before;date after;messages in the next day's log) +pastroll:{[sub;stamped] + (use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; + d0:.u.d; + upd[`trade;$[stamped;(.z.p;`R;1f;1i);(`R;1f;1i)]]; + f:hsym`$BASE,"/",sub,"/tp",string d0+1; + (d0;.u.d;$[()~key f;0;first -11!(-2;f)])} / init helpers that store handles / state for assertions doinit:{[cfg] resetcalls[]; resettimer[]; resethandlers[]; (tk`init)[cfg;deps[]]; } diff --git a/di/torq/proc/tickerplant/tickerplant.md b/di/torq/proc/tickerplant/tickerplant.md index d1f337600..8fd77262a 100644 --- a/di/torq/proc/tickerplant/tickerplant.md +++ b/di/torq/proc/tickerplant/tickerplant.md @@ -22,12 +22,15 @@ coexists with `di.torq.servers`' own `.z.pc` hook (see Notes). ## Config +There is no publish-mode setting. As TorQ's `tickerplant.q`, q's `-t` decides: started with `-t ` +(di.torq stamps it into config as `timerms`) the tickerplant buffers updates and flushes them every `-t` +ms; without `-t`, or with `-t 0`, it publishes each update immediately. + ```toml -publishmode = "immediate" # "immediate" (publish each update) or "batched" (buffer, flush on a timer) -pubperiod = 1 # batched only: flush period in SECONDS (di.timer granularity) tplogdir = "tplog" # relative to TORQXDATAHOME, or absolute; empty/absent = no logging schemafile = "database.q" # defaults to /database.q (schema is code, not data) # rolltimezone / datatimezone / rolltimeoffset -> passed to di.eodtime (default GMT/GMT/0) +# rolltimeoffset = "0D17:00:00" -> a timespan string or a number of seconds ``` ## Behaviour @@ -49,7 +52,8 @@ schemafile = "database.q" # defaults to /database.q (schema is c and `upd` logs before it buffers, so a subscriber registered while rows sat unflushed would replay them from the log and then receive them again in the next flush. - **Timer jobs** (via injected `di.timer`): an EOD-roll check every second; plus, in - batched mode, a flush every `pubperiod` seconds (`di.pubsub.pubclear`). + batched mode, a flush every `-t` ms (`di.pubsub.pubclear`). In batched mode the EOD check stays this + separate 1s job, where TorQ runs it on every `.z.ts` tick. - **End of day** (`endofday`, published at root; fired by the roll-check job or via IPC): flush any buffer, `di.pubsub.callendofday`, roll the log (`di.tplogmgr.roll`), and advance di.eodtime's date / next-roll / daily-adjustment. @@ -70,11 +74,8 @@ because `di.tplogmgr.open` replays via `-11!`, which executes the root-level `up - A single malformed schema table (missing `time`/`sym`) is silently skipped rather than erroring (shape-filtering trade-off vs TorQ's strict assertion, chosen for robustness against ambient root tables). -- Batched flush granularity is whole seconds (di.timer's period unit); TorQ's `system"t"` - allows sub-second. Fine for v1. -- `di.eodtime` is vendored from an unmerged PR and `rolltimeoffset` can't be expressed - in TOML (no timespan type) — GMT-midnight rolls need no offset; a non-default offset - needs a `.q` settings file for now. +- `di.eodtime` is vendored from an unmerged PR. Timezone strings become symbols and + `rolltimeoffset` strings or seconds become a timespan; an unconvertible offset errors at init. ## Testing diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 36ce49282..b85183638 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -19,7 +19,9 @@ resolvedir:{[base;dir] } / consumers coerce at point of use: config values may be symbols (.q) or strings (.toml) -astz:{[x] $[11h=abs type x;x;`$x]} / to symbol (timezones, publishmode) +astz:{[x] $[11h=abs type x;x;`$x]} / to symbol (timezones) +/ a timespan, string, symbol or number of seconds as a timespan; null if not convertible +totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; / feed payloads may arrive as a table or as a list of columns; normalise to columns tocols:{[x] $[98h=type x;value flip x;x]} @@ -37,10 +39,13 @@ stamp:{[x] / stamps, logs (unless replaying - logh is 0 during the replay inside tplog.open), then / publishes immediately or buffers into the root table for the flush job. upd:{[t;x] - x:stamp tocols x; + x:tocols x; + / roll the day first if past the roll: always when immediate, for unstamped data when batched + if[$[.z.m.batchms>0;not -12=type first first x;1b];eodcheck[]]; + x:stamp x; if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.u.i+:1]; if[count .z.m.tplogdir;.u.icounts[t]+:count first x]; - $[.z.m.publishmode=`batched; + $[.z.m.batchms>0; t insert x; (.z.m.ps`publish)[t;flip (cols value t)!$[0>type first x;enlist each x;x]] ]; @@ -53,7 +58,7 @@ sub:{[x;y] if[x~`;:sub[;y] each .z.m.tables]; if[not x in .z.m.tables;'x]; / batched: flush first, so a replaying subscriber doesn't receive the buffer twice - if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + if[.z.m.batchms>0;(.z.m.ps`pubclear)[.z.m.tables]]; r:(.z.m.ps`subscribe)[x;y]; (first r 0;first r 1)} @@ -75,7 +80,7 @@ subdetails:{[tabs;syms] / batched: flush FIRST, to the subscribers that already exist. rowcount counts every message logged, and upd logs / before it buffers - so a subscriber registered while rows sat in the buffer would replay them from the log and / then receive the same rows again in the next flush. flushed before it registers, it sees them exactly once - if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + if[.z.m.batchms>0;(.z.m.ps`pubclear)[.z.m.tables]]; sub:(.z.m.ps`subscribe)[tabs;syms]; d:(.z.m.eod`getd)[]; lf:$[00;(.z.m.ps`pubclear)[.z.m.tables]]; d:(.z.m.eod`getd)[]; / tell subscribers (e.g. di.torq.proc.rdb) to end the day for partition d - AFTER any final flush / above, so they save exactly the day's data. Carries the date (vendored pubsub patch). @@ -103,15 +108,16 @@ endofday:{[] / EOD check (timer job, ~1s): roll when the next-roll time has passed. eodcheck:{[] if[(.z.m.eod`getnextroll)[]<.z.p;endofday[]];} -/ builds eodtime's merged init dict from the log dep + any tz config present, coercing -/ timezone values to symbols. rolltimeoffset only passed if already a timespan (TOML has -/ no timespan type, so a .toml settings file leaves it at eodtime's default). +/ di.eodtime init dict: timezones as symbols, rolltimeoffset as a timespan eoddeps:{[config;logdep] - d:enlist[`log]!enlist logdep; - if[`rolltimezone in key config;d[`rolltimezone]:astz config`rolltimezone]; - if[`datatimezone in key config;d[`datatimezone]:astz config`datatimezone]; - if[(`rolltimeoffset in key config) and -16h=type config`rolltimeoffset;d[`rolltimeoffset]:config`rolltimeoffset]; - d + d:()!(); + if[`rolltimezone in key config;d:d,enlist[`rolltimezone]!enlist astz config`rolltimezone]; + if[`datatimezone in key config;d:d,enlist[`datatimezone]!enlist astz config`datatimezone]; + if[`rolltimeoffset in key config; + if[null o:totimespan config`rolltimeoffset;'"di.torq.proc.tickerplant: rolltimeoffset must be a timespan"]; + d:d,enlist[`rolltimeoffset]!enlist o]; + / log first, then the eodtime keys + (enlist[`log]!enlist logdep),d } init:{[config;deps] @@ -122,8 +128,8 @@ init:{[config;deps] .z.m.timer:deps`timer; .z.m.handlers:deps`handlers; .z.m.cfg:config; - .z.m.publishmode:$[`publishmode in key config;astz config`publishmode;`immediate]; - .z.m.pubperiod:$[`pubperiod in key config;"j"$config`pubperiod;1]; + / batched every -t ms when -t is set (config timerms), immediate otherwise, as TorQ's tickerplant.q + .z.m.batchms:$[`timerms in key config;0^config`timerms;0]; .z.m.tplogdir:$[`tplogdir in key config;resolvedir[datahome[];config`tplogdir];""]; / schema: load the schema file at root; publishable tables are the UNKEYED ones with @@ -183,10 +189,10 @@ init:{[config;deps] .z.m.log[`info][`tickerplant;"opened tp log, replayed ",(string r 1)," message(s)"]; ]; - / timer jobs: EOD roll check every second; batched flush every pubperiod seconds - (.z.m.timer`addjob)[`tpeodcheck;eodcheck;();1;1h;()!()]; - if[.z.m.publishmode=`batched; - (.z.m.timer`addjob)[`tpflush;flush;();.z.m.pubperiod;1h;()!()]]; + / timer jobs: EOD roll check every second; batched flush every -t ms + (.z.m.timer`addjob)[`tpeodcheck;eodcheck;();0D00:00:01;1h;()!()]; + if[.z.m.batchms>0; + (.z.m.timer`addjob)[`tpflush;flush;();0D00:00:00.001*.z.m.batchms;1h;()!()]]; - .z.m.log[`info][`tickerplant;"initialised, mode=",(string .z.m.publishmode),", tables=",", " sv string tabs]; + .z.m.log[`info][`tickerplant;"initialised, mode=",$[.z.m.batchms>0;"batched every ",(string .z.m.batchms),"ms";"immediate"],", tables=",", " sv string tabs]; } diff --git a/di/torq/proc/wdb/test.csv b/di/torq/proc/wdb/test.csv index d16008828..f613cf08a 100644 --- a/di/torq/proc/wdb/test.csv +++ b/di/torq/proc/wdb/test.csv @@ -47,16 +47,19 @@ true,0,0,q,partbyfirstchar`part,1,,partbyfirstchar sorted then merged by whole p true,0,0,q,partbyfirstchar`col,1,,partbyfirstchar sorted then merged column by column true,0,0,q,partbyfirstchar`hybrid,1,,partbyfirstchar sorted then merged by the hybrid method true,0,0,q,segments[],1,,an intraday flush writes one segment per parted value and tracks its size +true,0,0,q,failedmerge[],1,,a failed merge signals out of end of day and leaves the segments on disk true,0,0,q,missingtables[],1,,startup writes empty table schemas into the working partition true,0,0,q,tabsizes[],1,,tablelist orders tables by bytes written -true,0,0,q,manipulation[],1,,savedownmanipulation is applied before a table is written +true,0,0,q,manipulation[],1,,savedownmanipulation is applied once before a table is written (5 doubled to 10) true,0,0,q,postreplay[],1,,postreplay is called after the move +true,0,0,q,failedpostreplay[],1,,a failing postreplay stops end of day after the move: no reload and the partition does not advance (as TorQ's wdb) true,0,0,q,compression[],1,,compression is applied to the hdb and reset afterwards true,0,0,q,fixpartition[],1,,data replayed into the wrong partition is moved to the tp log date 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,savejobmode[],1,,the flush job is scheduled from the end of the previous run (mode 3) 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 @@ -81,7 +84,7 @@ comment,,,,,,,sort mode - proctypes sort and sortworker run,0,0,q,"system ""l di/torq/proc/wdb/testsort.q""",1,,load the sort-mode fixture helpers run,0,0,q,setupfixture[],1,,fixture dirs and the env the module resolves paths against comment,,,,,,,the end of day tail -true,0,0,q,tailok[],1,,sym reloaded, both tables sorted by time, partition moved into the hdb, working dir gone +true,0,0,q,tailok[],1,,sym reloaded, both tables sorted by sym then time, partition moved into the hdb, working dir gone true,0,0,q,enumintact[],1,,the sym column still resolves after the move - the point of enumerating against hdb/sym true,0,0,q,discovertables[],1,,no table list means whatever is in the working partition true,0,0,q,defaultsavedir[],1,,an empty savedir on the wire falls back to the configured one @@ -95,7 +98,7 @@ true,0,0,q,badreloadorder[],1,,a reloadorder entry that is neither an hdb, rdb, true,0,0,q,idbreloadorder[],1,,idb in reloadorder is dispatched rather than reported as unknown comment,,,,,,,config true,0,0,q,stringconfig[],1,,string (toml / command-line) settings are parsed into the right types -true,0,0,q,sortcsvhonoured[],1,,a sortcsv overrides di.dbwrite's time-asc default +true,0,0,q,sortcsvhonoured[],1,,a sortcsv overrides di.dbwrite's sym-then-time p# default true,0,0,q,defaultsortcsv[],1,,with no sortcsv the app's sort.csv is used comment,,,,,,,the process entry point true,0,0,q,initpublishes[],1,,init opens hdb/rdb/idb/gateway/sortworker/wdb connections (never a tickerplant) and publishes the root entry point diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 356d3f9ba..ba2689a05 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -118,6 +118,17 @@ segments:{[] 3=count select from ps where ptdir like "*trade*") }; +/ a merge that fails (hdb destination with a mismatched sym type) stops end of day before the segments are deleted +failedmerge:{[] + freshwdb cfg[],`writedownmode`mergemode!(`partbyattr;`part); + feed[]; + (` sv hdbpart[`trade],`) set ([]time:`timestamp$();sym:`long$();price:`float$()); + ok:@[{.u.end x;1b};today[];{0b}]; + segs:@[{key hsym `$(1_string x),"/trade"};wdbpart[];{()}]; + (use`di.merge)[`clearpartsizes][]; + chk `signalled`segskept!(not ok;`aapl`ibm`msft~asc segs) + }; + / startup writes empty schemas into the working partition for the idb missingtables:{[] freshwdb cfg[]; @@ -147,6 +158,18 @@ postreplay:{[] (last POST)~today[] }; +/ a failing postreplay propagates out of end of day after the move, as TorQ's wdb: no reload, the partition does not advance +failedpostreplay:{[] + freshwdb cfg[],(enlist`postreplay)!enlist {[d;p] '"boom"}; + feed[]; + e:@[{.u.end x;""};today[];{x}]; + chk `signalled`moved`noreload`notadvanced!( + e~"boom"; + 0 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 +# postreplay (optional, .q settings) -> {[hdbdir;pt]} called after the move, before the reload; an error stops end of day, as TorQ # 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 $TORQXAPPCONFIG/sort.csv if present, else time asc +# sortcsv (optional) -> di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else the di.dbwrite default (sort by sym then time, p# on sym) ``` The schema comes from the **tickerplant**, not a local `database.q`: `.sub.subscribe` finds the diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index 5ca52d556..c32a66782 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -53,13 +53,6 @@ tablelist:{[] ((exec tablename from `bytes xdesc .z.m.tabsizes) union tables[`.] / function that ensures a list of syms is returned no matter what is passed to it ensuresymlist:{[s] -1 _ `${@[x; where not ((type each x) in (10 -10h));string]} s,(::)} -/ applies the table's savedownmanipulation function, if any, before a save -manipulate:{[t;x] - $[t in key .z.m.savedownmanipulation; - @[.z.m.savedownmanipulation t;x;{[x;e] .z.m.log[`error][`manipulate;"save down manipulation failed : ",e];x}[x]]; - x] - } - / saves a table to the partition once over its row limit; cleared with @[`.;...] as bare writes land in the module savetables:{[dir;pt;forcesave;tabname] / check row count @@ -69,7 +62,7 @@ savetables:{[dir;pt;forcesave;tabname] .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]]); + (` sv .Q.par[dir;pt;tabname],`;.Q.en[.z.m.hdbdir;r:0!(.z.m.dbw`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"]; @@ -135,7 +128,7 @@ savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] / get list of distinct combinations for partition directories extrapartitions:$[writedownmode~`partbyfirstchar;.z.m.mrg`getfirstcharpartitions;.z.m.mrg`getextrapartitions][tablename;extrapartitiontype]; / enumerate data to be upserted - enumdata:.Q.en[.z.m.hdbdir;0!manipulate[tablename;`. tablename]]; + enumdata:.Q.en[.z.m.hdbdir;0!(.z.m.dbw`manipulate)[tablename;`. tablename]]; .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; / upsert data to specific partition directory upserttopartition[dir;tablename;enumdata;pt;extrapartitiontype;;writedownmode] each extrapartitions; @@ -262,7 +255,7 @@ doreload:{[pt] 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)]]; + (.z.m.timer`addjob)[`sortflushend;flushend;();0D00:00:01;1h;`startattime`maxruns!(.z.m.timeouttime;1)]]; flushend[]]; } @@ -342,16 +335,11 @@ endofdaysortdate:{[dir;pt;tablist;hdbsettings] " 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]; + / call the postreplay hook, unprotected as TorQ's wdb + (.z.m.dbw`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 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]} @@ -439,8 +427,8 @@ endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode 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]; + / call the postreplay hook, unprotected as TorQ's wdb + (.z.m.dbw`postreplay)[hdbsettings`hdbdir;pt]; $[.z.m.permitreload;doreload pt;if[.z.m.gc;.Q.gc[]]]; } @@ -607,7 +595,10 @@ checksortparams:{[] / 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]; + / the save down hooks from config, defaulting as TorQ's wdb.q:78-79, go to di.dbwrite + sdm:$[`savedownmanipulation in key config;config`savedownmanipulation;()!()]; + pr:$[`postreplay in key config;config`postreplay;{[d;p]}]; + (.z.m.dbw`init)[`log`savedownmanipulation`postreplay!(deps`log;sdm;pr)]; 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]; } @@ -646,10 +637,8 @@ setconfig:{[config] .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.getpartition:$[`getpartition in key config;config`getpartition;defaultgetpartition]; .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]; @@ -748,7 +737,8 @@ init:{[config;deps] 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;()!()]; + / mode 3h reschedules from the end of the previous flush, as TorQ's .timer.repeat does + (.z.m.timer`addjob)[`wdbsave;savetodisk;();0D00:00:01*.z.m.settimer;3h;()!()]; 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/servers/servers.md b/di/torq/servers/servers.md index 658c28a39..397d1353f 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -89,6 +89,7 @@ Published at root by `init`, same bodies as legacy: | `.servers.cleanup` | l.116–118 | | `.servers.addnthawc` | l.121–128 | | `.servers.getdetails` | l.137 | +| `.servers.addh` | l.130–134 | | `.servers.addhw` / `.servers.addw` | l.139–150 | | `.servers.retry` | l.157 | | `.servers.retrydiscovery` | l.158–168 | @@ -98,8 +99,10 @@ Published at root by `init`, same bodies as legacy: | `.servers.register` | l.207–211 | | `.servers.querydiscovery` | l.215–221 | | `.servers.registerfromdiscovery` | l.225–231 | -| `.servers.addprocs` | l.233–244 | +| `.servers.addprocs` | l.233–244 (calls `.servers.addprocscustom`) | | `.servers.procupdate` | l.251 | +| `.servers.refreshattributes` | l.255–258 | +| `.servers.getserverbytype` / `.servers.gethandlebytype` / `.servers.gethpbytype` | l.97–107, over `SERVERS` | | `.servers.domainsocketsenabled` | l.261–267 | | `.servers.formathp` | l.271–307 | | `.servers.formatprocs` | l.310–314 | @@ -109,11 +112,19 @@ Published at root by `init`, same bodies as legacy: Also defined at root, for di.subscriptions' `.sub` and the tickerplants' startup waits: - `.servers.getservers` (5-arg; the exported 1-arg `getservers` is separate); -- `.servers.connectcustom` (called by `retryrows`); -- `.servers.startupdepnamecycles`. +- `.servers.connectcustom` (called by `retryrows`) and `.servers.addprocscustom` (called by `addprocs`), each kept if + already defined, as legacy; +- `.servers.startupdepnamecycles`, `.servers.startupdepcycles` and `.servers.startupdependent`. -They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqprocnamesnotconn` and -`startupdepcyclestypename`. +The root `.servers.gethandlebytype` is legacy's `getserverbytype[;`w;]`: it reopens dead handles first +(`getservers[…;1b;1b]`). The exported `gethandlebytype` does not; it picks only from live rows. + +`.servers.getserverbytype`/`.servers.gethpbytype` share their names with di.serverselect's +`getserverbytype`/`gethpbytype`, but read a different registry: these pick from `.servers.SERVERS` (this +process's connections, by proctype), di.serverselect's from its own server pool (filled by `addserver*`). + +They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqproctypesnotconn`, +`reqprocnamesnotconn` and `startupdepcyclestypename`. The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, `startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to @@ -122,7 +133,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser **Conversions** (legacy calls with no di equivalent): - `.lg.*` becomes the injected `log`. - `.dotz.set` on `.z.pc` becomes `handlers[`register]`. -- `.timer.repeat` becomes `timer[`addjob]`, mode 3 (next run from finish), period in seconds. +- `.timer.repeat` becomes `timer[`addjob]`, mode 3 (next run from finish), period as a timespan. - `.proc.cp[]` becomes `.z.p`. - `.proc.procname`/`proctype` in `getdetails` become init's identity. - `.proc.readprocs` becomes `readprocesscsv`. @@ -137,11 +148,10 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser module reads no files (`USERPASS`/`PASSWORDS` themselves are ported — see "Outbound credentials"); - `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`. +- `names`/`types`/`unregistered`/`checkw`/`reset`. + +**Residual:** `.servers.startup` is config-driven (`startup[config]`), so legacy's `.servers.startup[]` throws +`'type`. Accepting an empty call would silently connect to nothing; no port code calls it that way. **Legacy behaviour that differs from di.torq.servers 0.3.0:** - `startup` no longer excludes this process's own row. @@ -154,12 +164,15 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser ## Tests -`test.q` + `test.csv` (56 checks) spawn real q peers. They cover: +`test.q` + `test.csv` (71 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; +- `.servers.gethpbytype` (live, dead and unknown-selection) and the root `.servers.gethandlebytype`, `.servers.addh`, the `.servers.addprocscustom` hook called by `addprocs`, and `.servers.refreshattributes` + re-registering with a live discovery stub; - `waitfortype`, including a discovery stub that comes up after `startup`; -- `attributematch`, the root 5-arg `.servers.getservers` and `.servers.startupdepnamecycles`; +- `attributematch`, the root 5-arg `.servers.getservers`, `.servers.startupdepnamecycles`, + `.servers.startupdepcycles` and `.servers.startupdependent`; - input validation and `getapimeta`. The rest of the discovery protocol is covered by `di.torq.proc.discovery`'s suite. Run in a fresh diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index 668c0aae7..7465f7e8c 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -80,15 +80,16 @@ init:{[deps] 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); + pub:`opencon`cleanup`addnthawc`getdetails`addhw`addw`addh`retry`retrydiscovery`autodiscovery`retryrows`removerows`register`querydiscovery`registerfromdiscovery`addprocs`procupdate`refreshattributes`getserverbytype`gethandlebytype`gethpbytype`domainsocketsenabled`formathp`formatprocs`startup`pc!(opencon;cleanup;addnthawc;getdetails;addhw;addw;addh;retry;retrydiscovery;autodiscovery;retryrows;removerows;register;querydiscovery;registerfromdiscovery;addprocs;procupdate;refreshattributes;getserverbytype;getserverbytype[;`w;];gethpbytype;domainsocketsenabled;formathp;formatprocs;startup;pc); + / root .servers.gethandlebytype is legacy's getserverbytype[;`w;] (reopens dead handles), not the export set'[` sv/:`.servers,/:key pub;value pub]; if[not .z.m.registered; / .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;()!()]]]; + if[.servers.DISCOVERYRETRY>0;(.z.m.timer[`addjob])[`discoveryretry;retrydiscovery;();.servers.DISCOVERYRETRY;3;()!()]]; + if[.servers.RETRY>0;(.z.m.timer[`addjob])[`serversretry;retry;();.servers.RETRY;3;()!()]]]; .z.m.registered:1b; ]; .z.m.loginfo[`init;"di.torq.servers initialised"]; @@ -152,6 +153,13 @@ addhw:{[hpuP;W] addw:addhw[`] +/ open a connection to a server and store its details, as trackservers.q:130-134 +addh:{[hpuP] + W:opencon hpuP; + $[null W; + '"failed to open handle to ",string hpuP; + addhw[hpuP;W]]} + / after getting new servers run retry to open connections retry:{retryrows exec i from `.servers.SERVERS where not .dotz.liveh0 w,not proctype=`discovery} @@ -214,11 +222,18 @@ addprocs:{[connectiontab;procs;connect] 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,()];} + register[res;;connect] each $[procs~`ALL;exec distinct proctype from res;procs,()]; + .servers.addprocscustom[res;procs]} / used to handle updates from the discovery service procupdate:{[procs] addprocs[procs;exec distinct proctype from procs;0b];} +/ re-register this process's attributes with each discovery service, as trackservers.q:255-258 +refreshattributes:{ + retrydiscovery[]; + (neg exec w from .servers.getservers[`proctype;`discovery;()!();0b;0b])@\:(`..register;`); + } + / return true if unix domain sockets can be used domainsocketsenabled:{[] notwin:not .z.o like "w*"; @@ -315,6 +330,16 @@ gethandlebytype:{[pt;selection] wh }; +/ one server value for a proctype from SERVERS, reopening dead handles first, as trackservers.q:97-107 +getserverbytype:{[ptype;serverval;selection] + r:.servers.getservers[`proctype;ptype;()!();1b;1b]; + if[count r; + r:selector[r;selection]; + updatestats[r`w]]; + r[serverval]} + +gethpbytype:getserverbytype[;`hpup;] + signalfound:{[pt] / internal - log and return 1b once a connection to pt exists. .z.m.loginfo[`servers;"connected to ",string pt]; @@ -371,12 +396,16 @@ attributematch:{[req;avail] / root, for .sub: run on (re)connected SERVERS rows .servers.connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}]; +/ addprocs' hook for bespoke extensions when adding processes, as trackservers.q:246-247 +.servers.addprocscustom:@[value;`.servers.addprocscustom;{{[connectiontab;procs]}}]; / are any required processes not connected reqprocsnotconn:{[requiredprocs;typeorname] not all requiredprocs in ?[`.servers.SERVERS;enlist (`.dotz.liveh;`w);();typeorname] }; +reqproctypesnotconn:reqprocsnotconn[;`proctype]; + reqprocnamesnotconn:reqprocsnotconn[;`procname]; / block until all required processes are connected @@ -397,3 +426,7 @@ startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles] / root, for chainedtp and segmentedtp .servers.startupdepnamecycles:startupdepcyclestypename[;reqprocnamesnotconn;;]; + +/ root, as TorQ's: block until all required proctypes are connected, for a number of cycles or forever +.servers.startupdepcycles:startupdepcyclestypename[;reqproctypesnotconn;;]; +.servers.startupdependent:startupdepcyclestypename[;reqproctypesnotconn;;0W]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index 21467bac1..b4109a837 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -13,7 +13,7 @@ comment,,,,,,,init - wiring and idempotency run,0,0,q,svc.init[svrdeps[`otherproc`deadproc]],1,1,init with mock deps + config (dial otherproc and deadproc) true,0,0,q,"1=count select from handlercalls where event=`.z.pc,name=`servers",1,1,init registered its .z.pc observer via the handlers dep true,0,0,q,1=count select from timercalls where id=`serversretry,1,1,init scheduled the retry job via the timer dep -true,0,0,q,300=first exec period from timercalls where id=`serversretry,1,1,retry period is 300s +true,0,0,q,0D00:05=first exec period from timercalls where id=`serversretry,1,1,retry period is 5 minutes 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 @@ -30,6 +30,11 @@ true,0,0,q,"warnlogged[""failed to open connection""]",1,1,the failed dial was l comment,,,,,,,gethandlebytype - a genuinely live remote handle run,0,0,q,h:svc.gethandlebytype[`otherproc;`any],1,1,get a handle to the peer true,0,0,q,"2=h ""1+1""",1,1,the handle is a live remote connection to a separate process +comment,,,,,,,root .servers.gethpbytype over SERVERS (trackservers.q:97-107) +true,0,0,q,".servers.gethpbytype[`otherproc;`any]~first exec hpup from .servers.SERVERS where proctype=`otherproc",1,1,gethpbytype returns the live otherproc row's hpup +true,0,0,q,"(`symbol$())~.servers.gethpbytype[`deadproc;`any]",1,1,a proctype with no live server gives an empty list after the reopen attempt (as legacy r[serverval]) +fail,0,0,q,".servers.gethpbytype[`otherproc;`nosuch]",1,1,an unknown selection signals +true,0,0,q,".servers.gethandlebytype[`otherproc;`any]~first exec w from .servers.SERVERS where proctype=`otherproc",1,1,root gethandlebytype (legacy getserverbytype[;`w;]) returns the live otherproc handle 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) @@ -40,6 +45,10 @@ run,0,0,q,".servers.connectcustom:{[r] `ccrows set r}",1,1,record what retryrows 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,,,,,,,addh and the addprocscustom hook (trackservers.q:130-134; 244-247) +true,0,0,q,addhpeer[],1,1,addh opens a working handle to the peer and stores it in SERVERS +fail,0,0,q,".servers.addh `$"":localhost:"",string DEADPORT",1,1,addh signals when nothing is listening +true,0,0,q,addprocshook[],1,1,addprocs calls .servers.addprocscustom with the rows it added and the procs 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 @@ -51,6 +60,11 @@ true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,ge 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 +run,0,0,q,".servers.startupdepcycles[`otherproc;0;1]",1,1,startupdepcycles returns once otherproc is connected +fail,0,0,q,".servers.startupdepcycles[`deadproc;0;0]",1,1,startupdepcycles signals after its cycles are used up +true,0,0,q,"any (exec msg from logrows where lvl=`error,ctx=`connectionreport) like ""*cannot connect to deadproc""",1,1,the error names the proctype it could not reach +run,0,0,q,".servers.startupdependent[`otherproc;0]",1,1,startupdependent returns once otherproc is connected +true,0,0,q,0W~last value .servers.startupdependent,1,1,startupdependent never gives up waiting (its cycle count is 0W) 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 @@ -58,6 +72,7 @@ run,0,0,q,svc.startup[svrdeps[`tpproc]],1,1,startup while discovery is down - th true,0,0,q,0=count svc.getservers[`discovery],1,1,discovery is not live after startup run,0,0,q,spawndisc[],1,1,bring up the tpproc peer then discovery true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery and connects to the tpproc it names +true,0,0,q,refreshregisters[],1,1,refreshattributes sends one register to each live discovery service (trackservers.q:255-258) comment,,,,,,,retry periods from toml run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans diff --git a/di/torq/servers/test.q b/di/torq/servers/test.q index 8c8acc7a1..510dae5b9 100644 --- a/di/torq/servers/test.q +++ b/di/torq/servers/test.q @@ -13,7 +13,7 @@ mocklog:`info`warn`error!( / 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$();mode:`long$()); +timercalls:([]id:`symbol$();period:`timespan$();mode:`long$()); timerjobs:(`symbol$())!(); mocktimer:enlist[`addjob]!enlist {[id;func;params;period;mode;opts] timerjobs[id]:func; `timercalls upsert (id;period;`long$mode);}; @@ -30,34 +30,45 @@ warnlogged:{[s] any (exec msg from logrows where lvl=`warn) like "*",s,"*"}; firejob:{[id] timerjobs[id][]}; / --- real peer process fixture --- -FIXDIR:"/tmp/diserverstest"; +FIXDIR:"/tmp/diserverstest_",string .z.i; 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; +/ an OS-assigned free port: a q started with -p 0W writes its port and exits before any connection is made, +/ so the port can be bound again (no port picking: a port with no listener can still be unbindable) +reserveport:{[] + f:FIXDIR,"/port",string 1+count key hsym`$FIXDIR; + (hsym`$FIXDIR,"/portprobe.q") 0: enlist "(hsym`$first .z.x) 0: enlist string system\"p\"; exit 0"; + system QBIN," ",FIXDIR,"/portprobe.q ",f," -p 0W -q /dev/null 2>&1"; + "J"$first read0 hsym`$f}; + waitlisten:{[port;timeoutms] deadline:.z.p+`timespan$1000000*timeoutms; while[(.z.p/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"; - hclose h;}; +/ start q on port with args, logging to FIXDIR; wait until it listens and check the listener is the process +/ just spawned (its .z.i is the spawned pid); returns the pid +spawnat:{[args;port] + pid:"J"$first system QBIN," ",args," -p ",(string port)," -q ",FIXDIR,"/q",(string port),".log 2>&1 & echo $!"; + if[not waitlisten[port;3000];'"test: q failed to listen on ",(string port)," (see ",FIXDIR,"/q",(string port),".log)"]; + h:hopen (`$":localhost:",string port;2000); + ok:pid=h ".z.i"; + hclose h; + if[not ok;'"test: port ",(string port)," answered for a process this fixture did not spawn"]; + pid}; + +spawnpeer:{[] PEERPID::spawnat["";PEERPORT];}; killpeer:{[] if[not null PEERPID;@[system;"kill ",string PEERPID;{}]]; PEERPID::0N; system "sleep 0.3";}; setupfixture:{[] - / pick two free ports (peer + a never-listening dead one), then write a header'd process.csv + / reserve two ports (peer + a never-listening dead one), then write a header'd process.csv / phone book with self, the peer (otherproc), and a dead proctype. - PEERPORT::pickport 20000+`int$.z.i mod 20000; - DEADPORT::pickport PEERPORT+1; system "mkdir -p ",FIXDIR; + PEERPORT::reserveport[]; + DEADPORT::reserveport[]; (`$":",FIXDIR,"/process.csv") 0: ( "host,port,proctype,procname"; "localhost,",string[PEERPORT-2],",selfproc,selfinst"; @@ -73,24 +84,44 @@ 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; + DISCPORT::reserveport[]; + TPPORT::reserveport[]; (`$":",FIXDIR,"/process.csv") 0: (read0 `$":",FIXDIR,"/process.csv"),enlist "localhost,",string[DISCPORT],",discovery,discinst"; (`$":",FIXDIR,"/disc.q") 0: ( - "register:{}"; + "REGN:0;register:{[x] `REGN set REGN+1}"; "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;}; +spawnq:{[args;port] DISCPIDS,:spawnat[args;port];}; spawndisc:{[] spawnq["";TPPORT]; spawnq[FIXDIR,"/disc.q";DISCPORT];}; killdisc:{[] {@[system;"kill ",string x;{}]} each DISCPIDS; DISCPIDS::`long$();}; +/ addh to the live peer: the handle it returns works and is stored in SERVERS; the row is removed after +addhpeer:{[] + W:.servers.addh `$":localhost:",string PEERPORT; + r:(2=W"1+1";1=count select from .servers.SERVERS where w=W); + delete from `.servers.SERVERS where w=W; hclose W; + all r}; + +/ addprocs calls .servers.addprocscustom with the new rows and the procs; the hook and row are reset after +addprocshook:{[] + / bind the .z.pc that addprocs' removerows calls, as setupdisc does; a fresh dead port so no fixture row is replaced + .z.pc:{}; + `APC set (); + .servers.addprocscustom:{[t;p] `APC set (exec procname from t;p)}; + .servers.addprocs[([]procname:enlist`newinst;proctype:enlist`newproc;hpup:enlist`$":localhost:",string reserveport[]);enlist`newproc;0b]; + .servers.addprocscustom:{[connectiontab;procs]}; + delete from `.servers.SERVERS where procname=`newinst; + (enlist`newinst;enlist`newproc)~APC}; + +/ refreshattributes sends one register to each live discovery service +refreshregisters:{[] + h:first exec w from .servers.getservers[`proctype;`discovery;()!();0b;0b]; + b:h"REGN"; + .servers.refreshattributes[]; + (b+1)=h"REGN"}; + / build the deps dict di.torq would assemble: injectables + this process's config slice. / discovery off, so startup dials process.csv directly (trackservers.q's own defaults are 1b). 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/test.csv b/di/torq/test.csv index 37138ab36..e185afb7a 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -5,6 +5,18 @@ before,0,0,q,setupfixture[],1,,create a temp app fixture: settings, process.csv, fail,0,0,q,tq.reqenv[`DI_TORQ_TEST_NO_SUCH_VAR],1,,reqenv on a missing env var must error +comment,,,,,,,framework home: TORQXHOME if set, else the QPATH entry holding di/torq +true,0,0,q,"REPO~withenv[`TORQXHOME;"""";{.m.di.0torq.frameworkhome[]}]",1,,without TORQXHOME the framework home is the QPATH checkout +true,0,0,q,"""/opt/torqx""~withenv[`TORQXHOME;""/opt/torqx"";{.m.di.0torq.frameworkhome[]}]",1,,TORQXHOME is used as given when set +fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0torq.frameworkhome[]}]}]",1,,without TORQXHOME and no QPATH entry holding di/torq it errors +fail,0,0,q,"withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent:"";{.m.di.0torq.frameworkhome[]}]}]",1,,an empty QPATH entry is not the working directory +run,0,0,q,"system ""mkdir -p "",APPBASE,""/qhome/mod/di/torq""; (hsym`$APPBASE,""/qhome/mod/di/torq/init.q"") 0: ()",1,,a QHOME holding di/torq under mod +true,0,0,q,"(APPBASE,""/qhome/mod"")~withenv[`TORQXHOME;"""";{withenv[`QHOME;APPBASE,""/qhome"";{withenv[`QPATH;"""";{.m.di.0torq.frameworkhome[]}]}]}]",1,,without QPATH the framework home is $QHOME/mod, where use searches +true,0,0,q,"@[{withenv[`TORQXHOME;"""";{withenv[`QPATH;"""";{withenv[`QHOME;"""";{.m.di.0torq.frameworkhome[]}]}]}]};::;{x}] like ""*QPATH and QHOME are unset*""",1,,without QPATH or QHOME the error says so rather than searching /mod +true,0,0,q,"@[{withenv[`TORQXHOME;"""";{withenv[`QPATH;""/nonexistent"";{.m.di.0torq.frameworkhome[]}]}]};::;{x}] like ""*searched: /nonexistent*""",1,,the error names the entries searched +true,0,0,q,"(REPO,""/di/torq/settings"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.roots[]}]",1,,the builtin settings root needs no TORQXHOME +true,0,0,q,"(REPO,""/di/torq/permissions"")~first withenv[`TORQXHOME;"""";{.m.di.0torq.permissionroots[]}]",1,,the framework permissions root needs no TORQXHOME + fail,0,0,q,tq.init[`;`;()!()],1,,"auto-detect with no port set (system""p""=0) and two localhost rows in process.csv must fail as ambiguous" run,0,0,q,system "p 19999",1,,bind a port that appears nowhere in the fixture process.csv @@ -29,7 +41,7 @@ true,0,0,q,"(2;3)~(HITS;UPD)",1,,is not skipped: the ignorelist check only match 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,".m.di.0clienttracking.hit:first ctorig; .m.di.0clienttracking.hite:last ctorig",1,,restore client tracking -run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],x,`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings +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`clientsopencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works @@ -39,6 +51,12 @@ true,0,0,q,`di.torq.proc.segmentedtp~.m.di.0torq.builtin`segmentedchainedtp,1,,s run,0,0,q,r3:tq.init[TESTPROCNAME;`testinst;()!()],1,,explicit-identity init for a custom proctype true,0,0,q,TESTPROCNAME~r3`proctype,1,,identity resolved for the custom proctype true,0,0,q,`widget in key .k4unittestproc.capturedconfig,1,,config cascade reached the custom proctype's own settings file +true,0,0,q,"(`timerms in key .k4unittestproc.capturedconfig)&0N~.k4unittestproc.capturedconfig`timerms",1,,init stamps timerms from q's own -t (null here: this test process runs without -t) +true,0,0,q,"200~launchtimerms["" -t 200""]",1,,a process launched through torqx_init.q with -t 200 has timerms 200 in its config +true,0,0,q,"0N~launchtimerms[""""]",1,,a process launched without -t has a null timerms +true,0,0,q,"(`pptparent;1;1;1b;0b)~launchppt["" -parentproctype pptparent""]",1,,-parentproctype: stamped as a symbol; its settings tier read; proctype beats it; code// loaded before code// +true,0,0,q,"((`);0N;1;0b;0N)~launchppt[""""]",1,,without -parentproctype: parentproctype is a null symbol and no parent tier or code is loaded +true,0,0,q,"(`pptparent;1;1;0b;0N)~launchppt["" -parentproctype pptparent -loadprocesscode 0""]",1,,loadprocesscode 0b: the parent's code is not loaded (gated as torq.q:643); its settings still are true,0,0,q,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed true,0,0,q,1=.k4unittestproc.deferredcalled,1,,a function queued with .proc.addinitlist ran once after init @@ -68,6 +86,7 @@ true,0,0,q,not any `proctype`procname`torqxstackid`p`norun in key .m.di.0torq.cl true,0,0,q,(enlist"7")~(.m.di.0torq.clioverrideparams[cliopts])`myrows,1,,kept override values are unchanged (the .Q.opt string-list shape overrideconfig expects) true,0,0,q,0=count .m.di.0torq.clioverrideparams[()!()],1,,an empty command line yields no overrides true,0,0,q,0=count .m.di.0torq.clioverrideparams[`proctype`p!((enlist"hdb");(enlist"5560"))],1,,a command line of only reserved flags yields no overrides +true,0,0,q,"0=count .m.di.0torq.clioverrideparams[enlist[`parentproctype]!enlist enlist""wdb""]",1,,-parentproctype is a reserved flag (an identity input) not a config override comment,,,,,,,optional query logging - initquerylog wires di.querylog from a [querylog] settings section (init calls it last) run,0,0,q,.m.di.0torq.initquerylog[qlcfg 0b;r4`deps],1,,a [querylog] section with enabled=false is a silent no-op @@ -78,6 +97,7 @@ true,0,0,q,"(`upd;`.u.upd;""upd"";"".u.upd"")~.m.di.0torq.qlignore (""upd"";"".u run,0,0,q,.m.di.0torq.initquerylog[qlcfg 1b;r4`deps],1,,enable with defaults - memory-only log plus the flush timer job true,0,0,q,.m.di.0torq.querylogwired,1,,the wired flag is set true,0,0,q,`querylogflush in exec id from (r4[`deps][`timer][`getactivejobs])[],1,,the in-memory flush job was scheduled on the injected timer +true,0,0,q,3h=exec first mode from (r4[`deps][`timer][`getactivejobs])[] where id=`querylogflush,1,,the flush job reschedules from the end of the previous run (mode 3) as TorQ's .timer.repeat does run,0,0,q,n0:qlcompleted`pg,1,,baseline sync-query completions run,0,0,q,qlsync[],1,,one sync query through the wrapped .z.pg true,0,0,q,1=(qlcompleted`pg)-n0,1,,one sync query logs exactly one completion row diff --git a/di/torq/test.q b/di/torq/test.q index 7cd47722f..b43f69932 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -1,7 +1,7 @@ / fixture helpers for di.torq's tests. -/ Assumes q is started with the kdbx-modules repo root as the working directory AND with -/ TORQXHOME already pointing at the real kdbx-modules checkout (di.torq's own built-in -/ settings and `builtin` registry genuinely live there - there is no faking that part). +/ Assumes q is started with the kdbx-modules repo root as the working directory and on QPATH +/ (di.torq's own built-in settings and `builtin` registry genuinely live there - there is no +/ faking that part). / TORQXAPPCONFIG and TORQXAPPHOME are both repointed at a temp fixture below to / isolate everything else (process.csv, app-level settings, a scratch hdb dir, the / custom proctype's code file) from any real app - nothing this test does touches a @@ -14,9 +14,16 @@ APPBASE:"/tmp/di_torq_k4unit_app" HDBDIR:APPBASE,"/hdb" TESTPROCNAME:`k4unittestproc TESTPROCFILE:APPBASE,"/code/processes/",string[TESTPROCNAME],".q" +QBIN:first system "readlink -f /proc/",(string .z.i),"/exe" writelines:{[path;lines] (hsym `$path) 0: lines; } +/ the kdbx-modules checkout: the working directory +REPO:system "cd" + +/ f[] with env var e set to v, then e restored; f's error is re-signalled after the restore +withenv:{[e;v;f] o:getenv e; setenv[e;v]; r:@[{(1b;x[])};f;{(0b;x)}]; setenv[e;o]; $[r 0;r 1;'r 1]} + setupfixture:{[] system "rm -rf ",APPBASE; system "mkdir -p ",APPBASE,"/settings ",APPBASE,"/code/processes ",APPBASE,"/code/common ",APPBASE,"/code/",string[TESTPROCNAME]," ",APPBASE,"/code/testinst ",HDBDIR; @@ -28,6 +35,11 @@ setupfixture:{[] writelines[APPBASE,"/code/common/appcommon.q";enlist "APPCOMMON_LOADED:1b"]; writelines[APPBASE,"/code/",string[TESTPROCNAME],"/appproc.q";enlist "APPPROC_LOADED:1b"]; writelines[APPBASE,"/code/testinst/appname.q";enlist "APPNAME_LOADED:1b"]; + / -parentproctype fixtures: a parent settings tier (a parent-only key, a key the proctype also sets, and loadprocesscode + / declared so -loadprocesscode can override it) and parent code recording whether the proctype's code had loaded yet + writelines[APPBASE,"/settings/pptparent.q";("pptonly:1";"widget:0";"loadprocesscode:1b")]; + system "mkdir -p ",APPBASE,"/code/pptparent"; + writelines[APPBASE,"/code/pptparent/pptcode.q";("PPTCODE:1b";"PPTBEFOREPROC:@[value;`APPPROC_LOADED;0b]")]; / a scratch hdb: just a serialized table, the simplest thing \l can load (hsym `$HDBDIR,"/widgets") set ([]id:1 2 3); @@ -58,8 +70,33 @@ setupfixture:{[] " };"; "run:{[] runcalled::runcalled+1};"; "\\d .")]; + + / a launcher that starts a real process through torqx_init.q and writes the timerms its config carried + writelines[APPBASE,"/launch.q"; + ("system \"l ",REPO,"/di/torq/bin/torqx_init.q\";"; + "(hsym`$getenv[`TORQXAPPHOME],\"/timerms.txt\") 0: enlist .Q.s1 .k4unittestproc.capturedconfig`timerms;"; + "exit 0")]; } +/ a launcher that starts a real process through torqx_init.q and writes what -parentproctype changed +pptlauncher:{[] writelines[APPBASE,"/launchppt.q"; + ("system \"l ",REPO,"/di/torq/bin/torqx_init.q\";"; + "c:.k4unittestproc.capturedconfig;"; + "(hsym`$getenv[`TORQXAPPHOME],\"/ppt.txt\") 0: enlist .Q.s1 (c`parentproctype;$[`pptonly in key c;c`pptonly;0N];c`widget;@[value;`PPTCODE;0b];@[value;`PPTBEFOREPROC;0N]);"; + "exit 0")]} + +/ launch a real process with extra q flags; return (parentproctype;pptonly;widget;parent code loaded;proctype code loaded before it) +launchppt:{[flags] + pptlauncher[]; f:APPBASE,"/ppt.txt"; system "rm -f ",f; + system QBIN," ",APPBASE,"/launchppt.q -proctype ",(string TESTPROCNAME)," -procname testinst",flags," -q ",APPBASE,"/ppt.log 2>&1"; + value first read0 hsym`$f} + +/ launch a real process through torqx_init.q with extra q flags; return the timerms in its config +launchtimerms:{[flags] + f:APPBASE,"/timerms.txt"; system "rm -f ",f; + system QBIN," ",APPBASE,"/launch.q -proctype ",(string TESTPROCNAME)," -procname testinst",flags," -q ",APPBASE,"/launch.log 2>&1"; + value first read0 hsym`$f} + / helper so the test.csv cell stays comma-free (k4unit's CSV splits unquoted commas): writes / loadnamecode into the procname settings tier to turn on the procname-tier app-code cascade. enablenamecode:{[] writelines[APPBASE,"/settings/testinst.q";enlist "loadnamecode:1b"]; } diff --git a/di/torq/torq.md b/di/torq/torq.md index 73b6663df..76527af31 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -51,31 +51,35 @@ nothing at all). ### Environment variables -Three independent, explicitly-set env vars - not derived from each other: +`TORQXHOME` is optional; the app sets the other two: | var | what it points at | used for | |---|---|---| -| `TORQXHOME` | the `di.torq`/framework checkout | builtin settings root (`$TORQXHOME/di/torq/settings`) | +| `TORQXHOME` | the `di.torq`/framework checkout; when unset, the module search path entry that holds `di/torq` (`QPATH`'s non-empty entries, or `$QHOME/mod` when it has none, as `use` searches; with both unset, set `TORQXHOME`) | builtin settings root (`/di/torq/settings`) and framework permissions root (`/di/torq/permissions`) | | `TORQXAPPCONFIG` | the app's `appconfig/` directory | app settings root (`$TORQXAPPCONFIG/settings`) and `process.csv` | | `TORQXAPPHOME` | the app's own project root | `code/processes/{proctype}.q` (custom proctypes), and where `di.torq.proc.hdb`'s relative `dir:` settings resolve against | ### Config cascade `roots[]` builds the two roots `di.torq.config.cascade` needs -(`` `$TORQXHOME/di/torq/settings ``, `` `$TORQXAPPCONFIG/settings ``); `init` calls +(`` `/di/torq/settings ``, `` `$TORQXAPPCONFIG/settings ``); `init` calls `` (cc`cascade)[r 0;r 1;proctype;procname] `` and then adds the resolved `proctype`/`procname` into the result itself, so any module (or anything it calls) can find out who it is just by looking at its own `config` dict - no global to reach for. See `di.torq.config`'s own docs for the 5-tier cascade itself. +It also adds `timerms`: q's own `-t` in milliseconds, or null without `-t`. q consumes `-t`, so +`cmdlinet` reads it from the full command line `.z.X`, once. The tickerplants batch on it, as TorQ's +`.z.ts` runs at `-t`, without reading the command line themselves. + ### Dependency building `buildlogdep`/`buildtimerdep`/`buildhandlersdep` each build one of the three DI contract dependencies (`log`, `timer`, `handlers`), defaulting to `di.util.log`/`di.timer`/ `di.torq.handlers` respectively, with an override escape hatch - the `overrides` dict passed into `init` can specify a different module name under the `` `log ``/`` `timer ``/ -`` `handlers `` key. `buildtimerdep` also initializes `di.timer` itself (with no deps -of its own - it's Tier 1 standalone) and reshapes its exported `addjob` (a dict of +`` `handlers `` key. `buildtimerdep` also initializes `di.timer` itself (with the +injected `log` dep, through which di.timer logs failed jobs) and reshapes its exported `addjob` (a dict of `custom`/`default`/`simple` variants) down to the one signature the DI contract expects. @@ -112,15 +116,20 @@ The cascade mirrors the config cascade's shape: | tier | directory | flag | default | |------|-----------|------|---------| | common | `code/common/` | `loadcommoncode` | on | +| parentproctype | `code//` | `loadprocesscode`, and `-parentproctype` given | on when given | | proctype | `code//` | `loadprocesscode` | on | | procname | `code//` | `loadnamecode` | **off** | So **yes, it supports per-procname customisation** just like the config cascade — but, exactly 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: proctypes `sort` and `sortworker` are -built in and run `di.torq.proc.wdb` itself, with `settings/sort.q` and `settings/sortworker.q`. +config (so it's overridable per-process in settings). `-parentproctype` (TorQ's 4th tier, read +from the command line as `torq.q:376-380` and stamped into config as a symbol atom, null if not +given) adds a `{parentproctype}` settings tier between `default` and `{proctype}`, and loads +`code//` between `common` and ``, gated by `loadprocesscode` as `torq.q:643`. +It is a reserved flag, not a config override. Proctypes `sort` and `sortworker` still run +`di.torq.proc.wdb` with `settings/sort.q` and `settings/sortworker.q`; `-parentproctype wdb` adds +only what an app puts in a `wdb` settings tier or `code/wdb/`. 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`. @@ -342,9 +351,10 @@ freshly-started process. tmux mode is for local development; production stays on module's tests, and `di.torq`'s actual job is wiring them together correctly, which mocking them away wouldn't exercise. Only `TORQXAPPCONFIG`/`TORQXAPPHOME` are repointed at a temp fixture (a scratch settings tree, `process.csv`, and a throwaway -custom proctype file that publishes its own `run` hook to assert on) - `TORQXHOME` -stays real, since `di.torq`'s own built-in settings and registry genuinely live -there. Covers: `reqenv` erroring on a missing var, both auto-detect failure modes +custom proctype file that publishes its own `run` hook to assert on); the built-in +settings and registry are the checkout's own, found through `QPATH`, so the suite needs +no env vars set. Covers: `reqenv` erroring on a missing var, the framework home with and +without `TORQXHOME`, both auto-detect failure modes (no match, ambiguous), explicit-identity init for both a built-in and a custom proctype, config-cascade/deps reaching the started process type correctly, the `.run` hook firing by default and being skipped when `norun` is set, and successful diff --git a/di/torq/torq.q b/di/torq/torq.q index 28a432ff9..44e93d88a 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -12,8 +12,21 @@ reqenv:{[e] v } +/ the kdbx-modules checkout holding di.torq: TORQXHOME if set, else the module search path entry that holds di/torq +frameworkhome:{[] + if[count h:getenv`TORQXHOME;:h]; + / the module search path, as use searches it: QPATH's non-empty entries, or $QHOME/mod when it has none + p:":" vs getenv`QPATH; + p:p where 0/ between common and proctype, gated by loadprocesscode, as torq.q:643. 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 @@ -179,6 +191,7 @@ loadappcodedir:{[lg;dir] loadappcode:{[lg;config;proctype;procname] base:reqenv[`TORQXAPPHOME],"/code/"; if[optflag[config;`loadcommoncode;1b]; loadappcodedir[lg;base,"common"]]; + if[optflag[config;`loadprocesscode;1b] and not null ppt:$[`parentproctype in key config;config`parentproctype;`]; loadappcodedir[lg;base,string ppt]]; if[optflag[config;`loadprocesscode;1b]; loadappcodedir[lg;base,string proctype]]; if[optflag[config;`loadnamecode;0b]; loadappcodedir[lg;base,string procname]]; } @@ -222,7 +235,7 @@ initpermissions:{[config;deps] / permissions cascade. The rules are code (a paramcheck is a lambda), so they cannot be settings. / Loaded with `system "l"` at root, like loadappcodedir, so a rule file is an ordinary caller. permissionroots:{[] - (reqenv[`TORQXHOME],"/di/torq/permissions";reqenv[`TORQXAPPCONFIG],"/permissions") + (frameworkhome[],"/di/torq/permissions";reqenv[`TORQXAPPCONFIG],"/permissions") } loadpermissionrules:{[lg;config;proctype;procname] @@ -281,7 +294,7 @@ initquerylog:{[config;deps] ft:"j"$opt[`flushtime;86400]; if[ft>0; .z.m.qlflushtime:ft*0D00:00:01; - (deps[`timer][`addjob])[`querylogflush;flushquerylog;();"j"$opt[`flushinterval;1800];1h;()!()]]; + (deps[`timer][`addjob])[`querylogflush;flushquerylog;();0D00:00:01*"j"$opt[`flushinterval;1800];3h;()!()]]; msg:"query logging on (level ",(string cfg`level),", memory=",(string cfg`logtomemory),", disk=",(string cfg`logtodisk),")"; deps[`log][`info][`torq;msg," - di.querylog wraps .z.* directly; see torq.md Query logging"]; } @@ -299,13 +312,16 @@ initzpsignore:{[config] / 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. -reservedflags:`proctype`procname`torqxstackid`p`norun; +reservedflags:`proctype`procname`parentproctype`torqxstackid`p`norun; / the config-override params from a parsed command-line opt dict (.Q.opt .z.x): drop the reserved / flags, keep the rest. di.torq.config.overrideconfig then applies each to the matching setting / (parsed into its type) and skips any that don't name a real setting. Pure - unit-testable without .z.x. clioverrideparams:{[cmdlineopts] (key[cmdlineopts] except reservedflags)#cmdlineopts} +/ q's own -t in ms, null if not given; q consumes -t, so it is read from the full command line .z.X +cmdlinet:{[] $[`t in key o:.Q.opt .z.X;"J"$first o`t;0N]} + init:{[proctype;procname;overrides] / dependency check runs first, before anything else - a version mismatch should / be caught before identity resolution, config, or any module load even starts. @@ -326,23 +342,28 @@ init:{[proctype;procname;overrides] (dc`checkversiongraph)[enlist builtin proctype]; (dc`checkversiongraphfile)[proctype;reqenv[`TORQXAPPHOME],"/code/processes/",(string proctype),".deps.toml"]]; r:roots[]; + / -parentproctype, as torq.q:376-380: a symbol atom, null if not given + parentproctype:$[`parentproctype in key o:.Q.opt .z.x;first `$o`parentproctype;`]; / the logger is built before config so di.torq.config's command-line override layer (below) can log through it logdep:buildlogdep[overrides]; cc:use`di.torq.config; (cc`init)[enlist[`log]!enlist logdep]; / segmentedchainedtp uses segmentedtp's settings settingsproctype:$[proctype=`segmentedchainedtp;`segmentedtp;proctype]; - config:(cc`cascade)[r 0;r 1;settingsproctype;procname]; + if[not null parentproctype;logdep[`info][`init;"read in process parameter of parentproctype=",string parentproctype]]; + config:(cc`cascade)[r 0;r 1;parentproctype;settingsproctype;procname]; / command-line override layer - the TOP cascade tier. A launch flag matching a settings name / overrides it (parsed into that setting's type); reserved launcher/identity flags are excluded, / and a flag that doesn't name a real setting is skipped (see di.torq.config.overrideconfig). config:(cc`overrideconfig)[config; clioverrideparams .Q.opt .z.x]; / self-identity is resolved by di.torq and authoritative - stamped AFTER overrides so it always wins - config:config,`proctype`procname!(proctype;procname); + config:config,`proctype`procname`parentproctype!(proctype;procname;parentproctype); / the process.csv phone-book path, so di.torq.servers (and any consumer building its own startup config / slice from this config) can dial peers without reading env itself - keeps di.servers' env-free boundary. config:config,enlist[`processcsv]!enlist reqenv[`TORQXAPPCONFIG],"/process.csv"; - timerdep:buildtimerdep[overrides]; + / the process -t interval in ms, null if not given + config:config,enlist[`timerms]!enlist cmdlinet[]; + timerdep:buildtimerdep[overrides;logdep]; handlersdep:buildhandlersdep[overrides;logdep]; / servers is built LAST (it consumes log/timer/handlers at init) and injected alongside / them, so consumers read deps`servers instead of `use`+init-ing di.torq.servers themselves.