Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Server helper

Use createHoldEndpoint from @agentpost-tools/resourceshark-sdk/server to serve slots and hold requests from a browser or app. Use commitHold from the same entry point in your payment handler. Both run on your server with the project’s secret key.

Create a hold endpoint

Mount endpoint.handle(request, caller) at your app’s prefix, such as /api/booking. Authenticate the request in your app and pass the authenticated principal as caller. The workflow’s endpointTransport uses the same prefix. For a framework that handles routing itself, call slots, place, extend, release, or commit and send the returned EndpointAnswer as JSON at its status.

  • callerKey(caller) gives a stable, nonempty string for each principal. It can return a promise. The helper hashes the JSON pair of that key and the page’s trimmed attempt key with SHA-256. It sends the hex digest as Idempotency-Key. Your app’s sourceKey goes to ResourceShark as your hook returned it.
  • slots(query, caller) returns the slot query your app allows this principal to run.
  • place(input, caller) returns the hold request. Send its lines, sourceKey, and explicit ttl. Name scope.placeId on each line for a resource kept by place.
  • owns(hold, caller) is checked before each extend, release, and enabled commit, and on the hold a place call returns. An extend, release, or commit for a missing or unowned hold answers 404. If placement answers with a hold the principal does not own, the endpoint answers 409 duplicate_source without the hold. owns can receive a RetainedHold. Use a stored field such as sourceKey for ownership after retention removes the holder.
  • extend(hold, input, caller) returns an explicit ttl measured from the extension. Release needs only the ownership check.
  • commit(hold, input, caller) is optional. Supply it when a page can commit on its own, such as for a free booking. The hook returns the commit’s evidence, sourceKey, and any line quantities. Without this hook the endpoint answers 404 for commit.

This example serves one court at a place. It assigns each hold’s source key to the authenticated principal and their booking request ID. Pass the authenticated caller from your request handler to endpoint.handle. Put your app’s booking and hold rules in these hooks. Limit hold length and booking window checks a hold’s length and booking window on your server, and Cap a holder’s open holds limits how many holds a holder has open.

import {
  createHoldEndpoint,
  HoldRefusal,
} from '@agentpost-tools/resourceshark-sdk/server';

type Caller = { id: string };
type BookingRequest = { requestId: string; start: string; end: string };

export function bookingEndpoint(
  secretKey: string,
  court: { resourceId: string; placeId: string },
) {
  const prefixFor = ({ id }: Caller) => `booking:${encodeURIComponent(id)}:`;

  return createHoldEndpoint<Caller, BookingRequest>({
    secretKey,
    callerKey: ({ id }) => id,
    slots: ({ resourceId, from, to }) => {
      if (resourceId !== court.resourceId || !from || !to) {
        throw new HoldRefusal(
          'invalid_request',
          'Choose this court and a time range',
        );
      }
      return { resourceId, from, to, placeId: court.placeId };
    },
    place: (input, caller) => {
      if (
        typeof input?.requestId !== 'string' ||
        !/^[a-zA-Z0-9_-]{1,64}$/.test(input.requestId) ||
        typeof input.start !== 'string' ||
        typeof input.end !== 'string' ||
        !(Date.parse(input.start) < Date.parse(input.end))
      ) {
        throw new HoldRefusal(
          'invalid_request',
          'Send a booking ID and time range',
        );
      }
      return {
        lines: [
          {
            resourceId: court.resourceId,
            scope: { placeId: court.placeId },
            span: { start: input.start, end: input.end },
            quantity: 1,
          },
        ],
        ttl: '15m',
        sourceKey: `${prefixFor(caller)}${input.requestId}`,
      };
    },
    owns: (hold, caller) => hold.sourceKey.startsWith(prefixFor(caller)),
    extend: () => ({ ttl: '5m' }),
  });
}

Pass baseUrl or fetch to change the client connection. Set resourceCacheMs to reuse resource reads across placements. Its default is 0.

Wire format

Each path is relative to your app’s prefix. Each POST sends its attempt key as Idempotency-Key. The trimmed key must be 1 to 255 characters long. Send { input } as JSON for place, extend, and commit. Send {} when the input is undefined.

Method Path Request Success
GET /slots Query parameters 200 { slots, serverNow }
POST /holds { input } 201 { hold, serverNow }
POST /holds/:id/extend { input } 200 { hold, serverNow }
POST /holds/:id/release Empty body 200 { hold, serverNow }
POST /holds/:id/commit { input } 200 { hold, movements, serverNow } with duplicate: true when ResourceShark reports a replay

The slots query sends resourceId, from, and to. It includes placeId, condition, or instanceId when they apply. handle passes the query parameters as strings to the slots hook. Check the parameters there before returning a SlotsQuery.

Commit from a payment handler

Call commitHold(client, holdId, input, { idempotencyKey }) with the secret-key client. Pass the hold ID associated with the payment in your app. Supply your app’s evidence and sourceKey in input. The helper returns a CommitOutcome. A result with status: 'committed' carries the hold and its movements. It includes duplicate: true when ResourceShark reports a replay. A resolved result carries the first resolution. A failed result carries a WorkflowError.

An expired result gives expiresAt, the availability of each requested line, and allFit. Each line has enough to say whether its available quantity covers the requested quantity. If the answer has no lines, as happens after retention removes them, lines is null and allFit is false.

When the refusal includes lines, commitHold reads the expired hold to recover their spans. If that read fails or there are no positive quantities to consume, buy is null. Otherwise, call buy when your app decides to submit a separate consume. It sends each positive quantity with its scope and any recovered span. Pass your app’s evidence, sourceKey, and an idempotencyKey for the consume. You can reuse the commit’s sourceKey. Availability can change before buy runs. Handle the bought, short, and failed outcomes. Take a payment after a hold expired reads an expired commit and buys the same stock.

Errors

Throw HoldRefusal in a hook to return your app’s refusal to the page. The constructor takes code, message, optional status, optional details, and optional errorClass. The default status is 400, and the default class is change_the_request. The helper sends { error: { code, class, message, details?, docs? } }.

The helper passes these refusal details to the page.

  • insufficient_supply, exhausted_until_supply, and assignment_infeasible keep the short lines and any reported nextSupplyAt.
  • hold_expired and hold_resolved keep details when they name the hold authorized by owns for the action.

duplicate_source omits details. A duplicate_source answer from ResourceShark gets a generic message. The helper throws when it cannot reach ResourceShark, ResourceShark answers 401 or 403, or a hook throws an unexpected error. Handle those failures in your server. ResourceShark errors explains each code and what to do next.