keepup-admin 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/events.py ADDED
@@ -0,0 +1,764 @@
1
+ """The application's event log.
2
+
3
+ Not the request audit (`keepup/audit.py`) and not the application log
4
+ (`keepup/logging_setup.py`): this records things that happened in the product's
5
+ own terms -- somebody signed in, an order was accepted, a job failed -- so that
6
+ they can be read back by type and by actor long after the log files rotated.
7
+
8
+ Which types exist is the application's business and arrives through
9
+ KeepupSettings: the framework holds the table, the API and the retention, and
10
+ knows none of the names. See `doc/event_manager.md`.
11
+ """
12
+
13
+ import logging
14
+ import json
15
+ from datetime import datetime, timedelta
16
+ from typing import Optional, List, Dict, Any
17
+ from fastapi import HTTPException, Query, Depends
18
+ from pydantic import BaseModel, Field
19
+ from sqlalchemy import Column, DateTime, Index, String, Text
20
+ from sqlalchemy.dialects import postgresql
21
+
22
+ from keepup import tables
23
+ from keepup.db import DatabaseManager
24
+ from keepup.db import db_config
25
+ from keepup.instance import get_instance_id, get_instance_name
26
+ from keepup.auth.dependencies import get_current_admin
27
+
28
+ #: What an application may import from this module. Everything else is
29
+ #: internal and may change without notice -- see doc/keepup.md.
30
+ __all__ = [
31
+ "emit_event",
32
+ "init_event_manager",
33
+ "register_event_api_routes",
34
+ ]
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ APP_EVENTS = tables.table(
39
+ "app_events",
40
+ tables.big_auto_id(),
41
+ Column("event_type", String(100), nullable=False),
42
+ Column("event_text", Text, nullable=False),
43
+ Column("event_data", postgresql.JSONB().with_variant(Text(), "sqlite")),
44
+ Column("instance_id", String(100), nullable=False),
45
+ Column("instance_name", String(100)),
46
+ Column("created_at", DateTime, server_default=tables.NOW),
47
+ Index("idx_app_events_event_type", "event_type"),
48
+ Index("idx_app_events_instance_id", "instance_id"),
49
+ Index("idx_app_events_instance_name", "instance_name"),
50
+ )
51
+ # Newest first, as the listing pages; the type-and-date pair was only ever
52
+ # created on PostgreSQL.
53
+ Index("idx_app_events_created_at", APP_EVENTS.c.created_at.desc())
54
+ Index("idx_app_events_type_date", APP_EVENTS.c.event_type,
55
+ APP_EVENTS.c.created_at.desc()).ddl_if(dialect="postgresql")
56
+
57
+
58
+ class AppEvent(BaseModel):
59
+ """Application event."""
60
+ id: Optional[int] = None
61
+ event_type: str = Field(..., description="Event type, for example 'user_login', 'payment_success', 'error'")
62
+ event_text: str = Field(..., description="Event text")
63
+ event_data: Optional[Dict[str, Any]] = Field(None, description="Extra event payload, as JSON")
64
+ instance_id: Optional[str] = Field(None, description="Id of the instance that produced the event")
65
+ instance_name: Optional[str] = Field(None, description="Name of the instance that produced the event")
66
+ created_at: Optional[datetime] = Field(None, description="When the event was created")
67
+
68
+
69
+ class EventCreate(BaseModel):
70
+ """Payload for creating an event."""
71
+ event_type: str = Field(..., min_length=1, max_length=100, description="Event type")
72
+ event_text: str = Field(..., min_length=1, description="Event text")
73
+ event_data: Optional[Dict[str, Any]] = Field(None, description="Extra payload")
74
+
75
+
76
+ class EventListResponse(BaseModel):
77
+ """Response carrying a list of events."""
78
+ events: List[Dict[str, Any]]
79
+ total: int
80
+ page: int
81
+ page_size: int
82
+ total_pages: int
83
+
84
+
85
+ class EventManager:
86
+ """Application event manager."""
87
+
88
+ def __init__(self):
89
+ self.instance_id = get_instance_id()
90
+ self.instance_name = get_instance_name()
91
+ self._initialized = False
92
+
93
+ def init_table(self):
94
+ """Create the app_events table."""
95
+ try:
96
+ tables.ensure_tables(APP_EVENTS)
97
+ self._initialized = True
98
+ logger.info(f"App events table initialized successfully (instance: {self.instance_name})")
99
+
100
+ except Exception as e:
101
+ logger.error(f"Error initializing app events table: {str(e)}")
102
+ raise
103
+
104
+ async def create_event(
105
+ self,
106
+ event_type: str,
107
+ event_text: str,
108
+ event_data: Optional[Dict[str, Any]] = None,
109
+ instance_id: Optional[str] = None,
110
+ instance_name: Optional[str] = None
111
+ ) -> int:
112
+ """Create an event.
113
+
114
+ Args:
115
+ event_type: event type
116
+ event_text: event text
117
+ event_data: optional extra payload
118
+ instance_id: instance id, defaults to the current instance
119
+ instance_name: instance name, defaults to the current instance
120
+
121
+ Returns:
122
+ int: id of the created event.
123
+ """
124
+ if not self._initialized:
125
+ self.init_table()
126
+
127
+ try:
128
+ event_instance_id = instance_id or self.instance_id
129
+ event_instance_name = instance_name or self.instance_name
130
+
131
+ event_data_json = json.dumps(event_data, ensure_ascii=False) if event_data else None
132
+
133
+ if db_config.is_postgres():
134
+ query = '''
135
+ INSERT INTO app_events (event_type, event_text, event_data, instance_id, instance_name)
136
+ VALUES (%s, %s, %s, %s, %s)
137
+ RETURNING id
138
+ '''
139
+ params = (event_type, event_text, event_data_json, event_instance_id, event_instance_name)
140
+ else:
141
+ query = '''
142
+ INSERT INTO app_events (event_type, event_text, event_data, instance_id, instance_name)
143
+ VALUES (?, ?, ?, ?, ?)
144
+ '''
145
+ params = (event_type, event_text, event_data_json, event_instance_id, event_instance_name)
146
+
147
+ conn = DatabaseManager.get_connection()
148
+ cursor = conn.cursor()
149
+
150
+ try:
151
+ cursor.execute(query, params)
152
+ conn.commit()
153
+
154
+ if db_config.is_postgres():
155
+ event_id = cursor.fetchone()["id"]
156
+ else:
157
+ event_id = cursor.lastrowid
158
+
159
+ logger.debug(f"Event created: {event_type} - {event_text[:50]} (instance: {event_instance_name})")
160
+ return event_id
161
+
162
+ finally:
163
+ cursor.close()
164
+ conn.close()
165
+
166
+ except Exception as e:
167
+ logger.error(f"Error creating event: {str(e)}")
168
+ raise
169
+
170
+ async def get_events(
171
+ self,
172
+ event_type: Optional[str] = None,
173
+ instance_id: Optional[str] = None,
174
+ instance_name: Optional[str] = None,
175
+ start_date: Optional[datetime] = None,
176
+ end_date: Optional[datetime] = None,
177
+ page: int = 1,
178
+ page_size: int = 50
179
+ ) -> Dict[str, Any]:
180
+ """Return events, filtered and paginated.
181
+
182
+ Args:
183
+ event_type: filter by event type
184
+ instance_id: filter by instance id
185
+ instance_name: filter by instance name
186
+ start_date: lower date bound
187
+ end_date: upper date bound
188
+ page: page number, starting at 1
189
+ page_size: page size
190
+
191
+ Returns:
192
+ Dict with the events and their metadata.
193
+ """
194
+ if not self._initialized:
195
+ self.init_table()
196
+
197
+ try:
198
+ conditions = []
199
+ params = []
200
+
201
+ if event_type:
202
+ conditions.append("event_type = ?" if not db_config.is_postgres() else "event_type = %s")
203
+ params.append(event_type)
204
+
205
+ if instance_id:
206
+ conditions.append("instance_id = ?" if not db_config.is_postgres() else "instance_id = %s")
207
+ params.append(instance_id)
208
+
209
+ if instance_name:
210
+ conditions.append("instance_name = ?" if not db_config.is_postgres() else "instance_name = %s")
211
+ params.append(instance_name)
212
+
213
+ if start_date:
214
+ conditions.append("created_at >= ?" if not db_config.is_postgres() else "created_at >= %s")
215
+ params.append(start_date)
216
+
217
+ if end_date:
218
+ conditions.append("created_at <= ?" if not db_config.is_postgres() else "created_at <= %s")
219
+ params.append(end_date)
220
+
221
+ where_clause = f"WHERE {' AND '.join(conditions)}" if conditions else ""
222
+
223
+ count_query = f"SELECT COUNT(*) as total FROM app_events {where_clause}"
224
+
225
+ if db_config.is_postgres():
226
+ count_query = count_query.replace('?', '%s')
227
+
228
+ conn = DatabaseManager.get_connection()
229
+ cursor = conn.cursor()
230
+
231
+ try:
232
+ cursor.execute(count_query, params)
233
+ total_result = cursor.fetchone()
234
+ total = total_result['total'] if total_result else 0
235
+
236
+ offset = (page - 1) * page_size
237
+
238
+ select_query = f'''
239
+ SELECT id, event_type, event_text, event_data, instance_id, instance_name, created_at
240
+ FROM app_events
241
+ {where_clause}
242
+ ORDER BY created_at DESC
243
+ LIMIT ? OFFSET ?
244
+ ''' if not db_config.is_postgres() else f'''
245
+ SELECT id, event_type, event_text, event_data, instance_id, instance_name, created_at
246
+ FROM app_events
247
+ {where_clause}
248
+ ORDER BY created_at DESC
249
+ LIMIT %s OFFSET %s
250
+ '''
251
+
252
+ query_params = params + [page_size, offset]
253
+ if db_config.is_postgres():
254
+ select_query = select_query.replace('?', '%s')
255
+
256
+ cursor.execute(select_query, query_params)
257
+ rows = cursor.fetchall()
258
+
259
+ events = []
260
+ for row in rows:
261
+ event = {
262
+ 'id': row['id'],
263
+ 'event_type': row['event_type'],
264
+ 'event_text': row['event_text'],
265
+ 'instance_id': row['instance_id'],
266
+ 'instance_name': row['instance_name'] if len(row) > 5 else None,
267
+ 'created_at': row['created_at'].isoformat() if len(row) > 6 and hasattr(row['created_at'], 'isoformat') else str(
268
+ row['created_at']) if len(row) > 6 else None
269
+ }
270
+
271
+ if len(row) > 3 and row['event_text']:
272
+ try:
273
+ if isinstance(row['event_text'], str):
274
+ event['event_data'] = json.loads(row['event_text'])
275
+ else:
276
+ event['event_data'] = row['event_text']
277
+ except:
278
+ event['event_data'] = row['event_text']
279
+
280
+ events.append(event)
281
+
282
+ total_pages = (total + page_size - 1) // page_size
283
+
284
+ return {
285
+ 'events': events,
286
+ 'total': total,
287
+ 'page': page,
288
+ 'page_size': page_size,
289
+ 'total_pages': total_pages
290
+ }
291
+
292
+ finally:
293
+ cursor.close()
294
+ conn.close()
295
+
296
+ except Exception as e:
297
+ logger.error(f"Error getting events: {str(e)}")
298
+ raise
299
+
300
+ async def get_event_types(self) -> List[str]:
301
+ """Return every distinct event type.
302
+
303
+ Returns:
304
+ List[str]: the event types.
305
+ """
306
+ if not self._initialized:
307
+ self.init_table()
308
+
309
+ try:
310
+ query = '''
311
+ SELECT DISTINCT event_type
312
+ FROM app_events
313
+ ORDER BY event_type
314
+ '''
315
+
316
+ if db_config.is_postgres():
317
+ query = query.replace('?', '%s')
318
+
319
+ conn = DatabaseManager.get_connection()
320
+ cursor = conn.cursor()
321
+
322
+ try:
323
+ cursor.execute(query)
324
+ rows = cursor.fetchall()
325
+ return [row['event_type'] for row in rows]
326
+ finally:
327
+ cursor.close()
328
+ conn.close()
329
+
330
+ except Exception as e:
331
+ logger.error(f"Error getting event types: {str(e)}")
332
+ return []
333
+
334
+ async def get_instances(self) -> List[Dict[str, str]]:
335
+ """Return every instance that has produced events.
336
+
337
+ Returns:
338
+ List[Dict]: instances with their id and name.
339
+ """
340
+ if not self._initialized:
341
+ self.init_table()
342
+
343
+ try:
344
+ query = '''
345
+ SELECT DISTINCT instance_id, instance_name
346
+ FROM app_events
347
+ WHERE instance_name IS NOT NULL
348
+ ORDER BY instance_name
349
+ '''
350
+
351
+ if db_config.is_postgres():
352
+ query = query.replace('?', '%s')
353
+
354
+ conn = DatabaseManager.get_connection()
355
+ cursor = conn.cursor()
356
+
357
+ try:
358
+ cursor.execute(query)
359
+ rows = cursor.fetchall()
360
+ return [
361
+ {
362
+ 'instance_id': row['instance_id'],
363
+ 'instance_name': row['instance_name']
364
+ }
365
+ for row in rows
366
+ ]
367
+ finally:
368
+ cursor.close()
369
+ conn.close()
370
+
371
+ except Exception as e:
372
+ logger.error(f"Error getting instances: {str(e)}")
373
+ return []
374
+
375
+ async def delete_old_events(self, days: int = 30) -> int:
376
+ """Delete events older than the given number of days.
377
+
378
+ Args:
379
+ days: age threshold in days, 30 by default
380
+
381
+ Returns:
382
+ int: number of deleted events.
383
+ """
384
+ if not self._initialized:
385
+ self.init_table()
386
+
387
+ try:
388
+ # The boundary is computed here rather than written into the
389
+ # statement. It used to be `INTERVAL '%s days'` -- the placeholder
390
+ # inside a string literal, where the driver's quoting does not
391
+ # reach: a string argument would have left the literal. Nothing
392
+ # exploited it only because the one caller passes an int from a
393
+ # bounded query parameter, and this is a public method (keepup-15).
394
+ cutoff = datetime.utcnow() - timedelta(days=int(days))
395
+ if db_config.is_postgres():
396
+ query = '''
397
+ DELETE FROM app_events
398
+ WHERE created_at < %s
399
+ RETURNING id
400
+ '''
401
+ params = (cutoff,)
402
+ else:
403
+ query = '''
404
+ DELETE FROM app_events
405
+ WHERE created_at < ?
406
+ '''
407
+ params = (cutoff,)
408
+
409
+ conn = DatabaseManager.get_connection()
410
+ cursor = conn.cursor()
411
+
412
+ try:
413
+ cursor.execute(query, params)
414
+ conn.commit()
415
+
416
+ if db_config.is_postgres():
417
+ deleted_count = cursor.rowcount
418
+ else:
419
+ deleted_count = cursor.rowcount
420
+
421
+ if deleted_count > 0:
422
+ logger.info(f"Deleted {deleted_count} old events (older than {days} days)")
423
+
424
+ return deleted_count
425
+
426
+ finally:
427
+ cursor.close()
428
+ conn.close()
429
+
430
+ except Exception as e:
431
+ logger.error(f"Error deleting old events: {str(e)}")
432
+ return 0
433
+
434
+ async def get_events_stats(self) -> Dict[str, Any]:
435
+ """Return event statistics grouped by instance.
436
+
437
+ Returns:
438
+ Dict: the statistics.
439
+ """
440
+ if not self._initialized:
441
+ self.init_table()
442
+
443
+ try:
444
+ if db_config.is_postgres():
445
+ type_stats_query = '''
446
+ SELECT
447
+ event_type,
448
+ COUNT(*) as count,
449
+ MIN(created_at) as first_event,
450
+ MAX(created_at) as last_event
451
+ FROM app_events
452
+ GROUP BY event_type
453
+ ORDER BY count DESC
454
+ '''
455
+
456
+ instance_stats_query = '''
457
+ SELECT
458
+ instance_id,
459
+ instance_name,
460
+ COUNT(*) as event_count,
461
+ MIN(created_at) as first_event,
462
+ MAX(created_at) as last_event
463
+ FROM app_events
464
+ GROUP BY instance_id, instance_name
465
+ ORDER BY event_count DESC
466
+ '''
467
+ else:
468
+ type_stats_query = '''
469
+ SELECT
470
+ event_type,
471
+ COUNT(*) as count,
472
+ MIN(created_at) as first_event,
473
+ MAX(created_at) as last_event
474
+ FROM app_events
475
+ GROUP BY event_type
476
+ ORDER BY count DESC
477
+ '''
478
+
479
+ instance_stats_query = '''
480
+ SELECT
481
+ instance_id,
482
+ instance_name,
483
+ COUNT(*) as event_count,
484
+ MIN(created_at) as first_event,
485
+ MAX(created_at) as last_event
486
+ FROM app_events
487
+ GROUP BY instance_id, instance_name
488
+ ORDER BY event_count DESC
489
+ '''
490
+
491
+ conn = DatabaseManager.get_connection()
492
+ cursor = conn.cursor()
493
+
494
+ try:
495
+ cursor.execute(type_stats_query)
496
+ type_rows = cursor.fetchall()
497
+
498
+ type_stats = []
499
+ for row in type_rows:
500
+ type_stats.append({
501
+ 'event_type': row[0],
502
+ 'count': row[1],
503
+ 'first_event': row[2].isoformat() if hasattr(row[2], 'isoformat') else str(row[2]),
504
+ 'last_event': row[3].isoformat() if hasattr(row[3], 'isoformat') else str(row[3])
505
+ })
506
+
507
+ cursor.execute(instance_stats_query)
508
+ instance_rows = cursor.fetchall()
509
+
510
+ instance_stats = []
511
+ for row in instance_rows:
512
+ instance_stats.append({
513
+ 'instance_id': row[0],
514
+ 'instance_name': row[1],
515
+ 'event_count': row[2],
516
+ 'first_event': row[3].isoformat() if hasattr(row[3], 'isoformat') else str(row[3]),
517
+ 'last_event': row[4].isoformat() if hasattr(row[4], 'isoformat') else str(row[4])
518
+ })
519
+
520
+ total_count = sum(stat['count'] for stat in type_stats)
521
+
522
+ return {
523
+ "total_events": total_count,
524
+ "unique_event_types": len(type_stats),
525
+ "unique_instances": len(instance_stats),
526
+ "event_types": type_stats,
527
+ "instances": instance_stats,
528
+ "current_instance": {
529
+ "id": self.instance_id,
530
+ "name": self.instance_name
531
+ }
532
+ }
533
+
534
+ finally:
535
+ cursor.close()
536
+ conn.close()
537
+
538
+ except Exception as e:
539
+ logger.error(f"Error getting events stats: {str(e)}")
540
+ return {
541
+ "total_events": 0,
542
+ "unique_event_types": 0,
543
+ "unique_instances": 0,
544
+ "event_types": [],
545
+ "instances": [],
546
+ "current_instance": {
547
+ "id": self.instance_id,
548
+ "name": self.instance_name
549
+ }
550
+ }
551
+
552
+
553
+ event_manager = EventManager()
554
+
555
+ async def emit_event(
556
+ event_type: str,
557
+ event_text: str,
558
+ event_data: Optional[Dict[str, Any]] = None,
559
+ instance_id: Optional[str] = None,
560
+ instance_name: Optional[str] = None
561
+ ) -> int:
562
+ """Emit an event from anywhere in the application.
563
+
564
+ Args:
565
+ event_type: event type
566
+ event_text: event text
567
+ event_data: optional extra payload
568
+ instance_id: instance id
569
+ instance_name: instance name
570
+
571
+ Returns:
572
+ int: id of the created event.
573
+ """
574
+ return await event_manager.create_event(
575
+ event_type=event_type,
576
+ event_text=event_text,
577
+ event_data=event_data,
578
+ instance_id=instance_id,
579
+ instance_name=instance_name
580
+ )
581
+
582
+
583
+ async def get_events_paginated(
584
+ event_type: Optional[str] = None,
585
+ instance_id: Optional[str] = None,
586
+ instance_name: Optional[str] = None,
587
+ start_date: Optional[datetime] = None,
588
+ end_date: Optional[datetime] = None,
589
+ page: int = 1,
590
+ page_size: int = 50
591
+ ) -> Dict[str, Any]:
592
+ """Return events with pagination."""
593
+ return await event_manager.get_events(
594
+ event_type=event_type,
595
+ instance_id=instance_id,
596
+ instance_name=instance_name,
597
+ start_date=start_date,
598
+ end_date=end_date,
599
+ page=page,
600
+ page_size=page_size
601
+ )
602
+
603
+
604
+ def register_event_api_routes(app, declared_event_types=None):
605
+ """Register the event API routes on the application.
606
+
607
+ ``declared_event_types`` is supplied by the application: a callable
608
+ returning the event types it declares in code but may never have emitted.
609
+ The framework has no catalogue of its own -- which types exist is a
610
+ property of the application, and reaching into it from here would point
611
+ the dependency the wrong way.
612
+ """
613
+
614
+ @app.post("/api/events", response_model=Dict[str, Any])
615
+ async def create_event_endpoint(
616
+ event: EventCreate,
617
+ current_user: dict = Depends(get_current_admin)
618
+ ):
619
+ """Create an event.
620
+
621
+ Administrators only. Audit events are written by the server itself at
622
+ the point the action happens (the application's audit helper), never
623
+ accepted over HTTP: a journal the watched party can fill is not
624
+ evidence. The event is attached to the current instance.
625
+ """
626
+ try:
627
+ event_id = await event_manager.create_event(
628
+ event_type=event.event_type,
629
+ event_text=event.event_text,
630
+ event_data=event.event_data
631
+ )
632
+
633
+ return {
634
+ "success": True,
635
+ "event_id": event_id,
636
+ "message": "Event created successfully",
637
+ "instance": {
638
+ "id": event_manager.instance_id,
639
+ "name": event_manager.instance_name
640
+ }
641
+ }
642
+ except Exception as e:
643
+ logger.error(f"Error in create_event_endpoint: {str(e)}")
644
+ raise HTTPException(status_code=500, detail=str(e))
645
+
646
+ @app.get("/api/events", response_model=EventListResponse)
647
+ async def get_events_endpoint(
648
+ event_type: Optional[str] = Query(None, description="Filter by event type"),
649
+ instance_id: Optional[str] = Query(None, description="Filter by instance id"),
650
+ instance_name: Optional[str] = Query(None, description="Filter by instance name"),
651
+ start_date: Optional[datetime] = Query(None, description="Lower date bound, ISO format"),
652
+ end_date: Optional[datetime] = Query(None, description="Upper date bound, ISO format"),
653
+ page: int = Query(1, ge=1, description="Page number"),
654
+ page_size: int = Query(50, ge=1, le=500, description="Page size"),
655
+ current_user: dict = Depends(get_current_admin)
656
+ ):
657
+ """Return events, filtered and paginated.
658
+
659
+ Administrators only: the journal holds logins, agent connections and
660
+ console entries of every user, which is the administrator's view of
661
+ the platform and not the user's own.
662
+ """
663
+ try:
664
+ result = await event_manager.get_events(
665
+ event_type=event_type,
666
+ instance_id=instance_id,
667
+ instance_name=instance_name,
668
+ start_date=start_date,
669
+ end_date=end_date,
670
+ page=page,
671
+ page_size=page_size
672
+ )
673
+
674
+ return result
675
+ except Exception as e:
676
+ logger.error(f"Error in get_events_endpoint: {str(e)}")
677
+ raise HTTPException(status_code=500, detail=str(e))
678
+
679
+ @app.get("/api/events/types")
680
+ async def get_event_types_endpoint(
681
+ current_user: dict = Depends(get_current_admin)
682
+ ):
683
+ """Every type the filter may offer: seen in the journal, or declared.
684
+
685
+ A list built only from what the table holds cannot offer a type that
686
+ has never occurred -- which is exactly the one an administrator asks
687
+ for when checking whether something happened at all. The declared
688
+ audit types are therefore added to the observed ones.
689
+
690
+ The declared types are supplied by the application through
691
+ ``register_event_api_routes``; the framework does not import the
692
+ application's audit catalogue.
693
+ """
694
+ try:
695
+ declared = list(declared_event_types() or ()) if declared_event_types else []
696
+
697
+ observed = await event_manager.get_event_types()
698
+ event_types = sorted(set(observed) | set(declared))
699
+ return {
700
+ "event_types": event_types,
701
+ "count": len(event_types)
702
+ }
703
+ except Exception as e:
704
+ logger.error(f"Error in get_event_types_endpoint: {str(e)}")
705
+ raise HTTPException(status_code=500, detail=str(e))
706
+
707
+ @app.get("/api/events/instances")
708
+ async def get_instances_endpoint(
709
+ current_user: dict = Depends(get_current_admin)
710
+ ):
711
+ """Return every instance that has produced events (administrators only)."""
712
+ try:
713
+ instances = await event_manager.get_instances()
714
+ return {
715
+ "instances": instances,
716
+ "count": len(instances),
717
+ "current_instance": {
718
+ "id": event_manager.instance_id,
719
+ "name": event_manager.instance_name
720
+ }
721
+ }
722
+ except Exception as e:
723
+ logger.error(f"Error in get_instances_endpoint: {str(e)}")
724
+ raise HTTPException(status_code=500, detail=str(e))
725
+
726
+ @app.delete("/api/events/cleanup")
727
+ async def cleanup_old_events_endpoint(
728
+ days: int = Query(30, ge=1, le=365, description="Delete events older than N days"),
729
+ current_user: dict = Depends(get_current_admin)
730
+ ):
731
+ """Delete old events (administrators only)."""
732
+ try:
733
+ deleted_count = await event_manager.delete_old_events(days)
734
+ return {
735
+ "success": True,
736
+ "deleted_count": deleted_count,
737
+ "message": f"Deleted {deleted_count} events older than {days} days"
738
+ }
739
+ except Exception as e:
740
+ logger.error(f"Error in cleanup_old_events_endpoint: {str(e)}")
741
+ raise HTTPException(status_code=500, detail=str(e))
742
+
743
+ @app.get("/api/events/stats")
744
+ async def get_events_stats_endpoint(
745
+ current_user: dict = Depends(get_current_admin)
746
+ ):
747
+ """Return extended event statistics (administrators only)."""
748
+ try:
749
+ stats = await event_manager.get_events_stats()
750
+ return stats
751
+ except Exception as e:
752
+ logger.error(f"Error in get_events_stats_endpoint: {str(e)}")
753
+ raise HTTPException(status_code=500, detail=str(e))
754
+
755
+
756
+ def init_event_manager():
757
+ """Initialise the event manager at application start."""
758
+ try:
759
+ event_manager.init_table()
760
+ logger.info(f"Event manager initialized successfully (instance: {event_manager.instance_name})")
761
+ return event_manager
762
+ except Exception as e:
763
+ logger.error(f"Failed to initialize event manager: {str(e)}")
764
+ return None