firebase-tools-with-isolate 13.15.0-0 → 13.16.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.
Files changed (48) hide show
  1. package/lib/commands/deploy.js +3 -1
  2. package/lib/dataconnect/client.js +2 -1
  3. package/lib/dataconnect/fileUtils.js +52 -11
  4. package/lib/dataconnect/provisionCloudSql.js +5 -1
  5. package/lib/deploy/extensions/planner.js +52 -1
  6. package/lib/deploy/extensions/prepare.js +98 -23
  7. package/lib/deploy/extensions/release.js +6 -0
  8. package/lib/deploy/functions/build.js +5 -5
  9. package/lib/deploy/functions/deploy.js +12 -12
  10. package/lib/deploy/functions/params.js +5 -3
  11. package/lib/deploy/functions/prepare.js +8 -1
  12. package/lib/deploy/functions/release/index.js +4 -0
  13. package/lib/deploy/functions/runtimes/discovery/parsing.js +1 -1
  14. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +46 -0
  15. package/lib/emulator/constants.js +7 -0
  16. package/lib/emulator/controller.js +11 -1
  17. package/lib/emulator/downloadableEmulators.js +12 -12
  18. package/lib/emulator/env.js +3 -0
  19. package/lib/emulator/functionsEmulator.js +30 -1
  20. package/lib/emulator/functionsEmulatorShared.js +16 -0
  21. package/lib/emulator/portUtils.js +1 -0
  22. package/lib/emulator/registry.js +1 -0
  23. package/lib/emulator/taskQueue.js +348 -0
  24. package/lib/emulator/tasksEmulator.js +237 -0
  25. package/lib/emulator/types.js +3 -0
  26. package/lib/extensions/askUserForEventsConfig.js +18 -8
  27. package/lib/extensions/askUserForParam.js +2 -1
  28. package/lib/extensions/displayExtensionInfo.js +5 -5
  29. package/lib/extensions/extensionsApi.js +1 -1
  30. package/lib/extensions/extensionsHelper.js +25 -3
  31. package/lib/extensions/localHelper.js +1 -1
  32. package/lib/extensions/refs.js +26 -11
  33. package/lib/extensions/runtimes/common.js +75 -0
  34. package/lib/extensions/types.js +56 -1
  35. package/lib/frameworks/constants.js +1 -1
  36. package/lib/frameworks/next/constants.js +1 -1
  37. package/lib/frameworks/next/index.js +35 -15
  38. package/lib/frameworks/next/utils.js +51 -1
  39. package/lib/init/features/dataconnect/index.js +14 -8
  40. package/lib/init/features/dataconnect/sdk.js +64 -48
  41. package/lib/prompt.js +22 -1
  42. package/package.json +3 -3
  43. package/schema/firebase-config.json +12 -0
  44. package/templates/init/dataconnect/connector.yaml +5 -3
  45. package/templates/init/dataconnect/dataconnect.yaml +5 -5
  46. package/templates/init/dataconnect/mutations.gql +44 -29
  47. package/templates/init/dataconnect/queries.gql +66 -38
  48. package/templates/init/dataconnect/schema.gql +38 -21
@@ -44,6 +44,7 @@ const hostingEmulator_1 = require("./hostingEmulator");
44
44
  const pubsubEmulator_1 = require("./pubsubEmulator");
45
45
  const storage_1 = require("./storage");
46
46
  const fileUtils_1 = require("../dataconnect/fileUtils");
47
+ const tasksEmulator_1 = require("./tasksEmulator");
47
48
  const START_LOGGING_EMULATOR = utils.envOverride("START_LOGGING_EMULATOR", "false", (val) => val === "true");
48
49
  async function exportOnExit(options) {
49
50
  const exportOnExitDir = options.exportOnExit;
@@ -222,10 +223,12 @@ async function startAll(options, showUI = true, runningTestScript = false) {
222
223
  if (emulatableBackends.length) {
223
224
  listenConfig[types_1.Emulators.FUNCTIONS] = getListenConfig(options, types_1.Emulators.FUNCTIONS);
224
225
  listenConfig[types_1.Emulators.EVENTARC] = getListenConfig(options, types_1.Emulators.EVENTARC);
226
+ listenConfig[types_1.Emulators.TASKS] = getListenConfig(options, types_1.Emulators.TASKS);
225
227
  }
226
228
  for (const emulator of types_1.ALL_EMULATORS) {
227
229
  if (emulator === types_1.Emulators.FUNCTIONS ||
228
230
  emulator === types_1.Emulators.EVENTARC ||
231
+ emulator === types_1.Emulators.TASKS ||
229
232
  emulator === types_1.Emulators.EXTENSIONS ||
230
233
  (emulator === types_1.Emulators.UI && !showUI)) {
231
234
  continue;
@@ -330,11 +333,12 @@ async function startAll(options, showUI = true, runningTestScript = false) {
330
333
  await startEmulator(extensionEmulator);
331
334
  }
332
335
  if (emulatableBackends.length) {
333
- if (!listenForEmulator.functions || !listenForEmulator.eventarc) {
336
+ if (!listenForEmulator.functions || !listenForEmulator.eventarc || !listenForEmulator.tasks) {
334
337
  listenForEmulator = await (0, portUtils_1.resolveHostAndAssignPorts)({
335
338
  ...listenForEmulator,
336
339
  functions: listenForEmulator.functions ?? getListenConfig(options, types_1.Emulators.FUNCTIONS),
337
340
  eventarc: listenForEmulator.eventarc ?? getListenConfig(options, types_1.Emulators.EVENTARC),
341
+ tasks: listenForEmulator.eventarc ?? getListenConfig(options, types_1.Emulators.TASKS),
338
342
  });
339
343
  hubLogger.log("DEBUG", "late-assigned ports for functions and eventarc emulators", {
340
344
  user: listenForEmulator,
@@ -372,6 +376,12 @@ async function startAll(options, showUI = true, runningTestScript = false) {
372
376
  port: eventarcAddr.port,
373
377
  });
374
378
  await startEmulator(eventarcEmulator);
379
+ const tasksAddr = legacyGetFirstAddr(types_1.Emulators.TASKS);
380
+ const tasksEmulator = new tasksEmulator_1.TasksEmulator({
381
+ host: tasksAddr.host,
382
+ port: tasksAddr.port,
383
+ });
384
+ await startEmulator(tasksEmulator);
375
385
  }
376
386
  if (listenForEmulator.firestore) {
377
387
  const firestoreLogger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.FIRESTORE);
@@ -23,9 +23,9 @@ const EMULATOR_UPDATE_DETAILS = {
23
23
  expectedChecksum: "2fd771101c0e1f7898c04c9204f2ce63",
24
24
  },
25
25
  firestore: {
26
- version: "1.19.7",
27
- expectedSize: 66438992,
28
- expectedChecksum: "aec233bea95c5cfab03881574ec16d6c",
26
+ version: "1.19.8",
27
+ expectedSize: 63634791,
28
+ expectedChecksum: "9b43a6daa590678de9b7df6d68260395",
29
29
  },
30
30
  storage: {
31
31
  version: "1.1.3",
@@ -46,20 +46,20 @@ const EMULATOR_UPDATE_DETAILS = {
46
46
  },
47
47
  dataconnect: process.platform === "darwin"
48
48
  ? {
49
- version: "1.3.2",
50
- expectedSize: 24195840,
51
- expectedChecksum: "b60f4501c657bec4dc8df3f3ec7ab3fd",
49
+ version: "1.3.5",
50
+ expectedSize: 24232704,
51
+ expectedChecksum: "4eabf613a4a5feeaa173e1375b62bde0",
52
52
  }
53
53
  : process.platform === "win32"
54
54
  ? {
55
- version: "1.3.2",
56
- expectedSize: 24610304,
57
- expectedChecksum: "37d5e08f4df5e07b41160b8f2fd90135",
55
+ version: "1.3.5",
56
+ expectedSize: 24651264,
57
+ expectedChecksum: "c7b2b7168ff7226f4e5626ae7d13e0ca",
58
58
  }
59
59
  : {
60
- version: "1.3.2",
61
- expectedSize: 24109208,
62
- expectedChecksum: "52b09c69bc9a3a84b01a3a7311817229",
60
+ version: "1.3.5",
61
+ expectedSize: 24146072,
62
+ expectedChecksum: "1457937751ce25fa332cdc16b561d64b",
63
63
  },
64
64
  };
65
65
  exports.DownloadDetails = {
@@ -31,6 +31,9 @@ function setEnvVarsForEmulators(env, emulators) {
31
31
  case types_1.Emulators.EVENTARC:
32
32
  env[constants_1.Constants.CLOUD_EVENTARC_EMULATOR_HOST] = `http://${host}`;
33
33
  break;
34
+ case types_1.Emulators.TASKS:
35
+ env[constants_1.Constants.CLOUD_TASKS_EMULATOR_HOST] = host;
36
+ break;
34
37
  }
35
38
  }
36
39
  }
@@ -322,7 +322,14 @@ class FunctionsEmulator {
322
322
  };
323
323
  const userEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
324
324
  const discoveredBuild = await runtimeDelegate.discoverBuild(runtimeConfig, environment);
325
- const resolution = await (0, build_1.resolveBackend)(discoveredBuild, JSON.parse(firebaseConfig), userEnvOpt, userEnvs);
325
+ const resolution = await (0, build_1.resolveBackend)({
326
+ build: discoveredBuild,
327
+ firebaseConfig: JSON.parse(firebaseConfig),
328
+ userEnvOpt,
329
+ userEnvs,
330
+ nonInteractive: false,
331
+ isEmulator: true,
332
+ });
326
333
  const discoveredBackend = resolution.backend;
327
334
  const endpoints = backend.allEndpoints(discoveredBackend);
328
335
  (0, functionsEmulatorShared_1.prepareEndpoints)(endpoints);
@@ -385,6 +392,9 @@ class FunctionsEmulator {
385
392
  if (definition.httpsTrigger) {
386
393
  added = true;
387
394
  url = FunctionsEmulator.getHttpFunctionUrl(this.args.projectId, definition.name, definition.region);
395
+ if (definition.taskQueueTrigger) {
396
+ added = await this.addTaskQueueTrigger(this.args.projectId, definition.region, definition.name, url, definition.taskQueueTrigger);
397
+ }
388
398
  }
389
399
  else if (definition.eventTrigger) {
390
400
  const service = (0, functionsEmulatorShared_1.getFunctionService)(definition);
@@ -771,6 +781,25 @@ class FunctionsEmulator {
771
781
  };
772
782
  return true;
773
783
  }
784
+ async addTaskQueueTrigger(projectId, location, entryPoint, defaultUri, taskQueueTrigger) {
785
+ logger_1.logger.debug(`addTaskQueueTrigger`, JSON.stringify(taskQueueTrigger));
786
+ if (!registry_1.EmulatorRegistry.isRunning(types_1.Emulators.TASKS)) {
787
+ logger_1.logger.debug(`addTaskQueueTrigger`, "TQ not running");
788
+ return Promise.resolve(false);
789
+ }
790
+ const bundle = {
791
+ ...taskQueueTrigger,
792
+ defaultUri,
793
+ };
794
+ try {
795
+ await registry_1.EmulatorRegistry.client(types_1.Emulators.TASKS).post(`/projects/${projectId}/locations/${location}/queues/${entryPoint}`, bundle);
796
+ return true;
797
+ }
798
+ catch (err) {
799
+ this.logger.log("WARN", "Error adding Task Queue function: " + err);
800
+ return false;
801
+ }
802
+ }
774
803
  getProjectId() {
775
804
  return this.args.projectId;
776
805
  }
@@ -131,6 +131,19 @@ function emulatedFunctionsFromEndpoints(endpoints) {
131
131
  }
132
132
  else if (backend.isTaskQueueTriggered(endpoint)) {
133
133
  def.httpsTrigger = {};
134
+ def.taskQueueTrigger = {
135
+ retryConfig: {
136
+ maxAttempts: endpoint.taskQueueTrigger.retryConfig?.maxAttempts,
137
+ maxRetrySeconds: endpoint.taskQueueTrigger.retryConfig?.maxRetrySeconds,
138
+ maxBackoffSeconds: endpoint.taskQueueTrigger.retryConfig?.maxBackoffSeconds,
139
+ maxDoublings: endpoint.taskQueueTrigger.retryConfig?.maxDoublings,
140
+ minBackoffSeconds: endpoint.taskQueueTrigger.retryConfig?.minBackoffSeconds,
141
+ },
142
+ rateLimits: {
143
+ maxConcurrentDispatches: endpoint.taskQueueTrigger.rateLimits?.maxConcurrentDispatches,
144
+ maxDispatchesPerSecond: endpoint.taskQueueTrigger.rateLimits?.maxDispatchesPerSecond,
145
+ },
146
+ };
134
147
  }
135
148
  else {
136
149
  }
@@ -188,6 +201,9 @@ function getFunctionService(def) {
188
201
  if (def.httpsTrigger) {
189
202
  return "https";
190
203
  }
204
+ if (def.taskQueueTrigger) {
205
+ return constants_1.Constants.SERVICE_CLOUD_TASKS;
206
+ }
191
207
  return "unknown";
192
208
  }
193
209
  exports.getFunctionService = getFunctionService;
@@ -156,6 +156,7 @@ const EMULATOR_CAN_LISTEN_ON_PRIMARY_ONLY = {
156
156
  functions: true,
157
157
  logging: true,
158
158
  storage: true,
159
+ tasks: true,
159
160
  hosting: true,
160
161
  };
161
162
  const MAX_PORT = 65535;
@@ -49,6 +49,7 @@ class EmulatorRegistry {
49
49
  storage: 3.5,
50
50
  eventarc: 3.6,
51
51
  dataconnect: 3.7,
52
+ tasks: 3.8,
52
53
  hub: 4,
53
54
  logging: 5,
54
55
  };
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TaskQueue = exports.TaskStatus = exports.Queue = void 0;
4
+ const abort_controller_1 = require("abort-controller");
5
+ const emulatorLogger_1 = require("./emulatorLogger");
6
+ const types_1 = require("./types");
7
+ const node_fetch_1 = require("node-fetch");
8
+ class Node {
9
+ constructor(data) {
10
+ this.data = data;
11
+ this.next = null;
12
+ this.prev = null;
13
+ }
14
+ }
15
+ class Queue {
16
+ constructor(capacity = 10000) {
17
+ this.nodeMap = {};
18
+ this.count = 0;
19
+ this.first = null;
20
+ this.last = null;
21
+ this.capacity = capacity;
22
+ }
23
+ enqueue(id, item) {
24
+ if (this.count >= this.capacity) {
25
+ throw new Error("Queue has reached capacity");
26
+ }
27
+ const newNode = new Node(item);
28
+ if (this.nodeMap[id] !== undefined) {
29
+ throw new Error("Queue IDs must be unique");
30
+ }
31
+ this.nodeMap[id] = newNode;
32
+ if (!this.first) {
33
+ this.first = newNode;
34
+ }
35
+ if (this.last) {
36
+ this.last.next = newNode;
37
+ }
38
+ newNode.prev = this.last;
39
+ this.last = newNode;
40
+ this.count++;
41
+ }
42
+ peek() {
43
+ if (this.first) {
44
+ return this.first.data;
45
+ }
46
+ else {
47
+ throw new Error("Trying to peek into an empty queue");
48
+ }
49
+ }
50
+ dequeue() {
51
+ if (this.first) {
52
+ const currentFirst = this.first;
53
+ this.first = this.first.next;
54
+ if (this.last === currentFirst) {
55
+ this.last = null;
56
+ }
57
+ this.count--;
58
+ return currentFirst.data;
59
+ }
60
+ else {
61
+ throw new Error("Trying to dequeue from an empty queue");
62
+ }
63
+ }
64
+ remove(id) {
65
+ if (this.nodeMap[id] === undefined) {
66
+ throw new Error("Trying to remove a task that doesn't exist");
67
+ }
68
+ const toRemove = this.nodeMap[id];
69
+ if (toRemove.next === null && toRemove.prev === null) {
70
+ this.first = null;
71
+ this.last = null;
72
+ }
73
+ else if (toRemove.next === null) {
74
+ this.last = toRemove.prev;
75
+ toRemove.prev.next = null;
76
+ }
77
+ else if (toRemove.prev === null) {
78
+ this.first = toRemove.next;
79
+ toRemove.next.prev = null;
80
+ }
81
+ else {
82
+ const prev = toRemove.prev;
83
+ const next = toRemove.next;
84
+ prev.next = next;
85
+ next.prev = prev;
86
+ }
87
+ delete this.nodeMap[id];
88
+ this.count--;
89
+ }
90
+ getAll() {
91
+ const all = [];
92
+ let curr = this.first;
93
+ while (curr) {
94
+ all.push(curr.data);
95
+ curr = curr.next;
96
+ }
97
+ return all;
98
+ }
99
+ isEmpty() {
100
+ return this.first === null;
101
+ }
102
+ size() {
103
+ return this.count;
104
+ }
105
+ }
106
+ exports.Queue = Queue;
107
+ var TaskStatus;
108
+ (function (TaskStatus) {
109
+ TaskStatus[TaskStatus["NOT_STARTED"] = 0] = "NOT_STARTED";
110
+ TaskStatus[TaskStatus["RUNNING"] = 1] = "RUNNING";
111
+ TaskStatus[TaskStatus["RETRY"] = 2] = "RETRY";
112
+ TaskStatus[TaskStatus["FAILED"] = 3] = "FAILED";
113
+ TaskStatus[TaskStatus["FINISHED"] = 4] = "FINISHED";
114
+ })(TaskStatus = exports.TaskStatus || (exports.TaskStatus = {}));
115
+ class TaskQueue {
116
+ constructor(key, config) {
117
+ this.key = key;
118
+ this.config = config;
119
+ this.queue = new Queue();
120
+ this.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.TASKS);
121
+ this.tokens = 0;
122
+ this.addedTimes = [];
123
+ this.completedTimes = [];
124
+ this.failedTimes = [];
125
+ this.maxTokens = Math.max(this.config.rateLimits.maxDispatchesPerSecond, 1.1);
126
+ this.lastTokenUpdate = Date.now();
127
+ this.queuedIds = new Set();
128
+ this.dispatches = new Array(this.config.rateLimits.maxConcurrentDispatches).fill(null);
129
+ this.openDispatches = Array.from(this.dispatches.keys());
130
+ }
131
+ dispatchTasks() {
132
+ while (!this.queue.isEmpty() && this.openDispatches.length > 0 && this.tokens >= 1) {
133
+ const dispatchLocation = this.openDispatches.pop();
134
+ if (dispatchLocation !== undefined) {
135
+ const dispatch = this.queue.dequeue();
136
+ dispatch.metadata.lastRunTime = null;
137
+ dispatch.metadata.currentAttempt = 1;
138
+ dispatch.metadata.status = TaskStatus.NOT_STARTED;
139
+ dispatch.metadata.startTime = Date.now();
140
+ this.dispatches[dispatchLocation] = dispatch;
141
+ this.tokens--;
142
+ }
143
+ }
144
+ }
145
+ setDispatch(dispatches) {
146
+ this.dispatches = dispatches;
147
+ const open = [];
148
+ for (let i = 0; i < this.dispatches.length; i++) {
149
+ if (dispatches[i] === null) {
150
+ open.push(i);
151
+ }
152
+ }
153
+ this.openDispatches = open;
154
+ }
155
+ getDispatch() {
156
+ return this.dispatches;
157
+ }
158
+ processDispatch() {
159
+ for (let i = 0; i < this.dispatches.length; i++) {
160
+ if (this.dispatches[i] !== null) {
161
+ switch (this.dispatches[i]?.metadata.status) {
162
+ case TaskStatus.FAILED:
163
+ this.dispatches[i] = null;
164
+ this.openDispatches.push(i);
165
+ this.completedTimes.push(Date.now());
166
+ this.failedTimes.push(Date.now());
167
+ break;
168
+ case TaskStatus.NOT_STARTED:
169
+ void this.runTask(i);
170
+ break;
171
+ case TaskStatus.RETRY:
172
+ this.handleRetry(i);
173
+ break;
174
+ case TaskStatus.FINISHED:
175
+ this.dispatches[i] = null;
176
+ this.openDispatches.push(i);
177
+ this.completedTimes.push(Date.now());
178
+ break;
179
+ }
180
+ }
181
+ }
182
+ }
183
+ async runTask(dispatchIndex) {
184
+ if (this.dispatches[dispatchIndex] === null) {
185
+ throw new Error("Trying to dispatch a nonexistent task");
186
+ }
187
+ const emulatedTask = this.dispatches[dispatchIndex];
188
+ if (emulatedTask.metadata.lastRunTime !== null &&
189
+ Date.now() - emulatedTask.metadata.lastRunTime < emulatedTask.metadata.currentBackoff * 1000) {
190
+ return;
191
+ }
192
+ emulatedTask.metadata.status = TaskStatus.RUNNING;
193
+ try {
194
+ const headers = {
195
+ "Content-Type": "application/json",
196
+ "X-CloudTasks-QueueName": this.key,
197
+ "X-CloudTasks-TaskName": emulatedTask.task.name.split("/").pop(),
198
+ "X-CloudTasks-TaskRetryCount": `${emulatedTask.metadata.currentAttempt - 1}`,
199
+ "X-CloudTasks-TaskExecutionCount": `${emulatedTask.metadata.executionCount}`,
200
+ "X-CloudTasks-TaskETA": `${emulatedTask.task.scheduleTime || Date.now()}`,
201
+ ...emulatedTask.task.httpRequest.headers,
202
+ };
203
+ if (emulatedTask.metadata.previousResponse) {
204
+ headers["X-CloudTasks-TaskPreviousResponse"] = `${emulatedTask.metadata.previousResponse}`;
205
+ }
206
+ const controller = new abort_controller_1.default();
207
+ const signal = controller.signal;
208
+ const request = (0, node_fetch_1.default)(emulatedTask.task.httpRequest.url, {
209
+ method: "POST",
210
+ headers: headers,
211
+ body: JSON.stringify(emulatedTask.task.httpRequest.body),
212
+ signal: signal,
213
+ });
214
+ const dispatchDeadline = emulatedTask.task.dispatchDeadline;
215
+ const dispatchDeadlineSeconds = dispatchDeadline
216
+ ? parseInt(dispatchDeadline.substring(0, dispatchDeadline.length - 1))
217
+ : 60;
218
+ const abortId = setTimeout(() => {
219
+ controller.abort();
220
+ }, dispatchDeadlineSeconds * 1000);
221
+ const response = await request;
222
+ clearTimeout(abortId);
223
+ if (response.ok) {
224
+ emulatedTask.metadata.status = TaskStatus.FINISHED;
225
+ return;
226
+ }
227
+ else {
228
+ if (!(response.status >= 500 && response.status <= 599)) {
229
+ emulatedTask.metadata.executionCount++;
230
+ }
231
+ emulatedTask.metadata.previousResponse = response.status;
232
+ emulatedTask.metadata.status = TaskStatus.RETRY;
233
+ emulatedTask.metadata.lastRunTime = Date.now();
234
+ }
235
+ }
236
+ catch (e) {
237
+ this.logger.logLabeled("WARN", `${e}`);
238
+ emulatedTask.metadata.status = TaskStatus.RETRY;
239
+ emulatedTask.metadata.lastRunTime = Date.now();
240
+ }
241
+ }
242
+ handleRetry(dispatchIndex) {
243
+ if (this.dispatches[dispatchIndex] === null) {
244
+ throw new Error("Trying to retry a nonexistent task");
245
+ }
246
+ const { metadata } = this.dispatches[dispatchIndex];
247
+ const { retryConfig } = this.config;
248
+ if (this.shouldStopRetrying(metadata, retryConfig)) {
249
+ metadata.status = TaskStatus.FAILED;
250
+ return;
251
+ }
252
+ this.updateMetadata(metadata, retryConfig);
253
+ metadata.status = TaskStatus.NOT_STARTED;
254
+ }
255
+ shouldStopRetrying(metadata, retryOptions) {
256
+ if (metadata.currentAttempt > retryOptions.maxAttempts) {
257
+ if (retryOptions.maxRetrySeconds === null || retryOptions.maxRetrySeconds === 0) {
258
+ return true;
259
+ }
260
+ if (Date.now() - metadata.startTime > retryOptions.maxRetrySeconds * 1000) {
261
+ return true;
262
+ }
263
+ }
264
+ return false;
265
+ }
266
+ updateMetadata(metadata, retryOptions) {
267
+ const timeMultplier = Math.pow(2, Math.min(metadata.currentAttempt - 1, retryOptions.maxDoublings)) +
268
+ Math.max(0, metadata.currentAttempt - retryOptions.maxDoublings - 1) *
269
+ Math.pow(2, retryOptions.maxDoublings);
270
+ metadata.currentBackoff = Math.min(retryOptions.maxBackoffSeconds, timeMultplier * retryOptions.minBackoffSeconds);
271
+ metadata.currentAttempt++;
272
+ }
273
+ isActive() {
274
+ return !this.queue.isEmpty() || this.dispatches.some((e) => e !== null);
275
+ }
276
+ refillTokens() {
277
+ const tokensToAdd = ((Date.now() - this.lastTokenUpdate) / 1000) * this.config.rateLimits.maxDispatchesPerSecond;
278
+ this.addTokens(tokensToAdd);
279
+ this.lastTokenUpdate = Date.now();
280
+ }
281
+ addTokens(t) {
282
+ this.tokens += t;
283
+ this.tokens = Math.min(this.tokens, this.maxTokens);
284
+ }
285
+ setTokens(t) {
286
+ this.tokens = t;
287
+ }
288
+ getTokens() {
289
+ return this.tokens;
290
+ }
291
+ enqueue(task) {
292
+ if (this.queuedIds.has(task.name)) {
293
+ throw new Error(`A task has already been queued with id ${task.name}`);
294
+ }
295
+ const emulatedTask = {
296
+ task: task,
297
+ metadata: {
298
+ currentAttempt: 0,
299
+ currentBackoff: 0,
300
+ startTime: 0,
301
+ status: TaskStatus.NOT_STARTED,
302
+ lastRunTime: null,
303
+ previousResponse: null,
304
+ executionCount: 0,
305
+ },
306
+ };
307
+ emulatedTask.task.httpRequest.url =
308
+ emulatedTask.task.httpRequest.url === ""
309
+ ? this.config.defaultUri
310
+ : emulatedTask.task.httpRequest.url;
311
+ this.queue.enqueue(emulatedTask.task.name, emulatedTask);
312
+ this.queuedIds.add(task.name);
313
+ this.addedTimes.push(Date.now());
314
+ }
315
+ delete(taskId) {
316
+ this.queue.remove(taskId);
317
+ }
318
+ getDebugInfo() {
319
+ return `
320
+ Task Queue (${this.key}):
321
+ - Active: ${this.isActive().toString()}
322
+ - Tokens: ${this.tokens}
323
+ - In Queue: ${this.queue.size()}
324
+ - Dispatch: [
325
+ ${this.dispatches.map((t) => (t === null ? "empty" : t.task.name)).join(",\n")}
326
+ ]
327
+ - Open Locations: [${this.openDispatches.join(", ")}]
328
+ `;
329
+ }
330
+ getStatistics() {
331
+ const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
332
+ const oneMinuteAgo = Date.now() - 60 * 1000;
333
+ this.addedTimes = this.addedTimes.filter((t) => t > fiveMinutesAgo);
334
+ this.failedTimes = this.failedTimes.filter((t) => t > fiveMinutesAgo);
335
+ this.completedTimes = this.completedTimes.filter((t) => t > oneMinuteAgo);
336
+ return {
337
+ numberOfTasks: this.queue.size(),
338
+ tasksAdded: this.addedTimes.length / 5,
339
+ completedLastMin: this.completedTimes.length,
340
+ failedTasks: this.failedTimes.length / 5,
341
+ runningTasks: this.dispatches.length,
342
+ maxRate: this.config.rateLimits.maxDispatchesPerSecond,
343
+ maxConcurrent: this.config.rateLimits.maxConcurrentDispatches,
344
+ };
345
+ }
346
+ }
347
+ exports.TaskQueue = TaskQueue;
348
+ TaskQueue.TASK_QUEUE_INTERVAL = 1000;