Skip to content

AI-native design editor. Open-source Figma alternative.

feat(cloud): report server errors to PostHog error tracking when configured (#1730)

Danila Poyarkovab914f8129b9
diff --git a/bun.lock b/bun.lock
index 6587320dc..efca0bde7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -251,6 +251,7 @@
"kysely": "^0.29.6",
"lib0": "^0.2.117",
"nodemailer": "^9.0.5",
+ "posthog-node": "5.56.0",
"smol-toml": "^1.8.0",
"ufo": "^1.6.4",
"valibot": "^1.5.0",
@@ -4413,6 +4414,8 @@
"postgres-interval": ["[email protected]", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="],
+ "posthog-node": ["[email protected]", "", { "dependencies": { "@posthog/core": "^1.59.0" }, "peerDependencies": { "rxjs": "^7.0.0" }, "optionalPeers": ["rxjs"] }, "sha512-BOCNJfM+ZTivY+qvNpxyUsG2rV4dyGjiz1+j5OcEqSy7YoSKabTZvLyl8h8X+pADgq5TlqpN0UdT+bXQJjs3mQ=="],
+
"pptxgenjs": ["[email protected]", "", { "dependencies": { "@types/node": "^22.8.1", "https": "^1.0.0", "image-size": "^1.2.1", "jszip": "^3.10.1" } }, "sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
diff --git a/changes/1730/added.md b/changes/1730/added.md
new file mode 100644
index 000000000..58e5eac08
--- /dev/null
+++ b/changes/1730/added.md
@@ -0,0 +1 @@
+- Self-hosted Cloud servers can report their errors to PostHog error tracking through an optional `[error_tracking]` table in the deployment configuration; servers without it send nothing.
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.md
index 17f875993..1e35c6751 100644
--- a/packages/cloud/AGENTS.md
+++ b/packages/cloud/AGENTS.md
@@ -8,6 +8,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo
- `src/server` receives its database, object store, auth adapter, and delivery through injection and never imports `pg`, opens listeners, runs migrations, or starts timers; runtimes under `src/runtime/` own those (`src/runtime/node/server.ts`).
- The package is published to npm; a directory imported as `#cloud/<dir>` is listed in `imports` in `package.json`, since the wildcard there names `.ts` files (`bun run check:packages`).
- `@better-auth/core` is pinned to the `better-auth` version though nothing imports it: `@better-auth/passkey` accepts any later core, whose exact `@better-fetch/fetch` differs from its own, and npm then never finishes installing the package (`bun run test:packages`).
+- Errors no route handled, and failures of work a runtime owns, go through `reportCloudError` with the injected `CloudErrorReporter`; only runtimes create one, from the optional `[error_tracking]` table, so a deployment without it sends nothing (`src/runtime/posthog/errors.ts`, `tests/server/errors/handler.test.ts`).
- Runtime code runs on Node 22 and Bun alike: serve HTTP through `@hono/node-server`, not `Bun.serve` or other `Bun.*` APIs (`tsdown.standalone.config.ts` targets `node22`).
## Data and security
diff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.toml
index a1f65fd0d..0654b0df2 100644
--- a/packages/cloud/deploy/openpencil-cloud.example.toml
+++ b/packages/cloud/deploy/openpencil-cloud.example.toml
@@ -108,6 +108,12 @@ transport = "none"
# OPENPENCIL_CLOUD_SERVICE_TOKEN; requires entitlements from the database.
# [internal_api]
+# Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. The host
+# defaults to https://us.i.posthog.com and the project API key to POSTHOG_PROJECT_API_KEY.
+# [error_tracking]
+# provider = "posthog"
+# host = "https://eu.i.posthog.com"
+
[workers.email]
batch_size = 50
interval_ms = 30000
diff --git a/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
index fbba81cab..30b6fcb05 100644
--- a/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
+++ b/packages/cloud/deploy/openpencil/staging/openpencil-cloud.toml
@@ -62,3 +62,8 @@ maximum_participants = 100
[entitlements.ai]
enabled = false
+
+# Server errors go to the OpenPencil PostHog project; the key is the POSTHOG_PROJECT_API_KEY secret.
+[error_tracking]
+provider = "posthog"
+host = "https://eu.i.posthog.com"
diff --git a/packages/cloud/package.json b/packages/cloud/package.json
index 121539282..d2d31098a 100644
--- a/packages/cloud/package.json
+++ b/packages/cloud/package.json
@@ -39,6 +39,7 @@
"#cloud/server/documents": "./src/server/documents/index.ts",
"#cloud/server/documents/versions": "./src/server/documents/versions/index.ts",
"#cloud/server/email": "./src/server/email/index.ts",
+ "#cloud/server/errors": "./src/server/errors/index.ts",
"#cloud/server/internal": "./src/server/internal/index.ts",
"#cloud/server/invitations": "./src/server/invitations/index.ts",
"#cloud/server/objects": "./src/server/objects/index.ts",
@@ -133,6 +134,7 @@
"kysely": "^0.29.6",
"lib0": "^0.2.117",
"nodemailer": "^9.0.5",
+ "posthog-node": "5.56.0",
"smol-toml": "^1.8.0",
"ufo": "^1.6.4",
"valibot": "^1.5.0",
diff --git a/packages/cloud/src/runtime/cloudflare/environment.ts b/packages/cloud/src/runtime/cloudflare/environment.ts
index d18e95090..14c9abab4 100644
--- a/packages/cloud/src/runtime/cloudflare/environment.ts
+++ b/packages/cloud/src/runtime/cloudflare/environment.ts
@@ -1,8 +1,10 @@
+import { createPostHogErrorReporter } from '#cloud/runtime/posthog/errors'
import {
loadAISigningKey,
parseCloudDeploymentTOML,
type AISigningKey,
type CloudEnvironment,
+ type CloudErrorReporter,
type CloudServerConfig
} from '#cloud/server'
@@ -26,6 +28,8 @@ export type CloudflareCloudEnvironment = CloudflareCloudBindings & Record<string
export type PreparedCloudflareCloud = {
config: CloudServerConfig
aiSigningKey: AISigningKey | undefined
+ /** Set when the deployment configures error tracking. */
+ reportError: CloudErrorReporter | undefined
}
/** The Worker's string variables and secrets, with `DATABASE_URL` from Hyperdrive. */
@@ -44,14 +48,24 @@ function configEnvironment(env: CloudflareCloudEnvironment): CloudEnvironment {
*/
export function cloudflareCloudSetup(source: string) {
let prepared: Promise<PreparedCloudflareCloud> | null = null
- return (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {
+ /** Set once an attempt's config parses, so its later setup steps that fail can be reported. */
+ let reportError: CloudErrorReporter | undefined
+ const prepare = (env: CloudflareCloudEnvironment): Promise<PreparedCloudflareCloud> => {
prepared ??= (async () => {
+ // An attempt whose config fails to parse has no project to report to, not an earlier one's.
+ reportError = undefined
const config = parseCloudDeploymentTOML(source, configEnvironment(env))
- return { config, aiSigningKey: await loadAISigningKey(config) }
+ reportError = createPostHogErrorReporter(config, 'cloudflare')
+ return { config, aiSigningKey: await loadAISigningKey(config), reportError }
})().catch((error: unknown) => {
prepared = null
throw error
})
return prepared
}
+ return {
+ prepare,
+ /** The reporter of the latest attempt, once its config parsed, if it configures error tracking. */
+ reporter: () => reportError
+ }
}
diff --git a/packages/cloud/src/runtime/cloudflare/relay.ts b/packages/cloud/src/runtime/cloudflare/relay.ts
index ab196314e..66e793091 100644
--- a/packages/cloud/src/runtime/cloudflare/relay.ts
+++ b/packages/cloud/src/runtime/cloudflare/relay.ts
@@ -5,6 +5,7 @@ import {
createCollaborationStateStore,
createConfiguredCloudPolicy,
relayDocumentLookups,
+ reportCloudError,
type CollaborationRelay,
type RelayConnection
} from '#cloud/server'
@@ -96,7 +97,7 @@ export function createCloudflareRelayObject(
#opened: CollaborationRelay | null = null
#open(documentId: string) {
- this.#relay ??= prepare(this.env).then(({ config }) => {
+ this.#relay ??= prepare(this.env).then(({ config, reportError }) => {
const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
this.#opened = createCollaborationRelay({
authSecret: config.authSecret,
@@ -104,6 +105,8 @@ export function createCloudflareRelayObject(
store: createCollaborationStateStore(database),
maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,
maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,
+ onError: (message, error) =>
+ this.ctx.waitUntil(reportCloudError(reportError, message, error, { source: 'relay' })),
...relayDocumentLookups(
database,
createConfiguredCloudPolicy(config, database),
diff --git a/packages/cloud/src/runtime/cloudflare/worker.ts b/packages/cloud/src/runtime/cloudflare/worker.ts
index 17d0036b9..fd9373585 100644
--- a/packages/cloud/src/runtime/cloudflare/worker.ts
+++ b/packages/cloud/src/runtime/cloudflare/worker.ts
@@ -4,13 +4,17 @@ import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import { createCloudServer } from '#cloud/runtime/site/server'
import {
cleanupPassOptions,
+ cloudErrorHandler,
createCleanupServices,
createCloudApp,
createCloudAuthenticationRuntime,
createConfiguredCloudPolicy,
createInvitationOutbox,
createTransactionalEmailService,
+ reportCloudError,
runCleanup,
+ type CloudErrorReporter,
+ type CloudErrorSource,
type TransactionalEmailService
} from '#cloud/server'
import { Hono } from 'hono'
@@ -30,6 +34,19 @@ function emailTransport({ config }: PreparedCloudflareCloud, env: CloudflareClou
return createCloudflareEmailTransport(env.EMAIL)
}
+/** A reporter whose reports keep the Worker running until they are sent. */
+function keptAlive(
+ reporter: CloudErrorReporter | undefined,
+ context: Pick<ExecutionContext, 'waitUntil'>
+): CloudErrorReporter | undefined {
+ if (!reporter) return undefined
+ return (error, errorContext) => {
+ const reported = reporter(error, errorContext)
+ context.waitUntil(reported)
+ return reported
+ }
+}
+
/**
* What one request or cron run needs. Workers can't share connections between requests, so each
* gets its own database client, closed once its background work settles.
@@ -40,6 +57,9 @@ function cloudServices(
context: Pick<ExecutionContext, 'waitUntil'>
) {
const { config } = prepared
+ const reporter = keptAlive(prepared.reportError, context)
+ const reportError = (message: string, error: unknown, source: CloudErrorSource) =>
+ reportCloudError(reporter, message, error, { source })
const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
const objects = createS3ObjectStore(config)
const transport = emailTransport(prepared, env)
@@ -61,7 +81,7 @@ function cloudServices(
const background: Promise<unknown>[] = []
const runInBackground = (task: Promise<unknown>) => {
background.push(
- task.catch((error: unknown) => console.error('[Cloud] Background work failed:', error))
+ task.catch((error: unknown) => reportError('Background work failed:', error, 'background'))
)
}
const deliver = () =>
@@ -78,27 +98,52 @@ function cloudServices(
transport,
runInBackground,
deliver,
+ reporter,
/** Sends what the request queued and closes the database after everything it started. */
finish() {
context.waitUntil(
Promise.allSettled(background)
.then(() => (enqueued && transport ? deliver() : undefined))
- .catch((error: unknown) => console.error('[Cloud] Sending email failed:', error))
+ .catch((error: unknown) => reportError('Sending email failed:', error, 'email'))
.then(() => database.destroy())
)
}
}
}
+/** Cleanup, and email that failed to send after its request or that a full batch left behind. */
+async function runScheduled(
+ prepared: PreparedCloudflareCloud,
+ env: CloudflareCloudEnvironment,
+ context: Pick<ExecutionContext, 'waitUntil'>
+) {
+ const services = cloudServices(prepared, env, context)
+ const { config, database, objects } = services
+ try {
+ if (config.cleanupEnabled) {
+ const policy = createConfiguredCloudPolicy(config, database)
+ await runCleanup(
+ createCleanupServices(config, database, objects, policy),
+ cleanupPassOptions(config)
+ )
+ }
+ if (services.transport) await services.deliver()
+ } finally {
+ services.finish()
+ }
+}
+
/**
* OpenPencil Cloud on Cloudflare Workers, configured by a deployment TOML. The Worker serves the
* API, the editor, and the portal per request, a Durable Object per document runs its collaboration rooms, and a
* Cron Trigger runs cleanup and retries email.
*/
export function createCloudflareCloud(configSource: string) {
- const prepare = cloudflareCloudSetup(configSource)
+ const { prepare, reporter } = cloudflareCloudSetup(configSource)
const router = new Hono<{ Bindings: CloudflareCloudEnvironment }>()
+ // Setup, relay routing, and the runtime around the app; the app reports its own errors.
+ .onError((error, c) => cloudErrorHandler(keptAlive(reporter(), c.executionCtx))(error, c))
.get(RELAY_PATH, routeToRelay)
.all('*', async (c) => {
const prepared = await prepare(c.env)
@@ -122,11 +167,13 @@ export function createCloudflareCloud(configSource: string) {
onDocumentRestored: (documentId) =>
runInBackground(relayFor(c.env, documentId).startOver(documentId)),
onDocumentVersionsChanged: (documentId) =>
- runInBackground(relayFor(c.env, documentId).announceVersions(documentId))
+ runInBackground(relayFor(c.env, documentId).announceVersions(documentId)),
+ reportError: services.reporter
})
return await createCloudServer(app, {
site: assetSiteFiles(c.env.ASSETS),
- indexingPolicy: config.indexingPolicy
+ indexingPolicy: config.indexingPolicy,
+ reportError: services.reporter
}).fetch(c.req.raw)
} finally {
services.finish()
@@ -137,21 +184,11 @@ export function createCloudflareCloud(configSource: string) {
fetch: (request, env, context) => router.fetch(request, env, context),
async scheduled(_controller, env, context) {
- const prepared = await prepare(env)
- const services = cloudServices(prepared, env, context)
- const { config, database, objects } = services
try {
- if (config.cleanupEnabled) {
- const policy = createConfiguredCloudPolicy(config, database)
- await runCleanup(
- createCleanupServices(config, database, objects, policy),
- cleanupPassOptions(config)
- )
- }
- // Retries what failed to send after its request, and what a full batch left behind.
- if (services.transport) await services.deliver()
- } finally {
- services.finish()
+ await runScheduled(await prepare(env), env, context)
+ } catch (error) {
+ await reportCloudError(reporter(), 'Scheduled run failed:', error, { source: 'scheduled' })
+ throw error
}
}
}
diff --git a/packages/cloud/src/runtime/node/bootstrap.ts b/packages/cloud/src/runtime/node/bootstrap.ts
index d11ce4bdd..52aeef057 100644
--- a/packages/cloud/src/runtime/node/bootstrap.ts
+++ b/packages/cloud/src/runtime/node/bootstrap.ts
@@ -7,6 +7,14 @@ import {
import { loadNodeCloudServerConfig } from './config'
+/** The deployment's database, migrated to this version before anything uses it. */
+export async function migratedNodeCloudDatabase(config: CloudServerConfig) {
+ const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
+ const auth = createBetterAuthAdapter(config, database)
+ await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
+ return { database, auth }
+}
+
export async function createMigratedNodeCloudDatabase(
environment: Readonly<Record<string, string | undefined>>
): Promise<{
@@ -15,8 +23,5 @@ export async function createMigratedNodeCloudDatabase(
auth: ReturnType<typeof createBetterAuthAdapter>
}> {
const config = await loadNodeCloudServerConfig(environment)
- const database = createPostgresCloudDatabase({ connectionString: config.databaseURL })
- const auth = createBetterAuthAdapter(config, database)
- await migrateCloudDatabase(database, { run: auth.migrate, schemaVersion: auth.schemaVersion })
- return { config, database, auth }
+ return { config, ...(await migratedNodeCloudDatabase(config)) }
}
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index 8ed77209e..e0738f637 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -1,4 +1,5 @@
import { defaultRelayURL } from '#cloud/contract'
+import { createPostHogErrorReporter } from '#cloud/runtime/posthog/errors'
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'
import {
@@ -11,11 +12,15 @@ import {
createCleanupServices,
createConfiguredCloudPolicy,
relayDocumentLookups,
+ reportCloudError,
startCleanupWorker,
- startTransactionalEmailWorker
+ startTransactionalEmailWorker,
+ type CloudErrorReporter,
+ type CloudServerConfig
} from '#cloud/server'
-import { createMigratedNodeCloudDatabase } from './bootstrap'
+import { migratedNodeCloudDatabase } from './bootstrap'
+import { loadNodeCloudServerConfig } from './config'
import { createNodeTransactionalEmailRuntime } from './email/runtime'
import { listen } from './listen'
import { attachCollaborationRelay } from './relay'
@@ -40,9 +45,30 @@ function siteFiles(
return undefined
}
+/**
+ * Starts the server. Once the config parses, a startup that fails, such as a migration, a signing
+ * key, or a port that cannot be bound, is reported before it is thrown; a config that does not
+ * parse has no error tracking to report to.
+ */
export async function startNodeCloudServer(options: NodeCloudServerOptions = {}) {
const environment = options.environment ?? process.env
- const { config, database } = await createMigratedNodeCloudDatabase(environment)
+ const config = await loadNodeCloudServerConfig(environment)
+ const reportError = createPostHogErrorReporter(config, 'node')
+ try {
+ return await startConfiguredServer(config, environment, options, reportError)
+ } catch (error) {
+ await reportCloudError(reportError, 'Starting the server failed:', error, { source: 'setup' })
+ throw error
+ }
+}
+
+async function startConfiguredServer(
+ config: CloudServerConfig,
+ environment: Readonly<Record<string, string | undefined>>,
+ options: NodeCloudServerOptions,
+ reportError: CloudErrorReporter | undefined
+) {
+ const { database } = await migratedNodeCloudDatabase(config)
// Before any worker starts, so a key that cannot sign leaves nothing running.
const aiSigningKey = await loadAISigningKey(config).catch(async (error: unknown) => {
await database.destroy()
@@ -60,7 +86,8 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
? startCleanupWorker(createCleanupServices(config, database, objects, policy), {
...cleanupPassOptions(config),
intervalMs: config.cleanupIntervalMs,
- onError: (error) => console.error('[Cloud] Cleanup worker failed:', error)
+ onError: (error) =>
+ void reportCloudError(reportError, 'Cleanup worker failed:', error, { source: 'cleanup' })
})
: undefined
const relay = createCollaborationRelay({
@@ -68,6 +95,8 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
store: createCollaborationStateStore(database),
maximumMessageBytes: config.technicalLimits.maximumCollaborationMessageBytes,
maximumConnectionsPerRoom: config.technicalLimits.maximumConnectionsPerRoom,
+ onError: (message, error) =>
+ void reportCloudError(reportError, message, error, { source: 'relay' }),
...relayDocumentLookups(database, policy, config.deployment)
})
const app = createCloudApp({
@@ -81,7 +110,8 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
aiSigningKey,
relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),
onDocumentRestored: (documentId) => relay.startOver(documentId),
- onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId)
+ onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId),
+ reportError
})
const emailWorker = emailTransport
? startTransactionalEmailWorker(email, {
@@ -89,12 +119,14 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
intervalMs: config.emailIntervalMs,
leaseDurationMs: config.emailLeaseDurationMs,
maximumAttempts: config.emailMaximumAttempts,
- onError: (error) => console.error('[Cloud] Email worker failed:', error)
+ onError: (error) =>
+ void reportCloudError(reportError, 'Email worker failed:', error, { source: 'email' })
})
: undefined
const cloudServer = createCloudServer(app, {
site: siteFiles(environment),
- indexingPolicy: config.indexingPolicy
+ indexingPolicy: config.indexingPolicy,
+ reportError
})
const server = await listen(
async (request) => cloudServer.fetch(request),
diff --git a/packages/cloud/src/runtime/posthog/errors.ts b/packages/cloud/src/runtime/posthog/errors.ts
new file mode 100644
index 000000000..29d55a8d2
--- /dev/null
+++ b/packages/cloud/src/runtime/posthog/errors.ts
@@ -0,0 +1,48 @@
+import type { CloudServerConfig } from '#cloud/server'
+import type { CloudErrorReporter } from '#cloud/server/errors'
+import { PostHog, type PostHogOptions } from 'posthog-node'
+
+/** Which runtime serves the deployment, as its error reports name it. */
+export type CloudRuntimeName = 'node' | 'cloudflare'
+
+/**
+ * Reports server errors to the PostHog project the deployment's `[error_tracking]` names, or
+ * returns nothing when it names none. Each error is sent as it is caught, as a `$exception` with
+ * no person profile: reports carry the runtime, the deployment, and where the error was caught,
+ * never who made the request or what it carried.
+ */
+export function createPostHogErrorReporter(
+ config: CloudServerConfig,
+ runtime: CloudRuntimeName,
+ options: Pick<PostHogOptions, 'fetch'> = {}
+): CloudErrorReporter | undefined {
+ const tracking = config.errorTracking
+ if (!tracking) return undefined
+ const client = new PostHog(tracking.projectAPIKey, {
+ host: tracking.host,
+ disableGeoip: true,
+ ...options
+ })
+ // The SDK resolves a capture that PostHog refused and emits the refusal instead.
+ client.on('error', (failure: unknown) => {
+ console.error('[Cloud] PostHog refused an error report:', failure)
+ })
+ const deployment = {
+ cloud_runtime: runtime,
+ cloud_deployment: config.deployment,
+ cloud_host: new URL(config.publicURL).host
+ }
+ return async (error, context) => {
+ try {
+ // Undefined request fields are left out of the event's JSON.
+ await client.captureExceptionImmediate(error, undefined, {
+ ...deployment,
+ cloud_source: context.source,
+ http_method: context.method,
+ http_route: context.route
+ })
+ } catch (failure) {
+ console.error('[Cloud] Reporting an error failed:', failure)
+ }
+ }
+}
diff --git a/packages/cloud/src/runtime/site/server.ts b/packages/cloud/src/runtime/site/server.ts
index cc53c0eb7..515737106 100644
--- a/packages/cloud/src/runtime/site/server.ts
+++ b/packages/cloud/src/runtime/site/server.ts
@@ -1,5 +1,5 @@
import { CLOUD_PORTAL_PAGE_ROOTS } from '#cloud/contract'
-import { withIndexingPolicy } from '#cloud/server'
+import { cloudErrorHandler, withIndexingPolicy, type CloudErrorReporter } from '#cloud/server'
import { Hono } from 'hono'
/** A file of the Cloud site (`bun run build:cloud`): the editor and the portal. */
@@ -29,6 +29,8 @@ export type CloudServerOptions = {
/** The built site; without it, the server answers only its API. */
site?: SiteFiles
indexingPolicy: 'allow' | 'deny'
+ /** Reports errors reading the site's files, when the deployment configures error tracking. */
+ reportError?: CloudErrorReporter
}
function cacheControl(path: string): string {
@@ -43,9 +45,9 @@ function cacheControl(path: string): string {
*/
export function createCloudServer(
api: { fetch(request: Request): Response | Promise<Response> },
- { site, indexingPolicy }: CloudServerOptions
+ { site, indexingPolicy, reportError }: CloudServerOptions
) {
- const server = new Hono()
+ const server = new Hono().onError(cloudErrorHandler(reportError))
server.use(async (c, next) => {
await next()
c.res = withIndexingPolicy(c.res, c.req.path, indexingPolicy)
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index a68c27e2a..a6b2ce3a4 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -39,6 +39,7 @@ import type { CloudDatabase } from '#cloud/server/db'
import { createDocumentService } from '#cloud/server/documents'
import { createDocumentVersionService } from '#cloud/server/documents/versions'
import type { TransactionalEmailService } from '#cloud/server/email'
+import { cloudErrorHandler, type CloudErrorReporter } from '#cloud/server/errors'
import { createInternalRoutes, createInternalService } from '#cloud/server/internal'
import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
import type { ObjectStore } from '#cloud/server/objects'
@@ -87,6 +88,8 @@ export type CloudServices = {
onDocumentRestored?: (documentId: string) => void
/** Tells a document's live rooms its version history changed, on the relay this runtime runs. */
onDocumentVersionsChanged?: (documentId: string) => void
+ /** Reports errors no route handled, when the deployment configures error tracking. */
+ reportError?: CloudErrorReporter
}
type CloudEnvironment = CloudAPIEnvironment
@@ -310,6 +313,7 @@ export function createCloudApp(services: CloudServices) {
: new Hono()
return new Hono<CloudEnvironment>()
+ .onError(cloudErrorHandler(services.reportError))
.use(CLOUD_DISCOVERY_PATH, cloudCORS)
.use('/api/*', cloudCORS)
.use('*', async (context, next) => {
diff --git a/packages/cloud/src/server/config/deployment.ts b/packages/cloud/src/server/config/deployment.ts
index aa5184338..bfab8538b 100644
--- a/packages/cloud/src/server/config/deployment.ts
+++ b/packages/cloud/src/server/config/deployment.ts
@@ -99,6 +99,16 @@ function serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironm
}
}
+function errorTrackingConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
+ const tracking = config.error_tracking
+ if (!tracking) return undefined
+ return {
+ provider: tracking.provider,
+ host: tracking.host,
+ projectAPIKey: configuredText(environment, tracking.project_api_key)
+ }
+}
+
/** Hard limits, whatever a plan allows; each lives in the section it limits. */
function technicalLimits(config: CloudDeploymentConfig) {
return {
@@ -166,6 +176,7 @@ export function parseCloudDeploymentConfig(
...emailConfig(config, environment),
...workerConfig(config),
...serviceConfig(config, environment),
+ errorTracking: errorTrackingConfig(config, environment),
technicalLimits: technicalLimits(config)
})
}
diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.ts
index 925479cef..8146b2c1c 100644
--- a/packages/cloud/src/server/config/schema.ts
+++ b/packages/cloud/src/server/config/schema.ts
@@ -146,7 +146,15 @@ const rawCloudServerConfigSchema = v.object({
),
billingPortalURL: v.optional(httpURLSchema),
/** The bearer token services such as billing present to the internal API. */
- internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32)))
+ internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32))),
+ /** Where server errors are reported; without it the server reports nothing. */
+ errorTracking: v.optional(
+ v.object({
+ provider: v.literal('posthog'),
+ host: httpURLSchema,
+ projectAPIKey: v.pipe(v.string(), v.trim(), v.minLength(1))
+ })
+ )
})
export type CloudServerConfig = v.InferOutput<typeof rawCloudServerConfigSchema>
@@ -263,6 +271,9 @@ export function parseCloudServerConfig(input: unknown): CloudServerConfig {
return config
}
+/** PostHog's US Cloud ingestion host. */
+const POSTHOG_DEFAULT_HOST = 'https://us.i.posthog.com'
+
const DEFAULT_SECRET_NAMES = {
databaseURL: 'DATABASE_URL',
authSecret: 'BETTER_AUTH_SECRET',
@@ -276,7 +287,8 @@ const DEFAULT_SECRET_NAMES = {
smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',
turnstileSecretKey: 'TURNSTILE_SECRET_KEY',
aiSigningKey: 'OPENPENCIL_CLOUD_AI_SIGNING_KEY',
- internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN'
+ internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN',
+ posthogProjectAPIKey: 'POSTHOG_PROJECT_API_KEY'
} as const
const urlSchema = v.pipe(v.string(), v.url())
@@ -503,6 +515,16 @@ export const cloudDeploymentConfigSchema = v.strictObject({
billing: v.optional(v.strictObject({ portal_url: urlSchema })),
internal_api: v.optional(
v.strictObject({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
+ ),
+ /** Optional: reports server errors to PostHog error tracking. Leave it out to send nothing. */
+ error_tracking: v.optional(
+ v.strictObject({
+ provider: v.literal('posthog'),
+ host: v.optional(urlSchema, POSTHOG_DEFAULT_HOST),
+ project_api_key: v.optional(configurableTextSchema, {
+ from_env: DEFAULT_SECRET_NAMES.posthogProjectAPIKey
+ })
+ })
)
})
diff --git a/packages/cloud/src/server/errors/index.ts b/packages/cloud/src/server/errors/index.ts
new file mode 100644
index 000000000..bdc6a30f9
--- /dev/null
+++ b/packages/cloud/src/server/errors/index.ts
@@ -0,0 +1,56 @@
+import type { Context, ErrorHandler } from 'hono'
+import { HTTPException } from 'hono/http-exception'
+import { routePath } from 'hono/route'
+
+/** Where the server caught an error. */
+export const CLOUD_ERROR_SOURCES = [
+ 'request',
+ 'background',
+ 'cleanup',
+ 'email',
+ 'relay',
+ 'scheduled',
+ 'setup'
+] as const
+export type CloudErrorSource = (typeof CLOUD_ERROR_SOURCES)[number]
+
+/** What the server knows about a caught error; never who made the request or what it carried. */
+export type CloudErrorContext = {
+ source: CloudErrorSource
+ /** For a request: its method and the route pattern it matched, not the path with its IDs. */
+ method?: string
+ route?: string
+}
+
+/**
+ * Sends a caught error to the deployment's error tracking. Runtimes create one only when the
+ * deployment configures error tracking; its promise never rejects.
+ */
+export type CloudErrorReporter = (error: unknown, context: CloudErrorContext) => Promise<void>
+
+/** Logs a caught error and reports it, when the deployment reports errors. */
+export function reportCloudError(
+ reporter: CloudErrorReporter | undefined,
+ message: string,
+ error: unknown,
+ context: CloudErrorContext
+): Promise<void> {
+ console.error(`[Cloud] ${message}`, error)
+ return reporter ? reporter(error, context) : Promise.resolve()
+}
+
+function requestContext(context: Context): CloudErrorContext {
+ return { source: 'request', method: context.req.method, route: routePath(context) }
+}
+
+/**
+ * The app's last error handler, as Hono's default: an `HTTPException` answers with its response,
+ * anything else is logged, reported, and answered with a 500.
+ */
+export function cloudErrorHandler(reporter: CloudErrorReporter | undefined): ErrorHandler {
+ return (error, context) => {
+ if (error instanceof HTTPException) return error.getResponse()
+ void reportCloudError(reporter, 'Request failed:', error, requestContext(context))
+ return context.text('Internal Server Error', 500)
+ }
+}
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
index 90e0e8311..7c49b64ef 100644
--- a/packages/cloud/src/server/index.ts
+++ b/packages/cloud/src/server/index.ts
@@ -182,6 +182,14 @@ export {
type TransactionalEmailWorker,
type TransactionalEmailWorkerOptions
} from './email'
+export {
+ CLOUD_ERROR_SOURCES,
+ cloudErrorHandler,
+ reportCloudError,
+ type CloudErrorContext,
+ type CloudErrorReporter,
+ type CloudErrorSource
+} from './errors'
export {
createInternalRoutes,
createInternalService,
diff --git a/packages/cloud/tests/runtime/posthog/errors.test.ts b/packages/cloud/tests/runtime/posthog/errors.test.ts
new file mode 100644
index 000000000..39408828a
--- /dev/null
+++ b/packages/cloud/tests/runtime/posthog/errors.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, spyOn, test } from 'bun:test'
+import { gunzipSync } from 'node:zlib'
+
+import { createPostHogErrorReporter } from '#cloud/runtime/posthog/errors'
+import { parseCloudServerConfig } from '#cloud/server'
+import * as v from 'valibot'
+
+type ErrorTracking = { provider: 'posthog'; host: string; projectAPIKey: string }
+
+function config(errorTracking?: ErrorTracking) {
+ return parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'https://cloud.example.com',
+ databaseURL: 'postgresql://user:password@database/openpencil',
+ authSecret: 'auth-secret-at-least-32-characters-long',
+ s3Endpoint: 'https://objects.example.com',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'access-key',
+ s3SecretAccessKey: 'secret-key',
+ errorTracking
+ })
+}
+
+/** The batch PostHog was sent, which the SDK compresses. */
+function sentJSON(body: unknown): unknown {
+ if (!(body instanceof Uint8Array)) throw new Error('Expected a compressed body')
+ const text = new TextDecoder().decode(gunzipSync(body))
+ return v.parse(v.pipe(v.string(), v.parseJson(), v.unknown()), text)
+}
+
+describe('PostHog error reporter', () => {
+ test('is not created without error tracking', () => {
+ expect(createPostHogErrorReporter(config(), 'node')).toBeUndefined()
+ })
+
+ test('sends an anonymous exception to the configured host as it is caught', async () => {
+ const sent: { url: string; body: unknown }[] = []
+ const report = createPostHogErrorReporter(
+ config({ provider: 'posthog', host: 'https://eu.i.posthog.com', projectAPIKey: 'phc_test' }),
+ 'cloudflare',
+ {
+ fetch: async (url, options) => {
+ sent.push({ url, body: options.body })
+ return { status: 200, text: async () => '{}', json: async () => ({}) }
+ }
+ }
+ )
+ await report?.(new TypeError('row missing'), {
+ source: 'request',
+ method: 'POST',
+ route: '/api/documents/:id'
+ })
+
+ expect(sent).toHaveLength(1)
+ expect(sent[0]?.url).toBe('https://eu.i.posthog.com/batch/')
+ expect(sentJSON(sent[0]?.body)).toMatchObject({
+ api_key: 'phc_test',
+ batch: [
+ {
+ event: '$exception',
+ properties: {
+ $process_person_profile: false,
+ $geoip_disable: true,
+ $exception_list: [{ type: 'TypeError', value: 'row missing' }],
+ cloud_runtime: 'cloudflare',
+ cloud_deployment: 'self-hosted',
+ cloud_host: 'cloud.example.com',
+ cloud_source: 'request',
+ http_method: 'POST',
+ http_route: '/api/documents/:id'
+ }
+ }
+ ]
+ })
+ })
+
+ test('logs a report PostHog refuses', async () => {
+ const logged = spyOn(console, 'error').mockImplementation(() => undefined)
+ try {
+ const report = createPostHogErrorReporter(
+ config({ provider: 'posthog', host: 'https://eu.i.posthog.com', projectAPIKey: 'phc_x' }),
+ 'node',
+ {
+ fetch: async () => ({ status: 401, text: async () => '{}', json: async () => ({}) })
+ }
+ )
+ await report?.(new Error('broken'), { source: 'cleanup' })
+ const refusal = logged.mock.calls.find(
+ ([message]) => message === '[Cloud] PostHog refused an error report:'
+ )
+ expect(refusal?.[1]).toBeInstanceOf(Error)
+ } finally {
+ logged.mockRestore()
+ }
+ })
+})
diff --git a/packages/cloud/tests/runtime/site/server.test.ts b/packages/cloud/tests/runtime/site/server.test.ts
index 2d55026a5..be7998d40 100644
--- a/packages/cloud/tests/runtime/site/server.test.ts
+++ b/packages/cloud/tests/runtime/site/server.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, test } from 'bun:test'
+import { describe, expect, spyOn, test } from 'bun:test'
import { createCloudServer, type SiteFiles } from '#cloud/runtime/site/server'
+import type { CloudErrorContext } from '#cloud/server'
const files: Record<string, string> = {
'/cloud.html': '<!doctype html><title>Portal</title>',
@@ -81,4 +82,28 @@ describe('Cloud server', () => {
(await bare.request('https://cloud.example/', { headers: { Accept: 'text/html' } })).status
).toBe(404)
})
+
+ test('reports a site file it fails to read and answers 500', async () => {
+ const logged = spyOn(console, 'error').mockImplementation(() => undefined)
+ const reported: { error: unknown; context: CloudErrorContext }[] = []
+ const failure = new Error('assets unavailable')
+ try {
+ const failing = createCloudServer(api, {
+ site: async () => {
+ throw failure
+ },
+ indexingPolicy: 'deny',
+ reportError: async (error, context) => {
+ reported.push({ error, context })
+ }
+ })
+ const response = await failing.request(new Request('https://cloud.example/favicon.svg'))
+ expect(response.status).toBe(500)
+ expect(reported).toEqual([
+ { error: failure, context: { source: 'request', method: 'GET', route: '/*' } }
+ ])
+ } finally {
+ logged.mockRestore()
+ }
+ })
})
diff --git a/packages/cloud/tests/server/config/deployment.test.ts b/packages/cloud/tests/server/config/deployment.test.ts
index 309c021d3..12a05ed62 100644
--- a/packages/cloud/tests/server/config/deployment.test.ts
+++ b/packages/cloud/tests/server/config/deployment.test.ts
@@ -184,6 +184,30 @@ describe('Cloud TOML deployment configuration', () => {
).toThrow()
})
+ test('reports server errors only when error tracking is configured', () => {
+ expect(parseCloudDeploymentTOML(minimalSource, environment).errorTracking).toBeUndefined()
+
+ const tracked = `${minimalSource}
+[error_tracking]
+provider = "posthog"
+`
+ expect(() => parseCloudDeploymentTOML(tracked, environment)).toThrow('POSTHOG_PROJECT_API_KEY')
+ expect(
+ parseCloudDeploymentTOML(tracked, { ...environment, POSTHOG_PROJECT_API_KEY: 'phc_test' })
+ .errorTracking
+ ).toEqual({ provider: 'posthog', host: 'https://us.i.posthog.com', projectAPIKey: 'phc_test' })
+
+ const inline = tracked.replace(
+ 'provider = "posthog"',
+ 'provider = "posthog"\nhost = "https://eu.i.posthog.com"\nproject_api_key = "phc_inline"'
+ )
+ expect(parseCloudDeploymentTOML(inline, environment).errorTracking).toEqual({
+ provider: 'posthog',
+ host: 'https://eu.i.posthog.com',
+ projectAPIKey: 'phc_inline'
+ })
+ })
+
test('advertises an AI service and billing portal only when configured', () => {
const plain = cloudDiscoveryFromConfig(parseCloudDeploymentTOML(minimalSource, environment))
expect(plain.ai).toBeUndefined()
diff --git a/packages/cloud/tests/server/errors/handler.test.ts b/packages/cloud/tests/server/errors/handler.test.ts
new file mode 100644
index 000000000..d9455812b
--- /dev/null
+++ b/packages/cloud/tests/server/errors/handler.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, spyOn, test } from 'bun:test'
+
+import { cloudErrorHandler, type CloudErrorContext } from '#cloud/server/errors'
+import { Hono } from 'hono'
+import { HTTPException } from 'hono/http-exception'
+
+type Reported = { error: unknown; context: CloudErrorContext }
+
+const failure = new Error('database unavailable')
+
+function appReporting(reported: Reported[]) {
+ return new Hono()
+ .onError(
+ cloudErrorHandler(async (error, context) => {
+ reported.push({ error, context })
+ })
+ )
+ .get('/api/documents/:id', () => {
+ throw failure
+ })
+ .get('/api/limited', () => {
+ throw new HTTPException(429, { message: 'slow down' })
+ })
+}
+
+describe('Cloud error handler', () => {
+ test('reports an unhandled error with its route pattern and answers 500', async () => {
+ const logged = spyOn(console, 'error').mockImplementation(() => undefined)
+ const reported: Reported[] = []
+ try {
+ const response = await appReporting(reported).request('/api/documents/secret-id')
+ expect(response.status).toBe(500)
+ expect(await response.text()).toBe('Internal Server Error')
+ expect(reported).toHaveLength(1)
+ expect(reported[0]?.error).toBe(failure)
+ expect(reported[0]?.context).toEqual({
+ source: 'request',
+ method: 'GET',
+ route: '/api/documents/:id'
+ })
+ expect(logged).toHaveBeenCalledTimes(1)
+ } finally {
+ logged.mockRestore()
+ }
+ })
+
+ test('answers an HTTP exception with its own response and reports nothing', async () => {
+ const reported: Reported[] = []
+ const response = await appReporting(reported).request('/api/limited')
+ expect(response.status).toBe(429)
+ expect(reported).toEqual([])
+ })
+
+ test('still answers 500 when the deployment reports nothing', async () => {
+ const logged = spyOn(console, 'error').mockImplementation(() => undefined)
+ try {
+ const app = new Hono().onError(cloudErrorHandler(undefined)).get('/', () => {
+ throw new Error('broken')
+ })
+ expect((await app.request('/')).status).toBe(500)
+ } finally {
+ logged.mockRestore()
+ }
+ })
+})
diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.md
index 8d055e53e..30b69f79e 100644
--- a/packages/docs/reference/self-hosting-cloud.md
+++ b/packages/docs/reference/self-hosting-cloud.md
@@ -139,6 +139,10 @@ Any S3-compatible store works; the project tests against SeaweedFS and Garage. K
Revision keys are immutable, so bucket versioning isn't needed, but it isn't a backup either. Size `[workers.cleanup]` for your upload volume and retention, or set `enabled = false` and run `cleanup` from a scheduler.
+## Error tracking
+
+The server reports nothing unless you ask it to. Add an `[error_tracking]` table with `provider = "posthog"` to send errors no request handled, and failures of startup once the configuration parses, background work, cleanup, email delivery, and the collaboration relay, to PostHog error tracking. `host` defaults to PostHog's US Cloud, `https://us.i.posthog.com`; set `https://eu.i.posthog.com` or your own instance's address instead. The project API key defaults to `POSTHOG_PROJECT_API_KEY`. Each report carries the error's message and stack, the runtime, the deployment mode and host, where the error was caught, and for a request its method and route pattern. It names no account and creates no person in PostHog, and it leaves out the client's address and the request body, though an error's message can quote a value the failing code handled, such as a malformed ID in a database error. Errors are still logged either way.
+
## Backups and upgrades
Back up PostgreSQL and the bucket together. To upgrade, build the new version, stop the old process, and start the new one: it applies migrations before it accepts requests. Migrations only move forward, so restore the database backup to roll back.