@entifix/workflow 0.23.24 → 0.23.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,8 +25,9 @@ how long a finished flow keeps its journal (`'30 days'`, any `Duration`
25
25
  input). There is no default — a layer without it fails to build with
26
26
  `JournalRetentionUnset` — because the journal holds every flow's inputs. A
27
27
  purge runs beside the runner every `purgeInterval` (an hour by default) and
28
- empties the journal of flows that ended more than that long ago, keeping their
29
- status row; `onPurge` hears what each pass did.
28
+ empties the journal of flows that ended more than that long ago and whose
29
+ workflow has returned, keeping their status row; `onPurge` hears what each pass
30
+ did.
30
31
 
31
32
  ---
32
33
 
@@ -39,11 +39,15 @@ export declare class JournalRetentionUnset extends JournalRetentionUnset_base<{
39
39
  get message(): string;
40
40
  }
41
41
  /**
42
- * Purges one batch: the flows that ended more than `retention` ago and still
43
- * hold a journal lose their messages and replies — every one the workflow and
42
+ * Purges one batch: the flows that ended more than `retention` ago, whose
43
+ * workflow has returned, and that still hold a journal lose their messages and
44
+ * replies — every one the workflow and
44
45
  * its clock entity recorded under the flow's execution id — and their status
45
46
  * row keeps its state, step and timestamps but drops its payload columns and
46
- * is stamped purged. One statement, so a batch is all or nothing; rows locked
47
+ * is stamped purged. A flow's state turns terminal before its workflow writes
48
+ * its last step — the announcement of how it ended — so a journal is emptied
49
+ * only once the run's reply says it is complete; emptied sooner, that last
50
+ * step landed in a journal already stamped purged, and stayed. One statement, so a batch is all or nothing; rows locked
47
51
  * by a concurrent pass are skipped, never waited on. Answers how many flows it
48
52
  * purged.
49
53
  */
@@ -1 +1 @@
1
- {"version":3,"file":"journal-retention.d.ts","sourceRoot":"","sources":["../../src/postgres/journal-retention.ts"],"names":[],"mappings":"AACA,OAAO,EAAQ,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAIvC,+E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AAO,MAA4B,uEAoClC,CAAC;AAiBJ;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAAI,SAAS,gBAAgB,mEAgBxD,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { translateSqlError } from '@entifix/sql';
2
2
  import { Data, Duration, Effect, Layer, Option } from 'effect';
3
3
  import { SqlClient } from 'effect/sql';
4
+ import { SlipWorkflow } from '../interpreter/slip-workflow.js';
4
5
  import { TERMINAL_FLOW_STATES } from '../status/flow-status-store.js';
5
6
  /** How often the purge looks for journals past their retention, by default. */ export const JOURNAL_PURGE_INTERVAL = Duration.hours(1);
6
7
  /** Flows purged per statement, by default. */ export const JOURNAL_PURGE_BATCH = 100;
@@ -29,20 +30,33 @@ const positive = (input)=>Option.match(input === undefined ? Option.none() : Dur
29
30
  };
30
31
  });
31
32
  const TERMINAL = TERMINAL_FLOW_STATES.map((state)=>`'${state}'`).join(', ');
33
+ /** The entity the cluster runs a slip's workflow as. */ const SLIP_ENTITY = `'Workflow/${SlipWorkflow._tag}'`;
32
34
  /**
33
- * Purges one batch: the flows that ended more than `retention` ago and still
34
- * hold a journal lose their messages and replies — every one the workflow and
35
+ * Purges one batch: the flows that ended more than `retention` ago, whose
36
+ * workflow has returned, and that still hold a journal lose their messages and
37
+ * replies — every one the workflow and
35
38
  * its clock entity recorded under the flow's execution id — and their status
36
39
  * row keeps its state, step and timestamps but drops its payload columns and
37
- * is stamped purged. One statement, so a batch is all or nothing; rows locked
40
+ * is stamped purged. A flow's state turns terminal before its workflow writes
41
+ * its last step — the announcement of how it ended — so a journal is emptied
42
+ * only once the run's reply says it is complete; emptied sooner, that last
43
+ * step landed in a journal already stamped purged, and stayed. One statement, so a batch is all or nothing; rows locked
38
44
  * by a concurrent pass are skipped, never waited on. Answers how many flows it
39
45
  * purged.
40
46
  */ export const purgeFinishedJournals = (sql, retention, batch = JOURNAL_PURGE_BATCH)=>sql`
41
47
  WITH due AS (
42
- SELECT flow_id, execution_id FROM entifix_flow_status
48
+ SELECT flow_id, execution_id FROM entifix_flow_status status
43
49
  WHERE state IN (${sql.literal(TERMINAL)})
44
50
  AND purged_at IS NULL
45
51
  AND terminal_at < now() - make_interval(secs => ${Duration.toSeconds(retention)})
52
+ AND EXISTS (
53
+ SELECT 1 FROM cluster_messages run
54
+ JOIN cluster_replies reply ON reply.request_id = run.id
55
+ WHERE run.entity_id = status.execution_id
56
+ AND run.entity_type = ${sql.literal(SLIP_ENTITY)}
57
+ AND run.tag = 'run'
58
+ AND reply.payload::jsonb #>> '{value,_tag}' = 'Complete'
59
+ )
46
60
  ORDER BY terminal_at
47
61
  LIMIT ${batch}
48
62
  FOR UPDATE SKIP LOCKED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/postgres/journal-retention.ts"],"sourcesContent":["import { translateSqlError } from '@entifix/sql';\nimport { Data, Duration, Effect, Layer, Option } from 'effect';\nimport { SqlClient } from 'effect/sql';\n\nimport { TERMINAL_FLOW_STATES } from '../status/flow-status-store.js';\n\n/** How often the purge looks for journals past their retention, by default. */\nexport const JOURNAL_PURGE_INTERVAL = Duration.hours(1);\n/** Flows purged per statement, by default. */\nexport const JOURNAL_PURGE_BATCH = 100;\n\n/** What one purge pass did, for the host to log; the package logs nothing. */\nexport type JournalPurgeOutcome =\n | { readonly _tag: 'purged'; readonly flows: number }\n | { readonly _tag: 'purgeFailed'; readonly failure: unknown };\n\n/**\n * How long a finished flow's journal is kept. The journal holds every flow's\n * start input and step inputs, which can carry personal data, so retention is\n * the store owner's — the engine's — and the host must state it: there is no\n * default that silently keeps everything forever.\n */\nexport interface JournalRetention {\n /** How long after a flow ends its journal is purged. Required, and positive. */\n readonly journalRetention: Duration.Input;\n /** How often the purge runs. Defaults to {@link JOURNAL_PURGE_INTERVAL}. */\n readonly purgeInterval?: Duration.Input;\n /** Flows purged per statement. Defaults to {@link JOURNAL_PURGE_BATCH}. */\n readonly purgeBatch?: number;\n /** Told what each pass did. */\n readonly onPurge?: (outcome: JournalPurgeOutcome) => Effect.Effect<void>;\n}\n\n/** The engine was started without a usable retention for its journal. */\nexport class JournalRetentionUnset extends Data.TaggedError(\n 'JournalRetentionUnset',\n)<{ readonly dial: 'journalRetention'; readonly reason: string }> {\n override get message(): string {\n return this.reason;\n }\n}\n\nconst positive = (input: Duration.Input | undefined): Duration.Duration =>\n Option.match(\n input === undefined ? Option.none() : Duration.fromInput(input),\n {\n onNone: () => Duration.zero,\n onSome: duration => duration,\n },\n );\n\n/** The dials, checked; a retention that is missing, unreadable or not positive fails. */\nconst readRetention = (options: JournalRetention) =>\n Effect.gen(function* () {\n const retention = positive(options.journalRetention);\n if (!Duration.isGreaterThan(retention, Duration.zero)) {\n return yield* Effect.fail(\n new JournalRetentionUnset({\n dial: 'journalRetention',\n reason:\n options.journalRetention === undefined\n ? 'the flow engine needs journalRetention: how long a finished flow keeps its journal'\n : `journalRetention ${String(options.journalRetention)} is not a positive duration`,\n }),\n );\n }\n const interval = positive(options.purgeInterval);\n return {\n retention,\n interval: Duration.isGreaterThan(interval, Duration.zero)\n ? interval\n : JOURNAL_PURGE_INTERVAL,\n batch:\n options.purgeBatch !== undefined && options.purgeBatch > 0\n ? Math.floor(options.purgeBatch)\n : JOURNAL_PURGE_BATCH,\n };\n });\n\nconst TERMINAL = TERMINAL_FLOW_STATES.map(state => `'${state}'`).join(', ');\n\n/**\n * Purges one batch: the flows that ended more than `retention` ago and still\n * hold a journal lose their messages and replies — every one the workflow and\n * its clock entity recorded under the flow's execution id — and their status\n * row keeps its state, step and timestamps but drops its payload columns and\n * is stamped purged. One statement, so a batch is all or nothing; rows locked\n * by a concurrent pass are skipped, never waited on. Answers how many flows it\n * purged.\n */\nexport const purgeFinishedJournals = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number = JOURNAL_PURGE_BATCH,\n) =>\n sql<{ readonly flow_id: string }>`\n WITH due AS (\n SELECT flow_id, execution_id FROM entifix_flow_status\n WHERE state IN (${sql.literal(TERMINAL)})\n AND purged_at IS NULL\n AND terminal_at < now() - make_interval(secs => ${Duration.toSeconds(retention)})\n ORDER BY terminal_at\n LIMIT ${batch}\n FOR UPDATE SKIP LOCKED\n ),\n replies AS (\n DELETE FROM cluster_replies WHERE request_id IN (\n SELECT id FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n ),\n messages AS (\n DELETE FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n UPDATE entifix_flow_status\n SET correlation = NULL, accepts = NULL, purged_at = now()\n WHERE flow_id IN (SELECT flow_id FROM due)\n RETURNING flow_id`.pipe(\n Effect.map(rows => rows.length),\n Effect.mapError(error => translateSqlError(error)),\n );\n\n/** Purges batch after batch until one comes back short. */\nconst purgeAll = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number,\n) =>\n Effect.gen(function* () {\n let total = 0;\n for (;;) {\n const purged = yield* purgeFinishedJournals(sql, retention, batch);\n total += purged;\n if (purged < batch) return total;\n }\n });\n\n/**\n * The purge as a daemon beside the runner, for as long as the engine's layer\n * lives: one pass every interval, the first an interval after start — by then\n * the engine has created the tables it purges. A failed pass is reported and\n * the next one runs — a purge that stopped would look exactly like one with\n * nothing to do. Fails to build with {@link JournalRetentionUnset} when the\n * retention is not stated.\n */\nexport const JournalPurgeLayer = (options: JournalRetention) =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const { retention, interval, batch } = yield* readRetention(options);\n const sql = yield* SqlClient.SqlClient;\n const report = options.onPurge ?? (() => Effect.void);\n const pass = purgeAll(sql, retention, batch).pipe(\n Effect.matchEffect({\n onSuccess: flows => report({ _tag: 'purged', flows }),\n onFailure: failure => report({ _tag: 'purgeFailed', failure }),\n }),\n );\n yield* Effect.forkScoped(\n Effect.sleep(interval).pipe(Effect.andThen(pass), Effect.forever),\n );\n }),\n );\n"],"names":["translateSqlError","Data","Duration","Effect","Layer","Option","SqlClient","TERMINAL_FLOW_STATES","JOURNAL_PURGE_INTERVAL","hours","JOURNAL_PURGE_BATCH","JournalRetentionUnset","TaggedError","message","reason","positive","input","match","undefined","none","fromInput","onNone","zero","onSome","duration","readRetention","options","gen","retention","journalRetention","isGreaterThan","fail","dial","String","interval","purgeInterval","batch","purgeBatch","Math","floor","TERMINAL","map","state","join","purgeFinishedJournals","sql","literal","toSeconds","pipe","rows","length","mapError","error","purgeAll","total","purged","JournalPurgeLayer","effectDiscard","report","onPurge","void","pass","matchEffect","onSuccess","flows","_tag","onFailure","failure","forkScoped","sleep","andThen","forever"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,eAAe;AACjD,SAASC,IAAI,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/D,SAASC,SAAS,QAAQ,aAAa;AAEvC,SAASC,oBAAoB,QAAQ,iCAAiC;AAEtE,6EAA6E,GAC7E,OAAO,MAAMC,yBAAyBN,SAASO,KAAK,CAAC,GAAG;AACxD,4CAA4C,GAC5C,OAAO,MAAMC,sBAAsB,IAAI;AAwBvC,uEAAuE,GACvE,OAAO,MAAMC,8BAA8BV,KAAKW,WAAW,CACzD;IAEA,IAAaC,UAAkB;QAC7B,OAAO,IAAI,CAACC,MAAM;IACpB;AACF;AAEA,MAAMC,WAAW,CAACC,QAChBX,OAAOY,KAAK,CACVD,UAAUE,YAAYb,OAAOc,IAAI,KAAKjB,SAASkB,SAAS,CAACJ,QACzD;QACEK,QAAQ,IAAMnB,SAASoB,IAAI;QAC3BC,QAAQC,CAAAA,WAAYA;IACtB;AAGJ,uFAAuF,GACvF,MAAMC,gBAAgB,CAACC,UACrBvB,OAAOwB,GAAG,CAAC;QACT,MAAMC,YAAYb,SAASW,QAAQG,gBAAgB;QACnD,IAAI,CAAC3B,SAAS4B,aAAa,CAACF,WAAW1B,SAASoB,IAAI,GAAG;YACrD,OAAO,OAAOnB,OAAO4B,IAAI,CACvB,IAAIpB,sBAAsB;gBACxBqB,MAAM;gBACNlB,QACEY,QAAQG,gBAAgB,KAAKX,YACzB,uF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AAE,GAAG,OAAOX,cAAcC;QAC5D,MAAMmB,MAAM,OAAOvC,UAAUA,SAAS;QACtC,MAAMoD,UAAShC,mBAAAA,QAAQiC,OAAO,YAAfjC,mBAAoB,IAAMvB,OAAOyD,IAAI;QACpD,MAAMC,OAAOR,SAASR,KAAKjB,WAAWQ,OAAOY,IAAI,CAC/C7C,OAAO2D,WAAW,CAAC;YACjBC,WAAWC,CAAAA,QAASN,OAAO;oBAAEO,MAAM;oBAAUD;gBAAM;YACnDE,WAAWC,CAAAA,UAAWT,OAAO;oBAAEO,MAAM;oBAAeE;gBAAQ;QAC9D;QAEF,OAAOhE,OAAOiE,UAAU,CACtBjE,OAAOkE,KAAK,CAACnC,UAAUc,IAAI,CAAC7C,OAAOmE,OAAO,CAACT,OAAO1D,OAAOoE,OAAO;IAEpE,IACA"}
1
+ {"version":3,"sources":["../../src/postgres/journal-retention.ts"],"sourcesContent":["import { translateSqlError } from '@entifix/sql';\nimport { Data, Duration, Effect, Layer, Option } from 'effect';\nimport { SqlClient } from 'effect/sql';\n\nimport { SlipWorkflow } from '../interpreter/slip-workflow.js';\nimport { TERMINAL_FLOW_STATES } from '../status/flow-status-store.js';\n\n/** How often the purge looks for journals past their retention, by default. */\nexport const JOURNAL_PURGE_INTERVAL = Duration.hours(1);\n/** Flows purged per statement, by default. */\nexport const JOURNAL_PURGE_BATCH = 100;\n\n/** What one purge pass did, for the host to log; the package logs nothing. */\nexport type JournalPurgeOutcome =\n | { readonly _tag: 'purged'; readonly flows: number }\n | { readonly _tag: 'purgeFailed'; readonly failure: unknown };\n\n/**\n * How long a finished flow's journal is kept. The journal holds every flow's\n * start input and step inputs, which can carry personal data, so retention is\n * the store owner's — the engine's — and the host must state it: there is no\n * default that silently keeps everything forever.\n */\nexport interface JournalRetention {\n /** How long after a flow ends its journal is purged. Required, and positive. */\n readonly journalRetention: Duration.Input;\n /** How often the purge runs. Defaults to {@link JOURNAL_PURGE_INTERVAL}. */\n readonly purgeInterval?: Duration.Input;\n /** Flows purged per statement. Defaults to {@link JOURNAL_PURGE_BATCH}. */\n readonly purgeBatch?: number;\n /** Told what each pass did. */\n readonly onPurge?: (outcome: JournalPurgeOutcome) => Effect.Effect<void>;\n}\n\n/** The engine was started without a usable retention for its journal. */\nexport class JournalRetentionUnset extends Data.TaggedError(\n 'JournalRetentionUnset',\n)<{ readonly dial: 'journalRetention'; readonly reason: string }> {\n override get message(): string {\n return this.reason;\n }\n}\n\nconst positive = (input: Duration.Input | undefined): Duration.Duration =>\n Option.match(\n input === undefined ? Option.none() : Duration.fromInput(input),\n {\n onNone: () => Duration.zero,\n onSome: duration => duration,\n },\n );\n\n/** The dials, checked; a retention that is missing, unreadable or not positive fails. */\nconst readRetention = (options: JournalRetention) =>\n Effect.gen(function* () {\n const retention = positive(options.journalRetention);\n if (!Duration.isGreaterThan(retention, Duration.zero)) {\n return yield* Effect.fail(\n new JournalRetentionUnset({\n dial: 'journalRetention',\n reason:\n options.journalRetention === undefined\n ? 'the flow engine needs journalRetention: how long a finished flow keeps its journal'\n : `journalRetention ${String(options.journalRetention)} is not a positive duration`,\n }),\n );\n }\n const interval = positive(options.purgeInterval);\n return {\n retention,\n interval: Duration.isGreaterThan(interval, Duration.zero)\n ? interval\n : JOURNAL_PURGE_INTERVAL,\n batch:\n options.purgeBatch !== undefined && options.purgeBatch > 0\n ? Math.floor(options.purgeBatch)\n : JOURNAL_PURGE_BATCH,\n };\n });\n\nconst TERMINAL = TERMINAL_FLOW_STATES.map(state => `'${state}'`).join(', ');\n\n/** The entity the cluster runs a slip's workflow as. */\nconst SLIP_ENTITY = `'Workflow/${SlipWorkflow._tag}'`;\n\n/**\n * Purges one batch: the flows that ended more than `retention` ago, whose\n * workflow has returned, and that still hold a journal lose their messages and\n * replies — every one the workflow and\n * its clock entity recorded under the flow's execution id — and their status\n * row keeps its state, step and timestamps but drops its payload columns and\n * is stamped purged. A flow's state turns terminal before its workflow writes\n * its last step — the announcement of how it ended — so a journal is emptied\n * only once the run's reply says it is complete; emptied sooner, that last\n * step landed in a journal already stamped purged, and stayed. One statement, so a batch is all or nothing; rows locked\n * by a concurrent pass are skipped, never waited on. Answers how many flows it\n * purged.\n */\nexport const purgeFinishedJournals = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number = JOURNAL_PURGE_BATCH,\n) =>\n sql<{ readonly flow_id: string }>`\n WITH due AS (\n SELECT flow_id, execution_id FROM entifix_flow_status status\n WHERE state IN (${sql.literal(TERMINAL)})\n AND purged_at IS NULL\n AND terminal_at < now() - make_interval(secs => ${Duration.toSeconds(retention)})\n AND EXISTS (\n SELECT 1 FROM cluster_messages run\n JOIN cluster_replies reply ON reply.request_id = run.id\n WHERE run.entity_id = status.execution_id\n AND run.entity_type = ${sql.literal(SLIP_ENTITY)}\n AND run.tag = 'run'\n AND reply.payload::jsonb #>> '{value,_tag}' = 'Complete'\n )\n ORDER BY terminal_at\n LIMIT ${batch}\n FOR UPDATE SKIP LOCKED\n ),\n replies AS (\n DELETE FROM cluster_replies WHERE request_id IN (\n SELECT id FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n ),\n messages AS (\n DELETE FROM cluster_messages\n WHERE entity_id IN (SELECT execution_id FROM due)\n )\n UPDATE entifix_flow_status\n SET correlation = NULL, accepts = NULL, purged_at = now()\n WHERE flow_id IN (SELECT flow_id FROM due)\n RETURNING flow_id`.pipe(\n Effect.map(rows => rows.length),\n Effect.mapError(error => translateSqlError(error)),\n );\n\n/** Purges batch after batch until one comes back short. */\nconst purgeAll = (\n sql: SqlClient.SqlClient,\n retention: Duration.Duration,\n batch: number,\n) =>\n Effect.gen(function* () {\n let total = 0;\n for (;;) {\n const purged = yield* purgeFinishedJournals(sql, retention, batch);\n total += purged;\n if (purged < batch) return total;\n }\n });\n\n/**\n * The purge as a daemon beside the runner, for as long as the engine's layer\n * lives: one pass every interval, the first an interval after start — by then\n * the engine has created the tables it purges. A failed pass is reported and\n * the next one runs — a purge that stopped would look exactly like one with\n * nothing to do. Fails to build with {@link JournalRetentionUnset} when the\n * retention is not stated.\n */\nexport const JournalPurgeLayer = (options: JournalRetention) =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const { retention, interval, batch } = yield* readRetention(options);\n const sql = yield* SqlClient.SqlClient;\n const report = options.onPurge ?? (() => Effect.void);\n const pass = purgeAll(sql, retention, batch).pipe(\n Effect.matchEffect({\n onSuccess: flows => report({ _tag: 'purged', flows }),\n onFailure: failure => report({ _tag: 'purgeFailed', failure }),\n }),\n );\n yield* Effect.forkScoped(\n Effect.sleep(interval).pipe(Effect.andThen(pass), Effect.forever),\n );\n }),\n );\n"],"names":["translateSqlError","Data","Duration","Effect","Layer","Option","SqlClient","SlipWorkflow","TERMINAL_FLOW_STATES","JOURNAL_PURGE_INTERVAL","hours","JOURNAL_PURGE_BATCH","JournalRetentionUnset","TaggedError","message","reason","positive","input","match","undefined","none","fromInput","onNone","zero","onSome","duration","readRetention","options","gen","retention","journalRetention","isGreaterThan","fail","dial","String","interval","purgeInterval","batch","purgeBatch","Math","floor","TERMINAL","map","state","join","SLIP_ENTITY","_tag","purgeFinishedJournals","sql","literal","toSeconds","pipe","rows","length","mapError","error","purgeAll","total","purged","JournalPurgeLayer","effectDiscard","report","onPurge","void","pass","matchEffect","onSuccess","flows","onFailure","failure","forkScoped","sleep","andThen","forever"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,eAAe;AACjD,SAASC,IAAI,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/D,SAASC,SAAS,QAAQ,aAAa;AAEvC,SAASC,YAAY,QAAQ,kCAAkC;AAC/D,SAASC,oBAAoB,QAAQ,iCAAiC;AAEtE,6EAA6E,GAC7E,OAAO,MAAMC,yBAAyBP,SAASQ,KAAK,CAAC,GAAG;AACxD,4CAA4C,GAC5C,OAAO,MAAMC,sBAAsB,IAAI;AAwBvC,uEAAuE,GACvE,OAAO,MAAMC,8BAA8BX,KAA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@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/workflow",
3
- "version": "0.23.24",
3
+ "version": "0.23.26",
4
4
  "description": "Durable flows: the slip interpreter on Effect Workflow, behind the flow engine port, with Postgres storage and socket runners.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -89,16 +89,16 @@
89
89
  },
90
90
  "dependencies": {
91
91
  "@swc/helpers": "0.5.23",
92
- "@entifix/business": "0.23.24",
93
- "@entifix/core": "0.23.24",
94
- "@entifix/sql": "0.23.24",
95
- "@entifix/transactions": "0.23.24"
92
+ "@entifix/business": "0.23.26",
93
+ "@entifix/transactions": "0.23.26",
94
+ "@entifix/sql": "0.23.26",
95
+ "@entifix/core": "0.23.26"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@effect/platform-node": "4.0.7",
99
99
  "@effect/sql-pg": "4.0.7",
100
100
  "effect": "4.0.7",
101
- "@entifix/testing-unit": "0.23.24"
101
+ "@entifix/testing-unit": "0.23.26"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "@effect/platform-node": "^4.0.7",