Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,29 @@ unlock = api.bulk_list_unlock()
tagged = api.bulk_list_files_by_tag(unlock["unlockuuid"], "archived", 0, 100)
```

### Errors and timeouts

Calls do not raise on API errors. They return `{"status": "error", "message": ...}`, and when the server
answered, `httpcode` holds its HTTP status, so you can tell cases apart without matching message text. The
[error reference](https://docs.databunker.org/pro/api/errors) lists the status codes and common messages.

```python
result = api.get_user("email", "nobody@example.com")
if result["status"] == "error":
if result.get("httpcode") == 404:
... # no such user
else:
raise RuntimeError(result["message"]) # 403 bad token, 5xx, or no httpcode: no response at all
```

Every request has a timeout: 10 seconds to connect and 300 seconds to read by default. A call that times out
returns an error without `httpcode`. Pass `timeout` to change it, as seconds or a `(connect, read)` pair;
`None` waits forever:

```python
api = DatabunkerproAPI(base_url, x_bunker_token=token, timeout=(5, 60))
```

## Features

- User Management
Expand Down
64 changes: 48 additions & 16 deletions databunkerpro/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,24 @@
import json
import re
from datetime import datetime
from typing import Any, Dict, Iterable, List, Mapping, Optional, TypedDict, Union, cast
from typing import (
Any,
Dict,
Iterable,
List,
Mapping,
Optional,
Tuple,
TypedDict,
Union,
cast,
)

import requests

#: (connect, read) seconds: an unreachable host fails fast, a slow bulk call still has time
DEFAULT_TIMEOUT: Tuple[float, float] = (10.0, 300.0)


# Type definitions for better type safety and documentation
class UserOptions(TypedDict, total=False):
Expand Down Expand Up @@ -184,12 +198,20 @@ class DatabunkerproAPI:
"""Main client class for interacting with the DatabunkerPro API."""

def __init__(
self, base_url: str, x_bunker_token: str = "", x_bunker_tenant: str = ""
self,
base_url: str,
x_bunker_token: str = "",
x_bunker_tenant: str = "",
timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_TIMEOUT,
):
"""Initialize the DatabunkerPro API client."""
"""Initialize the DatabunkerPro API client.

timeout is passed to requests: seconds, or (connect, read); None waits forever.
"""
self.base_url = base_url.rstrip("/")
self.x_bunker_token = x_bunker_token
self.x_bunker_tenant = x_bunker_tenant
self.timeout = timeout

def _make_request(
self,
Expand All @@ -214,21 +236,31 @@ def _make_request(
body = None

try:
response = requests.post(url, headers=headers, data=body)
result: Dict[str, Any] = response.json()

if not response.ok:
if result.get("status"):
return result
else:
return {
"status": "error",
"message": result.get("message", "API request failed"),
}
return result
response = requests.post(
url, headers=headers, data=body, timeout=self.timeout
)
except requests.exceptions.RequestException as e:
return {"status": "error", "message": f"Error making request: {str(e)}"}

try:
result: Dict[str, Any] = response.json()
except ValueError:
# a non-JSON reply, such as a proxy's HTML error page
return {
"status": "error",
"message": f"Invalid JSON response (HTTP {response.status_code})",
"httpcode": response.status_code,
}

if not response.ok:
if not result.get("status"):
result = {
"status": "error",
"message": result.get("message", "API request failed"),
}
result["httpcode"] = response.status_code
return result

def raw_request(
self,
endpoint: str,
Expand All @@ -249,7 +281,7 @@ def raw_request(
body = json.dumps(body_data)
else:
body = None
response = requests.post(url, headers=headers, data=body)
response = requests.post(url, headers=headers, data=body, timeout=self.timeout)
return response.content

# User Management
Expand Down
105 changes: 105 additions & 0 deletions tests/test_http_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""Offline tests for error results and timeouts, against a local stub server."""

import json
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import requests

from databunkerpro import DatabunkerproAPI

# endpoint -> (HTTP status, body, delay in seconds)
REPLIES = {
"UserGet": (
404,
{"status": "error", "message": "The user record was not found"},
0,
),
"UserCreate": (409, {"status": "error", "message": "Duplicate index: login"}, 0),
"FileGet": (502, "<html>Bad Gateway</html>", 0),
"TokenGet": (500, {"message": "boom"}, 0),
"SystemGetSystemStats": (200, {"status": "ok", "stats": {}}, 0),
"Slow": (200, {"status": "ok"}, 2),
}


class Handler(BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
code, body, delay = REPLIES[self.path.rsplit("/", 1)[-1]]
time.sleep(delay)
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
try:
self.wfile.write(data)
except OSError:
pass # the client gave up (timeout test)

def log_message(self, *args):
pass


class TestHttpErrors(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
cls.url = f"http://127.0.0.1:{cls.server.server_address[1]}"
cls.api = DatabunkerproAPI(cls.url, "TOKEN")

@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()

def test_error_keeps_server_message_and_adds_httpcode(self):
self.assertEqual(
self.api.get_user("login", "x"),
{
"status": "error",
"message": "The user record was not found",
"httpcode": 404,
},
)
self.assertEqual(self.api.create_user({"login": "x"})["httpcode"], 409)

def test_error_without_status_field(self):
self.assertEqual(
self.api.get_token("t"),
{"status": "error", "message": "boom", "httpcode": 500},
)

def test_non_json_reply(self):
result = self.api.get_file("login", "x", filename="f")
self.assertEqual(result["status"], "error")
self.assertEqual(result["httpcode"], 502)

def test_success_has_no_httpcode(self):
self.assertEqual(self.api.get_system_stats(), {"status": "ok", "stats": {}})

def test_connection_failure_has_no_httpcode(self):
api = DatabunkerproAPI("http://127.0.0.1:9", "TOKEN", timeout=2)
result = api.get_user("login", "x")
self.assertEqual(result["status"], "error")
self.assertNotIn("httpcode", result)

def test_timeout_returns_error(self):
api = DatabunkerproAPI(self.url, "TOKEN", timeout=0.5)
start = time.monotonic()
result = api._make_request("Slow")
self.assertLess(time.monotonic() - start, 1.5)
self.assertEqual(result["status"], "error")
self.assertIn("timed out", result["message"].lower())

def test_raw_request_timeout_raises(self):
api = DatabunkerproAPI(self.url, "TOKEN", timeout=0.5)
with self.assertRaises(requests.exceptions.Timeout):
api.raw_request("Slow")

def test_default_timeout(self):
self.assertEqual(self.api.timeout, (10.0, 300.0))
self.assertIsNone(DatabunkerproAPI(self.url, timeout=None).timeout)
Loading