Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Keep the first response for an Idempotency-Key, and fix four API details

Claudecdf437d9ba4f
diff --git a/docs/api.md b/docs/api.md
index 6000484..fb1ace4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -80,6 +80,7 @@ Every error has the same shape, and the code is meant for your program:
| 422 | `idempotency_key_reused` | An `Idempotency-Key` was used before with a different request. |
| 429 | `rate_limited` | Too many requests. Wait the number of seconds in `Retry-After`. |
| 500 | `internal_error` | Something went wrong on the install. Try again later. |
+| 503 | `internal_error` | Email is not set up on the install yet, so nothing was sent. Try again once it is. |
## Rate limits
diff --git a/src/lib/api/envelopes.ts b/src/lib/api/envelopes.ts
index 6f04f7a..b644f8d 100644
--- a/src/lib/api/envelopes.ts
+++ b/src/lib/api/envelopes.ts
@@ -680,7 +680,9 @@ export async function listApiEnvelopeEvents(
created_at AS "createdAt"
FROM audit_events
WHERE envelope_id = $1
- ORDER BY sequence ASC
+ -- Events from before the audit chain have no sequence and come
+ -- first, in the same order as the envelope's audit trail.
+ ORDER BY sequence ASC NULLS FIRST, created_at ASC, id ASC
`,
[envelopeId],
);
diff --git a/src/lib/api/idempotency.ts b/src/lib/api/idempotency.ts
index 7759573..955e1dd 100644
--- a/src/lib/api/idempotency.ts
+++ b/src/lib/api/idempotency.ts
@@ -126,16 +126,27 @@ export type IdempotencyReservation = {
reservedAt: number;
};
-/** Keeps the response for retries. */
+/** A response kept for a key, which retries get again. */
+export type KeptResponse = { response: unknown; statusCode: number };
+
+/**
+ * Keeps the response for retries, unless one is kept already. A retry can
+ * answer from the envelope while the first request is still finishing, so
+ * two requests may finish one reservation: the first to do so is kept, and
+ * the other gets that response back here to answer with instead, so every
+ * answer under the key is the same. Null when this response was kept, or
+ * the reservation is gone.
+ */
export async function completeIdempotencyKey(
- input: IdempotencyReservation & { response: unknown; statusCode: number },
+ input: IdempotencyReservation & KeptResponse,
database: DbExecutor = getDb(),
-) {
- await database.query(
+): Promise<KeptResponse | null> {
+ const completed = await database.query(
`
UPDATE api_idempotency
SET status_code = $4, response = $5
WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at = $3
+ AND status_code IS NULL
`,
[
input.apiKeyId,
@@ -145,6 +156,23 @@ export async function completeIdempotencyKey(
JSON.stringify(input.response),
],
);
+
+ if ((completed.rowCount ?? 0) === 1) {
+ return null;
+ }
+
+ // Under READ COMMITTED a completion that waited on the other one sees it
+ // committed, so it is there to read.
+ return queryOne<KeptResponse>(
+ database,
+ `
+ SELECT status_code AS "statusCode", response
+ FROM api_idempotency
+ WHERE api_key_id = $1 AND idempotency_key = $2 AND created_at = $3
+ AND status_code IS NOT NULL
+ `,
+ [input.apiKeyId, input.key, input.reservedAt],
+ );
}
/**
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index c062863..b587f3b 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -27,6 +27,15 @@ const errors = {
"500": errorResponse,
};
+// For the calls that email signers: 503 when the install has no email yet.
+const emailErrors = {
+ ...errors,
+ "503": {
+ ...errorResponse,
+ description: "Email is not set up on the install yet, so nothing was sent.",
+ },
+};
+
const envelopeResponse = (description: string) => ({
content: {
"application/json": { schema: { $ref: "#/components/schemas/Envelope" } },
@@ -436,7 +445,7 @@ export function buildOpenApiDocument(
"201": envelopeResponse("The envelope, sent if send was given."),
"413": errorResponse,
"422": errorResponse,
- ...errors,
+ ...emailErrors,
},
summary: "Create an envelope, and send it if asked",
},
@@ -529,7 +538,10 @@ export function buildOpenApiDocument(
"/envelopes/{id}/remind": {
post: {
parameters: [idParameter],
- responses: { "200": envelopeResponse("The envelope."), ...errors },
+ responses: {
+ "200": envelopeResponse("The envelope."),
+ ...emailErrors,
+ },
summary: "Remind each signer whose turn it is",
},
},
@@ -548,7 +560,7 @@ export function buildOpenApiDocument(
"200": envelopeResponse("The envelope, now sent."),
"413": errorResponse,
"422": errorResponse,
- ...errors,
+ ...emailErrors,
},
summary: "Send a draft",
},
@@ -560,7 +572,9 @@ export function buildOpenApiDocument(
content: {
"application/json": {
schema: {
- properties: { reason: { maxLength: 1000, type: "string" } },
+ properties: {
+ reason: { maxLength: 1000, type: ["string", "null"] },
+ },
type: "object",
},
},
@@ -679,7 +693,7 @@ export function buildOpenApiDocument(
"201": envelopeResponse("The new envelope."),
"413": errorResponse,
"422": errorResponse,
- ...errors,
+ ...emailErrors,
},
summary: "Create an envelope from a template",
},
diff --git a/src/lib/api/route.dbtest.ts b/src/lib/api/route.dbtest.ts
index 9340c60..17b7b0a 100644
--- a/src/lib/api/route.dbtest.ts
+++ b/src/lib/api/route.dbtest.ts
@@ -27,12 +27,18 @@ registerHooks({
},
});
-let database: pg.Pool;
+let database: pg.Pool | undefined;
let replaced: pg.Pool | null = null;
let route: typeof RouteModule;
const createdUsers: string[] = [];
const createdKeys: string[] = [];
+/** The test database, once `before` has opened it. */
+function db(): pg.Pool {
+ assert.ok(database, "The test database did not open.");
+ return database;
+}
+
before(async () => {
database = await openTestDatabase();
replaced = replaceDbPoolForTests(database);
@@ -40,16 +46,27 @@ before(async () => {
});
after(async () => {
- // api_idempotency has no foreign key to the key, so its rows go first.
- await database.query(
- `delete from public.api_idempotency where api_key_id = any($1)`,
- [createdKeys],
- );
- await database.query(`delete from public."user" where id = any($1)`, [
- createdUsers,
- ]);
- replaceDbPoolForTests(replaced ?? database);
- await database.end();
+ // Nothing to clean up if the database never opened, and its own error
+ // is the one that matters.
+ if (!database) {
+ return;
+ }
+
+ const pool = database;
+
+ try {
+ // api_idempotency has no foreign key to the key, so its rows go first.
+ await pool.query(
+ `delete from public.api_idempotency where api_key_id = any($1)`,
+ [createdKeys],
+ );
+ await pool.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ } finally {
+ replaceDbPoolForTests(replaced ?? pool);
+ await pool.end();
+ }
});
async function createContext(idempotencyKey: string) {
@@ -57,7 +74,7 @@ async function createContext(idempotencyKey: string) {
const email = `${id}@example.test`;
createdUsers.push(id);
- await database.query(
+ await db().query(
`
insert into public."user" (id, name, email, role, "emailVerified")
values ($1, $2, $3, 'admin', true)
@@ -68,7 +85,7 @@ async function createContext(idempotencyKey: string) {
const { summary } = await createApiKey(
{ email, userId: id },
{ expiresInDays: null, name: "Route test", scope: "write" },
- database,
+ db(),
);
createdKeys.push(summary.id);
@@ -117,12 +134,113 @@ test("a request whose envelope could not be noted keeps its key, so a retry cann
key,
requestHash: hashRequest("POST /api/v1/envelopes", body),
},
- database,
+ db(),
),
{ kind: "in_progress" },
);
});
+test(
+ "a retry answering from the envelope does not replace the response the first request kept",
+ {
+ timeout: 10_000,
+ },
+ async () => {
+ const key = `order-${randomUUID()}`;
+ const context = await createContext(key);
+ const body = '{"title":"Lease"}';
+ let recoveryStarted!: () => void;
+ const recovering = new Promise<void>((resolve) => {
+ recoveryStarted = resolve;
+ });
+ let letRecoveryFinish!: () => void;
+ const recoveryMayFinish = new Promise<void>((resolve) => {
+ letRecoveryFinish = resolve;
+ });
+ let retry: Promise<Response> | undefined;
+
+ const first = await route.runIdempotently(
+ context,
+ "POST /api/v1/envelopes",
+ body,
+ async (remember) => {
+ await remember("envelope-1");
+
+ // A retry comes in now. The envelope is noted and no response is
+ // kept yet, so it answers from the envelope, and finishes only after
+ // this request has kept its own response.
+ retry = route.runIdempotently(
+ context,
+ "POST /api/v1/envelopes",
+ body,
+ () => Promise.reject(new Error("A retry must not make an envelope.")),
+ async () => {
+ recoveryStarted();
+ await recoveryMayFinish;
+
+ return { body: { from: "retry" }, status: 201 };
+ },
+ );
+ await recovering;
+
+ return { body: { from: "first" }, status: 201 };
+ },
+ );
+
+ letRecoveryFinish();
+
+ const second = await retry!;
+
+ assert.equal(first.status, 201);
+ assert.deepEqual(await first.json(), { from: "first" });
+ assert.equal(second.status, 201);
+ assert.equal(second.headers.get("idempotent-replayed"), "true");
+ assert.deepEqual(await second.json(), { from: "first" });
+ assert.deepEqual(
+ await claimIdempotencyKey(
+ {
+ apiKeyId: context.actor.apiKeyId,
+ key,
+ requestHash: hashRequest("POST /api/v1/envelopes", body),
+ },
+ db(),
+ ),
+ { kind: "replay", response: { from: "first" }, statusCode: 201 },
+ );
+ },
+);
+
+test("a first request that finishes after a retry answered for it gives the answer the retry kept", async () => {
+ const key = `order-${randomUUID()}`;
+ const context = await createContext(key);
+ const body = '{"title":"Lease"}';
+
+ const first = await route.runIdempotently(
+ context,
+ "POST /api/v1/envelopes",
+ body,
+ async (remember) => {
+ await remember("envelope-2");
+
+ const retried = await route.runIdempotently(
+ context,
+ "POST /api/v1/envelopes",
+ body,
+ () => Promise.reject(new Error("A retry must not make an envelope.")),
+ async () => ({ body: { from: "retry" }, status: 201 }),
+ );
+
+ assert.deepEqual(await retried.json(), { from: "retry" });
+
+ return { body: { from: "first" }, status: 201 };
+ },
+ );
+
+ assert.equal(first.status, 201);
+ assert.equal(first.headers.get("idempotent-replayed"), null);
+ assert.deepEqual(await first.json(), { from: "retry" });
+});
+
test("a request that fails before making anything lets its key go", async () => {
const key = `order-${randomUUID()}`;
const context = await createContext(key);
@@ -140,7 +258,7 @@ test("a request that fails before making anything lets its key go", async () =>
key,
requestHash: hashRequest("POST /api/v1/envelopes", body),
},
- database,
+ db(),
);
assert.equal(claim.kind, "new");
diff --git a/src/lib/api/route.ts b/src/lib/api/route.ts
index 439f8dc..71dbe20 100644
--- a/src/lib/api/route.ts
+++ b/src/lib/api/route.ts
@@ -260,20 +260,21 @@ export async function runIdempotently(
}
const recovered = await runCatching(() => recover(previous.resourceId));
-
- if (isKept(recovered.status)) {
- await completeIdempotencyKey({
- apiKeyId: claim.apiKeyId,
- key,
- reservedAt: previous.reservedAt,
- response: recovered.body,
- statusCode: recovered.status,
- });
- }
-
- return apiJson(recovered.body, {
+ // The first request may have finished meanwhile. Its response is then
+ // the one kept, and the answer here too.
+ const kept = isKept(recovered.status)
+ ? await completeIdempotencyKey({
+ apiKeyId: claim.apiKeyId,
+ key,
+ reservedAt: previous.reservedAt,
+ response: recovered.body,
+ statusCode: recovered.status,
+ })
+ : null;
+
+ return apiJson(kept ? kept.response : recovered.body, {
headers: { "idempotent-replayed": "true" },
- status: recovered.status,
+ status: kept ? kept.statusCode : recovered.status,
});
}
case "new":
@@ -315,11 +316,17 @@ export async function runIdempotently(
}
if (isKept(result.status)) {
- await completeIdempotencyKey({
+ // A retry may have answered from the envelope first. Its response is
+ // then the one kept, and the answer here too.
+ const kept = await completeIdempotencyKey({
...reservation,
response: result.body,
statusCode: result.status,
});
+
+ if (kept) {
+ return apiJson(kept.response, { status: kept.statusCode });
+ }
} else if (!made) {
await releaseIdempotencyKey(reservation).catch(() => undefined);
}