welearn-database 1.5.7__tar.gz → 1.5.8.dev0__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 (57) hide show
  1. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/PKG-INFO +1 -1
  2. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/pyproject.toml +1 -1
  3. welearn_database-1.5.8.dev0/welearn_database/alembic/versions/1_5_8_add_auth_event_table_and_grafana_views.py +436 -0
  4. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/enumeration.py +9 -0
  5. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/grafana.py +122 -0
  6. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/user_related.py +81 -1
  7. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/LICENSE +0 -0
  8. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/README.md +0 -0
  9. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/__init__.py +0 -0
  10. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/README +0 -0
  11. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/env.py +0 -0
  12. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/script.py.mako +0 -0
  13. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/0310ff0bda4f_track_document_last_state.py +0 -0
  14. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/068312e7800c_add_referrer_origin_column_to_user_and_.py +0 -0
  15. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/0e0bc0fca384_doc_qty_per_source.py +0 -0
  16. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/16ff997426d3_remove_error_retrieval_unique_constraint.py +0 -0
  17. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/1_5_5_analytical_view_for_research.py +0 -0
  18. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/1_5_6_add_is_hidden_column_to_category.py +0 -0
  19. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/1_5_7_add_feature_thread_and_guest_feature_usage_tables.py +0 -0
  20. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/2ad4895b2674_data_collection.py +0 -0
  21. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/4c7161819e5a_grafana_views.py +0 -0
  22. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/4f5a188dd614_add_main_url_column.py +0 -0
  23. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/4fcbfb7f3145_added_api_key_management_table.py +0 -0
  24. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/5aad97149044_add_histo_table_for_materialized_views.py +0 -0
  25. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/5d46d7920342_support_sub_corpus.py +0 -0
  26. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/5d82613c9aca_context_document.py +0 -0
  27. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/6d4346fad6f4_view_used_feature_per_session.py +0 -0
  28. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/821173cf9c5d_initial_migration.py +0 -0
  29. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/84c42739c17b_create_table_errordataquality.py +0 -0
  30. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/89920abb7ff8_add_category.py +0 -0
  31. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/8b780aea403a_add_university_data.py +0 -0
  32. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/95ffe7afa64c_add_index_idx_welearn_document_keyword_.py +0 -0
  33. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/96bba9e4842a_merge_external_id_error_quality.py +0 -0
  34. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/9b4f1da0c1f2_data_collection_for_focus_group.py +0 -0
  35. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/a50a1db3ca2a_add_used_since_column_for_embeddings.py +0 -0
  36. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/b031206324b7_agent_related.py +0 -0
  37. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/b049924f7067_modify_corpus_name_embedding_model_lang_.py +0 -0
  38. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/b84462ca3800_update_grafana_process_state_view.py +0 -0
  39. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/ccdbd708c997_create_column_external_id.py +0 -0
  40. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/d22d6324c256_cleaned_document_state.py +0 -0
  41. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/d990f127902f_merge_keycloack_and_new_cleaned_state_.py +0 -0
  42. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/e354666f951d_inferred_user.py +0 -0
  43. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/f10903998081_keycloack_id_for_user_id.py +0 -0
  44. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/f1ce0ad2845b_add_doi_column_to_document.py +0 -0
  45. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/f5e91a5c950d_add_analytic_form.py +0 -0
  46. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/alembic/versions/f8602200fa99_update_session_view.py +0 -0
  47. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/__init__.py +0 -0
  48. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/details_dict.py +0 -0
  49. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/__init__.py +0 -0
  50. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/agent_related.py +0 -0
  51. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/corpus_related.py +0 -0
  52. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/data/models/document_related.py +0 -0
  53. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/database_utils.py +0 -0
  54. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/exceptions.py +0 -0
  55. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/modules/__init__.py +0 -0
  56. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/modules/text_cleaning.py +0 -0
  57. {welearn_database-1.5.7 → welearn_database-1.5.8.dev0}/welearn_database/regular_expression.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: welearn-database
3
- Version: 1.5.7
3
+ Version: 1.5.8.dev0
4
4
  Summary: All stuff related to relationnal database from the WeLearn project
5
5
  License: cc-by-sa-nc
6
6
  Author: Théo
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "welearn-database"
3
- version = "1.5.7"
3
+ version = "1.5.8.dev0"
4
4
 
5
5
  description = "All stuff related to relationnal database from the WeLearn project"
6
6
  authors = [
@@ -0,0 +1,436 @@
1
+ """add auth_event table, its grafana views and the grafana usage views
2
+
3
+ Revision ID: 1_5_8
4
+ Revises: 1_5_7
5
+ Create Date: 2026-11-26 17:36:17.512738
6
+
7
+ """
8
+
9
+ from typing import Sequence, Union
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+ from sqlalchemy.dialects import postgresql
14
+
15
+ # revision identifiers, used by Alembic.
16
+ revision: str = "1_5_8"
17
+ down_revision: Union[str, None] = "1_5_7"
18
+ branch_labels: Union[str, Sequence[str], None] = None
19
+ depends_on: Union[str, Sequence[str], None] = None
20
+
21
+ SCHEMA = "user_related"
22
+
23
+ # written out rather than read from AuthEventType, so this revision keeps
24
+ # creating the same type if the enum changes later
25
+ EVENT_TYPES = ["signup", "account_created", "login", "logout"]
26
+
27
+ # the API paths (endpoint_request.endpoint_name) of each feature, as LIKE
28
+ # patterns that don't overlap, so a request gets one feature at most. Paths not
29
+ # listed (session, guest quota, access, logout, metrics, health, the lists
30
+ # loaded when the app starts...) are plumbing and have no feature.
31
+ ENDPOINT_FEATURES = [
32
+ # a question asked; history and threads are loaded on boot, so left out
33
+ ("/api/v1/qna/chat/agent", "chat"),
34
+ ("/api/v1/qna/chat/agent_stream", "chat"),
35
+ ("/api/v1/qna/chat/answer", "chat"),
36
+ ("/api/v1/qna/stream", "chat"),
37
+ ("/api/v1/qna/reformulate/%", "chat"),
38
+ ("/api/v1/search/by_document", "search"),
39
+ ("/api/v1/search/by_slices", "search"),
40
+ ("/api/v1/search/multiple_by_slices", "search"),
41
+ ("/api/v1/search/collections/%", "search"),
42
+ # the client sends it with each search, to show the query's SDGs
43
+ ("/api/v1/search/sdg_classify", "sdg detection"),
44
+ ("/api/v1/tutor/files/content", "syllabus (from scratch)"),
45
+ ("/api/v1/tutor/search_extracts", "syllabus (from scratch)"),
46
+ ("/api/v1/tutor/search_datasets", "syllabus (from scratch)"),
47
+ ("/api/v1/tutor/syllabus", "syllabus (from scratch)"),
48
+ ("/api/v1/tutor/syllabus/feedback", "syllabus (from scratch)"),
49
+ ("/api/v1/tutor/syllabus/user_update", "syllabus (from scratch)"),
50
+ ("/api/v1/tutor/course/%", "syllabus v2 (existing course)"),
51
+ # the hidden /tutor_test page and the steps it calls
52
+ ("/api/v1/tutor/mas_files/%", "syllabus (test page)"),
53
+ ("/api/v1/tutor/api/%", "syllabus (test page)"),
54
+ ("/api/v1/tutor/syllabus/description", "syllabus (test page)"),
55
+ ("/api/v1/tutor/syllabus/learning_objectives", "syllabus (test page)"),
56
+ ("/api/v1/tutor/syllabus/learning_outcomes", "syllabus (test page)"),
57
+ ("/api/v1/tutor/syllabus/competency_map", "syllabus (test page)"),
58
+ ("/api/v1/tutor/syllabus/sustainability_integration", "syllabus (test page)"),
59
+ # a bookmark added or removed; the bare list is loaded on boot
60
+ ("/api/v1/user/bookmarks/%", "bookmarks"),
61
+ ("/api/v1/user/%/bookmarks/%", "bookmarks"),
62
+ ("/api/v1/bibliography/%", "bibliography export"),
63
+ ("/api/v1/micro_learning/%", "learn (microlearning)"),
64
+ ("/api/v1/user/university-request", "university request"),
65
+ ]
66
+
67
+ # a guest who logs in later gets its keycloak_id on the same row, so it counts
68
+ # as an account for its past too
69
+ USER_KIND = "CASE WHEN iu.keycloak_id IS NULL THEN 'guest' ELSE 'account' END"
70
+
71
+ # 6d4346fad6f4's definition, restored as is by the downgrade
72
+ OLD_USED_FEATURE_PER_SESSION = """
73
+ CREATE OR REPLACE VIEW grafana.used_feature_per_session
74
+ AS WITH matching_features_endpoint AS (
75
+ SELECT
76
+ endpoint_name,
77
+ feature_name
78
+ FROM
79
+ (
80
+ VALUES
81
+ ('/api/v1/search/by_document', 'search'),
82
+ ('/api/v1/qna/chat/answer', 'chat'),
83
+ ('/api/v1/qna/chat/agent', 'chat'),
84
+ ('/api/v1/tutor/syllabus', 'syllabus'),
85
+ ('/api/v1/user/bookmarks/' || ':' || 'document_id', 'bookmark'),
86
+ ('/api/v1/user/' || ':' || 'user_id' || '/bookmarks/' || ':' || 'document_id', 'bookmark')
87
+ ) AS t(endpoint_name, feature_name)
88
+ ),
89
+ session_feature_pair AS (
90
+ SELECT
91
+ DISTINCT
92
+ er.session_id,
93
+ mfe.feature_name
94
+ FROM
95
+ user_related.endpoint_request er
96
+ CROSS JOIN matching_features_endpoint mfe
97
+ ORDER BY
98
+ er.session_id
99
+ ),
100
+ actual_count AS (
101
+ SELECT
102
+ er.session_id,
103
+ mfe.feature_name,
104
+ COUNT(1) AS cnt
105
+ FROM
106
+ user_related.endpoint_request er
107
+ INNER JOIN
108
+ user_related."session" s ON
109
+ s.id = er.session_id
110
+ INNER JOIN
111
+ matching_features_endpoint mfe ON
112
+ mfe.endpoint_name = er.endpoint_name
113
+ GROUP BY
114
+ er.session_id,
115
+ mfe.feature_name
116
+ )
117
+ SELECT
118
+ s.inferred_user_id,
119
+ sfp.session_id,
120
+ sfp.feature_name,
121
+ COALESCE(ac.cnt, 0) AS cnt,
122
+ COALESCE(ac.cnt, 0) > 0 AS is_feature_used,
123
+ s.created_at AS session_created_at
124
+ FROM
125
+ session_feature_pair sfp
126
+ LEFT JOIN actual_count ac ON
127
+ ac.feature_name = sfp.feature_name
128
+ AND ac.session_id = sfp.session_id
129
+ INNER JOIN user_related."session" s ON
130
+ s.id = sfp.session_id
131
+ ORDER BY
132
+ session_created_at
133
+ """
134
+
135
+
136
+ def _comment(view: str, text: str) -> None:
137
+ op.execute(f"COMMENT ON VIEW grafana.{view} IS '{text}';")
138
+
139
+
140
+ def upgrade() -> None:
141
+ op.create_table(
142
+ "auth_event",
143
+ sa.Column(
144
+ "id", sa.Uuid(), server_default=sa.text("gen_random_uuid()"), nullable=False
145
+ ),
146
+ sa.Column("inferred_user_id", sa.Uuid(), nullable=False),
147
+ sa.Column("session_id", sa.Uuid(), nullable=True),
148
+ sa.Column(
149
+ "event_type",
150
+ postgresql.ENUM(*EVENT_TYPES, name="auth_event_type", schema=SCHEMA),
151
+ nullable=False,
152
+ ),
153
+ sa.Column("identity_provider", sa.String(), nullable=True),
154
+ sa.Column("is_limited_access", sa.Boolean(), nullable=False),
155
+ sa.Column("keycloak_session_id", sa.String(), nullable=True),
156
+ sa.Column(
157
+ "created_at",
158
+ sa.TIMESTAMP(),
159
+ server_default=sa.text("NOW()"),
160
+ nullable=False,
161
+ ),
162
+ sa.PrimaryKeyConstraint("id"),
163
+ sa.ForeignKeyConstraint(
164
+ ["inferred_user_id"],
165
+ [f"{SCHEMA}.inferred_user.id"],
166
+ name="auth_event_inferred_user_id_fkey",
167
+ ondelete="CASCADE",
168
+ ),
169
+ # events outlive a purged session, they only lose its host
170
+ sa.ForeignKeyConstraint(
171
+ ["session_id"],
172
+ [f"{SCHEMA}.session.id"],
173
+ name="auth_event_session_id_fkey",
174
+ ondelete="SET NULL",
175
+ ),
176
+ schema=SCHEMA,
177
+ )
178
+ op.create_index(
179
+ "auth_event_created_at_idx", "auth_event", ["created_at"], schema=SCHEMA
180
+ )
181
+ op.create_index(
182
+ "auth_event_event_type_created_at_idx",
183
+ "auth_event",
184
+ ["event_type", "created_at"],
185
+ schema=SCHEMA,
186
+ )
187
+ # one login per Keycloak session: a concurrent second insert fails here
188
+ op.create_index(
189
+ "auth_event_login_keycloak_session_key",
190
+ "auth_event",
191
+ ["inferred_user_id", "keycloak_session_id"],
192
+ unique=True,
193
+ schema=SCHEMA,
194
+ postgresql_where=sa.text(
195
+ "event_type = 'login' AND keycloak_session_id IS NOT NULL"
196
+ ),
197
+ )
198
+
199
+ # keycloak_session_id is left out: dashboards don't need it
200
+ op.execute(
201
+ """
202
+ CREATE OR REPLACE VIEW grafana.auth_event
203
+ AS SELECT auth_event.id,
204
+ auth_event.inferred_user_id,
205
+ auth_event.session_id,
206
+ auth_event.event_type,
207
+ auth_event.identity_provider,
208
+ auth_event.is_limited_access,
209
+ auth_event.created_at,
210
+ session.host
211
+ FROM user_related.auth_event
212
+ LEFT JOIN user_related.session ON session.id = auth_event.session_id;
213
+ """
214
+ )
215
+ # provider labels the NULL identity_provider (email/password or unknown) so
216
+ # it shows up as its own series in Grafana
217
+ op.execute(
218
+ """
219
+ CREATE OR REPLACE VIEW grafana.auth_event_daily
220
+ AS SELECT date_trunc('day', auth_event.created_at) AS day,
221
+ auth_event.event_type,
222
+ auth_event.identity_provider,
223
+ COALESCE(auth_event.identity_provider, 'email_or_unknown') AS provider,
224
+ auth_event.is_limited_access,
225
+ count(*) AS events,
226
+ count(DISTINCT auth_event.inferred_user_id) AS users
227
+ FROM user_related.auth_event
228
+ GROUP BY date_trunc('day', auth_event.created_at),
229
+ auth_event.event_type,
230
+ auth_event.identity_provider,
231
+ auth_event.is_limited_access;
232
+ """
233
+ )
234
+
235
+ values = ",\n ".join(
236
+ f"('{pattern}', '{feature}')" for pattern, feature in ENDPOINT_FEATURES
237
+ )
238
+ op.execute(
239
+ f"""
240
+ CREATE OR REPLACE VIEW grafana.endpoint_feature
241
+ AS SELECT endpoint_feature.endpoint_pattern,
242
+ endpoint_feature.feature
243
+ FROM (VALUES
244
+ {values}
245
+ ) AS endpoint_feature(endpoint_pattern, feature);
246
+ """
247
+ )
248
+ _comment(
249
+ "endpoint_feature",
250
+ "The feature of each API path, as a LIKE pattern on "
251
+ "endpoint_request.endpoint_name; other paths are plumbing.",
252
+ )
253
+ op.execute(
254
+ f"""
255
+ CREATE OR REPLACE VIEW grafana.feature_request
256
+ AS SELECT er.id,
257
+ er.session_id,
258
+ s.inferred_user_id,
259
+ {USER_KIND} AS user_kind,
260
+ ef.feature,
261
+ er.created_at
262
+ FROM user_related.endpoint_request er
263
+ JOIN grafana.endpoint_feature ef ON er.endpoint_name LIKE ef.endpoint_pattern
264
+ JOIN user_related.session s ON s.id = er.session_id
265
+ JOIN user_related.inferred_user iu ON iu.id = s.inferred_user_id;
266
+ """
267
+ )
268
+ _comment(
269
+ "feature_request",
270
+ "The API requests that use a feature (see endpoint_feature), with their "
271
+ "user. user_kind is guest when the user has no account today.",
272
+ )
273
+ op.execute(
274
+ f"""
275
+ CREATE OR REPLACE VIEW grafana.active_user_day
276
+ AS SELECT date_trunc('day', er.created_at) AS day,
277
+ s.inferred_user_id,
278
+ {USER_KIND} AS user_kind,
279
+ count(*) AS requests
280
+ FROM user_related.endpoint_request er
281
+ JOIN user_related.session s ON s.id = er.session_id
282
+ JOIN user_related.inferred_user iu ON iu.id = s.inferred_user_id
283
+ GROUP BY (date_trunc('day', er.created_at)), s.inferred_user_id, iu.keycloak_id;
284
+ """
285
+ )
286
+ _comment(
287
+ "active_user_day",
288
+ "One row per user and day with at least one API request. user_kind is "
289
+ "guest when the user has no account today: a guest who logs in later "
290
+ "counts as an account for its past days too.",
291
+ )
292
+ op.execute(
293
+ """
294
+ CREATE OR REPLACE VIEW grafana.active_users_daily
295
+ AS SELECT active_user_day.day,
296
+ active_user_day.user_kind,
297
+ count(*) AS active_users,
298
+ sum(active_user_day.requests)::bigint AS requests
299
+ FROM grafana.active_user_day
300
+ GROUP BY active_user_day.day, active_user_day.user_kind;
301
+ """
302
+ )
303
+ _comment(
304
+ "active_users_daily",
305
+ "Users with at least one API request per day, guests and accounts "
306
+ "(see active_user_day). Days cannot be summed: count distinct users "
307
+ "of active_user_day over a range instead.",
308
+ )
309
+ op.execute(
310
+ """
311
+ CREATE OR REPLACE VIEW grafana.new_users_daily
312
+ AS SELECT date_trunc('day', inferred_user.created_at) AS day,
313
+ count(*) AS new_users,
314
+ count(inferred_user.keycloak_id) AS with_account
315
+ FROM user_related.inferred_user
316
+ GROUP BY (date_trunc('day', inferred_user.created_at));
317
+ """
318
+ )
319
+ _comment(
320
+ "new_users_daily",
321
+ "Users (inferred_user rows) created per day, and how many of them have "
322
+ "an account today.",
323
+ )
324
+ op.execute(
325
+ """
326
+ CREATE OR REPLACE VIEW grafana.feature_usage_daily
327
+ AS SELECT date_trunc('day', feature_request.created_at) AS day,
328
+ feature_request.feature,
329
+ feature_request.user_kind,
330
+ count(DISTINCT feature_request.inferred_user_id) AS users,
331
+ count(*) AS requests
332
+ FROM grafana.feature_request
333
+ GROUP BY (date_trunc('day', feature_request.created_at)),
334
+ feature_request.feature,
335
+ feature_request.user_kind;
336
+ """
337
+ )
338
+ _comment(
339
+ "feature_usage_daily",
340
+ "Distinct users and requests per day, feature and user_kind (see "
341
+ "feature_request). Days cannot be summed for users.",
342
+ )
343
+ op.execute(
344
+ """
345
+ CREATE OR REPLACE VIEW grafana.guest_limit_hit
346
+ AS SELECT guest_feature_usage.id,
347
+ guest_feature_usage.inferred_user_id,
348
+ feature.title AS feature,
349
+ guest_feature_usage.created_at
350
+ FROM user_related.guest_feature_usage
351
+ JOIN user_related.feature ON feature.id = guest_feature_usage.feature_id
352
+ WHERE guest_feature_usage.action = 'quota_exceeded';
353
+ """
354
+ )
355
+ _comment(
356
+ "guest_limit_hit",
357
+ "Each time a guest was refused a use of a feature (feature table title) "
358
+ "because its daily quota was used up.",
359
+ )
360
+ op.execute(
361
+ """
362
+ CREATE OR REPLACE VIEW grafana.guest_limit_hits_daily
363
+ AS SELECT date_trunc('day', guest_limit_hit.created_at) AS day,
364
+ guest_limit_hit.feature,
365
+ count(DISTINCT guest_limit_hit.inferred_user_id) AS users,
366
+ count(*) AS refusals
367
+ FROM grafana.guest_limit_hit
368
+ GROUP BY (date_trunc('day', guest_limit_hit.created_at)), guest_limit_hit.feature;
369
+ """
370
+ )
371
+ _comment(
372
+ "guest_limit_hits_daily",
373
+ "Guests refused for a used-up quota, and refusals, per day and feature "
374
+ "(see guest_limit_hit). Days cannot be summed for users.",
375
+ )
376
+ # same columns as 6d4346fad6f4, so its panels keep working; it now uses the
377
+ # current paths and matches a bookmark path with its document id
378
+ op.execute(
379
+ """
380
+ CREATE OR REPLACE VIEW grafana.used_feature_per_session
381
+ AS WITH used AS (
382
+ SELECT feature_request.session_id,
383
+ feature_request.feature,
384
+ count(*) AS cnt
385
+ FROM grafana.feature_request
386
+ GROUP BY feature_request.session_id, feature_request.feature
387
+ ), features AS (
388
+ SELECT DISTINCT endpoint_feature.feature
389
+ FROM grafana.endpoint_feature
390
+ ), sessions AS (
391
+ SELECT DISTINCT endpoint_request.session_id
392
+ FROM user_related.endpoint_request
393
+ )
394
+ SELECT s.inferred_user_id,
395
+ sessions.session_id,
396
+ features.feature AS feature_name,
397
+ COALESCE(used.cnt, 0::bigint) AS cnt,
398
+ COALESCE(used.cnt, 0::bigint) > 0 AS is_feature_used,
399
+ s.created_at AS session_created_at
400
+ FROM sessions
401
+ CROSS JOIN features
402
+ JOIN user_related.session s ON s.id = sessions.session_id
403
+ LEFT JOIN used ON used.session_id = sessions.session_id
404
+ AND used.feature = features.feature;
405
+ """
406
+ )
407
+ _comment(
408
+ "used_feature_per_session",
409
+ "One row per session with API requests and per feature (see "
410
+ "endpoint_feature): cnt requests, is_feature_used when cnt > 0.",
411
+ )
412
+
413
+
414
+ def downgrade() -> None:
415
+ # back to its old definition first, so the views it used can be dropped
416
+ op.execute(OLD_USED_FEATURE_PER_SESSION)
417
+ op.execute("COMMENT ON VIEW grafana.used_feature_per_session IS NULL;")
418
+ op.execute("DROP VIEW IF EXISTS grafana.guest_limit_hits_daily;")
419
+ op.execute("DROP VIEW IF EXISTS grafana.guest_limit_hit;")
420
+ op.execute("DROP VIEW IF EXISTS grafana.feature_usage_daily;")
421
+ op.execute("DROP VIEW IF EXISTS grafana.new_users_daily;")
422
+ op.execute("DROP VIEW IF EXISTS grafana.active_users_daily;")
423
+ op.execute("DROP VIEW IF EXISTS grafana.active_user_day;")
424
+ op.execute("DROP VIEW IF EXISTS grafana.feature_request;")
425
+ op.execute("DROP VIEW IF EXISTS grafana.endpoint_feature;")
426
+ op.execute("DROP VIEW IF EXISTS grafana.auth_event_daily;")
427
+ op.execute("DROP VIEW IF EXISTS grafana.auth_event;")
428
+ op.drop_index(
429
+ "auth_event_login_keycloak_session_key", table_name="auth_event", schema=SCHEMA
430
+ )
431
+ op.drop_index(
432
+ "auth_event_event_type_created_at_idx", table_name="auth_event", schema=SCHEMA
433
+ )
434
+ op.drop_index("auth_event_created_at_idx", table_name="auth_event", schema=SCHEMA)
435
+ op.drop_table("auth_event", schema=SCHEMA)
436
+ op.execute(f"DROP TYPE IF EXISTS {SCHEMA}.auth_event_type;")
@@ -50,3 +50,12 @@ class QuestionType(StrEnum):
50
50
  TEXT = auto()
51
51
  CHECKBOX = auto()
52
52
  PREDEFINED_TEXT = auto()
53
+
54
+
55
+ class AuthEventType(StrEnum):
56
+ # an email account created through WeLearn's sign-up form
57
+ SIGNUP = auto()
58
+ # a Keycloak account seen by WeLearn for the first time (first Google, university or email login)
59
+ ACCOUNT_CREATED = auto()
60
+ LOGIN = auto()
61
+ LOGOUT = auto()
@@ -11,6 +11,62 @@ from welearn_database.data.models import Base
11
11
  schema_name = DbSchemaEnum.GRAFANA.value
12
12
 
13
13
 
14
+ class ActiveUserDay(Base):
15
+ __tablename__ = "active_user_day"
16
+ __table_args__ = {"schema": schema_name}
17
+ __read_only__ = True
18
+
19
+ day: Mapped[datetime] = mapped_column(primary_key=True)
20
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(
21
+ UUID(as_uuid=True), primary_key=True
22
+ )
23
+ user_kind: Mapped[str] = mapped_column()
24
+ requests: Mapped[int] = mapped_column()
25
+
26
+
27
+ class ActiveUsersDaily(Base):
28
+ __tablename__ = "active_users_daily"
29
+ __table_args__ = {"schema": schema_name}
30
+ __read_only__ = True
31
+
32
+ day: Mapped[datetime] = mapped_column(primary_key=True)
33
+ user_kind: Mapped[str] = mapped_column(primary_key=True)
34
+ active_users: Mapped[int] = mapped_column()
35
+ requests: Mapped[int] = mapped_column()
36
+
37
+
38
+ class AuthEvent(Base):
39
+ __tablename__ = "auth_event"
40
+ __table_args__ = {"schema": schema_name}
41
+ __read_only__ = True
42
+
43
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
44
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
45
+ session_id: Mapped[uuid.UUID | None] = mapped_column(
46
+ UUID(as_uuid=True), nullable=True
47
+ )
48
+ event_type: Mapped[str] = mapped_column()
49
+ identity_provider: Mapped[str | None] = mapped_column(nullable=True)
50
+ is_limited_access: Mapped[bool] = mapped_column()
51
+ created_at: Mapped[datetime] = mapped_column()
52
+ host: Mapped[str | None] = mapped_column(nullable=True)
53
+
54
+
55
+ class AuthEventDaily(Base):
56
+ __tablename__ = "auth_event_daily"
57
+ __table_args__ = {"schema": schema_name}
58
+ __read_only__ = True
59
+
60
+ # the view has no id: its grouping columns identify a row
61
+ day: Mapped[datetime] = mapped_column(primary_key=True)
62
+ event_type: Mapped[str] = mapped_column(primary_key=True)
63
+ provider: Mapped[str] = mapped_column(primary_key=True)
64
+ is_limited_access: Mapped[bool] = mapped_column(primary_key=True)
65
+ identity_provider: Mapped[str | None] = mapped_column(nullable=True)
66
+ events: Mapped[int] = mapped_column()
67
+ users: Mapped[int] = mapped_column()
68
+
69
+
14
70
  class Corpus(Base):
15
71
  __tablename__ = "corpus"
16
72
  __table_args__ = {"schema": schema_name}
@@ -61,6 +117,15 @@ class DocumentStateSummary(Base):
61
117
  total_documents: Mapped[int] = mapped_column()
62
118
 
63
119
 
120
+ class EndpointFeature(Base):
121
+ __tablename__ = "endpoint_feature"
122
+ __table_args__ = {"schema": schema_name}
123
+ __read_only__ = True
124
+
125
+ endpoint_pattern: Mapped[str] = mapped_column(primary_key=True)
126
+ feature: Mapped[str] = mapped_column()
127
+
128
+
64
129
  class EndpointRequest(Base):
65
130
  __tablename__ = "endpoint_request"
66
131
  __table_args__ = {"schema": schema_name}
@@ -74,6 +139,53 @@ class EndpointRequest(Base):
74
139
  created_at: Mapped[datetime] = mapped_column()
75
140
 
76
141
 
142
+ class FeatureRequest(Base):
143
+ __tablename__ = "feature_request"
144
+ __table_args__ = {"schema": schema_name}
145
+ __read_only__ = True
146
+
147
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
148
+ session_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
149
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
150
+ user_kind: Mapped[str] = mapped_column()
151
+ feature: Mapped[str] = mapped_column()
152
+ created_at: Mapped[datetime] = mapped_column()
153
+
154
+
155
+ class FeatureUsageDaily(Base):
156
+ __tablename__ = "feature_usage_daily"
157
+ __table_args__ = {"schema": schema_name}
158
+ __read_only__ = True
159
+
160
+ day: Mapped[datetime] = mapped_column(primary_key=True)
161
+ feature: Mapped[str] = mapped_column(primary_key=True)
162
+ user_kind: Mapped[str] = mapped_column(primary_key=True)
163
+ users: Mapped[int] = mapped_column()
164
+ requests: Mapped[int] = mapped_column()
165
+
166
+
167
+ class GuestLimitHit(Base):
168
+ __tablename__ = "guest_limit_hit"
169
+ __table_args__ = {"schema": schema_name}
170
+ __read_only__ = True
171
+
172
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
173
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
174
+ feature: Mapped[str] = mapped_column()
175
+ created_at: Mapped[datetime] = mapped_column()
176
+
177
+
178
+ class GuestLimitHitsDaily(Base):
179
+ __tablename__ = "guest_limit_hits_daily"
180
+ __table_args__ = {"schema": schema_name}
181
+ __read_only__ = True
182
+
183
+ day: Mapped[datetime] = mapped_column(primary_key=True)
184
+ feature: Mapped[str] = mapped_column(primary_key=True)
185
+ users: Mapped[int] = mapped_column()
186
+ refusals: Mapped[int] = mapped_column()
187
+
188
+
77
189
  class InferredUser(Base):
78
190
  __tablename__ = "inferred_user"
79
191
  __table_args__ = {"schema": schema_name}
@@ -83,6 +195,16 @@ class InferredUser(Base):
83
195
  created_at: Mapped[datetime] = mapped_column()
84
196
 
85
197
 
198
+ class NewUsersDaily(Base):
199
+ __tablename__ = "new_users_daily"
200
+ __table_args__ = {"schema": schema_name}
201
+ __read_only__ = True
202
+
203
+ day: Mapped[datetime] = mapped_column(primary_key=True)
204
+ new_users: Mapped[int] = mapped_column()
205
+ with_account: Mapped[int] = mapped_column()
206
+
207
+
86
208
  class ProcessState(Base):
87
209
  __tablename__ = "process_state"
88
210
  __table_args__ = {"schema": schema_name}
@@ -5,7 +5,12 @@ from sqlalchemy import Computed, ForeignKey, Index, func, text, types
5
5
  from sqlalchemy.dialects.postgresql import ENUM, TIMESTAMP
6
6
  from sqlalchemy.orm import Mapped, mapped_column, relationship
7
7
 
8
- from welearn_database.data.enumeration import DbSchemaEnum, FilterType, QuestionType
8
+ from welearn_database.data.enumeration import (
9
+ AuthEventType,
10
+ DbSchemaEnum,
11
+ FilterType,
12
+ QuestionType,
13
+ )
9
14
  from welearn_database.data.models.document_related import WeLearnDocument
10
15
 
11
16
  from . import Base
@@ -440,3 +445,78 @@ class GuestFeatureUsage(Base):
440
445
  )
441
446
  inferred_user: Mapped["InferredUser"] = relationship()
442
447
  feature: Mapped["Feature"] = relationship()
448
+
449
+
450
+ # the API records one login per Keycloak session; this filter lets a concurrent
451
+ # second insert of the same login fail on the unique index instead of duplicating it
452
+ _ONE_LOGIN_PER_KEYCLOAK_SESSION = text(
453
+ "event_type = 'login' AND keycloak_session_id IS NOT NULL"
454
+ )
455
+
456
+
457
+ class AuthEvent(Base):
458
+ """
459
+ An authentication event of a user: a sign-up through WeLearn's form, an
460
+ account seen for the first time, a login or a logout. The user is only
461
+ known by its pseudonymous inferred_user id: no email or name is stored.
462
+ identity_provider is the Keycloak IdP alias (google, a university...), NULL
463
+ for email/password or when unknown.
464
+ """
465
+
466
+ __tablename__ = "auth_event"
467
+ __table_args__ = (
468
+ Index("auth_event_created_at_idx", "created_at"),
469
+ Index("auth_event_event_type_created_at_idx", "event_type", "created_at"),
470
+ Index(
471
+ "auth_event_login_keycloak_session_key",
472
+ "inferred_user_id",
473
+ "keycloak_session_id",
474
+ unique=True,
475
+ postgresql_where=_ONE_LOGIN_PER_KEYCLOAK_SESSION,
476
+ sqlite_where=_ONE_LOGIN_PER_KEYCLOAK_SESSION,
477
+ ),
478
+ {"schema": DbSchemaEnum.USER_RELATED.value},
479
+ )
480
+
481
+ id: Mapped[UUID] = mapped_column(
482
+ types.Uuid, primary_key=True, nullable=False, server_default="gen_random_uuid()"
483
+ )
484
+ inferred_user_id: Mapped[UUID] = mapped_column(
485
+ types.Uuid,
486
+ ForeignKey(
487
+ f"{DbSchemaEnum.USER_RELATED.value}.inferred_user.id",
488
+ name="auth_event_inferred_user_id_fkey",
489
+ ondelete="CASCADE",
490
+ ),
491
+ nullable=False,
492
+ )
493
+ session_id: Mapped[UUID | None] = mapped_column(
494
+ types.Uuid,
495
+ ForeignKey(
496
+ f"{DbSchemaEnum.USER_RELATED.value}.session.id",
497
+ name="auth_event_session_id_fkey",
498
+ ondelete="SET NULL",
499
+ ),
500
+ nullable=True,
501
+ )
502
+ event_type: Mapped[str] = mapped_column(
503
+ ENUM(
504
+ *(e.value for e in AuthEventType),
505
+ name="auth_event_type",
506
+ schema=DbSchemaEnum.USER_RELATED.value,
507
+ # SQLite has no enum type: a CHECK keeps the same rule in the tests
508
+ create_constraint=True,
509
+ ),
510
+ nullable=False,
511
+ )
512
+ identity_provider: Mapped[str | None]
513
+ is_limited_access: Mapped[bool]
514
+ keycloak_session_id: Mapped[str | None]
515
+ created_at: Mapped[datetime] = mapped_column(
516
+ TIMESTAMP(timezone=False),
517
+ nullable=False,
518
+ default=func.localtimestamp(),
519
+ server_default="NOW()",
520
+ )
521
+ inferred_user: Mapped["InferredUser"] = relationship()
522
+ session: Mapped["Session | None"] = relationship()