CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sentry--serverless

Official Sentry SDK for various serverless solutions including AWS Lambda and Google Cloud Functions

Pending
Overview
Eval results
Files

gcp-functions.mddocs/

Google Cloud Functions Integration

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.

Capabilities

Initialization

Initialize the Sentry GCP Functions SDK with platform-specific configurations and integrations.

/**
 * Initialize Sentry for Google Cloud Functions
 * @param options - Configuration options for the SDK
 */
function init(options?: NodeOptions): void;

Usage Examples:

import { GCPFunction } from "@sentry/serverless";

// Basic initialization
GCPFunction.init({
  dsn: "your-dsn-here",
});

// With performance tracing
GCPFunction.init({
  dsn: "your-dsn-here",
  tracesSampleRate: 1.0,
  environment: "production",
});

HTTP Functions

Wrap HTTP functions (Express-style request/response handlers) with error capture and performance tracing.

/**
 * Wraps an HTTP function handler adding error capture and tracing capabilities
 * @param fn - HTTP handler function
 * @param wrapOptions - Optional configuration for wrapper behavior
 * @returns Wrapped HTTP function with Sentry capabilities
 */
function wrapHttpFunction(
  fn: HttpFunction,
  wrapOptions?: Partial<HttpFunctionWrapperOptions>
): HttpFunction;

interface HttpFunction {
  (req: Request, res: Response): any;
}

interface HttpFunctionWrapperOptions extends GCPWrapperOptions {
  /** Configuration for adding request data to events */
  addRequestDataToEventOptions?: AddRequestDataToEventOptions;
  /** @deprecated Use addRequestDataToEventOptions instead */
  parseRequestOptions?: ParseRequestOptions;
}

interface AddRequestDataToEventOptions {
  include?: {
    request?: ('cookies' | 'data' | 'headers' | 'method' | 'query_string' | 'url')[];
    user?: ('id' | 'username' | 'email' | 'ip_address')[];
  };
}

interface GCPWrapperOptions {
  /** Timeout for flushing events before function terminates (default: 2000ms) */
  flushTimeout: number;
}

Usage Examples:

import { GCPFunction } from "@sentry/serverless";

// Basic HTTP function wrapping
exports.helloHttp = GCPFunction.wrapHttpFunction((req, res) => {
  res.send("Hello World!");
});

// With request data capturing
exports.apiHandler = GCPFunction.wrapHttpFunction((req, res) => {
  const { name } = req.body;
  res.json({ message: `Hello ${name}!` });
}, {
  addRequestDataToEventOptions: {
    include: {
      request: ['headers', 'method', 'url'],
      user: ['id', 'email']
    }
  }
});

// Error handling example
exports.errorHandler = GCPFunction.wrapHttpFunction((req, res) => {
  if (!req.body.data) {
    throw new Error("Missing data parameter");
  }
  res.json({ success: true });
});

Event Functions

Wrap background event functions with error capture and performance tracing.

/**
 * Wraps an event function handler adding error capture and tracing capabilities
 * @param fn - Event handler function (with or without callback)
 * @param wrapOptions - Optional configuration for wrapper behavior
 * @returns Wrapped event function with Sentry capabilities
 */
function wrapEventFunction(
  fn: EventFunction | EventFunctionWithCallback,
  wrapOptions?: Partial<EventFunctionWrapperOptions>
): EventFunctionWithCallback;

interface EventFunction {
  (data: Record<string, any>, context: Context): any;
}

interface EventFunctionWithCallback {
  (data: Record<string, any>, context: Context, callback: Function): any;
}

type EventFunctionWrapperOptions = GCPWrapperOptions;

Usage Examples:

import { GCPFunction } from "@sentry/serverless";

// Basic event function (async)
exports.processEvent = GCPFunction.wrapEventFunction(async (data, context) => {
  console.log(`Processing event: ${context.eventType}`);
  await processEventData(data);
});

// Event function with callback
exports.processEventCallback = GCPFunction.wrapEventFunction((data, context, callback) => {
  console.log(`Event ID: ${context.eventId}`);
  processEventData(data)
    .then(() => callback())
    .catch(callback);
});

// Pub/Sub message processing
exports.processPubSubMessage = GCPFunction.wrapEventFunction((message, context) => {
  const data = message.data ? Buffer.from(message.data, 'base64').toString() : 'No data';
  console.log(`Received message: ${data}`);
  
  // Process the message
  return processMessage(JSON.parse(data));
});

Cloud Event Functions

Wrap Cloud Event functions (CloudEvents specification) with error capture and performance tracing.

/**
 * Wraps a cloud event function handler adding error capture and tracing capabilities
 * @param fn - Cloud event handler function (with or without callback)
 * @param wrapOptions - Optional configuration for wrapper behavior
 * @returns Wrapped cloud event function with Sentry capabilities
 */
function wrapCloudEventFunction(
  fn: CloudEventFunction | CloudEventFunctionWithCallback,
  wrapOptions?: Partial<CloudEventFunctionWrapperOptions>
): CloudEventFunctionWithCallback;

interface CloudEventFunction {
  (cloudevent: CloudEventsContext): any;
}

interface CloudEventFunctionWithCallback {
  (cloudevent: CloudEventsContext, callback: Function): any;
}

type CloudEventFunctionWrapperOptions = GCPWrapperOptions;

Usage Examples:

import { GCPFunction } from "@sentry/serverless";

// Basic cloud event function (async)
exports.handleCloudEvent = GCPFunction.wrapCloudEventFunction(async (cloudEvent) => {
  console.log(`Event type: ${cloudEvent.type}`);
  console.log(`Event source: ${cloudEvent.source}`);
  
  // Process the cloud event
  await processCloudEvent(cloudEvent);
});

// Cloud event function with callback
exports.handleCloudEventCallback = GCPFunction.wrapCloudEventFunction((cloudEvent, callback) => {
  console.log(`Event ID: ${cloudEvent.id}`);
  console.log(`Event time: ${cloudEvent.time}`);
  
  processCloudEvent(cloudEvent)
    .then(() => callback())
    .catch(callback);
});

// Storage event processing
exports.processStorageEvent = GCPFunction.wrapCloudEventFunction((cloudEvent) => {
  if (cloudEvent.type === 'google.cloud.storage.object.v1.finalized') {
    const fileName = cloudEvent.data?.name;
    console.log(`File uploaded: ${fileName}`);
    return processUploadedFile(fileName);
  }
});

Default Integrations

Get the default integrations configured for Google Cloud Functions environment.

/**
 * Get the default integrations for the GCP SDK
 * @param options - SDK options to configure integrations
 * @returns Array of default integrations including Google Cloud integrations
 */
function getDefaultIntegrations(options: Options): Integration[];

/** @deprecated Use getDefaultIntegrations(options) instead */
const defaultIntegrations: Integration[];

Usage Examples:

import { GCPFunction } from "@sentry/serverless";

// Get default integrations
const integrations = GCPFunction.getDefaultIntegrations({
  // configuration options
});

// Use in custom initialization
GCPFunction.init({
  dsn: "your-dsn-here",
  integrations: [
    ...GCPFunction.getDefaultIntegrations({}),
    // Add additional custom integrations
  ]
});

Context Types

interface CloudFunctionsContext {
  /** Unique event identifier */
  eventId?: string;
  /** Event timestamp in ISO format */
  timestamp?: string;
  /** Type of the triggering event */
  eventType?: string;
  /** Resource that triggered the event */
  resource?: string;
}

interface CloudEventsContext {
  [key: string]: any;
  /** Event type (e.g., 'com.example.string.sent') */
  type?: string;
  /** CloudEvents specification version */
  specversion?: string;
  /** Event producer identifier */
  source?: string;
  /** Unique event identifier */
  id?: string;
  /** Event timestamp */
  time?: string;
  /** Schema URL for the event data */
  schemaurl?: string;
  /** Content type of the event data */
  contenttype?: string;
}

type Context = CloudFunctionsContext | CloudEventsContext;

// Express types re-exported for convenience
type Request = import('express').Request;
type Response = import('express').Response;

Context Enhancement

The GCP Functions integration automatically enhances Sentry scopes with function-specific context:

GCP Function Context

// Automatically added to scope for event and cloud event functions
{
  "gcp.function.context": {
    "eventId": "1234567890",
    "timestamp": "2023-01-01T12:00:00.000Z",
    "eventType": "google.pubsub.topic.publish",
    "resource": "projects/my-project/topics/my-topic"
  }
}

Request Context

For HTTP functions, request data is automatically captured based on configuration:

// Automatically added for HTTP functions
{
  "request": {
    "method": "POST",
    "url": "https://us-central1-project.cloudfunctions.net/my-function",
    "headers": {
      "content-type": "application/json",
      "user-agent": "Mozilla/5.0..."
    }
  }
}

Error Handling

The GCP Functions integration provides comprehensive error handling:

  • Automatic Exception Capture: All uncaught exceptions are automatically captured
  • Promise Rejection Handling: Unhandled promise rejections are captured
  • Context Preservation: Function context is preserved in error reports
  • Event Flushing: Ensures events are sent before function terminates
  • Callback Error Handling: Properly handles both callback and promise-based patterns

Performance Tracing

Automatic performance tracing capabilities:

  • Function Tracing: Each function invocation is traced as a transaction
  • HTTP Request Tracing: HTTP functions automatically trace the request/response cycle
  • Event Processing Tracing: Event and cloud event functions trace the event processing
  • Distributed Tracing: Continues traces from incoming requests and events
  • Custom Spans: Add custom spans within your function logic
import { GCPFunction, startSpan } from "@sentry/serverless";

exports.complexHandler = GCPFunction.wrapHttpFunction((req, res) => {
  return startSpan({ name: "process-request", op: "function" }, async (span) => {
    span.setTag("request-type", req.headers['content-type']);
    
    const result = await processRequest(req.body);
    res.json(result);
  });
});

Integration with Google Cloud Services

The SDK includes automatic integrations for Google Cloud services:

  • Google Cloud HTTP Integration: Traces HTTP calls to Google Cloud APIs
  • Google Cloud gRPC Integration: Traces gRPC calls to Google Cloud services
  • Optional Loading: Integrations are marked as optional and won't fail if dependencies are missing

These integrations automatically instrument Google Cloud client libraries to provide visibility into service calls made from your functions.

Install with Tessl CLI

npx tessl i tessl/npm-sentry--serverless

docs

aws-lambda.md

aws-services.md

core-sentry.md

gcp-functions.md

index.md

tile.json