0
# Google Cloud Functions Integration
1
2
Complete Google Cloud Functions support with HTTP function wrapping, event function handling, cloud event processing, and performance tracing capabilities specifically designed for the GCP serverless environment.
3
4
## Capabilities
5
6
### Initialization
7
8
Initialize the Sentry GCP Functions SDK with platform-specific configurations and integrations.
9
10
```typescript { .api }
11
/**
12
* Initialize Sentry for Google Cloud Functions
13
* @param options - Configuration options for the SDK
14
*/
15
function init(options?: NodeOptions): void;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { GCPFunction } from "@sentry/serverless";
22
23
// Basic initialization
24
GCPFunction.init({
25
dsn: "your-dsn-here",
26
});
27
28
// With performance tracing
29
GCPFunction.init({
30
dsn: "your-dsn-here",
31
tracesSampleRate: 1.0,
32
environment: "production",
33
});
34
```
35
36
### HTTP Functions
37
38
Wrap HTTP functions (Express-style request/response handlers) with error capture and performance tracing.
39
40
```typescript { .api }
41
/**
42
* Wraps an HTTP function handler adding error capture and tracing capabilities
43
* @param fn - HTTP handler function
44
* @param wrapOptions - Optional configuration for wrapper behavior
45
* @returns Wrapped HTTP function with Sentry capabilities
46
*/
47
function wrapHttpFunction(
48
fn: HttpFunction,
49
wrapOptions?: Partial<HttpFunctionWrapperOptions>
50
): HttpFunction;
51
52
interface HttpFunction {
53
(req: Request, res: Response): any;
54
}
55
56
interface HttpFunctionWrapperOptions extends GCPWrapperOptions {
57
/** Configuration for adding request data to events */
58
addRequestDataToEventOptions?: AddRequestDataToEventOptions;
59
/** @deprecated Use addRequestDataToEventOptions instead */
60
parseRequestOptions?: ParseRequestOptions;
61
}
62
63
interface AddRequestDataToEventOptions {
64
include?: {
65
request?: ('cookies' | 'data' | 'headers' | 'method' | 'query_string' | 'url')[];
66
user?: ('id' | 'username' | 'email' | 'ip_address')[];
67
};
68
}
69
70
interface GCPWrapperOptions {
71
/** Timeout for flushing events before function terminates (default: 2000ms) */
72
flushTimeout: number;
73
}
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { GCPFunction } from "@sentry/serverless";
80
81
// Basic HTTP function wrapping
82
exports.helloHttp = GCPFunction.wrapHttpFunction((req, res) => {
83
res.send("Hello World!");
84
});
85
86
// With request data capturing
87
exports.apiHandler = GCPFunction.wrapHttpFunction((req, res) => {
88
const { name } = req.body;
89
res.json({ message: `Hello ${name}!` });
90
}, {
91
addRequestDataToEventOptions: {
92
include: {
93
request: ['headers', 'method', 'url'],
94
user: ['id', 'email']
95
}
96
}
97
});
98
99
// Error handling example
100
exports.errorHandler = GCPFunction.wrapHttpFunction((req, res) => {
101
if (!req.body.data) {
102
throw new Error("Missing data parameter");
103
}
104
res.json({ success: true });
105
});
106
```
107
108
### Event Functions
109
110
Wrap background event functions with error capture and performance tracing.
111
112
```typescript { .api }
113
/**
114
* Wraps an event function handler adding error capture and tracing capabilities
115
* @param fn - Event handler function (with or without callback)
116
* @param wrapOptions - Optional configuration for wrapper behavior
117
* @returns Wrapped event function with Sentry capabilities
118
*/
119
function wrapEventFunction(
120
fn: EventFunction | EventFunctionWithCallback,
121
wrapOptions?: Partial<EventFunctionWrapperOptions>
122
): EventFunctionWithCallback;
123
124
interface EventFunction {
125
(data: Record<string, any>, context: Context): any;
126
}
127
128
interface EventFunctionWithCallback {
129
(data: Record<string, any>, context: Context, callback: Function): any;
130
}
131
132
type EventFunctionWrapperOptions = GCPWrapperOptions;
133
```
134
135
**Usage Examples:**
136
137
```typescript
138
import { GCPFunction } from "@sentry/serverless";
139
140
// Basic event function (async)
141
exports.processEvent = GCPFunction.wrapEventFunction(async (data, context) => {
142
console.log(`Processing event: ${context.eventType}`);
143
await processEventData(data);
144
});
145
146
// Event function with callback
147
exports.processEventCallback = GCPFunction.wrapEventFunction((data, context, callback) => {
148
console.log(`Event ID: ${context.eventId}`);
149
processEventData(data)
150
.then(() => callback())
151
.catch(callback);
152
});
153
154
// Pub/Sub message processing
155
exports.processPubSubMessage = GCPFunction.wrapEventFunction((message, context) => {
156
const data = message.data ? Buffer.from(message.data, 'base64').toString() : 'No data';
157
console.log(`Received message: ${data}`);
158
159
// Process the message
160
return processMessage(JSON.parse(data));
161
});
162
```
163
164
### Cloud Event Functions
165
166
Wrap Cloud Event functions (CloudEvents specification) with error capture and performance tracing.
167
168
```typescript { .api }
169
/**
170
* Wraps a cloud event function handler adding error capture and tracing capabilities
171
* @param fn - Cloud event handler function (with or without callback)
172
* @param wrapOptions - Optional configuration for wrapper behavior
173
* @returns Wrapped cloud event function with Sentry capabilities
174
*/
175
function wrapCloudEventFunction(
176
fn: CloudEventFunction | CloudEventFunctionWithCallback,
177
wrapOptions?: Partial<CloudEventFunctionWrapperOptions>
178
): CloudEventFunctionWithCallback;
179
180
interface CloudEventFunction {
181
(cloudevent: CloudEventsContext): any;
182
}
183
184
interface CloudEventFunctionWithCallback {
185
(cloudevent: CloudEventsContext, callback: Function): any;
186
}
187
188
type CloudEventFunctionWrapperOptions = GCPWrapperOptions;
189
```
190
191
**Usage Examples:**
192
193
```typescript
194
import { GCPFunction } from "@sentry/serverless";
195
196
// Basic cloud event function (async)
197
exports.handleCloudEvent = GCPFunction.wrapCloudEventFunction(async (cloudEvent) => {
198
console.log(`Event type: ${cloudEvent.type}`);
199
console.log(`Event source: ${cloudEvent.source}`);
200
201
// Process the cloud event
202
await processCloudEvent(cloudEvent);
203
});
204
205
// Cloud event function with callback
206
exports.handleCloudEventCallback = GCPFunction.wrapCloudEventFunction((cloudEvent, callback) => {
207
console.log(`Event ID: ${cloudEvent.id}`);
208
console.log(`Event time: ${cloudEvent.time}`);
209
210
processCloudEvent(cloudEvent)
211
.then(() => callback())
212
.catch(callback);
213
});
214
215
// Storage event processing
216
exports.processStorageEvent = GCPFunction.wrapCloudEventFunction((cloudEvent) => {
217
if (cloudEvent.type === 'google.cloud.storage.object.v1.finalized') {
218
const fileName = cloudEvent.data?.name;
219
console.log(`File uploaded: ${fileName}`);
220
return processUploadedFile(fileName);
221
}
222
});
223
```
224
225
### Default Integrations
226
227
Get the default integrations configured for Google Cloud Functions environment.
228
229
```typescript { .api }
230
/**
231
* Get the default integrations for the GCP SDK
232
* @param options - SDK options to configure integrations
233
* @returns Array of default integrations including Google Cloud integrations
234
*/
235
function getDefaultIntegrations(options: Options): Integration[];
236
237
/** @deprecated Use getDefaultIntegrations(options) instead */
238
const defaultIntegrations: Integration[];
239
```
240
241
**Usage Examples:**
242
243
```typescript
244
import { GCPFunction } from "@sentry/serverless";
245
246
// Get default integrations
247
const integrations = GCPFunction.getDefaultIntegrations({
248
// configuration options
249
});
250
251
// Use in custom initialization
252
GCPFunction.init({
253
dsn: "your-dsn-here",
254
integrations: [
255
...GCPFunction.getDefaultIntegrations({}),
256
// Add additional custom integrations
257
]
258
});
259
```
260
261
## Context Types
262
263
```typescript { .api }
264
interface CloudFunctionsContext {
265
/** Unique event identifier */
266
eventId?: string;
267
/** Event timestamp in ISO format */
268
timestamp?: string;
269
/** Type of the triggering event */
270
eventType?: string;
271
/** Resource that triggered the event */
272
resource?: string;
273
}
274
275
interface CloudEventsContext {
276
[key: string]: any;
277
/** Event type (e.g., 'com.example.string.sent') */
278
type?: string;
279
/** CloudEvents specification version */
280
specversion?: string;
281
/** Event producer identifier */
282
source?: string;
283
/** Unique event identifier */
284
id?: string;
285
/** Event timestamp */
286
time?: string;
287
/** Schema URL for the event data */
288
schemaurl?: string;
289
/** Content type of the event data */
290
contenttype?: string;
291
}
292
293
type Context = CloudFunctionsContext | CloudEventsContext;
294
295
// Express types re-exported for convenience
296
type Request = import('express').Request;
297
type Response = import('express').Response;
298
```
299
300
## Context Enhancement
301
302
The GCP Functions integration automatically enhances Sentry scopes with function-specific context:
303
304
### GCP Function Context
305
306
```typescript
307
// Automatically added to scope for event and cloud event functions
308
{
309
"gcp.function.context": {
310
"eventId": "1234567890",
311
"timestamp": "2023-01-01T12:00:00.000Z",
312
"eventType": "google.pubsub.topic.publish",
313
"resource": "projects/my-project/topics/my-topic"
314
}
315
}
316
```
317
318
### Request Context
319
320
For HTTP functions, request data is automatically captured based on configuration:
321
322
```typescript
323
// Automatically added for HTTP functions
324
{
325
"request": {
326
"method": "POST",
327
"url": "https://us-central1-project.cloudfunctions.net/my-function",
328
"headers": {
329
"content-type": "application/json",
330
"user-agent": "Mozilla/5.0..."
331
}
332
}
333
}
334
```
335
336
## Error Handling
337
338
The GCP Functions integration provides comprehensive error handling:
339
340
- **Automatic Exception Capture**: All uncaught exceptions are automatically captured
341
- **Promise Rejection Handling**: Unhandled promise rejections are captured
342
- **Context Preservation**: Function context is preserved in error reports
343
- **Event Flushing**: Ensures events are sent before function terminates
344
- **Callback Error Handling**: Properly handles both callback and promise-based patterns
345
346
## Performance Tracing
347
348
Automatic performance tracing capabilities:
349
350
- **Function Tracing**: Each function invocation is traced as a transaction
351
- **HTTP Request Tracing**: HTTP functions automatically trace the request/response cycle
352
- **Event Processing Tracing**: Event and cloud event functions trace the event processing
353
- **Distributed Tracing**: Continues traces from incoming requests and events
354
- **Custom Spans**: Add custom spans within your function logic
355
356
```typescript
357
import { GCPFunction, startSpan } from "@sentry/serverless";
358
359
exports.complexHandler = GCPFunction.wrapHttpFunction((req, res) => {
360
return startSpan({ name: "process-request", op: "function" }, async (span) => {
361
span.setTag("request-type", req.headers['content-type']);
362
363
const result = await processRequest(req.body);
364
res.json(result);
365
});
366
});
367
```
368
369
## Integration with Google Cloud Services
370
371
The SDK includes automatic integrations for Google Cloud services:
372
373
- **Google Cloud HTTP Integration**: Traces HTTP calls to Google Cloud APIs
374
- **Google Cloud gRPC Integration**: Traces gRPC calls to Google Cloud services
375
- **Optional Loading**: Integrations are marked as optional and won't fail if dependencies are missing
376
377
These integrations automatically instrument Google Cloud client libraries to provide visibility into service calls made from your functions.