[![Build &
test](https://github.com/biblioteksentralen/cloud-run-core/actions/workflows/ci.yml/badge.svg)](https://github.com/biblioteksentralen/cloud-run-core/actions/workflows/ci.yml)
![NPM](https://img.shields.io/npm/v/%40biblioteksentralen%2Fcloud-run-core)

# Core package for GCP Cloud Run

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

- [Development](#development)
- [Install](#install)
- [Create a HTTP service](#create-a-http-service)
- [Logging](#logging)
  - [Logging in HTTP services](#logging-in-http-services)
  - [Logging in scripts / GCP Cloud Run Jobs](#logging-in-scripts--gcp-cloud-run-jobs)
  - [`LOG_LEVEL` -  Control minimum log level](#log_level----control-minimum-log-level)
- [Routing](#routing)
- [Error handling](#error-handling)
- [Sentry integration](#sentry-integration)
- [Graceful shutdown](#graceful-shutdown)
- [Pub/Sub helpers](#pubsub-helpers)
- [Detecting Cloud Run environment](#detecting-cloud-run-environment)
- [Peculiarities](#peculiarities)

## Development

```shell
▶ pnpm install
▶ pnpm test
```

Publishing the package:

```shell
▶ pn changeset  # create a new changeset
▶ pn changeset version  # updates version number and changelog 
▶ git commit -m "publish vX.X.X"
▶ pn changeset publish
▶ git push --follow-tags
```

## Install

```shell
▶ npm install @biblioteksentralen/cloud-run-core
```

## Create a HTTP service

To create an Express-based HTTP service:

```ts
// src/start.ts
import { createService } 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("/", async (req, res) => {
  req.log.info(`Hello log!`);
  // ...
});

service.start();
```

## Logging

### Logging in HTTP services

The HTTP service comes pre-configured with a logging middleware that sets up
[Pino](https://github.com/pinojs/pino) to structure logs for [Google Cloud
Logging](https://cloud.google.com/logging/docs/overview) with [trace
context](https://cloud.google.com/trace/docs/trace-log-integration). The logger is added to the
Express Request context, so it can be used in all request handlers:

```ts
// 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!`);
}
```

```ts
// src/start.ts
// ...
import { funRequestHandler } from "./endpoints/funRequestHandler.js";

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

### Logging in scripts / GCP Cloud Run Jobs

In scripts / GCP Cloud Run Jobs:

```ts
import { logger } from "@biblioteksentralen/cloud-run-core"

logger.info({ someProperty: "someValue" }, "Hello world")
```

The logger is configured so it formats logs as JSON structured for GCP Cloud Logging when running in
GCP, or when output is piped to another process (no TTY), and with pino-pretty otherwise.

To manually disable pino-pretty, set the environment variable `PINO_PRETTY=false`.

### `LOG_LEVEL` -  Control minimum log level

The environment variable `LOG_LEVEL` can be used to control the minimum log level.
Defaults to `debug`.

## Routing

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

```ts
// src/start.ts
import { createService, createRouter } 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("/", 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](https://www.codeconcisely.com/posts/how-to-handle-errors-in-express-with-typescript/)*.

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

```ts
// 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:

```json
{ "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:

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

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

```json
{ "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:

```ts
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).

```ts
throw new Unauthorized('🔒 Unauthorized');
```

## Sentry integration

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

```ts
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
    ...
  },
  ...
});
```

## Graceful shutdown

The package uses [http-terminator](https://github.com/gajus/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.

```ts
// src/start.ts
import { createService } 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](https://cloud.google.com/pubsub/docs/push).

The package is agnostic when it comes to which schema parsing/validation library
to use, but we recommend using Zod.

```ts
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);
  const data = messageSchema.parse(JSON.parse(message.data));
  // ...
});
```

## Detecting Cloud Run environment

```ts
import { isCloudRunEnvironment } from "@biblioteksentralen/cloud-run-core";

isCloudRunEnvironment()
```

will return true if running as a Cloud Run Service or Job.

## 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`
