firebase-tools-with-isolate 13.15.0-0 → 13.26.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 (235) hide show
  1. package/lib/api.js +3 -1
  2. package/lib/apiv2.js +10 -3
  3. package/lib/appdistribution/client.js +62 -8
  4. package/lib/appdistribution/distribution.js +1 -1
  5. package/lib/apphosting/backend.js +299 -0
  6. package/lib/apphosting/config.js +31 -8
  7. package/lib/apphosting/githubConnections.js +70 -22
  8. package/lib/apphosting/index.js +3 -312
  9. package/lib/apphosting/rollout.js +138 -0
  10. package/lib/apphosting/secrets/index.js +70 -5
  11. package/lib/apphosting/utils.js +41 -0
  12. package/lib/apphosting/yaml.js +82 -0
  13. package/lib/archiveDirectory.js +1 -1
  14. package/lib/auth.js +31 -5
  15. package/lib/bin/firebase.js +2 -2
  16. package/lib/command.js +18 -4
  17. package/lib/commands/appdistribution-distribute.js +4 -4
  18. package/lib/commands/{appdistribution-group-create.js → appdistribution-groups-create.js} +2 -1
  19. package/lib/commands/{appdistribution-group-delete.js → appdistribution-groups-delete.js} +3 -2
  20. package/lib/commands/appdistribution-groups-list.js +55 -0
  21. package/lib/commands/appdistribution-testers-list.js +52 -0
  22. package/lib/commands/appdistribution-testers-remove.js +1 -1
  23. package/lib/commands/apphosting-backends-create.js +4 -4
  24. package/lib/commands/apphosting-backends-delete.js +7 -15
  25. package/lib/commands/apphosting-backends-get.js +1 -1
  26. package/lib/commands/apphosting-config-export.js +51 -0
  27. package/lib/commands/apphosting-repos-create.js +23 -0
  28. package/lib/commands/apphosting-rollouts-create.js +14 -15
  29. package/lib/commands/apphosting-secrets-grantaccess.js +2 -2
  30. package/lib/commands/database-import.js +4 -2
  31. package/lib/commands/database-push.js +4 -2
  32. package/lib/commands/database-set.js +4 -2
  33. package/lib/commands/database-settings-get.js +1 -1
  34. package/lib/commands/database-settings-set.js +1 -1
  35. package/lib/commands/dataconnect-sdk-generate.js +4 -1
  36. package/lib/commands/dataconnect-services-list.js +4 -3
  37. package/lib/commands/dataconnect-sql-diff.js +1 -1
  38. package/lib/commands/dataconnect-sql-grant.js +37 -0
  39. package/lib/commands/dataconnect-sql-migrate.js +1 -1
  40. package/lib/commands/dataconnect-sql-shell.js +115 -0
  41. package/lib/commands/deploy.js +5 -1
  42. package/lib/commands/emulators-start.js +4 -1
  43. package/lib/commands/ext-dev-init.js +2 -2
  44. package/lib/commands/ext-dev-list.js +1 -1
  45. package/lib/commands/ext-dev-register.js +2 -2
  46. package/lib/commands/ext-dev-upload.js +2 -2
  47. package/lib/commands/ext-dev-usage.js +2 -2
  48. package/lib/commands/ext-info.js +3 -1
  49. package/lib/commands/ext-install.js +2 -2
  50. package/lib/commands/ext-sdk-install.js +88 -0
  51. package/lib/commands/ext.js +1 -0
  52. package/lib/commands/firestore-databases-restore.js +39 -1
  53. package/lib/commands/functions-secrets-access.js +2 -4
  54. package/lib/commands/index.js +15 -2
  55. package/lib/commands/init.js +25 -15
  56. package/lib/commands/setup-emulators-dataconnect.js +0 -13
  57. package/lib/commands/use.js +1 -1
  58. package/lib/config.js +14 -4
  59. package/lib/crashlytics/buildToolsJarHelper.js +2 -2
  60. package/lib/dataconnect/client.js +3 -2
  61. package/lib/dataconnect/dataplaneClient.js +12 -9
  62. package/lib/dataconnect/ensureApis.js +6 -1
  63. package/lib/dataconnect/fileUtils.js +29 -12
  64. package/lib/dataconnect/freeTrial.js +45 -9
  65. package/lib/dataconnect/load.js +3 -1
  66. package/lib/dataconnect/provisionCloudSql.js +41 -24
  67. package/lib/dataconnect/schemaMigration.js +215 -74
  68. package/lib/dataconnect/types.js +4 -1
  69. package/lib/dataconnect/webhook.js +32 -0
  70. package/lib/deploy/dataconnect/deploy.js +18 -15
  71. package/lib/deploy/dataconnect/prepare.js +41 -0
  72. package/lib/deploy/dataconnect/release.js +16 -7
  73. package/lib/deploy/extensions/deploy.js +3 -1
  74. package/lib/deploy/extensions/deploymentSummary.js +7 -3
  75. package/lib/deploy/extensions/planner.js +95 -5
  76. package/lib/deploy/extensions/prepare.js +89 -42
  77. package/lib/deploy/extensions/release.js +17 -10
  78. package/lib/deploy/extensions/tasks.js +32 -21
  79. package/lib/deploy/firestore/prepare.js +9 -0
  80. package/lib/deploy/firestore/release.js +3 -6
  81. package/lib/deploy/functions/build.js +5 -5
  82. package/lib/deploy/functions/checkIam.js +7 -2
  83. package/lib/deploy/functions/deploy.js +12 -12
  84. package/lib/deploy/functions/ensure.js +11 -3
  85. package/lib/deploy/functions/params.js +5 -3
  86. package/lib/deploy/functions/prepare.js +18 -3
  87. package/lib/deploy/functions/release/index.js +4 -0
  88. package/lib/deploy/functions/release/planner.js +2 -1
  89. package/lib/deploy/functions/runtimes/discovery/index.js +6 -2
  90. package/lib/deploy/functions/runtimes/discovery/parsing.js +1 -1
  91. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +46 -0
  92. package/lib/deploy/functions/runtimes/node/index.js +5 -0
  93. package/lib/deploy/functions/services/auth.js +34 -3
  94. package/lib/deploy/functions/services/index.js +2 -0
  95. package/lib/deploy/index.js +8 -5
  96. package/lib/deploy/lifecycleHooks.js +2 -1
  97. package/lib/emulator/apphosting/config.js +27 -0
  98. package/lib/emulator/apphosting/index.js +38 -0
  99. package/lib/emulator/apphosting/serve.js +50 -0
  100. package/lib/emulator/apphosting/utils.js +18 -0
  101. package/lib/emulator/auth/handlers.js +27 -0
  102. package/lib/emulator/auth/operations.js +41 -2
  103. package/lib/emulator/auth/state.js +2 -1
  104. package/lib/emulator/commandUtils.js +8 -3
  105. package/lib/emulator/constants.js +11 -1
  106. package/lib/emulator/controller.js +59 -6
  107. package/lib/emulator/dataconnect/pg-gateway/auth/base-auth-flow.js +11 -0
  108. package/lib/emulator/dataconnect/pg-gateway/auth/cert.js +58 -0
  109. package/lib/emulator/dataconnect/pg-gateway/auth/index.js +22 -0
  110. package/lib/emulator/dataconnect/pg-gateway/auth/md5.js +124 -0
  111. package/lib/emulator/dataconnect/pg-gateway/auth/password.js +54 -0
  112. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/sasl-mechanism.js +34 -0
  113. package/lib/emulator/dataconnect/pg-gateway/auth/sasl/scram-sha-256.js +270 -0
  114. package/lib/emulator/dataconnect/pg-gateway/auth/trust.js +2 -0
  115. package/lib/emulator/dataconnect/pg-gateway/backend-error.js +75 -0
  116. package/lib/emulator/dataconnect/pg-gateway/buffer-reader.js +54 -0
  117. package/lib/emulator/dataconnect/pg-gateway/buffer-writer.js +79 -0
  118. package/lib/emulator/dataconnect/pg-gateway/connection.js +315 -0
  119. package/lib/emulator/dataconnect/pg-gateway/connection.types.js +8 -0
  120. package/lib/emulator/dataconnect/pg-gateway/crypto.js +40 -0
  121. package/lib/emulator/dataconnect/pg-gateway/duplex.js +53 -0
  122. package/lib/emulator/dataconnect/pg-gateway/index.js +27 -0
  123. package/lib/emulator/dataconnect/pg-gateway/message-buffer.js +82 -0
  124. package/lib/emulator/dataconnect/pg-gateway/message-codes.js +52 -0
  125. package/lib/emulator/dataconnect/pg-gateway/platforms/node/index.js +16 -0
  126. package/lib/emulator/dataconnect/pg-gateway/polyfills/readable-stream-async-iterator.js +35 -0
  127. package/lib/emulator/dataconnect/pg-gateway/utils.js +40 -0
  128. package/lib/emulator/dataconnect/pgliteServer.js +95 -0
  129. package/lib/emulator/dataconnectEmulator.js +58 -75
  130. package/lib/emulator/dataconnectToolkitController.js +44 -0
  131. package/lib/emulator/downloadableEmulators.js +30 -19
  132. package/lib/emulator/emulatorLogger.js +3 -0
  133. package/lib/emulator/env.js +3 -0
  134. package/lib/emulator/eventarcEmulator.js +1 -1
  135. package/lib/emulator/extensionsEmulator.js +38 -6
  136. package/lib/emulator/functionsEmulator.js +115 -42
  137. package/lib/emulator/functionsEmulatorShared.js +18 -1
  138. package/lib/emulator/functionsRuntimeWorker.js +2 -1
  139. package/lib/emulator/hub.js +13 -9
  140. package/lib/emulator/hubExport.js +10 -3
  141. package/lib/emulator/loggingEmulator.js +2 -2
  142. package/lib/emulator/portUtils.js +11 -11
  143. package/lib/emulator/registry.js +2 -0
  144. package/lib/emulator/storage/persistence.js +2 -2
  145. package/lib/emulator/storage/rules/runtime.js +1 -1
  146. package/lib/emulator/taskQueue.js +348 -0
  147. package/lib/emulator/tasksEmulator.js +240 -0
  148. package/lib/emulator/types.js +6 -0
  149. package/lib/emulator/ui.js +51 -25
  150. package/lib/error.js +31 -1
  151. package/lib/experiments.js +5 -0
  152. package/lib/extensions/askUserForEventsConfig.js +18 -8
  153. package/lib/extensions/askUserForParam.js +2 -1
  154. package/lib/extensions/displayExtensionInfo.js +5 -5
  155. package/lib/extensions/emulator/triggerHelper.js +1 -1
  156. package/lib/extensions/extensionsApi.js +15 -11
  157. package/lib/extensions/extensionsHelper.js +39 -8
  158. package/lib/extensions/localHelper.js +32 -1
  159. package/lib/extensions/refs.js +26 -11
  160. package/lib/extensions/runtimes/common.js +215 -0
  161. package/lib/extensions/runtimes/node.js +401 -0
  162. package/lib/extensions/types.js +67 -1
  163. package/lib/extensions/warnings.js +5 -2
  164. package/lib/firestore/api.js +2 -1
  165. package/lib/firestore/checkDatabaseType.js +10 -3
  166. package/lib/firestore/delete.js +11 -0
  167. package/lib/firestore/options.js +7 -0
  168. package/lib/frameworks/angular/index.js +15 -3
  169. package/lib/frameworks/constants.js +2 -2
  170. package/lib/frameworks/flutter/index.js +6 -6
  171. package/lib/frameworks/flutter/utils.js +34 -1
  172. package/lib/frameworks/next/constants.js +1 -1
  173. package/lib/frameworks/next/index.js +45 -17
  174. package/lib/frameworks/next/utils.js +57 -4
  175. package/lib/frameworks/vite/index.js +2 -2
  176. package/lib/fsutils.js +13 -1
  177. package/lib/functions/constants.js +4 -0
  178. package/lib/functions/events/v1.js +9 -2
  179. package/lib/gcp/apphosting.js +1 -1
  180. package/lib/gcp/cloudmonitoring.js +3 -3
  181. package/lib/gcp/cloudsql/cloudsqladmin.js +32 -20
  182. package/lib/gcp/cloudsql/connect.js +49 -37
  183. package/lib/gcp/cloudsql/interactive.js +49 -0
  184. package/lib/gcp/cloudsql/permissions.js +165 -0
  185. package/lib/gcp/devConnect.js +38 -1
  186. package/lib/gcp/firestore.js +5 -1
  187. package/lib/gcp/secretManager.js +12 -5
  188. package/lib/getProjectNumber.js +1 -1
  189. package/lib/init/features/apphosting.js +15 -0
  190. package/lib/init/features/dataconnect/index.js +166 -121
  191. package/lib/init/features/dataconnect/sdk.js +90 -81
  192. package/lib/init/features/emulators.js +2 -15
  193. package/lib/init/features/firestore/index.js +20 -1
  194. package/lib/init/features/firestore/indexes.js +4 -4
  195. package/lib/init/features/genkit/index.js +444 -0
  196. package/lib/init/features/hosting/index.js +2 -2
  197. package/lib/init/features/index.js +1 -1
  198. package/lib/init/features/project.js +6 -6
  199. package/lib/init/features/storage.js +0 -2
  200. package/lib/init/index.js +1 -0
  201. package/lib/init/spawn.js +23 -2
  202. package/lib/logger.js +2 -2
  203. package/lib/management/projects.js +24 -4
  204. package/lib/projectUtils.js +1 -1
  205. package/lib/prompt.js +22 -1
  206. package/lib/rc.js +1 -8
  207. package/lib/requireAuth.js +19 -5
  208. package/lib/requireDatabaseInstance.js +1 -1
  209. package/lib/requirePermissions.js +1 -1
  210. package/lib/responseToError.js +5 -2
  211. package/lib/rulesDeploy.js +1 -1
  212. package/lib/templates.js +2 -2
  213. package/lib/utils.js +16 -11
  214. package/lib/vsCodeUtils.js +8 -0
  215. package/package.json +8 -7
  216. package/schema/connector-yaml.json +57 -17
  217. package/schema/firebase-config.json +36 -0
  218. package/templates/extensions/javascript/package.lint.json +2 -2
  219. package/templates/extensions/javascript/package.nolint.json +2 -2
  220. package/templates/extensions/typescript/package.lint.json +2 -2
  221. package/templates/extensions/typescript/package.nolint.json +2 -2
  222. package/templates/genkit/firebase.0.9.0.template +57 -0
  223. package/templates/init/apphosting/apphosting.yaml +23 -0
  224. package/templates/init/dataconnect/connector.yaml +4 -3
  225. package/templates/init/dataconnect/dataconnect-fdccompatiblemode.yaml +12 -0
  226. package/templates/init/dataconnect/dataconnect.yaml +6 -6
  227. package/templates/init/dataconnect/mutations.gql +44 -29
  228. package/templates/init/dataconnect/queries.gql +65 -38
  229. package/templates/init/dataconnect/schema.gql +38 -21
  230. package/templates/init/functions/javascript/package.lint.json +2 -2
  231. package/templates/init/functions/javascript/package.nolint.json +2 -2
  232. package/templates/init/functions/typescript/package.lint.json +2 -2
  233. package/templates/init/functions/typescript/package.nolint.json +2 -2
  234. package/lib/ensureCloudResourceLocation.js +0 -12
  235. package/lib/init/features/genkit.js +0 -53
@@ -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;
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TasksEmulator = exports.TaskQueueController = void 0;
4
+ const express = require("express");
5
+ const constants_1 = require("./constants");
6
+ const types_1 = require("./types");
7
+ const utils_1 = require("../utils");
8
+ const emulatorLogger_1 = require("./emulatorLogger");
9
+ const taskQueue_1 = require("./taskQueue");
10
+ const cors = require("cors");
11
+ const RETRY_CONFIG_DEFAULTS = {
12
+ maxAttempts: 3,
13
+ maxRetrySeconds: null,
14
+ maxBackoffSeconds: 60 * 60,
15
+ maxDoublings: 16,
16
+ minBackoffSeconds: 0.1,
17
+ };
18
+ const RATE_LIMITS_DEFAULT = {
19
+ maxConcurrentDispatches: 1000,
20
+ maxDispatchesPerSecond: 500,
21
+ };
22
+ class TaskQueueController {
23
+ constructor() {
24
+ this.queues = {};
25
+ this.tokenRefillIds = [];
26
+ this.running = false;
27
+ this.listenId = null;
28
+ }
29
+ enqueue(key, task) {
30
+ if (!this.queues[key]) {
31
+ throw new Error("Queue does not exist");
32
+ }
33
+ this.queues[key].enqueue(task);
34
+ }
35
+ delete(key, taskId) {
36
+ if (!this.queues[key]) {
37
+ throw new Error("Queue does not exist");
38
+ }
39
+ this.queues[key].delete(taskId);
40
+ }
41
+ createQueue(key, config) {
42
+ const newQueue = new taskQueue_1.TaskQueue(key, config);
43
+ const intervalID = setInterval(() => newQueue.refillTokens(), TaskQueueController.TOKEN_REFRESH_INTERVAL);
44
+ this.tokenRefillIds.push(intervalID);
45
+ this.queues[key] = newQueue;
46
+ }
47
+ listen() {
48
+ let shouldUpdate = false;
49
+ for (const [_key, queue] of Object.entries(this.queues)) {
50
+ shouldUpdate = shouldUpdate || queue.isActive();
51
+ }
52
+ if (shouldUpdate) {
53
+ this.updateQueues();
54
+ this.listenId = setTimeout(() => this.listen(), TaskQueueController.UPDATE_TIMEOUT);
55
+ }
56
+ else {
57
+ this.listenId = setTimeout(() => this.listen(), TaskQueueController.LISTEN_TIMEOUT);
58
+ }
59
+ }
60
+ updateQueues() {
61
+ for (const [_key, queue] of Object.entries(this.queues)) {
62
+ if (queue.isActive()) {
63
+ queue.dispatchTasks();
64
+ queue.processDispatch();
65
+ }
66
+ }
67
+ }
68
+ start() {
69
+ this.running = true;
70
+ this.listen();
71
+ }
72
+ stop() {
73
+ if (this.listenId) {
74
+ clearTimeout(this.listenId);
75
+ }
76
+ this.tokenRefillIds.forEach(clearInterval);
77
+ this.running = false;
78
+ }
79
+ isRunning() {
80
+ return this.running;
81
+ }
82
+ getStatistics() {
83
+ const stats = {};
84
+ for (const [key, queue] of Object.entries(this.queues)) {
85
+ stats[key] = queue.getStatistics();
86
+ }
87
+ return stats;
88
+ }
89
+ }
90
+ exports.TaskQueueController = TaskQueueController;
91
+ TaskQueueController.UPDATE_TIMEOUT = 0;
92
+ TaskQueueController.LISTEN_TIMEOUT = 1000;
93
+ TaskQueueController.TOKEN_REFRESH_INTERVAL = 1000;
94
+ class TasksEmulator {
95
+ constructor(args) {
96
+ this.args = args;
97
+ this.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.TASKS);
98
+ this.controller = new TaskQueueController();
99
+ }
100
+ validateQueueId(queueId) {
101
+ if (typeof queueId !== "string") {
102
+ return false;
103
+ }
104
+ if (queueId.length > 100) {
105
+ return false;
106
+ }
107
+ const regex = /^[A-Za-z0-9-]+$/;
108
+ return regex.test(queueId);
109
+ }
110
+ createHubServer() {
111
+ const hub = express();
112
+ const createTaskQueueRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name`;
113
+ const createTaskQueueHandler = (req, res) => {
114
+ const projectId = req.params.project_id;
115
+ const locationId = req.params.location_id;
116
+ const queueName = req.params.queue_name;
117
+ if (!this.validateQueueId(queueName)) {
118
+ res.status(400).json({
119
+ error: "Queue ID must start with a letter followed by up to 62 letters, numbers, " +
120
+ "hyphens, or underscores and must end with a letter or a number",
121
+ });
122
+ return;
123
+ }
124
+ const key = `queue:${projectId}-${locationId}-${queueName}`;
125
+ this.logger.logLabeled("SUCCESS", "tasks", `Created queue with key: ${key}`);
126
+ const body = req.body;
127
+ const taskQueueConfig = {
128
+ retryConfig: {
129
+ maxAttempts: body.retryConfig?.maxAttempts ?? RETRY_CONFIG_DEFAULTS.maxAttempts,
130
+ maxRetrySeconds: body.retryConfig?.maxRetrySeconds ?? RETRY_CONFIG_DEFAULTS.maxRetrySeconds,
131
+ maxBackoffSeconds: body.retryConfig?.maxBackoffSeconds ?? RETRY_CONFIG_DEFAULTS.maxBackoffSeconds,
132
+ maxDoublings: body.retryConfig?.maxDoublings ?? RETRY_CONFIG_DEFAULTS.maxDoublings,
133
+ minBackoffSeconds: body.retryConfig?.minBackoffSeconds ?? RETRY_CONFIG_DEFAULTS.minBackoffSeconds,
134
+ },
135
+ rateLimits: {
136
+ maxConcurrentDispatches: body.rateLimits?.maxConcurrentDispatches ?? RATE_LIMITS_DEFAULT.maxConcurrentDispatches,
137
+ maxDispatchesPerSecond: body.rateLimits?.maxDispatchesPerSecond ?? RATE_LIMITS_DEFAULT.maxDispatchesPerSecond,
138
+ },
139
+ timeoutSeconds: body.timeoutSeconds ?? 10,
140
+ retry: body.retry ?? false,
141
+ defaultUri: body.defaultUri,
142
+ };
143
+ if (taskQueueConfig.rateLimits.maxConcurrentDispatches > 5000) {
144
+ res.status(400).json({ error: "cannot set maxConcurrentDispatches to a value over 5000" });
145
+ return;
146
+ }
147
+ this.controller.createQueue(key, taskQueueConfig);
148
+ this.logger.log("DEBUG", `Created task queue ${key} with configuration: ${JSON.stringify(taskQueueConfig)}`);
149
+ res.status(200).send({ taskQueueConfig });
150
+ };
151
+ const enqueueTasksRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name/tasks`;
152
+ const enqueueTasksHandler = (req, res) => {
153
+ if (!this.controller.isRunning()) {
154
+ this.controller.start();
155
+ }
156
+ const projectId = req.params.project_id;
157
+ const locationId = req.params.location_id;
158
+ const queueName = req.params.queue_name;
159
+ const queueKey = `queue:${projectId}-${locationId}-${queueName}`;
160
+ if (!this.controller.queues[queueKey]) {
161
+ this.logger.log("WARN", "Tried to queue a task into a non-existent queue");
162
+ res.status(404).send("Tried to queue a task from a non-existent queue");
163
+ return;
164
+ }
165
+ req.body.task.name =
166
+ req.body.task.name ??
167
+ `/projects/${projectId}/locations/${locationId}/queues/${queueName}/tasks/${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}`;
168
+ req.body.task.httpRequest.body = JSON.parse(atob(req.body.task.httpRequest.body));
169
+ const task = req.body.task;
170
+ try {
171
+ this.controller.enqueue(queueKey, task);
172
+ this.logger.log("DEBUG", `Enqueueing task ${task.name} onto ${queueKey}`);
173
+ res.status(200).send({ task: task });
174
+ }
175
+ catch (e) {
176
+ res.status(409).send("A task with the same name already exists");
177
+ }
178
+ };
179
+ const deleteTasksRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name/tasks/:task_id`;
180
+ const deleteTasksHandler = (req, res) => {
181
+ const projectId = req.params.project_id;
182
+ const locationId = req.params.location_id;
183
+ const queueName = req.params.queue_name;
184
+ const taskId = req.params.task_id;
185
+ const queueKey = `queue:${projectId}-${locationId}-${queueName}`;
186
+ if (!this.controller.queues[queueKey]) {
187
+ this.logger.log("WARN", "Tried to remove a task from a non-existent queue");
188
+ res.status(404).send("Tried to remove a task from a non-existent queue");
189
+ return;
190
+ }
191
+ try {
192
+ const taskName = `projects/${projectId}/locations/${locationId}/queues/${queueName}/tasks/${taskId}`;
193
+ this.logger.log("DEBUG", `removing: ${taskName}`);
194
+ this.controller.delete(queueKey, taskName);
195
+ res.status(200).send({ res: "OK" });
196
+ }
197
+ catch (e) {
198
+ this.logger.log("WARN", "Tried to remove a task that doesn't exist");
199
+ res.status(404).send("Tried to remove a task that doesn't exist");
200
+ }
201
+ };
202
+ const getStatsRoute = `/queueStats`;
203
+ const getStatsHandler = (req, res) => {
204
+ res.json(this.controller.getStatistics());
205
+ };
206
+ hub.get([getStatsRoute], cors({ origin: true }), getStatsHandler);
207
+ hub.post([createTaskQueueRoute], express.json(), createTaskQueueHandler);
208
+ hub.post([enqueueTasksRoute], express.json(), enqueueTasksHandler);
209
+ hub.delete([deleteTasksRoute], express.json(), deleteTasksHandler);
210
+ return hub;
211
+ }
212
+ async start() {
213
+ const { host, port } = this.getInfo();
214
+ const server = this.createHubServer().listen(port, host);
215
+ this.destroyServer = (0, utils_1.createDestroyer)(server);
216
+ return Promise.resolve();
217
+ }
218
+ async connect() {
219
+ return Promise.resolve();
220
+ }
221
+ async stop() {
222
+ if (this.destroyServer) {
223
+ await this.destroyServer();
224
+ }
225
+ this.controller.stop();
226
+ }
227
+ getInfo() {
228
+ const host = this.args.host || constants_1.Constants.getDefaultHost();
229
+ const port = this.args.port || constants_1.Constants.getDefaultPort(types_1.Emulators.TASKS);
230
+ return {
231
+ name: this.getName(),
232
+ host,
233
+ port,
234
+ };
235
+ }
236
+ getName() {
237
+ return types_1.Emulators.TASKS;
238
+ }
239
+ }
240
+ exports.TasksEmulator = TasksEmulator;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Severity = exports.EmulatorLog = exports.FunctionsExecutionMode = exports.isEmulator = exports.isDownloadableEmulator = exports.ALL_EMULATORS = exports.EMULATORS_SUPPORTED_BY_USE_EMULATOR = exports.EMULATORS_SUPPORTED_BY_UI = exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = exports.ALL_SERVICE_EMULATORS = exports.IMPORT_EXPORT_EMULATORS = exports.DOWNLOADABLE_EMULATORS = exports.Emulators = void 0;
4
+ const experiments = require("../experiments");
4
5
  var Emulators;
5
6
  (function (Emulators) {
6
7
  Emulators["AUTH"] = "auth";
@@ -9,6 +10,7 @@ var Emulators;
9
10
  Emulators["FIRESTORE"] = "firestore";
10
11
  Emulators["DATABASE"] = "database";
11
12
  Emulators["HOSTING"] = "hosting";
13
+ Emulators["APPHOSTING"] = "apphosting";
12
14
  Emulators["PUBSUB"] = "pubsub";
13
15
  Emulators["UI"] = "ui";
14
16
  Emulators["LOGGING"] = "logging";
@@ -16,6 +18,7 @@ var Emulators;
16
18
  Emulators["EXTENSIONS"] = "extensions";
17
19
  Emulators["EVENTARC"] = "eventarc";
18
20
  Emulators["DATACONNECT"] = "dataconnect";
21
+ Emulators["TASKS"] = "tasks";
19
22
  })(Emulators = exports.Emulators || (exports.Emulators = {}));
20
23
  exports.DOWNLOADABLE_EMULATORS = [
21
24
  Emulators.FIRESTORE,
@@ -32,6 +35,7 @@ exports.IMPORT_EXPORT_EMULATORS = [
32
35
  Emulators.STORAGE,
33
36
  ];
34
37
  exports.ALL_SERVICE_EMULATORS = [
38
+ ...(experiments.isEnabled("emulatorapphosting") ? [Emulators.APPHOSTING] : []),
35
39
  Emulators.AUTH,
36
40
  Emulators.FUNCTIONS,
37
41
  Emulators.FIRESTORE,
@@ -41,6 +45,7 @@ exports.ALL_SERVICE_EMULATORS = [
41
45
  Emulators.STORAGE,
42
46
  Emulators.EVENTARC,
43
47
  Emulators.DATACONNECT,
48
+ Emulators.TASKS,
44
49
  ].filter((v) => v);
45
50
  exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = [
46
51
  Emulators.FIRESTORE,
@@ -48,6 +53,7 @@ exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = [
48
53
  Emulators.PUBSUB,
49
54
  Emulators.STORAGE,
50
55
  Emulators.EVENTARC,
56
+ Emulators.TASKS,
51
57
  ];
52
58
  exports.EMULATORS_SUPPORTED_BY_UI = [
53
59
  Emulators.AUTH,