Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/commex-2324-once-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@godaddy/app-connect': minor
---

Add a once-only helper, exported from the package root and from `@godaddy/app-connect/once`. `once(store, key, fn, { leaseMs })` records one outcome per key, runs `fn` one caller at a time, and answers `done`, `duplicate`, `in_flight` or `refused` (when `fn` throws `Refused`). A claim whose lease passes is taken over, so work a crashed instance held is retried instead of lost; work that outlives its lease can run again, so pair it with an idempotency key.

Stores implement `OnceStore`. `createMysqlOnceStore` keeps claims in MySQL 8 or later through a `mysql2/promise` pool and ships its table DDL (`onceTableDdl`); `createMemoryOnceStore` is for tests and local runs. `deriveId(namespace, name)` builds RFC 9562 version 5 ids for stable keys and idempotency keys.
88 changes: 87 additions & 1 deletion packages/app-connect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A collection of tools and utilities for building applications that integrate wit

This library provides essential functionality for developers building applications that work with the GoDaddy platform. It handles platform integration concerns like request verification, webhook validation, authentication, and API communication.

> **Note:** This library is under active development. Currently, it provides request verification and webhook subscription verification functionality, with more features planned for future releases.
> **Note:** This library is under active development. Currently, it provides request verification, webhook subscription verification and once-only work, with more features planned for future releases.

## Installation

Expand Down Expand Up @@ -51,6 +51,15 @@ Verify that incoming webhook subscriptions are genuinely from the GoDaddy platfo
- Express.js middleware for easy integration
- Configurable via environment variables or runtime options

### Once-only Work

Record one outcome per key across every instance of the app, and run the work for it one caller at a time, so a redelivered webhook or a retried job doesn't repeat a side effect. Work that outlives its lease can run again, so pair it with an idempotency key.

- `once(store, key, fn)` with the outcomes `done`, `duplicate`, `in_flight` and `refused`
- A lease, so work a crashed instance claimed is taken over instead of lost
- A MySQL 8 store (a `mysql2/promise` pool) and an in-memory store for tests
- `deriveId(namespace, name)` for stable name-based ids (RFC 9562 version 5)

## Usage

### Configuration
Expand Down Expand Up @@ -215,6 +224,43 @@ function processWebhookSubscription(req) {
}
```

### Once-only Work

```typescript
import { createPool } from 'mysql2/promise';
import { Refused, createMysqlOnceStore, deriveId, once } from '@godaddy/app-connect/once';

const store = createMysqlOnceStore(createPool(process.env.DATABASE_URL!));
// One random UUID per app (run crypto.randomUUID() once), never changed.
// Don't copy someone else's: apps sharing it would share idempotency keys.
const NAMESPACE = process.env.ONCE_NAMESPACE!;

const result = await once(store, `order-event:${eventId}`, async () => {
const response = await sendToVendor(order, { idempotencyKey: deriveId(NAMESPACE, eventId) });
if (response.status === 422) throw new Refused('vendor_rejected'); // recorded; never retried
if (!response.ok) throw new Error(`vendor answered ${response.status}`); // released; a retry runs again
return response.id;
});

switch (result.status) {
case 'done': // the work ran now; result.value is what it returned
case 'duplicate': // it already finished earlier (result.outcome says how)
case 'refused': // it ran now and was refused for good
return res.status(200).end();
case 'in_flight': // another instance holds it (or a claim whose response was lost, until its lease passes); ask the sender to retry
return res.status(503).end();
}
```

- Pass a `mysql2/promise` Pool, not a connection the app uses for its own transactions: claims must commit on their own to be seen by other instances. A claim that waits on a row lock answers `in_flight` only after the server's `innodb_lock_wait_timeout` (50 seconds by default); lower it for the store's pool if senders time out sooner. A claim that waited has its lease renewed from when it got the row. Keep the pool's charset utf8mb4 (the mysql2 default), or keys with characters outside the BMP can be cut short and collide.
- The store creates its table (`app_connect_once`) on first use. To create it from a migration instead, use `onceTableDdl()` and pass `createTable: false`. The store needs MySQL 8 or later (the key uses `utf8mb4_0900_bin`, which MariaDB doesn't have).
- Rows are kept. Prune finished rows and claims whose lease has passed in small batches, for example `DELETE FROM app_connect_once WHERE updated_at < ? AND (state <> 'claimed' OR lease_until < ?) LIMIT 1000` (both in Unix milliseconds), so claims aren't kept waiting on a long delete. A pruned key can run again, so keep rows longer than any sender may redeliver or retry the same key.
- Leases are judged by each instance's own clock, so keep instances' clocks in sync (NTP) to well inside a lease. A clock that runs ahead by more than the lease takes over claims that are still live.
- `createMemoryOnceStore()` keeps claims in one process and never forgets finished keys, so use it for tests and local runs only.
- `leaseMs` (default 5 minutes) must be longer than the work can take. Once it passes, another caller may take the key over and run the work again, so make the work safe to repeat, for example with an idempotency key from `deriveId`.
- Keys are at most 255 characters; derive a shorter one with `deriveId` when needed. A `Refused` reason is stored, so keep it a short code, never vendor text or shopper data.
- When the work finished but its outcome could not be recorded, `once` throws `OnceNotRecordedError` (with the work's return value as `value`); answer the delivery as failed so it is retried.

## API Reference

### Core Functions
Expand Down Expand Up @@ -263,6 +309,46 @@ import { verifyAction, verifyWebhookSubscription, VerifiableRequest } from '@god

See the [Next.js App Router Integration](#nextjs-app-router-integration-nextjs-13) example for action verification details. The pattern is similar for webhook verification.

### Once-only Work

All of these are exported from `@godaddy/app-connect/once` and from the package root.

#### `once(store, key, fn, options?): Promise<OnceResult<T>>`

Records one outcome for `key`, running `fn` one caller at a time. Answers `{ status: 'done', value }`, `{ status: 'duplicate', outcome }`, `{ status: 'in_flight' }` or `{ status: 'refused', reason }`. `options.leaseMs` defaults to 5 minutes; `options.onReleaseError` hears about a claim that couldn't be released after `fn` threw (pass a wrapper such as `(err, key) => logger.error({ err, key }, 'release failed')`, so the logger keeps its `this`). It throws a `TypeError` for a bad key or lease, whatever `store.claim` throws, whatever `fn` throws other than `Refused` (after releasing the claim), and `OnceNotRecordedError` when `fn` finished but its outcome could not be recorded. After any of these this caller didn't record an outcome, so answer the delivery as failed; the retry's `once` call shows whether another caller finished the key meanwhile (see `OnceClaimLostError` below).

#### `Refused`

Throw `new Refused(reason)` from `fn` to record a refusal for good.

#### `createMysqlOnceStore(pool, options?): OnceStore`

A store in MySQL 8. Options: `table` (default `app_connect_once`), `createTable` (default true) and `now`.

#### `onceTableDdl(table?): string`

The `CREATE TABLE IF NOT EXISTS` statement for a migration.

#### `createMemoryOnceStore(options?): OnceStore`

A store in this process's memory, for tests and local runs.

#### `deriveId(namespace, name): string`

An RFC 9562 version 5 UUID for `name` in the `namespace` UUID.

#### `OnceNotRecordedError` and `OnceClaimLostError`

`OnceNotRecordedError` has `key`, `outcome`, `value` (what `fn` returned, not enumerable) and `cause`. When `cause` is an `OnceClaimLostError`, the lease passed and another caller took the key over, so it may already be done; otherwise the store failed and the key stays claimed until its lease passes. Neither error puts the key in its message, but keep shopper data out of keys anyway: they're stored.

#### `OnceStore`

The port for a custom store: `claim(key, leaseMs)` answers `claimed` (with a token), `done`, `refused` or `in_flight`, atomically across processes, taking over a claim whose lease has passed; `complete(key, token, outcome)` records the outcome for the token's holder and throws `OnceClaimLostError` otherwise; `release(key, token)` forgets the holder's claim and does nothing otherwise.

#### Constants

`DEFAULT_LEASE_MS` (5 minutes), `DEFAULT_ONCE_TABLE` (`app_connect_once`), `MAX_KEY_LENGTH` and `MAX_REASON_LENGTH` (255 characters each).

### Helper Functions

#### `getWebhookSecret(options?): string`
Expand Down
8 changes: 7 additions & 1 deletion packages/app-connect/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@godaddy/app-connect",
"version": "1.0.2",
"description": "GoDaddy App Connect - A verification library for GoDaddy Platform App requests",
"description": "GoDaddy App Connect - Request verification and once-only work for GoDaddy Platform Apps",
"type": "module",
"types": "./dist/index.d.ts",
"files": [
Expand All @@ -27,6 +27,11 @@
"types": "./dist/tanstack/index.d.ts",
"import": "./dist/tanstack/index.js",
"default": "./dist/tanstack/index.js"
},
"./once": {
"types": "./dist/once/index.d.ts",
"import": "./dist/once/index.js",
"default": "./dist/once/index.js"
}
},
"scripts": {
Expand Down Expand Up @@ -62,6 +67,7 @@
"@biomejs/biome": "1.9.4",
"@types/express": "^5.0.2",
"@types/node": "^22.13.1",
"mysql2": "3.24.6",
"pino-pretty": "^13.0.0",
"tsdown": "^0.15.6",
"typescript": "~5.7.3",
Expand Down
26 changes: 26 additions & 0 deletions packages/app-connect/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,32 @@ export { createActionMiddleware, createWebhookMiddleware } from './express';
export * as next from './next';
export * as tanstack from './tanstack';

// Export the once-only helper
export {
DEFAULT_LEASE_MS,
DEFAULT_ONCE_TABLE,
MAX_KEY_LENGTH,
MAX_REASON_LENGTH,
OnceClaimLostError,
OnceNotRecordedError,
Refused,
createMemoryOnceStore,
createMysqlOnceStore,
deriveId,
once,
onceTableDdl,
} from './once';
export type {
MemoryOnceStoreOptions,
MysqlOnceStoreOptions,
OnceClaim,
OnceOptions,
OnceOutcome,
OnceResult,
OnceStore,
SqlQueryRunner,
} from './once';

// Export types
export type { Result } from './types/result';
export type { VerifiableRequest } from './types/verifiable-request';
Expand Down
47 changes: 47 additions & 0 deletions packages/app-connect/src/once/derive-id.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest';
import { deriveId } from './derive-id';

const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';

describe('deriveId', () => {
it('matches the RFC 9562 version 5 example', () => {
// RFC 9562, Appendix A.4: the DNS namespace and "www.example.com".
expect(deriveId(DNS_NAMESPACE, 'www.example.com')).toBe(
'2ed6657d-e927-568b-95e1-2665a8aea6a2',
);
expect(deriveId(DNS_NAMESPACE.toUpperCase(), 'www.example.com')).toBe(
'2ed6657d-e927-568b-95e1-2665a8aea6a2',
);
});

it('is stable for a name and differs across names and namespaces', () => {
const id = deriveId(DNS_NAMESPACE, 'a');
expect(deriveId(DNS_NAMESPACE, 'a')).toBe(id);
expect(deriveId(DNS_NAMESPACE, 'b')).not.toBe(id);
expect(deriveId('6ba7b811-9dad-11d1-80b4-00c04fd430c8', 'a')).not.toBe(id);
expect(id).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
);
});

it('hashes the name as UTF-8', () => {
expect(deriveId(DNS_NAMESPACE, 'café')).not.toBe(
deriveId(DNS_NAMESPACE, 'cafe'),
);
});

it('refuses a name with a lone surrogate, which would share an id', () => {
expect(() => deriveId(DNS_NAMESPACE, 'a\uD800')).toThrow(TypeError);
expect(deriveId(DNS_NAMESPACE, '😀')).toMatch(/^[0-9a-f-]{36}$/);
});

it('refuses a namespace that is not a UUID', () => {
for (const namespace of [
'',
'not-a-uuid',
'6ba7b8109dad11d180b400c04fd430c8',
]) {
expect(() => deriveId(namespace, 'a')).toThrow(TypeError);
}
});
});
39 changes: 39 additions & 0 deletions packages/app-connect/src/once/derive-id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { createHash } from 'node:crypto';
import { isWellFormed } from './store';

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

/**
* A name-based id (RFC 9562 version 5 UUID): the same namespace and name
* always give the same id, and different names give different ids.
*
* Use it for ids that must not change across retries, such as a once key, an
* idempotency key sent to a vendor, or the id of a record written for an
* outside event: `deriveId(MY_APP_NAMESPACE, storeId + ':sale:' + paymentId)`.
* Pick one random namespace UUID per app and never change it, or every
* derived id changes with it.
*
* @param namespace A UUID, in the usual 8-4-4-4-12 hex form
* @param name Any string; it is hashed as UTF-8
* @returns A lowercase UUID string
*/
export function deriveId(namespace: string, name: string): string {
if (!UUID.test(namespace)) {
throw new TypeError('deriveId: the namespace must be a UUID');
}
if (!isWellFormed(name)) {
// A lone surrogate hashes as U+FFFD, so two names would share an id.
throw new TypeError(
'deriveId: the name must be well-formed text (no lone surrogates)',
);
}
const hash = createHash('sha1')
.update(Buffer.from(namespace.replace(/-/g, ''), 'hex'))
.update(name, 'utf8')
.digest();
const bytes = hash.subarray(0, 16);
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
const hex = bytes.toString('hex');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
28 changes: 28 additions & 0 deletions packages/app-connect/src/once/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export {
DEFAULT_LEASE_MS,
OnceNotRecordedError,
type OnceOptions,
type OnceResult,
Refused,
once,
} from './once';
export {
MAX_KEY_LENGTH,
MAX_REASON_LENGTH,
type OnceClaim,
OnceClaimLostError,
type OnceOutcome,
type OnceStore,
} from './store';
export {
type MemoryOnceStoreOptions,
createMemoryOnceStore,
} from './memory-store';
export {
DEFAULT_ONCE_TABLE,
type MysqlOnceStoreOptions,
type SqlQueryRunner,
createMysqlOnceStore,
onceTableDdl,
} from './mysql-store';
export { deriveId } from './derive-id';
7 changes: 7 additions & 0 deletions packages/app-connect/src/once/memory-store.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { describe } from 'vitest';
import { createMemoryOnceStore } from './memory-store';
import { onceStoreContract } from './store-contract.test-helper';

describe('memory once store', () => {
onceStoreContract((now) => createMemoryOnceStore({ now }));
});
78 changes: 78 additions & 0 deletions packages/app-connect/src/once/memory-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { randomUUID } from 'node:crypto';
import {
type OnceClaim,
OnceClaimLostError,
type OnceOutcome,
type OnceStore,
checkClaim,
checkOutcome,
trimReason,
} from './store';

type Entry =
| { state: 'claimed'; token: string; leaseUntil: number }
| { state: 'done' }
| { state: 'refused'; reason?: string };

export interface MemoryOnceStoreOptions {
/** Unix milliseconds. Injected so tests control time. */
now?: () => number;
}

/**
* A `OnceStore` held in this process's memory. Claims hold only inside one
* process, are lost on restart, and finished keys are never forgotten, so use
* it for tests and local runs only. Use the MySQL store in an app.
*/
export function createMemoryOnceStore(
options: MemoryOnceStoreOptions = {},
): OnceStore {
const now = options.now ?? Date.now;
const entries = new Map<string, Entry>();

return {
async claim(key: string, leaseMs: number): Promise<OnceClaim> {
checkClaim(key, leaseMs);
const at = now();
const entry = entries.get(key);
if (entry?.state === 'done') {
return { status: 'done' };
}
if (entry?.state === 'refused') {
return { status: 'refused', reason: entry.reason };
}
// A new key, or a claim whose lease has passed, is claimed.
if (entry === undefined || entry.leaseUntil < at) {
const token = randomUUID();
entries.set(key, { state: 'claimed', token, leaseUntil: at + leaseMs });
return { status: 'claimed', token };
}
return { status: 'in_flight' };
},

async complete(
key: string,
token: string,
outcome: OnceOutcome,
): Promise<void> {
checkOutcome(outcome);
const entry = entries.get(key);
if (entry?.state !== 'claimed' || entry.token !== token) {
throw new OnceClaimLostError(key);
}
entries.set(
key,
outcome.status === 'done'
? { state: 'done' }
: { state: 'refused', reason: trimReason(outcome.reason) },
);
},

async release(key: string, token: string): Promise<void> {
const entry = entries.get(key);
if (entry?.state === 'claimed' && entry.token === token) {
entries.delete(key);
}
},
};
}
Loading