@outputai/core 0.17.1-next.78fc808.0 → 0.18.0

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.
@@ -1,9 +1,15 @@
1
- import { Freshness } from '../models_pricing.js';
1
+ import { CacheFreshness, PricingSource } from '../../consts.js';
2
2
  import { LLMGenerationUsage, LLMGenerationUsageItem } from './llm_generation_usage.js';
3
3
  import Decimal from 'decimal.js';
4
4
  import { isNonNegativeNumber } from '#helpers/number';
5
5
  import { LLMGeneration } from './llm_generation.js';
6
6
 
7
+ const LLMGenerationCostStatus = Object.freeze( {
8
+ PRECISE: 'precise',
9
+ IMPRECISE: 'imprecise',
10
+ INCOMPLETE: 'incomplete'
11
+ } );
12
+
7
13
  export class LLMGenerationCostItem {
8
14
  static Status = Object.freeze( {
9
15
  OK: 'ok',
@@ -36,13 +42,52 @@ export class LLMGenerationCostItem {
36
42
  }
37
43
  }
38
44
 
45
+ const groupItems = rawItems => Map.groupBy( rawItems, e => e.key )
46
+ .values()
47
+ .toArray()
48
+ .map( items => {
49
+ if ( items.length === 1 ) {
50
+ return items[0];
51
+ }
52
+
53
+ const { group, label, ppm, status: itemStatus, tier } = items[0];
54
+ const amount = items.reduce( ( sum, item ) => sum + item.amount, 0 );
55
+ const itemTotal = isNonNegativeNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
56
+ return new LLMGenerationCostItem( group, label, amount, ppm, itemTotal, itemStatus, tier );
57
+ } );
58
+
59
+ const resolveStatus = ( { items, usageStatus, pricingFreshness } ) => {
60
+ const statuses = items.filter( i => i.amount > 0 ).reduce( ( summary, item ) =>
61
+ Object.assign( summary, { [item.status]: true } ), {} );
62
+
63
+ const hasMissing = statuses[LLMGenerationCostItem.Status.MISSING];
64
+ const hasFallback = statuses[LLMGenerationCostItem.Status.FALLBACK];
65
+ const hasUncertain = statuses[LLMGenerationCostItem.Status.UNCERTAIN];
66
+ const isIncomplete = usageStatus === LLMGenerationUsage.Status.INCOMPLETE;
67
+ const isSnapshot = pricingFreshness === CacheFreshness.SNAPSHOT;
68
+
69
+ if ( hasMissing || isIncomplete ) {
70
+ return LLMGenerationCostStatus.INCOMPLETE;
71
+ }
72
+
73
+ if ( hasFallback || hasUncertain || isSnapshot ) {
74
+ return LLMGenerationCostStatus.IMPRECISE;
75
+ }
76
+
77
+ return LLMGenerationCostStatus.PRECISE;
78
+ };
79
+
80
+ /**
81
+ * Sum item totals. If totals have value 0, return 0. If there are no items with total, return null
82
+ */
83
+ const sumItemsByGroup = ( items, group ) => {
84
+ const meaningfulItems = items.filter( p => p.group === group && isNonNegativeNumber( p.total ) );
85
+ return meaningfulItems.length > 0 ? meaningfulItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
86
+ };
87
+
39
88
  export class LLMGenerationCost extends LLMGeneration {
40
89
  static TYPE = 'llm:generation:cost';
41
- static Status = Object.freeze( {
42
- PRECISE: 'precise',
43
- IMPRECISE: 'imprecise',
44
- INCOMPLETE: 'incomplete'
45
- } );
90
+ static Status = LLMGenerationCostStatus;
46
91
 
47
92
  input = null;
48
93
  output = null;
@@ -50,50 +95,40 @@ export class LLMGenerationCost extends LLMGeneration {
50
95
  total = null;
51
96
  status = LLMGenerationCost.Status.INCOMPLETE;
52
97
  pricingFreshness = null;
98
+ pricingSource;
53
99
  items = [];
54
100
 
55
- constructor( modelId, providerId, promptName, requestDetails, items, usageStatus, pricingFreshness ) {
56
- super( LLMGenerationCost.TYPE, modelId, providerId, promptName, requestDetails );
101
+ static buildFromProvider( { modelId, providerId, promptName, requestDetails, total, status } ) {
102
+ const instance = new LLMGenerationCost( modelId, providerId, promptName, requestDetails );
103
+ instance.pricingSource = PricingSource.PROVIDER;
104
+ instance.total = total;
105
+ instance.status = status;
106
+ return instance;
107
+ }
57
108
 
58
- // group items with the same key, summing amount
59
- this.items = Map.groupBy( items, e => e.key )
60
- .values()
61
- .toArray()
62
- .map( items => {
63
- if ( items.length === 1 ) {
64
- return items[0];
65
- }
66
-
67
- const { group, label, ppm, status, tier } = items[0];
68
- const amount = items.reduce( ( sum, item ) => sum + item.amount, 0 );
69
- const total = isNonNegativeNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
70
- return new LLMGenerationCostItem( group, label, amount, ppm, total, status, tier );
71
- } );
72
-
73
- this.pricingFreshness = pricingFreshness;
74
-
75
- const meaningfulItems = this.items.filter( v => v.amount > 0 );
76
- const hasMissingItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.MISSING );
77
- const hasFallbackItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.FALLBACK );
78
- const hasUncertainItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.UNCERTAIN );
79
-
80
- if ( hasMissingItems || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
81
- this.status = LLMGenerationCost.Status.INCOMPLETE;
82
- } else if ( hasFallbackItems || pricingFreshness === Freshness.SNAPSHOT || hasUncertainItems ) {
83
- this.status = LLMGenerationCost.Status.IMPRECISE;
84
- } else {
85
- this.status = LLMGenerationCost.Status.PRECISE;
86
- }
109
+ static buildFromModelsDev( { modelId, providerId, promptName, requestDetails, items: rawItems, usageStatus, pricingFreshness } ) {
110
+ const items = groupItems( rawItems );
111
+ const status = resolveStatus( { items, usageStatus, pricingFreshness } );
112
+ const input = sumItemsByGroup( items, LLMGenerationUsageItem.Group.INPUT );
113
+ const output = sumItemsByGroup( items, LLMGenerationUsageItem.Group.OUTPUT );
114
+ const tools = sumItemsByGroup( items, LLMGenerationUsageItem.Group.TOOLS );
87
115
 
88
- const sumGroup = group => {
89
- const groupItems = this.items.filter( p => p.group === group && isNonNegativeNumber( p.total ) );
90
- return groupItems.length > 0 ? groupItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
91
- };
92
- this.input = sumGroup( LLMGenerationUsageItem.Group.INPUT );
93
- this.output = sumGroup( LLMGenerationUsageItem.Group.OUTPUT );
94
- this.tools = sumGroup( LLMGenerationUsageItem.Group.TOOLS );
95
- if ( isNonNegativeNumber( this.input ) || isNonNegativeNumber( this.output ) || isNonNegativeNumber( this.tools ) ) {
96
- this.total = Decimal( this.input ?? 0 ).add( this.output ?? 0 ).add( this.tools ?? 0 ).toNumber();
97
- }
116
+ const totals = [ input, output, tools ].filter( isNonNegativeNumber );
117
+ const total = totals.length > 0 ? totals.reduce( ( s, v ) => s.add( v ), Decimal( 0 ) ).toNumber() : null;
118
+
119
+ const instance = new LLMGenerationCost( modelId, providerId, promptName, requestDetails );
120
+ instance.pricingSource = PricingSource.MODELS_DEV;
121
+ instance.pricingFreshness = pricingFreshness;
122
+ instance.items = items;
123
+ instance.status = status;
124
+ instance.input = input;
125
+ instance.output = output;
126
+ instance.tools = tools;
127
+ instance.total = total;
128
+ return instance;
129
+ }
130
+
131
+ constructor( modelId, providerId, promptName, requestDetails = null ) {
132
+ super( LLMGenerationCost.TYPE, modelId, providerId, promptName, requestDetails );
98
133
  }
99
134
  }
@@ -1,4 +1,4 @@
1
- import { fetchModelsPricing } from './models_pricing.js';
1
+ import { getPricing } from '../pricing/cache.js';
2
2
  import { LLMGenerationUsage, LLMGenerationUsageItem } from './attributes/llm_generation_usage.js';
3
3
  import { resolveWebSearchPpm } from './web_search.js';
4
4
  import { Logger } from '#runtime_logger';
@@ -119,16 +119,10 @@ const hasTiers = modelPricing => Array.isArray( modelPricing?.cost?.tiers ) && m
119
119
  *
120
120
  * @param {LLMGenerationUsage} usage - Normalized LLM generation usage
121
121
  * @param {LLMGenerationUsage[]} stepsUsage - Per-request usage for multi-step calls
122
- * @returns {Promise<LLMGenerationCost | null>} LLM generation cost with input, output, total and breakdown
122
+ * @returns {LLMGenerationCost} LLM generation cost with input, output, total and breakdown
123
123
  */
124
- export const calculateCosts = async ( usage, stepsUsage ) => {
125
- const { models, freshness: pricingFreshness } = await fetchModelsPricing();
126
-
127
- if ( !models ) {
128
- Logger.warn( 'Failed to fetch models pricing', { namespace: 'LLM' } );
129
- return null;
130
- }
131
-
124
+ export const calculateCosts = ( usage, stepsUsage ) => {
125
+ const { models, freshness: pricingFreshness } = getPricing();
132
126
  const { providerId, modelId } = usage;
133
127
 
134
128
  const modelPricing = models.get( `${providerId}/${modelId}` );
@@ -143,24 +137,34 @@ export const calculateCosts = async ( usage, stepsUsage ) => {
143
137
  Logger.warn( 'Tool call with no rate for model', { namespace: 'LLM', modelId, providerId, type: unrated.label } );
144
138
  }
145
139
 
146
- return new LLMGenerationCost( modelId, providerId, usage.promptName, usage.requestDetails, items, usage.status, pricingFreshness );
140
+ return LLMGenerationCost.buildFromModelsDev( {
141
+ modelId,
142
+ providerId,
143
+ promptName: usage.promptName,
144
+ requestDetails: usage.requestDetails,
145
+ items,
146
+ usageStatus: usage.status,
147
+ pricingFreshness
148
+ } );
147
149
  };
148
150
 
149
151
  /**
150
152
  * Calculates a cost using the legacy aggregate pricing behavior.
151
153
  *
152
154
  * @param {LLMGenerationUsage} usage - Normalized aggregate LLM generation usage
153
- * @returns {Promise<LLMGenerationCost | null>} Cost compatible with the legacy conversion
155
+ * @returns {LLMGenerationCost} Cost compatible with the legacy conversion
154
156
  */
155
- export const calculateLegacyCosts = async usage => {
156
- const { models, freshness: pricingFreshness } = await fetchModelsPricing();
157
- if ( !models ) {
158
- return null;
159
- }
160
-
157
+ export const calculateLegacyCosts = usage => {
158
+ const { models } = getPricing();
161
159
  const { providerId, modelId } = usage;
162
160
  const modelPricing = models.get( `${providerId}/${modelId}` );
163
161
  const items = calculateStandardUsage( usage, modelPricing );
164
162
 
165
- return new LLMGenerationCost( modelId, providerId, null, null, items, usage.status, pricingFreshness );
163
+ return LLMGenerationCost.buildFromModelsDev( {
164
+ modelId,
165
+ providerId,
166
+ promptName: null,
167
+ requestDetails: null,
168
+ items
169
+ } );
166
170
  };
@@ -1,7 +1,9 @@
1
1
  import { BaseAttribute } from '#trace_attribute';
2
2
  import Decimal from 'decimal.js';
3
+ import { LLMGenerationCostItem } from './attributes/llm_generation_cost.js';
3
4
 
4
5
  const exists = v => Number.isFinite( v );
6
+ const { FALLBACK, MISSING } = LLMGenerationCostItem.Status;
5
7
 
6
8
  /** Legacy priced usage attribute retained for trace compatibility. */
7
9
  export class LLMUsageLegacy extends BaseAttribute {
@@ -30,7 +32,7 @@ export class LLMUsageLegacy extends BaseAttribute {
30
32
  }
31
33
 
32
34
  export const convertCostToLegacy = cost => {
33
- if ( !cost || cost.items.every( v => v.status === 'missing' ) ) {
35
+ if ( !cost || cost.items.every( v => v.status === MISSING ) ) {
34
36
  return null;
35
37
  }
36
38
 
@@ -55,7 +57,7 @@ export const convertCostToLegacy = cost => {
55
57
  }
56
58
 
57
59
  if ( cacheReadItem ) {
58
- const ppm = [ 'fallback', 'missing' ].includes( cacheReadItem.status ) ? 0 : cacheReadItem.ppm;
60
+ const ppm = [ FALLBACK, MISSING ].includes( cacheReadItem.status ) ? 0 : cacheReadItem.ppm;
59
61
  usage.push( { type: 'input_cached', ppm, amount: cacheReadItem.amount } );
60
62
  }
61
63
  }
@@ -1,5 +1,7 @@
1
1
  import { parseLLMUsage } from './usage.js';
2
2
  import { calculateCosts, calculateLegacyCosts } from './cost.js';
3
+ import { calculateProviderCosts } from './provider_cost.js';
4
+ import { getStepCostExtractorForProvider } from '../ai_provider.js';
3
5
  import { stepEventBus } from '#bus';
4
6
  import { addEventActionWithContext, EventAction } from '#tracing';
5
7
  import { Logger } from '#runtime_logger';
@@ -27,24 +29,39 @@ export class Metering {
27
29
  legacy: null
28
30
  };
29
31
 
30
- async #createAttributes( { usage, steps, requestDetails } ) {
32
+ #createAttributes( { usage, steps, requestDetails, response } ) {
31
33
  const baseUsageArgs = {
32
34
  prompt: this.#prompt,
33
35
  toolIdsByName: this.#toolIdsByName
34
36
  };
35
37
  // Only the call-level usage carries the request details; the per-step usages feed the tiered cost items only
36
38
  const totalUsage = parseLLMUsage( { ...baseUsageArgs, usage, steps, requestDetails } );
37
- const stepsUsage = steps.map( step => parseLLMUsage( { ...baseUsageArgs, usage: step.usage, steps: [ step ] } ) );
38
39
 
39
40
  this.#attributes.usage = totalUsage;
40
- if ( this.#attributes.usage ) {
41
- this.#attributes.cost = await calculateCosts( this.#attributes.usage, stepsUsage );
41
+ if ( !this.#attributes.usage ) {
42
+ return;
43
+ }
42
44
 
43
- if ( this.#attributes.cost ) {
44
- // @TEMP Preserve the deprecated event and trace attribute for legacy consumers.
45
- const legacyCost = await calculateLegacyCosts( this.#attributes.usage );
46
- this.#attributes.legacy = convertCostToLegacy( legacyCost );
47
- }
45
+ const extractStepCost = getStepCostExtractorForProvider( this.#prompt?.config?.provider );
46
+ if ( extractStepCost ) {
47
+ // Provider-reported path: never models.dev, and legacy cost is unsupported
48
+ this.#attributes.cost = calculateProviderCosts( {
49
+ usage: this.#attributes.usage,
50
+ steps,
51
+ response,
52
+ extractor: extractStepCost
53
+ } );
54
+ return;
55
+ }
56
+
57
+ const stepsUsage = steps.map( step => parseLLMUsage( { ...baseUsageArgs, usage: step.usage, steps: [ step ] } ) );
58
+
59
+ this.#attributes.cost = calculateCosts( this.#attributes.usage, stepsUsage );
60
+
61
+ if ( this.#attributes.cost ) {
62
+ // @TEMP Preserve the deprecated event and trace attribute for legacy consumers.
63
+ const legacyCost = calculateLegacyCosts( this.#attributes.usage );
64
+ this.#attributes.legacy = convertCostToLegacy( legacyCost );
48
65
  }
49
66
  }
50
67
 
@@ -103,9 +120,9 @@ export class Metering {
103
120
  *
104
121
  * @param {object} [response] - AI SDK response, whose aggregate usage and steps take precedence
105
122
  * over the recorded steps; omitted by the paths that end without one
106
- * @returns {Promise<void>}
123
+ * @returns {void}
107
124
  */
108
- bill = async ( response = null ) => {
125
+ bill = ( response = null ) => {
109
126
  if ( this.#billed ) {
110
127
  return;
111
128
  }
@@ -127,7 +144,7 @@ export class Metering {
127
144
 
128
145
  this.#billed = true;
129
146
 
130
- await this.#createAttributes( { usage, steps, requestDetails } );
147
+ this.#createAttributes( { usage, steps, requestDetails, response } );
131
148
  this.#attachAttributes();
132
149
  this.#emitEvents();
133
150
 
@@ -0,0 +1,70 @@
1
+ import Decimal from 'decimal.js';
2
+ import { isNonNegativeNumber } from '#helpers/number';
3
+ import { LLMGenerationCost } from './attributes/llm_generation_cost.js';
4
+ import { serializeError } from '#helpers/error_serializer';
5
+ import { Logger } from '#runtime_logger';
6
+
7
+ /**
8
+ * Steps for provider-reported cost when the call has none: `finalStep`, else top-level
9
+ * `providerMetadata` as a single synthetic step. Real steps (response or recorded) win first.
10
+ *
11
+ * @param {object} args
12
+ * @param {object[]} args.steps - Steps already chosen by metering (`response.steps` or recorded)
13
+ * @param {object|null|undefined} [args.response] - AI SDK response, when present
14
+ * @returns {object[]}
15
+ */
16
+ export const resolveProviderCostSteps = ( { steps, response } ) => {
17
+ if ( steps.length > 0 ) {
18
+ return steps;
19
+ }
20
+ if ( response?.finalStep ) {
21
+ return [ response.finalStep ];
22
+ }
23
+ if ( response?.providerMetadata !== undefined && response.providerMetadata !== null ) {
24
+ return [ { providerMetadata: response.providerMetadata } ];
25
+ }
26
+ return [];
27
+ };
28
+
29
+ /**
30
+ * Builds an {@link LLMGenerationCost} from a provider-reported dollar amount per step.
31
+ *
32
+ * Never reads models.dev. Empty or missing amounts yield `total: null` and status `incomplete`.
33
+ * With no steps, falls back via {@link resolveProviderCostSteps}.
34
+ *
35
+ * @param {object} args
36
+ * @param {import('./attributes/llm_generation_usage.js').LLMGenerationUsage} args.usage - normalized usage
37
+ * @param {object[]} args.steps - AI SDK steps (or recorded steps) carrying `providerMetadata`
38
+ * @param {object|null|undefined} [args.response] - AI SDK response used only when `steps` is empty
39
+ * @param {(providerMetadata: object|undefined) => number|null} args.extractor - registered step cost extractor
40
+ * @returns {LLMGenerationCost}
41
+ */
42
+ export const calculateProviderCosts = ( { usage, steps, response, extractor } ) => {
43
+ const { modelId, providerId, promptName, requestDetails } = usage;
44
+ const stepList = resolveProviderCostSteps( {
45
+ steps: Array.isArray( steps ) ? steps : [],
46
+ response
47
+ } );
48
+
49
+ const stepCosts = stepList
50
+ .map( step => {
51
+ try {
52
+ return extractor( step?.providerMetadata );
53
+ } catch ( error ) {
54
+ Logger.warn( 'Error on extractStepCost()', {
55
+ namespace: 'LLM',
56
+ providerId,
57
+ error: serializeError( error )
58
+ } );
59
+ return null;
60
+ }
61
+ } )
62
+ .filter( a => isNonNegativeNumber( a ) );
63
+
64
+ const total = stepCosts.length > 0 ? stepCosts.reduce( ( s, v ) => s.add( v ), Decimal( 0 ) ).toNumber() : null;
65
+ const status = stepCosts.length === stepList.length && stepList.length > 0 ?
66
+ LLMGenerationCost.Status.PRECISE :
67
+ LLMGenerationCost.Status.INCOMPLETE;
68
+
69
+ return LLMGenerationCost.buildFromProvider( { modelId, providerId, promptName, requestDetails, total, status } );
70
+ };
@@ -81,7 +81,7 @@ export const wrapTextGeneration = async ( { name, prompt, toolIdsByName, fn } )
81
81
 
82
82
  const { result: response, error } = await inlineTryAsync( () => fn( { onStepEndHook } ) );
83
83
 
84
- await metering.bill( response );
84
+ metering.bill( response );
85
85
 
86
86
  if ( error ) {
87
87
  throw handleAiSdkError( { traceId, error } );
@@ -128,7 +128,7 @@ export const wrapImageGeneration = async ( { name, prompt, fn } ) => {
128
128
  throw handleAiSdkError( { traceId, error } );
129
129
  }
130
130
 
131
- await metering.bill( response );
131
+ metering.bill( response );
132
132
 
133
133
  try {
134
134
  const { usage, image: result, providerMetadata } = response;
@@ -145,7 +145,7 @@ export const wrapImageGeneration = async ( { name, prompt, fn } ) => {
145
145
  };
146
146
 
147
147
  /** Awaits a consumer callback, logging and swallowing its failures: the hooks are fire and forget */
148
- const invokeCallback = async ( cb, args, cbName ) => {
148
+ const fireCallback = async ( cb, args, cbName ) => {
149
149
  if ( typeof cb === 'function' ) {
150
150
  try {
151
151
  await cb( ...args );
@@ -211,20 +211,20 @@ export const wrapStream = ( { name, prompt, toolIdsByName, abortSignal, fn } ) =
211
211
 
212
212
  const onStepEndHook = metering.recordStep;
213
213
 
214
- const onAbortHook = async () => {
214
+ const onAbortHook = () => {
215
215
  removeAbortListener();
216
216
 
217
- await metering.bill();
217
+ metering.bill();
218
218
  // abortion was caused by timeout and not signal
219
219
  if ( !abortSignal?.aborted ) {
220
220
  handleAiSdkError( { traceId, error: new Error( 'Streaming timed out.' ) } );
221
221
  }
222
222
  };
223
223
 
224
- const onEndHook = async ( response, callback ) => {
224
+ const onEndHook = ( response, callback ) => {
225
225
  removeAbortListener();
226
226
 
227
- await metering.bill( response );
227
+ metering.bill( response );
228
228
 
229
229
  try {
230
230
  const { text: result, finalStep, usage } = response;
@@ -234,20 +234,20 @@ export const wrapStream = ( { name, prompt, toolIdsByName, abortSignal, fn } ) =
234
234
  const proxyResponse = createResponseProxy( { response, properties: { cost: metering.attributes.cost, sources, result } } );
235
235
  addEventActionWithContext( EventAction.END, { id: traceId, details: { result, usage, providerMetadata, sources } } );
236
236
 
237
- await invokeCallback( callback, [ proxyResponse ], 'onEnd' );
237
+ fireCallback( callback, [ proxyResponse ], 'onEnd' );
238
238
  } catch ( error ) {
239
239
  Logger.error( 'AI SDK response handling failed', { namespace: 'LLM', error: error?.message || String( error ) } );
240
240
  handleResponseError( { traceId, error } );
241
241
  }
242
242
  };
243
243
 
244
- const onErrorHook = async ( event, callback ) => {
244
+ const onErrorHook = ( event, callback ) => {
245
245
  removeAbortListener();
246
- await metering.bill();
246
+ metering.bill();
247
247
 
248
248
  const error = event?.error instanceof Error ? event.error : new Error( 'Streaming failed.', { cause: event?.error } );
249
249
  const mappedError = handleAiSdkError( { traceId, error } );
250
- await invokeCallback( callback, [ mappedError ], 'onError' );
250
+ fireCallback( callback, [ mappedError ], 'onError' );
251
251
  };
252
252
 
253
253
  const handleStreamError = error => {
@@ -3,6 +3,7 @@ import { WorkflowExecutionAlreadyStartedError, WorkflowIdConflictPolicy } from '
3
3
  import { WORKFLOW_CATALOG } from '#consts';
4
4
  import { catalogId as workflowId, taskQueue } from '../configs.js';
5
5
  import { createChildLogger } from '#logger';
6
+ import { CancelableRunner } from '#helpers/cancelable_runner';
6
7
  import { sleepCancellable } from '#helpers/promise';
7
8
  import { serializeError } from '#helpers/error_serializer';
8
9
 
@@ -16,17 +17,10 @@ const RETRY_DELAY = 10_000;
16
17
  const WORKFLOW_TASK_TIMEOUT = 30_000;
17
18
 
18
19
  /** Make sure the latest version of the catalog workflow is running. Stateful. */
19
- export class CatalogPublisher {
20
- #connection = null;
21
- #namespace = null;
20
+ export class CatalogPublisher extends CancelableRunner {
22
21
  #catalog = null;
23
22
  #catalogHash = null;
24
23
  #client = null;
25
- #signal = null;
26
-
27
- #abortCtrl = new AbortController();
28
- #running = false;
29
- #execution = null;
30
24
 
31
25
  async #describe() {
32
26
  log.info( 'Checking running catalog hash against worker hash...' );
@@ -58,7 +52,7 @@ export class CatalogPublisher {
58
52
  }
59
53
  };
60
54
 
61
- async #start() {
55
+ async #startWorkflow() {
62
56
  log.info( 'Starting catalog workflow...' );
63
57
 
64
58
  try {
@@ -87,8 +81,7 @@ export class CatalogPublisher {
87
81
  }
88
82
  }
89
83
 
90
- /** Run the sequence to start the catalog */
91
- async #execute( signal, retries = 0 ) {
84
+ async #publish( signal, retries = 0 ) {
92
85
  if ( signal.aborted ) {
93
86
  return;
94
87
  }
@@ -104,46 +97,39 @@ export class CatalogPublisher {
104
97
  await this.#terminate( description.runId );
105
98
  }
106
99
 
107
- const success = await this.#start();
100
+ const success = await this.#startWorkflow();
108
101
  log.info( success ? 'Catalog workflow started' : 'Found a catalog workflow with matching hashes, start skipped' );
109
102
  } catch ( error ) {
110
103
  if ( retries < MAX_RETRIES ) {
111
104
  log.warn( 'Error while starting catalog workflow, retrying...', { error: serializeError( error, { dropKeys: [ 'stack' ] } ) } );
112
105
  await sleepCancellable( RETRY_DELAY, signal );
113
- await this.#execute( signal, retries + 1 );
106
+ await this.#publish( signal, retries + 1 );
114
107
  } else {
115
108
  throw error;
116
109
  }
117
110
  }
118
111
  }
119
112
 
113
+ /**
114
+ * @inheritdoc
115
+ * @param {AbortSignal} signal
116
+ */
117
+ async run( signal ) {
118
+ return this.#publish( signal );
119
+ }
120
+
121
+ /**
122
+ * @param {object} options
123
+ * @param {import('@temporalio/client').Connection} options.connection
124
+ * @param {string} options.namespace
125
+ * @param {object} options.catalog
126
+ * @param {string} options.catalogHash
127
+ * @param {AbortSignal} options.signal
128
+ */
120
129
  constructor( { connection, namespace, catalog, catalogHash, signal } ) {
121
- this.#connection = connection;
122
- this.#namespace = namespace;
130
+ super( { signal } );
123
131
  this.#catalog = catalog;
124
132
  this.#catalogHash = catalogHash;
125
- this.#signal = signal;
126
- this.#client = new Client( { connection: this.#connection, namespace: this.#namespace } );
127
- }
128
-
129
- get running() {
130
- return this.#running;
131
- }
132
-
133
- run() {
134
- if ( this.#execution ) {
135
- return this.#execution;
136
- }
137
-
138
- const signal = AbortSignal.any( [ this.#signal, this.#abortCtrl.signal ] );
139
-
140
- this.#running = true;
141
- this.#execution = this.#execute( signal ).finally( _ => this.#running = false );
142
- return this.#execution;
143
- }
144
-
145
- interrupt() {
146
- this.#abortCtrl.abort();
147
- return this.#execution ?? Promise.resolve();
133
+ this.#client = new Client( { connection, namespace } );
148
134
  }
149
135
  };