p3j-m: add WebSockets, Background Tasks, Scheduler, Session API reference pages

swadhinbiswas committed 3 months ago
f3ee3ef
1 parent 78f82c4
commit f3ee3ef
4 files changed
+258 -0
▼docs_site/src/content/docs/api-reference/background-tasks.md
+54-0
1
+---
2
+title: Background Tasks API
3
+description: Reference for post-response background task execution.
4
+---
5
+
6
+## `BackgroundTasks` Object
7
+
8
+```python
9
+from justapi import BackgroundTasks
10
+```
11
+
12
+| Method | Description |
13
+|---|---|
14
+| `tasks.add_task(func, *args, **kwargs)` | Register a function to run after the response |
15
+
16
+### `add_task()`
17
+
18
+| Parameter | Type | Description |
19
+|---|---|---|
20
+| `func` | callable | Function to execute in the background |
21
+| `*args` | any | Positional arguments for the function |
22
+| `**kwargs` | any | Keyword arguments for the function |
23
+
24
+Tasks are executed in registration order after the response is sent. If a task raises an exception, it's logged but subsequent tasks still execute.
25
+
26
+## Usage
27
+
28
+```python
29
+@app.post("/submit")
30
+def submit(request, tasks: BackgroundTasks):
31
+ tasks.add_task(send_email, "[email protected]", subject="Welcome")
32
+ return {"message": "Submitted"}
33
+```
34
+
35
+## Async Tasks
36
+
37
+```python
38
+import asyncio
39
+
40
+async def process_async(data: dict):
41
+ await asyncio.sleep(1)
42
+ print(f"Processed: {data}")
43
+
44
+@app.post("/process")
45
+async def process(request, tasks: BackgroundTasks):
46
+ tasks.add_task(process_async, {"id": 1})
47
+ return {"status": "processing"}
48
+```
49
+
50
+## See Also
51
+
52
+- [Background Tasks Tutorial](/tutorials/background-tasks/) — Usage patterns
53
+- [Scheduler API](/api-reference/scheduler/) — Cron-based periodic tasks
54
+- [JustAPIApp](/api-reference/justapiapp/) — App configuration
0
55
▼docs_site/src/content/docs/api-reference/scheduler.md
+75-0
1
+---
2
+title: Scheduler API
3
+description: Reference for the Rust-native cron-based task scheduler.
4
+---
5
+
6
+## `PyScheduler` Object
7
+
8
+The scheduler manages periodic tasks using cron expressions. It runs entirely in Rust with UTC-based timing.
9
+
10
+```python
11
+from justapi import PyScheduler
12
+
13
+scheduler = PyScheduler()
14
+```
15
+
16
+| Method | Description |
17
+|---|---|
18
+| `scheduler.cron(expression, callback)` | Schedule task with cron expression |
19
+| `scheduler.interval(seconds, callback)` | Schedule task at fixed interval |
20
+| `scheduler.once(delay_seconds, callback)` | Schedule one-time delayed task |
21
+
22
+### `scheduler.cron()`
23
+
24
+```python
25
+# Run every hour at minute 0
26
+scheduler.cron("0 * * * *", my_task)
27
+```
28
+
29
+| Parameter | Type | Description |
30
+|---|---|---|
31
+| `expression` | `str` | Standard 5-field cron expression (min hour day month weekday) |
32
+| `callback` | callable | Function to execute |
33
+
34
+### `scheduler.interval()`
35
+
36
+```python
37
+# Run every 30 seconds
38
+scheduler.interval(30, my_task)
39
+```
40
+
41
+| Parameter | Type | Description |
42
+|---|---|---|
43
+| `seconds` | `int` | Interval in seconds |
44
+| `callback` | callable | Function to execute |
45
+
46
+### `scheduler.once()`
47
+
48
+```python
49
+# Run once after 60 seconds
50
+scheduler.once(60, my_task)
51
+```
52
+
53
+| Parameter | Type | Description |
54
+|---|---|---|
55
+| `delay_seconds` | `int` | Delay before execution |
56
+| `callback` | callable | Function to execute |
57
+
58
+## Integration with App
59
+
60
+```python
61
+from justapi import JustAPIApp, PyScheduler
62
+
63
+app = JustAPIApp()
64
+scheduler = PyScheduler()
65
+
66
+def cleanup_expired_sessions():
67
+ app.db.execute("DELETE FROM sessions WHERE expires_at < NOW()")
68
+
69
+scheduler.cron("0 */6 * * *", cleanup_expired_sessions) # Every 6 hours
70
+```
71
+
72
+## See Also
73
+
74
+- [Background Tasks](/api-reference/background-tasks/) — Per-request background tasks
75
+- [JustAPIApp](/api-reference/justapiapp/) — App configuration
0
76
▼docs_site/src/content/docs/api-reference/session.md
+67-0
1
+---
2
+title: Session API (Agent System)
3
+description: Reference for Rust-backed agent session state management.
4
+---
5
+
6
+## `Session` Object
7
+
8
+Sessions provide durable per-client state storage backed by the Rust runtime. Sessions are identified by the `justapi_session` cookie or `?session=` query parameter.
9
+
10
+```python
11
+from justapi import Session
12
+```
13
+
14
+### Properties & Methods
15
+
16
+| Method | Returns | Description |
17
+|---|---|---|
18
+| `session.id` | `str` | Unique session identifier |
19
+| `session.get()` | `dict` | Get all session data |
20
+| `session.update(**kwargs)` | `None` | Update session data with key-value pairs |
21
+
22
+### Usage
23
+
24
+```python
25
+from justapi import JustAPIApp, Session
26
+
27
+app = JustAPIApp()
28
+app.enable_sessions()
29
+
30
+
31
+@app.get("/agent/state")
32
+def agent_state(request, session: Session):
33
+ prior = session.get().get("visits", 0)
34
+ session.update(visits=prior + 1)
35
+ return {
36
+ "session_id": session.id,
37
+ "visits": prior + 1,
38
+ "data": session.get(),
39
+ }
40
+```
41
+
42
+## Enabling Sessions
43
+
44
+```python
45
+app.enable_sessions()
46
+```
47
+
48
+This activates the Rust-backed session store. Sessions are:
49
+- Created on first use (new session ID generated)
50
+- Persisted across requests via cookie or query param
51
+- Available in any handler by declaring `session: Session`
52
+
53
+## System Routes
54
+
55
+```python
56
+app.enable_system_routes()
57
+```
58
+
59
+Enables:
60
+- `GET /_system/tools` — List registered MCP tools
61
+- `POST /_system/tools/call` — Call an MCP tool
62
+
63
+## See Also
64
+
65
+- [Agent System Guide](/advanced/agent-system/) — Deep dive into agent-native features
66
+- [Dependency Injection API](/api-reference/dependency-injection/) — Session in DI
67
+- [JustAPIApp](/api-reference/justapiapp/) — enable_sessions() and enable_system_routes()
0
68
▼docs_site/src/content/docs/api-reference/websockets.md
+62-0
1
+---
2
+title: WebSockets API
3
+description: Reference for WebSocket handler registration and connection management.
4
+---
5
+
6
+## `@app.websocket()`
7
+
8
+Register a WebSocket handler:
9
+
10
+```python
11
+@app.websocket(path="/ws")
12
+async def handler(ws):
13
+ await ws.accept()
14
+ ...
15
+```
16
+
17
+| Parameter | Type | Default | Description |
18
+|---|---|---|---|
19
+| `path` | `str` | required | WebSocket endpoint path |
20
+
21
+## `WebSocket` Object
22
+
23
+| Method | Description |
24
+|---|---|
25
+| `await ws.accept()` | Accept the WebSocket upgrade |
26
+| `await ws.receive_text()` | Receive a text message (`str`) |
27
+| `await ws.receive_bytes()` | Receive a binary message (`bytes`) |
28
+| `await ws.receive_json()` | Receive and parse JSON message |
29
+| `await ws.send_text(data)` | Send a text message |
30
+| `await ws.send_bytes(data)` | Send a binary message |
31
+| `await ws.send_json(data)` | Send JSON message |
32
+| `await ws.close()` | Close the connection |
33
+
34
+## `WebSocketState`
35
+
36
+| State | Description |
37
+|---|---|
38
+| `CONNECTING` | Initial state, waiting for upgrade |
39
+| `OPEN` | Connection established, messages can be exchanged |
40
+| `CLOSING` | Close frame sent/received |
41
+| `CLOSED` | Connection closed |
42
+
43
+## Example
44
+
45
+```python
46
+@app.websocket("/chat")
47
+async def chat(ws):
48
+ await ws.accept()
49
+ try:
50
+ while True:
51
+ msg = await ws.receive_text()
52
+ await ws.send_text(f"Echo: {msg}")
53
+ except Exception:
54
+ pass
55
+ finally:
56
+ await ws.close()
57
+```
58
+
59
+## See Also
60
+
61
+- [WebSockets & SSE Tutorial](/tutorials/websockets-sse/) — Usage guide with broadcasting
62
+- [JustAPIApp](/api-reference/justapiapp/) — App configuration
0
63