Repository navigation
feat(usage): add the event Usage page and CSV export (#1166) #1481
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
7ea4598
dc0a3cc
5c1e547
48cacd1
56d6571
dcfef25
9a1371a
7e01c85
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """add usage records | ||
| Hourly totals of what each event used (#1166): seconds of audio transcribed, characters | ||
| translated, seconds of AI voice made, and listening time and connections per channel. | ||
| Revision ID: 054 | ||
| Revises: 053 | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import sqlalchemy as sa | ||
|
|
||
| from alembic import op | ||
|
|
||
| revision = "054" | ||
| down_revision = "053" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| op.create_table( | ||
| "usage_records", | ||
| sa.Column("id", sa.Integer(), primary_key=True), | ||
| sa.Column("event_id", sa.Integer(), sa.ForeignKey("events.id", ondelete="CASCADE"), nullable=False), | ||
| sa.Column("room_id", sa.Integer(), nullable=True), | ||
| sa.Column("service", sa.String(length=20), nullable=False), | ||
| sa.Column("provider", sa.String(length=32), nullable=False), | ||
| sa.Column("model", sa.String(length=100), nullable=False), | ||
| sa.Column("language_code", sa.String(length=10), nullable=False), | ||
| sa.Column("unit", sa.String(length=16), nullable=False), | ||
| sa.Column("quantity", sa.Float(), nullable=False), | ||
| sa.Column("period_start", sa.DateTime(timezone=True), nullable=False), | ||
| sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), | ||
| ) | ||
| op.create_index( | ||
| "uq_usage_records_bucket", | ||
| "usage_records", | ||
| ["event_id", "period_start", "room_id", "service", "provider", "model", "language_code"], | ||
| unique=True, | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| op.drop_index("uq_usage_records_bucket", table_name="usage_records") | ||
| op.drop_table("usage_records") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,7 +17,7 @@ | |
| from starlette.middleware.base import BaseHTTPMiddleware | ||
| from unilimit.integrations.fastapi import RateLimitExceeded, setup | ||
|
|
||
| from portal import meeting_source, program_ingest, youtube_caption_sync | ||
| from portal import meeting_source, program_ingest, usage, youtube_caption_sync | ||
| from portal.auth import ( | ||
| ADMIN_CSRF_COOKIE, | ||
| generate_admin_csrf_token, | ||
|
|
@@ -45,6 +45,7 @@ | |
| from portal.routers.program_ingest import router as program_ingest_router | ||
| from portal.routers.public import router as public_router | ||
| from portal.routers.translation_models import router as translation_models_router | ||
| from portal.routers.usage import router as usage_router | ||
| from portal.routers.webhooks import router as webhooks_router | ||
| from portal.routers.youtube import router as youtube_router | ||
| from portal.security_headers import SecurityHeadersMiddleware, apply_security_headers, forwarded_https | ||
|
|
@@ -113,6 +114,8 @@ async def _gen(): | |
| ingest_task = asyncio.create_task(program_ingest.reconcile_loop()) if settings.program_ingest_enabled else None | ||
| meeting_task = asyncio.create_task(meeting_source.reconcile_loop()) | ||
| attendance_task = asyncio.create_task(booths.attendance.run()) | ||
| usage_task = asyncio.create_task(usage.meter.run()) | ||
| listening_task = asyncio.create_task(usage.ListeningSampler(usage.meter).run()) | ||
| # Restores saved YouTube caption choices after a restart and keeps them in step (#1087, plan 006). | ||
| captions_task = ( | ||
| asyncio.create_task(youtube_caption_sync.reconcile_loop()) if settings.youtube_connect_enabled else None | ||
|
|
@@ -135,7 +138,16 @@ async def _gen(): | |
| logging.getLogger("uvicorn.access").addFilter(_HealthCheckFilter()) | ||
| yield | ||
|
|
||
| tasks_to_cancel = [reaper_task, webhook_task, notification_task, rate_limit_cleanup_task, meeting_task, attendance_task] | ||
| tasks_to_cancel = [ | ||
| reaper_task, | ||
| webhook_task, | ||
| notification_task, | ||
| rate_limit_cleanup_task, | ||
| meeting_task, | ||
| attendance_task, | ||
| usage_task, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Usage recorded after the final meter flush is lost on shutdown. Lifespan cancels The loss covers only usage accepted during the teardown window for each active session. It repeats on every restart while sessions are active. Stop and await active transcription sessions before cancelling Locations:
|
||
| listening_task, | ||
| ] | ||
| if ingest_task: | ||
| tasks_to_cancel.append(ingest_task) | ||
| if recovery_task: | ||
|
|
@@ -417,6 +429,7 @@ async def general_exception_handler(request: Request, exc: Exception): | |
| app.include_router(youtube_router) | ||
| app.include_router(meeting_source_router) | ||
| app.include_router(attendance_router) | ||
| app.include_router(usage_router) | ||
| app.include_router(translation_models_router) | ||
| app.include_router(meeting_analysis_router) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -775,6 +775,47 @@ def __repr__(self) -> str: | |
| return f"<UsageMetric event={self.event_id} metric={self.metric_name!r} value={self.value}>" | ||
|
|
||
|
|
||
| class UsageRecord(Base): | ||
| """How much of one service an event used in one hour (#1166). | ||
|
|
||
| Written in batches by ``portal.usage`` (never on the live path): each save adds to the | ||
| row for its hour, room, service, provider, model and language. ``quantity`` is in | ||
| ``unit`` (seconds, characters or connections), so rows of one service add up. | ||
| """ | ||
|
|
||
| __tablename__ = "usage_records" | ||
| __table_args__ = ( | ||
| Index( | ||
| "uq_usage_records_bucket", | ||
| "event_id", | ||
| "period_start", | ||
| "room_id", | ||
| "service", | ||
| "provider", | ||
| "model", | ||
| "language_code", | ||
| unique=True, | ||
| ), | ||
| ) | ||
|
|
||
| id: Mapped[int] = mapped_column(primary_key=True) | ||
| event_id: Mapped[int] = mapped_column(ForeignKey("events.id", ondelete="CASCADE")) | ||
| # A plain value, not a foreign key: usage stays after a room is removed. | ||
| room_id: Mapped[int | None] = mapped_column(Integer, nullable=True) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deleted-room usage can take a replacement room's name and bucket.
When the old and replacement rooms share an event, service, provider, model, language, and hour, their usage also merges into one bucket, because the unique index includes The same reuse can drop usage. If the replacement room belongs to another event, Room identity must not be reused while usage rows refer to it. Historical usage must stay attributed to the deleted room. Fixing identity at the room level also removes the cross-event discard.
|
||
| service: Mapped[str] = mapped_column(String(20)) | ||
| provider: Mapped[str] = mapped_column(String(32), default="") | ||
| model: Mapped[str] = mapped_column(String(100), default="") | ||
| language_code: Mapped[str] = mapped_column(String(10), default="") | ||
| unit: Mapped[str] = mapped_column(String(16)) | ||
| quantity: Mapped[float] = mapped_column(sa.Float, default=0.0) | ||
| # Start of the UTC hour the usage happened in. | ||
| period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True)) | ||
| updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now) | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"<UsageRecord event={self.event_id} service={self.service!r} quantity={self.quantity}>" | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Interpreter attendance (#1215) | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium · Roomless usage is counted twice
When separate portal processes save the same roomless usage bucket concurrently, the unique index permits duplicate rows when
room_idis NULL, so both saves insert a row and later updates add usage to each; reports count the bucket more than once.Enforce uniqueness for NULL room IDs and use an atomic upsert for the bucket.
Also at
portal/usage.py:262-276,portal/models.py:788-798.