gcf-utils 13.3.2-beta.2 → 13.5.1

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.
@@ -15,7 +15,11 @@
15
15
  // limitations under the License.
16
16
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
17
17
  if (k2 === undefined) k2 = k;
18
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
18
+ var desc = Object.getOwnPropertyDescriptor(m, k);
19
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
20
+ desc = { enumerable: true, get: function() { return m[k]; } };
21
+ }
22
+ Object.defineProperty(o, k2, desc);
19
23
  }) : (function(o, m, k, k2) {
20
24
  if (k2 === undefined) k2 = k;
21
25
  o[k2] = m[k];
@@ -79,14 +83,14 @@ const botname = argv.bot;
79
83
  const webhookSecret = argv.secret;
80
84
  const id = Number(argv.id);
81
85
  async function run(keyfile, webhookSecret, id, project, botname) {
82
- const blob = await genkey_util_1.gather(keyfile, id, webhookSecret);
86
+ const blob = await (0, genkey_util_1.gather)(keyfile, id, webhookSecret);
83
87
  const opts = project
84
88
  ? {
85
89
  projectId: project,
86
90
  }
87
91
  : undefined;
88
92
  const smclient = new secret_manager_1.v1.SecretManagerServiceClient(opts);
89
- await genkey_util_1.create(smclient, project, botname, blob);
93
+ await (0, genkey_util_1.create)(smclient, project, botname, blob);
90
94
  }
91
95
  run(keyfile, webhookSecret, id, project, botname);
92
96
  //# sourceMappingURL=genkey.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"genkey.js","sourceRoot":"","sources":["../../../src/bin/genkey.ts"],"names":[],"mappings":";;AACA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;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;IACzD,MAAM,IAAA,oBAAM,EAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AACjD,CAAC;AAED,GAAG,CAAC,OAAO,EAAE,aAAa,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC"}
@@ -0,0 +1,21 @@
1
+ import * as express from 'express';
2
+ /**
3
+ * Type of function execution trigger
4
+ */
5
+ export declare enum TriggerType {
6
+ GITHUB = "GitHub Webhook",
7
+ SCHEDULER = "Cloud Scheduler",
8
+ TASK = "Cloud Task",
9
+ PUBSUB = "Pub/Sub",
10
+ UNKNOWN = "Unknown"
11
+ }
12
+ export interface BotRequest {
13
+ eventName: string;
14
+ githubDeliveryId: string;
15
+ signature?: string;
16
+ taskName?: string;
17
+ taskRetryCount?: number;
18
+ traceId?: string;
19
+ triggerType: TriggerType;
20
+ }
21
+ export declare function parseBotRequest(request: express.Request): BotRequest;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ // Copyright 2022 Google LLC
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.parseBotRequest = exports.TriggerType = void 0;
17
+ const custom_events_1 = require("./custom-events");
18
+ /**
19
+ * Type of function execution trigger
20
+ */
21
+ var TriggerType;
22
+ (function (TriggerType) {
23
+ TriggerType["GITHUB"] = "GitHub Webhook";
24
+ TriggerType["SCHEDULER"] = "Cloud Scheduler";
25
+ TriggerType["TASK"] = "Cloud Task";
26
+ TriggerType["PUBSUB"] = "Pub/Sub";
27
+ TriggerType["UNKNOWN"] = "Unknown";
28
+ })(TriggerType = exports.TriggerType || (exports.TriggerType = {}));
29
+ function parseBotRequest(request) {
30
+ const eventName = request.get('X-GitHub-Event') || '';
31
+ const githubDeliveryId = request.get('X-GitHub-Delivery') || '';
32
+ const signature = parseSignatureHeader(request);
33
+ const taskName = request.get('X-CloudTasks-TaskName');
34
+ const taskRetryCount = parseInt(request.get('X-CloudTasks-TaskRetryCount') || '0');
35
+ const triggerType = parseTriggerType(eventName, taskName);
36
+ const traceId = parseTraceId(request);
37
+ return {
38
+ eventName,
39
+ githubDeliveryId,
40
+ signature,
41
+ taskName,
42
+ taskRetryCount,
43
+ traceId,
44
+ triggerType,
45
+ };
46
+ }
47
+ exports.parseBotRequest = parseBotRequest;
48
+ /**
49
+ * Determine the type of trigger that started this execution
50
+ * @param eventName event name from header
51
+ * @param taskName task id from header
52
+ */
53
+ function parseTriggerType(eventName, taskName) {
54
+ if (!taskName && custom_events_1.SCHEDULER_EVENT_NAMES.includes(eventName)) {
55
+ return TriggerType.SCHEDULER;
56
+ }
57
+ else if (!taskName && eventName === 'pubsub.message') {
58
+ return TriggerType.PUBSUB;
59
+ }
60
+ else if (!taskName && eventName) {
61
+ return TriggerType.GITHUB;
62
+ }
63
+ else if (eventName) {
64
+ return TriggerType.TASK;
65
+ }
66
+ return TriggerType.UNKNOWN;
67
+ }
68
+ /**
69
+ * Parse the signature from the request headers.
70
+ *
71
+ * If the expected header is not set, returns `unset` because the verification
72
+ * function throws an exception on empty string when we would rather
73
+ * treat the error as an invalid signature.
74
+ * @param request incoming trigger request
75
+ */
76
+ function parseSignatureHeader(request) {
77
+ const sha1Signature = request.get('X-Hub-Signature');
78
+ if (sha1Signature) {
79
+ return sha1Signature;
80
+ }
81
+ return 'unset';
82
+ }
83
+ /**
84
+ * Parse the trace id from the trace context header. The format of the header
85
+ * looks something like `<trace-id>/<span-id>;o=<options-flags>`.
86
+ * @param request incoming trigger request
87
+ */
88
+ function parseTraceId(request) {
89
+ const traceContext = request.get('X-Cloud-Trace-Context');
90
+ if (!traceContext) {
91
+ return undefined;
92
+ }
93
+ const parts = traceContext.split('/');
94
+ if (parts.length === 0 || !parts[0]) {
95
+ return undefined;
96
+ }
97
+ return parts[0];
98
+ }
99
+ //# sourceMappingURL=bot-request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot-request.js","sourceRoot":"","sources":["../../src/bot-request.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAGjC,mDAAsD;AAEtD;;GAEG;AACH,IAAY,WAMX;AAND,WAAY,WAAW;IACrB,wCAAyB,CAAA;IACzB,4CAA6B,CAAA;IAC7B,kCAAmB,CAAA;IACnB,iCAAkB,CAAA;IAClB,kCAAmB,CAAA;AACrB,CAAC,EANW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAMtB;AAYD,SAAgB,eAAe,CAAC,OAAwB;IACtD,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;IACtD,MAAM,gBAAgB,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,IAAI,EAAE,CAAC;IAChE,MAAM,SAAS,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACtD,MAAM,cAAc,GAAG,QAAQ,CAC7B,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,IAAI,GAAG,CAClD,CAAC;IACF,MAAM,WAAW,GAAG,gBAAgB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACtC,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 -0,0 +1,4 @@
1
+ export declare const SCHEDULER_GLOBAL_EVENT_NAME = "schedule.global";
2
+ export declare const SCHEDULER_INSTALLATION_EVENT_NAME = "schedule.installation";
3
+ export declare const SCHEDULER_REPOSITORY_EVENT_NAME = "schedule.repository";
4
+ export declare const SCHEDULER_EVENT_NAMES: string[];
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ // Copyright 2022 Google LLC
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.SCHEDULER_EVENT_NAMES = exports.SCHEDULER_REPOSITORY_EVENT_NAME = exports.SCHEDULER_INSTALLATION_EVENT_NAME = exports.SCHEDULER_GLOBAL_EVENT_NAME = void 0;
17
+ exports.SCHEDULER_GLOBAL_EVENT_NAME = 'schedule.global';
18
+ exports.SCHEDULER_INSTALLATION_EVENT_NAME = 'schedule.installation';
19
+ exports.SCHEDULER_REPOSITORY_EVENT_NAME = 'schedule.repository';
20
+ exports.SCHEDULER_EVENT_NAMES = [
21
+ exports.SCHEDULER_GLOBAL_EVENT_NAME,
22
+ exports.SCHEDULER_INSTALLATION_EVENT_NAME,
23
+ exports.SCHEDULER_REPOSITORY_EVENT_NAME,
24
+ ];
25
+ //# sourceMappingURL=custom-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custom-events.js","sourceRoot":"","sources":["../../src/custom-events.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEpB,QAAA,2BAA2B,GAAG,iBAAiB,CAAC;AAChD,QAAA,iCAAiC,GAAG,uBAAuB,CAAC;AAC5D,QAAA,+BAA+B,GAAG,qBAAqB,CAAC;AACxD,QAAA,qBAAqB,GAAG;IACnC,mCAA2B;IAC3B,yCAAiC;IACjC,uCAA+B;CAChC,CAAC"}
@@ -8,6 +8,8 @@ import { Storage } from '@google-cloud/storage';
8
8
  import * as express from 'express';
9
9
  import { Octokit } from '@octokit/rest';
10
10
  import { GCFLogger } from './logging/gcf-logger';
11
+ export { TriggerType } from './bot-request';
12
+ export { GCFLogger } from './logging/gcf-logger';
11
13
  export interface RequestWithRawBody extends express.Request {
12
14
  rawBody?: Buffer;
13
15
  }
@@ -48,16 +50,6 @@ export interface CronPayload {
48
50
  };
49
51
  cron_org: string;
50
52
  }
51
- /**
52
- * Type of function execution trigger
53
- */
54
- export declare enum TriggerType {
55
- GITHUB = "GitHub Webhook",
56
- SCHEDULER = "Cloud Scheduler",
57
- TASK = "Cloud Task",
58
- PUBSUB = "Pub/Sub",
59
- UNKNOWN = "Unknown"
60
- }
61
53
  /**
62
54
  * It creates a comment string used for `addOrUpdateissuecomment`.
63
55
  */
@@ -105,26 +97,6 @@ export declare class GCFBootstrapper {
105
97
  getSecretName(): string;
106
98
  getLatestSecretVersionName(): string;
107
99
  getProbotConfig(logging?: boolean): Promise<Options>;
108
- /**
109
- * Parse the signature from the request headers.
110
- *
111
- * If the expected header is not set, returns `unset` because the verification
112
- * function throws an exception on empty string when we would rather
113
- * treat the error as an invalid signature.
114
- * @param request incoming trigger request
115
- */
116
- private static parseSignatureHeader;
117
- /**
118
- * Parse the event name, delivery id, signature and task id from the request headers
119
- * @param request incoming trigger request
120
- */
121
- private static parseRequestHeaders;
122
- /**
123
- * Determine the type of trigger that started this execution
124
- * @param name event name from header
125
- * @param taskId task id from header
126
- */
127
- private static parseTriggerType;
128
100
  private parseWrapConfig;
129
101
  private getRetryLimit;
130
102
  /**
@@ -141,6 +113,7 @@ export declare class GCFBootstrapper {
141
113
  * @param wrapOptions {WrapOptions} Bot handler options
142
114
  */
143
115
  gcf(appFn: ApplicationFunction, wrapOptions?: WrapOptions): HandlerFunction;
116
+ private buildLoggerBindings;
144
117
  /**
145
118
  * Entrypoint for handling all scheduled tasks.
146
119
  *
@@ -236,4 +209,4 @@ export declare class GCFBootstrapper {
236
209
  private maybeWriteBodyToTmp;
237
210
  private maybeDownloadOriginalBody;
238
211
  }
239
- export {};
212
+ export declare function getContextLogger(context: any): GCFLogger;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.GCFBootstrapper = exports.addOrUpdateIssueComment = exports.getCommentMark = exports.TriggerType = exports.logger = void 0;
6
+ exports.getContextLogger = exports.GCFBootstrapper = exports.addOrUpdateIssueComment = exports.getCommentMark = exports.logger = exports.GCFLogger = exports.TriggerType = void 0;
7
7
  // Copyright 2019 Google LLC
8
8
  //
9
9
  // Licensed under the Apache License, Version 2.0 (the "License");
@@ -34,17 +34,15 @@ const uuid_1 = require("uuid");
34
34
  const server_1 = require("./server/server");
35
35
  const run_1 = require("@googleapis/run");
36
36
  const google_auth_library_1 = require("google-auth-library");
37
+ const bot_request_1 = require("./bot-request");
38
+ const custom_events_1 = require("./custom-events");
39
+ var bot_request_2 = require("./bot-request");
40
+ Object.defineProperty(exports, "TriggerType", { enumerable: true, get: function () { return bot_request_2.TriggerType; } });
41
+ var gcf_logger_2 = require("./logging/gcf-logger");
42
+ Object.defineProperty(exports, "GCFLogger", { enumerable: true, get: function () { return gcf_logger_2.GCFLogger; } });
37
43
  // eslint-disable-next-line @typescript-eslint/no-var-requires
38
44
  const LoggingOctokitPlugin = require('../src/logging/logging-octokit-plugin.js');
39
45
  const DEFAULT_CRON_TYPE = 'repository';
40
- const SCHEDULER_GLOBAL_EVENT_NAME = 'schedule.global';
41
- const SCHEDULER_INSTALLATION_EVENT_NAME = 'schedule.installation';
42
- const SCHEDULER_REPOSITORY_EVENT_NAME = 'schedule.repository';
43
- const SCHEDULER_EVENT_NAMES = [
44
- SCHEDULER_GLOBAL_EVENT_NAME,
45
- SCHEDULER_INSTALLATION_EVENT_NAME,
46
- SCHEDULER_REPOSITORY_EVENT_NAME,
47
- ];
48
46
  const RUNNING_IN_TEST = process.env.NODE_ENV === 'test';
49
47
  const DEFAULT_TASK_CALLER = 'task-caller@repo-automation-bots.iam.gserviceaccount.com';
50
48
  const DEFAULT_WRAP_CONFIG = {
@@ -55,17 +53,6 @@ const DEFAULT_WRAP_CONFIG = {
55
53
  maxPubSubRetries: 0,
56
54
  };
57
55
  exports.logger = new gcf_logger_1.GCFLogger();
58
- /**
59
- * Type of function execution trigger
60
- */
61
- var TriggerType;
62
- (function (TriggerType) {
63
- TriggerType["GITHUB"] = "GitHub Webhook";
64
- TriggerType["SCHEDULER"] = "Cloud Scheduler";
65
- TriggerType["TASK"] = "Cloud Task";
66
- TriggerType["PUBSUB"] = "Pub/Sub";
67
- TriggerType["UNKNOWN"] = "Unknown";
68
- })(TriggerType = exports.TriggerType || (exports.TriggerType = {}));
69
56
  /**
70
57
  * It creates a comment string used for `addOrUpdateissuecomment`.
71
58
  */
@@ -89,7 +76,7 @@ exports.getCommentMark = getCommentMark;
89
76
  */
90
77
  const addOrUpdateIssueComment = async (octokit, owner, repo, issueNumber, installationId, commentBody, onlyUpdate = false) => {
91
78
  var _a;
92
- const commentMark = exports.getCommentMark(installationId);
79
+ const commentMark = (0, exports.getCommentMark)(installationId);
93
80
  const listCommentsResponse = await octokit.issues.listComments({
94
81
  owner: owner,
95
82
  repo: repo,
@@ -160,7 +147,7 @@ class GCFBootstrapper {
160
147
  async loadProbot(appFn, logging) {
161
148
  if (!this.probot) {
162
149
  const cfg = await this.getProbotConfig(logging);
163
- this.probot = probot_1.createProbot({ overrides: cfg });
150
+ this.probot = (0, probot_1.createProbot)({ overrides: cfg });
164
151
  }
165
152
  await this.probot.load(appFn);
166
153
  return this.probot;
@@ -206,63 +193,11 @@ class GCFBootstrapper {
206
193
  });
207
194
  return {
208
195
  ...config,
196
+ log: exports.logger,
209
197
  Octokit: DefaultOctokit,
210
198
  };
211
199
  }
212
200
  }
213
- /**
214
- * Parse the signature from the request headers.
215
- *
216
- * If the expected header is not set, returns `unset` because the verification
217
- * function throws an exception on empty string when we would rather
218
- * treat the error as an invalid signature.
219
- * @param request incoming trigger request
220
- */
221
- static parseSignatureHeader(request) {
222
- const sha1Signature = request.get('x-hub-signature') || request.get('X-Hub-Signature');
223
- if (sha1Signature) {
224
- return sha1Signature;
225
- }
226
- return 'unset';
227
- }
228
- /**
229
- * Parse the event name, delivery id, signature and task id from the request headers
230
- * @param request incoming trigger request
231
- */
232
- static parseRequestHeaders(request) {
233
- const name = request.get('x-github-event') || request.get('X-GitHub-Event') || '';
234
- const id = request.get('x-github-delivery') ||
235
- request.get('X-GitHub-Delivery') ||
236
- '';
237
- const signature = this.parseSignatureHeader(request);
238
- const taskId = request.get('X-CloudTasks-TaskName') ||
239
- request.get('x-cloudtasks-taskname') ||
240
- '';
241
- const taskRetries = parseInt(request.get('X-CloudTasks-TaskRetryCount') ||
242
- request.get('x-cloudtasks-taskretrycount') ||
243
- '0');
244
- return { name, id, signature, taskId, taskRetries };
245
- }
246
- /**
247
- * Determine the type of trigger that started this execution
248
- * @param name event name from header
249
- * @param taskId task id from header
250
- */
251
- static parseTriggerType(name, taskId) {
252
- if (!taskId && SCHEDULER_EVENT_NAMES.includes(name)) {
253
- return TriggerType.SCHEDULER;
254
- }
255
- else if (!taskId && name === 'pubsub.message') {
256
- return TriggerType.PUBSUB;
257
- }
258
- else if (!taskId && name) {
259
- return TriggerType.GITHUB;
260
- }
261
- else if (name) {
262
- return TriggerType.TASK;
263
- }
264
- return TriggerType.UNKNOWN;
265
- }
266
201
  parseWrapConfig(wrapOptions) {
267
202
  const wrapConfig = {
268
203
  ...DEFAULT_WRAP_CONFIG,
@@ -294,7 +229,7 @@ class GCFBootstrapper {
294
229
  * @param wrapOptions {WrapOptions} Bot handler options
295
230
  */
296
231
  server(appFn, wrapOptions) {
297
- return server_1.getServer(this.gcf(appFn, wrapOptions));
232
+ return (0, server_1.getServer)(this.gcf(appFn, wrapOptions));
298
233
  }
299
234
  /**
300
235
  * Wrap an ApplicationFunction in so it can be started in a Google
@@ -307,13 +242,11 @@ class GCFBootstrapper {
307
242
  const wrapConfig = this.parseWrapConfig(wrapOptions);
308
243
  this.probot =
309
244
  this.probot || (await this.loadProbot(appFn, wrapConfig.logging));
310
- const { name, id, signature, taskId, taskRetries } = GCFBootstrapper.parseRequestHeaders(request);
311
- const triggerType = GCFBootstrapper.parseTriggerType(name, taskId);
245
+ // parse all common fields from a bot request
246
+ const botRequest = (0, bot_request_1.parseBotRequest)(request);
312
247
  // validate the signature
313
- exports.logger.info(`request.rawBody: ${request.rawBody}`);
314
248
  if (!wrapConfig.skipVerification &&
315
- !(await this.probot.webhooks.verify(request.rawBody ? request.rawBody.toString() : request.body, signature))) {
316
- exports.logger.info('Signature verification failed');
249
+ !(await this.probot.webhooks.verify(request.rawBody ? request.rawBody.toString() : request.body, botRequest.signature))) {
317
250
  response.status(400).send({
318
251
  statusCode: 400,
319
252
  body: JSON.stringify({ message: 'Invalid signature' }),
@@ -324,33 +257,34 @@ class GCFBootstrapper {
324
257
  * Note: any logs written before resetting bindings may contain
325
258
  * bindings from previous executions
326
259
  */
260
+ const loggerBindings = this.buildLoggerBindings(botRequest, request.body);
327
261
  exports.logger.resetBindings();
328
- exports.logger.addBindings(trigger_info_builder_1.buildTriggerInfo(triggerType, id, name, request.body));
262
+ exports.logger.addBindings(loggerBindings);
263
+ const requestLogger = exports.logger.child(loggerBindings);
329
264
  try {
330
- if (triggerType === TriggerType.UNKNOWN) {
331
- exports.logger.info('Trigger type is unknown');
265
+ if (botRequest.triggerType === bot_request_1.TriggerType.UNKNOWN) {
332
266
  response.sendStatus(400);
333
267
  return;
334
268
  }
335
- else if (triggerType === TriggerType.SCHEDULER) {
269
+ else if (botRequest.triggerType === bot_request_1.TriggerType.SCHEDULER) {
336
270
  // Cloud scheduler tasks (cron)
337
- await this.handleScheduled(id, request, wrapConfig);
271
+ await this.handleScheduled(botRequest.githubDeliveryId, request, wrapConfig);
338
272
  }
339
- else if (triggerType === TriggerType.PUBSUB) {
273
+ else if (botRequest.triggerType === bot_request_1.TriggerType.PUBSUB) {
340
274
  const payload = this.parsePubSubPayload(request);
341
275
  await this.enqueueTask({
342
- id,
343
- name,
276
+ id: botRequest.githubDeliveryId,
277
+ name: botRequest.eventName,
344
278
  body: JSON.stringify(payload),
345
279
  });
346
280
  }
347
- else if (triggerType === TriggerType.TASK) {
348
- const maxRetries = this.getRetryLimit(wrapConfig, name);
281
+ else if (botRequest.triggerType === bot_request_1.TriggerType.TASK) {
282
+ const maxRetries = this.getRetryLimit(wrapConfig, botRequest.eventName);
349
283
  // Abort task retries if we've hit the max number by
350
284
  // returning "success"
351
- if (taskRetries > maxRetries) {
352
- exports.logger.metric('too-many-retries');
353
- exports.logger.info(`Too many retries: ${taskRetries} > ${maxRetries}`);
285
+ if (botRequest.taskRetryCount > maxRetries) {
286
+ requestLogger.metric('too-many-retries');
287
+ requestLogger.info(`Too many retries: ${botRequest.taskRetryCount} > ${maxRetries}`);
354
288
  // return 200 so we don't retry the task again
355
289
  response.send({
356
290
  statusCode: 200,
@@ -364,28 +298,29 @@ class GCFBootstrapper {
364
298
  // The payload does not exist, stop retrying on this task by letting
365
299
  // this request "succeed".
366
300
  if (!payload) {
367
- exports.logger.metric('payload-expired');
301
+ requestLogger.metric('payload-expired');
368
302
  response.send({
369
303
  statusCode: 200,
370
304
  body: JSON.stringify({ message: 'Payload expired' }),
371
305
  });
372
306
  return;
373
307
  }
308
+ setContextLogger(payload, requestLogger);
374
309
  // TODO: find out the best way to get this type, and whether we can
375
310
  // keep using a custom event name.
376
311
  await this.probot.receive({
377
312
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
378
- name: name,
313
+ name: botRequest.eventName,
379
314
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
380
- id: id,
315
+ id: botRequest.githubDeliveryId,
381
316
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
382
317
  payload: payload,
383
318
  });
384
319
  }
385
- else if (triggerType === TriggerType.GITHUB) {
320
+ else if (botRequest.triggerType === bot_request_1.TriggerType.GITHUB) {
386
321
  await this.enqueueTask({
387
- id,
388
- name,
322
+ id: botRequest.githubDeliveryId,
323
+ name: botRequest.eventName,
389
324
  body: JSON.stringify(request.body),
390
325
  });
391
326
  }
@@ -395,16 +330,30 @@ class GCFBootstrapper {
395
330
  });
396
331
  }
397
332
  catch (err) {
398
- exports.logger.error(err);
333
+ requestLogger.error(err);
399
334
  response.status(500).send({
400
335
  statusCode: 500,
401
336
  body: JSON.stringify({ message: err.message }),
402
337
  });
403
338
  return;
404
339
  }
340
+ requestLogger.flushSync();
405
341
  exports.logger.flushSync();
406
342
  };
407
343
  }
344
+ buildLoggerBindings(botRequest,
345
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
346
+ requestBody) {
347
+ const extras = {};
348
+ const triggerInfo = (0, trigger_info_builder_1.buildTriggerInfo)(botRequest, requestBody);
349
+ if (botRequest.traceId) {
350
+ extras['logging.googleapis.com/trace'] = `projects/${this.projectId}/traces/${botRequest.traceId}`;
351
+ }
352
+ return {
353
+ ...triggerInfo,
354
+ ...extras,
355
+ };
356
+ }
408
357
  /**
409
358
  * Entrypoint for handling all scheduled tasks.
410
359
  *
@@ -440,7 +389,7 @@ class GCFBootstrapper {
440
389
  async handleScheduledGlobal(id, body) {
441
390
  await this.enqueueTask({
442
391
  id,
443
- name: SCHEDULER_GLOBAL_EVENT_NAME,
392
+ name: custom_events_1.SCHEDULER_GLOBAL_EVENT_NAME,
444
393
  body: JSON.stringify(body),
445
394
  });
446
395
  }
@@ -501,7 +450,7 @@ class GCFBootstrapper {
501
450
  if (body.installation) {
502
451
  await this.enqueueTask({
503
452
  id,
504
- name: SCHEDULER_INSTALLATION_EVENT_NAME,
453
+ name: custom_events_1.SCHEDULER_INSTALLATION_EVENT_NAME,
505
454
  body: JSON.stringify(body),
506
455
  });
507
456
  }
@@ -523,7 +472,7 @@ class GCFBootstrapper {
523
472
  };
524
473
  await this.enqueueTask({
525
474
  id,
526
- name: SCHEDULER_INSTALLATION_EVENT_NAME,
475
+ name: custom_events_1.SCHEDULER_INSTALLATION_EVENT_NAME,
527
476
  body: JSON.stringify(payload),
528
477
  });
529
478
  }
@@ -549,7 +498,7 @@ class GCFBootstrapper {
549
498
  var _a, _b;
550
499
  if (body.repo) {
551
500
  // Job was scheduled for a single repository:
552
- await this.scheduledToTask(body.repo, id, body, SCHEDULER_REPOSITORY_EVENT_NAME);
501
+ await this.scheduledToTask(body.repo, id, body, custom_events_1.SCHEDULER_REPOSITORY_EVENT_NAME);
553
502
  }
554
503
  else if (body.installation) {
555
504
  const generator = this.eachInstalledRepository(body.installation.id, wrapConfig);
@@ -559,7 +508,7 @@ class GCFBootstrapper {
559
508
  if (repo.archived === true || repo.disabled === true) {
560
509
  continue;
561
510
  }
562
- promises.push(this.scheduledToTask(repo.full_name, id, body, SCHEDULER_REPOSITORY_EVENT_NAME));
511
+ promises.push(this.scheduledToTask(repo.full_name, id, body, custom_events_1.SCHEDULER_REPOSITORY_EVENT_NAME));
563
512
  if (promises.length >= batchSize) {
564
513
  await Promise.all(promises);
565
514
  promises.splice(0, promises.length);
@@ -601,7 +550,7 @@ class GCFBootstrapper {
601
550
  if (repo.archived === true || repo.disabled === true) {
602
551
  continue;
603
552
  }
604
- promises.push(this.scheduledToTask(repo.full_name, id, payload, SCHEDULER_REPOSITORY_EVENT_NAME));
553
+ promises.push(this.scheduledToTask(repo.full_name, id, payload, custom_events_1.SCHEDULER_REPOSITORY_EVENT_NAME));
605
554
  if (promises.length >= batchSize) {
606
555
  await Promise.all(promises);
607
556
  promises.splice(0, promises.length);
@@ -716,7 +665,7 @@ class GCFBootstrapper {
716
665
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
717
666
  });
718
667
  const authClient = await auth.getClient();
719
- const client = await run_1.run({
668
+ const client = await (0, run_1.run)({
720
669
  version: 'v1',
721
670
  auth: authClient,
722
671
  });
@@ -765,6 +714,7 @@ class GCFBootstrapper {
765
714
  await this.cloudTasksClient.createTask({
766
715
  parent: queuePath,
767
716
  task: {
717
+ dispatchDeadline: { seconds: 60 * 30 },
768
718
  httpRequest: {
769
719
  httpMethod: 'POST',
770
720
  headers: {
@@ -813,13 +763,13 @@ class GCFBootstrapper {
813
763
  */
814
764
  async maybeWriteBodyToTmp(body) {
815
765
  if (this.payloadBucket) {
816
- const tmp = `${Date.now()}-${uuid_1.v4()}.txt`;
766
+ const tmp = `${Date.now()}-${(0, uuid_1.v4)()}.txt`;
817
767
  const bucket = this.storage.bucket(this.payloadBucket);
818
768
  const writeable = bucket.file(tmp).createWriteStream({
819
769
  validation: !RUNNING_IN_TEST,
820
770
  });
821
771
  exports.logger.info(`uploading payload to ${tmp}`);
822
- into_stream_1.default(body).pipe(writeable);
772
+ (0, into_stream_1.default)(body).pipe(writeable);
823
773
  await new Promise((resolve, reject) => {
824
774
  writeable.on('error', reject);
825
775
  writeable.on('finish', resolve);
@@ -849,7 +799,7 @@ class GCFBootstrapper {
849
799
  validation: !RUNNING_IN_TEST,
850
800
  });
851
801
  try {
852
- const content = await get_stream_1.default(readable);
802
+ const content = await (0, get_stream_1.default)(readable);
853
803
  exports.logger.info(`downloaded payload from ${payload.tmpUrl}`);
854
804
  return JSON.parse(content);
855
805
  }
@@ -868,4 +818,21 @@ class GCFBootstrapper {
868
818
  }
869
819
  }
870
820
  exports.GCFBootstrapper = GCFBootstrapper;
821
+ const loggerCache = new WeakMap();
822
+ // Helper to inject the request logger
823
+ function setContextLogger(payload, logger) {
824
+ loggerCache.set(payload, logger);
825
+ }
826
+ // Helper to extract the request logger from the request payload.
827
+ // If gcf-utils wrapper did not provide a logger, fall back to the
828
+ // default logger.
829
+ function getContextLogger(context) {
830
+ const requestLogger = loggerCache.get(context === null || context === void 0 ? void 0 : context.payload);
831
+ if (!requestLogger) {
832
+ exports.logger.warn('Failed to find a context logger');
833
+ return exports.logger;
834
+ }
835
+ return requestLogger;
836
+ }
837
+ exports.getContextLogger = getContextLogger;
871
838
  //# sourceMappingURL=gcf-utils.js.map