@outputai/core 0.17.1-next.b47353f.0 → 0.18.1-dev.72b80da.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,4 +1,5 @@
1
1
  import { sleepCancellable } from '#helpers/promise';
2
+ import { CancelableRunner } from '#helpers/cancelable_runner';
2
3
  import { createChildLogger } from '#logger';
3
4
  import { setTimeout as delay } from 'node:timers/promises';
4
5
 
@@ -18,20 +19,40 @@ const HEALTHY_LOG_EVERY_LOOPS = 60;
18
19
  * Watches the Temporal connection health.
19
20
  * Rejects with a ConnectionLostError once the connection is considered lost.
20
21
  */
21
- export class TemporalConnectionMonitor {
22
+ export class TemporalConnectionMonitor extends CancelableRunner {
22
23
  #maxFailures = MAX_FAILURES;
23
24
  #checkIntervalMs = CHECK_INTERVAL_MS;
24
25
  #checkTimeoutMs = CHECK_TIMEOUT_MS;
25
26
 
26
- #abortCtrl = new AbortController();
27
27
  #failures = 0;
28
28
  #loops = 0;
29
- #running = false;
30
- #execution = null;
31
29
  #connection = null;
32
- #signal = null;
33
30
 
34
- #watch = async signal => {
31
+ /**
32
+ * @param {object} options
33
+ * @param {import('@temporalio/worker').NativeConnection} options.connection - Temporal connection
34
+ * @param {AbortSignal} options.signal - stops watching when aborted
35
+ * @param {object} [options.overrides] - health check tuning, mostly for tests
36
+ */
37
+ constructor( { connection, signal, overrides = {} } ) {
38
+ super( { signal } );
39
+ this.#connection = connection;
40
+ if ( Number.isFinite( overrides?.maxFailures ) ) {
41
+ this.#maxFailures = overrides.maxFailures;
42
+ }
43
+ if ( Number.isFinite( overrides?.checkIntervalMs ) ) {
44
+ this.#checkIntervalMs = overrides.checkIntervalMs;
45
+ }
46
+ if ( Number.isFinite( overrides?.checkTimeoutMs ) ) {
47
+ this.#checkTimeoutMs = overrides.checkTimeoutMs;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * @inheritdoc
53
+ * @param {AbortSignal} signal
54
+ */
55
+ async run( signal ) {
35
56
  while ( !signal.aborted ) {
36
57
  try {
37
58
  await Promise.race( [
@@ -58,7 +79,7 @@ export class TemporalConnectionMonitor {
58
79
  const failureMessage = error?.message ?? String( error );
59
80
  if ( ++this.#failures >= this.#maxFailures ) {
60
81
  log.warn( 'Connection lost', { error: failureMessage, failures: this.#failures } );
61
- this.#abortCtrl.abort();
82
+ this.abort();
62
83
  throw new ConnectionLostError( 'Connection lost', { cause: error } );
63
84
  }
64
85
 
@@ -68,62 +89,5 @@ export class TemporalConnectionMonitor {
68
89
  this.#loops++;
69
90
  await sleepCancellable( this.#checkIntervalMs, signal );
70
91
  }
71
- };
72
-
73
- /**
74
- * @param {object} options
75
- * @param {import('@temporalio/worker').NativeConnection} options.connection - Temporal connection
76
- * @param {AbortSignal} options.signal - stops watching when aborted
77
- * @param {object} [options.overrides] - health check tuning, mostly for tests
78
- */
79
- constructor( { connection, signal, overrides = {} } ) {
80
- this.#connection = connection;
81
- this.#signal = signal;
82
- if ( Number.isFinite( overrides?.maxFailures ) ) {
83
- this.#maxFailures = overrides.maxFailures;
84
- }
85
- if ( Number.isFinite( overrides?.checkIntervalMs ) ) {
86
- this.#checkIntervalMs = overrides.checkIntervalMs;
87
- }
88
- if ( Number.isFinite( overrides?.checkTimeoutMs ) ) {
89
- this.#checkTimeoutMs = overrides.checkTimeoutMs;
90
- }
91
- }
92
-
93
- /** Returns whether the monitor is watching */
94
- get running() {
95
- return this.#running;
96
- }
97
-
98
- /**
99
- * Starts watching the connection. Aborting the signal stops the watch.
100
- * @returns {Promise<void>} resolves when the watch has stopped, rejects when the connection is lost
101
- */
102
- start() {
103
- if ( this.#execution ) {
104
- return this.#execution;
105
- }
106
-
107
- const signal = AbortSignal.any( [ this.#signal, this.#abortCtrl.signal ] );
108
-
109
- if ( signal.aborted ) {
110
- return Promise.resolve();
111
- }
112
-
113
- this.#running = true;
114
- this.#execution = this.#watch( signal ).finally( () => {
115
- this.#running = false;
116
- } );
117
-
118
- return this.#execution;
119
- }
120
-
121
- /**
122
- * Stops watching, without reporting a connection loss.
123
- * @returns {Promise<void>} resolves when the watch has fully stopped, rejects when it failed
124
- */
125
- stop() {
126
- this.#abortCtrl.abort();
127
- return this.#execution ?? Promise.resolve();
128
92
  }
129
93
  };
@@ -34,15 +34,17 @@ import { WorkerRunner } from './worker_runner.js';
34
34
  import { shutdownServices } from './shutdown.js';
35
35
  import { init as initCredentials } from '#credentials/init';
36
36
  import { buildWorkerOptions } from './worker_options.js';
37
+ import { LLMPricingRetriever } from '../llm/pricing/job.js';
37
38
 
38
39
  import './log_hooks.js';
39
40
 
40
41
  const log = createChildLogger( 'Worker' );
41
42
 
42
43
  const services = {
44
+ catalogPublisher: null,
43
45
  connection: null,
44
46
  connectionMonitor: null,
45
- catalogPublisher: null,
47
+ llmPricingRetriever: null,
46
48
  workerRunner: null
47
49
  };
48
50
 
@@ -96,14 +98,20 @@ const execute = async () => {
96
98
  log.info( 'Setting up temporal endpoint...' );
97
99
  run( () => setupClientConfig( { connection, namespace } ) );
98
100
 
99
- log.info( 'Creating catalog publisher...' );
100
- services.catalogPublisher = run( () => new CatalogPublisher( { connection, namespace, catalog, catalogHash, signal } ) );
101
-
102
101
  log.info( 'Creating connection monitor...' );
103
102
  services.connectionMonitor = run( () => new TemporalConnectionMonitor( { connection, signal } ) );
104
103
 
105
104
  log.info( 'Publishing catalog workflow...' );
106
- await run( () => services.catalogPublisher.run() );
105
+ await run( () => {
106
+ services.catalogPublisher = new CatalogPublisher( { connection, namespace, catalog, catalogHash, signal } );
107
+ return services.catalogPublisher.start();
108
+ } );
109
+
110
+ log.info( 'Starting LLM pricing retriever...' );
111
+ run( () => {
112
+ services.llmPricingRetriever = new LLMPricingRetriever( { signal } );
113
+ services.llmPricingRetriever.start();
114
+ } );
107
115
 
108
116
  log.info( 'Creating Temporal worker...' );
109
117
  const worker = await run( () => Worker.create( {
@@ -3,45 +3,42 @@ import { createChildLogger } from '#logger';
3
3
 
4
4
  const log = createChildLogger( 'Worker Shutdown' );
5
5
 
6
+ /**
7
+ * Invokes a shutdown function with logs + timer
8
+ * Must invoke around a try/catch and await, since this handles both throws and rejections
9
+ */
10
+ const invokeShutdown = async ( fn, name, startedAt = Date.now() ) => {
11
+ log.info( `Stopping ${name}...` );
12
+ const getElapsed = () => Date.now() - startedAt;
13
+ try {
14
+ await fn();
15
+ log.info( `${name} stopped`, { elapsedMs: getElapsed() } );
16
+ } catch ( error ) {
17
+ log.warn( `${name} failed to stop`, {
18
+ error: serializeError( error ),
19
+ elapsedMs: getElapsed()
20
+ } );
21
+ }
22
+ };
23
+
6
24
  /**
7
25
  * Gracefully shuts every running service down, in order.
8
26
  * A service that fails to stop never interrupts the sequence
9
27
  */
10
- export const shutdownServices = async ( { workerRunner, connectionMonitor, catalogPublisher, connection } ) => {
11
- const shutdownJobs = [
12
- {
13
- label: 'Stopping Worker',
14
- isActive: () => workerRunner?.running,
15
- stop: () => workerRunner.stop()
16
- },
17
- {
18
- label: 'Stopping Connection Monitor',
19
- isActive: () => connectionMonitor?.running,
20
- stop: () => connectionMonitor.stop()
21
- },
22
- {
23
- label: 'Interrupting Catalog Publisher',
24
- isActive: () => catalogPublisher?.running,
25
- stop: () => catalogPublisher.interrupt()
26
- },
27
- {
28
- label: 'Closing Connection',
29
- isActive: () => connection,
30
- stop: () => connection.close()
31
- }
32
- ];
33
-
34
- for ( const { label, isActive, stop } of shutdownJobs ) {
35
- if ( isActive() ) {
36
- const shutdownStartedAt = Date.now();
37
- log.info( `${label}...` );
38
- // a try covers a service that throws instead of rejecting, which a catch on the promise would miss
39
- try {
40
- await stop();
41
- log.info( `${label} complete`, { shutdownDurationMs: Date.now() - shutdownStartedAt } );
42
- } catch ( error ) {
43
- log.warn( `${label} failed`, { error: serializeError( error ), shutdownDurationMs: Date.now() - shutdownStartedAt } );
44
- }
45
- }
28
+ export const shutdownServices = async services => {
29
+ if ( services.workerRunner?.running ) {
30
+ await invokeShutdown( () => services.workerRunner.stop(), 'Worker' );
31
+ }
32
+ if ( services.connectionMonitor?.running ) {
33
+ await invokeShutdown( () => services.connectionMonitor.stop(), 'Connection Monitor' );
34
+ }
35
+ if ( services.catalogPublisher?.running ) {
36
+ await invokeShutdown( () => services.catalogPublisher.stop(), 'Catalog Publisher' );
37
+ }
38
+ if ( services.llmPricingRetriever?.running ) {
39
+ await invokeShutdown( () => services.llmPricingRetriever.stop(), 'LLM Pricing Retriever' );
40
+ }
41
+ if ( services.connection ) {
42
+ await invokeShutdown( () => services.connection.close(), 'Temporal Connection' );
46
43
  }
47
44
  };
@@ -1,96 +0,0 @@
1
- import { Logger } from '#runtime_logger';
2
- import { EnvHttpProxyAgent, fetch } from 'undici';
3
- import modelsPricingSnapshot from './models_pricing_snapshot.json' with { type: 'json' };
4
-
5
- const logger = Logger.createLogger( 'LLM' );
6
- const costTableUrl = 'https://models.dev/api.json';
7
- const cacheTTL = 1000 * 60 * 60 * 24; // 1 day
8
- const cooldownTTL = 1000 * 60 * 10; // 10 minutes
9
-
10
- /* Ignore HTTP/2. Check: https://github.com/growthxai/output/issues/299 */
11
- const dispatcher = new EnvHttpProxyAgent( { allowH2: false } );
12
-
13
- export const cache = {
14
- content: null,
15
- expiresAt: 0
16
- };
17
-
18
- export const Freshness = {
19
- LIVE: 'live',
20
- CACHED: 'cached',
21
- STALE: 'stale',
22
- SNAPSHOT: 'snapshot'
23
- };
24
-
25
- export const state = {
26
- ignoreLiveRequestsUntil: 0
27
- };
28
-
29
- const parseData = data => {
30
- const map = new Map();
31
- try {
32
- for ( const [ providerId, provider ] of Object.entries( data ) ) {
33
- if ( providerId === '_meta' ) {
34
- continue;
35
- }
36
- for ( const [ modelName, { cost, reasoning } ] of Object.entries( provider.models ?? {} ) ) {
37
- if ( cost ) { // some models don't have cost
38
- map.set( `${providerId}/${modelName}`, {
39
- cost,
40
- reasoning: reasoning === true
41
- } );
42
- }
43
- }
44
- }
45
- if ( map.size === 0 ) {
46
- throw new Error( 'Empty response' );
47
- }
48
- return map;
49
- } catch ( error ) {
50
- logger.error( `Models pricing: Data parsing failure "${error.message}".` );
51
- return null;
52
- }
53
- };
54
-
55
- const fallbackTable = parseData( modelsPricingSnapshot );
56
-
57
- const fetchData = async () => {
58
- try {
59
- const res = await fetch( costTableUrl, { dispatcher } );
60
- if ( res.ok ) {
61
- return await res.json();
62
- } else {
63
- logger.error( `Models pricing: Data fetch HTTP error ${res.status}.` );
64
- return null;
65
- }
66
- } catch ( error ) {
67
- logger.error( `Models pricing: Data fetch failure "${error.code ?? error.name}".` );
68
- return null;
69
- }
70
- };
71
-
72
- export const fetchModelsPricing = async () => {
73
- if ( cache.content && cache.expiresAt > Date.now() ) {
74
- return { models: cache.content, freshness: Freshness.CACHED };
75
- }
76
-
77
- if ( state.ignoreLiveRequestsUntil < Date.now() ) {
78
- const table = await fetchData();
79
- const models = table ? parseData( table ) : null;
80
-
81
- if ( models ) {
82
- cache.content = models;
83
- cache.expiresAt = Date.now() + cacheTTL;
84
- return { models, freshness: Freshness.LIVE };
85
- } else {
86
- state.ignoreLiveRequestsUntil = Date.now() + cooldownTTL;
87
- }
88
- }
89
-
90
- if ( cache.content ) {
91
- logger.warn( 'Models pricing: using stale cache.' );
92
- return { models: cache.content, freshness: Freshness.STALE };
93
- }
94
- logger.warn( 'Models pricing: using built-in fallback.' );
95
- return { models: fallbackTable, freshness: Freshness.SNAPSHOT };
96
- };