diff --git a/di/clienttracking/clienttracking.md b/di/clienttracking/clienttracking.md index ca5ed538..45df3f10 100644 --- a/di/clienttracking/clienttracking.md +++ b/di/clienttracking/clienttracking.md @@ -8,36 +8,34 @@ queries they sent, how many failed and how many bytes they were sent. | Name | What | |---|---| | `.clients.clients` | session table, keyed on `w`: `ipa u a k K c s o f pid port startp endp lastp hits errs sz` | -| `.clients.po[result;W]` / `.clients.wo[result;W]` | record a new connection / websocket | -| `.clients.pc[result;W]` | mark a closed connection: `w` becomes null, `endp` is set | -| `.clients.hit[x]` / `.clients.hite[x]` | count a query and its result bytes / count a failed query, then re-signal | -| `.clients.cleanup[]` | mark dead handles, close idle ones (`MAXIDLE`), purge old closed rows (`RETAIN`) | -| `.clients.addw[w]` | record handle `w` by hand | -| `.clients.unregistered[]` | see below | -| `.dotz.ipa` / `.dotz.liveh` / `.dotz.livehn` | host name lookup and live-handle checks, defined if absent | +| `.dotz.liveh` / `.dotz.livehn` / `.dotz.liveh0` | live-handle checks, defined if absent (di.torq.servers defines them too) | + +Everything else is module-private: `po`/`wo` record a new connection/websocket, `pc` marks a closed one +(`w` null, `endp` set), `hit`/`hite` count a query and its result bytes / a failed query, `cleanup` marks +dead handles, closes idle ones and purges old closed rows, `addw[w]` records a handle by hand. ## Settings -A `clients` section of the process config, set onto `.clients.`: +Required in `config`; `di/torq/settings/default.q` declares them all: | Key | Default | Meaning | |---|---|---| -| `enabled` | `1b` | track connections | -| `opencloseonly` | `0b` | track connections but not queries | -| `INTRUSIVE` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | -| `AUTOCLEAN` | `1b` | not read | -| `RETAIN` | `` `long$0D02 `` | nanoseconds to keep a closed row | -| `MAXIDLE` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | +| `clientsenabled` | `1b` | track connections | +| `clientsopencloseonly` | `0b` | track connections but not queries | +| `clientsintrusive` | `0b` | ask each new kdb+ client for `k K c s o f pid port`; don't use with non-kdb+ clients | +| `clientsautoclean` | `1b` | not read | +| `clientsretain` | `` `long$0D02 `` | nanoseconds to keep a closed row | +| `clientsmaxidle` | `` `long$0D `` | nanoseconds of idleness before a handle is closed; 0 means never | ## init[config;deps] Requires `handlers` (`di.torq.handlers`). It: -1. applies the `clients` section; -2. registers `.clients.pc` on `.z.pc`, whether or not `enabled`; -3. when `enabled`, registers `.clients.po` on `.z.po`, `.clients.wo` on `.z.wo` and `.clients.pc` on `.z.wc`; -4. when `enabled` and not `opencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through - `di.torq.handlers`) with `{.clients.hit[@[x;y;.clients.hite]]}` around the current handler. +1. signals if any setting is missing, then applies them; +2. registers `pc` on `.z.pc`, whether or not `enabled`; +3. when `clientsenabled`, registers `po` on `.z.po`, `wo` on `.z.wo` and `pc` on `.z.wc`; +4. when `clientsenabled` and not `clientsopencloseonly`, wraps `.z.pg`, `.z.ps` and `.z.ws` directly (not through + `di.torq.handlers`) with `{hit[@[x;y;hite]]}` around the current handler. An unset `.z.pg`/`.z.ps` is taken as `value`, and an unset `.z.ws` as an echo. Call `init` once: a second call wraps the query handlers again. An exec owner registered on those @@ -48,9 +46,9 @@ events through `di.torq.handlers` afterwards replaces the wrap. - `hits`, `errs` and `sz` count async (`.z.ps`) and websocket (`.z.ws`) messages too, including the bytes of results that are never sent back. - A closed row keeps its key with `w` set to null, so several closed rows share a null key. -- A handle closed by the `MAXIDLE` sweep still has a null `endp`, so the same sweep drops its row +- A handle closed by the `clientsmaxidle` sweep still has a null `endp`, so the same sweep drops its row instead of marking it. -- `.clients.unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. +- The private `unregistered[]` reads a `CLIENTS` table that doesn't exist, and fails. - `hits` and `errs` are ints. ## Testing @@ -60,7 +58,8 @@ k4unit:use`di.k4unit k4unit.moduletest`di.clienttracking ``` -`test.q`/`test.csv` start four server peers (defaults, `opencloseonly`, disabled, and `INTRUSIVE` -with a one-second `MAXIDLE` and `RETAIN`) and connect to them. The tests cover the table and -defaults, connection rows, hits, bytes and errors, closing and `addw`, websocket rows, both -settings modes, the `INTRUSIVE` reply, idle closing and the `RETAIN` purge. +`test.q`/`test.csv` start four server peers, each configured from the settings file plus overrides +(defaults, `clientsopencloseonly`, disabled, and `clientsintrusive` with a one-second `clientsmaxidle` +and `clientsretain`), and connect to them. The tests cover the settings, the table, the init checks, +the stored settings, connection rows, hits, bytes and errors, closing and `addw`, websocket rows, both +settings modes, the intrusive reply, idle closing and the retain purge. diff --git a/di/clienttracking/clienttracking.q b/di/clienttracking/clienttracking.q index a406a72a..76047c2d 100644 --- a/di/clienttracking/clienttracking.q +++ b/di/clienttracking/clienttracking.q @@ -2,55 +2,50 @@ init:{[config;deps] if[not `handlers in key deps;'"di.clienttracking: handlers dependency is required - see di.torq.handlers"]; - {[s;k] set[` sv `.clients,k;s k]}[s] each key s:$[`clients in key config;config`clients;()!()]; + / all settings required + req:`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean`clientsretain`clientsmaxidle; + if[count m:req except key config;'"di.clienttracking: missing settings: ",", " sv string m]; + .z.m.enabled:config`clientsenabled; + .z.m.opencloseonly:config`clientsopencloseonly; + .z.m.intrusive:config`clientsintrusive; + .z.m.autoclean:config`clientsautoclean; + .z.m.retain:config`clientsretain; + .z.m.maxidle:config`clientsmaxidle; r:deps[`handlers]`register; - r[`.z.pc;`;`clients;0j;.clients.pc[::;]]; - if[.clients.enabled; - r[`.z.po;`;`clients;0j;.clients.po[::;]]; - r[`.z.wo;`;`clients;0j;.clients.wo[::;]]; - r[`.z.wc;`;`clients;0j;.clients.pc[::;]]; - if[not .clients.opencloseonly; - set[`.z.pg;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.pg;{.:}]]; - set[`.z.ps;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.ps;{.:}]]; - set[`.z.ws;{.clients.hit[@[x;y;.clients.hite]]}@[value;`.z.ws;{{neg[.z.w]x;}}]]]]; + r[`.z.pc;`;`clients;0j;pc[::;]]; + if[enabled; + r[`.z.po;`;`clients;0j;po[::;]]; + r[`.z.wo;`;`clients;0j;wo[::;]]; + r[`.z.wc;`;`clients;0j;pc[::;]]; + if[not opencloseonly; + set[`.z.pg;{hit[@[x;y;hite]]}@[value;`.z.pg;{.:}]]; + set[`.z.ps;{hit[@[x;y;hite]]}@[value;`.z.ps;{.:}]]; + set[`.z.ws;{hit[@[x;y;hite]]}@[value;`.z.ws;{{neg[.z.w]x;}}]]]]; } -\d .dotz - -if[not `IPA in key `.dotz; - IPA:(.z.a,.Q.addr`localhost)!.z.h,`localhost; - ipa:{$[`~r:IPA x;IPA[x]:$[`~r:.Q.host x;`$"."sv string"i"$0x0 vs x;r];r]}]; +IPA:(.z.a,.Q.addr`localhost)!.z.h,`localhost; +ipa:{$[`~r:IPA x;.z.m.IPA[x]:$[`~r:.Q.host x;`$"."sv string"i"$0x0 vs x;r];r]}; +livehx:{y in x,key .z.W}; +/ live-handle checks, shared with di.torq.servers if[not `liveh in key `.dotz; - livehx:{y in x,key .z.W}; liveh:livehx(); livehn:livehx 0Ni; liveh0:livehx 0i]; - -\d .clients - -/ settings -enabled:1b -opencloseonly:0b -INTRUSIVE:0b -AUTOCLEAN:1b -RETAIN:`long$0D02 -MAXIDLE:`long$0D + .dotz.liveh:livehx(); .dotz.livehn:livehx 0Ni; .dotz.liveh0:livehx 0i]; -enabled:@[value;`enabled;1b] -opencloseonly:@[value;`opencloseonly;0b] - -clients:@[value;`clients;([w:`int$()]ipa:`symbol$();u:`symbol$();a:`int$();k:`date$();K:`float$();c:`int$();s:`int$();o:`symbol$();f:`symbol$();pid:`int$();port:`int$();startp:`timestamp$();endp:`timestamp$();lastp:`timestamp$();hits:`int$();errs:`int$();sz:`long$())] +/ root: queried remotely +.clients.clients:@[value;`.clients.clients;([w:`int$()]ipa:`symbol$();u:`symbol$();a:`int$();k:`date$();K:`float$();c:`int$();s:`int$();o:`symbol$();f:`symbol$();pid:`int$();port:`int$();startp:`timestamp$();endp:`timestamp$();lastp:`timestamp$();hits:`int$();errs:`int$();sz:`long$())]; unregistered:{except[key .z.W;exec w from`CLIENTS]} cleanup:{ if[count w0:exec w from`.clients.clients where not .dotz.livehn w; update endp:.z.p,w:0Ni from`.clients.clients where w in w0]; - if[.clients.MAXIDLE>0; - hclose each exec w from`.clients.clients where .dotz.liveh w,lastp<.z.p-.clients.MAXIDLE]; - delete from`.clients.clients where not .dotz.liveh w,endp<.z.p-.clients.RETAIN;} + if[maxidle>0; + hclose each exec w from`.clients.clients where .dotz.liveh w,lastp<.z.p-.z.m.maxidle]; + delete from`.clients.clients where not .dotz.liveh w,endp<.z.p-.z.m.retain;} hit:{update lastp:.z.p,hits:hits+1i,sz:sz+-22!x from`.clients.clients where w=.z.w;x} hite:{update lastp:.z.p,hits:hits+1i,errs:errs+1i from`.clients.clients where w=.z.w;'x} po:{[result;W] cleanup[]; - `.clients.clients upsert(W;.dotz.ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); - if[INTRUSIVE; + `.clients.clients upsert(W;ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); + if[intrusive; neg[W]"neg[.z.w]\"update k:\",(string .z.k),\",K:\",(-3!.z.K),\",c:\",(-3!.z.c),\",s:\",(-3!system\"s\"),\",o:\",(-3!.z.o),\",f:\",(-3!.z.f),\",pid:\",(-3!.z.i),\",port:\",(-3!system\"p\"),\" from`.clients.clients where w=.z.w\""]; result} addw:{po[x;x]} @@ -58,7 +53,5 @@ pc:{[result;W] update w:0Ni,endp:.z.p from`.clients.clients where w=W;cleanup[]; wo:{[result;W] cleanup[]; - `.clients.clients upsert(W;.dotz.ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); + `.clients.clients upsert(W;ipa .z.a;.z.u;.z.a;0Nd;0n;0Ni;0Ni;(`);(`);0Ni;0Ni;zp;0Np;zp:.z.p;0i;0i;0j); result} - -\d . diff --git a/di/clienttracking/test.csv b/di/clienttracking/test.csv index 6e697b2c..fa77aa94 100644 --- a/di/clienttracking/test.csv +++ b/di/clienttracking/test.csv @@ -4,12 +4,14 @@ before,0,0,q,system "l di/clienttracking/test.q",1,,load fixture helpers before,0,0,q,setupfixture[],1,,start the server peers comment,,,,,,,settings and table -true,0,0,q,"(1b;0b;0b;1b)~.clients`enabled`opencloseonly`INTRUSIVE`AUTOCLEAN",1,,boolean defaults -true,0,0,q,"(`long$0D02;0)~.clients`RETAIN`MAXIDLE",1,,RETAIN two hours and MAXIDLE off +run,0,0,q,"S:(use`di.torq.config)[`parsefile] SETTINGS",1,,read the settings file +true,0,0,q,"(1b;0b;0b;1b)~S`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean",1,,boolean defaults +true,0,0,q,"(`long$0D02;0)~S`clientsretain`clientsmaxidle",1,,retain two hours and maxidle off true,0,0,q,"(enlist`w)~keys .clients.clients",1,,table keyed on w true,0,0,q,"`ipa`u`a`k`K`c`s`o`f`pid`port`startp`endp`lastp`hits`errs`sz~cols value .clients.clients",1,,table columns true,0,0,q,"""iij""~exec t from meta .clients.clients where c in `hits`errs`sz",1,,hits and errs int; sz long fail,0,0,q,"ct.init[()!();()!()]",1,,init without handlers must error +fail,0,0,q,"ct.init[()!();enlist[`handlers]!enlist()!()]",1,,init without settings must error comment,,,,,,,connection lifecycle run,0,0,q,ha:peer PORTS`a,1,,connect to the default peer @@ -17,6 +19,7 @@ true,0,0,q,"1=ha""count select from .clients.clients where w=.z.w""",1,,a connec true,0,0,q,"(.z.u;`localhost;`int$.Q.addr`localhost)~(mine[ha;""u""];mine[ha;""ipa""];mine[ha;""a""])",1,,row records user and address true,0,0,q,"(mine[ha;""startp""]<=mine[ha;""lastp""]) and null mine[ha;""endp""]",1,,startp and lastp set; endp null while open true,0,0,q,"ha""all {`clients in exec name from h.list x} each `.z.po`.z.pc`.z.wo`.z.wc""",1,,open and close observers registered +true,0,0,q,"(S`clientsenabled`clientsopencloseonly`clientsintrusive`clientsautoclean`clientsretain`clientsmaxidle)~ha"".m.di.0clienttracking`enabled`opencloseonly`intrusive`autoclean`retain`maxidle""",1,,init stores the settings comment,,,,,,,usage run,0,0,q,"n0:mine[ha;""hits""]; ha""1+1""; n1:mine[ha;""hits""]",1,,two sync queries @@ -31,10 +34,10 @@ comment,,,,,,,close and manual add run,0,0,q,"c0:ha""count select from .clients.clients where null w,not null endp""; hclose ha; hb:peer PORTS`a",1,,close and reconnect true,0,0,q,"(c0+1)=hb""count select from .clients.clients where null w,not null endp""",1,,a close nulls w and sets endp true,0,0,q,"1=hb""count select from .clients.clients where w=.z.w""",1,,the new connection has its own row -true,0,0,q,"0i=hb"".clients.addw .z.w; exec first hits from .clients.clients where w=.z.w""",1,,addw records the handle afresh -fail,0,0,q,"hb"".clients.unregistered[]""",1,,unregistered reads a CLIENTS table that does not exist -true,0,0,q,"hb"".clients.wo[::;999i]; 1=count select from .clients.clients where w=999i""",1,,a websocket open adds a row -true,0,0,q,"hb"".clients.pc[::;999i]; 0=count select from .clients.clients where w=999i""",1,,a websocket close nulls w +true,0,0,q,"0i=hb"".m.di.0clienttracking.addw .z.w; exec first hits from .clients.clients where w=.z.w""",1,,addw records the handle afresh +fail,0,0,q,"hb"".m.di.0clienttracking.unregistered[]""",1,,unregistered reads a CLIENTS table that does not exist +true,0,0,q,"hb"".m.di.0clienttracking.wo[::;999i]; 1=count select from .clients.clients where w=999i""",1,,a websocket open adds a row +true,0,0,q,"hb"".m.di.0clienttracking.pc[::;999i]; 0=count select from .clients.clients where w=999i""",1,,a websocket close nulls w comment,,,,,,,opencloseonly run,0,0,q,"hbb:peer PORTS`b; hbb""1+1""; hbb""1+1""",1,,connect and query the opencloseonly peer @@ -46,12 +49,12 @@ run,0,0,q,hc:peer PORTS`c,1,,connect to the disabled peer true,0,0,q,"0=hc""count .clients.clients""",1,,connections are not recorded true,0,0,q,"hc""(`clients in exec name from h.list`.z.pc) and not `clients in exec name from h.list`.z.po""",1,,.z.pc is still wired when disabled -comment,,,,,,,INTRUSIVE and settings section +comment,,,,,,,intrusive and settings overrides run,0,0,q,"hd:peer PORTS`d; hd""1""; hd""1""",1,,connect to the INTRUSIVE peer and let the reply arrive true,0,0,q,"(.z.i;.z.k;system""p"")~(mine[hd;""pid""];mine[hd;""k""];mine[hd;""port""])",1,,the client reported its pid and version and port -true,0,0,q,"(`long$0D00:00:01)~hd"".clients.MAXIDLE""",1,,a clients section overrides the defaults +true,0,0,q,"(`long$0D00:00:01)~hd"".m.di.0clienttracking.maxidle""",1,,settings override the defaults -comment,,,,,,,MAXIDLE and RETAIN +comment,,,,,,,maxidle and retain run,0,0,q,"hd2:peer PORTS`d; system ""sleep 1.5""; hd3:peer PORTS`d",1,,leave two connections idle past MAXIDLE then connect again true,0,0,q,"`closed~@[hd2;""1"";{`closed}]",1,,an idle connection is closed true,0,0,q,"1=hd3""count .clients.clients""",1,,closed idle connections and expired rows are dropped diff --git a/di/clienttracking/test.q b/di/clienttracking/test.q index dd2f56b6..ba9f7a13 100644 --- a/di/clienttracking/test.q +++ b/di/clienttracking/test.q @@ -8,7 +8,10 @@ peer:{[p] hopen `$":localhost:",string p} PORTS:`a`b`c`d!4#0N / a: defaults; b: opencloseonly; c: disabled; d: INTRUSIVE with a 1s MAXIDLE and RETAIN -CFGS:`a`b`c`d!("()!()";"enlist[`opencloseonly]!enlist 1b";"enlist[`enabled]!enlist 0b";"`INTRUSIVE`MAXIDLE`RETAIN!(1b;`long$0D00:00:01;`long$0D00:00:01)") +CFGS:`a`b`c`d!("()!()";"enlist[`clientsopencloseonly]!enlist 1b";"enlist[`clientsenabled]!enlist 0b";"`clientsintrusive`clientsmaxidle`clientsretain!(1b;`long$0D00:00:01;`long$0D00:00:01)") + +/ the settings file, the base of every peer's config +SETTINGS:"di/torq/settings/default.q" setupfixture:{[] system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; @@ -16,7 +19,7 @@ setupfixture:{[] "h:use`di.torq.handlers"; "h.init enlist[`log]!enlist `info`warn`error!3#{[c;m]}"; "ct:use`di.clienttracking"; - "ct.init[enlist[`clients]!enlist ",c,";enlist[`handlers]!enlist `register`remove`list#h]")}'[key CFGS;value CFGS]; + "ct.init[((use`di.torq.config)[`parsefile] \"",SETTINGS,"\"),",c,";enlist[`handlers]!enlist `register`remove`list#h]")}'[key CFGS;value CFGS]; p:40000+(`int$.z.i mod 20000)+til 500; p:p where isfree each p; PORTS::key[PORTS]!4#p; {system QBIN," ",FIXDIR,"/",string[x],".q -p ",(string y)," -q /dev/null 2>&1 &"}'[key PORTS;value PORTS]; diff --git a/di/dbwrite/VERSION b/di/dbwrite/VERSION index 6e8bf73a..0ea3a944 100644 --- a/di/dbwrite/VERSION +++ b/di/dbwrite/VERSION @@ -1 +1 @@ -0.1.0 +0.2.0 diff --git a/di/dbwrite/dbwrite.md b/di/dbwrite/dbwrite.md index 1b0b4916..037087c4 100644 --- a/di/dbwrite/dbwrite.md +++ b/di/dbwrite/dbwrite.md @@ -69,6 +69,7 @@ default,,time,1 | `savedown[dir;part;tabname;data]` | Write an in-memory table to an HDB partition, sort it, then run gc | | `appenddown[dir;part;tabname;data]` | Append rows to an existing partition (no sort) | | `applyattr[dloc;colname;att]` | Apply a single kdb+ attribute to an on-disk column | +| `gc[]` | Run `.Q.gc[]` and log memory stats before and after | --- @@ -207,5 +208,5 @@ The suite injects binary mock loggers (`{[c;m] ...}`): a no-op logger, and a cap ## Exported symbols ```q -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc]) ``` diff --git a/di/dbwrite/init.q b/di/dbwrite/init.q index dcea6c10..115c2160 100644 --- a/di/dbwrite/init.q +++ b/di/dbwrite/init.q @@ -8,4 +8,4 @@ / BOTH the file (pre-load manifest walk) and this export (post-load session audit). version:first read0`:::VERSION -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;version]) +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;gc;version]) diff --git a/di/dbwrite/test.csv b/di/dbwrite/test.csv index f6df53fa..a61af3c1 100644 --- a/di/dbwrite/test.csv +++ b/di/dbwrite/test.csv @@ -190,6 +190,11 @@ true,0,0,q,"any caplog[`msg] like ""*read 3 sort config*""",1,1,readcsv logs the true,0,0,q,all not null (select from caplog where fn=`info)[`ctx],1,1,readcsv logs are tagged with a context symbol true,0,0,q,not any caplog[`fn]=`error,1,1,readcsv logs no errors on success +comment,,,,,,,log call verification - gc +run,0,0,q,caplog:0#caplog,1,1,reset log capture +run,0,0,q,dbwrite.gc[],1,1,gc runs +true,0,0,q,2=count select from caplog where ctx=`gc,1,1,gc logs before and after + comment,,,,,,,log call verification - readcsv error logging on file read failure run,0,0,q,caplog:0#caplog,1,1,reset log capture run,0,0,q,@[dbwrite.readcsv;`:nonexistent_file.csv;{x}],1,1,trigger file read error diff --git a/di/merge/VERSION b/di/merge/VERSION index 6c6aa7cb..341cf11f 100644 --- a/di/merge/VERSION +++ b/di/merge/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 \ No newline at end of file diff --git a/di/merge/init.q b/di/merge/init.q index 89aaff43..6fb02598 100644 --- a/di/merge/init.q +++ b/di/merge/init.q @@ -18,4 +18,5 @@ if[0=count version;'"di.merge: VERSION file is empty"]; / public api - only the functions intended to be called externally are exported export:([init;checkpartitiontype;checkenumerabletype;getextrapartitions;getfirstcharpartitions; getpartchunks;mergebypart;mergebycol;mergehybrid;trackpartition;clearpartsizes; - getpartsizes;syncpartsizes;version;getapimeta]) + getpartsizes;syncpartsizes;getmergebybytelimit;getpartlimit;getextrapartitiontype; + version;getapimeta]) diff --git a/di/merge/merge.md b/di/merge/merge.md index 8ff328f6..2165b655 100644 --- a/di/merge/merge.md +++ b/di/merge/merge.md @@ -11,7 +11,7 @@ On-disk data-merging utilities for the write-down flow, extracted from TorQ's `c - Sync a partsizes table received from a peer process into local tracked state (`syncpartsizes`) - see "Cross-process partition-size sync" below - Re-sort a segment by its parted column(s) when the `p#` attribute cannot otherwise be applied, so the merged partition ends up correctly parted - Batch sizing bounded by both a data limit (rows or bytes, per `mergebybytelimit`) and a maximum partition count per batch (`partlimit`) -- Helpers to validate and enumerate a table's parted columns (`checkpartitiontype`, `checkenumerabletype`, `getextrapartitions`, `getfirstcharpartitions`) +- Helpers to validate and enumerate a table's parted columns (`checkpartitiontype`, `checkenumerabletype`, `getextrapartitions`, `getfirstcharpartitions`, `getextrapartitiontype`) - No hard module dependencies - logging is injected via `init`, and the parted column(s) a merge needs are passed in by the caller rather than read from sort config, so `di.merge` stays independent of `di.sort` --- @@ -24,7 +24,7 @@ On-disk data-merging utilities for the write-down flow, extracted from TorQ's `c **Hard dependency:** none - the only runtime dependency (`log`) is injected via `init`, so any module exporting the contracted signatures can be supplied. -The parted (`` `p# ``) column(s) for a table - `extrapartitiontype` in the function signatures below - are **passed in by the caller**. TorQ's original `merge.q` read these from the `.sort.params` global (populated from `sort.csv`); on extraction that coupling was removed so `di.merge` does not depend on `di.sort`. The caller (e.g. `di.wdb`) obtains the parted columns from its own sort configuration and passes them to `mergebypart` / `mergehybrid` / the check functions. +The parted (`` `p# ``) column(s) for a table - `extrapartitiontype` in the function signatures below - are **passed in by the caller**. TorQ's original `merge.q` read these from the `.sort.params` global (populated from `sort.csv`); on extraction that coupling was removed so `di.merge` does not depend on `di.sort`. The caller (e.g. `di.wdb`) obtains the parted columns from its own sort configuration and passes them to `mergebypart` / `mergehybrid` / the check functions. `getextrapartitiontype` looks them up in a sort config the caller passes in. **`tablename` must resolve as a real global/root table.** `checkpartitiontype`, `checkenumerabletype`, `getextrapartitions` and `getfirstcharpartitions` all take `tablename` and dereference it directly - `checkpartitiontype` via `cols get tablename`, the other three via `meta[tablename]` or a functional select (`` ?[tablename;...] ``). None of them accept an in-memory table value in place of a resolvable symbol; this matches legacy TorQ's own behaviour and is not a limitation introduced by this module. @@ -79,6 +79,9 @@ merge.trackpartition[`:tmp/2025.01.01/trade; count data; -22!data] ### `getpartsizes[]` Return the current tracked segment sizes (keyed on `ptdir`), e.g. to sync to sort-worker processes. +### `getmergebybytelimit[]` / `getpartlimit[]` +Return the `mergebybytelimit` and `partlimit` this module was initialised with. + ### `clearpartsizes[]` Drop all tracked segment sizes. Call once end-of-day merging is complete. @@ -118,6 +121,12 @@ Return the distinct combinations of the parted column values - one per partition ### `getfirstcharpartitions[tablename;extrapartitiontype]` Return the partition values grouped by the first character of the (single) parted column. +### `getextrapartitiontype[sortconfig;tablename]` +Return the parted (`p#`) column(s) for `tablename` from `sortconfig` (a sort table with `tabname`, `column`, `sort` and `att` columns, e.g. di.dbwrite's `getconfig[]`): the table's own sorted `p#` columns, else those of the `default` row. Error-logs when neither is defined. +```q +merge.getextrapartitiontype[dbw.getconfig[]; `trade] +``` + ### `version` Module version string (from the `VERSION` file), for `di.depcheck` to check against dependants' minimum-version requirements. @@ -284,7 +293,7 @@ Mock loggers only check that a message was logged at the right level - they do n ## Notes -- Extracted from TorQ `code/common/merge.q`. The one behavioural change on extraction is the removal of the `.sort.params`/`sort.csv` lookup (`getextrapartitiontype`): the parted column(s) are now a parameter (`extrapartitiontype`) supplied by the caller, keeping the module standalone. All error/info messages that referenced `sort.csv` in the legacy source have been reworded accordingly. +- Extracted from TorQ `code/common/merge.q`. The one behavioural change on extraction is the removal of the `.sort.params`/`sort.csv` lookup (`getextrapartitiontype`): the parted column(s) are now a parameter (`extrapartitiontype`) supplied by the caller, and `getextrapartitiontype` takes the sort config as a parameter, keeping the module standalone. The other error/info messages that referenced `sort.csv` in the legacy source have been reworded accordingly. - `init` must be called before any other function - enforced by the `requireinit` guard on every other exported function, not just documented convention. - The `VERSION`-file read pattern (fail loud on missing/unreadable/empty, `trim` against trailing whitespace) follows `di.servers`, not `di.eodtime` (which has no `VERSION` handling at all). - The merge functions operate on on-disk paths (`get`/`set`/`upsert` against file symbols); they do not manage the segment or destination directory lifecycle - that remains the caller's responsibility. diff --git a/di/merge/merge.q b/di/merge/merge.q index adaf734e..519c4181 100644 --- a/di/merge/merge.q +++ b/di/merge/merge.q @@ -5,8 +5,7 @@ / per partition by a row-count / byte-size limit / merging keeps memory flat - segments are read and upserted a batch at a time rather / than held in memory and written once at end-of-day -/ the parted (`p#) column(s) for a table are supplied by the caller as extrapartitiontype; -/ the module never reads sort config itself, so it stays independent of di.sort +/ p# columns come from the caller, or from a sort config it passes in; never read here / config and the injected log dependency are passed to init in a single dictionary: config / keys (see merge.md) are optional with defaults; log is required and init errors / immediately if it is missing or does not provide info/error - see merge.md @@ -89,6 +88,17 @@ getpartsizes:{[] .z.m.partsizes }; +/ the configured mergebybytelimit and partlimit +getmergebybytelimit:{[] + requireinit[`getmergebybytelimit]; + .z.m.mergebybytelimit + }; + +getpartlimit:{[] + requireinit[`getpartlimit]; + .z.m.partlimit + }; + / upsert a partsizes-shaped table received from a peer process into local tracked state syncpartsizes:{[t] / t: a table shaped like getpartsizes[] (ptdir/rowcount/bytes), typically received over IPC @@ -253,6 +263,20 @@ getfirstcharpartitions:{[tablename;extrapartitiontype] group ?[tablename;();();({first each string x};(distinct;first extrapartitiontype))] }; +/ a table's p# columns from a sort config, else the default's +getextrapartitiontype:{[sortconfig;tablename] + requireinit[`getextrapartitiontype]; + tabparts:$[count tabparts:distinct exec column from sortconfig where tabname=tablename,sort=1,att=`p; + [.z.m.loginfo[`getextraparttype;"parted attribute p found in sort.csv for ",(string tablename)," table"]; + tabparts]; + count defaultparts:distinct exec column from sortconfig where tabname=`default,sort=1,att=`p; + [.z.m.loginfo[`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table, using default instead"]; + defaultparts]; + [.z.m.logerr[`getextraparttype;"parted attribute p not found in sort.csv for ",(string tablename)," table and default not defined"]] + ]; + tabparts + }; + / ============================================================ / initialisation / ============================================================ @@ -323,6 +347,11 @@ getapimeta:{[] "[symbol: ptdir; long: rowcount; long: bytes]";"null"); (`clearpartsizes;1b;"drop all tracked segment sizes";"[]";"null"); (`getpartsizes; 1b;"current tracked segment sizes";"[]";"table: ptdir/rowcount/bytes"); + (`getmergebybytelimit;1b;"the configured mergebybytelimit";"[]";"boolean"); + (`getpartlimit;1b;"the configured partlimit";"[]";"long"); + (`getextrapartitiontype; + 1b;"the parted column(s) for a table from a sort config, else the default's"; + "[table: sortconfig; symbol: tablename]";"symbol list: parted columns"); (`syncpartsizes; 1b;"upsert a partsizes table received from a peer process into local tracked state"; "[table: t]";"null"); diff --git a/di/merge/test.csv b/di/merge/test.csv index 4bf32797..afa116a9 100644 --- a/di/merge/test.csv +++ b/di/merge/test.csv @@ -24,6 +24,9 @@ fail,0,0,q,merge.checkpartitiontype[`t;enlist`sym],1,1,checkpartitiontype reject fail,0,0,q,merge.checkenumerabletype[`t;enlist`sym],1,1,checkenumerabletype rejected before init fail,0,0,q,merge.getextrapartitions[`t;enlist`sym],1,1,getextrapartitions rejected before init fail,0,0,q,merge.getfirstcharpartitions[`t;enlist`sym],1,1,getfirstcharpartitions rejected before init +fail,0,0,q,merge.getmergebybytelimit[],1,1,getmergebybytelimit rejected before init +fail,0,0,q,merge.getpartlimit[],1,1,getpartlimit rejected before init +fail,0,0,q,"merge.getextrapartitiontype[([]tabname:`$();column:`$();sort:`boolean$();att:`$());`t]",1,1,getextrapartitiontype rejected before init true,0,0,q,".[merge.trackpartition;(`:g1;1;1);{x}]~""di.merge: trackpartition: init must be called before any other function""",1,1,requireinit error message names the function and is precise comment,,,,,,,init - dependency injection validation (log is required with info and error keys) @@ -36,6 +39,7 @@ fail,0,0,q,merge.init[enlist[`log]!enlist(enlist[`info]!enlist mylog`info)],1,1, fail,0,0,q,merge.init[enlist[`log]!enlist(enlist[`error]!enlist mylog`error)],1,1,init rejects a log dict missing the info level true,0,0,q,"(8#@[merge.init;(::);{x}])~""di.merge""",1,1,error message is prefixed di.merge run,0,0,q,merge.init[enlist[`log]!enlist mylog],1,1,init with a valid minimal (info+error only) log dep +true,0,0,q,(0b;1000)~(merge.getmergebybytelimit[];merge.getpartlimit[]),1,1,mergebybytelimit and partlimit default to 0b and 1000 comment,,,,,,,version and getapimeta true,0,0,q,`version in key merge,1,1,version is still an export - di.depcheck reads it there @@ -95,6 +99,7 @@ run,0,0,q,merge.trackpartition[`:b1;1;100],1,1,track b1 with a small row count b run,0,0,q,merge.trackpartition[`:b2;1;100],1,1,track b2 run,0,0,q,merge.trackpartition[`:b3;1;100],1,1,track b3 true,0,0,q,merge.getpartchunks[`:b1`:b2`:b3;250]~(`:b1`:b2;enlist`:b3),1,1,batching uses bytes not row count (row count alone would fit all three) +true,0,0,q,merge.getmergebybytelimit[],1,1,getmergebybytelimit returns the configured value run,0,0,q,merge.init[enlist[`log]!enlist mylog],1,1,restore row-count batching (default) comment,,,,,,,getpartchunks splits a batch that exceeds partlimit partitions @@ -256,6 +261,15 @@ comment,,,,,,,getfirstcharpartitions groups partition values by first character run,0,0,q,fctbl:([]sym:`aa`ab`ba`bb`ac;px:1 2 3 4 5),1,1,table with symbol values sharing first characters true,0,0,q,merge.getfirstcharpartitions[`fctbl;enlist`sym]~(`aa`ab`ac;`ba`bb),1,1,values grouped by first character not by full value +comment,,,,,,,getextrapartitiontype reads the p# columns from the sort config passed in +run,0,0,q,"sc:([]tabname:`trade`trade`default;column:`sym`time`sym;sort:101b;att:`p``p)",1,1,sort config: trade parted on sym; default parted on sym +true,0,0,q,(enlist`sym)~merge.getextrapartitiontype[sc;`trade],1,1,the table's own p# column +true,0,0,q,(enlist`sym)~merge.getextrapartitiontype[sc;`quote],1,1,a table not in the config falls back to the default +run,0,0,q,merge.init[enlist[`log]!enlist logcap],1,1,init with the capturing logger +run,0,0,q,caplog:0#caplog,1,1,reset the capture +run,0,0,q,merge.getextrapartitiontype[delete from sc where tabname=`default;`quote],1,1,no table entry and no default +true,0,0,q,"any (exec msg from caplog where fn=`error) like ""*default not defined*""",1,1,is error-logged + comment,,,,,,,parted-column checks route through the injected logger and no longer reference sort.csv run,0,0,q,merge.init[enlist[`log]!enlist logcap],1,1,init with the capturing logger run,0,0,q,qtbl:([]a:1 2;b:3 4;f:1.0 2.0),1,1,table with long and float columns diff --git a/di/os/VERSION b/di/os/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/os/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/os/init.q b/di/os/init.q index 65fd437a..0f28d521 100644 --- a/di/os/init.q +++ b/di/os/init.q @@ -166,4 +166,6 @@ setdrysyscalls:{[on] cleardrysyscalls[] +version:first read0`:::VERSION + export:`syscall`drysyscall _ .z.m diff --git a/di/os/os.md b/di/os/os.md index 66e93852..b10b9cd5 100644 --- a/di/os/os.md +++ b/di/os/os.md @@ -6,6 +6,8 @@ Designed to work on both **Linux/Unix** and **Windows**, functions automatically **All functions that accept path arguments can accept string or hsym paths.** +`version` holds the module version, read from its `VERSION` file. + --- ## :desktop_computer: OS Detection diff --git a/di/os/test.csv b/di/os/test.csv index c41bf302..017c83bd 100644 --- a/di/os/test.csv +++ b/di/os/test.csv @@ -2,6 +2,7 @@ action,ms,bytes,lang,code,repeat,minver,comment before,0,0,q,os:use`di.os,1,,Initialize module before,0,0,q,"system ""l "", os.abspath[""di/os/test.q""]",1,1,load additional testing functions / dependencies true,0,0,q,-1h=type .m.di.0os.iswindows,1,1, +true,0,0,q,os.version~first read0`:di/os/VERSION,1,1,version read from the VERSION file run,0,0,q,k4unit.mock[`.m.di.0os.iswindows;0b],1,1, true,0,0,q,enlist["path"]~distinct os.topath each .testos.pathvars"path",1,1, diff --git a/di/pubsub/VERSION b/di/pubsub/VERSION index 0ea3a944..1d0ba9ea 100644 --- a/di/pubsub/VERSION +++ b/di/pubsub/VERSION @@ -1 +1 @@ -0.2.0 +0.4.0 diff --git a/di/pubsub/pubsub.md b/di/pubsub/pubsub.md index 7fc5f6d8..1cc0a7b4 100644 --- a/di/pubsub/pubsub.md +++ b/di/pubsub/pubsub.md @@ -49,8 +49,8 @@ publish data with/without filters. The function takes two arguments: t and x, wh | Function | Description | |---------------------------|------------------------------------------------------------------------------| | `pubsub.setsubtables` | Set a specified list of tables that are available for subscription. | -| `pubsub.callendofday` | Broadcast an end-of-day event to all subscribers (requires `endofday`). | -| `pubsub.callendofperiod` | Broadcast an end-of-period event to all subscribers (requires `endofperiod`).| +| `pubsub.callendofday` | Broadcast end of day to all subscribers as `.u.end[d]`. | +| `pubsub.callendofperiod` | Broadcast end of period to all subscribers as `endofperiod[currp;nextp;data]`.| | `pubsub.closesub` | Remove handle upon connection close. Not bound to `.z.pc` by the module - the consumer binds it (see Notes). | | `pubsub.subclear` | Publish tables and clear up the contents. | | `pubsub.init` | Initialize variables - run before calling pub/sub functions to populate required state (e.g., tables/schemas). Takes a deps dict with a required `log`. | @@ -87,11 +87,17 @@ q)pubsub.subscribestrfilter["quote";"bid>50.0";"time,sym,bid"] ## `.stpps`, `.u.sub`, `.ps` -A second pub/sub API at root, in a `\d .stpps` section at the end of `pubsub.q`, with its own state, -separate from the API above: `.stpps.t`/`subrequestall`/`subrequestfiltered`, `.stpps.allsubhandles`, -`suball`/`subfiltered`/`add`/`errparse`/`addfiltered`/`selfiltered`/`pub`, -`delhandle`/`delhandlef`/`closesub`/`extractschema`/`init`, root `.u.sub`, and -`.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`. +A second pub/sub API at root, with its own state, separate from the API above: `.stpps.t`/`subrequestall`/ +`schemas`/`tabcols`, `.stpps.endp`/`end`/`allsubhandles`/`pub`/`pubclear`/`closesub`/`attrstrip`/`init`, +root `.u.sub`/`.u.pub`, `.ps.loaded`/`publish`/`subscribe`/`init`/`initialise`/`subtable`/`subtablefiltered`, +and `.ds.map`/`subreq`/`stripe`. Its filtered-subscription registry `subrequestfiltered`, +`schemasnoattributes` and the helpers `stpsuball`/`stpsubfiltered`/`stpadd`/`errparse`/`stpaddfiltered`/ +`selfiltered`/`stpdelhandle`/`stpdelhandlef`/`stpextractschema` are module-private. + +- `endp[cur;next;data]` and `end[date;data]` send `(`endofperiod;cur;next;data)` and `(`endofday;date;data)` to + every subscriber. +- `pubclear[tabs]` publishes the tables and resets them to `schemasnoattributes`, which `attrstrip` sets. +- `.ds.stripe` needs `.ds.numseg` set. - `.stpps` logs its errors through the `log` passed to `init`. - The consumer registers `.stpps.closesub` on `.z.pc` through its handlers dependency. diff --git a/di/pubsub/pubsub.q b/di/pubsub/pubsub.q index 16b1f328..daba39f9 100644 --- a/di/pubsub/pubsub.q +++ b/di/pubsub/pubsub.q @@ -74,11 +74,11 @@ closesub:{[h] delete from .z.M.reqfilteredtbl where handle=h; }; -/ broadcast to all subscribers upon end of day, client needs to define endofday function -callendofday:{[d](neg getallhandles[])@\:(`endofday;d)}; +/ broadcast end of day to all subscribers as .u.end[d] +callendofday:{[d](neg getallhandles[])@\:(`.u.end;d)}; / broadcast to all subscribers upon end of period, client needs to define endofperiod function -callendofperiod:{(neg getallhandles[])@\:(`endofperiod;x)}; +callendofperiod:{[currp;nextp;data] (neg getallhandles[])@\:(`endofperiod;currp;nextp;data)}; / get table schema extractschema:{[table]0#value table}; @@ -131,94 +131,136 @@ init:{[deps] if[count tabcols;.z.m.initialized:1b]; }; -/ .stpps, .u.sub, .ps -\d .stpps +/ root, for segmentedtp and chainedtp: the stp pub/sub tables and subscribers +.stpps.t:`; +.stpps.subrequestall:enlist[`]!enlist (); +subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()); -t:` -subrequestall:enlist[`]!enlist () -subrequestfiltered:([]tbl:`$();handle:`int$();filts:();columns:()) +.stpps.endp:{ + (neg .stpps.allsubhandles[])@\:(`endofperiod;x;y;z); + }; + +.stpps.end:{ + (neg .stpps.allsubhandles[])@\:(`endofday;x;y); + }; -allsubhandles:{ - distinct raze union/[value subrequestall;exec handle from .stpps.subrequestfiltered] +.stpps.allsubhandles:{ + distinct raze union/[value .stpps.subrequestall;exec handle from .z.m.subrequestfiltered] }; -suball:{ - delhandle[x;.z.w]; - add[x]; - :(x;schemas[x]); +stpsuball:{ + stpdelhandle[x;.z.w]; + stpadd[x]; + :(x;.stpps.schemas[x]); }; -subfiltered:{[x;y] - delhandlef[x;.z.w]; - val:![11 99h;(selfiltered;addfiltered)][type y] . (x;y); - $[all raze null val;(x;schemas[x]);val] +stpsubfiltered:{[x;y] + stpdelhandlef[x;.z.w]; + val:![11 99h;(selfiltered;stpaddfiltered)][type y] . (x;y); + $[all raze null val;(x;.stpps.schemas[x]);val] }; -add:{ - if[not (count subrequestall x)>i:subrequestall[x]?.z.w; - subrequestall[x],:.z.w]; +stpadd:{ + if[not (count .stpps.subrequestall x)>i:.stpps.subrequestall[x]?.z.w; + .stpps.subrequestall[x],:.z.w]; }; errparse:{.z.m.log[`error][`addfiltered;m:y," error: ",x];'m}; -addfiltered:{[x;y] - filters:$[all null f:y[x;`filters];();@[parse;"select from t where ",f;.stpps.errparse[;"Filter"]] 2]; - columns:last $[all null c:y[x;`columns];();@[parse;"select ",c," from t";.stpps.errparse[;"Column"]]]; - @[eval;(?;.stpps.schemas[x];filters;0b;columns);.stpps.errparse[;"Query"]]; - `.stpps.subrequestfiltered upsert (x;.z.w;filters;columns); +stpaddfiltered:{[x;y] + filters:$[all null f:y[x;`filters];();@[parse;"select from t where ",f;errparse[;"Filter"]] 2]; + columns:last $[all null c:y[x;`columns];();@[parse;"select ",c," from t";errparse[;"Column"]]]; + @[eval;(?;.stpps.schemas[x];filters;0b;columns);errparse[;"Query"]]; + .z.m.subrequestfiltered:.z.m.subrequestfiltered upsert (x;.z.w;filters;columns); }; selfiltered:{[x;y] filts:enlist enlist (in;`sym;enlist y); - @[eval;(?;.stpps.schemas[x];filts;0b;());.stpps.errparse[;"Query"]]; - `.stpps.subrequestfiltered upsert (x;.z.w;filts;()); + @[eval;(?;.stpps.schemas[x];filts;0b;());errparse[;"Query"]]; + .z.m.subrequestfiltered:.z.m.subrequestfiltered upsert (x;.z.w;filts;()); }; -pub:{[t;x] +.stpps.pub:{[t;x] if[not count x;:()]; - if[count h:subrequestall[t];-25!(h;(`upd;t;x))]; - if[t in .stpps.subrequestfiltered`tbl; + if[count h:.stpps.subrequestall[t];-25!(h;(`upd;t;x))]; + if[t in .z.m.subrequestfiltered`tbl; {[t;x;sels] data:eval(?;x;sels`filts;0b;sels`columns); if[count data;neg[sels`handle](`upd;t;data)]}[t;x;] - each select handle,filts,columns from .stpps.subrequestfiltered where tbl=t + each select handle,filts,columns from .z.m.subrequestfiltered where tbl=t ]; }; -delhandle:{[t;h] +.stpps.pubclear:{ + .stpps.pub'[x;value each x,:()]; + @[`.;x;:;schemasnoattributes[x]]; + } + +stpdelhandle:{[t;h] @[`.stpps.subrequestall;t;except;h]; }; -delhandlef:{[t;h] - delete from `.stpps.subrequestfiltered where tbl=t,handle=h; +stpdelhandlef:{[t;h] + .z.m.subrequestfiltered:delete from .z.m.subrequestfiltered where tbl=t,handle=h; }; -closesub:{[h] - delhandle[;h]each t; - delhandlef[;h]each t; +.stpps.closesub:{[h] + stpdelhandle[;h]each .stpps.t; + stpdelhandlef[;h]each .stpps.t; }; -extractschema:{t:value x; $[.Q.qp t; t; 0#t]}; +stpextractschema:{t:value x; $[.Q.qp t; t; 0#t]}; + +.stpps.attrstrip:{[t] + {@[x;cols x;`#]} each .stpps.t:t; + .z.m.schemasnoattributes:.stpps.t!stpextractschema each .stpps.t; + }; -init:{[t] +.stpps.init:{[t] if[count b:t where not t in tables[];{.z.m.log[`error][`psinit;m:"Table ",string[x]," does not exist"];'m} each b]; .stpps.t:t except b; - .stpps.schemas:.stpps.t!extractschema each .stpps.t; + .stpps.schemas:.stpps.t!stpextractschema each .stpps.t; .stpps.tabcols:.stpps.t!cols each .stpps.t; }; -\d . - +/ root: the subscribe/publish entry points .u.sub:{[x;y] if[x~`;:.z.s[;y] each .stpps.t]; if[not x in .stpps.t; .z.m.log[`error][`sub;m:"Table ",string[x]," not in list of stp pub/sub tables"]; :(x;m) ]; - $[y~`;.stpps.suball[x];.stpps.subfiltered[x;y]] + $[y~`;stpsuball[x];stpsubfiltered[x;y]] }; +.u.pub:.stpps.pub + .ps.loaded:1b; .ps.publish:.stpps.pub; .ps.subscribe:.u.sub; .ps.init:.stpps.init; .ps.initialise:{.ps.init[tables[]];.ps.initialised:1b}; + +.ps.subtable:{[tab;syms] + .z.m.log[`info][`subtable;"Received a subscription to ",$[count tab;tab;"all tables"]," for ",$[count syms;syms;"all syms"]]; + val:.u.sub[`$tab;$[count syms;::;first] `$csv vs syms]; + $[10h~type last val;'last val;val] + }; + +.ps.subtablefiltered:{[tab;filters;columns] + .z.m.log[`info][`subtablefiltered;"Received a subscription to ",$[count tab;tab;"all tables"]," for filters: ",filters," and columns: ",columns]; + val:.u.sub[`$tab;1!enlist `tabname`filters`columns!(`$tab;filters;columns)]; + $[10h~type last val;'last val;val] + }; + +.ds.map:{[numseg;sym] sym!(sum each string sym)mod numseg}; + +.ds.subreq:(`u#`$())!`int$(); + +.ds.stripe:{[input;skey] + if[0=count input;:`boolean$()]; + if[0N in val:.ds.subreq input; + .ds.subreq,:.ds.map[.ds.numseg;distinct input where null val]; + val:.ds.subreq input; + ]; + skey=val + }; diff --git a/di/pubsub/test.csv b/di/pubsub/test.csv index e5aa98ff..4f7b23cb 100644 --- a/di/pubsub/test.csv +++ b/di/pubsub/test.csv @@ -133,12 +133,13 @@ run,0,0,q,"r:h(`.u.sub;`nosuch;`)",1,,subscribe to a table that is not published true,0,0,q,`nosuch~first r,1,,.u.sub returns the table name true,0,0,q,"(`sub;""Table nosuch not in list of stp pub/sub tables"")~h""lastlog""",1,,and logs the error through the injected log run,0,0,q,"r:h(`.u.sub;`quote;enlist`IBM)",1,,sym-filtered subscription (a sym list) -true,0,0,q,"clt in h""exec handle from .stpps.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered +true,0,0,q,"clt in h""exec handle from .m.di.0pubsub.subrequestfiltered where tbl=`quote""",1,,client registered in subrequestfiltered true,0,0,q,"clt in h"".stpps.allsubhandles[]""",1,,allsubhandles includes the client run,0,0,q,"h(`.stpps.closesub;clt)",1,,closesub for the client handle true,0,0,q,"not clt in h"".stpps.allsubhandles[]""",1,,client removed from both registries true,0,0,q,"""Table nosuchtable does not exist""~h""@[.stpps.init;enlist`nosuchtable;{x}]""",1,,init signals on a missing table true,0,0,q,"(`psinit;""Table nosuchtable does not exist"")~h""lastlog""",1,,and logs it through the injected log +true,0,0,q,"`currp`nextp`data~h""(value pubsub.callendofperiod)1""",1,,callendofperiod takes the three endofperiod arguments run,0,0,q,neg[h](exit;0);neg[h](::),1,,close background process and flush run,0,0,q,hclose h,1,,close handle diff --git a/di/subscriptions/subscriptions.md b/di/subscriptions/subscriptions.md index 95142638..74863a5b 100644 --- a/di/subscriptions/subscriptions.md +++ b/di/subscriptions/subscriptions.md @@ -17,7 +17,7 @@ classic standard-TP `.u.i`/`.u.L`/`.u.d` global reads. | Function | Description | |---|---| -| `init[config;deps]` | validate the deps, stash `log`, load di.tplogmgr, apply the `.sub` settings, register `.sub.pc` and the `checksubscriptions` job (once) | +| `init[config;deps]` | validate the deps, stash `log`, load di.tplogmgr, signal if a setting is missing, apply the settings, register `pc` and the `checksubscriptions` job (once) | | `subscribe[tph;tabs;syms;replay]` | subscribe over an open TP handle; returns the subdetails dict | | `subscribed[]` | `1b` if any subscription is active | | `getsubscriptions[]` | the active-subscriptions registry table | @@ -55,15 +55,16 @@ in di.tplogmgr's module context) lands in the module's *private* namespace, not ## `.sub` -A second subscription API at root `.sub`, in a `\d .sub` section at the end of `subscriptions.q`, with -its own state: `AUTORECONNECT`, `checksubscriptionperiod`, `SUBSCRIPTIONS`, `getsubscriptionhandles`, -`updatesubscriptions`, `reconnectinit`, `reducesubs`, `createtables`, `replay`, `subscribe`, -`replayupd`, `checksubscriptions`, `retrysubscription`, `autoreconnect`, `pc`. `subscribe` asks the +A second subscription API at root: `.sub.subscribe[tabs;instrs;setschema;replaylog;proc]`, +`.sub.getsubscriptionhandles[proctype;procname;attributes]` and its registry `.sub.SUBSCRIPTIONS`. It is +built on the module-private `updatesubscriptions`, `reconnectinit`, `reducesubs`, `createtables`, `replay`, +`replayupd`, `checksubscriptions`, `retrysubscription`, `resubscribe` and `pc`. `.sub.subscribe` asks the publisher for its `tptype` (`standard`, `chained` or `segmented`) and subscribes to match. It calls `.servers.getservers`, `.servers.enabled` and `.servers.connectcustom` from `di.torq.servers` 0.5.0. -- Settings (flat config): `autoreconnect` (default `0b`), `checksubscriptionperiod` (default `0D00:00:10`). -- `init` registers, once per process: `.sub.pc[::;]` on `.z.pc` through `handlers`, and +- Settings, both required; `di/torq/settings/default.q` declares them: `autoreconnect` (`0b`), + `checksubscriptionperiod` (`0D00:00:10`). +- `init` registers, once per process: `pc[::;]` on `.z.pc` through `handlers`, and `checksubscriptions` every `checksubscriptionperiod` (converted to seconds, timer mode 1) through `timer` when the period is above 0. diff --git a/di/subscriptions/subscriptions.q b/di/subscriptions/subscriptions.q index 30d15561..8d1e2092 100644 --- a/di/subscriptions/subscriptions.q +++ b/di/subscriptions/subscriptions.q @@ -22,12 +22,13 @@ init:{[config;deps] if[not `handlers in key deps;'"di.subscriptions: handlers dependency is required - see di.torq.handlers"]; .z.m.log:deps`log; .z.m.tp:use`di.tplogmgr; / for replayupto (repair-aware, count-limited -11!) - / .sub settings - if[`autoreconnect in key config;.sub.AUTORECONNECT:config`autoreconnect]; - if[`checksubscriptionperiod in key config;.sub.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod]; + / all settings required + if[count m:`autoreconnect`checksubscriptionperiod except key config;'"di.subscriptions: missing settings: ",", " sv string m]; + .z.m.autoreconnect:config`autoreconnect; + .z.m.checksubscriptionperiod:(not @[value;`.proc.lowpowermode;0b])*config`checksubscriptionperiod; if[not .z.m.registered; - (deps[`handlers]`register)[`.z.pc;`;`sub;0j;.sub.pc[::;]]; - if[.sub.checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;.sub.checksubscriptions;();`long$.sub.checksubscriptionperiod%0D00:00:01;1;()!()]]; + (deps[`handlers]`register)[`.z.pc;`;`sub;0j;pc[::;]]; + if[checksubscriptionperiod>0;(deps[`timer]`addjob)[`checksubscriptions;checksubscriptions;();`long$checksubscriptionperiod%0D00:00:01;1;()!()]]; .z.m.registered:1b]; } @@ -88,15 +89,10 @@ subscribed:{[] 01{print $4}' "$CSVPATH" } +startwithall() { + # $1 = procname -> false if its optional startwithall column is 0 + [ "$(getfield "$(findprocno "$1")" startwithall)" != "0" ] +} + findproc() { # $1 = proctype, $2 = procname -> prints matching pid(s), if any. # The token after -procname must be a SPACE or END-OF-LINE, not just a space: a @@ -274,7 +279,10 @@ foreachtarget() { # $1 = fn, $2 = target ("" or "all" means every row), remaining args passed through local fn="$1"; local target="$2"; shift 2 if [ -z "$target" ] || [ "$target" = "all" ]; then - for p in $(allprocnames); do "$fn" "$p" "$@"; done + for p in $(allprocnames); do + [ "$fn" = start_one ] && ! startwithall "$p" && continue + "$fn" "$p" "$@" + done else "$fn" "$target" "$@" fi @@ -283,7 +291,8 @@ foreachtarget() { usage() { cat >&2 < .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | | `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | -| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. Returns the **updated config dict**. Requires `init`. | +| `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. A `.section.key` (or `section.key`) name overrides that key of a dict-valued section, e.g. `-.clients.opencloseonly 0`, under the same rules; the key must already be in the section. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | | `getapimeta` | `getapimeta[]` | This module's API metadata — one `(name;public;descrip;params;return)` row per exported function, for `di.torq` to register with `di.api`. | -Internal helpers — `parsetier` (per-tier `.q`+`.toml` merge), `applyoverride`, +Internal helpers — `parsetier` (per-tier `.q`+`.toml` merge), `applyoverride`, `settingpath`, `parsefailed`, and `hexchars` — are deliberately not exported. ## Injectable dependencies diff --git a/di/torq/config/config.q b/di/torq/config/config.q index 9222f54b..89c7569b 100644 --- a/di/torq/config/config.q +++ b/di/torq/config/config.q @@ -153,16 +153,27 @@ overrideconfig:{[config;params] 'err; ]; ]; - defined:vars where vars in key config; - undefined:vars except defined; + paths:settingpath[config] each vars; + undefined:vars where 0=count each paths; if[count undefined; .z.m.logwarn[`overrideconfig;"skipping unknown setting(s): ",", " sv string undefined]; ]; - / fold each defined override into the config dict; a skipped/rejected one leaves it unchanged - :{[config;params;name] - res:applyoverride[name;config name;params name]; - $[res 0;@[config;name;:;res 1];config] - }[;params;]/[config;defined]; + / fold each override into the config dict at its path; a skipped/rejected one leaves it unchanged + w:where 0/_`; `logdir` may be a path string | -| `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms | +| `subscribeto` / `subscribesyms` | `` ` `` / `` ` `` — all tables, all syms; also strings, `""` for all | | `replay` / `schema` | `0b` / `1b` | | `connections` / `startup` | `` `tickerplant `` / `1b` | ## init[config;deps] Requires `log`, `timer` and `handlers`. It initialises `di.pubsub` (with the log) and -`di.subscriptions`, registers `.stpps.closesub` on `.z.pc`, applies the settings, then: +`di.subscriptions`, registers `.stpps.closesub` on `.z.pc`, applies the settings (signalling if any is +missing), then: 1. registers a `.z.pc` observer that logs and exits 0 when the upstream handle closes; -2. sets `.ctp.upd` from `createlogfile`/`pubinterval`, and root `upd` if absent; +2. sets `upd` from `createlogfile`/`pubinterval`, and root `upd` if absent; 3. `.ps.initialise[]`; 4. `.servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]`; -5. `.ctp.subscribe[]`: finds the upstream handle, `refreshtp`, subscribes through `di.subscriptions`, takes - `.u.d` from the reply; -6. builds `.ctp.tableschemas`; +5. `subscribe[]`; +6. builds `tableschemas`; 7. when `pubinterval` is above 0, adds the `publishalltables` job (seconds, timer mode 2). di.torq runs `.ps.initialise[]` again after the module loads, which publishes the subscribed tables. @@ -51,14 +54,15 @@ di.torq runs `.ps.initialise[]` again after the module loads, which publishes th - The upstream is found by procname through `di.torq.servers` (with the default settings, through discovery). With `tpcheckcycles` `0W` it waits for it indefinitely. -- End of day follows the rdb/wdb convention: `endofday[d]` in, `` (`endofday;d) `` out. +- An upstream that sends `endofday` rather than `.u.end` (a segmented tickerplant) does not end the day here. +- `.u.icounts` values are one-item lists after an all-syms subscribe. - A corrupt own log is reported and opened anyway. - `pubinterval` must be a whole number of seconds (the timer runs in seconds); anything else fails `init`. ## Downstream subscribers -`.u.subdetails[tabs;syms]` subscribes the caller through `.ctp.sub`, the protocol `di.subscriptions` -subscribers (di rdb/wdb) use. With `createlogfile` on, `logfile` is `.u.L` and `rowcount` `.u.i`, so +`subdetails` serves `.sub` subscribers. `.u.subdetails[tabs;syms]` subscribes the caller through `sub` for +`di.subscriptions` `subscribe`. With `createlogfile` on, `logfile` is `.u.L` and `rowcount` `.u.i`, so subscribers replay chainedtp's own log; otherwise `` ` `` and 0. Plain `.u.sub` subscribers are served by `di.pubsub`. @@ -69,7 +73,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.chainedtp ``` -`test.q`/`test.csv` run a real upstream (di tickerplant surface, found through `di.torq.servers`) and +`test.q`/`test.csv` run a real upstream (segmented tickerplant surface, found through `di.torq.servers`) and real `.u.sub` and `di.subscriptions` subscribers: subscribe and schema, tick-by-tick delivery, -`.u.subdetails`, `tablelist`, end of day, the own log, batch publish, `clearlogonsubscription`, a +`subdetails`, `.u.subdetails`, `tablelist`, `.u.end`, the own log, batch publish, `clearlogonsubscription`, a corrupt log, and a subscriber replaying the own log. diff --git a/di/torq/proc/chainedtp/chainedtp.q b/di/torq/proc/chainedtp/chainedtp.q index 2103f6bc..d9bb8dd6 100644 --- a/di/torq/proc/chainedtp/chainedtp.q +++ b/di/torq/proc/chainedtp/chainedtp.q @@ -3,57 +3,61 @@ / a timespan, a "0D00:00:01" string or a number of seconds (TOML has no timespan type) totimespan:{[x] $[-16h=type x;x;10h=abs type x;"N"$(),x;-11h=type x;"N"$string x;type[x] in -5 -6 -7h;0D00:00:01*x;0Nn]}; +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; + init:{[config;deps] if[not `log in key deps;'"di.torq.proc.chainedtp: log dependency is required - see di.util.log"]; if[not `timer in key deps;'"di.torq.proc.chainedtp: timer dependency is required - see di.timer"]; if[not `handlers in key deps;'"di.torq.proc.chainedtp: handlers dependency is required - see di.torq.handlers"]; + / all settings required + req:`tickerplantname`pubinterval`tpconnsleep`createlogfile`logdir`subscribeto`subscribesyms`replay`schema`clearlogonsubscription`tpcheckcycles; + if[count m:req except key config;'"di.torq.proc.chainedtp: missing settings: ",", " sv string m]; .z.m.log:deps`log; .z.m.procname:config`procname; (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; (deps[`handlers]`register)[`.z.pc;`;`stpps;0j;.stpps.closesub]; (use`di.subscriptions)[`init][config;deps]; - {[config;k] if[k in key config;set[` sv `.ctp,k;config k]]}[config] each `tickerplantname`pubinterval`tpconnsleep`createlogfile`logdir`subscribeto`subscribesyms`replay`schema`clearlogonsubscription`tpcheckcycles; - .ctp.pubinterval:totimespan .ctp.pubinterval; - if[10h=type .ctp.logdir;.ctp.logdir:hsym`$.ctp.logdir]; - if[0<>(`long$.ctp.pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; - (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[.ctp.tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .ctp.tickerplantname];exit 0]}]; - .ctp.upd:$[.ctp.createlogfile; - $[.ctp.pubinterval;{[t;x] .ctp.writetolog[t;x];.ctp.batchpub[t;x];};{[t;x] .ctp.writetolog[t;x];.ctp.tickpub[t;x];}]; - $[.ctp.pubinterval;.ctp.batchpub;.ctp.tickpub]]; - if[not `upd in key `.;set[`upd;.ctp.upd]]; + .z.m.tickerplantname:tosym config`tickerplantname; + .z.m.pubinterval:totimespan config`pubinterval; + .z.m.tpconnsleep:config`tpconnsleep; + .z.m.createlogfile:config`createlogfile; + .z.m.logdir:$[10h=type l:config`logdir;hsym`$l;l]; + .z.m.subscribeto:tosym config`subscribeto; + .z.m.subscribesyms:tosym config`subscribesyms; + .z.m.replay:config`replay; + .z.m.schema:config`schema; + .z.m.clearlogonsubscription:config`clearlogonsubscription; + .z.m.tpcheckcycles:config`tpcheckcycles; + if[0<>(`long$pubinterval) mod 1000000000;'"di.torq.proc.chainedtp: pubinterval must be a whole number of seconds"]; + (deps[`handlers]`register)[`.z.pc;`;`chainedtp;0j;{[y] if[tph=y;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string tickerplantname];exit 0]}]; + .z.m.upd:$[createlogfile; + $[pubinterval;{[t;x] writetolog[t;x];batchpub[t;x];};{[t;x] writetolog[t;x];tickpub[t;x];}]; + $[pubinterval;batchpub;tickpub]]; + if[not `upd in key `.;set[`upd;upd]]; .ps.initialise[]; - .servers.startupdepnamecycles[.ctp.tickerplantname;.ctp.tpconnsleep;.ctp.tpcheckcycles]; - .ctp.subscribe[]; - .ctp.tableschemas:{x!(0#)@'value@'x} (),$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto]; - if[.ctp.pubinterval;(deps[`timer]`addjob)[`publishalltables;.ctp.publishalltables;();`long$.ctp.pubinterval%0D00:00:01;2;()!()]]; + .servers.startupdepnamecycles[tickerplantname;tpconnsleep;tpcheckcycles]; + subscribe[]; + .z.m.tableschemas:{x!(0#)@'value@'x} (),$[any null subscribeto;tables[`.];subscribeto]; + if[pubinterval;(deps[`timer]`addjob)[`publishalltables;publishalltables;();`long$pubinterval%0D00:00:01;2;()!()]]; } -\d . +/ root: the subscriber contract +@[`.;`tptype;:;`chained]; -tptype:`chained; +@[`.;`tablelist;:;{.stpps.t}]; -tablelist:{.stpps.t} +@[`.;`subdetails;:;{[tabs;instruments] + r:sub[tabs;instruments]; + `schemalist`logfilelist`rowcounts`date!r@/:(`schema;$[r[`logfile]~();();enlist`i`logfile];`icounts;`d) + }]; .u.subdetails:{[tabs;syms] - r:.ctp.sub[tabs;syms]; s:r`schema; + r:sub[tabs;syms]; s:r`schema; if[-11h=type first s;s:enlist s]; - `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[.ctp.createlogfile;r`logfile;`];$[.ctp.createlogfile;r`i;0];.u.d) + `tables`schemas`logfile`rowcount`date!(s[;0];s[;0]!s[;1];$[createlogfile;r`logfile;`];$[createlogfile;r`i;0];.u.d) } -\d .ctp - -tickerplantname:@[value;`tickerplantname;`tickerplant1]; -pubinterval:@[value;`pubinterval;0D00:00:00]; -tpconnsleep:@[value;`tpconnsleep;10]; -createlogfile:@[value;`createlogfile;0b]; -logdir:@[value;`logdir;`:tplogs]; -subscribeto:@[value;`subscribeto;`]; -subscribesyms:@[value;`subscribesyms;`]; -replay:@[value;`replay;0b]; -schema:@[value;`schema;1b]; -clearlogonsubscription:@[value;`clearlogonsubscription;0b]; -tpcheckcycles:@[value;`tpcheckcycles;0W]; - tph:0N; .u.icounts:.u.jcounts:(`symbol$())!0#0,(); .u.i:.u.j:0; @@ -82,14 +86,19 @@ openlog:{[lgfile] } subscribe:{[] - s:.sub.getsubscriptionhandles[`;.ctp.tickerplantname;()!()]; + s:.sub.getsubscriptionhandles[`;tickerplantname;()!()]; if[count s; - subproc:first s; - .ctp.tph:subproc`w; - refreshtp @[tph;".u.d";.z.D]; - .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; - r:(use`di.subscriptions)[`subscribe][tph;subscribeto;subscribesyms;replay]; - .u.d::r`date]; + subproc:first s; + .z.m.tph:subproc`w; + refreshtp @[tph;".u.d";.z.D]; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:.sub.subscribe[subscribeto;subscribesyms;schema;replay;subproc]; + if[`d in key r;.u.d::r[`d]]; + if[(`icounts in key r) & (not createlogfile); + subtabs:$[subscribeto~`;key r`icounts;subscribeto],(); + .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; + ] + ]; } writetolog:{[t;x] @@ -110,7 +119,7 @@ batchpub:{[t;x] } publishalltables:{[] - pubtables:$[any null .ctp.subscribeto;tables[`.];.ctp.subscribeto],(); + pubtables:$[any null subscribeto;tables[`.];subscribeto],(); .ps.publish'[pubtables;value each pubtables]; cleartables[pubtables]; .u.i:.u.j; @@ -124,7 +133,7 @@ cleartables:{[t] } createlogfilename:{[d] - ` sv (.ctp.logdir;`$string[.z.m.procname],"_",string d) + ` sv (logdir;`$string[procname],"_",string d) } refreshtp:{[d] @@ -140,7 +149,7 @@ refreshtp:{[d] } notpconnected:{[] - 0 = count select from .sub.SUBSCRIPTIONS where procname in .ctp.tickerplantname, active} + 0 = count select from .sub.SUBSCRIPTIONS where procname in .z.m.tickerplantname, active} sub:{[subtabs;subsyms] r:(`schema`icounts`i`logfile`d)!(); @@ -151,16 +160,10 @@ sub:{[subtabs;subsyms] r } -\d .u - -end:{[d] +/ root: the upstream ends the day +.u.end:{[d] .z.m.log[`info][`end;"end of day invoked"]; - .ctp.publishalltables[]; - .ctp.refreshtp[d+1]; - (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`endofday;d) + publishalltables[]; + refreshtp[d+1]; + (neg union[@[value;(`.stpps.allsubhandles;`);()]; @[{union/[(value x)[;;0]]};`.u.w;()]])@\:(`.u.end;d) } - -\d . - -endofday:{[d] .u.end d} - diff --git a/di/torq/proc/chainedtp/test.csv b/di/torq/proc/chainedtp/test.csv index 1b2cf237..66806a44 100644 --- a/di/torq/proc/chainedtp/test.csv +++ b/di/torq/proc/chainedtp/test.csv @@ -8,69 +8,73 @@ comment,,,,,,,init - dependencies fail,0,0,q,"ctp.init[cfg[];enlist[`log]!enlist mocklog]",1,,init without timer must error fail,0,0,q,"ctp.init[cfg[];`log`timer!(mocklog;mocktimer)]",1,,init without handlers must error fail,0,0,q,"ctp.init[cfg[];`timer`handlers!(mocktimer;mockhandlers)]",1,,init without log must error +fail,0,0,q,"ctp.init[`proctype`procname!(`chainedtp;`chainedtp1);deps[]]",1,,init without settings must error fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:00.500;deps[]]",1,,a sub-second pubinterval must error fail,0,0,q,"ctp.init[cfg[],enlist[`pubinterval]!enlist 0D00:00:01.500;deps[]]",1,,a fractional-second pubinterval must error comment,,,,,,,init - connect and subscribe -run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir!(""0D00:00:00"";""tplogs"");deps[]]",1,,init with toml-style pubinterval and logdir strings -true,0,0,q,0D~.ctp.pubinterval,1,,a pubinterval string becomes a timespan -true,0,0,q,`:tplogs~.ctp.logdir,1,,a logdir string becomes a file symbol -true,0,0,q,".ctp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle +run,0,0,q,"ctp.init[cfg[],`pubinterval`logdir`tickerplantname`subscribeto`subscribesyms!(""0D00:00:00"";""tplogs"";""tickerplant1"";"""";"""");deps[]]",1,,init with toml-style strings +true,0,0,q,"(`tickerplant1;`;`)~.m.di.0torq.0proc.0chainedtp.tickerplantname,.m.di.0torq.0proc.0chainedtp.subscribeto,.m.di.0torq.0proc.0chainedtp.subscribesyms",1,,symbol settings strings become symbols; empty means all +true,0,0,q,0D~.m.di.0torq.0proc.0chainedtp.pubinterval,1,,a pubinterval string becomes a timespan +true,0,0,q,`:tplogs~.m.di.0torq.0proc.0chainedtp.logdir,1,,a logdir string becomes a file symbol +true,0,0,q,".m.di.0torq.0proc.0chainedtp.tph=first exec w from .servers.SERVERS where procname=`tickerplant1",1,,tph is the upstream handle true,0,0,q,`trade in tables[],1,,upstream schema defined at root -true,0,0,q,.u.d~D,1,,date taken from the .u.subdetails reply -true,0,0,q,"1=count (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed through di.subscriptions +true,0,0,q,.u.d~D,1,,date taken from the upstream +true,0,0,q,"1=count select from .sub.SUBSCRIPTIONS where table=`trade,active",1,,subscribed to trade true,0,0,q,all `stpps`chainedtp`sub in exec name from handlercalls where event=`.z.pc,1,,.z.pc observers registered -true,0,0,q,`trade in key .ctp.tableschemas,1,,tableschemas holds trade +true,0,0,q,`trade in key .m.di.0torq.0proc.0chainedtp.tableschemas,1,,tableschemas holds trade true,0,0,q,not `publishalltables in exec id from timercalls,1,,no batch job at pubinterval 0 -true,0,0,q,upd~.ctp.tickpub,1,,root upd is tick-by-tick publish +true,0,0,q,upd~.m.di.0torq.0proc.0chainedtp.tickpub,1,,root upd is tick-by-tick publish run,0,0,q,.ps.initialise[],1,,.ps.initialise again after the process module loads (as di.torq does) true,0,0,q,`trade in .stpps.t,1,,trade is published -true,0,0,q,".ctp.tph~first exec handle from (use`di.subscriptions)[`getsubscriptions][]",1,,subscription is on the upstream handle -true,0,0,q,"`trade in first exec tabs from (use`di.subscriptions)[`getsubscriptions][]",1,,subscribed to trade comment,,,,,,,tick by tick run,0,0,q,"dh:hopen `$"":localhost:"",string DNPORT",1,,connect to the downstream peer run,0,0,q,"r:dh""(.z.w)(`.u.sub;`trade;`)""",1,,downstream subscribes to trade true,0,0,q,`trade~first r,1,,.u.sub returns the table true,0,0,q,"dh in .stpps.subrequestall`trade",1,,downstream registered -run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows -true,0,0,q,3=.u.icounts`trade,1,,icounts updated +run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 3)",1,,upstream publishes 3 rows +true,0,0,q,(enlist 3)~.u.icounts`trade,1,,icounts updated (one-item list as the subscribe reshape leaves it) true,0,0,q,"(1;3)~dh""(count got;count last last got)""",1,,downstream received the 3 rows +true,0,0,q,"`schemalist`logfilelist`rowcounts`date~key dh""(.z.w)(`subdetails;`trade;`)""",1,,subdetails keys +true,0,0,q,"()~(dh""(.z.w)(`subdetails;`trade;`)"")`logfilelist",1,,no log file without createlogfile true,0,0,q,"`tables`schemas`logfile`rowcount`date~key dh""(.z.w)(`.u.subdetails;`trade;`)""",1,,.u.subdetails keys true,0,0,q,"(`;0)~(dh""(.z.w)(`.u.subdetails;`trade;`)"")`logfile`rowcount",1,,no log and no replay without createlogfile true,0,0,q,"`trade in dh""(.z.w)(`tablelist;`)""",1,,tablelist lists trade comment,,,,,,,end of day -run,0,0,q,endofday D,1,,end of day through root endofday -true,0,0,q,"(enlist D)~dh""ended""",1,,endofday passed to the downstream +run,0,0,q,.u.end D,1,,end of day +true,0,0,q,"(enlist D)~dh""ended""",1,,.u.end passed to the downstream true,0,0,q,.u.d=D+1,1,,date rolled true,0,0,q,0=count trade,1,,trade cleared comment,,,,,,,own log and batch publish -run,0,0,q,".ctp.createlogfile:1b;.ctp.logdir:hsym`$FIXDIR;.ctp.refreshtp D",1,,create a log for D +run,0,0,q,".m.di.0torq.0proc.0chainedtp.createlogfile:1b;.m.di.0torq.0proc.0chainedtp.logdir:hsym`$FIXDIR;.m.di.0torq.0proc.0chainedtp.refreshtp D",1,,create a log for D true,0,0,q,".u.L~hsym`$FIXDIR,""/chainedtp1_"",string D",1,,log named /_ -run,0,0,q,.ctp.writetolog[`trade;rows 2],1,,write one message +run,0,0,q,.m.di.0torq.0proc.0chainedtp.writetolog[`trade;rows 2],1,,write one message true,0,0,q,"(1;1)~(.u.j;-11!(-2;.u.L))",1,,one message counted and on disk -run,0,0,q,.ctp.batchpub[`trade;rows 2],1,,batch 2 rows +run,0,0,q,.m.di.0torq.0proc.0chainedtp.batchpub[`trade;rows 2],1,,batch 2 rows true,0,0,q,2=count trade,1,,batched in the root table -run,0,0,q,.ctp.publishalltables[],1,,publish the batch +run,0,0,q,.m.di.0torq.0proc.0chainedtp.publishalltables[],1,,publish the batch true,0,0,q,"(2;2)~dh""(count got;count last last got)""",1,,downstream received the batch true,0,0,q,"(0;1)~(count trade;.u.i)",1,,trade cleared and .u.i caught up -run,0,0,q,.ctp.refreshtp D,1,,reopen the existing log +run,0,0,q,.m.di.0torq.0proc.0chainedtp.refreshtp D,1,,reopen the existing log true,0,0,q,1=.u.i,1,,existing messages counted -run,0,0,q,".ctp.clearlogonsubscription:1b;.ctp.refreshtp D",1,,reopen with clearlogonsubscription +run,0,0,q,".m.di.0torq.0proc.0chainedtp.clearlogonsubscription:1b;.m.di.0torq.0proc.0chainedtp.refreshtp D",1,,reopen with clearlogonsubscription true,0,0,q,0=.u.i,1,,log cleared +run,0,0,q,"r:subdetails[`trade;`]",1,,subdetails with a log +true,0,0,q,"(enlist(0;.u.L))~r`logfilelist",1,,logfilelist carries i and the log file run,0,0,q,"r:.u.subdetails[`trade;`]",1,,.u.subdetails with a log true,0,0,q,"(.u.L;.u.i)~r`logfile`rowcount",1,,logfile and rowcount are the own log and .u.i run,0,0,q,"bf:hsym`$FIXDIR,""/bad""; bf set (); lh:hopen bf; lh enlist(`upd;`trade;rows 1); hclose lh; bf 1: (read1 bf),0x0102030405",1,,write a log with one message and a bad tail -run,0,0,q,bh:.ctp.openlog bf,1,,open it +run,0,0,q,bh:.m.di.0torq.0proc.0chainedtp.openlog bf,1,,open it true,0,0,q,"errlogged""is corrupt""",1,,corruption reported true,0,0,q,-6h=type bh,1,,and the log opened anyway true,0,0,q,1=first .u.i,1,,.u.i holds the good-prefix count of 1 comment,,,,,,,di.subscriptions subscriber downstream run,0,0,q,.stpps.closesub 0i,1,,drop handle 0 left by the local .u.subdetails call -run,0,0,q,".ctp.refreshtp D;.ctp.writetolog[`trade;rows 3];.ctp.tickpub[`trade;rows 3]",1,,fresh log with one 3-row message before the peer subscribes +run,0,0,q,".m.di.0torq.0proc.0chainedtp.refreshtp D;.m.di.0torq.0proc.0chainedtp.writetolog[`trade;rows 3];.m.di.0torq.0proc.0chainedtp.tickpub[`trade;rows 3]",1,,fresh log with one 3-row message before the peer subscribes run,0,0,q,"sh:hopen `$"":localhost:"",string DSPORT",1,,connect to the di.subscriptions peer run,0,0,q,"sd:sh""subs.subscribe[.z.w;`trade;`;1b]""",1,,peer subscribes to trade through .u.subdetails true,0,0,q,(enlist`trade)~sd`tables,1,,tables is a symbol list for one table @@ -80,7 +84,7 @@ true,0,0,q,"(cols trade)~cols (sd`schemas)`trade",1,,schema for trade true,0,0,q,"sh""`trade in tables[]""",1,,trade defined at root on the peer true,0,0,q,"sh""1=count subs.getsubscriptions[]""",1,,peer recorded the subscription true,0,0,q,"sd2:sh""(.z.w)(`.u.subdetails;`;`)""; (11h=type sd2`tables) and `trade in sd2`tables",1,,tables is a symbol list for all tables -run,0,0,q,".ctp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows +run,0,0,q,".m.di.0torq.0proc.0chainedtp.tph({(neg .z.w)(`upd;`trade;x)};rows 2)",1,,upstream publishes 2 rows true,0,0,q,"(`trade;2)~sh""(first last got;count last last got)""",1,,peer received the rows after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/chainedtp/test.q b/di/torq/proc/chainedtp/test.q index 5557083a..57bf48d3 100644 --- a/di/torq/proc/chainedtp/test.q +++ b/di/torq/proc/chainedtp/test.q @@ -1,4 +1,4 @@ -/ test helpers: recording mocks, a real upstream (di tickerplant surface) and real downstream subscribers +/ test helpers: recording mocks, a real upstream (segmented tickerplant surface) and real downstream subscribers logrows:([]lvl:`symbol$();ctx:`symbol$();msg:()) mocklog:`info`warn`error!({[c;m]`logrows upsert(`info;c;m)};{[c;m]`logrows upsert(`warn;c;m)};{[c;m]`logrows upsert(`error;c;m)}) @@ -15,19 +15,21 @@ isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]} waitlisten:{[p] d:.z.p+0D00:00:03; while[(.z.p **No `deps.toml`.** `di.os` ships no `VERSION` file, and `di.torq.depcheck`'s manifest walk -> fails outright on a declared dependency it can't read a version for. Declaring `di.os` today -> would break every housekeeping start with a `DEPENDENCY CHECK FAILED … has no VERSION file`. -> Add the declaration once `di.os` carries a `VERSION`. + directory, and its dry-run mode makes a destructive action testable); declared in `deps.toml`. ## Config @@ -196,8 +191,6 @@ Roughly in the order they'd pay off: - **A run summary worth monitoring.** Counts and bytes reclaimed per job, kept as a table (like `di.compression`'s stats) so a dashboard or heartbeat can see that housekeeping is actually keeping up, rather than reading log lines. -- **`deps.toml` declaring `di.os`** — blocked purely on `di.os` shipping a `VERSION` file (see - Dependencies above). - **Windows.** The `.win` branch, if TorqX ever needs it. - **Malformed-header reporting.** `0:` pads a too-short header with invented names, so the error says `has columns wrong, header, entirely, x, x1, x2, x3`. Reporting the raw header line would diff --git a/di/torq/proc/housekeeping/housekeeping.q b/di/torq/proc/housekeeping/housekeeping.q index a600d0c3..e665f027 100644 --- a/di/torq/proc/housekeeping/housekeeping.q +++ b/di/torq/proc/housekeeping/housekeeping.q @@ -228,9 +228,7 @@ init:{[config;deps] / runtimes:02:00:00 in settings and a dead 12:00 in code - with its -hkusage text quoting 12:00. .z.m.runtimes:$[`runtimes in key config;astimespans config`runtimes;enlist 0D02:00:00]; / di.os for the rm action - it picks file vs directory, and its dry-run mode is what lets the - / tests assert on a destructive action without destroying anything. Deliberately NOT declared - / in a deps.toml: di.os ships no VERSION file, so declaring it would fail di.torq.depcheck's - / manifest walk outright (see housekeeping.md). Add the declaration once di.os carries one. + / tests assert on a destructive action without destroying anything .z.m.os:use`di.os; / publish the IPC-callable surface at a real root-level name - use-loading this file compiles / it into a private namespace (see di.torq.proc.hdb.init's identical note), so a remote or diff --git a/di/torq/proc/rdb/VERSION b/di/torq/proc/rdb/VERSION index 0d91a54c..1d0ba9ea 100644 --- a/di/torq/proc/rdb/VERSION +++ b/di/torq/proc/rdb/VERSION @@ -1 +1 @@ -0.3.0 +0.4.0 diff --git a/di/torq/proc/rdb/deps.toml b/di/torq/proc/rdb/deps.toml index 633b7f8d..2b008dbc 100644 --- a/di/torq/proc/rdb/deps.toml +++ b/di/torq/proc/rdb/deps.toml @@ -1,5 +1,5 @@ # Peer modules di.torq.proc.rdb `use`s (see di/torq/depcheck/depcheck.md for the manifest-graph mechanism). [dependencies] -"di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers) -"di.subscriptions" = "0.1.0" +"di.torq.servers" = "0.5.0" # requires the INJECTED-servers contract (deps`servers) +"di.subscriptions" = "0.2.0" "di.dbwrite" = "0.1.0" diff --git a/di/torq/proc/rdb/rdb.md b/di/torq/proc/rdb/rdb.md index db5a1c95..2fa77af8 100644 --- a/di/torq/proc/rdb/rdb.md +++ b/di/torq/proc/rdb/rdb.md @@ -49,8 +49,8 @@ di.subscriptions defines the tables at root from what the TP returns. - **Accumulate** (`upd`, published at root): a **root-namespace-safe** append — upserts a table payload (live) or a list-of-columns payload (replay) into the root table via `@[`.;t;…]`. Set at root **before** subscribing so replay drives it too. -- **End of day** (`endofday[date]`, published at root, also `.u.end`): the tickerplant - broadcasts `(`endofday;date)` at roll (see below). Behaviour depends on `reloadenabled`: +- **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#]`), then tells every connected HDB to `.hdb.reload[]`. @@ -84,11 +84,7 @@ probes for a wdb's existence (fail-fast / explicit-config, per the TorQ conventi The RDB's writedown is triggered **by the tickerplant**, not a local timer — so it saves exactly the day's data, only after the TP has sent its last message for the day. This -required a fix to di.pubsub (vendored into TorqX): `callendofday` now broadcasts -`(`endofday;date)` instead of a bare `` `endofday`` symbol. A bare async symbol is **not** -applied by a default `.z.ps` (it returns the function, doesn't call it) and carries no -partition date; the 2-list form is applied as `endofday[date]` (classic `.u.end` style). -Feed this fix upstream when di.pubsub is next touched. +uses di.pubsub's `callendofday`, which broadcasts `(`.u.end;date)`. ## Not included (future / other-process / deprecated) diff --git a/di/torq/proc/rdb/rdb.q b/di/torq/proc/rdb/rdb.q index 4cfa30ea..8fb3c2c4 100644 --- a/di/torq/proc/rdb/rdb.q +++ b/di/torq/proc/rdb/rdb.q @@ -53,7 +53,7 @@ notifyhdbs:{[] .z.m.log[`warn][`rdb;"no hdb connected to notify for reload"]]; } -/ end of day: called by the tickerplant as endofday[date] (di.pubsub's dated broadcast). +/ end of day for a date: .u.end[date] (tickerplant, chainedtp) or endofday[date;data] (segmented). / standalone mode: save every non-ignored root table to the HDB, clear it, reload the HDB(s). / wdb-fronted mode (reloadenabled=1b): the wdb owns the writedown - snapshot the per-table / row counts (so a later reload[] drops exactly the prior day) and escape, leaving the data @@ -131,11 +131,10 @@ init:{[config;deps] tpt:first .z.m.tptypes; if[not (.z.m.svc`waitfortype)[tpt;timeout;500]; '"di.torq.proc.rdb: no ",(string tpt)," connection within ",(string timeout),"ms - cannot start rdb"]; - tph:(.z.m.svc`gethandlebytype)[tpt;`any]; .z.m.subs:use`di.subscriptions; (.z.m.subs`init)[config;deps]; - sd:(.z.m.subs`subscribe)[tph;subscribeto;subscribesyms;replaylog]; - .z.m.log[`info][`rdb;"subscribed; replayed ",(string sd`rowcount)," message(s), partition date ",string sd`date]; + 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. @@ -143,10 +142,12 @@ init:{[config;deps] (.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 (the TP calls endofday[date]; .u.end is the alias). + / publish the EOD entry points at root. / reload[date] is the wdb's IPC entry point when reloadenabled (harmless if never called). - @[`.;`endofday;:;endofday]; - @[`.;`.u.end;:;endofday]; + set[`.u.end;endofday]; + / segmented tickerplant entry points + @[`.;`endofday;:;{[d;x] endofday d}]; + @[`.;`endofperiod;:;{[currp;nextp;data] .z.m.log[`info][`endofperiod;"Received endofperiod. currentperiod, nextperiod and data are ",(string currp),", ", (string nextp),", ", .Q.s1 data]}]; @[`.;`reload;:;reload]; .z.m.log[`info][`rdb;"initialised, hdbdir=",.z.m.hdbdir,", reloadenabled=",string .z.m.reloadenabled]; } diff --git a/di/torq/proc/segmentedtp/VERSION b/di/torq/proc/segmentedtp/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/torq/proc/segmentedtp/VERSION +++ b/di/torq/proc/segmentedtp/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/torq/proc/segmentedtp/deps.toml b/di/torq/proc/segmentedtp/deps.toml index 5e783dd7..2eb9276d 100644 --- a/di/torq/proc/segmentedtp/deps.toml +++ b/di/torq/proc/segmentedtp/deps.toml @@ -1,5 +1,7 @@ # Peer modules di.torq.proc.segmentedtp `use`s (see di/torq/depcheck/depcheck.md). [dependencies] -"di.pubsub" = "0.1.0" +"di.pubsub" = "0.3.0" "di.eodtime" = "0.1.0" -"di.tplogmgr" = "0.1.0" +"di.subscriptions" = "0.2.0" +"di.torq.servers" = "0.5.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/segmentedtp/init.q b/di/torq/proc/segmentedtp/init.q index 31796976..ec4762fc 100644 --- a/di/torq/proc/segmentedtp/init.q +++ b/di/torq/proc/segmentedtp/init.q @@ -1,5 +1,9 @@ +\l ::stpps.q +\l ::sctp.q +\l ::stplog.q +\l ::stpmeta.q \l ::segmentedtp.q version:first read0`:::VERSION -export:([init;upd;teardown;tablelist;subdetails;readcustomcsv;setcustommode;getcounts;getapimeta;version]) +export:([init;version]) diff --git a/di/torq/proc/segmentedtp/sctp.q b/di/torq/proc/segmentedtp/sctp.q new file mode 100644 index 00000000..ed2ce540 --- /dev/null +++ b/di/torq/proc/segmentedtp/sctp.q @@ -0,0 +1,29 @@ +/ subscribe to segmented tickerplant +.sctp.subscribe:{[] + s:.sub.getsubscriptionhandles[`;.sctp.tickerplantname;()!()]; + if[count s; + subproc:first s; + `.sctp.tph set subproc`w; + .z.m.log[`info][`subscribe;"subscribing to ", string subproc`procname]; + r:.sub.subscribe[.sctp.subscribeto;.sctp.subscribesyms;.sctp.schema;.sctp.replay;subproc]; + if[`d in key r;.u.d::r[`d]]; + if[(`icounts in key r) & (.sctp.loggingmode<>`create); + subtabs:$[.sctp.subscribeto~`;key r`icounts;.sctp.subscribeto],(); + .u.jcounts::.u.icounts::$[0=count r`icounts;()!();subtabs!enlist [r`icounts]subtabs]; + ] + ]; + } + +/ initialise chained STP +.sctp.init:{ + `endofperiod set {[x;y;z] .stplg.endofperiod[x;y;z]}; + `endofday set {[x;y] .stplg.endofday[x;y]}; + .servers.startupdepnamecycles[.sctp.tickerplantname;.sctp.tpconnsleep;.sctp.tpcheckcycles]; + .sctp.subscribe[]; + }; + +/ extract data from incoming table as a list +@[`.;`upd;:;{[t;x] + x:value flip x; + .u.upd[t;x] + }]; diff --git a/di/torq/proc/segmentedtp/segmentedtp.md b/di/torq/proc/segmentedtp/segmentedtp.md index 1f093912..9750a5f2 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.md +++ b/di/torq/proc/segmentedtp/segmentedtp.md @@ -1,379 +1,104 @@ # di.torq.proc.segmentedtp -The segmented tickerplant: receives updates from feeds, timestamps them, writes them to a -configurable **layout of log files** (per table or shared, rolled per period or per day, or a -per-table mix), publishes them to subscribers in one of three **batch modes**, and rolls its -logs at end of period and end of day. It is the TorqX process type for TorQ's -`segmentedtickerplant` proctype. - -Built from the real TorQ source — `code/processes/segmentedtickerplant.q`, -`code/segmentedtickerplant/{stplog,stpmeta,pubsub}.q` and `config/settings/segmentedtickerplant.q` -— onto the `di.torq` process-module conventions, mirroring `di.torq.proc.tickerplant` wherever -segmented TP's own requirements don't force a divergence. **Standalone configuration only:** -TorQ's chained variant (`sctp.q`, which subscribes *to* a parent TP) is out of scope. - -| Dependency | Kind | Role | -| --- | --- | --- | -| `log` | injected | `` `info`warn`error ``, each `{[ctx;msg]}` — required | -| `timer` | injected | `` `addjob`deletejobs`enablejobs`disablejobs `` (di.timer contract) — required | -| `handlers` | injected | `` `register`remove `` (di.torq.handlers contract) — required | -| `servers` | injected | passed by `di.torq`, deliberately unread (no connection needs), as in `di.torq.proc.tickerplant` | -| `di.pubsub` | `use` | subscribe / publish / end-of-period and end-of-day broadcast; its `closesub` is registered on `.z.pc` through `handlers` (di.pubsub no longer binds `.z.pc` at load) | -| `di.eodtime` | `use` | roll date, next roll time, data-timezone adjustment | -| `di.tplogmgr` | `use` | `write` only — see "Why log handling is self-implemented" | - -`deps.toml` declares all three `use`d modules at `0.1.0`. - ---- - -## Config - -`init[config;deps]` — the merged settings dict from `di.torq`'s cascade. Values may be symbols -(`.q` settings) or strings (`.toml`); each is coerced where it is read. - -| Key | Default | Notes | -| --- | --- | --- | -| `kdbtplog` | **required** | root directory for the logs; relative to `TORQXDATAHOME` (falls back to `TORQXAPPHOME`) or absolute. TorQ read `KDBTPLOG`; there is no TorqX equivalent, and TorQ never allowed "no directory" — only `createlogs:0b` | -| `schemafile` | `/database.q` | as `di.torq.proc.tickerplant`: publishable tables are the unkeyed ones with `time`,`sym` first; `` `g# `` applied to `sym` | -| `multilog` | `` `tabperiod `` | naming mode — `tabperiod`, `singular`, `periodic`, `tabular` or `custom` | -| `multilogperiod` | `0D01` | period length (timespan, or a `"0D01:00:00"` string). **Forced to `1D` when the top-level mode is `singular` or `tabular`** — never inside `custom` | -| `batchmode` | `` `defaultbatch `` | `memorybatch`, `defaultbatch` or `immediate` | -| `replayperiod` | `` `day `` | `period` or `day` — what `subdetails` offers for replay | -| `errmode` | `1b` | divert updates that fail to a per-day error log | -| `errorlogname` | `` `segmentederrorlogfile `` | name part of the error log file | -| `createlogs` | `1b` | `0b` publishes without writing any log | -| `logprefix` | the process name | prefix for file and directory names — TorQ used `.proc.procname`, and `di.torq` stamps `procname` into every config, so two segmented tickerplants sharing a `kdbtplog` cannot write the same files or clobber each other's metatable. `"stp"` only when no `procname` is in the config (a hand-wired `init`). An explicit `logprefix` always wins; an empty one is rejected | -| `tickinterval` | `1` | **seconds** — di.timer's unit for modes 1-3. Not TorQ's `system"t 1000"` milliseconds; `1000` here would tick every ~16 minutes (a value of 60 or more is logged at `warn`). di.timer's period is a whole number of seconds, so a sub-second flush is not possible | -| `customcsv` | none | `table,mode` csv for `custom` mode, relative to `TORQXAPPHOME` or absolute | -| `rolltimezone` / `datatimezone` / `rolltimeoffset` | GMT / GMT / `0D` | passed to di.eodtime. `rolltimeoffset` accepts a timespan, a `"0D10:00:00"` string or seconds (like `multilogperiod`); a value that cannot be parsed is dropped with a `warn`, never silently — `di.torq.proc.tickerplant` drops a non-timespan silently | -| `proctype` / `procname` | stamped by `di.torq` | carried in the end-of-period data dict | - -`multilog`, `batchmode` and `replayperiod` are dispatch keys, so an unrecognised value **fails -`init`** with a message naming the setting; so do a non-positive `multilogperiod` or -`tickinterval`. TorQ's settings comment lists `prior` for `replayperiod`, but `stplog.q` never -implemented it — it is rejected. A `multilogperiod` shorter than the tick interval is logged at -`warn` (the past-period guard would trip on every roll). - -Type coercion: booleans accept `1b`/`0b`, `"true"`/`"false"`, `"1"`/`"0"` and numbers; integers -accept numbers or numeric strings; `multilogperiod` accepts a timespan, a `"0D01:00:00"` string, or a -number of seconds. Strings are *parsed*, never cast — `` `boolean$"true" `` is a boolean **list**, -which would throw `'type` in `if`/`$` on every update, and `"j"$"5"` is the character code 53. - ---- - -## Initialisation - -```q -sp:use`di.torq.proc.segmentedtp -sp.init[`kdbtplog`multilog`batchmode!("tplog";`singular;`immediate);`log`timer`handlers!(logdep;timerdep;handlersdep)] -``` - -`di.torq` does this for a `segmentedtp` proctype (`di.torq.builtin`). `init`: - -1. validates the deps (plain signals — nothing is wired yet), tears down a previous successful - `init`, and releases anything a previous *failed* `init` left open (handles, the timer job, - the `.z.exit` registration — removals are no-ops when absent); -2. reads and validates every setting, loads the schema file, initialises di.pubsub and di.eodtime; -3. publishes the root IPC surface: `upd`, `.u.upd`, `.u.sub`, `tablelist`, `subdetails`, and - `tptype:`segmented` (what TorQ's `.sub.subscribe` reads to choose its protocol); -4. opens the day's directory `/_`, its logs, error log and metatable; -5. schedules the timer job `` `segmentedtp `` every `tickinterval` seconds and registers - `.z.exit` (name `` `segmentedtp ``) and di.pubsub's `closesub` on `.z.pc` (name `` `pubsub ``) through - `handlers` as simple events; -6. sets its initialised flag as the **literal last statement**, so a throw anywhere above leaves - the module uninitialised and a retry runs a full `init`. - -Every exported function except `init`, `readcustomcsv`, `getapimeta` and `version` signals if -called before `init`. All post-`init` errors are logged at `error` before being signalled. - ---- - -## Exported functions - -| Function | Description | -| --- | --- | -| `init[config;deps]` | see above | -| `upd[t;x]` | feed entry point (also root `upd` / `.u.upd`). `t` a table symbol, or a symbol list with `x` a matching list of payloads; `x` a list of columns or a table | -| `tablelist[]` | the publishable tables — TorQ `.sub.subscribe`'s `tablesfunc` for a segmented TP | -| `subdetails[tabs;instruments]` | TorQ `.sub.subscribe`'s `subfunc`: registers the caller with di.pubsub and returns `` `schemalist`logfilelist`rowcounts`date`logdir `` | -| `readcustomcsv[path]` | reads a `table,mode` csv into a `table!mode` dict; touches no state, callable before `init` | -| `setcustommode[dict]` | replaces the custom assignment at runtime (custom mode only) | -| `getcounts[]` | `` `seqnum`tables `` — per-table `msgcount`/`rowcount` (logged and published) and `pendingmsgcount`/`pendingrowcount` (in the unflushed batch) | -| `teardown[]` | flush, close every segment and file, remove the timer job and the `.z.exit` and `.z.pc` handlers | -| `getapimeta[]` | api metadata for `di.torq` to register with `di.api` (callable functions only) | -| `version` | the `VERSION` file's contents | - ---- - -## Naming modes - -Files live in `/_/`; timestamps are `YYYYMMDDHHMMSS` of the period -start (data-timezone adjusted), exactly as `stplog.q` builds them with `logprefix` for `procname`. - -| Mode | Files | Rolled | -| --- | --- | --- | -| `tabperiod` | `stp_` — one per table | every `multilogperiod` | -| `singular` | `stp_` — one shared by all tables | daily (period forced to `1D`) | -| `periodic` | `stp_periodic` — one shared by all tables | every `multilogperiod` | -| `tabular` | `stp_
` — one per table | daily (period forced to `1D`) | -| `custom` | per table, under its own mode from the csv / `setcustommode` | periodic/tabperiod tables per period; singular/tabular tables daily only | - -Also in the directory: `stp_` (one error log per day, when `errmode`) -and `stpmeta`, the metatable. - -In custom mode a table absent from the assignment is published but not logged. Custom mode with -no `customcsv` starts with nothing logged and a warning, until `setcustommode` is called. -`setcustommode` flushes, closes every open segment, and reopens every assigned table under the new -layout: a table whose file name is unchanged reopens the same file and resumes its metatable row. - -## Batch modes - -| Mode | On `upd` | On the timer flush | -| --- | --- | --- | -| `immediate` | write the log, publish | nothing | -| `defaultbatch` | insert into the root table, write the log; counts held as **pending** | publish and clear every table, then count the pending messages | -| `memorybatch` | insert into the root table only | per table with rows: write the whole buffer as **one** message, count it, publish and clear | - -Holding `defaultbatch` counts as pending until they are published is what keeps a subscriber's -replay count exact: a message already written but not yet published is not included in -`subdetails`' counts, because the subscriber will receive it live. - -## Timer job, period end and day end - -The `` `segmentedtp `` job flushes the batch and then checks for boundaries (TorQ's -`.stpps.zts.def`). `upd` also checks, so a boundary is not missed between ticks. - -The job body is protected and any failure is logged at `error`, and the job is registered with -`disableonfail` off. Both are needed: di.timer swallows a job's error unless its own `debug` flag -is on, and with `disableonfail` (its default) the first transient failure — a full disk on a -memorybatch flush, say — would silently stop this process flushing and rolling for good. A guard -trip still stops the job deliberately (via `disablejobs`); the next successful roll re-enables it. - -- **End of period** — flush, `di.pubsub.callendofperiod`, advance the period, then roll the - period-rolled tables: close their metatable rows, close their files, reset their message counts, - open the new period's files and rows. -- **End of day** — flush, `di.pubsub.callendofday[date]`, advance di.eodtime (date, next roll, - daily adjustment), close every segment, file and the error log, then start the new day - (fresh counts, directory, logs, error log and metatable). - -## Metatable - -`stpmeta` in the day directory: `seq`, `logname`, `start`, `end`, `tbls`, `msgcount`, `schema`, -`additional` — as TorQ's `stpmeta.q`. Persisted on every open and close. `end`/`msgcount` are set -when a segment closes; a null `end` means open (or never closed). - -## Subscriber protocol - -`subdetails[tabs;instruments]` returns: - -| Key | Value | -| --- | --- | -| `schemalist` | list of `(table;empty schema)` pairs for the tables subscribed | -| `logfilelist` | list of `(message count;log file)` pairs, as `-11!` takes them | -| `rowcounts` | `table!rows` for the day, for the tables subscribed | -| `date` | the roll date | -| `logdir` | `kdbtplog` as a symbol — **carried**: TorQ's `.sub.subscribe` segmented branch returns `details[`logdir]` to its caller (`subscriptions.q:132`), so a consumer of this exact protocol expects it | - -`logfilelist` under `replayperiod`: -- `day` — every metatable row naming a subscribed table: closed segments `0W` (replay in full), - open segments their current message count; -- `period` — the files currently open for the subscribed tables. - -Either way there is **one pair per physical file**, counting the messages of *every* table in it — -including tables outside the request, whose messages the file physically holds. A filtered -subscriber (sym list or filter table) therefore replays unfiltered files and must filter during -replay itself, as TorQ's `.sub.replayupd` does. `rowcounts` are the **day's** row totals per table -(as TorQ's `rowcount`), even under `replayperiod=period`. - -Verified end to end (a real subscriber process calling `subdetails`, replaying `logfilelist` with -`-11!`, then receiving live): every batch mode, a shared singular file, and a subscription made -across a period roll each delivered every message exactly once. - ---- - -## Design record - -### Why log handling is self-implemented - -`di.tplogmgr`'s `open`/`roll`/`logname` are fixed at one file per date (`/tp`). -Segmented TP exists to write several files per day under several naming schemes, so naming, -opening, closing and rolling are implemented here; only `write` is taken from `di.tplogmgr`. - -### Defects in the TorQ source, fixed from day one - -Each is a confirmed defect in the shipped TorQ code, not hypothetical hardening. Each has a -regression test asserting the corrected behaviour. - -1. **Corrupt logs were opened blind.** `openlog` `hopen`ed an existing file with no check. Every - existing file is now counted with the non-executing `-11!(-2;file)` first. A corrupt file's - good prefix is copied to `.good` (via a temp file and `mv`), and that copy is opened, - recorded in `currlog` and renamed in the metatable. The corrupt original is left untouched. A - later start prefers an existing `.good`, so the recovery is not repeated and appended messages - are not lost. A file too short to hold a log header, or one `-11!(-2;…)` cannot read at all - (it throws `'type` on either), holds no recoverable message and is recovered as an empty - `.good`. A corrupt `.good` is recovered in place (its own good prefix), the one case where the - file being recovered is overwritten. - *Decision:* a generic byte-prefix copy rather than `di.tplogmgr.check`/`di.tplog.repair`. - `di.tplog`'s repair matches the `(`upd;`trade;…)` message header only, so for any other table, - and for any shared file, it would write an empty `.good` — silent data loss. -2. **A roll-guard trip stopped the whole process timer.** `stpeoperiod`/`dayrollover`/`checkends` - called `system"t 0"`. The guards now call `timer.disablejobs[enlist`segmentedtp]` — this - module's job only — and every successful roll calls `enablejobs` for it. -3. **The error log leaked a handle every day.** It is tracked apart from the table logs, and - `dayrollover` never closed it. Day roll, teardown and clean exit now close it explicitly. -4. **An unclean shutdown left never-closed metatable rows, and TorQ added a row on every open.** - After the day's logs are opened, still-open rows are reconciled by **logname**. A row for a file - opened again is resumed (and a file already in the metatable is reopened rather than repeated). - Any other still-open row is an orphan, closed with a **null** message count and logged at - `warn`. The count is not reconstructed by replaying the file, which would drive the root `upd`. -5. **Replay lists were built per table.** Under `singular`/`periodic` several tables share one - file, and a `(count;file)` pair per table double-counts it. Pairs are now built per physical - file, summing every table writing to it. -6. **Custom mode's metatable split was two-way.** `updmeta[`custom]` sent every non-periodic table - down the per-table path, so custom `singular` tables got a row each. Metatable rows are now - grouped by the physical file each table is actually writing. That gives one shared row for a - shared file and one row for a per-table file, whatever mode assigned it, so the four-way split - needs no mode dispatch. -7. **A failed `init` could look initialised.** The initialised flag is written only as the last - statement of `init`. A retry after a part-way failure also releases the leaked handles and the - job/handler registration, so it registers exactly once. -8. **Unrecognised `multilog`/`batchmode`/`replayperiod` failed late or silently.** Each indexes a - dispatch dict, where an unknown key gives null — a confusing error somewhere unrelated or, for - `replayperiod`, a bad `subdetails` answer with no error at all. All three are validated in - `init`, and each is resolved to its function once there. -9. **`createlogs:0b` made every update throw.** `` `..loghandles[t] enlist … `` applied a null handle. - TorQ's own chained TP masked this by setting `loghandles` to `(::)`; a standalone TP with - `createlogs:0b` — or a custom-mode table missing from the csv — threw on every `upd`. A table - with no open log is now published and counted without a write. - -### Further decisions - -- **Logs open at the period start, not at `.z.p`.** TorQ opened its first logs at the current - timestamp, so a restart always created new files. Opening at the aligned period start lets a - restart within a period resume the same files, which is the case fixes 1 and 4 exist for. Each - file's message count when opened is kept as its base count, so replay counts for a resumed file - include the messages already in it. -- **Period and day ends flush the batch mode, not just `pubclear`.** TorQ called `pubclear` at - period end. Under `memorybatch` that published the buffer without ever logging it, and under - `defaultbatch` it left pending counts to be added to the next period's file. -- **`upd` survives a failed boundary check.** The check is protected inside `upd`: a guard trip is - logged and stops the job, but the message that exposed it is still logged and published. In - TorQ's `errmode` the whole `.u.upd` was trapped, so that message went to the error log instead. -- **The error log is per day** (named with the day start), so a restart appends to it. -- **`.u.sub` and `tptype` are published** — TorQ's segmented TP exposed both; `.sub.subscribe` reads - `tptype` to pick the `tablelist`/`subdetails` protocol. -- **`logprefix` defaults to `procname`.** The first draft defaulted to a fixed `"stp"`, which dropped a - property TorQ had by construction: names unique per process. Review caught it; the process name from - `di.torq`'s config is now the default, `"stp"` the fallback for a hand-wired `init`. -- **A string table name in `upd` is accepted as the symbol.** `$[0h/fd` (Linux). +A segmented tickerplant. It stamps and logs incoming updates, per table and per period, and publishes them to +subscribers, filtered or not, immediately or in batches. With `sctpchainedtp` on, it runs as a chained segmented +tickerplant: it subscribes to another one and republishes what it receives. + +## Files + +`init.q` loads, in order: `stpps.q` (`.stpps.upd`/`.stpps.zts`), `sctp.q` (`.sctp`, the chained mode), `stplog.q` +(`.stplg`, logging and batching), `stpmeta.q` (`.stpm`, log metadata) and `segmentedtp.q` (the process and `init`). + +## Surface + +| Name | What | +|---|---| +| `tptype` | `` `segmented `` | +| `tablelist[]` | the published tables (`.stpps.t`) | +| `subdetails[tabs;instruments]` | subscribes the caller; returns `schemalist`, `logfilelist`, `rowcounts`, `date`, `logdir` | +| `.u.upd[t;x]` | the update entry point; `x` is a list of columns without `time` | +| `upd[t;x]` | chained: a table from the upstream, passed to `.u.upd` | +| `endofday[date;data]` / `endofperiod[cur;next;data]` | chained: set at root by `.sctp.init` | +| `currlog` / `loghandles` | open logs per table, and a view of their handles | +| `.stplg.*` | settings, `init`, `upd`/`zts` per batch mode, `replaylog`, `openlog`, `closelog`, `rolllog`, `endofday`, `endofperiod`, `checkends` | +| `.sctp.*` | settings, `subscribe`, `init` | +| `.stpm.metatable` | one row per opened log: `seq`, `logname`, `start`, `end`, `tbls`, `msgcount`, `schema`; saved as `stpmeta` in the log directory | + +Subscribers get `(`upd;t;x)`, `(`endofperiod;cur;next;data)` and `(`endofday;date;data)`, where `data` is +`proctype`, `procname`, `tables` and `p`. + +## Settings + +Every `stplg` and `sctp` setting and `createlogs` is required in `config`; the module keeps no defaults of +its own, and `di/torq/settings/segmentedtp.q` declares them all. `stplg` settings are set onto `.stplg.`: + +| Key | Default | +|---|---| +| `multilog` | `` `tabperiod `` — `tabperiod`, `periodic`, `tabular`, `singular` or `custom` | +| `multilogperiod` | `0D01` | +| `errmode` | `1b` — failed updates go to an error log | +| `batchmode` | `` `defaultbatch `` — `immediate`, `defaultbatch` or `memorybatch` | +| `replayperiod` | `` `day `` — `day` or `period` | +| `customcsv` | `"appconfig/stpcustom.csv"` — `table,mode` csv for `custom`; a relative path is under `TORQXAPPHOME`; unreadable fails `init` | +| `kdbtplog` | `KDBTPLOG` — the log root; logs go in `/_`; optional | +| `errorlogname` | `` `segmentederrorlogfile `` | + +`sctp` settings are set onto `.sctp.`: `chainedtp` (`0b`), `loggingmode` (`` `none ``: `none`, `create` or +`parent`), `tickerplantname` (`` `stp1 ``), `tpconnsleep` (`10`), `tpcheckcycles` (`0W`), `subscribeto` and +`subscribesyms` (`` ` ``), `replay` (`0b`), `schema` (`1b`). `loggingmode`, `tickerplantname`, `subscribeto` and +`subscribesyms` also take strings, so they can live in a `.toml` file as quoted keys (`"sctpchainedtp" = true`). + +Any of them can be given on the command line as `-stplg`, `-sctp` or `-createlogs`; an app sets only the +keys it overrides. + +An `eodtime` section, passed to di.eodtime's `init`: `rolltimezone`, `datatimezone`, `rolltimeoffset`. + +Flat: `schemafile` (required unless chained), `createlogs` (`1b`, required). + +## init[config;deps] + +Requires `log`, `timer` and `handlers`. It: + +1. initialises di.subscriptions, di.pubsub and di.eodtime, and registers `.stpps.closesub` on `.z.pc`; +2. applies the settings; `singular` and `tabular` set `multilogperiod` to `1D`; `custom` loads `customcsv`; + `parent` makes `replaylog` ask the upstream; +3. registers a `.z.pc` observer (chained: exit 1 when the upstream closes) and a `.z.exit` observer (flush + `memorybatch`, close the logs); +4. sets `.u.upd` from `batchmode` and adds the `stpzts` timer job (the batch timer and the end checks, every + second); +5. chained: waits for the upstream and subscribes; otherwise loads `schemafile`; +6. strips attributes from the published tables and opens the logs. + +Under di.torq, `generateschemas` is queued with `.proc.addinitlist`, so it runs again after di.torq's +`.ps.initialise[]` and the published tables stay the schema tables. + +## Behaviour to know + +- End of period and end of day are checked on each update and each timer tick. +- If the next period or roll is already past, or more than a day has gone by, the tick stops + (`.stplg.stopped`) and the check signals; other timer jobs keep running. Any other error in the tick is retried + on the next tick. +- Server tracking stays on (TorQ's STP turns it off), so the process can register with discovery. Heartbeating is + not wired and query logging is off unless `[querylog]` is enabled, as in TorQ's STP. +- `segmentedchainedtp` has no subscriber cutoff (TorQ's `.subcut`): slow subscribers are not disconnected. +- The first logs of a day have `seq` 0, and each period roll adds 1. +- After an end of period, `currperiod` becomes the old `nextperiod`. +- `period` replay returns `distinct` count and log pairs for the tables asked for; `day` replay returns every log of + the day, closed ones with count `0W`. +- In `custom` mode a table missing from the csv is not logged. +- Chained without `create`, `loghandles` becomes a dictionary of `::`, and `.z.exit` leaves the logs alone. +- The `.z.exit` flush runs only in `memorybatch`. +- `subdetails` and `.stplg.replaylog` take a list of tables. + +## Testing ```q k4unit:use`di.k4unit k4unit.moduletest`di.torq.proc.segmentedtp ``` -Run from the repository root (the suite loads `di/torq/proc/segmentedtp/test.q` by relative path). -**Put this repository first on `QPATH`** — a shared `mod/di` directory earlier on the path (e.g. a -`/opt/kdbx/mod/di` symlink to another checkout) silently supplies its own `di.eodtime`, `di.pubsub`, -`di.timer` and `di.k4unit`, and the suite then tests someone else's dependencies. Check with -`.Q.m.mp`di.eodtime`. - -**Integration suite** (`test_integration.csv`) — spawns real child kdb-x processes -(`test_integration_child.q`, which wires the module to the real di.timer, di.torq.handlers and -di.util.log and takes every `-flag` as a string setting, exercising the config coercions), and one -**real `di.torq` boot**: a throwaway app (schema, `process.csv`, a `segmentedtp.toml`) launched -through `torqx_init.q` exactly as `torqx.sh` does, asserting identity and settings reached the -module, feeding it, and exiting it cleanly. Run it in its own fresh q session, not after `moduletest`: - -```q -k4unit:use`di.k4unit -.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.torq.proc.segmentedtp;`test_integration.csv] -.m.di.0k4unit.KUrt[] -k4unit.getresults[] -``` +`test.q`/`test.csv` start five peers: `defaultbatch` with `tabperiod`, `immediate` with `singular`, `memorybatch` +with `tabular`, and two chained peers (`create`, `parent`) on the first. The test process subscribes through +`.sub.subscribe`. The tests cover the settings, the handshake, each batch mode and log naming, error mode, sym and +filtered subscriptions, both replay periods, end of period, end of day (including through the chained peer), the +`.z.exit` flush and the chained exit when the upstream is lost. diff --git a/di/torq/proc/segmentedtp/segmentedtp.q b/di/torq/proc/segmentedtp/segmentedtp.q index e39a91ae..35b19db1 100644 --- a/di/torq/proc/segmentedtp/segmentedtp.q +++ b/di/torq/proc/segmentedtp/segmentedtp.q @@ -1,768 +1,121 @@ -/ di.torq.proc.segmentedtp - segmented tickerplant. Receives feed updates, timestamps them, writes them to one of -/ five log layouts (per table or shared, rolled per period or per day, or a per-table custom mix), publishes them -/ via di.pubsub in one of three batch modes, and rolls its logs at end of period and end of day. -/ Built from TorQ/code/processes/segmentedtickerplant.q and code/segmentedtickerplant/{stplog,stpmeta,pubsub}.q, -/ standalone configuration only (the chained sctp.q variant is out of scope). Hard deps: di.pubsub (sub/pub), -/ di.eodtime (roll timing), di.tplogmgr (write only - naming, open and roll are self-implemented because -/ di.tplogmgr is fixed at one file per date). Injected deps: log, timer, handlers. Design record: segmentedtp.md. +/ di.torq.proc.segmentedtp - segmented tickerplant -/ --- constants --- +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; -modes:`tabperiod`singular`periodic`tabular`custom; -custommodes:`tabperiod`singular`periodic`tabular; -batchmodes:`memorybatch`defaultbatch`immediate; -replayperiods:`period`day; -jobid:`segmentedtp; / the timer job and .z.exit handler name -copychunk:8388608; / bytes per read when copying a corrupt log's good prefix - -/ live log per table: the file it writes to and the handle (shared by every table writing that file) -currlogschema:([tbl:`symbol$()]logname:`symbol$();handle:`int$()); - -/ on-disk metatable, one row per physical log file (TorQ's stpmeta.q) -metaschema:([]seq:`int$();logname:`symbol$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()); - -/ --- module state read before init has run (everything else is written by init) --- - -initdone:0b; -logwired:0b; -currlog:currlogschema; -errh:0Ni; - -/ --- shared helpers (as di.torq.proc.tickerplant) --- - -/ base dirs: CODE/CONFIG under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falling back to TORQXAPPHOME) -apphome:{getenv[`TORQXAPPHOME]}; -datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]}; - -/ resolve a possibly-relative dir setting to an absolute path STRING under base; symbol (.q) or string (.toml) input -resolvedir:{[base;dir] - dir:$[10h=abs type dir;dir;string dir]; - dir:$[(0.good - keep using it rather than the corrupt original -resolvelog:{[ln] $[type key g:goodname ln;g;ln]}; - -openfile:{[ln] - / hopen a log, creating it if absent. an existing log is counted first WITHOUT executing it, and a corrupt one - / is never opened blind (TorQ's openlog did) - its good prefix is copied to .good and that is opened. - / the message count found is kept as the file's base count. returns (name;handle) - if[not type key ln;.[ln;();:;()]]; - / a zero-byte file (a crash between create and header write) is safely re-headed; a file shorter than the 8-byte - / header, or one -11!(-2;..) cannot read at all, holds no recoverable message - recover it as an empty log - if[0=hcount ln;.[ln;();:;()]]; - info:@[-11!;(-2;ln);{0 0}]; - if[1info 1;.[tmp;();:;()];copyprefix[ln;tmp;info 1]]; - system "mv -f ",(shq 1_string tmp)," ",shq 1_string g; - renamemeta[ln;g]; - .z.m.log[`warn][`openlog;"corrupt log ",(1_string ln),": kept ",(string info 0)," good message(s) (",(string info 1)," bytes) in ",1_string g]; - g - }; - -copyprefix:{[src;dst;n] - / copy the first n bytes of src to dst in bounded chunks; the destination handle is closed even if a read fails - dst 1: `byte$(); - h:hopen dst; - r:@[{[src;h;n] copychunkto[src;h;n]/[0j]}[src;h];n;{[e] (`copyfailed;e)}]; - hclose h; - if[`copyfailed~first r;'"copying ",(1_string src),": ",r 1]; - }; - -/ shell-quote a path for system calls (mkdir / mv) -shq:{[p] "\"",p,"\""}; - -copychunkto:{[src;h;n;o] - / append the next chunk of src from offset o; returns the new offset, unchanged once at n (ending the over) - if[o>=n;:o]; - k:copychunk&n-o; - h read1 (src;o;k); - o+k - }; - -rebuildhandles:{[] .z.m.loghandles:exec tbl!handle from .z.m.currlog;}; - -openlog:{[tab;p] - / open - or share, when another table already has it open - the log tab writes to for the period starting p - ln:resolvelog lognamefor[tab;p]; - h:exec first handle from .z.m.currlog where logname=ln,not null handle; - if[null h;r:openfile ln;ln:r 0;h:r 1]; - .z.m.currlog:.z.m.currlog upsert (tab;ln;h); - rebuildhandles[]; - .z.m.log[`info][`openlog;"table ",(string tab)," logging to ",1_string ln]; - }; - -openfail:{[tab;e] .z.m.log[`error][`rolllog;"failed to open log for table ",(string tab),": ",e];}; - -openlogsafe:{[tab;p] .[openlog;(tab;p);openfail[tab]];}; - -closefail:{[h;e] .z.m.log[`warn][`closelog;"handle ",(string h)," already closed: ",e];}; - -closehandle:{[h] @[hclose;h;closefail[h]];}; - -closelogs:{[ts] - / close the files the given tables write to - a shared file is closed once, and only when no other table uses it - hs:distinct exec handle from .z.m.currlog where tbl in ts,not null handle; - hs:hs except exec handle from .z.m.currlog where not tbl in ts,not null handle; - closehandle each hs; - .z.m.currlog:update handle:0Ni from .z.m.currlog where tbl in ts; - rebuildhandles[]; - if[count hs;.z.m.log[`info][`closelog;"closed ",(string count hs)," log file(s)"]]; - }; - -openerrlog:{[] - / the day's error log for messages that fail in errmode - one per day, so a restart appends to it - d:(.z.m.eod`getd)[]; - r:openfile resolvelog lognameerror[.z.m.dldir;.z.m.errorlogname;"p"$d]; - .z.m.errlog:r 0; - .z.m.errh:r 1; - .z.m.log[`info][`openerrlog;"error log is ",1_string .z.m.errlog]; - }; - -closeerrlog:{[] - / the error log is tracked apart from currlog, so every roll and shutdown must close it explicitly - TorQ's - / dayrollover never did, leaking one handle per day - if[null .z.m.errh;:()]; - closehandle .z.m.errh; - .z.m.errh:0Ni; - .z.m.log[`info][`closeerrlog;"closed error log ",1_string .z.m.errlog]; - }; - -releaselogs:{[] - / close whatever an earlier init left open, without touching the metatable - used when init is called again - closehandle each distinct exec handle from .z.m.currlog where not null handle; - .z.m.currlog:currlogschema; - if[not null .z.m.errh;closehandle .z.m.errh]; - .z.m.errh:0Ni; - rebuildhandles[]; - }; - -writelog:{[t;msg] - / append to the table's log. tables with no open log (createlogs off, or unlisted in custom mode) are skipped - - / TorQ applied the null handle and threw on every update - if[not null h:.z.m.loghandles t;(.z.m.tp`write)[h;msg]]; - }; - -/ --- metatable (TorQ's stpmeta.q) --- - -filecount:{[ln] - / messages in a physical file: its count when opened plus what every table sharing it has written since - ts:exec tbl from .z.m.currlog where logname=ln; - (0^.z.m.basecount ln)+sum .z.m.msgcount ts - }; - -addmetarow:{[row] .z.m.metatable:.z.m.metatable,enlist row;}; - -renamemeta:{[ln;g] .z.m.metatable:update logname:g from .z.m.metatable where logname=ln;}; - -metaopen:{[p;ln;ts] - / a file already in the metatable (a restart or reassignment resuming the same segment) is reopened, not repeated - if[ln in .z.m.metatable`logname; - .z.m.metatable:update end:0Np,tbls:{distinct x,y}[;ts] each tbls from .z.m.metatable where logname=ln; - :()]; - addmetarow `seq`logname`start`end`tbls`msgcount`schema`additional!(.z.m.seq;ln;p;0Np;ts;0i;ts#.z.m.schemas;()!()); - }; - -metaclose:{[p;ln] - / stamp a segment closed with the messages its file holds - c:"i"$filecount ln; - .z.m.metatable:update end:p,msgcount:c from .z.m.metatable where logname=ln,null end; - }; - -updmeta:{[ev;ts;p] - / record segments opening or closing. grouped by PHYSICAL file, so a shared singular/periodic file gets one row and a - / per-table file one row whatever mode assigned it - TorQ's custom path wrote custom singular tables per table - if[not count ts;:()]; - grp:exec tbl by logname from .z.m.currlog where tbl in ts,not null logname; - if[count grp;$[ev=`open;metaopen[p]'[key grp;value grp];metaclose[p] each key grp]]; - setmeta[]; - }; - -setmetafail:{[e] .z.m.log[`error][`setmeta;"failed to persist the metatable: ",e];}; - -setmeta:{[] .[set;(hsym`$.z.m.dldir,"/stpmeta";.z.m.metatable);setmetafail];}; - -loadmetafail:{[e] - .z.m.log[`warn][`loadmeta;"unreadable metatable, starting a new one: ",e]; - :metaschema; - }; - -loadmeta:{[] - f:hsym`$.z.m.dldir,"/stpmeta"; - $[type key f;@[get;f;loadmetafail];metaschema] - }; - -reconcilemeta:{[] - / TorQ appended a row on every open, so an unclean exit left a never-closed row behind. a still-open row for a file - / opened again now is resumed; any other still-open row is an orphan - closed with an unknown (null) message count, - / not a count guessed by replaying the file, which would drive the root upd - cur:exec distinct logname from .z.m.currlog where not null logname; - stale:exec logname from .z.m.metatable where null end,not logname in cur; - now:.z.p+(.z.m.eod`getdailyadj)[]; - if[count stale; - .z.m.metatable:update end:now,msgcount:0Ni from .z.m.metatable where logname in stale; - .z.m.log[`warn][`reconcilemeta;"closed ",(string count stale)," segment(s) left open by an unclean shutdown: ",", " sv 1_'string stale]]; - resumed:exec seq from .z.m.metatable where logname in cur; - .z.m.seq:$[count resumed;max resumed;1i+-1i|max .z.m.metatable`seq]; - }; - -/ --- replay lists for subscribers: (message count;log file) pairs, as -11! takes them --- - -getlogsperiod:{[ts] - / the current period only: one pair per physical file, counting every table in it - not one pair per table, - / which double-counts a shared singular/periodic file - lns:exec distinct logname from .z.m.currlog where tbl in ts,not null handle; - flip (filecount each lns;lns) - }; - -getlogsday:{[ts] - / the whole day from the metatable: closed segments replay in full (0W), open ones up to their current count - m:select logname,end from .z.m.metatable where any each tbls in\: ts; - if[not count m;:()]; - flip (?[null m`end;filecount each m`logname;0W];m`logname) - }; - -getlogsfns:`period`day!(getlogsperiod;getlogsday); - -/ --- updates and the three batch modes (TorQ's .stplg.upd / .stplg.zts) --- - -stampcols:{[x;ts] - / prepend the arrival timestamp, unless the first column already is one (as di.torq.proc.tickerplant) - if[-12h=type first first x;:x]; - $[0>type first x;ts,x;(enlist(count first x)#ts),x] - }; - -updmemory:{[t;x;ts] - / memorybatch: buffer only - logging and publishing both wait for the flush - t insert stampcols[tocols x;ts]; - }; - -flushtable:{[t] - / memorybatch flush for one table: the whole buffer goes to the log as ONE message, then is published and cleared - if[not n:count value t;:()]; - writelog[t;(`upd;t;value flip value t)]; - .z.m.msgcount[t]+:1; - .z.m.rowcount[t]+:n; - (.z.m.ps`pubclear)[t]; - }; - -flushmemory:{[] flushtable each .z.m.pubtabs;}; - -upddefault:{[t;x;ts] - / defaultbatch: log straight away, publish on the flush. counts are held as pending until published, so a - / subscriber's replay count never includes a message it will also receive live - x:stampcols[tocols x;ts]; - t insert x; - writelog[t;(`upd;t;x)]; - .z.m.tmpmsgcount[t]+:1; - .z.m.tmprowcount[t]+:count first x; - }; - -resettmp:{[] - .z.m.tmpmsgcount:.z.m.pubtabs!count[.z.m.pubtabs]#0j; - .z.m.tmprowcount:.z.m.pubtabs!count[.z.m.pubtabs]#0j; - }; - -flushdefault:{[] - (.z.m.ps`pubclear)[.z.m.pubtabs]; - .z.m.msgcount+:.z.m.tmpmsgcount; - .z.m.rowcount+:.z.m.tmprowcount; - resettmp[]; - }; - -updimmediate:{[t;x;ts] - / immediate: log and publish on every update - x:stampcols[tocols x;ts]; - writelog[t;(`upd;t;x)]; - d:flip .z.m.tabcols[t]!$[0>type first x;enlist each x;x]; - .z.m.msgcount[t]+:1; - .z.m.rowcount[t]+:count d; - (.z.m.ps`publish)[t;d]; - }; - -flushimmediate:{[]}; - -updfns:`memorybatch`defaultbatch`immediate!(updmemory;upddefault;updimmediate); -flushfns:`memorybatch`defaultbatch`immediate!(flushmemory;flushdefault;flushimmediate); - -unknowntable:{[t;x;ts] raiseerror[`upd;"not a publishable table: ",-3!t]}; - -badmsg:{[t;x;e] - / errmode: log the failure, then keep the message in the error log as (`upderr;t;x) - .z.m.log[`warn][`upd;"bad message for ",(-3!t),": ",e]; - if[not null .z.m.errh;(.z.m.tp`write)[.z.m.errh;(`upderr;t;x)]]; - }; - -updmsg:{[t;x;ts] - / one table's message; in errmode a failure goes to the error log instead of back to the feed - f:$[t in .z.m.pubtabs;.z.m.updfn;unknowntable]; - $[.z.m.errmode;.[f;(t;x;ts);badmsg[t;x]];f[t;x;ts]]; - }; - -rollfail:{[e] .z.m.log[`error][`upd;"end of period/day check failed: ",e];}; - -upd:{[t;x] - / feed entry point (root upd / .u.upd): check for a period or day end, then log and publish under the batch mode. - / a failed roll is logged and stops the tick job, but does not lose the message that exposed it - requireinit`upd; - / a string table name would be iterated character by character below - if[10h=type t;t:`$t]; - now:.z.p; - if[.z.m.nextendutc.z.m.nextperiod;stopjob[`endofperiod;"next period is in the past"]]; - getnextendutc[]; - if[rolllogs and .z.m.createlogs;.z.m.seq+:1i;rolllog[.z.m.rolltabs;data`p]]; - (.z.m.timer`enablejobs)[enlist jobid]; - .z.m.log[`info][`endofperiod;"end of period complete, current period is now ",string .z.m.currperiod]; - }; - -closeday:{[p] - / close every open segment and file, the error log included - if[.z.m.createlogs;updmeta[`close;exec tbl from .z.m.currlog;p];closelogs exec tbl from .z.m.currlog]; - closeerrlog[]; - }; - -dayrollover:{[data] - nr:(.z.m.eod`getroll)[data`p]; - (.z.m.eod`setnextroll)[nr]; - if[(data`p)>nr;stopjob[`endofday;"next roll is in the past"]]; - (.z.m.eod`setd)[1+(.z.m.eod`getd)[]]; - closeday (data`p)+(.z.m.eod`getdailyadj)[]; - (.z.m.eod`setdailyadj)[(.z.m.eod`getdailyadjustment)[]]; - startday[]; - (.z.m.timer`enablejobs)[enlist jobid]; - .z.m.log[`info][`endofday;"end of day complete, date is now ",string (.z.m.eod`getd)[]]; - }; - -endofday:{[d;data] - / flush, tell subscribers, roll every log into the next day's directory - .z.m.flushfn[]; - (.z.m.ps`callendofday)[d]; - dayrollover data; - }; - -dayend:{[now] - if[(.z.m.eod`getd)[]<("d"$now)-1;stopjob[`checkends;"more than one day has passed since the last end of day"]]; - endofday[(.z.m.eod`getd)[];enddata now]; - }; - -checkends:{[now] - / fire end of period and/or end of day once a boundary has passed - if[.z.m.nextendutc>now;:()]; - adj:now+(.z.m.eod`getdailyadj)[]; - if[.z.m.nextperiodtype deps k;'"di.torq.proc.segmentedtp: ",(string k)," dependency must be a dict - ",hint]; - if[count missing:fns except key deps k;'"di.torq.proc.segmentedtp: ",(string k)," dependency is missing ",", " sv string missing]; - }; - -checkdeps:{[deps] - / validate the injected deps before anything is wired - plain signals, as no logger is usable yet - if[99h<>type deps;'"di.torq.proc.segmentedtp: deps must be a dict with `log`timer`handlers keys"]; - checkdep[deps;`log;`info`warn`error;"see di.util.log"]; - checkdep[deps;`timer;`addjob`deletejobs`enablejobs`disablejobs;"see di.timer"]; - checkdep[deps;`handlers;`register`remove;"see di.torq.handlers"]; - }; - -checkin:{[k;v;ok] - if[not v in ok;raiseerror[`init;(string k)," must be one of ",(", " sv string ok),"; got ",-3!v]]; - }; - -readconfig:{[config] - / read and validate every setting up front: a value used later as a dispatch key would otherwise index to null - / and fail somewhere unrelated - or, for replayperiod, not fail at all and corrupt subdetails - .z.m.cfg:config; - if[not `kdbtplog in key config;raiseerror[`init;"kdbtplog is required - the root directory for the log files"]]; - if[0=count tostr config`kdbtplog;raiseerror[`init;"kdbtplog must name a directory"]]; - .z.m.kdbtplog:resolvedir[datahome[];config`kdbtplog]; - .z.m.multilog:astz cfgor[config;`multilog;`tabperiod]; - .z.m.multilogperiod:totimespan cfgor[config;`multilogperiod;0D01]; - .z.m.errmode:tobool cfgor[config;`errmode;1b]; - .z.m.batchmode:astz cfgor[config;`batchmode;`defaultbatch]; - .z.m.replayperiod:astz cfgor[config;`replayperiod;`day]; - .z.m.errorlogname:astz cfgor[config;`errorlogname;`segmentederrorlogfile]; - .z.m.createlogs:tobool cfgor[config;`createlogs;1b]; - / file and directory names carry the process name, as TorQ's .proc.procname did: two segmented tickerplants - / sharing a kdbtplog then cannot write the same files or clobber each other's metatable. "stp" only when no - / procname is known (di.torq always stamps one) - .z.m.logprefix:tostr cfgor[config;`logprefix;$[`procname in key config;config`procname;"stp"]]; - if[0=count .z.m.logprefix;raiseerror[`init;"logprefix must not be empty"]]; - .z.m.tickinterval:tolong cfgor[config;`tickinterval;1]; - .z.m.proctype:astz cfgor[config;`proctype;`segmentedtp]; - .z.m.procname:astz cfgor[config;`procname;`]; - checkin[`multilog;.z.m.multilog;modes]; - checkin[`batchmode;.z.m.batchmode;batchmodes]; - checkin[`replayperiod;.z.m.replayperiod;replayperiods]; - if[not 0D<.z.m.multilogperiod;raiseerror[`init;"multilogperiod must be a positive timespan"]]; - if[not 0<.z.m.tickinterval;raiseerror[`init;"tickinterval must be a positive number of seconds"]]; - / TorQ's system"t 1000" was milliseconds; di.timer's period is seconds, so a carried-over 1000 is ~16 minutes - if[60<=.z.m.tickinterval; - .z.m.log[`warn][`init;"tickinterval is ",(string .z.m.tickinterval)," SECONDS - the batch flush and roll checks run that rarely"]]; - / singular and tabular roll daily - forced for the top-level mode only, never inside custom, as TorQ does - if[.z.m.multilog in `singular`tabular;.z.m.multilogperiod:1D]; - / a period the tick cannot keep up with trips the past-period guard on every roll - if[.z.m.multilogperiod<0D00:00:01*.z.m.tickinterval; - .z.m.log[`warn][`init;"multilogperiod ",(string .z.m.multilogperiod)," is shorter than the ",(string .z.m.tickinterval),"s tick interval"]]; - .z.m.updfn:updfns .z.m.batchmode; - .z.m.flushfn:flushfns .z.m.batchmode; - .z.m.getlogsfn:getlogsfns .z.m.replayperiod; - }; - -loadschema:{[config] - / load the schema file at root; publishable tables are the unkeyed ones with time,sym first (as di.torq.proc.tickerplant) - schemafile:$[`schemafile in key config;resolvedir[apphome[];config`schemafile];apphome[],"/database.q"]; - system "l ",schemafile; - allt:tables[]; - t:allt where {(98h=type value x) and `time`sym~2#cols x} each allt; - if[0=count t;raiseerror[`init;"schema file loaded no publishable tables (need unkeyed with time,sym first): ",schemafile]]; - {@[x;`sym;`g#]} each t; - .z.m.pubtabs:t; - .z.m.tabcols:t!cols each t; - .z.m.schemas:t!{0#value x} each t; - }; - -/ di.eodtime's merged init dict: the log dep plus any timezone config. built with ONE `!` over a general list - -/ amending keys onto enlist[`log]!enlist logdep (as di.torq.proc.tickerplant does) puts a TABLE on the value side, -/ since a one-element list of dicts is a table, and di.eodtime.init then throws 'type for any timezone setting. -/ rolltimeoffset is parsed like multilogperiod (a timespan, a "0D10:00:00" string, or seconds - TOML has no timespan -/ type); a value that cannot be parsed is dropped LOUDLY, at warn, not silently as a non-timespan would otherwise be -eoddeps:{[config;logdep] - ks:`rolltimezone`datatimezone inter key config; - tzvals:astz each config ks; - off:$[`rolltimeoffset in key config;totimespan config`rolltimeoffset;0Nn]; - if[(`rolltimeoffset in key config) and null off; - .z.m.log[`warn][`init;"rolltimeoffset ",(-3!config`rolltimeoffset)," is not a timespan, a timespan string or seconds - ignored"]]; - / a plain join, not ,: - amending a timespan onto a symbol vector in place throws 'type - if[not null off;ks,:`rolltimeoffset;tzvals:tzvals,enlist off]; - vals:(1+count ks)#(::); - vals[0]:logdep; - if[count ks;vals[1+til count ks]:tzvals]; - (`log,ks)!vals - }; - -publishroot:{[] - / the IPC surface a feed and TorQ's .sub.subscribe call by name - use keeps module code in a private namespace - set[`upd;upd]; - set[`.u.upd;upd]; - set[`.u.sub;sub]; - set[`tablelist;tablelist]; - set[`subdetails;subdetails]; - set[`tptype;`segmented]; - }; +/ a relative path is under the app home (TorQ's app config dir) +apppath:{[x] s:$[":"=first s:string x;1_s;s]; hsym`$$[("/"=first s) or 0=count h:getenv`TORQXAPPHOME;s;h,"/",s]}; init:{[config;deps] - / wire the injected deps, read config, load the schema, publish the root IPC surface, open the day's logs and - / schedule the tick job. safe to call again, and to retry after a call that failed part-way - checkdeps deps; - if[.z.m.initdone;teardown[]]; + if[not `log in key deps;'"di.torq.proc.segmentedtp: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.torq.proc.segmentedtp: timer dependency is required - see di.timer"]; + if[not `handlers in key deps;'"di.torq.proc.segmentedtp: handlers dependency is required - see di.torq.handlers"]; + / all settings required + req:`stplgmultilog`stplgmultilogperiod`stplgerrmode`stplgbatchmode`stplgreplayperiod`stplgcustomcsv`stplgerrorlogname; + req,:`sctpchainedtp`sctploggingmode`sctptickerplantname`sctptpconnsleep`sctptpcheckcycles`sctpsubscribeto; + req,:`sctpsubscribesyms`sctpreplay`sctpschema`createlogs; + if[count m:req except key config;'"di.torq.proc.segmentedtp: missing settings: ",", " sv string m]; .z.m.log:deps`log; - .z.m.logwired:1b; .z.m.timer:deps`timer; - .z.m.handlers:deps`handlers; - / a failed earlier init may have left handles open or a job/handler registered (both removals are no-ops if absent) - releaselogs[]; - (.z.m.timer`deletejobs)[enlist jobid]; - (.z.m.handlers`remove)[`.z.exit;`;jobid]; - (.z.m.handlers`remove)[`.z.pc;`;`pubsub]; - readconfig config; - loadschema config; - .z.m.ps:use`di.pubsub; - (.z.m.ps`setsubtables)[.z.m.pubtabs]; - (.z.m.ps`init)[]; - / di.pubsub's subscriber cleanup goes on .z.pc through the handlers dep (di.pubsub no longer binds .z.pc at load - - / that replaced the di.torq.handlers dispatcher, and di.torq.servers' hook with it, moments after di.torq installed it) - (.z.m.handlers`register)[`.z.pc;`;`pubsub;0;.z.m.ps`closesub]; + .z.m.procname:config`procname; + .z.m.proctype:config`proctype; + .z.m.params:config; + (use`di.subscriptions)[`init][config;deps]; + (use`di.pubsub)[`init][enlist[`log]!enlist deps`log]; + r:deps[`handlers]`register; + r[`.z.pc;`;`stpps;0j;.stpps.closesub]; + .z.m.os:use`di.os; .z.m.eod:use`di.eodtime; - (.z.m.eod`init)[eoddeps[config;.z.m.log]]; - .z.m.tp:use`di.tplogmgr; - .z.m.custommode:(`symbol$())!`symbol$(); - if[.z.m.multilog=`custom;loadcustom config]; - .z.m.seqnum:0; - publishroot[]; - startday[]; - (.z.m.timer`addjob)[jobid;tick;();.z.m.tickinterval;1h;jobopts]; - (.z.m.handlers`register)[`.z.exit;`;jobid;0;exithandler]; - msg:"initialised, multilog=",(string .z.m.multilog),", batchmode=",string .z.m.batchmode; - .z.m.log[`info][`segmentedtp;msg,", tables=",", " sv string .z.m.pubtabs]; - / written last: a throw anywhere above leaves the module uninitialised, so a retry is a full init, not a re-init - .z.m.initdone:1b; - }; - -getapimeta:{[] - / this module's api metadata, one row per CALLABLE API function, for di.torq to register with di.api. init and - / getapimeta are plumbing di.torq calls by convention and are deliberately not listed. names are bare. - :flip `name`public`descrip`params`return!flip( - (`upd; 1b; "log and publish a feed update under the batch mode"; "[symbol|symbol list: t; list|table: x]"; "null"); - (`tablelist; 1b; "the publishable tables"; "[]"; "symbol list"); - (`subdetails; 1b; "subscribe the caller; return schemas and replay details"; "[symbol: tabs; symbols|null: instruments]"; "dict"); - (`readcustomcsv; 1b; "read a table,mode csv into a custom mode dict"; "[symbol|string: path]"; "dict: table!mode"); - (`setcustommode; 1b; "replace the custom log assignment and reopen the logs"; "[dict: table!mode]"; "null"); - (`getcounts; 1b; "per-table counted and pending counts, plus the seqnum"; "[]"; "dict"); - (`teardown; 1b; "close every log; remove the tick job and .z.exit handler"; "[]"; "null")); - }; + .z.m.eod.init[(enlist[`log]!enlist deps`log),$[`eodtime in key config;config`eodtime;()!()]]; + if[`stplgkdbtplog in key config;.stplg.kdbtplog:tosym config`stplgkdbtplog]; + .stplg.multilog:tosym config`stplgmultilog; + .stplg.multilogperiod:config`stplgmultilogperiod; + .stplg.errmode:config`stplgerrmode; + .stplg.batchmode:tosym config`stplgbatchmode; + .stplg.replayperiod:tosym config`stplgreplayperiod; + .stplg.customcsv:apppath tosym config`stplgcustomcsv; + .stplg.errorlogname:tosym config`stplgerrorlogname; + .sctp.chainedtp:config`sctpchainedtp; + .sctp.loggingmode:tosym config`sctploggingmode; + .sctp.tickerplantname:tosym config`sctptickerplantname; + .sctp.tpconnsleep:config`sctptpconnsleep; + .sctp.tpcheckcycles:config`sctptpcheckcycles; + .sctp.subscribeto:tosym config`sctpsubscribeto; + .sctp.subscribesyms:tosym config`sctpsubscribesyms; + .sctp.replay:config`sctpreplay; + .sctp.schema:config`sctpschema; + set[`createlogs;config`createlogs]; + / subscribers replay from the parent's logs + if[.sctp.loggingmode=`parent;.stplg.replaylog:{[t] .sctp.tph (`.stplg.replaylog; t)}]; + / singular or tabular: no intraday roll + if[.stplg.multilog in `singular`tabular;.stplg.multilogperiod:1D]; + / custom: logging mode per table + if[.stplg.multilog~`custom; + @[{.stplg.custommode:1_(!) . ("SS";",")0: x};.stplg.customcsv; + {.z.m.log[`error][`stp;m:"failed to load custom mode csv ",string .stplg.customcsv];'"di.torq.proc.segmentedtp: ",m}]]; + / die if the main STP dies + r[`.z.pc;`;`sctp;0j;{[x] if[.sctp.chainedtp;if[.sctp.tph=x;.z.m.log[`error][`.z.pc;"lost connection to tickerplant : ",string .sctp.tickerplantname];exit 1]]}]; + / close logs on clean exit + r[`.z.exit;`;`stplg;0j;{[x] + if[not x~0i;.z.m.log[`error][`stpexit;"Bad exit!"];:()]; + .z.m.log[`info][`stpexit;"Exiting process"]; + if[.stplg.batchmode=`memorybatch; + .z.m.log[`info][`stpexit;"STP shutdown unexpectedly, batchmode = `memorybatch, therefore flushing any remaining data to the on-disk log file"]; + .stplg.zts.memorybatch[]; + .z.m.log[`info][`stpexit;"Complete!"]]; + if[.sctp.chainedtp and not .sctp.loggingmode=`create;:()]; + .z.m.log[`info][`stpexit;"Closing off log files"]; + .stpm.updmeta[.stplg.multilog][`close;.stpps.t;.z.p]; + .stplg.closelog each .stpps.t}]; + (`..setup)[.stplg.batchmode]; + / chained: subscribe to the main STP; otherwise load the schema file + $[.sctp.chainedtp;.sctp.init[];(`..loadschemas)[]]; + (`..generateschemas)[]; + / again after di.torq's .ps.initialise, which registers every root table + if[`addinitlist in key `.proc;.proc.addinitlist(`generateschemas;`)]; + .stplg.stopped:0b; + .stplg.init[string .z.m.procname]; + } + +/ subscribers use this to determine what type of process they are talking to +@[`.;`tptype;:;`segmented]; + +@[`.;`tablelist;:;{.stpps.t}]; + +/ subscribers who want to replay need this info +@[`.;`subdetails;:;{[tabs;instruments] + `schemalist`logfilelist`rowcounts`date`logdir!(.ps.subscribe\:[tabs;instruments];.stplg.replaylog[tabs];tabs#.stplg `rowcount;.z.m.eod.getd[];.stplg.kdbtplog) + }]; + +/ table and schema information and default table upd functions +@[`.;`generateschemas;:;{ + .stpps.init[tables[] except `currlog`heartbeat`logmsg`svrstoload]; + .stpps.attrstrip[.stpps.t]; + / table upd functions attach the current timestamp; chained they do nothing + $[.sctp.chainedtp; + .stplg.updtab:(.stpps.t!(count .stpps.t)#{[x;y] x}),.stplg.updtab; + .stplg.updtab:(.stpps.t!(count .stpps.t)#{(enlist(count first x)#y),x}),.stplg.updtab + ] + }]; + +/ load in schema file and kill proc if not present +@[`.;`loadschemas;:;{ + if[not `schemafile in key .z.m.params;.z.m.log[`error][`loadschema;"Schema file required!"];exit 1]; + @[{system"l ",x};raze .z.m.params[`schemafile];{.z.m.log[`error][`loadschema;"Failed to load schema file!"];exit 1}]; + }]; + +/ upd and zts behaviour from the batch mode +@[`.;`setup;:;{[batch] + if[not all batch in/: key'[.stplg`upd`zts];'"mode ",(string batch)," must be defined in both .stplg.upd and .stplg.zts"]; + chainmode:$[.sctp.chainedtp;`chained;`def]; + .stplg.updmsg:.stplg.upd[batch]; + .stplg.ts:.stplg.zts[batch]; + .u.upd:.stpps.upd[chainmode]; + / 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]; + / error mode: failed updates go to a separate log + if[.stplg.errmode; + .stp.upd:.u.upd; + .u.upd:{[t;x] .[.stp.upd;(t;x);{.stplg.badmsg[x;y;z]}[;t;x]]} + ]; + }]; diff --git a/di/torq/proc/segmentedtp/stplog.q b/di/torq/proc/segmentedtp/stplog.q new file mode 100644 index 00000000..78c6c741 --- /dev/null +++ b/di/torq/proc/segmentedtp/stplog.q @@ -0,0 +1,235 @@ +/ periodic tp logging + +/ live logs and handles to logs for each table +@[`.;`currlog;:;([tbl:`symbol$()]logname:`symbol$();handle:`int$())]; + +/ view of log file handles for faster lookups +value"loghandles::exec tbl!handle from currlog"; + +/ log root; config stplgkdbtplog overrides it +.stplg.kdbtplog:`$getenv`KDBTPLOG + +/ create log directory `:stplogs/date/tabname_time +.stplg.createdld:{[name;date] + if[not count dir:hsym .stplg.kdbtplog;.z.m.log[`error][`stp;"log directory not defined"];exit 1]; + .z.m.os[`mkdir] dir; + .z.m.os[`mkdir] .stplg.dldir:` sv dir,`$raze/[string name,"_",date]; + }; + +.stplg.gentimeformat:{(raze string "dv"$x) except ".:"}; + +/ tabperiod: one log per table, rolled periodically +.stplg.logname.tabperiod:{[dir;tab;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";tab),.stplg.gentimeformat[p]) }; + +/ singular: one log, rolled daily +.stplg.logname.singular:{[dir;tab;p] ` sv (hsym dir;`$raze string .z.m.procname,"_",.stplg.gentimeformat[p]) }; + +/ periodic: one log, rolled periodically +.stplg.logname.periodic:{[dir;tab;p] ` sv (hsym dir;`$raze string .z.m.procname,"_periodic",.stplg.gentimeformat[p]) }; + +/ tabular: one log per table, rolled daily +.stplg.logname.tabular:{[dir;tab;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";tab),.stplg.gentimeformat[p]) }; + +/ custom: mode per table from the custom csv; tables not in it are not logged +.stplg.logname.custom:{[dir;tab;p] .stplg.logname[.stplg.custommode tab][dir;tab;p] }; + +.stplg.logname.error:{[dir;ename;p] ` sv (hsym dir;`$raze string (.z.m.procname;"_";ename),.stplg.gentimeformat[p]) }; + +/ upd and timer functions per batch mode; pre-existing definitions kept +.stplg.upd:@[value;`.stplg.upd;enlist[`]!enlist ()]; +.stplg.zts:@[value;`.stplg.zts;enlist[`]!enlist ()]; + +/ functions to add columns on updates +.stplg.updtab:@[value;`.stplg.updtab;enlist[`]!enlist {(enlist(count first x)#y),x}] + +/ memorybatch: insert in memory; write, publish and count on the timer +.stplg.upd[`memorybatch]:{[t;x;now] + t insert .stplg.updtab[t] . (x;now); + }; + +.stplg.zts[`memorybatch]:{ + {[t] + if[count value t; + `..loghandles[t] enlist (`upd;t;value flip value t); + @[`.stplg.msgcount;t;+;1]; + @[`.stplg.rowcount;t;+;count value t]; + .stpps.pubclear[t]]; + }each .stpps.t; + }; + +/ defaultbatch: write immediately, publish on the timer +.stplg.upd[`defaultbatch]:{[t;x;now] + t insert x:.stplg.updtab[t] . (x;now); + `..loghandles[t] enlist(`upd;t;x); + @[`.stplg.tmpmsgcount;t;+;1]; + @[`.stplg.tmprowcount;t;+;count first x]; + }; + +.stplg.zts[`defaultbatch]:{ + .stpps.pubclear[.stpps.t]; + .stplg.msgcount+:.stplg.tmpmsgcount; + .stplg.rowcount+:.stplg.tmprowcount; + .stplg.tmpmsgcount:.stplg.tmprowcount:()!(); + }; + +/ immediate: write and publish immediately +.stplg.upd[`immediate]:{[t;x;now] + x:.stplg.updtab[t] . (x;now); + `..loghandles[t] enlist(`upd;t;x); + x:$[0h>type last x;enlist;flip] .stpps.tabcols[t]!x; + @[`.stplg.msgcount;t;+;1]; + @[`.stplg.rowcount;t;+;count x]; + .stpps.pub[t;x] + }; + +.stplg.zts[`immediate]:{} + +/ logcounts and lognames for client replay +.stplg.replaylog:{[t] + .stplg.getlogs[.stplg.replayperiod][t] + } + +.stplg.getlogs:enlist[`]!enlist () + +/ period: logs for the current logging period +.stplg.getlogs[`period]:{[t] + distinct flip (.stplg.msgcount;exec tbl!logname from `..currlog where tbl in t)@\:t + }; + +/ day: all of today's logs; closed logs count 0W +.stplg.getlogs[`day]:{[t] + lnames:select seq,tbls,logname,msgcount:0Wj from .stpm.metatable where any each tbls in\: t; + lnames:update msgcount:sum each .stplg.msgcount[tbls] from lnames where seq=.stplg.i; + flip value exec `long$msgcount,logname from lnames + }; + +/ open log for a table at the start of a logging period +.stplg.openlog:{[multilog;dir;tab;p] + lname:.stplg.logname[multilog][dir;tab;p]; + .z.m.log[`info][`openlog;"opening logfile: ",string lname]; + h:$[(notexists:not type key lname)or null h0:exec first handle from `..currlog where logname=lname; + [if[notexists;.[lname;();:;()]];hopen lname]; + h0 + ]; + `..currlog upsert (tab;lname;h); + }; + +/ error log for failed updates in error mode +.stplg.openlogerr:{[dir] + lname:.[.stplg.logname.error;(dir;.stplg.errorlogname;.z.p+.z.m.eod.getdailyadj[]);{.z.m.log[`error][`openlogerr;"failed to make error log: ",x]}]; + if[not type key lname;.[lname;();:;()]]; + h:@[{hopen x};lname;{.z.m.log[`error][`openlogerr;"failed to open handle to error log with error: ",x]}]; + `..currlog upsert (.stplg.errorlogname;lname;h); + }; + +.stplg.badmsg:{[e;t;x] + .z.m.log[`info][`upd;"Bad message received, error: ",e]; + `..loghandles[.stplg.errorlogname] enlist(`upderr;t;x); + }; + +.stplg.closelog:{[tab] + if[null h:`..currlog[tab;`handle];.z.m.log[`info][`closelog;"no open handle to log file"];:()]; + .z.m.log[`info][`closelog;"closing log file ",string `..currlog[tab;`logname]]; + @[hclose;h;{.z.m.log[`error][`closelog;"handle already closed"]}]; + update handle:0N from `..currlog where tbl=tab; + }; + +/ roll all logs at the end of a logging period +.stplg.rolllog:{[multilog;dir;tabs;p] + .stpm.updmeta[multilog][`close;tabs;p]; + .stplg.closelog each tabs; + @[`.stplg.msgcount;tabs;:;0]; + {[m;d;t] + .[.stplg.openlog;(m;d;t;.stplg.currperiod); + {.z.m.log[`error][`stp;"failed to open log for table ",string[y],": ",x]}[;t]] + }[multilog;dir;]each tabs; + .stpm.updmeta[multilog][`open;tabs;p]; + }; + +/ process data sent at endofday/endofperiod +.stplg.endofdaydata:@[value;`.stplg.endofdaydata;{ {`proctype`procname`tables!(.z.m.proctype;.z.m.procname;.stpps.t)} }]; + +/ chained end of period: pass on to subscribers; roll logs in create mode +.stplg.endofperiod:{[currentpd;nextpd;data] + .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`endofperiod;"executing end of period for ",.Q.s1 `currentperiod`nextperiod!(currentpd;nextpd)]; + .stpps.endp[currentpd;nextpd;data]; + .stplg.currperiod:nextpd; + if[.sctp.loggingmode=`create;.stplg.periodrollover[data]] + }; + +/ end of period: send to subscribers; roll logs unless end of day is due +.stplg.stpeoperiod:{[currentpd;nextpd;data;rolllogs] + .z.m.log[`info][`endofperiod;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`stpeoperiod;"passing on endofperiod message to subscribers"]; + .stpps.endp[currentpd;nextpd;data]; + .stplg.currperiod:.stplg.nextperiod; + if[(data`p)>.stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; + .stplg.stopped:1b;'"next period is in the past"]; + .stplg.getnextendUTC[]; + if[rolllogs;.stplg.periodrollover[data]]; + .z.m.log[`info][`stpeoperiod;"end of period complete, new values for current and next period are ",.Q.s1 (currentpd;nextpd)]; + } + +.stplg.periodrollover:{[data] + .stplg.i+:1; + .stplg.rolllog[.stplg.multilog;.stplg.dldir;.stplg.rolltabs;data`p]; + } + +/ end of day: send to subscribers and roll logs +.stplg.endofday:{[date;data] + .z.m.log[`info][`endofday;"flushing remaining data to subscribers and clearing tables"]; + .stpps.pubclear[.stplg.t]; + .z.m.log[`info][`endofday;"executing end of day for ",.Q.s1 .z.m.eod.getd[]]; + .stpps.end[date;data]; + .stplg.dayrollover[data]; + } + +.stplg.dayrollover:{[data] + .z.m.eod.setnextroll .z.m.eod.getroll data`p; + if[(data`p)>.z.m.eod.getnextroll[]; + .stplg.stopped:1b;'"next roll is in the past"]; + .stplg.getnextendUTC[]; + .z.m.eod.setd 1+.z.m.eod.getd[]; + .stpm.updmeta[.stplg.multilog][`close;.stplg.logtabs;(data`p)+.z.m.eod.getdailyadj[]]; + .stpm.metatable:0#.stpm.metatable; + .stplg.closelog each .stplg.logtabs; + .stplg.init[string .z.m.procname]; + .z.m.log[`info][`dayrollover;"end of day complete, new value for date is ",.Q.s1 .z.m.eod.getd[]]; + } + +.stplg.getnextendUTC:{.stplg.nextendUTC:-1+min(.z.m.eod.getnextroll[];.stplg.nextperiod - .z.m.eod.getdailyadj[])} + +.stplg.checkends:{ + if[.stplg.nextendUTC > x; :()]; + if[.stplg.nextperiod < x1:x+.z.m.eod.getdailyadj[]; .stplg.stpeoperiod[.stplg`currperiod;.stplg`nextperiod;.stplg.endofdaydata[],(enlist `p)!enlist x1;not .z.m.eod.getnextroll[] < x]]; + if[.z.m.eod.getnextroll[] < x;if[.z.m.eod.getd[]<("d"$x)-1;.stplg.stopped:1b;'"more than one day?"]; .stplg.endofday[.z.m.eod.getd[];.stplg.endofdaydata[],(enlist `p)!enlist x]]; + }; + +.stplg.init:{[dbname] + .stplg.t:tables[`.]except `currlog; + .stplg.msgcount:.stplg.rowcount:.stplg.t!count[.stplg.t]#0; + .stplg.tmpmsgcount:.stplg.tmprowcount:(`symbol$())!`long$(); + .stplg.logtabs:$[.stplg.multilog~`custom;key .stplg.custommode;.stplg.t]; + .stplg.rolltabs:$[.stplg.multilog~`custom;.stplg.logtabs except where .stplg.custommode in `tabular`singular;.stplg.t]; + .stplg.currperiod:.stplg.multilogperiod xbar .z.p+.z.m.eod.getdailyadj[]; + .stplg.nextperiod:.stplg.multilogperiod+.stplg.currperiod; + .stplg.getnextendUTC[]; + .stplg.i:1; + .stplg.seqnum:0; + if[(value `..createlogs) or .sctp.loggingmode=`create; + .stplg.createdld[dbname;.z.m.eod.getd[]]; + .stplg.openlog[.stplg.multilog;.stplg.dldir;;.z.p+.z.m.eod.getdailyadj[]]each .stplg.logtabs; + if[.stplg.errmode;.stplg.openlogerr[.stplg.dldir]]; + / read the meta table from disk and continue its sequence + .stpm.metatable:@[get;hsym`$string[.stplg.dldir],"/stpmeta";0#.stpm.metatable]; + .stplg.i:1+ -1|exec max seq from .stpm.metatable; + .stpm.updmeta[.stplg.multilog][`open;.stplg.logtabs;.z.p+.z.m.eod.getdailyadj[]]; + ] + / chained and not creating logs: no log handles + if[.sctp.chainedtp and not .sctp.loggingmode=`create; + `..loghandles set .stplg.t! (count .stplg.t) # enlist (::) + ] + }; diff --git a/di/torq/proc/segmentedtp/stpmeta.q b/di/torq/proc/segmentedtp/stpmeta.q new file mode 100644 index 00000000..f6507db7 --- /dev/null +++ b/di/torq/proc/segmentedtp/stpmeta.q @@ -0,0 +1,42 @@ +/ log file metadata: logs opened, tables feeding each, message counts + +.stpm.metatable:([]seq:`int$();logname:`$();start:`timestamp$();end:`timestamp$();tbls:();msgcount:`int$();schema:();additional:()) + +/ meta update per logging mode, run on log open and close +.stpm.updmeta:enlist[`]!enlist () + +.stpm.updmeta[`tabperiod]:{[x;t;p] + .stpm.getmeta[x;p;;]'[enlist each t;`..currlog[([]tbl:t)]`logname]; + .stpm.setmeta[.stplg.dldir;.stpm.metatable]; + }; + +.stpm.updmeta[`singular]:{[x;t;p] + .stpm.getmeta[x;p;t;`..currlog[first t]`logname]; + .stpm.setmeta[.stplg.dldir;.stpm.metatable]; + }; + +.stpm.updmeta[`periodic]:.stpm.updmeta[`singular] + +.stpm.updmeta[`tabular]:.stpm.updmeta[`tabperiod] + +.stpm.updmeta[`custom]:{[x;t;p] + pertabs:where `periodic=.stplg.custommode; + .stpm.updmeta[`periodic][x;t inter pertabs;p]; + .stpm.updmeta[`tabular][x;t except pertabs;p] + }; + +/ name, start, tables and schema on open; end and message count on close +.stpm.getmeta:{[x;p;t;ln] + if[x~`open; + s:((),t)!(),.stpps.schemas[t]; + `.stpm.metatable upsert (.stplg.i;ln;p;0Np;t;0;s;enlist ()!()); + ]; + if[x~`close; + update end:p,msgcount:sum .stplg.msgcount[t] from `.stpm.metatable where logname = ln + ] + }; + +.stpm.setmeta:{[dir;mt] + t:(hsym`$string[dir],"/stpmeta"); + .[{x set y};(t;mt);{.z.m.log[`error][`setmeta;"Failed to set metatable with error: ",x]}]; + }; diff --git a/di/torq/proc/segmentedtp/stpps.q b/di/torq/proc/segmentedtp/stpps.q new file mode 100644 index 00000000..1705ae99 --- /dev/null +++ b/di/torq/proc/segmentedtp/stpps.q @@ -0,0 +1,29 @@ +/ upd and zts wrapper functions + +/ check for end of day/period and call inner upd +.stpps.upd.def:{[t;x] + if[.stplg.nextendUTC1\"";columns:enlist\""sym,bid\"")]""; hb(`.u.upd;`quote;(`a`b;1 2f))",1,,filtered subscription with where and columns +true,0,0,q,"(`sym`bid;enlist`b)~(cols last first got;exec sym from last first got)",1,,only matching rows and columns published +true,0,0,q,"""next period is in the past""~hb""@[{.stplg.nextperiod:.z.p-2D; .stplg.getnextendUTC[]; .stplg.checkends .z.p};::;::]""",1,,a past next period signals +true,0,0,q,"(1b;`symbol$();60000i)~hb""(.stplg.stopped;stopped;system\""t\"")""",1,,the tick is stopped by flag; no jobs disabled; the process timer is untouched +true,0,0,q,"hb""n:.stplg.nextperiod; tick[]; n~.stplg.nextperiod""",1,,a stopped tick does nothing -comment,,,,,,,period and day rolls -true,0,0,q,periodroll[],1,,end of period closes the segment and rolls to a new file and notifies subscribers and lists the day -true,0,0,q,dayroll[],1,,end of day notifies subscribers and moves to the next day's directory and closes every segment +comment,,,,,,,memorybatch and tabular +run,0,0,q,"hc(`.u.upd;`trade;trd`a`b)",1,,send two trades +true,0,0,q,"(2;0)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"")",1,,held in memory and not logged +run,0,0,q,"hc""tick[]""",1,,timer +true,0,0,q,"(0;1;1;2)~(hc""count trade"";logcount hc""currlog[`trade;`logname]"";hc"".stplg.msgcount`trade"";hc"".stplg.rowcount`trade"")",1,,logged and counted on the timer +true,0,0,q,"(string hc""currlog[`trade;`logname]"") like ""*/stp3_trade2*""",1,,tabular log name -comment,,,,,,,subscriber surface / custom mode / lifecycle -true,0,0,q,subdetailsok[],1,,subdetails returns schemas and replay pairs and rowcounts and date and logdir -true,0,0,q,subbad[],1,,subdetails for only unknown tables throws -true,0,0,q,tablelistok[],1,,tablelist returns the publishable tables -true,0,0,q,readcsvok[],1,,readcustomcsv reads a table/mode csv from a string or symbol path -true,0,0,q,readcsvmissing[],1,,readcustomcsv rejects a missing file -true,0,0,q,readcsvbadmode[],1,,readcustomcsv rejects an unrecognised mode -true,0,0,q,readcsvbadheader[],1,,readcustomcsv rejects a csv without a table/mode header -true,0,0,q,setcustomok[],1,,setcustommode applies a new layout at runtime and reopens logs under it -true,0,0,q,setcustomnotcustom[],1,,setcustommode is rejected outside custom mode -true,0,0,q,setcustomunknown[],1,,setcustommode rejects tables that are not publishable -true,0,0,q,setcustombadmode[],1,,setcustommode rejects an unrecognised mode -true,0,0,q,exitok[],1,,a bad exit leaves logs alone and a clean exit flushes and closes them -true,0,0,q,teardownok[],1,,teardown flushes and closes every file and removes the job and handler -true,0,0,q,afterteardown[],1,,exported functions and the root upd reject calls after teardown +comment,,,,,,,chained +true,0,0,q,"(`quote`trade;1)~hs""(.stpps.t;count select from .sub.SUBSCRIPTIONS where table=`trade,active)""",1,,subscribed to the upstream +true,0,0,q,"waitfor {2=hs""count trade""}",1,,upstream publish arrives +true,0,0,q,"1 2~hs""(.stplg.updtab`trade)[1 2;3]""",1,,chained upd adds no time +run,0,0,q,"hs""tick[]""",1,,timer +true,0,0,q,"(0;1;1)~hs""(count trade;.stplg.msgcount`trade;logcount:{-11!(-2;x)} currlog[`trade;`logname])""",1,,published and logged in create mode +true,0,0,q,"(string hs""currlog[`trade;`logname]"") like ""*/sctp1_"",(string .z.d),""/sctp1_trade2*""",1,,own log in create mode +true,0,0,q,"(`parent;`stp1;`)~hp"".sctp`loggingmode`tickerplantname`subscribeto""",1,,toml-style sctp strings become symbols +true,0,0,q,"(ha"".stplg.replaylog`trade"")~hp"".stplg.replaylog`trade""",1,,parent mode replays the upstream logs +true,0,0,q,"hp""all (::)~/:value loghandles""",1,,parent mode writes no logs -after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs +comment,,,,,,,end of period +run,0,0,q,"eops:(); ha"".stplg.nextperiod:.z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the period end +true,0,0,q,"(1;`proctype`procname`tables`p;`stp1)~(count eops;key last last eops;(last last eops)`procname)",1,,endofperiod sent with process data +true,0,0,q,"(1;4;0)~ha""(.stplg.i;count .stpm.metatable;.stplg.msgcount`trade)""",1,,logs rolled and counts reset +true,0,0,q,"(0W;2)~ha""(first first r;count r:.stplg.replaylog`trade)""",1,,day replay lists the closed log as 0W +true,0,0,q,"1=count ha"".stplg.replayperiod:`period; r:.stplg.replaylog enlist`trade; .stplg.replayperiod:`day; r""",1,,period replay lists the current log only +true,0,0,q,"waitfor {1=hs"".stplg.i""}",1,,chained create mode rolls its logs + +comment,,,,,,,end of day +run,0,0,q,"eods:(); ha""(use`di.eodtime)[`setnextroll] .z.p-0D00:00:01; .stplg.getnextendUTC[]; tick[]""",1,,force the day end +true,0,0,q,"(1;.z.d;`stp1)~(count eods;first first eods;(last first eods)`procname)",1,,endofday sent with date and process data +true,0,0,q,"(.z.d+1;`$"":"",FIXDIR,""/a/stp1_"",string .z.d+1;2)~ha""((use`di.eodtime)[`getd][];.stplg.dldir;count .stpm.metatable)""",1,,date advanced and logs reopened +true,0,0,q,"ha"".z.p<(use`di.eodtime)[`getnextroll][]""",1,,next roll is in the future +true,0,0,q,"waitfor {(.z.d+1)=hs""(use`di.eodtime)[`getd][]""}",1,,chained passes end of day through + +comment,,,,,,,exit +run,0,0,q,"hc(`.u.upd;`trade;trd`x`y); cm:`$(string hc"".stplg.dldir""),""/stpmeta""; cl:hc""currlog[`trade;`logname]""; @[{neg[x]""exit 0"";neg[x][]};hc;()]",1,,send trades then exit cleanly +true,0,0,q,"waitfor {not alive PORTS`c}",1,,process exited +true,0,0,q,"(2;1b)~(logcount cl;all not null exec end from get cm)",1,,memorybatch flushed and logs closed on exit +run,0,0,q,"@[{neg[x]""exit 0"";neg[x][]};ha;()]",1,,upstream exits +true,0,0,q,"waitfor {not any alive each PORTS`s`p}",1,,chained processes exit when the upstream is lost + +after,0,0,q,teardownfixture[],1,,stop the peers and remove the fixture dir diff --git a/di/torq/proc/segmentedtp/test.q b/di/torq/proc/segmentedtp/test.q index d6404df4..a9d02c13 100644 --- a/di/torq/proc/segmentedtp/test.q +++ b/di/torq/proc/segmentedtp/test.q @@ -1,633 +1,65 @@ -/ fixture helpers for di.torq.proc.segmentedtp's unit tests. Assumes cwd is the kdbx-modules repo root. -/ Uses REAL di.pubsub / di.eodtime / di.tplogmgr with a recording mock log, timer and handlers - the timer -/ never runs a cycle, so tick/rolls fire only when a test calls them. Each scenario helper inits the module -/ against its own log dir and returns 1b only if every named check passes; the per-check dict is left in LAST -/ so a failing row can be diagnosed with `show LAST`. Helpers live here because CSV fields cannot hold commas. - -BASE:"/tmp/di_segmentedtp_k4unit"; -MOD:`.m.di.0torq.0proc.0segmentedtp; - -/ read / write module state and reach internal functions -mv:{[n] get .Q.dd[MOD;n]}; -mset:{[n;v] .Q.dd[MOD;n] set v;}; - -chk:{[d] `LAST set d; all value d}; -errmsg:{[f] @[f;::;{x}]}; - -/ 1b only if f throws AND the error names the expected reason - a bare `fail` row would also pass on an -/ unrelated error (a fixture bug), proving nothing about the path under test -throws:{[f;s] r:errmsg f; (10h=type r) and 0",FIXDIR,"/",string[n],".log 2>&1 &"} +waitfor:{[f] d:.z.p+0D00:00:05; while[(.z.ptype c;c;first c]}; -cnt:{[t;col] ct:0!((st`getcounts)[])`tables; first (ct col) where ct[`tbl]=t}; -tf:{[] (mv`gentimeformat) mv`currperiod}; -dayerrname:{[] `$"stp_segmentederrorlogfile",(mv`gentimeformat)"p"$(mv[`eod]`getd)[]}; - -/ open file descriptors of this process pointing exactly at a file (0 once closed) -fdcount:{[f] count @[system;"ls -l /proc/",(string .z.i),"/fd 2>/dev/null | awk '$NF==\"",(1_string f),"\"'";{()}]}; - -/ feed n rows of table t through the published root upd (column-list form, one record each) -feed:{[t;n] {[t;i] upd[t;(`$"S",string i;$[t=`depth;i;1.0*i])]}[t] each til n;}; - -/ truncate a log mid-message -smash:{[f] n:hcount f; f 1: read1 (f;0;n-5);}; - -/ --- init validation --- - -initbadschema:{[] throws[{(st`init)[`kdbtplog`schemafile!("tplog/v";BASE,"/badschema.q");deps[]]};"no publishable tables"]}; -initnotdict:{[] throws[{(st`init)[cfg["tplog/v";()!()];(::)]};"deps must be a dict"]}; -initnolog:{[] throws[{(st`init)[cfg["tplog/v";()!()];`timer`handlers#deps[]]};"log dependency is required"]}; -initnotimer:{[] throws[{(st`init)[cfg["tplog/v";()!()];`log`handlers#deps[]]};"timer dependency is required"]}; -initnohandlers:{[] throws[{(st`init)[cfg["tplog/v";()!()];`log`timer#deps[]]};"handlers dependency is required"]}; -initlogkeys:{[] throws[{(st`init)[cfg["tplog/v";()!()];@[deps[];`log;:;`info`warn#mocklog[]]]};"missing error"]}; -initnokdbtplog:{[] throws[{(st`init)[enlist[`schemafile]!enlist BASE,"/database.q";deps[]]};"kdbtplog is required"]}; -initbad:{[k;v] resetmocks[]; (st`init)[cfg["tplog/v";enlist[k]!enlist v];deps[]]}; -initrejects:{[k;v;s] throws[{[k;v;x] initbad[k;v]}[k;v];s]}; - -badmsgnames:{[] - m:errmsg each ({initbad[`multilog;`hourly]};{initbad[`batchmode;`sometimes]};{initbad[`replayperiod;`prior]}); - all 0.z.p) - }; - -/ a TOML-style string offset is parsed and reaches di.eodtime; a value that cannot be parsed is dropped with a warning -tzstringok:{[] - doinit cfg["tplog/tzs";`rolltimezone`rolltimeoffset!("GMT";"0D10:00:00")]; - nr:(mv[`eod]`getnextroll)[]; - a:enlist[`stringoffset]!enlist 0D10:00=`timespan$(`long$"n"$nr) mod `long$1D; - doinit cfg["tplog/tzb";enlist[`rolltimeoffset]!enlist `notatimespan]; - chk a,`badignored`badwarned!(0D=`timespan$(`long$"n"$(mv[`eod]`getnextroll)[]) mod `long$1D;0abs .z.p-first trade`time; - 2020.01.01D00:00:00=trade[1;`time]; - `C`D~trade[2 3;`sym]; - `E~last trade`sym; - `F~first quote`sym) - }; - -errmodeok:{[] - doinit cfg["tplog/err";()!()]; - upd[`nosuch;(`A;1.0)]; - upd[`trade;(`A;"notafloat")]; - `ERRS set (); - -11!mv`errlog; - chk `twoerrs`unknowntable`badtype`warned!( - 2=count ERRS; - `nosuch~first first ERRS; - `trade~first last ERRS; - 2=count select from calls where lvl=`warn,ctx=`upd) - }; - -noerrmode:{[] - doinit cfg["tplog/noerr";`errmode`batchmode!(0b;`immediate)]; - throws[{upd[`nosuch;(`A;1.0)]};"not a publishable table"] - }; - -nologsok:{[] - doinit cfg["tplog/nologs";`createlogs`errmode`batchmode!(0b;0b;`immediate)]; - r:@[{feed[`trade;2];1b};::;{x}]; - chk `nothrow`counted`nodir`nologs!(1b~r;2=cnt[`trade;`msgcount];()~key hsym`$BASE,"/tplog/nologs";0=count mv`currlog) - }; - -unlistedok:{[] - doinit cfg["tplog/unlisted";`multilog`errmode`batchmode`customcsv!(`custom;0b;`immediate;"partial.csv")]; - r:@[{feed[`quote;2];1b};::;{x}]; - chk `nothrow`counted`noquotelog`tradelog!(1b~r;2=cnt[`quote;`msgcount];not `quote in exec tbl from mv`currlog;`trade in exec tbl from mv`currlog) - }; - -/ --- fixes --- - -fix1:{[] - dir:"tplog/fix1"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - feed[`trade;3]; - orig:fileof`trade; - (st`teardown)[]; - smash orig; - osize:hcount orig; - doinit c; - g:fileof`trade; - m:metaof dir; - a:`usesgood`goodcount`basecount`warned`origuntouched`metarenamed!( - g~(mv`goodname) orig; - 2=logcount g; - 2=(mv`basecount) g; - 0.z.p+(mv[`eod]`getdailyadj)[]) - }; - -fix3:{[] - dir:"tplog/fix3"; - doinit cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - olderr:mv`errlog; - oldtrade:fileof`trade; - olddir:daydir dir; - a:enlist[`erropen]!enlist 1=fdcount olderr; - (mv[`eod]`setnextroll)[.z.p-1]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - chk a,`errclosed`tradeclosed`newerropen`newerrfile`oldmetaclosed!( - 0=fdcount olderr; - 0=fdcount oldtrade; - 1=fdcount mv`errlog; - not olderr~mv`errlog; - all not null (get hsym`$olddir,"/stpmeta")`end) - }; - -fix4resume:{[] - dir:"tplog/fix4"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - feed[`trade;2]; - m0:metaof dir; - / an unclean exit: handles abandoned, segments never closed - (mv`releaselogs)[]; - mset[`initdone;0b]; - doinit c; - m:metaof dir; - chk `norowadded`stillopen`seqkept`countresumed!(count[m0]=count m;all null m`end;(m0`seq)~m`seq;2=cnt[`trade;`msgcount]+(mv`basecount) fileof`trade) - }; - -fix4orphan:{[] - dir:"tplog/fix4o"; - c:cfg[dir;`multilog`batchmode!(`tabular;`immediate)]; - doinit c; - (st`teardown)[]; - ghost:hsym`$daydir[dir],"/stp_ghost20000101000000"; - m:metaof dir; - m:m,enlist `seq`logname`start`end`tbls`msgcount`schema`additional!(0i;ghost;.z.p;0Np;enlist`trade;5i;()!();()!()); - (hsym`$daydir[dir],"/stpmeta") set m; - doinit c; - n:metaof dir; - r:first select from n where logname=ghost; - chk `closed`nullcount`warned`othersresumed!( - not null r`end; - null r`msgcount; - 0ghost) - }; - -fix5:{[] - doinit cfg["tplog/fix5";`multilog`batchmode`replayperiod!(`singular;`immediate;`period)]; - feed[`trade;3]; - feed[`quote;2]; - f:fileof`trade; - both:(mv`getlogsperiod)`trade`quote; - one:(mv`getlogsperiod) enlist`trade; - sd:(st`subdetails)[enlist`trade;`]; - (use`di.pubsub)[`closesub][0]; - chk `sharedfile`onepair`summed`tradeonly`subdetails!( - f~fileof`quote; - 1=count both; - (5;f)~first both; - (5;f)~first one; - (enlist(5;f))~sd`logfilelist) - }; - -fix6:{[] - dir:"tplog/fix6"; - doinit cfg[dir;`multilog`batchmode`customcsv!(`custom;`immediate;"custom.csv")]; - m:metaof dir; - chk `tworows`shared`pertable!( - 2=count m; - 1=count select from m where {`quote`trade~asc x} each tbls; - 1=count select from m where {(enlist`depth)~x} each tbls) - }; - -/ --- rolls --- - -periodroll:{[] - dir:"tplog/proll"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;3]; - old:fileof`trade; - oldseq:mv`seq; - oldcp:mv`currperiod; - `EOP set (); - (st`subdetails)[`;`]; - np:.z.p+(mv[`eod]`getdailyadj)[]-0D00:00:01; - mset[`nextperiod;np]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - (use`di.pubsub)[`closesub][0]; - new:fileof`trade; - oldrow:first select from metaof[dir] where logname=old; - day:(mv`getlogsday) enlist`trade; - chk `newfile`oldclosed`oldcount`reset`seq`subscriber`daylist!( - not old~new; - not null oldrow`end; - 3i=oldrow`msgcount; - 0=cnt[`trade;`msgcount]; - (1i+oldseq)=mv`seq; - (oldcp;np)~2#EOP; - ((0W;old);(0;new))~day) - }; - -dayroll:{[] - dir:"tplog/droll"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;2]; - d0:(mv[`eod]`getd)[]; - olddir:daydir dir; - old:fileof`trade; - `EOD set 0Nd; - (st`subdetails)[`;`]; - (mv[`eod]`setnextroll)[.z.p-1]; - mset[`nextendutc;.z.p-1]; - (mv`tick)[]; - (use`di.pubsub)[`closesub][0]; - chk `subscriber`nextdate`newdir`oldclosed`reset`oldfdclosed!( - d0~EOD; - (d0+1)=(mv[`eod]`getd)[]; - not ()~key hsym`$daydir dir; - all not null (get hsym`$olddir,"/stpmeta")`end; - 0=cnt[`trade;`msgcount]; - 0=fdcount old) - }; - -/ --- subscriber surface, custom mode, lifecycle --- - -subdetailsok:{[] - dir:"tplog/subd"; - doinit cfg[dir;enlist[`batchmode]!enlist`immediate]; - feed[`trade;4]; - feed[`quote;1]; - sd:(st`subdetails)[`;`]; - (use`di.pubsub)[`closesub][0]; - chk `keys`schemas`rowcounts`pairs`tradepair`logdir`date!( - `schemalist`logfilelist`rowcounts`date`logdir~key sd; - (asc `trade`quote`depth)~asc first each sd`schemalist; - 4 1~sd[`rowcounts]`trade`quote; - all {(-7h=type x 0) and -11h=type x 1} each sd`logfilelist; - (4;fileof`trade) in sd`logfilelist; - (`$BASE,"/",dir)~sd`logdir; - (mv[`eod]`getd)[]~sd`date) - }; - -subbad:{[] - doinit cfg["tplog/subbad";()!()]; - throws[{(st`subdetails)[enlist`nosuch;`]};"not available"] - }; - -tablelistok:{[] - doinit cfg["tplog/tablelist";()!()]; - `depth`quote`trade~asc (st`tablelist)[] - }; - -readcsvok:{[] - ex:`trade`quote`depth!`singular`singular`tabperiod; - chk `string`symbol!(ex~(st`readcustomcsv) BASE,"/custom.csv";ex~(st`readcustomcsv) hsym`$BASE,"/custom.csv") - }; -readcsvmissing:{[] throws[{(st`readcustomcsv) BASE,"/nosuch.csv"};"not found"]}; -readcsvbadmode:{[] throws[{(st`readcustomcsv) BASE,"/badmode.csv"};"unrecognised mode"]}; -readcsvbadheader:{[] throws[{(st`readcustomcsv) BASE,"/badheader.csv"};"table,mode header"]}; - -setcustomok:{[] - dir:"tplog/setcustom"; - doinit cfg[dir;`multilog`batchmode!(`custom;`immediate)]; - a:`warned`nologs!(0/dev/null";{}]} each PIDS; - system "sleep 0.5"; - system "rm -rf ",IBASE; - }; - -/ ask the OS for a free port, then release it for the child to bind -freeport:{[] system"p 0W"; p:system"p"; system"p 0"; p}; - -tryopen:{[p] @[{hopen (`$":localhost:",string x;500)};p;0Ni]}; - -waitopen:{[p;n] - if[n<=0;:0Ni]; - if[not null h:tryopen p;:h]; - system "sleep 0.3"; - waitopen[p;n-1] - }; - -startchild:{[dir;args] - p:freeport[]; - cmd:QBIN," ",CHILD," -q -p ",(string p)," -kdbtplog ",dir," -schemafile ",IBASE,"/database.q ",args; - pid:"J"$first system cmd," >",IBASE,"/child.log 2>&1 & echo $!"; - `PIDS set PIDS,pid; - `pid`port`h!(pid;p;waitopen[p;40]) - }; - -kill9:{[c] - @[system;"kill -9 ",(string c`pid)," 2>/dev/null";{}]; - @[hclose;c`h;{}]; - system "sleep 0.5"; - }; - -/ n async updates then a sync round-trip, so every message has been processed before the helper returns -cfeed:{[c;t;n] - {[c;t;i] neg[c`h](`upd;t;(`$"S",string i;1.0*i))}[c;t] each til n; - c[`h]"::"; - }; - -cfile:{[c;t] c[`h] "exec first logname from ",SM,"currlog where tbl=`",string t}; -cpairs:{[c] c[`h] SM,"getlogsperiod`trade`quote"}; -cmetafile:{[c] hsym`$(c[`h] SM,"dldir"),"/stpmeta"}; - -smash:{[f] n:hcount f; f 1: read1 (f;0;n-5);}; - -/ open file descriptors of a process whose target contains a path -fdsfor:{[pid;f] c:@[system;"ls -l /proc/",(string pid),"/fd 2>/dev/null";{()}]; sum 0 di.torq.init -> settings cascade -> startbuiltin --- - -/ the kdbx-modules root that holds di/torq (two levels above the di.torq module dir) -torqxhome:{[] p:.Q.m.mp`di.torq; p:$[10h=type p;p;string p]; p:$[":"=first p;1_p;p]; "/" sv -2_"/" vs p}; - -stackapp:{[] - / a minimal app: schema, process.csv, and a proctype-tier toml with a string-valued timespan and booleans - / (singular forces the period to 1D whatever the toml says - the assertion below checks that too) - app:IBASE,"/app"; - system "mkdir -p ",app,"/appconfig/settings"; - (hsym`$app,"/database.q") 0: ( - "trade:([]time:`timestamp$();sym:`g#`symbol$();price:`float$())"; - "quote:([]time:`timestamp$();sym:`g#`symbol$();bid:`float$())"); - (hsym`$app,"/appconfig/settings/default.toml") 0: enlist "# app defaults"; - (hsym`$app,"/appconfig/settings/segmentedtp.toml") 0: ( - "kdbtplog = \"stplogs\"";"multilog = \"singular\"";"batchmode = \"immediate\""; - "multilogperiod = \"0D01:00:00\"";"errmode = true";"tickinterval = 1"); - app}; - -startstack:{[app;port] - / launch exactly as torqx.sh does: QINIT=torqx_init.q with explicit identity and a stack id - setenv[`TORQXHOME;torqxhome[]]; - setenv[`TORQXAPPCONFIG;app,"/appconfig"]; - setenv[`TORQXAPPHOME;app]; - setenv[`TORQXDATAHOME;app]; - (hsym`$app,"/appconfig/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string port),",segmentedtp,stp1"); - cmd:"QINIT=",torqxhome[],"/di/torq/bin/torqx_init.q ",QBIN," -q -p ",(string port)," -proctype segmentedtp -procname stp1 -torqxstackid itest"; - pid:"J"$first system cmd," >",IBASE,"/stack.log 2>&1 & echo $!"; - `PIDS set PIDS,pid; - `pid`port`h!(pid;port;waitopen[port;40])}; - -stackboot:{[] - / kdb-x abandons a QINIT script silently at the first error and leaves the process at its prompt, so a boot - / failure looks like a running process: assert the module's observable effects, never just "it came up" - app:stackapp[]; - c:startstack[app;freeport[]]; - if[null c`h;:chk enlist[`childup]!enlist 0b]; - a:`tptype`updpublished`identity`cascade`jobopts`exithandler!( - `segmented~c[`h]"tptype"; - c[`h]"`upd in key `."; - (`segmentedtp;`stp1)~c[`h]"(",SM,"proctype;",SM,"procname)"; - (`singular;`immediate;1D;1b)~c[`h]"(",SM,"multilog;",SM,"batchmode;",SM,"multilogperiod;",SM,"errmode)"; - 0b~c[`h]"exec first disableonfail from .m.di.0timer.jobs where id=`segmentedtp"; - `segmentedtp in c[`h]"exec name from (use`di.torq.handlers)[`list]`.z.exit"); - cfeed[c;`trade;3]; - cfeed[c;`quote;2]; - f:cfile[c;`trade]; - metaf:cmetafile c; - a:a,`shared`counted!(f~cfile[c;`quote];(enlist(5;f))~cpairs c); - @[c`h;"exit 0";{}]; - system "sleep 1"; - chk a,enlist[`cleanexitclosed]!enlist all not null (get metaf)`end - }; diff --git a/di/torq/proc/segmentedtp/test_integration_child.q b/di/torq/proc/segmentedtp/test_integration_child.q deleted file mode 100644 index c3839678..00000000 --- a/di/torq/proc/segmentedtp/test_integration_child.q +++ /dev/null @@ -1,24 +0,0 @@ -/ child process for test_integration.csv - not a test file itself; test_integration.q launches it. -/ Runs di.torq.proc.segmentedtp wired to the REAL di.timer, di.torq.handlers and di.util.log (built as di.torq -/ builds them). Every -flag value on the command line becomes a config setting as a STRING (as a .toml or a -/ command-line override would deliver it), so the module's own coercions are exercised: -kdbtplog -schemafile -/ -multilog -batchmode -multilogperiod -rolltimeoffset -replayperiod -tickinterval ... - -o:.Q.opt .z.x; -cfg:(key o)!first each value o; -if[not `tickinterval in key cfg;cfg[`tickinterval]:1]; -if[`rolltimeoffset in key cfg;cfg[`rolltimeoffset]:"N"$cfg`rolltimeoffset]; - -lg:use`di.util.log; -logdep:`info`warn`error!(lg`info;lg`warn;lg`error); - -tm:use`di.timer; -tm[`init][()!()]; -timerdep:`addjob`deletejobs`enablejobs`disablejobs`getactivejobs!((tm`addjob)`custom;tm`deletejobs;tm`enablejobs;tm`disablejobs;tm`getactivejobs); - -hz:use`di.torq.handlers; -hz[`init][enlist[`log]!enlist logdep]; -handlersdep:`register`remove`list!(hz`register;hz`remove;hz`list); - -sp:use`di.torq.proc.segmentedtp; -sp[`init][cfg;`log`timer`handlers!(logdep;timerdep;handlersdep)]; diff --git a/di/torq/proc/tickerlogreplay/VERSION b/di/torq/proc/tickerlogreplay/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/torq/proc/tickerlogreplay/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/torq/proc/tickerlogreplay/deps.toml b/di/torq/proc/tickerlogreplay/deps.toml new file mode 100644 index 00000000..8181643f --- /dev/null +++ b/di/torq/proc/tickerlogreplay/deps.toml @@ -0,0 +1,6 @@ +# Peer modules di.torq.proc.tickerlogreplay `use`s (see di/torq/depcheck/depcheck.md). +[dependencies] +"di.tplog" = "0.1.0" +"di.merge" = "0.2.0" +"di.dbwrite" = "0.2.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/tickerlogreplay/init.q b/di/torq/proc/tickerlogreplay/init.q new file mode 100644 index 00000000..8abf82af --- /dev/null +++ b/di/torq/proc/tickerlogreplay/init.q @@ -0,0 +1,8 @@ +\l ::tickerlogreplay.q + +version:first read0`:::VERSION + +/ the default sort config +sortdefault:("SSSB";enlist",")0:read0`:::sort.csv + +export:([init;version]) diff --git a/di/torq/proc/tickerlogreplay/sort.csv b/di/torq/proc/tickerlogreplay/sort.csv new file mode 100644 index 00000000..8ab1b9c3 --- /dev/null +++ b/di/torq/proc/tickerlogreplay/sort.csv @@ -0,0 +1,3 @@ +tabname,att,column,sort +default,p,sym,1 +default,,time,1 diff --git a/di/torq/proc/tickerlogreplay/test.csv b/di/torq/proc/tickerlogreplay/test.csv new file mode 100644 index 00000000..aea7fb3f --- /dev/null +++ b/di/torq/proc/tickerlogreplay/test.csv @@ -0,0 +1,118 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,tlr:use`di.torq.proc.tickerlogreplay,1,,load module +before,0,0,q,"system ""l di/torq/proc/tickerlogreplay/test.q""",1,,load fixture helpers +before,0,0,q,setupfixture[],1,,write the schema and a plain log; run a segmentedtp to write segmented logs + +comment,,,,,,,settings +true,0,0,q,all `savedownmanipulation`manipulate`postreplay in key .save,1,,save helpers defined +fail,0,0,q,"tlr.init[()!();()!()]",1,,init without log must error + +comment,,,,,,,plain log +true,0,0,q,0=replay sect plain "()!()",1,,a full replay exits 0 +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,every message replayed into a date partition +true,0,0,q,`a`b`c~syms[D;`trade],1,,the default sort csv sorts by sym +true,0,0,q,`p~attr hdb[D;`trade]`sym,1,,and applies p# to sym +true,0,0,q,"logged ""*replayed data into tables with the following counts: trade = 3; quote = 1*""",1,,table counts logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`tablelist]!enlist enlist`trade",1,,replay one table +true,0,0,q,(3;0)~(rows[D;`trade];rows[D;`quote]),1,,other tables are not saved +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "`firstmessage`lastmessage!1 1",1,,replay message 1 only +true,0,0,q,(0;1)~(rows[D;`trade];rows[D;`quote]),1,,only the quote message replayed; trade saved empty +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`messagechunks]!enlist 1",1,,save every message +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,chunked saves append +true,0,0,q,"logged ""*has been exceeded. Saving down*""",1,,chunk saves logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`messagechunks]!enlist -1",1,,negative chunks only track +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,tables saved at the end +true,0,0,q,"logged ""*Total message count so far is 3*""",1,,progress logged +run,0,0,q,clearhdb[],1,, +true,0,0,q,0=replay sect plain "enlist[`basicmode]!enlist 1b",1,,basic mode +true,0,0,q,(3;1)~(rows[D;`trade];rows[D;`quote]),1,,saved with .Q.hdpf +run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay sect plain ""enlist[`sortcsv]!enlist "",hp""timesort.csv""",1,,replay with a sort csv +true,0,0,q,(`b`a`c;`)~(syms[D;`trade];attr hdb[D;`trade]`sym),1,,the sort csv sorts by time with no attribute +run,0,0,q,clearhdb[],1,, +true,0,0,q,"0=replay sect plain ""enlist[`compression]!enlist 17 2 6""",1,,replay with compression +true,0,0,q,"0",FIXDIR,"/run.log 2>&1; echo $?"} +/ replay with q lines run before use and a config from a q expression; an init error exits 3 +replayp:{[pre;cfg] runq( + enlist["lg:`info`warn`error!({[c;m] -1 \"I \",string[c],\": \",m};{[c;m] -1 \"W \",string[c],\": \",m};{[c;m] -1 \"E \",string[c],\": \",m})"],pre,( + "r:use`di.torq.proc.tickerlogreplay"; + "@[r.init[;enlist[`log]!enlist lg];",cfg,";{-1 \"ERR \",x;exit 3}]"; + "exit 0"))} +replay:replayp[()] +/ replay settings for the plain log, with overrides +plain:{[x] "(`schemafile`hdbdir`tplogfile`segmentedmode!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",FIXDIR,"/tplog",D,"\";0b)),",x} +sect:{[x] "((use`di.torq.config)[`parsefile] \"di/torq/settings/tickerlogreplay.q\"),",x} +ran:{[x] read0 fp"run.log"} +logged:{[s] any ran[] like s} +/ was a log named in the list of logs to replay +replayed:{[s] any (ran[] where ran[] like "*Replaying the following log*") like "*",s,"*"} + +/ an hdb table, or () if absent +hdb:{[p;t] @[get;fp"hdb/",p,"/",string[t],"/";()]} +rows:{[p;t] count hdb[p;t]} +syms:{[p;t] (get fp"hdb/sym") hdb[p;t]`sym} +clearhdb:{system "rm -rf ",FIXDIR,"/hdb ",FIXDIR,"/tmp"} + +setupfixture:{[] + system "rm -rf ",FIXDIR; system "mkdir -p ",FIXDIR; + fp["schema.q"] 0: ( + "trade:([]time:`timestamp$();sym:`g#`symbol$();price:`float$();size:`int$())"; + "quote:([]time:`timestamp$();sym:`g#`symbol$();bid:`float$())"); + / plain log: trade b a, quote a, trade c + h:hopen fp["tplog",D] set (); + h enlist(`upd;`trade;(2026.10.01D10:00:00 2026.10.01D10:00:01;`b`a;1 2f;10 20i)); + h enlist(`upd;`quote;(enlist 2026.10.01D10:00:02;enlist`a;enlist 3f)); + h enlist(`upd;`trade;(enlist 2026.10.01D10:00:03;enlist`c;enlist 4f;enlist 40i)); + hclose h; + / a sort csv sorting trade by time only, with no attributes + fp["timesort.csv"] 0: ("tabname,att,column,sort";"default,,time,1"); + / segmented logs written by a segmentedtp process + runq( + "nolog:`info`warn`error!3#{[c;m]}"; + "h:use`di.torq.handlers"; + "h.init enlist[`log]!enlist nolog"; + "seg:use`di.torq.proc.segmentedtp"; + "seg.init[((use`di.torq.config)[`parsefile] \"di/torq/settings/default.q\"),((use`di.torq.config)[`parsefile] \"di/torq/settings/segmentedtp.q\"),`proctype`procname`schemafile`stplgkdbtplog!(`segmentedtp;`stp1;\"",FIXDIR,"/schema.q\";`$\"",FIXDIR,"/stp\");`log`timer`handlers!(nolog;enlist[`addjob]!enlist {[a;b;c;d;e;f]};`register`remove`list#h)]"; + ".u.upd[`trade;(`b`a;1 2f;10 20i)]"; + ".u.upd[`quote;(enlist`a;enlist 3f)]"; + ".u.upd[`trade;(enlist`c;enlist 4f;enlist 40i)]"; + "exit 0"); + `STPDIR`SD set' (FIXDIR,"/stp/",string first key fp"stp";string .z.d); + / a meta table naming logs from two dates + system "mkdir -p ",FIXDIR,"/mixed"; + fp["mixed/stpmeta"] set ([]seq:0 1i;logname:fp each ("mixed/stp1_trade20261001000000";"mixed/stp1_quote20261002000000");start:2#.z.p;end:2#0Np;tbls:(enlist`trade;enlist`quote);msgcount:2#0i;schema:(();());additional:(();())); + } + +/ replay settings for the segmentedtp logs, with overrides +seg:{[x] "(`schemafile`hdbdir`tplogdir!(`$\"",FIXDIR,"/schema.q\";`$\":",FIXDIR,"/hdb\";`$\":",STPDIR,"\")),",x} + +teardownfixture:{[] system "rm -rf ",FIXDIR} diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.md b/di/torq/proc/tickerlogreplay/tickerlogreplay.md new file mode 100644 index 00000000..a238c6fe --- /dev/null +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.md @@ -0,0 +1,91 @@ +# di.torq.proc.tickerlogreplay + +Replays tickerplant log files into a date-, month- or year-partitioned HDB. It reads either one plain +tickerplant log or a directory of segmented tickerplant logs (`di.torq.proc.segmentedtp` output, picked through +its `stpmeta` table). It can replay all messages or a range of them, save in chunks, sort and apply attributes +at the end, or partition to a temporary directory and merge on disk. + +## Files + +`init.q` loads `tickerlogreplay.q`: the module `init`, then `.save.manipulate` (defined if absent), the `.replay.upd` +hook, and `.save.savedownmanipulation` / `.save.postreplay` from their `.replay` names. `sort.csv` is the default sort +config. + +## Surface + +| Name | What | +|---|---| +| `init[config;deps]` | applies the settings, checks them, loads the schema, and replays if `autoreplay` | +| `.replay.upd[t;x]` | inserts a replayed message; set it before `use` to change how messages are applied | +| `.save.savedownmanipulation` / `.save.postreplay[d;p]` | table!function applied before saving / called after each log is saved; set `.replay.savedownmanipulation` / `.replay.postreplay` before `use` | + +## Settings + +Every setting is required in `config` and kept module-private; `di/torq/settings/tickerlogreplay.q` declares +them all with these defaults: + +| Key | Default | +|---|---| +| `schemafile` | `` ` `` — required | +| `hdbdir` | `` ` `` — required | +| `tplogfile` / `tplogdir` | `` ` `` — one of them is required | +| `segmentedmode` | `1b` — `tplogdir` is a segmented tickerplant log directory | +| `tablelist` | `` enlist`all `` | +| `firstmessage` / `lastmessage` | `0` / `0W` — inclusive message indices | +| `messagechunks` | `0W` — messages per save; negative only logs progress | +| `partitiontype` | `` `date `` — `date`, `month` or `year` | +| `emptytables` | `1b` — create each table empty in the partition first | +| `sortafterreplay` | `1b` | +| `sortcsv` | `` ` `` — null uses `sort.csv` (`sym` then `time`, `p#` on `sym`) | +| `basicmode` | `0b` — replay everything, then save with `.Q.hdpf` | +| `checklogfiles` | `0b` — replay a good copy of a corrupt log | +| `clean` | `1b` — delete the date's existing data first | +| `compression` | `()` — `.z.zd` when three values | +| `partandmerge` / `tempdir` / `mergemethod` | `0b` / `` `:tempmergedir `` / `` `part `` (`part`, `col` or `hybrid`) | +| `mergenumrows` / `mergenumtab` / `mergenumbytes` | `10000000` / `` `quote`trade!10000 50000 `` / `500000000` | +| `exitwhencomplete` / `autoreplay` / `gc` | `1b` / `1b` / `1b` | + +The symbol settings (`schemafile`, `hdbdir`, `tplogdir`, `tplogfile`, `tablelist`, `partitiontype`, `sortcsv`, +`tempdir`, `mergemethod`) also take strings, so they can live in a `.toml` file (`hdbdir = "hdb"`). Any +basic-typed setting can be given on the command line as `-`; an app sets only the keys it overrides. + +`mergebybytelimit` (`0b`) and `partlimit` (`1000`), also required, are passed to di.merge's `init`. The `p#` column(s) for each table come from di.merge's `getextrapartitiontype` on the sort config. + +## init[config;deps] + +Requires `log`. It: + +1. signals if any setting is missing, initialises di.dbwrite and di.merge, and applies the settings; +2. exits on a bad setting: + - code 1 for a null `schemafile`/`hdbdir`/log, an unknown `partitiontype`, `basicmode` with + `messagechunks`, a message range in segmented mode, or `partandmerge` into `hdbdir`; + - code 2 for zero `messagechunks` or a schema file that fails to load; +3. loads the schema file at root; +4. wraps `realupd` to filter on `tablelist` (plain logs) and to save every `messagechunks` messages; +5. loads `sortcsv`, or `sort.csv`, into di.dbwrite; +6. replays when `autoreplay`. + +## Behaviour to know + +- The replay process exits when complete unless `exitwhencomplete` is `0b`; call `init` once per process. +- Plain log dates come from the last ten characters of the file name (`YYYY.MM.DD`), segmented log dates from + their `_YYYYMMDDhhmmss` suffix. Segmented logs from more than one date are refused. +- With `checklogfiles` on a plain log, the repaired copy is named `.good`, so it has no date and its tables + are saved at the HDB root. +- In segmented mode, a non-default `firstmessage` or `lastmessage` is rejected at init (exit 1). +- `clean` deletes the whole date partition when `tablelist` is `all`, otherwise only the replayed tables. +- A table with no rows is still saved empty when `emptytables` is on. +- `partandmerge` turns `sortafterreplay` off and applies `p#` through the merge. + +## Testing + +```q +k4unit:use`di.k4unit +k4unit.moduletest`di.torq.proc.tickerlogreplay +``` + +`test.q`/`test.csv` write a plain log, run a segmentedtp process to write a segmented log directory, and run +each replay in a fresh q. The tests cover the settings, the init checks, full and table-filtered replays, +message ranges, chunked and track-only saves, basic mode, a custom sort csv, compression, clean, `upd`, +`savedownmanipulation` and `postreplay` overrides, all three merge methods, segmented replays (picking logs from +`stpmeta`, mixed dates refused), and `checklogfiles` on segmented and plain logs. diff --git a/di/torq/proc/tickerlogreplay/tickerlogreplay.q b/di/torq/proc/tickerlogreplay/tickerlogreplay.q new file mode 100644 index 00000000..c182194b --- /dev/null +++ b/di/torq/proc/tickerlogreplay/tickerlogreplay.q @@ -0,0 +1,397 @@ +/ di.torq.proc.tickerlogreplay - replay tickerplant log files into an hdb + +/ a symbol, a string or a list of strings (TOML has no symbol type) +tosym:{[x] $[type[x] in 0 10 -10h;`$x;x]}; + +/ log the error and exit +ex:{[id;message;code] .z.m.log[`error][id;message]; exit code} + +/ exit if a setting is null +exitifnull:{[name;val] + if[null val; + .z.m.log[`error][`init;"Variable ",(string name)," is null but must be set"]; + exit 1]} + +init:{[config;deps] + if[not `log in key deps;'"di.torq.proc.tickerlogreplay: log dependency is required - see di.util.log"]; + .z.m.log:deps`log; + .z.m.tplog:use`di.tplog; + .z.m.dbw:use`di.dbwrite; + .z.m.dbw.init enlist[`log]!enlist deps`log; + .z.m.os:use`di.os; + / all settings required + req:`firstmessage`lastmessage`messagechunks`segmentedmode`autoreplay`schemafile`tablelist`hdbdir`tplogfile`tplogdir; + req,:`partitiontype`emptytables`sortafterreplay`basicmode`exitwhencomplete`checklogfiles`gc`clean`sortcsv`compression; + req,:`partandmerge`tempdir`mergenumrows`mergenumtab`mergenumbytes`mergemethod`mergebybytelimit`partlimit; + if[count m:req except key config; + '"di.torq.proc.tickerlogreplay: missing settings: ",", " sv string m]; + .z.m.firstmessage:config`firstmessage; + .z.m.lastmessage:config`lastmessage; + .z.m.messagechunks:config`messagechunks; + .z.m.segmentedmode:config`segmentedmode; + .z.m.autoreplay:config`autoreplay; + .z.m.schemafile:tosym config`schemafile; + .z.m.tablelist:tosym config`tablelist; + .z.m.hdbdir:tosym config`hdbdir; + .z.m.tplogfile:tosym config`tplogfile; + .z.m.tplogdir:tosym config`tplogdir; + .z.m.partitiontype:tosym config`partitiontype; + .z.m.emptytables:config`emptytables; + .z.m.sortafterreplay:config`sortafterreplay; + .z.m.basicmode:config`basicmode; + .z.m.exitwhencomplete:config`exitwhencomplete; + .z.m.checklogfiles:config`checklogfiles; + .z.m.gc:config`gc; + .z.m.clean:config`clean; + .z.m.sortcsv:tosym config`sortcsv; + .z.m.compression:config`compression; + .z.m.partandmerge:config`partandmerge; + .z.m.tempdir:tosym config`tempdir; + .z.m.mergenumrows:config`mergenumrows; + .z.m.mergenumtab:config`mergenumtab; + .z.m.mergenumbytes:config`mergenumbytes; + .z.m.mergemethod:tosym config`mergemethod; + .z.m.tablelist:(),tablelist; + .z.m.merge:use`di.merge; + .z.m.merge.init `log`mergebybytelimit`partlimit!(deps`log;config`mergebybytelimit;config`partlimit); + / some variables must be set + exitifnull[`schemafile;schemafile]; + exitifnull[`hdbdir;hdbdir]; + if[all null (tplogdir;tplogfile);exitifnull[`tplogfile;tplogfile]]; + if[basicmode and (messagechunks within (0;-1 + 0W)); + ex[`replayinit; "if using basic mode, messagechunks must not be used (it should be set to 0W). basicmode will use .Q.hdpf to overwrite tables at the end of the replay";1]]; + if[not partitiontype in `date`month`year; ex[`replayinit;"partitiontype must be one of `date`month`year";1]]; + if[messagechunks=0;ex[`replayinit;"messagechunks value cannot be 0";2]]; + if[segmentedmode and ((0<>firstmessage) or 0W<>lastmessage);ex[`replayinit;"firstmessage must be 0 and lastmessage must be 0W while in segmented mode";1]]; + .z.m.trackonly:messagechunks < 0; + if[trackonly;.z.m.log[`info][`replayinit;"messagechunks value is negative - log replay progress will be tracked"]]; + .z.m.messagechunks:abs messagechunks; + if[partandmerge and hdbdir = tempdir;ex[`replayinit;"if using partandmerge replay, tempdir must be set to a different directory than the hdb";1]]; + if[partandmerge and sortafterreplay;(.z.m.sortafterreplay:0b; .z.m.log[`info][`replayinit;"Setting sortafterreplay to 0b"])]; + / load the schema + .z.m.log[`info][`replayinit;"loading schema file ",string schemafile]; + @[system;"l ",string schemafile;{ex[`replayinit;"failed to load replay file ",(string x)," - ",y;2]}[schemafile]]; + .z.m.log[`info][`replayinit;"hdb directory is set to ",string .z.m.hdbdir:hsym hdbdir]; + .z.m.log[`info][`replayinit;"tempdir directory is set to ",string .z.m.tempdir:hsym tempdir]; + / filter on the table list + if[(not tablelist~enlist `all) and not segmentedmode; .z.m.realupd:{[f;t;x] if[t in tablestoreplay; f[t;x]]}[realupd]]; + / chunked saves + if[messagechunks < 0W; .z.m.realupd:{[f;t;x] f[t;x]; checkcount[hdbdir;replaydate;1;tempdir]}[realupd]]; + / load the sort csv and kick off replay if auto-running + $[null sortcsv;.z.m.dbw.setconfig sortdefault;.z.m.dbw.readcsv sortcsv]; + if[autoreplay;initandrun[]]; + }; + +/ manipulate a table at save down time, defined if absent +if[not `manipulate in key `.save;.save.manipulate:{[t;x] + $[t in key .save.savedownmanipulation; + @[.save.savedownmanipulation[t];x;{.z.m.log[`error][`manipulate;"save down manipulation failed : ",y];x}[x]]; + x]}]; + +/ default upd; set .replay.upd before use to override +.replay.upd:@[value;`.replay.upd;{{[t;x] insert[t;x]}}] + +/ save down settings +.save.savedownmanipulation:@[value;`.replay.savedownmanipulation;()!()] // table!function applied to a table at save +.save.postreplay:@[value;`.replay.postreplay;{{[d;p] }}] // invoked after a log's tables are saved + +// the path to the table to save +pathtotable:{[h;p;t] `$(string .Q.par[h;partitiontype$p;t]),"/"} + +// create empty tables - we need to make sure we only create them once +emptytabs:`symbol$() +createemptytable:{[h;p;t;td] + $[partandmerge;dest:td;dest:h]; + if[(not (path:pathtotable[dest;p;t]) in emptytabs) and emptytables; + .z.m.log[`info][`replay;"creating empty table ",(string t)," at ",string path]; + .z.m.emptytabs,:path; + savetabdatatrapped[h;p;t;0#value t;0b;td]]} + +savetabdata:{[h;p;t;data;UPSERT;td] + $[partandmerge;path:pathtotable[td;p;t];path:pathtotable[h;p;t]]; + if[not partandmerge;.z.m.log[`info][`replay;"saving table ",(string t)," to ",string path]]; + .z.m.pathlist[t],:path; + $[partandmerge;savetablesbypart[td;p;t;h];$[UPSERT;upsert;set] . (path;.Q.en[h;0!.save.manipulate[t;data]])] + } + +savetabdatatrapped:{[h;p;t;data;UPSERT;td] .[savetabdata;(h;p;t;data;UPSERT;td);{.z.m.log[`error][`replay;"failed to save table : ",x]}]} + +// this function should be invoked for saving tables +savetab:{[td;h;p;t] + if[not partandmerge;createemptytable[h;p;t;td]]; + if[count value t; + .z.m.log[`info][`replay;"saving ",(string t)," which has row count ",string count value t]; + savetabdatatrapped[h;p;t;value t;1b;td]; + delete from t; + if[gc;.z.m.dbw.gc[]]]} + +// apply the sorting and attributes at the end of the replay, from tablename!(list of paths) +applysortandattr:{[pathlist] + {.z.m.dbw.sort . x} each flip (key;value) @\: distinct each pathlist + }; + +// table names in count order, smallest first +tabsincountorder:{x iasc count each value each x} + +// check if the count has been exceeded, and save down if it has +currentcount:0 +totalcount:0 +checkcount:{[h;p;counter;td] + .z.m.currentcount+:counter; + if[currentcount >= messagechunks; + $[trackonly; + [.z.m.totalcount +: currentcount; + .z.m.log[`info][`replay;"replayed a chunk of ",(string messagechunks)," messages. Total message count so far is ",string totalcount]]; + [.z.m.log[`info][`replay;"number of messages to replay at once (",(string messagechunks),") has been exceeded. Saving down"]; + savetab[td;h;p] each tabsincountorder[tablestoreplay]; + .z.m.log[`info][`replay;"save complete- replaying next chunk of data"]]]; + .z.m.currentcount:0]} + +// function used to finish off the replay +finishreplay:{[h;p;td] + // save down any tables which haven't been saved + savetab[td;h;p] each tabsincountorder[tablestoreplay]; + // invoke any user defined post replay function + .save.postreplay[h;p]; + } + +// takes in log file directories made with segmented tickerplant +expandstplogs:{[logdirectories] // always a list + {` sv'raze x,/:'key each x}$[`~tplogdir;{enlist first x};]hsym logdirectories + }; + +replaylog:{[logfile] + // set the upd function to be the initialupd function + .z.m.msgcount:.z.m.currentcount:.z.m.totalcount:0; + // check if logfile is corrupt + if[checklogfiles; logfile: .z.m.tplog.check[logfile;lastmessage]]; + $[firstmessage>0; + [.z.m.log[`info][`replay;"skipping first ",(string firstmessage)," messages"]; + @[`.;`upd;:;initialupd]]; + @[`.;`upd;:;realupd]]; + .z.m.tablecounts:.z.m.errorcounts:()!(); + + // If not running in segmented mode, reset replay date and clean HDB directory on each loop + .z.m.zipped:$[logfile like "*.gz";1b;0b]; + if[not segmentedmode; + // Pull out date from TP log file name - *YYYY.MM.DD (+ .gz if zipped) + .z.m.replaydate:"D"$$[zipped;-3_-13#;-10#] string logfile; + if[clean;cleanhdb replaydate] + ]; + + if[lastmessage ",fifo," &"; + @[system;fifostr;{.z.m.log[`error][`replay;"Failed to read log into named pipe"]}]; + fifo + }; + +// upd functions down here +realupd:{[f;t;x] + // increment the tablecounts + .z.m.tablecounts[t]+:count first x; + // run the supplied function in the error trap + .[f;(t;x);{[t;x;e] .z.m.errorcounts[t]+:count first x}[t;x]]; + }[.replay.upd] + +initialupd:{[t;x] + // spin through the first X messages + $[msgcount < (firstmessage - 1); + .z.m.msgcount+:1; + // Once we reach the correct message, reset the upd function + @[`.;`upd;:;realupd]] + } + +// extract user defined row counts +mergemaxrows:{[tabname] mergenumrows^mergenumtab[tabname]}; + +// post replay function for merge replay, invoked after all the tables have been written down for a given log file +postreplaymerge:{[td;p;h] + .z.m.os[`mkdir] .Q.par[td;p;`]; // ensures directory exists before removed + mergelimits:(tabsincountorder[tablestoreplay],())!$[.z.m.merge.getmergebybytelimit[];(count tabsincountorder[tablestoreplay])#mergenumbytes;({[x] mergenumrows^mergemaxrows[x]}tabsincountorder[tablestoreplay])],(); + // merge the tables from each partition in the tempdir together + mergetable[td;p;;mergelimits;h] each tabsincountorder[tablestoreplay]; + system"rm -r ",1_string .Q.par[td;p;`]; // delete the contents of tempdir after merge completion + } + +// function to upsert to specified directory +upserttopartition:{[h;dir;tablename;tabdata;pt;expttype;expt] + dirpar:.Q.par[dir;pt;`$string first expt]; + directory:` sv dirpar,tablename,`; + // make directories for tables if they don't exist + if[count tabpar:tabsincountorder[tablestoreplay] except key dirpar; + .z.m.log[`info][`dir;"creating directories under ",1_string dirpar]; + tabpar:tabpar except `heartbeat`logmsg; + .[{[d;h;t](` sv d,t,`) set .Q.en[h;0#value t]};] each dirpar,'h,'tabpar]; + .z.m.log[`info][`save;"saving ",(string tablename)," data to partition ",string directory]; + .[ + upsert; + (directory;r:update `sym!sym from ?[tabdata;{(x;y;(),z)}[in;;]'[expttype;expt];0b;()]); + {[e] .z.m.log[`error][`savetablesbypart;"Failed to save table to disk : ",e];'e}]; + /-key in partsizes are directory to partition, need to drop training slash in directory key + .z.m.merge.trackpartition[first ` vs directory;count r;-22!r]; + }; + +savetablesbypart:{[dir;pt;tablename;h] + arows: count value tablename; + .z.m.log[`info][`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; + // get additional partition(s) defined by parted attribute in sort.csv + extrapartitiontype:.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename]; + + // check each partition type actually is a column in the selected table + .z.m.merge.checkpartitiontype[tablename;extrapartitiontype]; + // enumerate data to be upserted + enumdata:update (`. `sym)?sym from .Q.en[h;value tablename]; + // get list of distinct combiniations for partition directories + extrapartitions:(`. `sym)?.z.m.merge.getextrapartitions[tablename;extrapartitiontype]; + + .z.m.log[`info][`save;"enumerated ",(string tablename)," table"]; + // upsert data to specific partition directory + upserttopartition[h;dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; + // empty the table + .z.m.log[`info][`delete;"deleting ",(string tablename)," data from in-memory table"]; + @[`.;tablename;0#]; + // run a garbage collection (if enabled) + if[gc;.z.m.dbw.gc[]]; + }; + + +mergetable:{[dir;pt;tablename;mergelimits;h] + // get int partitions + intpars:asc key ` sv dir,`$string pt; // list of enumerated partitions 0 1 2 3... + k:key each intdir:.Q.par[hsym dir;pt] each intpars; // list of table names + if[0=count raze k inter\: tablename; :()]; + // get list of partition directories containing specified table + partdirs:` sv' (intdir,'parts) where not ()~/:parts:k inter\: tablename; // get each of the directories that hold the table + // permanent storage destination, where data being merged too + dest:.Q.par[h;pt;tablename]; + // exit function if no subdirectories are found + if[0=count partdirs; :()]; + // if no table data set empty table. If data to merge, merge with correct merge function + $[0 = count partdirs inter exec ptdir from .z.m.merge.getpartsizes[]; + [.z.m.log[`warn][`merge;"no records for ", string[tablename]]; + (` sv dest,`) set @[.Q.en[h;value tablename];.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];`p#]; + ]; + [$[mergemethod~`part; + [dest:` sv .Q.par[h;pt;tablename],`; // provides path to where to move data to + /-get chunks to partitions to merge in batch + partchunks:.z.m.merge.getpartchunks[partdirs;mergelimits[tablename]]; + .z.m.merge.mergebypart[.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];dest]'[partchunks]; + ]; + mergemethod~`col; + [.z.m.merge.mergebycol[(tablename;value tablename);dest]'[partdirs]; + /- merging data by column does not create .d file - set it here after merge + .z.m.log[`info][`merge;"setting .d file"]; + (` sv dest,`.d) set cols value tablename; + ]; + .z.m.merge.mergehybrid[.z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename];(tablename;value tablename);dest;partdirs;mergelimits[tablename]] + ] + ] + ]; + .z.m.log[`info][`merge;"deleting ", string[tablename], " from temp storage"]; + {system"rm -r ",1_string x} each partdirs; + // set the attributes + .z.m.log[`info][`merge;"setting attributes"]; + @[dest;;`p#] each .z.m.merge.getextrapartitiontype[.z.m.dbw.getconfig[];tablename]; + .z.m.log[`info][`merge;"merge complete"]; + // run a garbage collection (if enabled) + if[gc;.z.m.dbw.gc[]]; + }; + +// Return log file if it exists and not in segmented mode +getlogfile:{ + if[segmentedmode;.z.m.log[`error][`getlogfile;m:"Segmented mode requires tplogdir."];'m]; + if[()~key hsym f:tplogfile;.z.m.log[`error][`getlogfile;m:"Specified tplogfile ",string[f]," does not exist"];'m]; + enlist hsym f + }; + +// Return contents of log directory if it exists +getlogdir:{ + if[()~key hsym d:tplogdir;.z.m.log[`error][`getlogdir;m:"Specified log directory ",string[d]," does not exist"];'m]; + if[d like "*.gz";.z.m.log[`error][`getlogdir;m:"Zipped log directories not supported."];'m]; + $[segmentedmode;getstplogs[d];.Q.dd[logdir;] each key logdir:hsym d] + }; + +// Use STP meta table and tplogdir to build log names +getstplogs:{[logdir] + // If trying to replay zipped files on Windows, error out + winzip:(.z.o like "w*") and z:`stpmeta.gz in key d:hsym logdir; + if[winzip;.z.m.log[`error][`replaylog;m:"Zipped log files cannot be directly replayed on Windows"];'m]; + + // If meta table is zipped, assume all other logs are zipped as well and build log names accordingly + if[z;system "gunzip ",1_string .Q.dd[d;`stpmeta.gz]]; + metatable:@[get;.Q.dd[d;`stpmeta];{.z.m.log[`error][`getstpmeta;m:"Log directory must contain valid STP meta table"];'m}]; + if[z;system "gzip ",1_string .Q.dd[d;`stpmeta]]; + names:exec distinct logname from metatable where any each tbls in .z.m.tablestoreplay; + .Q.dd[d;] each $[z;.Q.dd[;`gz];::] each last each ` vs' names + }; + +// Set up log replay list and clean HDB if necessary, kick off replay +initandrun:{ + if[all not null (tplogfile;tplogdir);.z.m.log[`error][`getlogs;m:"Can't pass in log file and directory."];'m]; + + .z.m.log[`info][`initandrun;"Initialising replay settings."]; + .z.m.tablestoreplay:$[`all~first tablelist;tables[];tablelist,()]; + .z.m.logstoreplay:$[not null tplogfile;getlogfile[];getlogdir[]]; + if[not count r:logstoreplay;.z.m.log[`error][`initandrun;m:"No log files found"];'m]; + + // If in segmented mode, get replay date and clean HDB once + if[segmentedmode; + // Pull out the date from the STP log file name - *_YYYYMMDDhhmmss (+ .gz if zipped) + .z.m.replaydate:first l:"D"$$[first[r] like "*.gz";-9_-17#;-6_-14#] each string r; + if[not 1=count distinct l;.z.m.log[`error][`replay;m:"Cannot replay logs from different dates in segmented mode!"];'m]; + if[clean;cleanhdb replaydate] + ]; + + + // Replay all logs and exit + .z.m.log[`info][`initandrun;"Replaying the following log(s): ",csv sv 1_'string logstoreplay]; + .z.m.pathlist:()!(); + replaylog each logstoreplay; + if[sortafterreplay;applysortandattr[pathlist]]; + if[partandmerge;postreplaymerge[tempdir;replaydate;hdbdir]]; + .z.m.log[`info][`replay;"replay complete"]; + if[exitwhencomplete;exit 0]; + }; diff --git a/di/torq/proc/tickerplant/VERSION b/di/torq/proc/tickerplant/VERSION index 6c6aa7cb..0ea3a944 100644 --- a/di/torq/proc/tickerplant/VERSION +++ b/di/torq/proc/tickerplant/VERSION @@ -1 +1 @@ -0.1.0 \ No newline at end of file +0.2.0 diff --git a/di/torq/proc/tickerplant/deps.toml b/di/torq/proc/tickerplant/deps.toml index 081c7f95..8296a8f0 100644 --- a/di/torq/proc/tickerplant/deps.toml +++ b/di/torq/proc/tickerplant/deps.toml @@ -1,5 +1,5 @@ # Peer modules di.torq.proc.tickerplant `use`s (see di/torq/depcheck/depcheck.md). [dependencies] -"di.pubsub" = "0.1.0" +"di.pubsub" = "0.4.0" "di.eodtime" = "0.1.0" "di.tplogmgr" = "0.1.0" diff --git a/di/torq/proc/tickerplant/test.csv b/di/torq/proc/tickerplant/test.csv index a6a0fba9..05f789fe 100644 --- a/di/torq/proc/tickerplant/test.csv +++ b/di/torq/proc/tickerplant/test.csv @@ -18,6 +18,11 @@ fail,0,0,q,(tk`init)[immcfg[];`log`timer#deps[]],1,,init without the handlers de run,0,0,q,feedtrades[2],1,,feed two trades in immediate mode true,0,0,q,0=count trade,1,,immediate mode retains no local rows true,0,0,q,loghas["log";2],1,,both feed messages were written to the tp log +true,0,0,q,"(2;enlist[`trade]!enlist 2;hsym`$BASE,""/log/tp"",string .u.d)~(.u.i;.u.icounts;.u.L)",1,,".u.i, .u.icounts and .u.L track the log" +true,0,0,q,`trade in key .u.w,1,,.u.w is keyed on the tables +true,0,0,q,"(`trade;98h;0)~{(x 0;type x 1;count x 1)} .u.sub[`trade;`]",1,,.u.sub returns (table;schema) +true,0,0,q,"(count .u.w)=count .u.sub[`;`]",1,,.u.sub on ` returns one pair per table +run,0,0,q,(use`di.pubsub)[`closesub][0],1,,drop the in-process subscription true,0,0,q,subdetailsok[],1,,subdetails returns rowcount + tables/schemas + logfile/date for a replaying subscriber true,0,0,q,subdetailsbatchedok[],1,,batched: subdetails flushes the buffer to existing subscribers before registering the caller - no replay-then-flush double delivery @@ -43,5 +48,6 @@ run,0,0,q,doinit[replaycfg[]],1,,re-init for the eod roll test (batched with a l run,0,0,q,ROLLDATE:"d"$.z.p,1,,capture today's date before rolling run,0,0,q,endofday[],1,,force an end-of-day roll true,0,0,q,rolledfile["replog";ROLLDATE+1],1,,the roll opened the next day's log file +true,0,0,q,"(ROLLDATE+1;0)~(.u.d;count .u.icounts)",1,,the roll advances .u.d and resets .u.icounts after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs diff --git a/di/torq/proc/tickerplant/tickerplant.q b/di/torq/proc/tickerplant/tickerplant.q index 73f2dadc..36ce4928 100644 --- a/di/torq/proc/tickerplant/tickerplant.q +++ b/di/torq/proc/tickerplant/tickerplant.q @@ -38,7 +38,8 @@ stamp:{[x] / publishes immediately or buffers into the root table for the flush job. upd:{[t;x] x:stamp tocols x; - if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.z.m.msgcount+:1]; + if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.u.i+:1]; + if[count .z.m.tplogdir;.u.icounts[t]+:count first x]; $[.z.m.publishmode=`batched; t insert x; (.z.m.ps`publish)[t;flip (cols value t)!$[0>type first x;enlist each x;x]] @@ -48,7 +49,13 @@ upd:{[t;x] / subscriber entry point (published at root as `.u.sub`). syms=` -> all data for the / table(s); a sym list -> a sym-filtered subscription. Delegates to di.pubsub, whose / .z.w-based registration sees the calling subscriber's handle. -sub:{[tabs;syms] (.z.m.ps`subscribe)[tabs;syms]} +sub:{[x;y] + if[x~`;:sub[;y] each .z.m.tables]; + if[not x in .z.m.tables;'x]; + / batched: flush first, so a replaying subscriber doesn't receive the buffer twice + if[.z.m.publishmode=`batched;(.z.m.ps`pubclear)[.z.m.tables]]; + r:(.z.m.ps`subscribe)[x;y]; + (first r 0;first r 1)} / subscription-details call (published at root as `.u.subdetails`) for a replaying / subscriber - di.torq.proc.rdb via di.subscriptions. In ONE synchronous call it (a) registers the @@ -72,7 +79,7 @@ subdetails:{[tabs;syms] sub:(.z.m.ps`subscribe)[tabs;syms]; d:(.z.m.eod`getd)[]; lf:$[00;r:(.z.m.tp`roll)[.z.m.logh;.z.m.tplogdir;d];.z.m.logh:r 0;.z.m.msgcount:r 1]; - (.z.m.eod`setd)[d+1]; + if[.z.m.logh>0;r:(.z.m.tp`roll)[.z.m.logh;.z.m.tplogdir;d];.z.m.logh:r 0;.u.i:r 1;.u.L:(.z.m.tp`logname)[.z.m.tplogdir;d+1]]; + .u.icounts:(`symbol$())!0#0; + (.z.m.eod`setd)[.u.d:d+1]; (.z.m.eod`setnextroll)[(.z.m.eod`getroll)[.z.p]]; (.z.m.eod`setdailyadj)[(.z.m.eod`getdailyadjustment)[]]; .z.m.log[`info][`tickerplant;"end of day complete, rolled ",(string d)," -> ",string d+1]; @@ -149,7 +157,12 @@ init:{[config;deps] / tplog: prepared now; log opened after the root upd is published (replay needs it) .z.m.tp:use`di.tplogmgr; .z.m.logh:0; - .z.m.msgcount:0; + / table names only, read by .sub.subscribe; di.pubsub holds the subscribers + .u.w:tabs!(count tabs)#(); + .u.i:0; + .u.icounts:(`symbol$())!0#0; + .u.L:`; + .u.d:(.z.m.eod`getd)[]; / publish the IPC surface at real root names (use mangles module code into a private / namespace, so a remote/replayed `upd`/`.u.sub` must resolve at root). Done BEFORE @@ -165,7 +178,8 @@ init:{[config;deps] system "mkdir -p ",.z.m.tplogdir; r:(.z.m.tp`open)[.z.m.tplogdir;(.z.m.eod`getd)[]]; .z.m.logh:r 0; - .z.m.msgcount:r 1; + .u.i:r 1; + .u.L:(.z.m.tp`logname)[.z.m.tplogdir;.u.d]; .z.m.log[`info][`tickerplant;"opened tp log, replayed ",(string r 1)," message(s)"]; ]; diff --git a/di/torq/proc/wdb/deps.toml b/di/torq/proc/wdb/deps.toml index ecd0c78e..02792cec 100644 --- a/di/torq/proc/wdb/deps.toml +++ b/di/torq/proc/wdb/deps.toml @@ -1,6 +1,7 @@ # Peer modules di.torq.proc.wdb `use`s (see di/torq/depcheck/depcheck.md for the manifest-graph mechanism). [dependencies] -"di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers) -"di.subscriptions" = "0.1.0" +"di.torq.servers" = "0.5.0" # requires the INJECTED-servers contract (deps`servers) +"di.subscriptions" = "0.2.0" "di.dbwrite" = "0.1.0" "di.merge" = "0.1.0" +"di.os" = "0.1.0" diff --git a/di/torq/proc/wdb/test.q b/di/torq/proc/wdb/test.q index 88bbf24d..356d3f9b 100644 --- a/di/torq/proc/wdb/test.q +++ b/di/torq/proc/wdb/test.q @@ -1,5 +1,6 @@ / fixture helpers for di.torq.proc.wdb's end-to-end tests. Assumes cwd is the kdbx-modules repo root. -/ A spawned q process answers .u.subdetails as the tickerplant; everything else is mocked. +/ A spawned q process answers .sub.subscribe as a segmented tickerplant, found through a real di.torq.servers; +/ everything else is mocked. BASE:"/tmp/di_wdb_k4unit"; TPPORT:25961; @@ -30,7 +31,9 @@ recdeps:{[] `log`timer`servers`handlers!(reclog;`addjob`deletejobs!({[a;b;c;d;e; starttp:{[] f:BASE,"/faketp.q"; (hsym `$f) 0: ("sc:`trade`quote!(([]time:`timestamp$();sym:`symbol$();price:`float$());([]time:`timestamp$();sym:`symbol$();bid:`float$()));"; - ".u.subdetails:{[t;s] `tables`schemas`logfile`rowcount`date!(key sc;sc;`;0;.z.D)};"); + "tptype:`segmented;"; + "tablelist:{key sc};"; + "subdetails:{[t;s] `schemalist`logfilelist`rowcounts`date`logdir!({(x;sc x)} each (),t;();(key sc)!0 0;.z.D;`)};"); system "timeout 300 ",(first .z.X)," ",f," -p ",(string TPPORT)," -q /dev/null 2>&1 &"; n:0; while[(null TPH) and 50>n+:1;`TPH set @[hopen;(`$"::",string TPPORT;200);{0Ni}];if[null TPH;system "sleep 0.1"]]; @@ -46,11 +49,22 @@ setup:{[] setenv[`TORQXAPPCONFIG;BASE,"/appconfig"]; (hsym `$BASE,"/appconfig/sort.csv") 0: ("tabname,att,column,sort";"default,p,sym,1";"default,,time,1"); starttp[]; + initservers[]; + }; + +/ .sub.subscribe finds the tickerplant through root .servers +svc:use`di.torq.servers; +/ loads root .sub, which freshwdb clears +use`di.subscriptions; +initservers:{[] + (hsym `$BASE,"/appconfig/process.csv") 0: ("host,port,proctype,procname";"localhost,",(string TPPORT),",tickerplant,tickerplant1"); + svc.init `log`timer`handlers`proctype`procname`processcsv`connections`discoveryregister`connectionsfromdiscovery!(reclog;`addjob`deletejobs!({[a;b;c;d;e;f]};{[x]});rechandlers;`wdb;`wdb1;BASE,"/appconfig/process.csv";`tickerplant;0b;0b); + .servers.startup ()!(); }; / numtab is pinned empty so numrows governs every table; the shipped default is covered by numtabdefault[] cfg:{[] - `savedir`hdbdir`sortcsv`numrows`numtab`replaynumtab`eodwaittime`reloadorder`ignorelist! + ((use`di.torq.config)[`parsefile] "di/torq/settings/default.q"),`savedir`hdbdir`sortcsv`numrows`numtab`replaynumtab`eodwaittime`reloadorder`ignorelist! ("wdb";"hdb";"appconfig/sort.csv";100000;(`symbol$())!`long$();(`symbol$())!`long$();0;`hdb;`heartbeat`logmsg`calls`scalls) }; @@ -61,6 +75,7 @@ wdbpart:{[] hsym `$BASE,"/wdb/",string today[]}; freshwdb:{[c] `calls set 0#calls; system "rm -rf ",BASE,"/wdb ",BASE,"/hdb"; + delete from `.sub.SUBSCRIPTIONS; wdb.init[c;recdeps[]]; }; @@ -76,7 +91,7 @@ feed:{[] eodok:{[c] freshwdb c; feed[]; - endofday today[]; + .u.end today[]; t:select from get hdbpart`trade; / enum on disk, but select resolves it once the sym domain is loaded - take the column as-is s:t`sym; @@ -120,7 +135,7 @@ tabsizes:{[] manipulation:{[] freshwdb cfg[],(enlist`savedownmanipulation)!enlist (enlist`trade)!enlist {update price:2*price from x}; upd[`trade;([]time:enlist .z.D+0D01;sym:enlist`ibm;price:enlist 5f)]; - endofday today[]; + .u.end today[]; 10f~first (get hdbpart`trade)`price }; @@ -128,14 +143,14 @@ postreplay:{[] `POST set (); freshwdb cfg[],(enlist`postreplay)!enlist {[d;p] `POST set (d;p)}; feed[]; - endofday today[]; + .u.end today[]; (last POST)~today[] }; compression:{[] freshwdb cfg[],(enlist`compression)!enlist 17 2 6; feed[]; - endofday today[]; + .u.end today[]; chk `compressed`reset!( 0 di.dbwrite sort/attribute config; else $TORQXAPPCONFIG/sort.csv if present, else time asc ``` -The schema comes from the **tickerplant** (via `subdetails`), not a local `database.q` — -di.subscriptions defines the tables at root from what the TP returns. +The schema comes from the **tickerplant**, not a local `database.q`: `.sub.subscribe` finds the +first `tickerplanttypes` process through `.sub.getsubscriptionhandles`, asks for its `tptype`, and +defines the tables at root from what it returns. ## Behaviour @@ -85,8 +86,8 @@ di.subscriptions defines the tables at root from what the TP returns. flushed at least one table, the partition is filled (`filldb`) and every connected `idbtypes` process is notified (`` .idb.intradayreload[] ``, async) — an all-skipped tick (nothing over threshold) stays silent. This is unconditional on `reloadorder`; it only needs an idb to be connected. -- **End of day** (`endofday[date]`, published at root): the tickerplant - broadcasts `(`endofday;date)` at roll (the same trigger as di.torq.proc.rdb). di.torq.proc.wdb flushes what +- **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[currp;nextp;data]` stub). di.torq.proc.wdb flushes what remains, then runs `endofdaysort` — `saveandsort` in-process, `save` by an async `.wdb.endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]` to each connected sort process. With no sort process connected, `save` @@ -204,11 +205,10 @@ sort process with `.merge.syncpartsizes` before the hand-off. - **FinSpace/AWS** — stripped. -The `endofperiod` stub legacy shipped in `writedown.q` **is** kept: `di.pubsub.callendofperiod` -broadcasts `` (`endofperiod;(current;next;data)) `` to every subscriber on each period roll, so a wdb -pointed at a segmented tickerplant would otherwise raise `'endofperiod` every period. The stub is -published at root by `init` and only logs. It is **monadic**, matching `callendofperiod`, which -sends the triple as a single argument. +The `endofperiod` stub legacy shipped in `writedown.q` **is** kept: a segmented tickerplant broadcasts +`` (`endofperiod;current;next;data) `` to every subscriber on each period roll, so a wdb pointed at +it would otherwise raise `'endofperiod` every period. The stub is published at root by `init`, takes +the three arguments and only logs, the same as di.torq.proc.rdb's. ## Migrating a TorQ wdb settings file diff --git a/di/torq/proc/wdb/wdb.q b/di/torq/proc/wdb/wdb.q index a02e2af1..5ca52d55 100644 --- a/di/torq/proc/wdb/wdb.q +++ b/di/torq/proc/wdb/wdb.q @@ -663,10 +663,9 @@ setconfig:{[config] .z.m.currentpartition:0N; } -/ logging stub for the period roll, as legacy's writedown.q shipped -/ monadic: di.pubsub.callendofperiod sends (`endofperiod;(currentpd;nextpd;data)) as one argument -endofperiod:{[x] - .z.m.log[`info][`endofperiod;"received endofperiod ",.Q.s1 x]; +/ logging stub for the period roll, as legacy's writedown.q shipped: a segmented tickerplant sends (`endofperiod;currp;nextp;data) +endofperiod:{[currp;nextp;data] + .z.m.log[`info][`endofperiod;"Received endofperiod. currentperiod, nextperiod and data are ",(string currp),", ", (string nextp),", ", .Q.s1 data]; } / publishes the root names other processes and legacy's peach lambdas call @@ -684,9 +683,10 @@ setroot:{[] / define .z.pd in order to connect to any worker processes @[`.z;`pd;:;{[] `u#raze {exec w from x} each (.z.m.svc`getservers) each .z.m.sortworkertypes}]; @[`.;`upd;:;.z.m.upd]; - @[`.;`endofday;:;endofday]; - @[`.;`endofperiod;:;endofperiod]; set[`.u.end;endofday]; + / segmented tickerplant entry points + @[`.;`endofday;:;{[d;x] endofday d}]; + @[`.;`endofperiod;:;endofperiod]; / the idb reads these at startup; currentpartition is republished at each end of day set[`.wdb.savedir;.z.m.savedir]; set[`.wdb.hdbdir;.z.m.hdbdir]; @@ -707,7 +707,6 @@ init:{[config;deps] / legacy passes -s -N on the command line; torqx.sh has no per-process flags, so it is a setting if[0.z.m.replaynumrows; {replaymaxrowcheck[x;maxrows x]} each tablelist[]]; diff --git a/di/torq/servers/VERSION b/di/torq/servers/VERSION index 8ea2ddfc..a918a2aa 100644 --- a/di/torq/servers/VERSION +++ b/di/torq/servers/VERSION @@ -1,2 +1 @@ -0.5.0 - +0.6.0 diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md index c2c548fb..073781f3 100644 --- a/di/torq/servers/servers.md +++ b/di/torq/servers/servers.md @@ -105,15 +105,13 @@ Published at root by `init`, same bodies as legacy: | `.servers.pc` | l.383, run on `.z.pc` | | timers `discoveryretry` / `serversretry` | l.387–389 | -Defined directly at root in a `\d .servers` section, for legacy `.sub` and chainedtp: +Also defined at root, for di.subscriptions' `.sub` and the tickerplants' startup waits: +- `.servers.getservers` (5-arg; the exported 1-arg `getservers` is separate); +- `.servers.connectcustom` (called by `retryrows`); +- `.servers.startupdepnamecycles`. -| Name | trackservers.q | -|---|---| -| `.servers.attributematch` | l.64–68 | -| `.servers.getservers` (legacy 5-arg; the exported 1-arg `getservers` is separate) | l.75–89 | -| `.servers.connectcustom` (called by `retryrows`) | l.198 | -| `.servers.reqprocsnotconn` / `.servers.reqprocnamesnotconn` | l.348–351, l.357 | -| `.servers.startupdepcyclestypename` / `.servers.startupdepnamecycles` | l.360–373, l.379 | +They are built on the module-private `attributematch`, `reqprocsnotconn`, `reqprocnamesnotconn` and +`startupdepcyclestypename`. The discovery process (`di.torq.proc.discovery`) calls `addw`, `removerows`, `cleanup`, `startup`, reads `SERVERS`/`nontorqprocesstab`, and pushes `procupdate`/`autodiscovery` to @@ -158,7 +156,7 @@ peers. Peers call discovery's root `register` (as `` `..register ``) and `getser - `startup` against a live and a dead peer (discovery off); - `gethandlebytype`, and retry recovering an ungraceful kill; - `waitfortype`, including a discovery stub that comes up after `startup`; -- the root `.servers` functions (`attributematch`, 5-arg `getservers`, `startupdepnamecycles`); +- `attributematch`, the root 5-arg `.servers.getservers` and `.servers.startupdepnamecycles`; - input validation and `getapimeta`. The rest of the discovery protocol is covered by `di.torq.proc.discovery`'s suite. Run in a fresh diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q index bf4ef09a..80bf783c 100644 --- a/di/torq/servers/servers.q +++ b/di/torq/servers/servers.q @@ -66,6 +66,8 @@ init:{[deps] {[deps;k] set[first .z.m.settings k;$[k in key deps;deps k;last .z.m.settings k]]}[deps] each key .z.m.settings; .servers.RETRY:totimespan .servers.RETRY; .servers.DISCOVERYRETRY:totimespan .servers.DISCOVERYRETRY; + / a string or a list of strings (TOML has no symbol type) + .servers.CONNECTIONS:$[11h=abs type c:.servers.CONNECTIONS;c;`$c]; set[`.servers.NONTORQPROCESSFILE;$[`nontorqprocessfile in key deps;hsym deps`nontorqprocessfile;hsym `$("/" sv -1_"/" vs .z.m.processcsv),"/nontorqprocess.csv"]]; / live-handle checks set[`.dotz.liveh;{x in key .z.W}]; @@ -329,17 +331,14 @@ getapimeta:{[] (`waitfortype; 1b; "block until a proctype connects or timeout elapses"; "[symbol: proctype; long: timeoutms; long: pollms]"; "boolean: 1b connected, 0b timed out")); }; -/ root .servers functions for .sub and startup waits -\d .servers - / match required attributes against advertised ones attributematch:{[req;avail] vals:key[req] inter key avail; notpresent:noval!(count noval:key[req] except key avail)#enlist(0b;()); notpresent,vals!{($[0>type y;x~y;all x in y];(x,()) inter y,())}'[req vals;avail vals]} -/ servers matching types or names, optionally reopening closed handles -getservers:{[nameortype;lookups;req;autoopen;onlyone] +/ root, for .sub: servers matching types or names, optionally reopening closed handles +.servers.getservers:{[nameortype;lookups;req;autoopen;onlyone] r:$[`~lookups; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS; nameortype~`proctype; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where proctype in lookups; select procname,proctype,lastp,w,hpup,attributes,index:i from .servers.SERVERS where procname in lookups]; @@ -350,10 +349,10 @@ getservers:{[nameortype;lookups;req;autoopen;onlyone] if[(alivecount=0) or (not onlyone) or (any not exec max alive by agg:?[nameortype~`proctype;proctype;procname] from r); retryrows exec index from r where not alive; r:select procname,proctype,lastp,w,hpup,attributes,alive:.dotz.liveh w from .servers.SERVERS where i in r`index]]]; - select procname,proctype,lastp,w,hpup,attributes,attribmatch:.servers.attributematch[req]each attributes from r where alive} + select procname,proctype,lastp,w,hpup,attributes,attribmatch:.z.m.attributematch[req]each attributes from r where alive} -/ run on (re)connected SERVERS rows -connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}] +/ root, for .sub: run on (re)connected SERVERS rows +.servers.connectcustom:@[value;`.servers.connectcustom;{[connectedrows]}]; / are any required processes not connected reqprocsnotconn:{[requiredprocs;typeorname] @@ -378,6 +377,5 @@ startupdepcyclestypename:{[requiredprocs;typeornamefunc;timeintv;cycles] ]; }; -startupdepnamecycles:startupdepcyclestypename[;.servers.reqprocnamesnotconn;;]; - -\d . \ No newline at end of file +/ root, for chainedtp and segmentedtp +.servers.startupdepnamecycles:startupdepcyclestypename[;reqprocnamesnotconn;;]; diff --git a/di/torq/servers/test.csv b/di/torq/servers/test.csv index b38c30c7..85f2ed3d 100644 --- a/di/torq/servers/test.csv +++ b/di/torq/servers/test.csv @@ -44,7 +44,7 @@ comment,,,,,,,waitfortype - connected vs timeout true,0,0,q,svc.waitfortype[`otherproc;2000;200],1,1,returns 1b immediately for an already-connected proctype true,0,0,q,0b~svc.waitfortype[`deadproc;700;200],1,1,returns 0b on timeout for a proctype that never comes up comment,,,,,,,root .servers functions -true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values +true,0,0,q,"(enlist[`a]!enlist(1b;enlist 1))~.m.di.0torq.0servers.attributematch[enlist[`a]!enlist 1;enlist[`a]!enlist 1 2]",1,1,attributematch reports a full match and the matched values true,0,0,q,"(enlist`otherproc)~exec proctype from .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,5-arg getservers returns the live row true,0,0,q,"`attribmatch in cols .servers.getservers[`proctype;`otherproc;()!();0b;0b]",1,1,getservers adds attribmatch true,0,0,q,"0=count .servers.getservers[`proctype;`deadproc;()!();0b;0b]",1,1,getservers drops dead rows @@ -61,6 +61,8 @@ true,0,0,q,svc.waitfortype[`tpproc;3000;200],1,1,waitfortype reaches discovery a comment,,,,,,,retry periods from toml run,0,0,q,"svc.init[svrdeps[`otherproc],`retry`discoveryretry!(""0D00:00:10"";10)]",1,1,retry as a string and discoveryretry as seconds true,0,0,q,"(0D00:00:10;0D00:00:10)~(.servers.RETRY;.servers.DISCOVERYRETRY)",1,1,both become timespans +run,0,0,q,"svc.init svrdeps enlist""otherproc""",1,1,connections as a list of strings +true,0,0,q,(enlist`otherproc)~.servers.CONNECTIONS,1,1,become symbols comment,,,,,,,input validation + getapimeta fail,0,0,q,"svc.getservers[""nosuch""]",1,1,getservers rejects a non-symbol proctype fail,0,0,q,"svc.gethandlebytype[`hdb;""any""]",1,1,gethandlebytype rejects a non-symbol selection diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q index fc24ba06..5f2c4af9 100644 --- a/di/torq/settings/default.q +++ b/di/torq/settings/default.q @@ -1,4 +1,4 @@ -/ built-in framework defaults: the .servers and .sub settings +/ built-in framework defaults: the servers, subscriptions and clienttracking settings / discovery - off unless the app turns it on discoveryregister:0b / register with the discovery service @@ -20,4 +20,11 @@ autoclean:0b / drop expired records when a connection clo / subscriptions autoreconnect:0b / resubscribe to processes previously subscribed to -checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never \ No newline at end of file +checksubscriptionperiod:0D00:00:10 / how often to check subscriptions are connected; 0D means never +/ client tracking +clientsenabled:1b / track connections +clientsopencloseonly:0b / track connections but not queries +clientsintrusive:0b / ask each new kdb+ client for its details +clientsautoclean:1b / not read +clientsretain:`long$0D02 / nanoseconds to keep a closed row +clientsmaxidle:`long$0D / nanoseconds of idleness before a handle is closed; 0 means never diff --git a/di/torq/settings/segmentedtp.q b/di/torq/settings/segmentedtp.q index 38b6064c..9fd67ccd 100644 --- a/di/torq/settings/segmentedtp.q +++ b/di/torq/settings/segmentedtp.q @@ -1,3 +1,21 @@ -/ connections only; an app clients section replaces this whole section -clients:(enlist`opencloseonly)!enlist 1b +/ track connections only +clientsopencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b +/ all required by init; override as -. kdbtplog comes from the environment +stplgmultilog:`tabperiod +stplgmultilogperiod:0D01 +stplgerrmode:1b +stplgbatchmode:`defaultbatch +stplgreplayperiod:`day +stplgcustomcsv:"appconfig/stpcustom.csv" +stplgerrorlogname:`segmentederrorlogfile +sctpchainedtp:0b +sctploggingmode:`none +sctptickerplantname:`stp1 +sctptpconnsleep:10 +sctptpcheckcycles:0W +sctpsubscribeto:` +sctpsubscribesyms:` +sctpreplay:0b +sctpschema:1b +createlogs:1b diff --git a/di/torq/settings/tickerlogreplay.q b/di/torq/settings/tickerlogreplay.q new file mode 100644 index 00000000..c7576bef --- /dev/null +++ b/di/torq/settings/tickerlogreplay.q @@ -0,0 +1,31 @@ +/ tickerlogreplay settings +/ all required by init; override basic-typed ones as - +firstmessage:0 +lastmessage:0W +messagechunks:0W +segmentedmode:1b +autoreplay:1b +schemafile:` +tablelist:enlist`all +hdbdir:` +tplogfile:` +tplogdir:` +partitiontype:`date +emptytables:1b +sortafterreplay:1b +basicmode:0b +exitwhencomplete:1b +checklogfiles:0b +gc:1b +clean:1b +sortcsv:` +partandmerge:0b +tempdir:`:tempmergedir +mergenumrows:10000000 +mergenumbytes:500000000 +mergemethod:`part +compression:() +mergenumtab:`quote`trade!10000 50000 +/ passed to di.merge's init +mergebybytelimit:0b +partlimit:1000 diff --git a/di/torq/settings/tickerplant.q b/di/torq/settings/tickerplant.q index 38b6064c..d3929c35 100644 --- a/di/torq/settings/tickerplant.q +++ b/di/torq/settings/tickerplant.q @@ -1,3 +1,3 @@ -/ connections only; an app clients section replaces this whole section -clients:(enlist`opencloseonly)!enlist 1b +/ track connections only +clientsopencloseonly:1b zpsignore:(enlist`enabled)!enlist 0b diff --git a/di/torq/test.csv b/di/torq/test.csv index acabc0e7..37138ab3 100644 --- a/di/torq/test.csv +++ b/di/torq/test.csv @@ -17,7 +17,7 @@ true,0,0,q,000b~(r`config)`discoveryregister`connectionsfromdiscovery`debug,1,,b true,0,0,q,`widgets in tables[],1,,the built-in hdb module actually mounted the fixture hdb dir true,0,0,q,(`handlers`log`servers`timer)~asc key r`deps,1,,all four core deps (incl injected servers) were built and passed through true,0,0,q,99h=type .clients.clients,1,,init wired client tracking (.clients.clients exists) -run,0,0,q,"ctorig:(.clients.hit;.clients.hite); .clients.hit:{HITS+::1;x}; .clients.hite:{HITE+::1;'x}; HITS::HITE::UPD::0; tgt:{[x] x}; upd:{[t;x] UPD+::1}; .u.upd:upd",1,,count client-tracking hits and upd calls +run,0,0,q,"ctorig:(.m.di.0clienttracking.hit;.m.di.0clienttracking.hite); .m.di.0clienttracking.hit:{HITS+::1;x}; .m.di.0clienttracking.hite:{HITE+::1;'x}; HITS::HITE::UPD::0; tgt:{[x] x}; upd:{[t;x] UPD+::1}; .u.upd:upd",1,,count client-tracking hits and upd calls run,0,0,q,.z.ps (`tgt;1),1,,a non-upd async message true,0,0,q,"(1;0)~(HITS;UPD)",1,,is counted by client tracking run,0,0,q,.z.ps (`upd;`trade;()),1,,an upd async message @@ -28,18 +28,21 @@ run,0,0,q,".z.ps ""upd[`trade;()]""",1,,a string upd message true,0,0,q,"(2;3)~(HITS;UPD)",1,,is not skipped: the ignorelist check only matches list heads run,0,0,q,"zps:.z.ps; .m.di.0torq.zpsignorewired:0b; .m.di.0torq.initzpsignore[enlist[`zpsignore]!enlist enlist[`enabled]!enlist 0b]",1,,zpsignore with enabled 0b true,0,0,q,zps~.z.ps,1,,leaves .z.ps untouched -run,0,0,q,".clients.hit:first ctorig; .clients.hite:last ctorig",1,,restore client tracking +run,0,0,q,".m.di.0clienttracking.hit:first ctorig; .m.di.0clienttracking.hite:last ctorig",1,,restore client tracking run,0,0,q,"ctp:{(use`di.torq.config)[`cascade] . .m.di.0torq.roots[],x,`$string[x],""1""} each `tickerplant`segmentedtp",1,,cascade the tickerplant and segmentedtp settings -true,0,0,q,"all {(1b;0b)~((x`clients)`opencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore +true,0,0,q,"all {(1b;0b)~(x`clientsopencloseonly;(x`zpsignore)`enabled)} each ctp",1,,tickerplants track connections only and have no zpsignore run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works true,0,0,q,`hdb~r2`proctype,1,,override path still resolves the same identity +true,0,0,q,`di.torq.proc.segmentedtp~.m.di.0torq.builtin`segmentedchainedtp,1,,segmentedchainedtp runs the segmentedtp module 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,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed +true,0,0,q,1=.k4unittestproc.deferredcalled,1,,a function queued with .proc.addinitlist ran once after init +true,0,0,q,()~.proc.initlist,1,,the deferred init list is emptied run,0,0,q,r5:tq.init[TESTPROCNAME;`testinst;enlist[`norun]!enlist 1b],1,,re-init with the norun override set (this reloads the proctype file, resetting runcalled to 0) true,0,0,q,0=.k4unittestproc.runcalled,1,,-norun skipped the hook - count stayed at 0 instead of incrementing to 1 diff --git a/di/torq/test.q b/di/torq/test.q index 6403bde7..7cd47722 100644 --- a/di/torq/test.q +++ b/di/torq/test.q @@ -48,7 +48,10 @@ setupfixture:{[] writelines[TESTPROCFILE; ("\\d .",string TESTPROCNAME; "runcalled:0;"; + "deferredcalled:0;"; + "deferred:{[x] deferredcalled::deferredcalled+1};"; "init:{[config;deps]"; + " .proc.addinitlist(`.k4unittestproc.deferred;`);"; " capturedconfig::config;"; " captureddeps::deps;"; " deps[`log][`info][`",(string TESTPROCNAME),";\"custom proctype initialised\"];"; diff --git a/di/torq/torq.md b/di/torq/torq.md index c3bae0ce..73b6663d 100644 --- a/di/torq/torq.md +++ b/di/torq/torq.md @@ -81,10 +81,14 @@ expects. ### Process-type dispatch -A small built-in registry maps proctype → module name: +A built-in registry maps proctype → module name, `` `x → `di.torq.proc.x `` for each of `hdb`, +`tickerplant`, `rdb`, `wdb`, `gateway`, `idb`, `segmentedtp`, `chainedtp`, `housekeeping`, `discovery` +and `tickerlogreplay`; `segmentedchainedtp` also maps to `di.torq.proc.segmentedtp` and resolves the +`segmentedtp` settings tier (builtin and app root alike); its chained behaviour comes from the instance's own +settings, e.g. `sctp1.toml`, as any other per-instance distinction does: ```q -builtin:(enlist`hdb)!enlist`di.torq.proc.hdb +builtin:`hdb`tickerplant`rdb`wdb`gateway`idb`segmentedtp`chainedtp`housekeeping`discovery`tickerlogreplay`segmentedchainedtp!`di.torq.proc.hdb`di.torq.proc.tickerplant ... ``` If `proctype` is in `builtin`, `startbuiltin` `use`-loads that module and calls its @@ -130,6 +134,9 @@ already uses for `code/processes/`. App code loads **after** the process module's `init` (so it can reference the module's tables and state) and **before** the `.run` hook (so an app file may define/override `` ..run ``). +After `.ps.initialise[]` and connections, `init` runs any functions a process queued with +`.proc.addinitlist[(func;arg)]` (`.proc.initlist`), then empties the list. + ### The `.run` post-init hook After starting the process type and loading app code, `init` calls `runhook[proctype;overrides]`: @@ -286,7 +293,8 @@ In practice nothing calls `tq.init` directly like the examples above - that's wh does on top of that (start/stop/restart/status across a whole `process.csv`, without duplicating any of the identity-resolution logic above - it only reads `process.csv` to know *which* processes exist, never to resolve *who a given session is*, which -stays exclusively `di.torq`'s job). +stays exclusively `di.torq`'s job). An optional `startwithall` column, as in TorQ, keeps a row with `0` out of +`torqx.sh start` / `start all`; it can still be started by name. ### Dev mode (tmux) @@ -323,11 +331,6 @@ freshly-started process. tmux mode is for local development; production stays on - **Query logging (`[querylog]`) wraps `.z.*` by direct assignment.** If a phased event's `exec` is claimed after startup, logging for that event silently drops to zero with no error. See [Query logging](#query-logging-optional). -- The builtin registry has exactly one entry (`` `hdb ``) so far - every other - proctype in a real deployment would be custom, until more `di.*` process-type - modules exist. -- No `di.torq.depcheck`-style pre-flight dependency validation yet (next up per the - modularisation plan). - `autodetect`'s host-matching has no `-procfile` override and no FinSpace-specific host handling - deliberately out of scope, same scoping-down `di.torq.servers` applies to its own `process.csv` reading. diff --git a/di/torq/torq.q b/di/torq/torq.q index e676b63f..f2868b88 100644 --- a/di/torq/torq.q +++ b/di/torq/torq.q @@ -4,7 +4,7 @@ / same init[config;deps] calling convention. / built-in process type registry: proctype -> di.* module name -builtin:`hdb`tickerplant`rdb`wdb`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker`discovery!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.wdb`di.torq.proc.discovery +builtin:`hdb`tickerplant`rdb`wdb`sort`gateway`idb`segmentedtp`chainedtp`housekeeping`sortworker`discovery`tickerlogreplay`segmentedchainedtp!`di.torq.proc.hdb`di.torq.proc.tickerplant`di.torq.proc.rdb`di.torq.proc.wdb`di.torq.proc.wdb`di.torq.proc.gateway`di.torq.proc.idb`di.torq.proc.segmentedtp`di.torq.proc.chainedtp`di.torq.proc.housekeeping`di.torq.proc.wdb`di.torq.proc.discovery`di.torq.proc.tickerlogreplay`di.torq.proc.segmentedtp reqenv:{[e] v:getenv e; @@ -280,7 +280,9 @@ init:{[proctype;procname;overrides] logdep:buildlogdep[overrides]; cc:use`di.torq.config; (cc`init)[enlist[`log]!enlist logdep]; - config:(cc`cascade)[r 0;r 1;proctype;procname]; + / segmentedchainedtp uses segmentedtp's settings + settingsproctype:$[proctype=`segmentedchainedtp;`segmentedtp;proctype]; + config:(cc`cascade)[r 0;r 1;settingsproctype;procname]; / command-line override layer - the TOP cascade tier. A launch flag matching a settings name / 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). @@ -301,6 +303,9 @@ init:{[proctype;procname;overrides] / the rolled files too, matching torq.q's own ordering. lr:use`di.torq.logroll; (lr`init)[config;deps]; + / init functions a process defers until pubsub and connections are initialised + set[`.proc.initlist;()]; + set[`.proc.addinitlist;{[x] .proc.initlist,:enlist x}]; $[proctype in key builtin; startbuiltin[proctype;config;deps]; startcustom[proctype;config;deps] @@ -313,6 +318,8 @@ init:{[proctype;procname;overrides] if[@[value;`.ps.loaded;0b];.ps.initialise[]]; / initialise connections if[@[value;`.servers.STARTUP;0b];.servers.startup config]; + / run deferred init functions + if[count .proc.initlist;value each .proc.initlist;.proc.initlist:()]; / .z.* wrappers: clients, querylog, zpsignore last initclients[config;deps]; / optional query logging - a no-op unless [querylog] enabled=true. LAST of everything that binds .z.*, because diff --git a/di/tplog/VERSION b/di/tplog/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/tplog/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/tplog/init.q b/di/tplog/init.q index 3220f689..ff02774c 100644 --- a/di/tplog/init.q +++ b/di/tplog/init.q @@ -68,5 +68,7 @@ repairover:{[logfile;goodlogh;d] :@[d;`start`size;:;(ns;chunk)]; }; -export:([check;repair]) +version:first read0`:::VERSION + +export:([check;repair;version]) diff --git a/di/tplog/tplog.md b/di/tplog/tplog.md index 25542e07..c96b4f52 100644 --- a/di/tplog/tplog.md +++ b/di/tplog/tplog.md @@ -205,6 +205,6 @@ test_repair_garbage_at_end[] The module exports: ```q -export:([check;repair]) +export:([check;repair;version]) ```