npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@biblioteksentralen/cloud-run-core

v0.8.9

Published

Core package for NodeJS services using Cloud Run

Downloads

1,439

Readme

Build &
test NPM

Core package for Node.JS Cloud Run services

This package contains some core functionality for Node.js services running on Google Cloud Run, such as logging and error handling.

Development

▶ pnpm install
▶ pnpm test

Publishing the package:

▶ pnpm version patch  # or minor / major
▶ pnpm publish

Usage

▶ npm install @biblioteksentralen/cloud-run-core

To create a new service for Cloud Run:

// src/start.ts
import { createService, asyncRoute } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";

const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });

service.router.get("/", asyncRoute(async (req, res) => {
  req.log.info(`Hello log!`);
  // ...
}));

service.start();

This configures the service with a logging middleware that configures Pino for Cloud Logging and includes trace context. The logger is added to the Express Request context, so it can be used in all request handlers:

// src/endpoints/funRequestHandler.ts
import { Request, Response } from "@biblioteksentralen/cloud-run-core";

export async function funRequestHandler(req: Request, res: Response): Promise<void> {
  req.log.info(`Hello log!`);
}
// src/start.ts
// ...
import { asyncRoute } from "@biblioteksentralen/cloud-run-core";
import { funRequestHandler } from "./endpoints/funRequestHandler.js";

// ...
service.router.get("/", asyncRoute(funRequestHandler));

Note: All async route handlers must be wrapped with asyncRoute due to the unfortunate fact that Express 4 is callback-based and Express 5 is still not released. Otherwise, the error handler and any post-processing middleware will not work correctly.

Logging levels

By default, the logger only processes log messages from info and higher levels, but the minimum logging level can be adjusted by setting the LOG_LEVEL environment variable.

As a general rule, debug logging should not be enabled in production environments. It should be reserved for things you’re tracking during development and testing, or when problems occur that require more detail. Set LOG_LEVEL=debug to enable debug logging.

Tip: Format logs with pino-pretty in development

When developing, pino-pretty can be used to format logs in a more human readable way. Install pino-pretty as a dev dependency:

pnpm add pino-pretty

and run your scripts with PINO_PRETTY=true:

{
  "scripts": {
    "dev": "PINO_PRETTY=true ts-node ./src/start.ts"
  }
}

Routing

Use createRouter() to create modular, mountable route handlers (uses express.Router()):

// src/start.ts
import { createService, createRouter, asyncRoute } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";

const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });

const adminRouter = createRouter()

adminRouter.get("/", asyncRoute(async (req, res) => {
  req.log.info(`Hello admin`);
  // ...
}));

service.router.use("/admin", adminRouter);

service.start();

Error handling

This package provides an error handling middleware that is automatically attached to the service when you start the service using service.start(), inspired by How to Handle Errors in Express with TypeScript.

Important: Express 4 doesn't support async route handlers well. Handlers must be wrapped with asyncRoute to avoid thrown errors to be lost.

AppError is a base class to be used for all known application errors (that is, all errors we throw ourselves).

// src/endpoints/funRequestHandler.ts
import { AppError, Request, Response } from "@biblioteksentralen/cloud-run-core";

export async function funRequestHandler(req: Request, res: Response) {
  // ...
  throw new AppError('🔥 Databasen har brent ned');
  // ...
}

As long as errors are thrown before writing the response has started, a JSON error response is produced on the form:

{ "error": "🔥 Databasen har brent ned" }

By default, errors based on AppError are considered operational and displayed in responses. If an error should not be displayed, set isOperational: false when constructing the error:

throw new AppError('🔥 Databasen har brent ned', { isOperational: false });

This results in a generic error response (but the original error is still logged):

{ "error": "Internal server error" }

A generic error response will also be shown for any unknown error, that is, any error that is not based on AppError) is thrown. All errors, both known and unknown, are logged.

By default, errors use status code 500. To use another status code:

throw new AppError('💤 Too early', { httpStatus: 425 });

The package also provides a few subclasses of AppError for common use cases, such as ClientRequestError (yields 400 response) and Unauthorized (yields 401 response).

throw new Unauthorized('🔒 Unauthorized');

Sentry integration

Set sentry.dsn when creating the client to enable Sentry error reporting and telemetry.

import { createService } from "@biblioteksentralen/cloud-run-core";

const service = createService("fun-service", { 
  sentry: {
    dsn: process.env.SENTRY_DSN,
    tracesSampleRate: 0.1,
    environment: process.env.NODE_ENV, // or similar
    ...
  },
  ...
});

Request validation with parseRequest

The parseRequest parses a request body using a Zod schema. If the input is invalid, the request will be logged together with the errors, and an "invalid request" is returned to the sender.

import { Request, Response, parseRequest } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";

export async function funRequestHandler(req: Request, res: Response) {
  const { isbn13 } = parseRequest(req.body, z.object({
    "isbn13": z.string().regex(/^978[0-9]{10}$/),
  }));

  res.json({ status: "ok", isbn13 });
}

Graceful shutdown

The package uses http-terminator to gracefully terminate the HTTP server when the process exists (on SIGTERM). An event, shutdown, is emitted after the server has shut down. You can listen to this if you want to do additional cleanup, such as closing database connections.

// src/start.ts
import { createService, asyncRoute } from "@biblioteksentralen/cloud-run-core";
import { z } from "zod";

const projectId = z.string().parse(process.env.GCP_PROJECT_ID);
const service = createService("fun-service", { projectId });

service.on("shutdown", async () => {
  await db.close()
});

// ...

service.start();

Pub/Sub helpers

The package provides a helper function to parse and validate Pub/Sub messages delivered through push delivery.

The package is agnostic when it comes to which schema parsing/validation library to use. We like Zod for its usability, and have added support for it in the errorHandler, but it's not very performant (https://moltar.github.io/typescript-runtime-type-benchmarks/), so you might pick something else if performance is important (if you do, remember to throw ClientRequestError when validation fails).

import { z } from "zod";
import {
  parsePubSubMessage,
  Request,
  Response,
} from "@biblioteksentralen/cloud-run-core";

const messageSchema = z.object({
  table: z.string(),
  key: z.number(),
});

app.post("/", async (req: Request, res: Response) => {
  const message = parsePubSubMessage(req, (data) => messageSchema.parse(JSON.parse(data)));
  // ...
});

Peculiarities

  • We include @types/express as a dependency, not a devDependency, because we extend and re-export the Request interface. Initially we kept it under devDependencies, but then all package consumers would have to install the package themselves. Not sure what's considered best practice in cases like this though.

  • @sentry-pakkene kan av og til komme ut av sync med hverandre. De jobber med å redusere mengden pakker for å redusere problemet: https://github.com/getsentry/sentry-javascript/issues/8965#issuecomment-1709923865 Inntil videre kan en prøve å oppdatere alle pakker og se om en klarer å få like versjoner fra pn ls --depth 3 @sentry/types