litestar-feedback 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. litestar_feedback-0.2.1/.gitignore +43 -0
  2. litestar_feedback-0.2.1/CHANGELOG.md +34 -0
  3. litestar_feedback-0.2.1/LICENSE +21 -0
  4. litestar_feedback-0.2.1/PKG-INFO +299 -0
  5. litestar_feedback-0.2.1/README.md +273 -0
  6. litestar_feedback-0.2.1/examples/__init__.py +0 -0
  7. litestar_feedback-0.2.1/examples/replay_app.py +99 -0
  8. litestar_feedback-0.2.1/examples/support_app.py +113 -0
  9. litestar_feedback-0.2.1/pyproject.toml +92 -0
  10. litestar_feedback-0.2.1/src/litestar_feedback/__init__.py +7 -0
  11. litestar_feedback-0.2.1/src/litestar_feedback/_sqltypes.py +41 -0
  12. litestar_feedback-0.2.1/src/litestar_feedback/caller.py +48 -0
  13. litestar_feedback-0.2.1/src/litestar_feedback/py.typed +0 -0
  14. litestar_feedback-0.2.1/src/litestar_feedback/replay/__init__.py +45 -0
  15. litestar_feedback-0.2.1/src/litestar_feedback/replay/adapter.py +101 -0
  16. litestar_feedback-0.2.1/src/litestar_feedback/replay/events.py +159 -0
  17. litestar_feedback-0.2.1/src/litestar_feedback/replay/migration.py +114 -0
  18. litestar_feedback-0.2.1/src/litestar_feedback/replay/models.py +100 -0
  19. litestar_feedback-0.2.1/src/litestar_feedback/replay/plugin.py +66 -0
  20. litestar_feedback-0.2.1/src/litestar_feedback/replay/routes.py +257 -0
  21. litestar_feedback-0.2.1/src/litestar_feedback/replay/service.py +411 -0
  22. litestar_feedback-0.2.1/src/litestar_feedback/support/__init__.py +52 -0
  23. litestar_feedback-0.2.1/src/litestar_feedback/support/adapter.py +109 -0
  24. litestar_feedback-0.2.1/src/litestar_feedback/support/contract.py +579 -0
  25. litestar_feedback-0.2.1/src/litestar_feedback/support/migration.py +129 -0
  26. litestar_feedback-0.2.1/src/litestar_feedback/support/models.py +160 -0
  27. litestar_feedback-0.2.1/src/litestar_feedback/support/plugin.py +43 -0
  28. litestar_feedback-0.2.1/src/litestar_feedback/support/pytest_plugin.py +63 -0
  29. litestar_feedback-0.2.1/src/litestar_feedback/support/routes.py +455 -0
  30. litestar_feedback-0.2.1/src/litestar_feedback/support/schemas.py +135 -0
  31. litestar_feedback-0.2.1/src/litestar_feedback/support/service.py +792 -0
  32. litestar_feedback-0.2.1/tests/__init__.py +0 -0
  33. litestar_feedback-0.2.1/tests/conftest.py +70 -0
  34. litestar_feedback-0.2.1/tests/test_replay.py +338 -0
  35. litestar_feedback-0.2.1/tests/test_support_contract.py +7 -0
  36. litestar_feedback-0.2.1/tests/test_support_rules.py +518 -0
@@ -0,0 +1,43 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+
7
+ # Build artifacts
8
+ /dist/
9
+ /build/
10
+ /site/
11
+ /public/
12
+
13
+ # uv / venv
14
+ .venv/
15
+ uv.lock.bak
16
+
17
+ # Tool caches
18
+ .pytest_cache/
19
+ .ruff_cache/
20
+ .pyright/
21
+ .mypy_cache/
22
+ .moon/cache/
23
+
24
+ # Editor
25
+ .vscode/
26
+ .idea/
27
+ *.swp
28
+
29
+ # Claude Code local state (per-machine; tracked .claude files and AGENTS.md stay in git)
30
+ .claude/settings.local.json
31
+ .claude/worktrees/
32
+
33
+ # Local session logs
34
+ logs/
35
+
36
+ # Personal, machine-specific agent overrides (AGENTS.md is tracked)
37
+ AGENTS.local.md
38
+ CLAUDE.local.md
39
+
40
+ # Local agent wiring: names cabildo-issues-mcp, which is not a dependency of this
41
+ # package. docs/issues/ IS tracked — the register is plain markdown anyone can read.
42
+ .mcp.json
43
+ build/
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ All notable changes to `litestar-feedback`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
4
+
5
+ ## [Unreleased]
6
+
7
+ First release. Nothing is on PyPI yet.
8
+
9
+ ### Added
10
+
11
+ - `SupportPlugin`: a customer support inbox with issues, a reply thread and an operator inbox,
12
+ following ISSUES-STANDARD.md.
13
+ - Issues move between `open`, `waiting_customer`, `resolved` and `closed`; other moves get 409.
14
+ - A customer reply on a closed issue opens a new issue that points to the closed one
15
+ (`follows_id`).
16
+ - Waiting and resolved issues move on by themselves after 14 days.
17
+ - Operators can write internal notes that customers never see.
18
+ - Operators set an issue's kind with `POST /admin/issues/{id}/kind`. The change shows as an
19
+ internal note and does not restart the 14-day timer.
20
+ - Customers get a mail (through your mailer) when an operator replies. The mail goes out only
21
+ after the reply is committed.
22
+ - Every support error has a stable `code` next to `detail`.
23
+ - Screenshots upload first and attach by id; uploads need a store you provide.
24
+ - Customer messages are rate limited per user.
25
+ - An Alembic helper creates the three tables.
26
+ - The standard's contract test ships as a pytest plugin you run against your own app.
27
+ - `ReplayPlugin`: stores rrweb session recordings sent in chunks, one per page load.
28
+ - Nobody can write into another user's recording.
29
+ - Chunk and session size caps.
30
+ - Playback can start at a moment, for example the moment a support issue was filed.
31
+ - Click heatmaps per page and viewport width.
32
+ - Old recordings are pruned; recordings that live issues point to are kept.
33
+ - A user's recordings can be deleted with the user.
34
+ - An optional consent check runs before each chunk is stored.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jorge Cardona
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,299 @@
1
+ Metadata-Version: 2.5
2
+ Name: litestar-feedback
3
+ Version: 0.2.1
4
+ Summary: Litestar plugins for an in-app customer support inbox and session replay
5
+ Project-URL: Homepage, https://gitlab.com/cardona-oss/litestar-feedback
6
+ Project-URL: Repository, https://gitlab.com/cardona-oss/litestar-feedback
7
+ Project-URL: Changelog, https://gitlab.com/cardona-oss/litestar-feedback/-/blob/main/CHANGELOG.md
8
+ Author-email: Jorge Cardona <jorgeecardona@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: customer-support,issues,litestar,plugin,rrweb,session-replay
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Framework :: Pytest
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: litestar>=2.23
23
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.30
24
+ Provides-Extra: replay
25
+ Description-Content-Type: text/markdown
26
+
27
+ # litestar-feedback
28
+
29
+ Litestar plugins for an in-app customer support inbox and session replay. `SupportPlugin`
30
+ stores customer issues with a reply thread and an operator inbox. `ReplayPlugin` stores rrweb
31
+ recordings, plays them back from a moment, and builds click heatmaps. Each plugin works alone.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ uv add litestar-feedback
37
+ ```
38
+
39
+ For replay, install the `replay` extra (empty today, kept for future dependencies):
40
+
41
+ ```bash
42
+ uv add "litestar-feedback[replay]"
43
+ ```
44
+
45
+ Requires Python 3.12+, Litestar 2.23+ and SQLAlchemy 2.0 async. No Advanced Alchemy.
46
+
47
+ ## Support inbox
48
+
49
+ `SupportPlugin` follows ISSUES-STANDARD.md: tables `issues`, `issue_events`,
50
+ `issue_attachments`, and routes under `/issues` and `/admin/issues`.
51
+
52
+ - Statuses `open`, `waiting_customer`, `resolved`, `closed`. A move not allowed is 409.
53
+ - `closed` is final. A customer comment on a closed issue opens a new issue whose `follows_id` is
54
+ the closed one. The answer is the new issue's first event, so its `issue_id` is the new issue.
55
+ An operator comment on a closed issue is 409 with `code: "issue_closed"`.
56
+ - A customer comment reopens a `waiting_customer` or `resolved` issue.
57
+ - A `waiting_customer` or `resolved` issue moves on after 14 days with no activity.
58
+ - Internal notes (`internal: true`) never reach customer routes, and never make a customer's
59
+ `last_seen_event_id` stale.
60
+ - The operator sets `kind` after triage. The change is written as an internal note.
61
+ - A public operator reply calls your mailer after the transaction commits. A rolled back reply
62
+ sends no mail. The event records `notified_at` or the reason it was skipped (`pending` until
63
+ the mailer answers).
64
+ - Customer messages are rate limited per actor (20 per hour by default). Over the limit is 429.
65
+ - Images are uploaded first, then attached by id. No store configured means 503.
66
+ - Every error body has `status_code`, `detail` and a stable `code`, for example `issue_closed`
67
+ or `stale_thread`.
68
+
69
+ ### Wire it
70
+
71
+ 1. Write a function that turns a request into a `Caller`.
72
+ 2. Write a function that opens a session for that caller.
73
+ 3. Add the plugin.
74
+
75
+ ```python
76
+ from contextlib import asynccontextmanager
77
+
78
+ from litestar import Litestar, Request
79
+ from litestar.exceptions import NotAuthorizedException
80
+ from sqlalchemy import text
81
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
82
+
83
+ from litestar_feedback.support import Caller, SupportAdapter, SupportConfig, SupportPlugin
84
+
85
+ engine = create_async_engine("postgresql+psycopg://app@db/app")
86
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
87
+
88
+
89
+ async def caller(request: Request) -> Caller:
90
+ user = request.user # however your app signs users in
91
+ if user is None:
92
+ raise NotAuthorizedException()
93
+ return Caller(
94
+ scope_id=str(user.tenant_id),
95
+ user_id=str(user.id),
96
+ actor=user.email,
97
+ is_operator=user.is_staff,
98
+ )
99
+
100
+
101
+ @asynccontextmanager
102
+ async def session(caller: Caller):
103
+ async with sessions.begin() as s:
104
+ if not caller.is_operator:
105
+ await s.execute(text("SELECT set_config('app.tenant_id', :t, true)"), {"t": caller.scope_id})
106
+ yield s
107
+
108
+
109
+ app = Litestar(
110
+ plugins=[
111
+ SupportPlugin(
112
+ adapter=SupportAdapter(caller=caller, session=session),
113
+ config=SupportConfig(path="/v1"),
114
+ )
115
+ ]
116
+ )
117
+ ```
118
+
119
+ A runnable version is [examples/support_app.py](examples/support_app.py).
120
+
121
+ ### Adapter
122
+
123
+ | Field | Type | What it does |
124
+ |---|---|---|
125
+ | `caller` | `async (Request) -> Caller` | Who is calling. Raise `NotAuthorizedException` for nobody. |
126
+ | `session` | `(Caller) -> async context manager of AsyncSession` | One transaction per request. Commit on exit, roll back on error. Set row-level security here. |
127
+ | `mailer` | `Mailer` or None | `async send_reply(ReplyNotice) -> bool`. False means the customer has no address. |
128
+ | `storage` | `AttachmentStore` or None | `async put`, `delete`, `presign_get`. None makes uploads return 503. |
129
+
130
+ `Caller` has `scope_id: str`, `user_id: str | None`, `actor: str`, `is_operator: bool`. The ids
131
+ are strings so UUID and integer keys fit the same columns.
132
+
133
+ `SupportConfig` holds `path`, the two timers, the rate limit, upload limits, `system_actor`,
134
+ `list_limit` and `clock`. Defaults follow the standard.
135
+
136
+ ### Routes
137
+
138
+ | Method | Path | Who |
139
+ |---|---|---|
140
+ | POST | `/issues` | customer |
141
+ | GET | `/issues` | customer |
142
+ | GET | `/issues/{id}` | customer |
143
+ | POST | `/issues/{id}/comments` | customer |
144
+ | POST | `/issues/{id}/resolve` | customer |
145
+ | POST | `/issue-attachments` | customer |
146
+ | GET | `/admin/issues` | operator |
147
+ | GET | `/admin/issues/{id}` | operator |
148
+ | POST | `/admin/issues/{id}/comments` | operator |
149
+ | POST | `/admin/issues/{id}/status` | operator |
150
+ | POST | `/admin/issues/{id}/kind` | operator |
151
+
152
+ ### Tables
153
+
154
+ Call the helper from an Alembic migration:
155
+
156
+ ```python
157
+ from alembic import op
158
+ from litestar_feedback.support.migration import create_tables, drop_tables
159
+
160
+
161
+ def upgrade() -> None:
162
+ create_tables(op)
163
+
164
+
165
+ def downgrade() -> None:
166
+ drop_tables(op)
167
+ ```
168
+
169
+ Then add your row-level security policies on `scope_id` in the same migration.
170
+
171
+ ### Jobs to schedule
172
+
173
+ The plugin applies timers when an issue is read. These `SupportService` methods are for a
174
+ scheduler:
175
+
176
+ - `sweep_timers()`: apply due timers to every issue.
177
+ - `reap_staged()`: delete uploads no message claimed within 24 hours.
178
+ - `forget_user(user_id)`: delete a user's screenshots and unlink their issues.
179
+ - `import_issue(...)`: insert a historical issue with `notify_skipped_reason='seeded'`.
180
+
181
+ ### Contract test
182
+
183
+ The package ships the standard's black-box contract as a pytest plugin.
184
+
185
+ 1. Define five fixtures in `tests/conftest.py`: `client`, `customer_headers`,
186
+ `operator_headers`, `other_tenant_headers`, `seeded_issue`.
187
+ 2. Add `tests/test_support_contract.py`:
188
+
189
+ ```python
190
+ from litestar_feedback.support.contract import SupportContract
191
+
192
+
193
+ class TestSupportContract(SupportContract):
194
+ pass
195
+ ```
196
+
197
+ Set the rate limit high in the app under test. Every contract test posts as one customer.
198
+
199
+ ## Session replay
200
+
201
+ `ReplayPlugin` stores rrweb events in chunks, one recording per page load. The browser recorder
202
+ is not part of this package: run rrweb in the browser and post its events to the ingest route.
203
+
204
+ - A session id belongs to the first caller that writes to it. Another scope or user gets 409.
205
+ - A repeated `seq` is ignored (`"action": "exists"`), so the browser can retry safely.
206
+ - Caps: 1 MiB per chunk, 5,000 events per chunk, 20 MiB per session. Over a cap is 413.
207
+ - Playback with `offset_ms` loads from the last full snapshot before that moment.
208
+ - Clicks are kept per page path and viewport width bucket, for heatmaps.
209
+ - `prune` deletes old recordings. `delete_user` deletes a user's recordings.
210
+ - Recordings in the adapter's `protected_sessions` survive both.
211
+
212
+ ### Ingest API
213
+
214
+ `POST /replay/ingest`, signed in as the user being recorded:
215
+
216
+ ```json
217
+ {
218
+ "session_id": "7c0e4b7e-2f1a-4c55-9a51-0d6c1f3f6a10",
219
+ "seq": 0,
220
+ "events": [{"type": 4, "timestamp": 1767225600000, "data": {"href": "https://app.example/orders", "width": 1280, "height": 800}}],
221
+ "entry_url": "https://app.example/orders",
222
+ "viewport_w": 1280,
223
+ "viewport_h": 800
224
+ }
225
+ ```
226
+
227
+ 1. Pick a new `session_id` (UUID) on every page load.
228
+ 2. Buffer rrweb events. Send them every 10 seconds or 400 events, with `seq` counting from 0.
229
+ 3. On 5xx, retry the same body. On 4xx, drop the batch.
230
+ 4. To link a support issue, put `replay_session_id` and `replay_offset_ms` (milliseconds since
231
+ the first event) in the issue's `context`.
232
+
233
+ The answer is `{"action": "appended" | "exists", "event_count": n}`. 403 means no consent.
234
+
235
+ ### Wire it
236
+
237
+ ```python
238
+ from litestar_feedback.replay import ReplayAdapter, ReplayConfig, ReplayPlugin
239
+ from litestar_feedback.support import referenced_replay_sessions
240
+
241
+ replay = ReplayPlugin(
242
+ adapter=ReplayAdapter(
243
+ caller=caller, # same functions as for SupportPlugin
244
+ session=session,
245
+ retention_days=30,
246
+ consent=has_analytics_consent, # async (Caller, Request) -> bool
247
+ protected_sessions=referenced_replay_sessions, # only if SupportPlugin is installed
248
+ ),
249
+ config=ReplayConfig(path="/v1"),
250
+ )
251
+ app = Litestar(plugins=[replay])
252
+ ```
253
+
254
+ Run the jobs from your scheduler. `system_caller` is an operator `Caller`:
255
+
256
+ ```python
257
+ result = await replay.prune(system_caller) # PruneResult(candidates, deleted, protected)
258
+ deleted = await replay.delete_user(system_caller, str(user.id))
259
+ ```
260
+
261
+ A runnable version is [examples/replay_app.py](examples/replay_app.py).
262
+
263
+ ### Adapter
264
+
265
+ | Field | Type | What it does |
266
+ |---|---|---|
267
+ | `caller` | `async (Request) -> Caller` | Who is calling. Operators can play back and see heatmaps. |
268
+ | `session` | `(Caller) -> async context manager of AsyncSession` | One transaction per request. |
269
+ | `chunk_store` | `ChunkStore` or None | `async put`, `get`, `delete`. None stores chunks in `replay_chunks.events`. |
270
+ | `retention_days` | `int` | `prune` deletes recordings whose last event is older. 0 keeps all. |
271
+ | `consent` | `async (Caller, Request) -> bool` or None | False answers 403 and stores nothing. |
272
+ | `protected_sessions` | `async (AsyncSession) -> set[UUID]` or None | Recordings that prune and user deletion keep. |
273
+
274
+ `ReplayConfig` holds `path`, the three caps, `viewport_buckets` (default `0, 640, 1024, 1440`),
275
+ the heatmap grid size, `list_limit` and `clock`.
276
+
277
+ ### Routes
278
+
279
+ | Method | Path | Who |
280
+ |---|---|---|
281
+ | POST | `/replay/ingest` | the recorded user |
282
+ | GET | `/admin/replay/sessions` | operator |
283
+ | GET | `/admin/replay/sessions/{id}?offset_ms=` | operator |
284
+ | DELETE | `/admin/replay/sessions/{id}` | operator |
285
+ | GET | `/admin/replay/heatmaps` | operator |
286
+ | GET | `/admin/replay/heatmap?path=&viewport_bucket=` | operator |
287
+
288
+ A heatmap is a grid: 20 columns across the viewport width, rows of 50 pixels. Click `y` is in
289
+ viewport pixels, not page pixels: rrweb reports clicks relative to the viewport.
290
+
291
+ ### Tables
292
+
293
+ `replay_sessions`, `replay_chunks`, `replay_clicks`. Create them with
294
+ `litestar_feedback.replay.migration.create_tables(op)` in an Alembic migration.
295
+
296
+ ## Links
297
+
298
+ - [CHANGELOG.md](CHANGELOG.md)
299
+ - [AGENTS.md](AGENTS.md)
@@ -0,0 +1,273 @@
1
+ # litestar-feedback
2
+
3
+ Litestar plugins for an in-app customer support inbox and session replay. `SupportPlugin`
4
+ stores customer issues with a reply thread and an operator inbox. `ReplayPlugin` stores rrweb
5
+ recordings, plays them back from a moment, and builds click heatmaps. Each plugin works alone.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ uv add litestar-feedback
11
+ ```
12
+
13
+ For replay, install the `replay` extra (empty today, kept for future dependencies):
14
+
15
+ ```bash
16
+ uv add "litestar-feedback[replay]"
17
+ ```
18
+
19
+ Requires Python 3.12+, Litestar 2.23+ and SQLAlchemy 2.0 async. No Advanced Alchemy.
20
+
21
+ ## Support inbox
22
+
23
+ `SupportPlugin` follows ISSUES-STANDARD.md: tables `issues`, `issue_events`,
24
+ `issue_attachments`, and routes under `/issues` and `/admin/issues`.
25
+
26
+ - Statuses `open`, `waiting_customer`, `resolved`, `closed`. A move not allowed is 409.
27
+ - `closed` is final. A customer comment on a closed issue opens a new issue whose `follows_id` is
28
+ the closed one. The answer is the new issue's first event, so its `issue_id` is the new issue.
29
+ An operator comment on a closed issue is 409 with `code: "issue_closed"`.
30
+ - A customer comment reopens a `waiting_customer` or `resolved` issue.
31
+ - A `waiting_customer` or `resolved` issue moves on after 14 days with no activity.
32
+ - Internal notes (`internal: true`) never reach customer routes, and never make a customer's
33
+ `last_seen_event_id` stale.
34
+ - The operator sets `kind` after triage. The change is written as an internal note.
35
+ - A public operator reply calls your mailer after the transaction commits. A rolled back reply
36
+ sends no mail. The event records `notified_at` or the reason it was skipped (`pending` until
37
+ the mailer answers).
38
+ - Customer messages are rate limited per actor (20 per hour by default). Over the limit is 429.
39
+ - Images are uploaded first, then attached by id. No store configured means 503.
40
+ - Every error body has `status_code`, `detail` and a stable `code`, for example `issue_closed`
41
+ or `stale_thread`.
42
+
43
+ ### Wire it
44
+
45
+ 1. Write a function that turns a request into a `Caller`.
46
+ 2. Write a function that opens a session for that caller.
47
+ 3. Add the plugin.
48
+
49
+ ```python
50
+ from contextlib import asynccontextmanager
51
+
52
+ from litestar import Litestar, Request
53
+ from litestar.exceptions import NotAuthorizedException
54
+ from sqlalchemy import text
55
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
56
+
57
+ from litestar_feedback.support import Caller, SupportAdapter, SupportConfig, SupportPlugin
58
+
59
+ engine = create_async_engine("postgresql+psycopg://app@db/app")
60
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
61
+
62
+
63
+ async def caller(request: Request) -> Caller:
64
+ user = request.user # however your app signs users in
65
+ if user is None:
66
+ raise NotAuthorizedException()
67
+ return Caller(
68
+ scope_id=str(user.tenant_id),
69
+ user_id=str(user.id),
70
+ actor=user.email,
71
+ is_operator=user.is_staff,
72
+ )
73
+
74
+
75
+ @asynccontextmanager
76
+ async def session(caller: Caller):
77
+ async with sessions.begin() as s:
78
+ if not caller.is_operator:
79
+ await s.execute(text("SELECT set_config('app.tenant_id', :t, true)"), {"t": caller.scope_id})
80
+ yield s
81
+
82
+
83
+ app = Litestar(
84
+ plugins=[
85
+ SupportPlugin(
86
+ adapter=SupportAdapter(caller=caller, session=session),
87
+ config=SupportConfig(path="/v1"),
88
+ )
89
+ ]
90
+ )
91
+ ```
92
+
93
+ A runnable version is [examples/support_app.py](examples/support_app.py).
94
+
95
+ ### Adapter
96
+
97
+ | Field | Type | What it does |
98
+ |---|---|---|
99
+ | `caller` | `async (Request) -> Caller` | Who is calling. Raise `NotAuthorizedException` for nobody. |
100
+ | `session` | `(Caller) -> async context manager of AsyncSession` | One transaction per request. Commit on exit, roll back on error. Set row-level security here. |
101
+ | `mailer` | `Mailer` or None | `async send_reply(ReplyNotice) -> bool`. False means the customer has no address. |
102
+ | `storage` | `AttachmentStore` or None | `async put`, `delete`, `presign_get`. None makes uploads return 503. |
103
+
104
+ `Caller` has `scope_id: str`, `user_id: str | None`, `actor: str`, `is_operator: bool`. The ids
105
+ are strings so UUID and integer keys fit the same columns.
106
+
107
+ `SupportConfig` holds `path`, the two timers, the rate limit, upload limits, `system_actor`,
108
+ `list_limit` and `clock`. Defaults follow the standard.
109
+
110
+ ### Routes
111
+
112
+ | Method | Path | Who |
113
+ |---|---|---|
114
+ | POST | `/issues` | customer |
115
+ | GET | `/issues` | customer |
116
+ | GET | `/issues/{id}` | customer |
117
+ | POST | `/issues/{id}/comments` | customer |
118
+ | POST | `/issues/{id}/resolve` | customer |
119
+ | POST | `/issue-attachments` | customer |
120
+ | GET | `/admin/issues` | operator |
121
+ | GET | `/admin/issues/{id}` | operator |
122
+ | POST | `/admin/issues/{id}/comments` | operator |
123
+ | POST | `/admin/issues/{id}/status` | operator |
124
+ | POST | `/admin/issues/{id}/kind` | operator |
125
+
126
+ ### Tables
127
+
128
+ Call the helper from an Alembic migration:
129
+
130
+ ```python
131
+ from alembic import op
132
+ from litestar_feedback.support.migration import create_tables, drop_tables
133
+
134
+
135
+ def upgrade() -> None:
136
+ create_tables(op)
137
+
138
+
139
+ def downgrade() -> None:
140
+ drop_tables(op)
141
+ ```
142
+
143
+ Then add your row-level security policies on `scope_id` in the same migration.
144
+
145
+ ### Jobs to schedule
146
+
147
+ The plugin applies timers when an issue is read. These `SupportService` methods are for a
148
+ scheduler:
149
+
150
+ - `sweep_timers()`: apply due timers to every issue.
151
+ - `reap_staged()`: delete uploads no message claimed within 24 hours.
152
+ - `forget_user(user_id)`: delete a user's screenshots and unlink their issues.
153
+ - `import_issue(...)`: insert a historical issue with `notify_skipped_reason='seeded'`.
154
+
155
+ ### Contract test
156
+
157
+ The package ships the standard's black-box contract as a pytest plugin.
158
+
159
+ 1. Define five fixtures in `tests/conftest.py`: `client`, `customer_headers`,
160
+ `operator_headers`, `other_tenant_headers`, `seeded_issue`.
161
+ 2. Add `tests/test_support_contract.py`:
162
+
163
+ ```python
164
+ from litestar_feedback.support.contract import SupportContract
165
+
166
+
167
+ class TestSupportContract(SupportContract):
168
+ pass
169
+ ```
170
+
171
+ Set the rate limit high in the app under test. Every contract test posts as one customer.
172
+
173
+ ## Session replay
174
+
175
+ `ReplayPlugin` stores rrweb events in chunks, one recording per page load. The browser recorder
176
+ is not part of this package: run rrweb in the browser and post its events to the ingest route.
177
+
178
+ - A session id belongs to the first caller that writes to it. Another scope or user gets 409.
179
+ - A repeated `seq` is ignored (`"action": "exists"`), so the browser can retry safely.
180
+ - Caps: 1 MiB per chunk, 5,000 events per chunk, 20 MiB per session. Over a cap is 413.
181
+ - Playback with `offset_ms` loads from the last full snapshot before that moment.
182
+ - Clicks are kept per page path and viewport width bucket, for heatmaps.
183
+ - `prune` deletes old recordings. `delete_user` deletes a user's recordings.
184
+ - Recordings in the adapter's `protected_sessions` survive both.
185
+
186
+ ### Ingest API
187
+
188
+ `POST /replay/ingest`, signed in as the user being recorded:
189
+
190
+ ```json
191
+ {
192
+ "session_id": "7c0e4b7e-2f1a-4c55-9a51-0d6c1f3f6a10",
193
+ "seq": 0,
194
+ "events": [{"type": 4, "timestamp": 1767225600000, "data": {"href": "https://app.example/orders", "width": 1280, "height": 800}}],
195
+ "entry_url": "https://app.example/orders",
196
+ "viewport_w": 1280,
197
+ "viewport_h": 800
198
+ }
199
+ ```
200
+
201
+ 1. Pick a new `session_id` (UUID) on every page load.
202
+ 2. Buffer rrweb events. Send them every 10 seconds or 400 events, with `seq` counting from 0.
203
+ 3. On 5xx, retry the same body. On 4xx, drop the batch.
204
+ 4. To link a support issue, put `replay_session_id` and `replay_offset_ms` (milliseconds since
205
+ the first event) in the issue's `context`.
206
+
207
+ The answer is `{"action": "appended" | "exists", "event_count": n}`. 403 means no consent.
208
+
209
+ ### Wire it
210
+
211
+ ```python
212
+ from litestar_feedback.replay import ReplayAdapter, ReplayConfig, ReplayPlugin
213
+ from litestar_feedback.support import referenced_replay_sessions
214
+
215
+ replay = ReplayPlugin(
216
+ adapter=ReplayAdapter(
217
+ caller=caller, # same functions as for SupportPlugin
218
+ session=session,
219
+ retention_days=30,
220
+ consent=has_analytics_consent, # async (Caller, Request) -> bool
221
+ protected_sessions=referenced_replay_sessions, # only if SupportPlugin is installed
222
+ ),
223
+ config=ReplayConfig(path="/v1"),
224
+ )
225
+ app = Litestar(plugins=[replay])
226
+ ```
227
+
228
+ Run the jobs from your scheduler. `system_caller` is an operator `Caller`:
229
+
230
+ ```python
231
+ result = await replay.prune(system_caller) # PruneResult(candidates, deleted, protected)
232
+ deleted = await replay.delete_user(system_caller, str(user.id))
233
+ ```
234
+
235
+ A runnable version is [examples/replay_app.py](examples/replay_app.py).
236
+
237
+ ### Adapter
238
+
239
+ | Field | Type | What it does |
240
+ |---|---|---|
241
+ | `caller` | `async (Request) -> Caller` | Who is calling. Operators can play back and see heatmaps. |
242
+ | `session` | `(Caller) -> async context manager of AsyncSession` | One transaction per request. |
243
+ | `chunk_store` | `ChunkStore` or None | `async put`, `get`, `delete`. None stores chunks in `replay_chunks.events`. |
244
+ | `retention_days` | `int` | `prune` deletes recordings whose last event is older. 0 keeps all. |
245
+ | `consent` | `async (Caller, Request) -> bool` or None | False answers 403 and stores nothing. |
246
+ | `protected_sessions` | `async (AsyncSession) -> set[UUID]` or None | Recordings that prune and user deletion keep. |
247
+
248
+ `ReplayConfig` holds `path`, the three caps, `viewport_buckets` (default `0, 640, 1024, 1440`),
249
+ the heatmap grid size, `list_limit` and `clock`.
250
+
251
+ ### Routes
252
+
253
+ | Method | Path | Who |
254
+ |---|---|---|
255
+ | POST | `/replay/ingest` | the recorded user |
256
+ | GET | `/admin/replay/sessions` | operator |
257
+ | GET | `/admin/replay/sessions/{id}?offset_ms=` | operator |
258
+ | DELETE | `/admin/replay/sessions/{id}` | operator |
259
+ | GET | `/admin/replay/heatmaps` | operator |
260
+ | GET | `/admin/replay/heatmap?path=&viewport_bucket=` | operator |
261
+
262
+ A heatmap is a grid: 20 columns across the viewport width, rows of 50 pixels. Click `y` is in
263
+ viewport pixels, not page pixels: rrweb reports clicks relative to the viewport.
264
+
265
+ ### Tables
266
+
267
+ `replay_sessions`, `replay_chunks`, `replay_clicks`. Create them with
268
+ `litestar_feedback.replay.migration.create_tables(op)` in an Alembic migration.
269
+
270
+ ## Links
271
+
272
+ - [CHANGELOG.md](CHANGELOG.md)
273
+ - [AGENTS.md](AGENTS.md)
File without changes