diff --git a/README.md b/README.md index e984d9e..1c68705 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ Source for the UsageRail SDKs. They check API keys, apply rate limits and quotas Setup guides and the API reference are at [usagerail.com/docs](https://usagerail.com/docs). +If you use a coding agent, [skills/add-usagerail/SKILL.md](skills/add-usagerail/SKILL.md) is an agent skill that walks it through adding the SDK to an existing API. + ## Issues and pull requests Both are welcome here. The SDKs are developed in UsageRail's main codebase, next to the service they talk to, and this repository is published from there. An accepted pull request is applied upstream and comes back here with the next sync, credited to you. diff --git a/skills/add-usagerail/SKILL.md b/skills/add-usagerail/SKILL.md new file mode 100644 index 0000000..ab2fffe --- /dev/null +++ b/skills/add-usagerail/SKILL.md @@ -0,0 +1,143 @@ +--- +name: add-usagerail +description: Add API keys, per-customer rate limits, quotas and usage metering to a Node.js or Python API server with the UsageRail SDK. Use when someone wants to sell access to their API, charge by usage through their own Stripe account, or keep one customer from using up their API. +metadata: + tags: "api, api-keys, rate-limiting, usage-billing, stripe, fastapi, express, django, flask, hono" +--- + +# Add UsageRail to an API + +UsageRail's SDK checks API keys, applies rate limits and quotas, and counts usage per customer inside the user's own API server. Requests never pass through UsageRail. Counts go to UsageRail in the background: every 60 seconds on a long-running server, and after each response in Next.js. + +## Before you change anything + +1. Find the framework. The SDKs cover Express, Hono, Fastify and Next.js on Node.js 22+, and FastAPI, Starlette, Flask and Django on Python 3.10+. For other languages, use the HTTP check endpoint described at https://usagerail.com/docs. It adds one network call per request. +2. Ask how callers authenticate today. With no keys yet, use `auth: "api-key"` and UsageRail issues the keys. With existing keys or logins, use `auth: "custom"` with a `consumer` function. In Node.js it returns `{ id }` for the caller, or `null` for anonymous traffic. In Python it returns the customer's ID as a string, or `None`. A bare string returned in Node.js is counted as anonymous. Return an identity the app's own code has verified, never a value the caller can set, such as a plain header. UsageRail has to run after that authentication: in Express, `app.use(usageRail(...))` goes after the auth middleware. In FastAPI the identity must come from an authentication middleware, not `Depends(...)`, and since FastAPI runs the middleware added last first, add the auth middleware after the line that adds UsageRail. In Django, list UsageRail after `AuthenticationMiddleware`. Django REST framework token or JWT authentication runs inside the view, after all middleware, so a consumer that reads `request.user` sees anonymous traffic: verify the token in the consumer function or in an earlier middleware. In Flask, register the app's own `before_request` hook first. +3. List the routes that must answer without a UsageRail key, such as health checks, webhook receivers and browsers' CORS preflight (`OPTIONS`) requests. With `auth: "api-key"`, any request UsageRail sees without a valid key gets a 401. In Express, mount it on the paid API's path, `app.use("/v1", usageRail(...))`, and register the CORS middleware before it. In FastAPI, add `CORSMiddleware` after the line that adds UsageRail, so it runs first. In Django, list the CORS middleware above UsageRail. Where the framework can't leave a route out, as with FastAPI, Flask and Django, tell the user which routes will start asking for a key. Once it's wired in, call each of those routes without a key and check that it still answers. +4. The user needs an app key from https://app.usagerail.com. Read it from the `USAGERAIL_APP_KEY` environment variable. Never write the key into source code, and never ask the user to paste it into the chat. + +## Wire it in + +Every request counts as 1 by default. The `track()` calls below only change that once the app counts units, which is set in the console under Settings > What counts as usage. While the app counts requests, `track()` does nothing. + +### FastAPI or Starlette + +```bash +pip install usagerail +``` + +```python +import os + +from fastapi import FastAPI, Request +from usagerail.fastapi import UsageRailMiddleware + +app = FastAPI() +app.add_middleware(UsageRailMiddleware, app_key=os.environ["USAGERAIL_APP_KEY"], auth="api-key") + + +@app.post("/v1/generate") +async def generate(request: Request): + result = await run_model(await request.json()) + request.state.usagerail.track(result.tokens) # optional: count tokens instead of requests + return result.body +``` + +### Flask + +```python +import os + +from flask import Flask +from usagerail.flask import UsageRail + +app = Flask(__name__) +UsageRail(app, app_key=os.environ["USAGERAIL_APP_KEY"], auth="api-key") +``` + +Inside a route, `g.usagerail.track(n)` counts custom units. + +### Django + +```python +# settings.py +import os + +MIDDLEWARE = [ + # ... + "usagerail.django.UsageRailMiddleware", +] +USAGERAIL = {"app_key": os.environ["USAGERAIL_APP_KEY"], "auth": "api-key"} +``` + +Inside a view, `request.usagerail.track(n)` counts custom units. + +Under uvicorn or another ASGI server, wrap the application in `asgi.py`, or every restart loses the counts that hadn't gone out yet: + +```python +import os + +from django.core.asgi import get_asgi_application +from usagerail.django import asgi + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +application = asgi(get_asgi_application()) +``` + +### Express + +```bash +npm install @usagerail/node +``` + +```js +import express from "express"; +import { usageRail } from "@usagerail/node/express"; + +const app = express(); + +app.use(usageRail({ + appKey: process.env.USAGERAIL_APP_KEY, + auth: "api-key", +})); + +app.post("/v1/generate", express.json(), async (req, res) => { + const result = await generate(req.body); + req.usageRail.track(result.tokens); // optional: count tokens + res.json(result); +}); +``` + +Hono and Fastify have their own entry points: `@usagerail/node/hono` and `@usagerail/node/fastify`. Hono on Node.js doesn't flush on its own: also call `flushOnExit(rail.engine)` from `@usagerail/node/node`, or counts not yet sent are lost when the process stops. Follow the framework's page in the docs for the full setup. + +On SIGTERM the Express middleware sends what's left, waiting at most 5 seconds, then lets the process exit. If the app handles SIGTERM itself, keep the value `usageRail()` returned and finish the app's own shutdown with `await middleware.engine.close()`. + +## How callers send their key + +In the `Authorization: Bearer ` header, or in `x-api-key` when there's no bearer token. + +## What rejected requests look like + +| Status | Meaning | +|---|---| +| 401 | Unknown or revoked key | +| 402 | Prepaid credit used up | +| 403 | Suspended customer | +| 429 | Rate limit or quota reached | +| 503 | UsageRail unreachable, and the app is set to refuse | + +Update the API's own docs and client error handling for these. + +## Tell the user before they deploy + +- Rate limits and quotas come from plans, set up in the console. Until the user makes a free plan the default (Make default) or moves customers onto a plan, customers have no rate limit or quota. Once that's done, go over a limit with a test key and check for the 429. +- Rate limits are counted per server instance by default. +- The Express middleware and the Python SDK don't check or count WebSocket connections. Hono counts a successful handshake once, and so does Fastify with `@fastify/websocket`. +- On a long-running server, counts are sent every 60 seconds. A process killed with `kill -9` or by running out of memory loses the counts it hadn't sent, and they're never billed. +- With Express and Fastify, and Hono with `flushOnExit`, the SDK sends the remaining counts on SIGTERM and when the process exits on its own. SIGINT (Ctrl+C) and a direct `process.exit()` skip that, so an app that stops another way should `await engine.close()` before it exits. +- Next.js has no background timer or exit hook: pass `waitUntil: after` from `next/server` (or `waitUntil` from `@vercel/functions`) so the counts go out after each response. See https://usagerail.com/docs/nextjs. +- In Python, FastAPI sends them during lifespan shutdown, and Flask and Django when the process exits normally, as under gunicorn. Django under uvicorn or another ASGI server needs the `asgi.py` wrapper above. +- To charge customers, the user connects their own Stripe account. Money goes straight there, and UsageRail is not a merchant of record. + +Setup for each framework, options and known limitations: [UsageRail docs](https://usagerail.com/docs)