Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/test_api_idempotency_limits.py8# Module : Tests9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Idempotency keys, tenant quotas, per-key rate limit and request size limits."""42import asyncio43import json4445import pytest46from apihelpers import assert_error, client_for, db, make_key, wait_job4748pytestmark = pytest.mark.pg495051async def test_idempotency_key_replays_the_same_job(stack):52 c = stack.client53 body = {"url": stack.url("/about"), "render": "http"}54 h = {"Idempotency-Key": "order-42"}55 first = await c.post("/v1/scrape", json=body, headers=h)56 assert first.status_code == 202 and "idempotent_replay" not in first.json()57 jid = first.json()["job_id"]58 second = await c.post("/v1/scrape", json=body, headers=h)59 assert second.status_code == 202 and second.json()["job_id"] == jid and second.json()["idempotent_replay"] is True60 assert second.headers["location"] == first.headers["location"] == f"/v1/jobs/{jid}"61 # the same request written differently (key order, defaults spelled out) is the same request62 same = {"render": "http", "priority": 5, "timeout_s": 60, "url": stack.url("/about"), "metadata": {},63 "policy": {"respect_robots_txt": True}}64 third = await c.post("/v1/scrape", content=json.dumps(same), headers=h | {"content-type": "application/json"})65 assert third.status_code == 202 and third.json()["job_id"] == jid and third.json()["idempotent_replay"] is True66 assert await db(stack, "select count(*) from jobs", one=True) == 167 assert await db(stack, "select count(*) from urls", one=True) == 168 assert await db(stack, "select value from usage_counters where metric='jobs'", one=True) == 169 # a different request under the same key is a conflict, on any route70 for route, other in (("/v1/scrape", body | {"priority": 6}), ("/v1/scrape", {"url": stack.url("/legal"), "render": "http"}),71 ("/v1/crawl", body), ("/v1/map", {"url": stack.url("/about")})):72 assert_error(await c.post(route, json=other, headers=h), 409, "idempotency_conflict")73 assert await db(stack, "select count(*) from jobs", one=True) == 174 # without a key every submission is a new job; another key is another job75 a = (await c.post("/v1/scrape", json=body)).json()["job_id"]76 b = (await c.post("/v1/scrape", json=body, headers={"Idempotency-Key": "order-43"})).json()["job_id"]77 assert len({jid, a, b}) == 378 # a replay returns the job as it is now, finished or not, and never restarts it79 await stack.start_worker()80 done = await wait_job(c, jid)81 replay = (await c.post("/v1/scrape", json=body, headers=h)).json()82 assert replay["job_id"] == jid and replay["status"] == done["status"] == "succeeded"83 assert replay["finished_at"] == done["finished_at"]84 assert await db(stack, "select count(*) from tasks where job_id=$1", jid, one=True) == 1858687async def test_concurrent_duplicate_submissions_create_exactly_one_job(stack):88 c = stack.client89 for round_, route in enumerate(("/v1/scrape", "/v1/crawl")):90 body = {"url": stack.url("/about"), "render": "http"}91 rs = await asyncio.gather(*[c.post(route, json=body, headers={"Idempotency-Key": f"burst-{round_}"})92 for _ in range(10)])93 assert [r.status_code for r in rs] == [202] * 10, [r.text[:200] for r in rs if r.status_code != 202]94 assert len({r.json()["job_id"] for r in rs}) == 195 assert sum(1 for r in rs if not r.json().get("idempotent_replay")) == 1, "exactly one submission is the original"96 assert await db(stack, "select count(*) from jobs where idempotency_key=$1", f"burst-{round_}", one=True) == 197 assert await db(stack, "select count(*) from jobs", one=True) == 298 assert await db(stack, "select value from usage_counters where metric='jobs'", one=True) == 299 # concurrent duplicates with *different* bodies: one job, the others are conflicts100 rs = await asyncio.gather(*[c.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http", "priority": i % 2},101 headers={"Idempotency-Key": "burst-x"}) for i in range(10)])102 codes = sorted(r.status_code for r in rs)103 assert set(codes) == {202, 409} and codes.count(202) == 5, codes104 assert await db(stack, "select count(*) from jobs where idempotency_key='burst-x'", one=True) == 1105106107async def test_tenant_quota_max_active_jobs(stack):108 c = stack.client109 await db(stack, "update tenants set quotas = '{\"max_active_jobs\": 2}' where id=$1", stack.tenant_id)110 body = {"url": stack.url("/about"), "render": "http"}111 j1 = (await c.post("/v1/scrape", json=body, headers={"Idempotency-Key": "q1"})).json()["job_id"]112 assert (await c.post("/v1/scrape", json=body)).status_code == 202113 e = assert_error(await c.post("/v1/scrape", json=body), 429, "quota_exceeded")114 assert e["details"] == {"quota": "max_active_jobs", "limit": 2}115 assert_error(await c.post("/v1/crawl", json=body), 429, "quota_exceeded")116 r = await c.post("/v1/batch", json={"items": [{"kind": "scrape", "request": body}]})117 assert r.json()["accepted"] == 0 and r.json()["items"][0]["error"]["code"] == "quota_exceeded"118 assert await db(stack, "select count(*) from jobs", one=True) == 2119 # replaying an accepted submission is not a new job and is not counted against the quota120 assert (await c.post("/v1/scrape", json=body, headers={"Idempotency-Key": "q1"})).json()["job_id"] == j1121 assert (await c.get("/v1/usage")).json()["quotas"]["max_active_jobs"] == 2122 # another tenant is not affected123 from apihelpers import make_tenant124 _, _, b = await make_tenant(stack)125 assert (await b.post("/v1/scrape", json=body)).status_code == 202126 # a finished (here: cancelled) job frees a slot127 assert (await c.post(f"/v1/jobs/{j1}/cancel")).json()["status"] == "cancelled"128 assert (await c.post("/v1/scrape", json=body)).status_code == 202129 assert_error(await c.post("/v1/scrape", json=body), 429, "quota_exceeded")130 # the quota holds under concurrency131 await db(stack, "update jobs set status='cancelled', finished_at=now() where tenant_id=$1", stack.tenant_id)132 rs = await asyncio.gather(*[c.post("/v1/scrape", json=body) for _ in range(10)])133 codes = sorted(r.status_code for r in rs)134 assert codes == [202] * 2 + [429] * 8, codes135 # daily quota136 await db(stack, "update tenants set quotas = '{\"max_jobs_per_day\": 1}' where id=$1", stack.tenant_id)137 e = assert_error(await c.post("/v1/scrape", json=body), 429, "quota_exceeded")138 assert e["details"]["quota"] == "max_jobs_per_day"139140141async def test_per_key_rate_limit(stack, monkeypatch):142 import time as real_time143144 import spider.api.app as app_mod145146 class Clock: # the limiter's clock, so that a slow machine cannot refill the bucket during the test147 now = 1000.0148 perf_counter = staticmethod(real_time.perf_counter)149150 @classmethod151 def monotonic(cls) -> float:152 return cls.now153 monkeypatch.setattr(app_mod, "time", Clock)154 monkeypatch.setattr(app_mod, "RATE_PER_MIN", 5)155 _, k1 = await make_key(stack, ["read"])156 _, k2 = await make_key(stack, ["read"])157 c1, c2 = client_for(stack, k1), client_for(stack, k2)158 codes = [(await c1.get("/v1/jobs")).status_code for _ in range(9)]159 assert codes == [200] * 5 + [429] * 4, codes160 e = assert_error(await c1.get("/v1/jobs"), 429, "rate_limited")161 assert e["details"]["retry_after_s"] >= 1162 assert_error(await c1.get("/v1/me"), 429, "rate_limited") # the limit is per key, not per route163 # another key has its own bucket; a dashboard session shares the bucket of its key164 assert (await c2.get("/v1/jobs")).status_code == 200165 browser = client_for(stack)166 assert (await browser.post("/v1/session", json={"api_key": k1})).status_code == 200167 assert_error(await browser.get("/v1/jobs"), 429, "rate_limited")168 # workers are paced by leases, not by the client limit169 w = client_for(stack, stack.worker_key)170 wid = (await w.post("/internal/v1/workers/register", json={"name": "w", "capabilities": ["http"]})).json()["worker_id"]171 assert [(await w.post(f"/internal/v1/workers/{wid}/heartbeat", json={})).status_code for _ in range(12)] == [200] * 12172 # the bucket refills at the configured rate: 5 per minute is one token every 12 seconds173 Clock.now += 11.0174 assert_error(await c1.get("/v1/jobs"), 429, "rate_limited")175 Clock.now += 1.5176 assert (await c1.get("/v1/jobs")).status_code == 200177 assert_error(await c1.get("/v1/jobs"), 429, "rate_limited")178 Clock.now += 3600 # and never beyond its capacity179 codes = [(await c1.get("/v1/jobs")).status_code for _ in range(7)]180 assert codes == [200] * 5 + [429] * 2, codes181182183async def test_request_body_larger_than_2mb_is_refused(stack):184 c = stack.client185 url = stack.url("/about")186 big = json.dumps({"url": url, "render": "http", "metadata": {"pad": "x" * 2_100_000}}).encode()187 assert_error(await c.post("/v1/scrape", content=big, headers={"content-type": "application/json"}),188 413, "payload_too_large")189 assert_error(await c.post("/v1/batch", content=big, headers={"content-type": "application/json"}),190 413, "payload_too_large")191192 async def chunks(data: bytes, size: int = 64_000):193 for i in range(0, len(data), size):194 yield data[i:i + size]195 # no Content-Length: the limit is enforced while reading196 r = await c.post("/v1/scrape", content=chunks(big), headers={"content-type": "application/json"})197 assert "content-length" not in r.request.headers and r.request.headers["transfer-encoding"] == "chunked"198 assert_error(r, 413, "payload_too_large")199 assert await db(stack, "select count(*) from jobs", one=True) == 0200 # just under the limit, with and without Content-Length, the request is processed normally201 ok = json.dumps({"url": url, "render": "http", "metadata": {"pad": "x" * 1_900_000}}).encode()202 assert len(ok) < 2_000_000203 assert (await c.post("/v1/scrape", content=ok, headers={"content-type": "application/json"})).status_code == 202204 r = await c.post("/v1/scrape", content=chunks(ok), headers={"content-type": "application/json"})205 assert r.status_code == 202, r.text206 small = await c.post("/v1/scrape", content=chunks(json.dumps({"url": url, "render": "http"}).encode(), 7),207 headers={"content-type": "application/json"})208 assert small.status_code == 202, small.text209 assert await db(stack, "select count(*) from jobs", one=True) == 3210