@codecompose/typed-pubsub

中文文档
1.2.1发布于 2026/03/15MITTypeScriptES Module构建来源已验证近 30 天下载 3345

A type-safe pub/sub abstraction for Google Cloud and Firebase

原始使用文档
文档目录12 节
  1. Features
  2. Installation
  3. Peer Dependencies
  4. Quick Start
  5. Usage Examples
  6. Basic Setup
  7. Preventing Duplicate Processing with Event Marking
  8. Handling Time-Sensitive Events
  9. API Reference
  10. createTypedPubsub(options)
  11. Key Handler Options
  12. Limitations and Alternatives

typed-pubsub

A type-safe PubSub abstraction for Google Cloud and Firebase.

Features

  • Type-safe messaging: Full TypeScript support for publishers and handlers
  • Runtime validation: Schema validation using Zod prevents invalid messages
  • Duplicate prevention: Optional event marking to prevent duplicate processing
  • Stale message handling: Optional time-based dropping of messages
  • Customizable defaults: Configure your own library-wide defaults with per-handler overrides. Out-of-the box you get:
    • Retries enabled with 7-day exponential backoff
    • Scale to maximum of 250 instances per topic (safer than Firebase's default of 3000)
    • 512MB memory allocation per instance

Installation

npm install @codecompose/typed-pubsub

Peer Dependencies

This package has the following peer dependencies:

  • @google-cloud/pubsub
  • firebase-functions
  • zod

Quick Start

  1. Define your message schemas with Zod
  2. Create a PubSub client
  3. Initialize the typed PubSub with your schemas
  4. Create type-safe publishers and handlers
import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { z } from "zod";

// 1. Define your schemas
const schemas = {
  user_created: z.object({
    userId: z.string(),
    email: z.string().email(),
  }),
};

// 2. Create PubSub client
const client = new PubSub();

// 3. Initialize typed PubSub
const pubsub = createTypedPubsub({
  client,
  schemas,
  region: "us-central1",
});

// 4a. Create and use a publisher
await pubsub.createPublisher("user_created")({
  userId: "123",
  email: "[email protected]",
});

// 4b. Create a handler
export const handle_user_created = pubsub.createHandler({
  topic: "user_created",
  handler: async (data) => {
    // data is fully typed based on the schema
    console.log(`New user created: ${data.email}`);
  },
});

Usage Examples

Basic Setup

import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { z } from "zod";

// Define your schemas
const schemas = {
  user_created: z.object({
    userId: z.string(),
    email: z.string().email(),
    createdAt: z.string().datetime(),
  }),
  order_placed: z.object({
    orderId: z.string(),
    userId: z.string(),
    items: z.array(
      z.object({
        productId: z.string(),
        quantity: z.number().int().positive(),
      }),
    ),
    total: z.number().positive(),
  }),
};

// Create typed Pubsub client
const pubsub = createTypedPubsub({
  client: new PubSub(),
  schemas,
  region: "us-central1",
});

// Publish a message
await pubsub.createPublisher("user_created")({
  userId: "123",
  email: "[email protected]",
  createdAt: new Date().toISOString(),
});

// Create a handler
export const handle_order_placed = pubsub.createHandler({
  topic: "order_placed",
  handler: async (data) => {
    // data is fully typed based on the schema
    console.log(`Processing order ${data.orderId} for user ${data.userId}`);
    // Process the order...
  },
  options: {
    memory: "1GiB",
    timeoutSeconds: 60,
    markEvent: true, // Never process this event more than once
  },
});

Note: The examples use snake_case for topic names (like "user_created") and exported cloud functions (like handle_order_placed). This is because casing is currently ignored in Cloud Run function names in GCP, so using snake_case is preferred for consistency.

Preventing Duplicate Processing with Event Marking

PubSub has at-least-once delivery semantics, meaning messages might occasionally be delivered more than once. For operations that must be executed exactly once (like payment processing or user credit awards), this library provides event marking.

The markEvent option uses your provided storage (like Redis) to track which event IDs have already been processed, ensuring each event is handled exactly once despite potential redeliveries.

import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { redis } from "./redis-client";

// Create event marking functions
const eventMarkingFunctions = {
  isEventProcessed: async (eventId) => {
    return Boolean(await redis.get(`event:${eventId}`));
  },
  markEventAsProcessed: async (eventId) => {
    await redis.set(`event:${eventId}`, "1", "EX", 86400); // 24 hours TTL
  },
};

// Create typed Pubsub client with event marking
const pubsub = createTypedPubsub({
  client: new PubSub(),
  schemas,
  region: "us-central1",
  options: {
    eventMarkingFunctions,
    defaultHandlerOptions: {
      markEvent: true, // Enable for all handlers by default
      vpcConnector: "redis-connector", // If Redis is in a VPC
    },
  },
});

Handling Time-Sensitive Events

For time-sensitive operations, you may want to discard messages that are too old. The retryMaxAgeMinutes option automatically drops events that exceed the specified age, preventing the processing of stale data.

// Configure time-based message dropping in the handler
export const handle_time_sensitive_events = pubsub.createHandler({
  topic: "time_sensitive_events",
  handler: async (data) => {
    // Process time-sensitive event
  },
  options: {
    retryMaxAgeMinutes: 60, // Only process events less than 1 hour old
  },
});

API Reference

createTypedPubsub(options)

Creates a type-safe Pubsub client for handling messages with schema validation.

Parameters

  • client: Google Cloud Pubsub client instance
  • schemas: Record of Zod schemas for each topic
  • region: GCP region for the Pubsub functions
  • options: (Optional) Configuration options
    • eventMarkingFunctions: (Optional) Functions for tracking processed events
    • defaultHandlerOptions: (Optional) Default options for all handlers
  • onMessagePublished: (Optional) Firebase message published handler, defaults to firebase implementation

Key Handler Options

OptionDescriptionDefault
retryEnable/disable automatic retriestrue
retryMaxAgeMinutesMaximum event age before droppingundefined (no limit)
memoryMemory allocation"512MiB"
markEventEnable duplicate preventionfalse
timeoutSecondsFunction timeout in seconds20
maxInstancesMaximum concurrent instances250
vpcConnectorName of the VPC connectorundefined

Important note about retry behavior: While you can enable/disable retries and set maximum age for retried events, the actual retry timing is controlled by the PubSub subscription's ACK deadline, not by the timeoutSeconds setting. The timeout will shut down the server process, but the event will only be retried after the ACK deadline expires, which cannot be configured through this library.

Limitations and Alternatives

While this library provides excellent type safety and schema validation for PubSub messages, there are some limitations inherent to PubSub:

  • Limited control over retry timing (controlled by subscription ACK deadline)
  • No built-in support for manually triggered retries
  • No fine-grained error handling for different failure scenarios

If your use case requires more advanced features like controlled retry intervals, manual retry triggering, or long-running background processes, consider using a dedicated task queue system. The typed-tasks library provides similar type-safety guarantees with more control over task execution.

版本与发布记录

@codecompose/typed-pubsub 共发布 6 个版本,首次发布于 2025/04/08;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.2.1latest2026/03/157 个月前
1.2.02025/12/1710 个月前
1.1.12025/09/141.2 年前
1.1.02025/09/081.2 年前
1.0.12025/04/081.6 年前
1.0.02025/04/081.6 年前

关于 @codecompose/typed-pubsub 的常见问题

@codecompose/typed-pubsub 是什么?

A type-safe pub/sub abstraction for Google Cloud and Firebase

如何安装 @codecompose/typed-pubsub?

在项目目录运行 npm install @codecompose/typed-pubsub,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@google-cloud/pubsub(>=4)、firebase-functions(>=6)、zod(>=3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@codecompose/typed-pubsub 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@codecompose/typed-pubsub 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@codecompose/typed-pubsub 可以商用吗?

@codecompose/typed-pubsub 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@codecompose/typed-pubsub 的下载量有多少?

根据 npm 官方下载统计,@codecompose/typed-pubsub 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,345 次,日均约 112 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codecompose/typed-pubsub 还在维护吗?

最新版本 1.2.1 发布于 2026/03/15(7 个月前);至今共发布 6 个版本,其中过去 12 个月发布了 2 个;首次发布于 2025/04/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。