mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted stack reads its tenant portfolio from Paperclip Cloud
through `GET /api/cloud/stacks`
> - Paperclip Cloud can answer that read with 429 when it throttles a
stack
> - The proxy changed every non-OK upstream status into a 502, and the
error handler reports every 5xx to Sentry
> - So Cloud backpressure showed up as a server crash on a staging stack
(`upstreamStatus=429`, `phase=http_response`)
> - This pull request passes an upstream 429 through as a 429 with a
bounded `Retry-After` hint
> - The benefit is a correct status for clients and no false crash
reports for throttling
## Linked Issues or Issue Description
Refs #15340 (bounded Cloud portfolio diagnostics), Refs #19033 (retry
one Cloud portfolio connection reset).
**What happened?**
A hosted staging stack reported "Paperclip Cloud portfolio request
failed" to Sentry. The diagnostics show `upstreamStatus=429` after 44
ms. Cloud throttled the read, and the proxy answered 502 and reported a
crash.
**What did you expect to happen?**
The proxy tells the client that Cloud is rate limiting the read. It does
not report a server fault.
**Steps to reproduce**
Make the Cloud tenant portfolio endpoint answer 429, then call `GET
/api/cloud/stacks`. Before this change the route answers 502
`cloud_portfolio_upstream_error` and reports to Sentry.
## What Changed
- `server/src/routes/cloud.ts`: an upstream 429 now gives 429
`cloud_portfolio_rate_limited`.
- The route copies Cloud's `Retry-After` as whole seconds. It accepts
delta seconds or an HTTP-date and clamps the value to 1–300 seconds. It
omits the header when the value is missing or malformed.
- The route logs the bounded diagnostics at warn level. It does not
report the 429 to Sentry and does not cache the throttled answer.
- 401, 403, 503 and the other failure phases keep the 502 contract and
the crash report.
- `server/src/__tests__/cloud-routes.test.ts`: new cases for the 429
status, the `Retry-After` forms, no Sentry report, and no cache entry.
- `docs/api/cloud.md` (new, in the API Reference nav): documents `GET
/api/cloud/stacks`, its error codes, and the 429 with its bounded
`Retry-After`.
- `server/src/routes/openapi.ts`: the `/api/cloud/stacks` entry now
lists the 429 response.
## Verification
- Red: with the old `cloud.ts`, `cloud-routes.test.ts` gave 5 failed
(the new 429 cases) and 23 passed.
- Green: `cd server && npx vitest run src/__tests__/cloud-routes.test.ts
src/__tests__/sentry.test.ts src/__tests__/cloud-portfolio-error.test.ts
src/__tests__/run-failure-sentry-real-sdk.test.ts` gave 68 passed and 18
skipped.
- `npx tsc --noEmit -p server/tsconfig.json` shows no errors in the
changed files.
- After review fixes (6a8f146c55): `cd server && npx vitest run
src/__tests__/cloud-routes.test.ts src/__tests__/openapi-routes.test.ts`
gave 80 passed.
## Risks
- Low risk. Only the 429 path changes.
- The two UI consumers (`useCloudInviteUrl`, `CompanyAccess`) treat any
error the same way, so the UI needs no change.
## Model Used
- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use and code execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
174 lines
5.9 KiB
TypeScript
174 lines
5.9 KiB
TypeScript
import { Router } from "express";
|
|
import { forbidden, HttpError, notFound } from "../errors.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { CloudPortfolioError, type CloudPortfolioPhase } from "../services/cloud-portfolio-error.js";
|
|
import {
|
|
getCloudStackContext,
|
|
type CloudInstanceEnv,
|
|
} from "../services/cloud-instance.js";
|
|
|
|
const DEFAULT_PORTFOLIO_CACHE_TTL_MS = 30_000;
|
|
const CLOUD_PORTFOLIO_PATH = "/v1/tenant/portfolio";
|
|
const RETRYABLE_FETCH_RESET_CODES = new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
|
|
|
|
const MAX_RETRY_AFTER_SECONDS = 300;
|
|
|
|
type PortfolioCacheEntry = {
|
|
expiresAt: number;
|
|
payload: unknown;
|
|
};
|
|
|
|
function retryAfterSeconds(value: string | null, currentTime: number): number | null {
|
|
const trimmed = value?.trim();
|
|
if (!trimmed) return null;
|
|
const seconds = /^\d+$/.test(trimmed)
|
|
? Number(trimmed)
|
|
: Math.ceil((Date.parse(trimmed) - currentTime) / 1000);
|
|
if (!Number.isFinite(seconds)) return null;
|
|
return Math.min(Math.max(seconds, 1), MAX_RETRY_AFTER_SECONDS);
|
|
}
|
|
|
|
export function cloudRoutes(opts: {
|
|
runtimeEnv?: CloudInstanceEnv;
|
|
fetchImpl?: typeof fetch;
|
|
now?: () => number;
|
|
cacheTtlMs?: number;
|
|
} = {}) {
|
|
const router = Router();
|
|
const runtimeEnv = opts.runtimeEnv ?? process.env;
|
|
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
const now = opts.now ?? Date.now;
|
|
const cacheTtlMs = opts.cacheTtlMs ?? DEFAULT_PORTFOLIO_CACHE_TTL_MS;
|
|
const portfolioCache = new Map<string, PortfolioCacheEntry>();
|
|
|
|
router.get("/stacks", async (req, res) => {
|
|
const context = getCloudStackContext(runtimeEnv);
|
|
if (!context) {
|
|
throw notFound("Cloud stack portfolio is unavailable");
|
|
}
|
|
if (req.actor.source !== "cloud_tenant" || !req.actor.userId?.trim()) {
|
|
throw forbidden("Trusted Cloud tenant access required", {
|
|
code: "cloud_tenant_required",
|
|
});
|
|
}
|
|
|
|
const tenantToken = runtimeEnv.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN?.trim();
|
|
if (!context.cloudOrigin || !context.stackId || !tenantToken) {
|
|
throw new HttpError(503, "Paperclip Cloud portfolio is not configured", {
|
|
code: "cloud_portfolio_not_configured",
|
|
});
|
|
}
|
|
|
|
const actorUserId = req.actor.userId.trim();
|
|
const cacheKey = `${context.cloudOrigin}\n${context.stackId}\n${actorUserId}`;
|
|
const currentTime = now();
|
|
for (const [key, entry] of portfolioCache) {
|
|
if (entry.expiresAt <= currentTime) portfolioCache.delete(key);
|
|
}
|
|
const cached = portfolioCache.get(cacheKey);
|
|
if (cached) {
|
|
res.setHeader("Cache-Control", "no-store");
|
|
res.json(cached.payload);
|
|
return;
|
|
}
|
|
|
|
let portfolioUrl: URL;
|
|
try {
|
|
portfolioUrl = new URL(CLOUD_PORTFOLIO_PATH, context.cloudOrigin);
|
|
} catch {
|
|
throw new HttpError(503, "Paperclip Cloud portfolio is not configured", {
|
|
code: "cloud_portfolio_not_configured",
|
|
});
|
|
}
|
|
|
|
const startedAt = performance.now();
|
|
let phase: CloudPortfolioPhase = "fetch";
|
|
let upstreamStatus: number | null = null;
|
|
let upstreamSignal: AbortSignal | undefined;
|
|
const portfolioError = (kind: "upstream" | "invalid_response", error?: unknown) => {
|
|
const reportableError = new CloudPortfolioError(kind, {
|
|
phase,
|
|
elapsedMs: performance.now() - startedAt,
|
|
upstreamStatus,
|
|
deadlineExceeded: upstreamSignal?.aborted === true,
|
|
}, error);
|
|
// Preserve the route callsite instead of grouping by this helper frame.
|
|
Error.captureStackTrace?.(reportableError, portfolioError);
|
|
return reportableError;
|
|
};
|
|
|
|
try {
|
|
upstreamSignal = AbortSignal.timeout(10_000);
|
|
let upstream: Response;
|
|
for (let attempt = 1; ; attempt++) {
|
|
try {
|
|
upstream = await fetchImpl(portfolioUrl, {
|
|
method: "GET",
|
|
headers: {
|
|
accept: "application/json",
|
|
authorization: `Bearer ${tenantToken}`,
|
|
"x-paperclip-cloud-user-id": actorUserId,
|
|
"x-paperclip-cloud-stack-id": context.stackId,
|
|
},
|
|
signal: upstreamSignal,
|
|
});
|
|
break;
|
|
} catch (error) {
|
|
const { diagnostics } = portfolioError("upstream", error);
|
|
if (attempt > 1 || !RETRYABLE_FETCH_RESET_CODES.has(String(diagnostics.networkCode))) throw error;
|
|
logger.warn(
|
|
{ cloudPortfolio: diagnostics },
|
|
"Paperclip Cloud portfolio connection reset; retrying once",
|
|
);
|
|
}
|
|
}
|
|
phase = "http_response";
|
|
upstreamStatus = upstream.status;
|
|
if (upstream.status === 429) {
|
|
logger.warn(
|
|
{ cloudPortfolio: portfolioError("upstream").diagnostics },
|
|
"Paperclip Cloud portfolio request rate limited",
|
|
);
|
|
const retryAfter = retryAfterSeconds(upstream.headers.get("retry-after"), now());
|
|
if (retryAfter !== null) res.setHeader("Retry-After", String(retryAfter));
|
|
throw new HttpError(429, "Paperclip Cloud portfolio is rate limited", {
|
|
code: "cloud_portfolio_rate_limited",
|
|
});
|
|
}
|
|
if (!upstream.ok) {
|
|
const error = portfolioError("upstream");
|
|
logger.warn(
|
|
{ cloudPortfolio: error.diagnostics },
|
|
"Paperclip Cloud portfolio request failed",
|
|
);
|
|
throw error;
|
|
}
|
|
|
|
phase = "response_body";
|
|
let payload: unknown;
|
|
try {
|
|
payload = await upstream.json();
|
|
} catch (error) {
|
|
throw portfolioError("invalid_response", error);
|
|
}
|
|
phase = "response_write";
|
|
portfolioCache.set(cacheKey, {
|
|
expiresAt: currentTime + cacheTtlMs,
|
|
payload,
|
|
});
|
|
res.setHeader("Cache-Control", "no-store");
|
|
res.json(payload);
|
|
} catch (error) {
|
|
if (error instanceof HttpError) throw error;
|
|
const reportableError = portfolioError("upstream", error);
|
|
logger.warn(
|
|
{ cloudPortfolio: reportableError.diagnostics },
|
|
"Paperclip Cloud portfolio request failed",
|
|
);
|
|
throw reportableError;
|
|
}
|
|
});
|
|
|
|
return router;
|
|
}
|