apify-client 3.0.0-beta.1 → 3.0.0-beta.100

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.
Files changed (131) hide show
  1. package/README.md +21 -5
  2. package/dist/apify_api_error.d.ts +64 -22
  3. package/dist/apify_api_error.js +100 -30
  4. package/dist/apify_client.d.ts +150 -35
  5. package/dist/apify_client.js +198 -118
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/base/api_client.d.ts +9 -9
  9. package/dist/base/api_client.js +41 -45
  10. package/dist/base/resource_client.d.ts +24 -10
  11. package/dist/base/resource_client.js +78 -48
  12. package/dist/base/resource_collection_client.d.ts +15 -6
  13. package/dist/base/resource_collection_client.js +40 -21
  14. package/dist/body_parser.d.ts +3 -4
  15. package/dist/body_parser.js +20 -32
  16. package/dist/bundle.js +47 -52
  17. package/dist/bundle.js.map +1 -1
  18. package/dist/generated/api.d.ts +3363 -1185
  19. package/dist/generated/api.js +1 -2
  20. package/dist/generated/schemas.d.ts +8146 -0
  21. package/dist/generated/schemas.js +1866 -0
  22. package/dist/http_clients/axios.d.ts +61 -0
  23. package/dist/http_clients/axios.js +119 -0
  24. package/dist/http_clients/base.d.ts +391 -0
  25. package/dist/http_clients/base.js +650 -0
  26. package/dist/http_clients/index.d.ts +4 -0
  27. package/dist/http_clients/index.js +2 -0
  28. package/dist/http_compressors/base.d.ts +40 -0
  29. package/dist/http_compressors/base.js +9 -0
  30. package/dist/http_compressors/brotli.d.ts +33 -0
  31. package/dist/http_compressors/brotli.js +39 -0
  32. package/dist/http_compressors/gzip.d.ts +33 -0
  33. package/dist/http_compressors/gzip.js +39 -0
  34. package/dist/http_compressors/index.d.ts +8 -0
  35. package/dist/http_compressors/index.js +3 -0
  36. package/dist/http_compressors/resolve.d.ts +24 -0
  37. package/dist/http_compressors/resolve.js +30 -0
  38. package/dist/http_compressors/zstd.d.ts +34 -0
  39. package/dist/http_compressors/zstd.js +43 -0
  40. package/dist/index.d.ts +38 -32
  41. package/dist/index.js +36 -36
  42. package/dist/invalid_response_body_error.d.ts +14 -0
  43. package/dist/invalid_response_body_error.js +18 -0
  44. package/dist/lazy_schema.d.ts +8 -0
  45. package/dist/lazy_schema.js +11 -0
  46. package/dist/models.d.ts +196 -278
  47. package/dist/models.js +14 -15
  48. package/dist/resource_clients/actor.d.ts +115 -45
  49. package/dist/resource_clients/actor.js +187 -116
  50. package/dist/resource_clients/actor_collection.d.ts +21 -17
  51. package/dist/resource_clients/actor_collection.js +26 -21
  52. package/dist/resource_clients/actor_env_var.d.ts +13 -6
  53. package/dist/resource_clients/actor_env_var.js +21 -14
  54. package/dist/resource_clients/actor_env_var_collection.d.ts +18 -22
  55. package/dist/resource_clients/actor_env_var_collection.js +23 -20
  56. package/dist/resource_clients/actor_server.d.ts +149 -0
  57. package/dist/resource_clients/actor_server.js +199 -0
  58. package/dist/resource_clients/actor_version.d.ts +30 -10
  59. package/dist/resource_clients/actor_version.js +29 -23
  60. package/dist/resource_clients/actor_version_collection.d.ts +20 -21
  61. package/dist/resource_clients/actor_version_collection.js +25 -20
  62. package/dist/resource_clients/build.d.ts +24 -11
  63. package/dist/resource_clients/build.js +43 -26
  64. package/dist/resource_clients/build_collection.d.ts +10 -8
  65. package/dist/resource_clients/build_collection.js +13 -13
  66. package/dist/resource_clients/dataset.d.ts +87 -40
  67. package/dist/resource_clients/dataset.js +159 -175
  68. package/dist/resource_clients/dataset_collection.d.ts +13 -9
  69. package/dist/resource_clients/dataset_collection.js +29 -21
  70. package/dist/resource_clients/key_value_store.d.ts +110 -28
  71. package/dist/resource_clients/key_value_store.js +177 -99
  72. package/dist/resource_clients/key_value_store_collection.d.ts +13 -9
  73. package/dist/resource_clients/key_value_store_collection.js +29 -21
  74. package/dist/resource_clients/log.d.ts +42 -23
  75. package/dist/resource_clients/log.js +156 -85
  76. package/dist/resource_clients/request_queue.d.ts +77 -38
  77. package/dist/resource_clients/request_queue.js +251 -172
  78. package/dist/resource_clients/request_queue_collection.d.ts +12 -8
  79. package/dist/resource_clients/request_queue_collection.js +23 -20
  80. package/dist/resource_clients/run.d.ts +134 -34
  81. package/dist/resource_clients/run.js +225 -84
  82. package/dist/resource_clients/run_collection.d.ts +8 -6
  83. package/dist/resource_clients/run_collection.js +18 -18
  84. package/dist/resource_clients/schedule.d.ts +20 -11
  85. package/dist/resource_clients/schedule.js +36 -30
  86. package/dist/resource_clients/schedule_collection.d.ts +10 -6
  87. package/dist/resource_clients/schedule_collection.js +20 -17
  88. package/dist/resource_clients/store_collection.d.ts +9 -7
  89. package/dist/resource_clients/store_collection.js +18 -18
  90. package/dist/resource_clients/task.d.ts +44 -21
  91. package/dist/resource_clients/task.js +116 -86
  92. package/dist/resource_clients/task_collection.d.ts +13 -9
  93. package/dist/resource_clients/task_collection.js +19 -16
  94. package/dist/resource_clients/user.d.ts +22 -13
  95. package/dist/resource_clients/user.js +46 -47
  96. package/dist/resource_clients/webhook.d.ts +21 -12
  97. package/dist/resource_clients/webhook.js +35 -30
  98. package/dist/resource_clients/webhook_collection.d.ts +11 -7
  99. package/dist/resource_clients/webhook_collection.js +20 -17
  100. package/dist/resource_clients/webhook_dispatch.d.ts +9 -6
  101. package/dist/resource_clients/webhook_dispatch.js +11 -10
  102. package/dist/resource_clients/webhook_dispatch_collection.d.ts +7 -5
  103. package/dist/resource_clients/webhook_dispatch_collection.js +13 -13
  104. package/dist/response_validation_error.d.ts +27 -0
  105. package/dist/response_validation_error.js +38 -0
  106. package/dist/runtime/node.d.ts +6 -0
  107. package/dist/runtime/node.js +87 -0
  108. package/dist/runtime/types.d.ts +60 -0
  109. package/dist/runtime/types.js +1 -0
  110. package/dist/runtime/web.d.ts +5 -0
  111. package/dist/runtime/web.js +21 -0
  112. package/dist/schemas.d.ts +381 -0
  113. package/dist/schemas.js +37 -0
  114. package/dist/statistics.d.ts +1 -6
  115. package/dist/statistics.js +7 -11
  116. package/dist/timeouts.d.ts +84 -0
  117. package/dist/timeouts.js +37 -0
  118. package/dist/timezones.d.ts +1 -1
  119. package/dist/timezones.js +1 -2
  120. package/dist/utils.d.ts +99 -70
  121. package/dist/utils.js +251 -229
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +48 -47
  125. package/dist/argument_validation_error.d.ts +0 -17
  126. package/dist/argument_validation_error.js +0 -157
  127. package/dist/http_client.d.ts +0 -88
  128. package/dist/http_client.js +0 -260
  129. package/dist/index.mjs +0 -42
  130. package/dist/interceptors.d.ts +0 -19
  131. package/dist/interceptors.js +0 -110
@@ -1,8 +1,9 @@
1
1
  import type { Readable } from 'node:stream';
2
2
  import type { Log } from '@apify/log';
3
3
  import { Logger, LogLevel } from '@apify/log';
4
- import type { ApiClientSubResourceOptions } from '../base/api_client';
5
- import { ResourceClient } from '../base/resource_client';
4
+ import type { ApiClientSubResourceOptions } from '../base/api_client.js';
5
+ import { ResourceClient } from '../base/resource_client.js';
6
+ import type { TimeoutOptions } from '../timeouts.js';
6
7
  /**
7
8
  * Client for accessing Actor run or build logs.
8
9
  *
@@ -18,6 +19,9 @@ import { ResourceClient } from '../base/resource_client';
18
19
  * const log = await runClient.log().get();
19
20
  * console.log(log);
20
21
  *
22
+ * // Get the log content as raw bytes
23
+ * const logBuffer = await runClient.log().get({ buffer: true });
24
+ *
21
25
  * // Stream the log in real-time
22
26
  * const stream = await runClient.log().stream();
23
27
  * stream.on('line', (line) => console.log(line));
@@ -33,18 +37,34 @@ export declare class LogClient extends ResourceClient {
33
37
  /**
34
38
  * Retrieves the log as a string.
35
39
  *
40
+ * The `buffer` option only selects the return type: the bytes come back as a Buffer (Node.js) or ArrayBuffer
41
+ * (browser), not decoded to a string. Either way the whole log is downloaded in one response; to read it
42
+ * incrementally, use {@link LogClient.stream}.
43
+ *
36
44
  * @param options - Log retrieval options.
37
45
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
38
- * @returns The log content as a string, or `undefined` if it does not exist.
46
+ * @param options.buffer - If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a
47
+ * string. It does not change how the log is fetched.
48
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
49
+ * @returns The log content, or `undefined` if it does not exist. A chained client such as `run.log()` throws an
50
+ * `ApifyApiError` on a 404, since the run itself may be what is missing.
39
51
  * @see https://docs.apify.com/api/v2/log-get
40
52
  */
41
- get(options?: LogOptions): Promise<string | undefined>;
53
+ get(options?: LogGetOptions & {
54
+ buffer?: false;
55
+ }): Promise<string | undefined>;
56
+ get(options: LogGetOptions & {
57
+ buffer: true;
58
+ }): Promise<Buffer | undefined>;
59
+ get(options?: LogGetOptions): Promise<string | Buffer | undefined>;
42
60
  /**
43
61
  * Retrieves the log as a Readable stream. Only works in Node.js.
44
62
  *
45
63
  * @param options - Log retrieval options.
46
64
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
47
- * @returns The log content as a Readable stream, or `undefined` if it does not exist.
65
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
66
+ * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
67
+ * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
48
68
  * @see https://docs.apify.com/api/v2/log-get
49
69
  */
50
70
  stream(options?: LogOptions): Promise<Readable | undefined>;
@@ -52,10 +72,21 @@ export declare class LogClient extends ResourceClient {
52
72
  /**
53
73
  * @since Added in 2.20.0
54
74
  */
55
- export interface LogOptions {
75
+ export interface LogOptions extends TimeoutOptions {
56
76
  /** @default false */
57
77
  raw?: boolean;
58
78
  }
79
+ /**
80
+ * Options for {@link LogClient.get}.
81
+ */
82
+ export interface LogGetOptions extends LogOptions {
83
+ /**
84
+ * If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a string. It only selects
85
+ * the return type; to read the log incrementally, use {@link LogClient.stream}.
86
+ * @default false
87
+ */
88
+ buffer?: boolean;
89
+ }
59
90
  /**
60
91
  * Logger for redirected actor logs.
61
92
  * @since Added in 2.20.0
@@ -69,31 +100,17 @@ export declare class LoggerActorRedirect extends Logger {
69
100
  * @since Added in 2.20.0
70
101
  */
71
102
  export declare class StreamedLog {
72
- private destinationLog;
73
- private streamBuffer;
74
- private splitMarker;
75
- private relevancyTimeLimit;
76
- private logClient;
77
- private streamingTask;
78
- private stopLogging;
103
+ #private;
79
104
  constructor(options: StreamedLogOptions);
80
105
  /**
81
106
  * Start log redirection.
82
107
  */
83
108
  start(): void;
84
109
  /**
85
- * Stop log redirection.
110
+ * Stop log redirection. Waits up to one second for lines already in flight, then aborts the log stream request. If
111
+ * no stream has delivered anything yet, reads the whole log in one request instead.
86
112
  */
87
113
  stop(): Promise<void>;
88
- /**
89
- * Get log stream from response and redirect it to another log.
90
- */
91
- private streamLog;
92
- private logStreamChunks;
93
- /**
94
- * Parse the buffer and log complete messages.
95
- */
96
- private logBufferContent;
97
114
  }
98
115
  /**
99
116
  * @since Added in 2.20.0
@@ -105,4 +122,6 @@ export interface StreamedLogOptions {
105
122
  toLog: Log;
106
123
  /** Whether to redirect all logs from Actor run start (even logs from the past). */
107
124
  fromStart?: boolean;
125
+ /** Ends the log stream once it aborts. */
126
+ signal?: AbortSignal;
108
127
  }
@@ -1,11 +1,21 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StreamedLog = exports.LoggerActorRedirect = exports.LogClient = void 0;
4
- const tslib_1 = require("tslib");
5
- const ansi_colors_1 = tslib_1.__importDefault(require("ansi-colors"));
6
- const log_1 = tslib_1.__importStar(require("@apify/log"));
7
- const resource_client_1 = require("../base/resource_client");
8
- const utils_1 = require("../utils");
1
+ import c from 'ansi-colors';
2
+ import { z } from 'zod';
3
+ import log, { Logger, LogLevel } from '@apify/log';
4
+ import { ResourceClient } from '../base/resource_client.js';
5
+ import { timeoutOptionsShape } from '../timeouts.js';
6
+ import { cast, catchNotFoundForResourceOrThrow, concatBytes, parseArgument, sleep } from '../utils.js';
7
+ /**
8
+ * Pause before the first reopen of a log stream that ended before the run logged anything. Each further reopen doubles
9
+ * the pause up to `EMPTY_LOG_STREAM_MAX_RETRY_MILLIS`, which bounds the request rate while a run waits long to start,
10
+ * for example for free memory.
11
+ */
12
+ const EMPTY_LOG_STREAM_RETRY_MILLIS = 500;
13
+ /** Upper bound on the pause between reopens of an empty log stream. */
14
+ const EMPTY_LOG_STREAM_MAX_RETRY_MILLIS = 5_000;
15
+ const logOptionsSchema = z.strictObject({ raw: z.boolean().optional(), ...timeoutOptionsShape });
16
+ const logGetOptionsSchema = logOptionsSchema.extend({ buffer: z.boolean().optional() });
17
+ /** How long `StreamedLog.stop()` waits for lines already in flight before aborting the log stream request. */
18
+ const STOP_GRACE_MILLIS = 1000;
9
19
  /**
10
20
  * Client for accessing Actor run or build logs.
11
21
  *
@@ -21,6 +31,9 @@ const utils_1 = require("../utils");
21
31
  * const log = await runClient.log().get();
22
32
  * console.log(log);
23
33
  *
34
+ * // Get the log content as raw bytes
35
+ * const logBuffer = await runClient.log().get({ buffer: true });
36
+ *
24
37
  * // Stream the log in real-time
25
38
  * const stream = await runClient.log().stream();
26
39
  * stream.on('line', (line) => console.log(line));
@@ -28,7 +41,7 @@ const utils_1 = require("../utils");
28
41
  *
29
42
  * @see https://docs.apify.com/platform/actors/running/runs-and-builds#logging
30
43
  */
31
- class LogClient extends resource_client_1.ResourceClient {
44
+ export class LogClient extends ResourceClient {
32
45
  /**
33
46
  * @hidden
34
47
  */
@@ -38,26 +51,23 @@ class LogClient extends resource_client_1.ResourceClient {
38
51
  ...options,
39
52
  });
40
53
  }
41
- /**
42
- * Retrieves the log as a string.
43
- *
44
- * @param options - Log retrieval options.
45
- * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
46
- * @returns The log content as a string, or `undefined` if it does not exist.
47
- * @see https://docs.apify.com/api/v2/log-get
48
- */
49
54
  async get(options = {}) {
55
+ const { timeoutSecs = 'long', signal, buffer, ...params } = parseArgument(options, logGetOptionsSchema, 'LogGetOptions');
50
56
  const requestOpts = {
51
- url: this._url(),
57
+ url: this.buildUrl(),
52
58
  method: 'GET',
53
- params: this._params(options),
59
+ params: this.buildParams(params),
60
+ timeoutSecs,
61
+ signal,
54
62
  };
63
+ if (buffer)
64
+ requestOpts.responseType = 'buffer';
55
65
  try {
56
66
  const response = await this.httpClient.call(requestOpts);
57
- return (0, utils_1.cast)(response.data);
67
+ return cast(response.data);
58
68
  }
59
69
  catch (err) {
60
- (0, utils_1.catchNotFoundOrThrow)(err);
70
+ catchNotFoundForResourceOrThrow(err, this.id);
61
71
  }
62
72
  return undefined;
63
73
  }
@@ -66,38 +76,42 @@ class LogClient extends resource_client_1.ResourceClient {
66
76
  *
67
77
  * @param options - Log retrieval options.
68
78
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
69
- * @returns The log content as a Readable stream, or `undefined` if it does not exist.
79
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
80
+ * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
81
+ * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
70
82
  * @see https://docs.apify.com/api/v2/log-get
71
83
  */
72
84
  async stream(options = {}) {
85
+ const { timeoutSecs = 'long', signal, raw } = parseArgument(options, logOptionsSchema, 'LogOptions');
73
86
  const params = {
74
87
  stream: true,
75
- raw: options.raw,
88
+ raw,
76
89
  };
77
90
  const requestOpts = {
78
- url: this._url(),
91
+ url: this.buildUrl(),
79
92
  method: 'GET',
80
- params: this._params(params),
93
+ params: this.buildParams(params),
81
94
  responseType: 'stream',
95
+ timeoutSecs,
96
+ signal,
82
97
  };
83
98
  try {
84
99
  const response = await this.httpClient.call(requestOpts);
85
- return (0, utils_1.cast)(response.data);
100
+ return cast(response.data);
86
101
  }
87
102
  catch (err) {
88
- (0, utils_1.catchNotFoundOrThrow)(err);
103
+ catchNotFoundForResourceOrThrow(err, this.id);
89
104
  }
90
105
  return undefined;
91
106
  }
92
107
  }
93
- exports.LogClient = LogClient;
94
108
  /**
95
109
  * Logger for redirected actor logs.
96
110
  * @since Added in 2.20.0
97
111
  */
98
- class LoggerActorRedirect extends log_1.Logger {
112
+ export class LoggerActorRedirect extends Logger {
99
113
  constructor(options = {}) {
100
- super({ skipTime: true, level: log_1.LogLevel.DEBUG, ...options });
114
+ super({ skipTime: true, level: LogLevel.DEBUG, ...options });
101
115
  }
102
116
  _log(level, message, data, exception, opts = {}) {
103
117
  if (level > this.options.level) {
@@ -112,52 +126,62 @@ class LoggerActorRedirect extends log_1.Logger {
112
126
  if (!this.options.skipTime) {
113
127
  maybeDate = `${new Date().toISOString().replace('Z', '').replace('T', ' ')} `;
114
128
  }
115
- const line = `${ansi_colors_1.default.gray(maybeDate)}${ansi_colors_1.default.cyan(prefix)}${message || ''}`;
129
+ const line = `${c.gray(maybeDate)}${c.cyan(prefix)}${message || ''}`;
116
130
  // All redirected logs are logged at info level to avid any console specific formating for non-info levels,
117
131
  // which have already been applied once to the original log. (For example error stack traces etc.)
118
- this._outputWithConsole(log_1.LogLevel.INFO, line);
132
+ this._outputWithConsole(LogLevel.INFO, line);
119
133
  return line;
120
134
  }
121
135
  }
122
- exports.LoggerActorRedirect = LoggerActorRedirect;
123
136
  /**
124
137
  * Helper class for redirecting streamed Actor logs to another log.
125
138
  * @since Added in 2.20.0
126
139
  */
127
- class StreamedLog {
128
- destinationLog;
129
- streamBuffer = [];
130
- splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
131
- relevancyTimeLimit;
132
- logClient;
133
- streamingTask = null;
134
- stopLogging = false;
140
+ export class StreamedLog {
141
+ #destinationLog;
142
+ #streamBuffer = [];
143
+ #decoder = new TextDecoder();
144
+ #splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
145
+ #relevancyTimeLimit;
146
+ #logClient;
147
+ #signal;
148
+ #streamingTask = null;
149
+ #stopLogging = false;
150
+ #stopController = new AbortController();
151
+ #wakeController = new AbortController();
135
152
  constructor(options) {
136
- const { toLog, logClient, fromStart = true } = options;
137
- this.destinationLog = toLog;
138
- this.logClient = logClient;
139
- this.relevancyTimeLimit = fromStart ? null : new Date();
153
+ const { toLog, logClient, fromStart = true, signal } = options;
154
+ this.#destinationLog = toLog;
155
+ this.#logClient = logClient;
156
+ this.#signal = signal;
157
+ this.#relevancyTimeLimit = fromStart ? null : new Date();
140
158
  }
141
159
  /**
142
160
  * Start log redirection.
143
161
  */
144
162
  start() {
145
- if (this.streamingTask) {
163
+ if (this.#streamingTask) {
146
164
  throw new Error('Streaming task already active');
147
165
  }
148
- this.stopLogging = false;
149
- this.streamingTask = this.streamLog();
166
+ this.#stopLogging = false;
167
+ this.#stopController = new AbortController();
168
+ this.#wakeController = new AbortController();
169
+ this.#streamingTask = this.#streamLog();
150
170
  }
151
171
  /**
152
- * Stop log redirection.
172
+ * Stop log redirection. Waits up to one second for lines already in flight, then aborts the log stream request. If
173
+ * no stream has delivered anything yet, reads the whole log in one request instead.
153
174
  */
154
175
  async stop() {
155
- if (!this.streamingTask) {
176
+ if (!this.#streamingTask) {
156
177
  throw new Error('Streaming task is not active');
157
178
  }
158
- this.stopLogging = true;
179
+ this.#stopLogging = true;
180
+ this.#wakeController.abort();
181
+ const stopController = this.#stopController;
182
+ const abortTimeout = setTimeout(() => stopController.abort(), STOP_GRACE_MILLIS);
159
183
  try {
160
- await this.streamingTask;
184
+ await this.#streamingTask;
161
185
  }
162
186
  catch (err) {
163
187
  if (!(err instanceof Error && err.name === 'AbortError')) {
@@ -165,74 +189,121 @@ class StreamedLog {
165
189
  }
166
190
  }
167
191
  finally {
168
- this.streamingTask = null;
192
+ clearTimeout(abortTimeout);
193
+ this.#streamingTask = null;
169
194
  }
170
195
  }
171
196
  /**
172
197
  * Get log stream from response and redirect it to another log.
173
198
  */
174
- async streamLog() {
175
- const logStream = await this.logClient.stream({ raw: true });
176
- if (!logStream) {
177
- return;
178
- }
199
+ async #streamLog() {
200
+ const signal = this.#signal
201
+ ? AbortSignal.any([this.#signal, this.#stopController.signal])
202
+ : this.#stopController.signal;
179
203
  try {
180
- const lastChunkRemainder = await this.logStreamChunks(logStream);
204
+ let lastChunkRemainder;
205
+ let retryMillis = EMPTY_LOG_STREAM_RETRY_MILLIS;
206
+ // The API serves the log of a run that has not logged anything yet as an empty stream that ends at once,
207
+ // so reopen it until the first bytes arrive. If stopped before any bytes arrive, fetch it in one request.
208
+ while (!lastChunkRemainder) {
209
+ if (this.#stopLogging) {
210
+ // `signal` is aborted once the stop grace period ends, which would cut this read short.
211
+ const logContent = await this.#logClient.get({ raw: true, signal: this.#signal });
212
+ lastChunkRemainder = await this.#logStreamChunks([new TextEncoder().encode(logContent ?? '')], signal);
213
+ break;
214
+ }
215
+ let logStream;
216
+ try {
217
+ logStream = await this.#logClient.stream({ raw: true, signal });
218
+ }
219
+ catch (err) {
220
+ // The stop grace period ended while the stream was connecting, so read the log in one request.
221
+ if (this.#stopLogging && !this.#signal?.aborted)
222
+ continue;
223
+ throw err;
224
+ }
225
+ if (!logStream) {
226
+ return;
227
+ }
228
+ // A stream opened during stop() would be cut after its first chunk, so read the log in one request.
229
+ if (this.#stopLogging) {
230
+ logStream.destroy();
231
+ continue;
232
+ }
233
+ lastChunkRemainder = await this.#logStreamChunks(logStream, signal);
234
+ if (!lastChunkRemainder) {
235
+ await sleep(retryMillis, AbortSignal.any([signal, this.#wakeController.signal]));
236
+ retryMillis = Math.min(retryMillis * 2, EMPTY_LOG_STREAM_MAX_RETRY_MILLIS);
237
+ }
238
+ }
181
239
  // Process whatever is left when exiting. Maybe it is incomplete, maybe it is last log without EOL.
182
- const lastMessage = Buffer.from(lastChunkRemainder).toString().trim();
240
+ const lastMessage = this.#decoder.decode(lastChunkRemainder).trim();
183
241
  if (lastMessage.length) {
184
- this.destinationLog.info(lastMessage);
242
+ this.#destinationLog.info(lastMessage);
185
243
  }
186
244
  }
187
245
  catch (err) {
188
- log_1.default.warning(`Log redirection stopped due to error`, err);
246
+ if (signal.aborted)
247
+ return;
248
+ log.warning(`Log redirection stopped due to error`, err);
189
249
  }
190
250
  }
191
- async logStreamChunks(logStream) {
251
+ /**
252
+ * Redirect every complete message in the chunks and return the incomplete rest, or `undefined` when there were no
253
+ * chunks at all.
254
+ */
255
+ async #logStreamChunks(logStream, signal) {
192
256
  // Chunk may be incomplete. Keep remainder for next chunk.
193
- let previousChunkRemainder = new Uint8Array();
194
- for await (const chunk of logStream) {
195
- // Handle possible leftover incomplete line from previous chunk.
196
- // Everything before last end of line is complete.
197
- const chunkWithPreviousRemainder = new Uint8Array(previousChunkRemainder.length + chunk.length);
198
- chunkWithPreviousRemainder.set(previousChunkRemainder, 0);
199
- chunkWithPreviousRemainder.set(chunk, previousChunkRemainder.length);
200
- const lastCompleteMessageIndex = chunkWithPreviousRemainder.lastIndexOf(0x0a);
201
- previousChunkRemainder = chunkWithPreviousRemainder.slice(lastCompleteMessageIndex);
202
- // Push complete part of the chunk to the buffer
203
- this.streamBuffer.push(Buffer.from(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex)));
204
- this.logBufferContent();
205
- // Keep processing the new data until stopped
206
- if (this.stopLogging) {
207
- break;
257
+ let previousChunkRemainder;
258
+ try {
259
+ for await (const chunk of logStream) {
260
+ // Handle possible leftover incomplete line from previous chunk.
261
+ // Everything before last end of line is complete.
262
+ previousChunkRemainder ??= new Uint8Array();
263
+ const chunkWithPreviousRemainder = new Uint8Array(previousChunkRemainder.length + chunk.length);
264
+ chunkWithPreviousRemainder.set(previousChunkRemainder, 0);
265
+ chunkWithPreviousRemainder.set(chunk, previousChunkRemainder.length);
266
+ const lastCompleteMessageIndex = chunkWithPreviousRemainder.lastIndexOf(0x0a);
267
+ previousChunkRemainder = chunkWithPreviousRemainder.slice(lastCompleteMessageIndex);
268
+ // Push complete part of the chunk to the buffer
269
+ this.#streamBuffer.push(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex));
270
+ this.#logBufferContent();
271
+ // Keep processing the new data until stopped
272
+ if (this.#stopLogging) {
273
+ break;
274
+ }
208
275
  }
209
276
  }
277
+ catch (err) {
278
+ // An aborted stream still hands back its unterminated last line, so the caller can flush it.
279
+ if (!signal.aborted)
280
+ throw err;
281
+ }
210
282
  return previousChunkRemainder;
211
283
  }
212
284
  /**
213
285
  * Parse the buffer and log complete messages.
214
286
  */
215
- logBufferContent() {
216
- const allParts = Buffer.concat(this.streamBuffer).toString().split(this.splitMarker).slice(1);
287
+ #logBufferContent() {
288
+ const allParts = this.#decoder.decode(concatBytes(this.#streamBuffer)).split(this.#splitMarker).slice(1);
217
289
  // Parse the buffer parts into complete messages
218
290
  const messageMarkers = allParts.filter((_, i) => i % 2 === 0);
219
291
  const messageContents = allParts.filter((_, i) => i % 2 !== 0);
220
- this.streamBuffer = [];
292
+ this.#streamBuffer = [];
221
293
  messageMarkers.forEach((marker, index) => {
222
294
  const decodedMarker = marker;
223
295
  const decodedContent = messageContents[index];
224
- if (this.relevancyTimeLimit) {
296
+ if (this.#relevancyTimeLimit) {
225
297
  // Log only relevant messages. Ignore too old log messages.
226
298
  const logTime = new Date(decodedMarker);
227
- if (logTime < this.relevancyTimeLimit) {
299
+ if (logTime < this.#relevancyTimeLimit) {
228
300
  return;
229
301
  }
230
302
  }
231
303
  const message = decodedMarker + decodedContent;
232
304
  // Original log level information is not available. Log all on info level. Log level could be guessed for
233
305
  // some logs, but for any multiline logs such guess would be probably correct only for the first line.
234
- this.destinationLog.info(message.trim());
306
+ this.#destinationLog.info(message.trim());
235
307
  });
236
308
  }
237
309
  }
238
- exports.StreamedLog = StreamedLog;