mirror of
https://github.com/Monadical-SAS/reflector.git
synced 2026-02-06 10:46:46 +00:00
Compare commits
6 Commits
fix-room-q
...
feature-le
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad64f43202 | ||
|
|
485b455c69 | ||
|
|
74c9ec2ff1 | ||
|
|
aac89e8d03 | ||
|
|
13088e72f8 | ||
|
|
775c9b667d |
12
.github/workflows/test_next_server.yml
vendored
12
.github/workflows/test_next_server.yml
vendored
@@ -13,9 +13,6 @@ on:
|
||||
jobs:
|
||||
test-next-server:
|
||||
runs-on: ubuntu-latest
|
||||
concurrency:
|
||||
group: test-next-server-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
defaults:
|
||||
run:
|
||||
@@ -24,12 +21,17 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
package_json_file: './www/package.json'
|
||||
version: 8
|
||||
|
||||
- name: Setup Node.js
|
||||
- name: Setup Node.js cache
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
"""drop_use_celery_column
|
||||
|
||||
Revision ID: 3aa20b96d963
|
||||
Revises: e69f08ead8ea
|
||||
Create Date: 2026-02-05 10:12:44.065279
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "3aa20b96d963"
|
||||
down_revision: Union[str, None] = "e69f08ead8ea"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("room", schema=None) as batch_op:
|
||||
batch_op.drop_column("use_celery")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("room", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"use_celery",
|
||||
sa.Boolean(),
|
||||
server_default=sa.text("false"),
|
||||
nullable=False,
|
||||
)
|
||||
)
|
||||
@@ -104,26 +104,6 @@ class CalendarEventController:
|
||||
results = await get_database().fetch_all(query)
|
||||
return [CalendarEvent(**result) for result in results]
|
||||
|
||||
async def get_upcoming_for_rooms(
|
||||
self, room_ids: list[str], minutes_ahead: int = 120
|
||||
) -> list[CalendarEvent]:
|
||||
now = datetime.now(timezone.utc)
|
||||
future_time = now + timedelta(minutes=minutes_ahead)
|
||||
query = (
|
||||
calendar_events.select()
|
||||
.where(
|
||||
sa.and_(
|
||||
calendar_events.c.room_id.in_(room_ids),
|
||||
calendar_events.c.is_deleted == False,
|
||||
calendar_events.c.start_time <= future_time,
|
||||
calendar_events.c.end_time >= now,
|
||||
)
|
||||
)
|
||||
.order_by(calendar_events.c.start_time.asc())
|
||||
)
|
||||
results = await get_database().fetch_all(query)
|
||||
return [CalendarEvent(**result) for result in results]
|
||||
|
||||
async def get_by_id(self, event_id: str) -> CalendarEvent | None:
|
||||
query = calendar_events.select().where(calendar_events.c.id == event_id)
|
||||
result = await get_database().fetch_one(query)
|
||||
|
||||
@@ -301,23 +301,6 @@ class MeetingController:
|
||||
results = await get_database().fetch_all(query)
|
||||
return [Meeting(**result) for result in results]
|
||||
|
||||
async def get_all_active_for_rooms(
|
||||
self, room_ids: list[str], current_time: datetime
|
||||
) -> list[Meeting]:
|
||||
query = (
|
||||
meetings.select()
|
||||
.where(
|
||||
sa.and_(
|
||||
meetings.c.room_id.in_(room_ids),
|
||||
meetings.c.end_date > current_time,
|
||||
meetings.c.is_active,
|
||||
)
|
||||
)
|
||||
.order_by(meetings.c.end_date.desc())
|
||||
)
|
||||
results = await get_database().fetch_all(query)
|
||||
return [Meeting(**result) for result in results]
|
||||
|
||||
async def get_active_by_calendar_event(
|
||||
self, room: Room, calendar_event_id: str, current_time: datetime
|
||||
) -> Meeting | None:
|
||||
|
||||
@@ -57,6 +57,12 @@ rooms = sqlalchemy.Table(
|
||||
sqlalchemy.String,
|
||||
nullable=False,
|
||||
),
|
||||
sqlalchemy.Column(
|
||||
"use_celery",
|
||||
sqlalchemy.Boolean,
|
||||
nullable=False,
|
||||
server_default=false(),
|
||||
),
|
||||
sqlalchemy.Column(
|
||||
"skip_consent",
|
||||
sqlalchemy.Boolean,
|
||||
@@ -91,6 +97,7 @@ class Room(BaseModel):
|
||||
ics_last_sync: datetime | None = None
|
||||
ics_last_etag: str | None = None
|
||||
platform: Platform = Field(default_factory=lambda: settings.DEFAULT_VIDEO_PLATFORM)
|
||||
use_celery: bool = False
|
||||
skip_consent: bool = False
|
||||
|
||||
|
||||
@@ -238,11 +245,6 @@ class RoomController:
|
||||
|
||||
return room
|
||||
|
||||
async def get_by_names(self, names: list[str]) -> list[Room]:
|
||||
query = rooms.select().where(rooms.c.name.in_(names))
|
||||
results = await get_database().fetch_all(query)
|
||||
return [Room(**r) for r in results]
|
||||
|
||||
async def get_ics_enabled(self) -> list[Room]:
|
||||
query = rooms.select().where(
|
||||
rooms.c.ics_enabled == True, rooms.c.ics_url != None
|
||||
|
||||
@@ -15,10 +15,14 @@ from hatchet_sdk.clients.rest.exceptions import ApiException, NotFoundException
|
||||
from hatchet_sdk.clients.rest.models import V1TaskStatus
|
||||
|
||||
from reflector.db.recordings import recordings_controller
|
||||
from reflector.db.rooms import rooms_controller
|
||||
from reflector.db.transcripts import Transcript, transcripts_controller
|
||||
from reflector.hatchet.client import HatchetClientManager
|
||||
from reflector.logger import logger
|
||||
from reflector.pipelines.main_file_pipeline import task_pipeline_file_process
|
||||
from reflector.pipelines.main_multitrack_pipeline import (
|
||||
task_pipeline_multitrack_process,
|
||||
)
|
||||
from reflector.utils.string import NonEmptyString
|
||||
|
||||
|
||||
@@ -177,98 +181,124 @@ async def dispatch_transcript_processing(
|
||||
Returns AsyncResult for Celery tasks, None for Hatchet workflows.
|
||||
"""
|
||||
if isinstance(config, MultitrackProcessingConfig):
|
||||
# Multitrack processing always uses Hatchet (no Celery fallback)
|
||||
# First check if we can replay (outside transaction since it's read-only)
|
||||
transcript = await transcripts_controller.get_by_id(config.transcript_id)
|
||||
if transcript and transcript.workflow_run_id and not force:
|
||||
can_replay = await HatchetClientManager.can_replay(
|
||||
transcript.workflow_run_id
|
||||
use_celery = False
|
||||
if config.room_id:
|
||||
room = await rooms_controller.get_by_id(config.room_id)
|
||||
use_celery = room.use_celery if room else False
|
||||
|
||||
use_hatchet = not use_celery
|
||||
|
||||
if use_celery:
|
||||
logger.info(
|
||||
"Room uses legacy Celery processing",
|
||||
room_id=config.room_id,
|
||||
transcript_id=config.transcript_id,
|
||||
)
|
||||
if can_replay:
|
||||
await HatchetClientManager.replay_workflow(transcript.workflow_run_id)
|
||||
logger.info(
|
||||
"Replaying Hatchet workflow",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
|
||||
if use_hatchet:
|
||||
# First check if we can replay (outside transaction since it's read-only)
|
||||
transcript = await transcripts_controller.get_by_id(config.transcript_id)
|
||||
if transcript and transcript.workflow_run_id and not force:
|
||||
can_replay = await HatchetClientManager.can_replay(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
return None
|
||||
else:
|
||||
# Workflow can't replay (CANCELLED, COMPLETED, or 404 deleted)
|
||||
# Log and proceed to start new workflow
|
||||
if can_replay:
|
||||
await HatchetClientManager.replay_workflow(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
logger.info(
|
||||
"Replaying Hatchet workflow",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
return None
|
||||
else:
|
||||
# Workflow can't replay (CANCELLED, COMPLETED, or 404 deleted)
|
||||
# Log and proceed to start new workflow
|
||||
try:
|
||||
status = await HatchetClientManager.get_workflow_run_status(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
logger.info(
|
||||
"Old workflow not replayable, starting new",
|
||||
old_workflow_id=transcript.workflow_run_id,
|
||||
old_status=status.value,
|
||||
)
|
||||
except NotFoundException:
|
||||
# Workflow deleted from Hatchet but ID still in DB
|
||||
logger.info(
|
||||
"Old workflow not found in Hatchet, starting new",
|
||||
old_workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
|
||||
# Force: cancel old workflow if exists
|
||||
if force and transcript and transcript.workflow_run_id:
|
||||
try:
|
||||
await HatchetClientManager.cancel_workflow(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
logger.info(
|
||||
"Cancelled old workflow (--force)",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
except NotFoundException:
|
||||
logger.info(
|
||||
"Old workflow already deleted (--force)",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": None}
|
||||
)
|
||||
|
||||
# Re-fetch and check for concurrent dispatch (optimistic approach).
|
||||
# No database lock - worst case is duplicate dispatch, but Hatchet
|
||||
# workflows are idempotent so this is acceptable.
|
||||
transcript = await transcripts_controller.get_by_id(config.transcript_id)
|
||||
if transcript and transcript.workflow_run_id:
|
||||
# Another process started a workflow between validation and now
|
||||
try:
|
||||
status = await HatchetClientManager.get_workflow_run_status(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
logger.info(
|
||||
"Old workflow not replayable, starting new",
|
||||
old_workflow_id=transcript.workflow_run_id,
|
||||
old_status=status.value,
|
||||
)
|
||||
except NotFoundException:
|
||||
# Workflow deleted from Hatchet but ID still in DB
|
||||
logger.info(
|
||||
"Old workflow not found in Hatchet, starting new",
|
||||
old_workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
if status in (V1TaskStatus.RUNNING, V1TaskStatus.QUEUED):
|
||||
logger.info(
|
||||
"Concurrent workflow detected, skipping dispatch",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
return None
|
||||
except ApiException:
|
||||
# Workflow might be gone (404) or API issue - proceed with new workflow
|
||||
pass
|
||||
|
||||
# Force: cancel old workflow if exists
|
||||
if force and transcript and transcript.workflow_run_id:
|
||||
try:
|
||||
await HatchetClientManager.cancel_workflow(transcript.workflow_run_id)
|
||||
logger.info(
|
||||
"Cancelled old workflow (--force)",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
except NotFoundException:
|
||||
logger.info(
|
||||
"Old workflow already deleted (--force)",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
await transcripts_controller.update(transcript, {"workflow_run_id": None})
|
||||
|
||||
# Re-fetch and check for concurrent dispatch (optimistic approach).
|
||||
# No database lock - worst case is duplicate dispatch, but Hatchet
|
||||
# workflows are idempotent so this is acceptable.
|
||||
transcript = await transcripts_controller.get_by_id(config.transcript_id)
|
||||
if transcript and transcript.workflow_run_id:
|
||||
# Another process started a workflow between validation and now
|
||||
try:
|
||||
status = await HatchetClientManager.get_workflow_run_status(
|
||||
transcript.workflow_run_id
|
||||
)
|
||||
if status in (V1TaskStatus.RUNNING, V1TaskStatus.QUEUED):
|
||||
logger.info(
|
||||
"Concurrent workflow detected, skipping dispatch",
|
||||
workflow_id=transcript.workflow_run_id,
|
||||
)
|
||||
return None
|
||||
except ApiException:
|
||||
# Workflow might be gone (404) or API issue - proceed with new workflow
|
||||
pass
|
||||
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": config.recording_id,
|
||||
"tracks": [{"s3_key": k} for k in config.track_keys],
|
||||
"bucket_name": config.bucket_name,
|
||||
"transcript_id": config.transcript_id,
|
||||
"room_id": config.room_id,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": config.transcript_id,
|
||||
"recording_id": config.recording_id,
|
||||
"daily_recording_id": config.recording_id,
|
||||
},
|
||||
)
|
||||
|
||||
if transcript:
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": workflow_id}
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": config.recording_id,
|
||||
"tracks": [{"s3_key": k} for k in config.track_keys],
|
||||
"bucket_name": config.bucket_name,
|
||||
"transcript_id": config.transcript_id,
|
||||
"room_id": config.room_id,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": config.transcript_id,
|
||||
"recording_id": config.recording_id,
|
||||
"daily_recording_id": config.recording_id,
|
||||
},
|
||||
)
|
||||
|
||||
logger.info("Hatchet workflow dispatched", workflow_id=workflow_id)
|
||||
return None
|
||||
if transcript:
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": workflow_id}
|
||||
)
|
||||
|
||||
logger.info("Hatchet workflow dispatched", workflow_id=workflow_id)
|
||||
return None
|
||||
|
||||
# Celery pipeline (durable workflows disabled)
|
||||
return task_pipeline_multitrack_process.delay(
|
||||
transcript_id=config.transcript_id,
|
||||
bucket_name=config.bucket_name,
|
||||
track_keys=config.track_keys,
|
||||
)
|
||||
elif isinstance(config, FileProcessingConfig):
|
||||
return task_pipeline_file_process.delay(transcript_id=config.transcript_id)
|
||||
else:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pydantic.types import PositiveInt
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from reflector.schemas.platform import DAILY_PLATFORM, Platform
|
||||
from reflector.schemas.platform import WHEREBY_PLATFORM, Platform
|
||||
from reflector.utils.string import NonEmptyString
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ class Settings(BaseSettings):
|
||||
None # Webhook UUID for this environment. Not used by production code
|
||||
)
|
||||
# Platform Configuration
|
||||
DEFAULT_VIDEO_PLATFORM: Platform = DAILY_PLATFORM
|
||||
DEFAULT_VIDEO_PLATFORM: Platform = WHEREBY_PLATFORM
|
||||
|
||||
# Zulip integration
|
||||
ZULIP_REALM: str | None = None
|
||||
|
||||
@@ -129,6 +129,10 @@ class DailyClient(VideoPlatformClient):
|
||||
"""Get room presence/session data for a Daily.co room."""
|
||||
return await self._api_client.get_room_presence(room_name)
|
||||
|
||||
async def delete_room(self, room_name: str) -> None:
|
||||
"""Delete a Daily.co room (idempotent - succeeds even if room doesn't exist)."""
|
||||
return await self._api_client.delete_room(room_name)
|
||||
|
||||
async def get_meeting_participants(
|
||||
self, meeting_id: str
|
||||
) -> MeetingParticipantsResponse:
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Literal, Optional
|
||||
@@ -8,14 +6,13 @@ from typing import Annotated, Any, Literal, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi_pagination import Page
|
||||
from fastapi_pagination.ext.databases import apaginate
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel
|
||||
from redis.exceptions import LockError
|
||||
|
||||
import reflector.auth as auth
|
||||
from reflector.db import get_database
|
||||
from reflector.db.calendar_events import calendar_events_controller
|
||||
from reflector.db.meetings import meetings_controller
|
||||
from reflector.db.rooms import Room as DbRoom
|
||||
from reflector.db.rooms import rooms_controller
|
||||
from reflector.redis_cache import RedisAsyncLock
|
||||
from reflector.schemas.platform import Platform
|
||||
@@ -23,6 +20,7 @@ from reflector.services.ics_sync import ics_sync_service
|
||||
from reflector.settings import settings
|
||||
from reflector.utils.url import add_query_param
|
||||
from reflector.video_platforms.factory import create_platform_client
|
||||
from reflector.worker.process import poll_daily_room_presence_task
|
||||
from reflector.worker.webhook import test_webhook
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -198,73 +196,6 @@ async def rooms_list(
|
||||
return paginated
|
||||
|
||||
|
||||
class BulkStatusRequest(BaseModel):
|
||||
room_names: list[str] = Field(max_length=100)
|
||||
|
||||
|
||||
class RoomMeetingStatus(BaseModel):
|
||||
active_meetings: list[Meeting]
|
||||
upcoming_events: list[CalendarEventResponse]
|
||||
|
||||
|
||||
@router.post("/rooms/meetings/bulk-status", response_model=dict[str, RoomMeetingStatus])
|
||||
async def rooms_bulk_meeting_status(
|
||||
request: BulkStatusRequest,
|
||||
user: Annotated[Optional[auth.UserInfo], Depends(auth.current_user_optional)],
|
||||
):
|
||||
user_id = user["sub"] if user else None
|
||||
|
||||
all_rooms = await rooms_controller.get_by_names(request.room_names)
|
||||
# Filter to rooms the user can see (owned or shared), matching rooms_list behavior
|
||||
rooms = [
|
||||
r
|
||||
for r in all_rooms
|
||||
if r.is_shared or (user_id is not None and r.user_id == user_id)
|
||||
]
|
||||
room_by_id: dict[str, DbRoom] = {r.id: r for r in rooms}
|
||||
room_ids = list(room_by_id.keys())
|
||||
|
||||
current_time = datetime.now(timezone.utc)
|
||||
active_meetings, upcoming_events = await asyncio.gather(
|
||||
meetings_controller.get_all_active_for_rooms(room_ids, current_time),
|
||||
calendar_events_controller.get_upcoming_for_rooms(room_ids),
|
||||
)
|
||||
|
||||
# Group by room name
|
||||
active_by_room: dict[str, list[Meeting]] = defaultdict(list)
|
||||
for m in active_meetings:
|
||||
room = room_by_id.get(m.room_id)
|
||||
if not room:
|
||||
continue
|
||||
m.platform = room.platform
|
||||
if user_id != room.user_id and m.platform == "whereby":
|
||||
m.host_room_url = ""
|
||||
active_by_room[room.name].append(
|
||||
Meeting.model_validate(m, from_attributes=True)
|
||||
)
|
||||
|
||||
upcoming_by_room: dict[str, list[CalendarEventResponse]] = defaultdict(list)
|
||||
for e in upcoming_events:
|
||||
room = room_by_id.get(e.room_id)
|
||||
if not room:
|
||||
continue
|
||||
if user_id != room.user_id:
|
||||
e.description = None
|
||||
e.attendees = None
|
||||
upcoming_by_room[room.name].append(
|
||||
CalendarEventResponse.model_validate(e, from_attributes=True)
|
||||
)
|
||||
|
||||
result: dict[str, RoomMeetingStatus] = {}
|
||||
for name in request.room_names:
|
||||
result[name] = RoomMeetingStatus(
|
||||
active_meetings=active_by_room.get(name, []),
|
||||
upcoming_events=upcoming_by_room.get(name, []),
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/rooms/{room_id}", response_model=RoomDetails)
|
||||
async def rooms_get(
|
||||
room_id: str,
|
||||
@@ -435,6 +366,53 @@ async def rooms_create_meeting(
|
||||
return meeting
|
||||
|
||||
|
||||
@router.post("/rooms/{room_name}/meetings/{meeting_id}/joined")
|
||||
async def rooms_joined_meeting(
|
||||
room_name: str,
|
||||
meeting_id: str,
|
||||
):
|
||||
"""Trigger presence poll (ideally when user actually joins meeting in Daily iframe)"""
|
||||
room = await rooms_controller.get_by_name(room_name)
|
||||
if not room:
|
||||
raise HTTPException(status_code=404, detail="Room not found")
|
||||
|
||||
meeting = await meetings_controller.get_by_id(meeting_id, room=room)
|
||||
if not meeting:
|
||||
raise HTTPException(status_code=404, detail="Meeting not found")
|
||||
|
||||
if meeting.platform == "daily":
|
||||
poll_daily_room_presence_task.delay(meeting_id)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/rooms/{room_name}/meetings/{meeting_id}/leave")
|
||||
async def rooms_leave_meeting(
|
||||
room_name: str,
|
||||
meeting_id: str,
|
||||
delay_seconds: int = 2,
|
||||
):
|
||||
"""Trigger presence recheck when user leaves meeting (e.g., tab close/navigation).
|
||||
|
||||
Queues presence poll with optional delay to allow Daily.co to detect disconnect.
|
||||
"""
|
||||
room = await rooms_controller.get_by_name(room_name)
|
||||
if not room:
|
||||
raise HTTPException(status_code=404, detail="Room not found")
|
||||
|
||||
meeting = await meetings_controller.get_by_id(meeting_id, room=room)
|
||||
if not meeting:
|
||||
raise HTTPException(status_code=404, detail="Meeting not found")
|
||||
|
||||
if meeting.platform == "daily":
|
||||
poll_daily_room_presence_task.apply_async(
|
||||
args=[meeting_id],
|
||||
countdown=delay_seconds,
|
||||
)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/rooms/{room_id}/webhook/test", response_model=WebhookTestResult)
|
||||
async def rooms_test_webhook(
|
||||
room_id: str,
|
||||
|
||||
@@ -27,6 +27,9 @@ from reflector.db.transcripts import (
|
||||
from reflector.hatchet.client import HatchetClientManager
|
||||
from reflector.pipelines.main_file_pipeline import task_pipeline_file_process
|
||||
from reflector.pipelines.main_live_pipeline import asynctask
|
||||
from reflector.pipelines.main_multitrack_pipeline import (
|
||||
task_pipeline_multitrack_process,
|
||||
)
|
||||
from reflector.pipelines.topic_processing import EmptyPipeline
|
||||
from reflector.processors import AudioFileWriterProcessor
|
||||
from reflector.processors.audio_waveform_processor import AudioWaveformProcessor
|
||||
@@ -348,29 +351,49 @@ async def _process_multitrack_recording_inner(
|
||||
room_id=room.id,
|
||||
)
|
||||
|
||||
# Multitrack processing always uses Hatchet (no Celery fallback)
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": recording_id,
|
||||
"tracks": [{"s3_key": k} for k in filter_cam_audio_tracks(track_keys)],
|
||||
"bucket_name": bucket_name,
|
||||
"transcript_id": transcript.id,
|
||||
"room_id": room.id,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": transcript.id,
|
||||
"recording_id": recording_id,
|
||||
"daily_recording_id": recording_id,
|
||||
},
|
||||
)
|
||||
logger.info(
|
||||
"Started Hatchet workflow",
|
||||
workflow_id=workflow_id,
|
||||
transcript_id=transcript.id,
|
||||
)
|
||||
use_celery = room and room.use_celery
|
||||
use_hatchet = not use_celery
|
||||
|
||||
await transcripts_controller.update(transcript, {"workflow_run_id": workflow_id})
|
||||
if use_celery:
|
||||
logger.info(
|
||||
"Room uses legacy Celery processing",
|
||||
room_id=room.id,
|
||||
transcript_id=transcript.id,
|
||||
)
|
||||
|
||||
if use_hatchet:
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": recording_id,
|
||||
"tracks": [{"s3_key": k} for k in filter_cam_audio_tracks(track_keys)],
|
||||
"bucket_name": bucket_name,
|
||||
"transcript_id": transcript.id,
|
||||
"room_id": room.id,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": transcript.id,
|
||||
"recording_id": recording_id,
|
||||
"daily_recording_id": recording_id,
|
||||
},
|
||||
)
|
||||
logger.info(
|
||||
"Started Hatchet workflow",
|
||||
workflow_id=workflow_id,
|
||||
transcript_id=transcript.id,
|
||||
)
|
||||
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": workflow_id}
|
||||
)
|
||||
return
|
||||
|
||||
# Celery pipeline (runs when durable workflows disabled)
|
||||
task_pipeline_multitrack_process.delay(
|
||||
transcript_id=transcript.id,
|
||||
bucket_name=bucket_name,
|
||||
track_keys=filter_cam_audio_tracks(track_keys),
|
||||
)
|
||||
|
||||
|
||||
@shared_task
|
||||
@@ -822,15 +845,47 @@ async def process_meetings():
|
||||
end_date = end_date.replace(tzinfo=timezone.utc)
|
||||
|
||||
client = create_platform_client(meeting.platform)
|
||||
room_sessions = await client.get_room_sessions(meeting.room_name)
|
||||
has_active_sessions = False
|
||||
has_had_sessions = False
|
||||
|
||||
has_active_sessions = bool(
|
||||
room_sessions and any(s.ended_at is None for s in room_sessions)
|
||||
)
|
||||
has_had_sessions = bool(room_sessions)
|
||||
logger_.info(
|
||||
f"has_active_sessions={has_active_sessions}, has_had_sessions={has_had_sessions}"
|
||||
)
|
||||
if meeting.platform == "daily":
|
||||
try:
|
||||
presence = await client.get_room_presence(meeting.room_name)
|
||||
has_active_sessions = presence.total_count > 0
|
||||
|
||||
room_sessions = await client.get_room_sessions(
|
||||
meeting.room_name
|
||||
)
|
||||
has_had_sessions = bool(room_sessions)
|
||||
|
||||
logger_.info(
|
||||
"Daily.co presence check",
|
||||
has_active_sessions=has_active_sessions,
|
||||
has_had_sessions=has_had_sessions,
|
||||
presence_count=presence.total_count,
|
||||
)
|
||||
except Exception:
|
||||
logger_.warning(
|
||||
"Daily.co presence API failed, falling back to DB sessions",
|
||||
exc_info=True,
|
||||
)
|
||||
room_sessions = await client.get_room_sessions(
|
||||
meeting.room_name
|
||||
)
|
||||
has_active_sessions = bool(
|
||||
room_sessions
|
||||
and any(s.ended_at is None for s in room_sessions)
|
||||
)
|
||||
has_had_sessions = bool(room_sessions)
|
||||
else:
|
||||
room_sessions = await client.get_room_sessions(meeting.room_name)
|
||||
has_active_sessions = bool(
|
||||
room_sessions and any(s.ended_at is None for s in room_sessions)
|
||||
)
|
||||
has_had_sessions = bool(room_sessions)
|
||||
logger_.info(
|
||||
f"has_active_sessions={has_active_sessions}, has_had_sessions={has_had_sessions}"
|
||||
)
|
||||
|
||||
if has_active_sessions:
|
||||
logger_.debug("Meeting still has active sessions, keep it")
|
||||
@@ -849,7 +904,20 @@ async def process_meetings():
|
||||
await meetings_controller.update_meeting(
|
||||
meeting.id, is_active=False
|
||||
)
|
||||
logger_.info("Meeting is deactivated")
|
||||
logger_.info("Meeting deactivated in database")
|
||||
|
||||
if meeting.platform == "daily":
|
||||
try:
|
||||
await client.delete_room(meeting.room_name)
|
||||
logger_.info(
|
||||
"Daily.co room deleted", room_name=meeting.room_name
|
||||
)
|
||||
except Exception:
|
||||
logger_.warning(
|
||||
"Failed to delete Daily.co room",
|
||||
room_name=meeting.room_name,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
processed_count += 1
|
||||
|
||||
@@ -1049,43 +1117,66 @@ async def reprocess_failed_daily_recordings():
|
||||
)
|
||||
continue
|
||||
|
||||
# Multitrack reprocessing always uses Hatchet (no Celery fallback)
|
||||
if not transcript:
|
||||
logger.warning(
|
||||
"No transcript for Hatchet reprocessing, skipping",
|
||||
recording_id=recording.id,
|
||||
use_celery = room and room.use_celery
|
||||
use_hatchet = not use_celery
|
||||
|
||||
if use_hatchet:
|
||||
if not transcript:
|
||||
logger.warning(
|
||||
"No transcript for Hatchet reprocessing, skipping",
|
||||
recording_id=recording.id,
|
||||
)
|
||||
continue
|
||||
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": recording.id,
|
||||
"tracks": [
|
||||
{"s3_key": k}
|
||||
for k in filter_cam_audio_tracks(recording.track_keys)
|
||||
],
|
||||
"bucket_name": bucket_name,
|
||||
"transcript_id": transcript.id,
|
||||
"room_id": room.id if room else None,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": transcript.id,
|
||||
"recording_id": recording.id,
|
||||
"reprocess": True,
|
||||
},
|
||||
)
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": workflow_id}
|
||||
)
|
||||
continue
|
||||
|
||||
workflow_id = await HatchetClientManager.start_workflow(
|
||||
workflow_name="DiarizationPipeline",
|
||||
input_data={
|
||||
"recording_id": recording.id,
|
||||
"tracks": [
|
||||
{"s3_key": k}
|
||||
for k in filter_cam_audio_tracks(recording.track_keys)
|
||||
],
|
||||
"bucket_name": bucket_name,
|
||||
"transcript_id": transcript.id,
|
||||
"room_id": room.id if room else None,
|
||||
},
|
||||
additional_metadata={
|
||||
"transcript_id": transcript.id,
|
||||
"recording_id": recording.id,
|
||||
"reprocess": True,
|
||||
},
|
||||
)
|
||||
await transcripts_controller.update(
|
||||
transcript, {"workflow_run_id": workflow_id}
|
||||
)
|
||||
logger.info(
|
||||
"Queued Daily recording for Hatchet reprocessing",
|
||||
recording_id=recording.id,
|
||||
workflow_id=workflow_id,
|
||||
room_name=meeting.room_name,
|
||||
track_count=len(recording.track_keys),
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"Queueing Daily recording for Celery reprocessing",
|
||||
recording_id=recording.id,
|
||||
room_name=meeting.room_name,
|
||||
track_count=len(recording.track_keys),
|
||||
transcript_status=transcript.status if transcript else None,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Queued Daily recording for Hatchet reprocessing",
|
||||
recording_id=recording.id,
|
||||
workflow_id=workflow_id,
|
||||
room_name=meeting.room_name,
|
||||
track_count=len(recording.track_keys),
|
||||
)
|
||||
# For reprocessing, pass actual recording time (though it's ignored - see _process_multitrack_recording_inner)
|
||||
# Reprocessing uses recording.meeting_id directly instead of time-based matching
|
||||
recording_start_ts = int(recording.recorded_at.timestamp())
|
||||
|
||||
process_multitrack_recording.delay(
|
||||
bucket_name=bucket_name,
|
||||
daily_room_name=meeting.room_name,
|
||||
recording_id=recording.id,
|
||||
track_keys=recording.track_keys,
|
||||
recording_start_ts=recording_start_ts,
|
||||
)
|
||||
|
||||
reprocessed_count += 1
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from reflector.schemas.platform import DAILY_PLATFORM, WHEREBY_PLATFORM
|
||||
from reflector.schemas.platform import WHEREBY_PLATFORM
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
@@ -14,7 +14,6 @@ def register_mock_platform():
|
||||
from reflector.video_platforms.registry import register_platform
|
||||
|
||||
register_platform(WHEREBY_PLATFORM, MockPlatformClient)
|
||||
register_platform(DAILY_PLATFORM, MockPlatformClient)
|
||||
yield
|
||||
|
||||
|
||||
|
||||
286
server/tests/test_daily_presence_deactivation.py
Normal file
286
server/tests/test_daily_presence_deactivation.py
Normal file
@@ -0,0 +1,286 @@
|
||||
"""Unit tests for Daily.co presence-based meeting deactivation logic.
|
||||
|
||||
Tests the fix for split room race condition by verifying:
|
||||
1. Real-time presence checking via Daily.co API
|
||||
2. Room deletion when meetings deactivate
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from reflector.dailyco_api.responses import (
|
||||
RoomPresenceParticipant,
|
||||
RoomPresenceResponse,
|
||||
)
|
||||
from reflector.db.daily_participant_sessions import (
|
||||
DailyParticipantSession,
|
||||
daily_participant_sessions_controller,
|
||||
)
|
||||
from reflector.db.meetings import meetings_controller
|
||||
from reflector.db.rooms import rooms_controller
|
||||
from reflector.video_platforms.daily import DailyClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def daily_room_and_meeting():
|
||||
"""Create test room and meeting for Daily platform."""
|
||||
room = await rooms_controller.add(
|
||||
name="test-daily",
|
||||
user_id="test-user",
|
||||
platform="daily",
|
||||
zulip_auto_post=False,
|
||||
zulip_stream="",
|
||||
zulip_topic="",
|
||||
is_locked=False,
|
||||
room_mode="normal",
|
||||
recording_type="cloud",
|
||||
recording_trigger="automatic-2nd-participant",
|
||||
is_shared=False,
|
||||
)
|
||||
|
||||
current_time = datetime.now(timezone.utc)
|
||||
end_time = current_time + timedelta(hours=2)
|
||||
|
||||
meeting = await meetings_controller.create(
|
||||
id="test-meeting-id",
|
||||
room_name="test-daily-20260129120000",
|
||||
room_url="https://daily.co/test",
|
||||
host_room_url="https://daily.co/test",
|
||||
start_date=current_time,
|
||||
end_date=end_time,
|
||||
room=room,
|
||||
)
|
||||
|
||||
return room, meeting
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_daily_client_has_delete_room_method():
|
||||
"""Verify DailyClient has delete_room method for cleanup."""
|
||||
# Create a mock DailyClient
|
||||
with patch("reflector.dailyco_api.client.DailyApiClient"):
|
||||
from reflector.video_platforms.models import VideoPlatformConfig
|
||||
|
||||
config = VideoPlatformConfig(api_key="test-key", webhook_secret="test-secret")
|
||||
client = DailyClient(config)
|
||||
|
||||
# Verify delete_room method exists
|
||||
assert hasattr(client, "delete_room")
|
||||
assert callable(getattr(client, "delete_room"))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_room_presence_returns_realtime_data(daily_room_and_meeting):
|
||||
"""Test that get_room_presence returns real-time participant data."""
|
||||
room, meeting = daily_room_and_meeting
|
||||
|
||||
# Mock Daily.co API response
|
||||
mock_presence = RoomPresenceResponse(
|
||||
total_count=2,
|
||||
data=[
|
||||
RoomPresenceParticipant(
|
||||
room=meeting.room_name,
|
||||
id="session-1",
|
||||
userId="user-1",
|
||||
userName="User One",
|
||||
joinTime="2026-01-29T12:00:00.000Z",
|
||||
duration=120,
|
||||
),
|
||||
RoomPresenceParticipant(
|
||||
room=meeting.room_name,
|
||||
id="session-2",
|
||||
userId="user-2",
|
||||
userName="User Two",
|
||||
joinTime="2026-01-29T12:05:00.000Z",
|
||||
duration=60,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
with patch("reflector.dailyco_api.client.DailyApiClient") as mock_api:
|
||||
from reflector.video_platforms.models import VideoPlatformConfig
|
||||
|
||||
config = VideoPlatformConfig(api_key="test-key", webhook_secret="test-secret")
|
||||
client = DailyClient(config)
|
||||
|
||||
# Mock the API client method
|
||||
client._api_client.get_room_presence = AsyncMock(return_value=mock_presence)
|
||||
|
||||
# Call get_room_presence
|
||||
result = await client.get_room_presence(meeting.room_name)
|
||||
|
||||
# Verify it calls Daily.co API
|
||||
client._api_client.get_room_presence.assert_called_once_with(meeting.room_name)
|
||||
|
||||
# Verify result contains real-time data
|
||||
assert result.total_count == 2
|
||||
assert len(result.data) == 2
|
||||
assert result.data[0].id == "session-1"
|
||||
assert result.data[1].id == "session-2"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_presence_shows_active_even_when_db_stale(daily_room_and_meeting):
|
||||
"""Test that Daily.co presence API is source of truth, not stale DB sessions."""
|
||||
room, meeting = daily_room_and_meeting
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
# Create stale DB session (left_at=NULL but user actually left)
|
||||
session_id = f"{meeting.id}:stale-user:{int((current_time - timedelta(minutes=5)).timestamp() * 1000)}"
|
||||
await daily_participant_sessions_controller.upsert_joined(
|
||||
DailyParticipantSession(
|
||||
id=session_id,
|
||||
meeting_id=meeting.id,
|
||||
room_id=room.id,
|
||||
session_id="stale-daily-session",
|
||||
user_name="Stale User",
|
||||
user_id="stale-user",
|
||||
joined_at=current_time - timedelta(minutes=5),
|
||||
left_at=None, # Stale - shows active but user left
|
||||
)
|
||||
)
|
||||
|
||||
# Verify DB shows active session
|
||||
db_sessions = await daily_participant_sessions_controller.get_active_by_meeting(
|
||||
meeting.id
|
||||
)
|
||||
assert len(db_sessions) == 1
|
||||
|
||||
# But Daily.co API shows room is empty
|
||||
mock_presence = RoomPresenceResponse(total_count=0, data=[])
|
||||
|
||||
with patch("reflector.dailyco_api.client.DailyApiClient"):
|
||||
from reflector.video_platforms.models import VideoPlatformConfig
|
||||
|
||||
config = VideoPlatformConfig(api_key="test-key", webhook_secret="test-secret")
|
||||
client = DailyClient(config)
|
||||
client._api_client.get_room_presence = AsyncMock(return_value=mock_presence)
|
||||
|
||||
# Get real-time presence
|
||||
presence = await client.get_room_presence(meeting.room_name)
|
||||
|
||||
# Real-time API shows no participants (truth)
|
||||
assert presence.total_count == 0
|
||||
assert len(presence.data) == 0
|
||||
|
||||
# DB shows 1 participant (stale)
|
||||
assert len(db_sessions) == 1
|
||||
|
||||
# Implementation should trust presence API, not DB
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_meeting_deactivation_logic_with_presence_empty():
|
||||
"""Test the core deactivation decision logic when presence shows room empty."""
|
||||
# This tests the logic that will be in process_meetings
|
||||
|
||||
# Simulate: DB shows stale active session
|
||||
has_active_db_sessions = True # DB is stale
|
||||
|
||||
# Simulate: Daily.co presence API shows room empty
|
||||
presence_count = 0 # Real-time truth
|
||||
|
||||
# Simulate: Meeting has been used before
|
||||
has_had_sessions = True
|
||||
|
||||
# Decision logic (what process_meetings should do):
|
||||
# - If presence API available: trust it
|
||||
# - If presence shows empty AND has_had_sessions: deactivate
|
||||
|
||||
if presence_count == 0 and has_had_sessions:
|
||||
should_deactivate = True
|
||||
else:
|
||||
should_deactivate = False
|
||||
|
||||
assert should_deactivate is True # Should deactivate despite stale DB
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_meeting_deactivation_logic_with_presence_active():
|
||||
"""Test that meetings stay active when presence shows participants."""
|
||||
# Simulate: DB shows no sessions (not yet updated)
|
||||
has_active_db_sessions = False # DB hasn't caught up
|
||||
|
||||
# Simulate: Daily.co presence API shows active participant
|
||||
presence_count = 1 # Real-time truth
|
||||
|
||||
# Decision logic: presence shows activity, keep meeting active
|
||||
if presence_count > 0:
|
||||
should_deactivate = False
|
||||
else:
|
||||
should_deactivate = True
|
||||
|
||||
assert should_deactivate is False # Should stay active
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_room_called_on_deactivation(daily_room_and_meeting):
|
||||
"""Test that Daily.co room is deleted when meeting deactivates."""
|
||||
room, meeting = daily_room_and_meeting
|
||||
|
||||
with patch("reflector.dailyco_api.client.DailyApiClient"):
|
||||
from reflector.video_platforms.models import VideoPlatformConfig
|
||||
|
||||
config = VideoPlatformConfig(api_key="test-key", webhook_secret="test-secret")
|
||||
client = DailyClient(config)
|
||||
|
||||
# Mock delete_room API call
|
||||
client._api_client.delete_room = AsyncMock()
|
||||
|
||||
# Simulate deactivation - should delete room
|
||||
await client._api_client.delete_room(meeting.room_name)
|
||||
|
||||
# Verify delete was called
|
||||
client._api_client.delete_room.assert_called_once_with(meeting.room_name)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_room_idempotent_on_404():
|
||||
"""Test that room deletion is idempotent (succeeds even if room doesn't exist)."""
|
||||
from reflector.dailyco_api.client import DailyApiClient
|
||||
|
||||
# Create real client to test delete_room logic
|
||||
client = DailyApiClient(api_key="test-key")
|
||||
|
||||
# Mock the HTTP client
|
||||
mock_http_client = AsyncMock()
|
||||
mock_response = AsyncMock()
|
||||
mock_response.status_code = 404 # Room not found
|
||||
mock_http_client.delete = AsyncMock(return_value=mock_response)
|
||||
|
||||
# Mock _get_client to return our mock
|
||||
async def mock_get_client():
|
||||
return mock_http_client
|
||||
|
||||
client._get_client = mock_get_client
|
||||
|
||||
# delete_room should succeed even on 404 (idempotent)
|
||||
await client.delete_room("nonexistent-room")
|
||||
|
||||
# Verify delete was attempted
|
||||
mock_http_client.delete.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_failure_fallback_to_db_sessions():
|
||||
"""Test that system falls back to DB sessions if Daily.co API fails."""
|
||||
# Simulate: Daily.co API throws exception
|
||||
api_exception = Exception("API unavailable")
|
||||
|
||||
# Simulate: DB shows active session
|
||||
has_active_db_sessions = True
|
||||
|
||||
# Decision logic with fallback:
|
||||
try:
|
||||
presence_count = None
|
||||
raise api_exception # Simulating API failure
|
||||
except Exception:
|
||||
# Fallback: use DB sessions (conservative - don't deactivate if unsure)
|
||||
if has_active_db_sessions:
|
||||
should_deactivate = False
|
||||
else:
|
||||
should_deactivate = True
|
||||
|
||||
assert should_deactivate is False # Conservative: keep active on API failure
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -142,17 +142,17 @@ async def test_whereby_recording_uses_file_pipeline(client):
|
||||
"reflector.services.transcript_process.task_pipeline_file_process"
|
||||
) as mock_file_pipeline,
|
||||
patch(
|
||||
"reflector.services.transcript_process.HatchetClientManager"
|
||||
) as mock_hatchet,
|
||||
"reflector.services.transcript_process.task_pipeline_multitrack_process"
|
||||
) as mock_multitrack_pipeline,
|
||||
):
|
||||
response = await client.post(f"/transcripts/{transcript.id}/process")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
|
||||
# Whereby recordings should use file pipeline, not Hatchet
|
||||
# Whereby recordings should use file pipeline
|
||||
mock_file_pipeline.delay.assert_called_once_with(transcript_id=transcript.id)
|
||||
mock_hatchet.start_workflow.assert_not_called()
|
||||
mock_multitrack_pipeline.delay.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("setup_database")
|
||||
@@ -177,6 +177,8 @@ async def test_dailyco_recording_uses_multitrack_pipeline(client):
|
||||
recording_trigger="automatic-2nd-participant",
|
||||
is_shared=False,
|
||||
)
|
||||
# Force Celery backend for test
|
||||
await rooms_controller.update(room, {"use_celery": True})
|
||||
|
||||
transcript = await transcripts_controller.add(
|
||||
"",
|
||||
@@ -211,23 +213,18 @@ async def test_dailyco_recording_uses_multitrack_pipeline(client):
|
||||
"reflector.services.transcript_process.task_pipeline_file_process"
|
||||
) as mock_file_pipeline,
|
||||
patch(
|
||||
"reflector.services.transcript_process.HatchetClientManager"
|
||||
) as mock_hatchet,
|
||||
"reflector.services.transcript_process.task_pipeline_multitrack_process"
|
||||
) as mock_multitrack_pipeline,
|
||||
):
|
||||
mock_hatchet.start_workflow = AsyncMock(return_value="test-workflow-id")
|
||||
|
||||
response = await client.post(f"/transcripts/{transcript.id}/process")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
|
||||
# Daily.co multitrack recordings should use Hatchet workflow
|
||||
mock_hatchet.start_workflow.assert_called_once()
|
||||
call_kwargs = mock_hatchet.start_workflow.call_args.kwargs
|
||||
assert call_kwargs["workflow_name"] == "DiarizationPipeline"
|
||||
assert call_kwargs["input_data"]["transcript_id"] == transcript.id
|
||||
assert call_kwargs["input_data"]["bucket_name"] == "daily-bucket"
|
||||
assert call_kwargs["input_data"]["tracks"] == [
|
||||
{"s3_key": k} for k in track_keys
|
||||
]
|
||||
# Daily.co multitrack recordings should use multitrack pipeline
|
||||
mock_multitrack_pipeline.delay.assert_called_once_with(
|
||||
transcript_id=transcript.id,
|
||||
bucket_name="daily-bucket",
|
||||
track_keys=track_keys,
|
||||
)
|
||||
mock_file_pipeline.delay.assert_not_called()
|
||||
|
||||
@@ -24,15 +24,24 @@ import { useAuth } from "../../lib/AuthProvider";
|
||||
import { useConsentDialog } from "../../lib/consent";
|
||||
import {
|
||||
useRoomJoinMeeting,
|
||||
useRoomJoinedMeeting,
|
||||
useRoomLeaveMeeting,
|
||||
useMeetingStartRecording,
|
||||
leaveRoomPostUrl,
|
||||
LeaveRoomBody,
|
||||
} from "../../lib/apiHooks";
|
||||
import { omit } from "remeda";
|
||||
import {
|
||||
assertExists,
|
||||
assertExistsAndNonEmptyString,
|
||||
NonEmptyString,
|
||||
parseNonEmptyString,
|
||||
} from "../../lib/utils";
|
||||
import { assertMeetingId, DailyRecordingType } from "../../lib/types";
|
||||
import {
|
||||
assertMeetingId,
|
||||
DailyRecordingType,
|
||||
MeetingId,
|
||||
} from "../../lib/types";
|
||||
import { useUuidV5 } from "react-uuid-hook";
|
||||
|
||||
const CONSENT_BUTTON_ID = "recording-consent";
|
||||
@@ -179,6 +188,58 @@ const useFrame = (
|
||||
] as const;
|
||||
};
|
||||
|
||||
const leaveDaily = () => {
|
||||
const frame = DailyIframe.getCallInstance();
|
||||
frame?.leave();
|
||||
};
|
||||
|
||||
const useDirtyDisconnects = (
|
||||
meetingId: NonEmptyString,
|
||||
roomName: NonEmptyString,
|
||||
) => {
|
||||
useEffect(() => {
|
||||
if (!meetingId || !roomName) return;
|
||||
|
||||
const handleBeforeUnload = () => {
|
||||
leaveDaily();
|
||||
navigator.sendBeacon(
|
||||
leaveRoomPostUrl(
|
||||
{
|
||||
room_name: roomName,
|
||||
meeting_id: meetingId,
|
||||
},
|
||||
{
|
||||
delay_seconds: 5,
|
||||
},
|
||||
),
|
||||
undefined satisfies LeaveRoomBody,
|
||||
);
|
||||
};
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
}, [meetingId, roomName]);
|
||||
};
|
||||
|
||||
const useDisconnects = (
|
||||
meetingId: NonEmptyString,
|
||||
roomName: NonEmptyString,
|
||||
leaveMutation: ReturnType<typeof useRoomLeaveMeeting>,
|
||||
) => {
|
||||
useDirtyDisconnects(meetingId, roomName);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
leaveDaily();
|
||||
leaveMutation.mutate({
|
||||
params: {
|
||||
path: { meeting_id: meetingId, room_name: roomName },
|
||||
query: { delay_seconds: 5 },
|
||||
},
|
||||
});
|
||||
};
|
||||
}, [meetingId, roomName]);
|
||||
};
|
||||
|
||||
export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
@@ -186,6 +247,8 @@ export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
const authLastUserId = auth.lastUserId;
|
||||
const [container, setContainer] = useState<HTMLDivElement | null>(null);
|
||||
const joinMutation = useRoomJoinMeeting();
|
||||
const joinedMutation = useRoomJoinedMeeting();
|
||||
const leaveMutation = useRoomLeaveMeeting();
|
||||
const startRecordingMutation = useMeetingStartRecording();
|
||||
const [joinedMeeting, setJoinedMeeting] = useState<Meeting | null>(null);
|
||||
|
||||
@@ -195,7 +258,9 @@ export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
useUuidV5(meeting.id, RAW_TRACKS_NAMESPACE)[0],
|
||||
);
|
||||
|
||||
const roomName = params?.roomName as string;
|
||||
if (typeof params.roomName === "object")
|
||||
throw new Error(`Invalid room name in params. array? ${params.roomName}`);
|
||||
const roomName = assertExistsAndNonEmptyString(params.roomName);
|
||||
|
||||
const {
|
||||
showConsentModal,
|
||||
@@ -237,6 +302,8 @@ export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
router.push("/browse");
|
||||
}, [router]);
|
||||
|
||||
useDisconnects(meeting.id as MeetingId, roomName, leaveMutation);
|
||||
|
||||
const handleCustomButtonClick = useCallback(
|
||||
(ev: DailyEventObjectCustomButtonClick) => {
|
||||
if (ev.button_id === CONSENT_BUTTON_ID) {
|
||||
@@ -249,6 +316,15 @@ export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
);
|
||||
|
||||
const handleFrameJoinMeeting = useCallback(() => {
|
||||
joinedMutation.mutate({
|
||||
params: {
|
||||
path: {
|
||||
room_name: roomName,
|
||||
meeting_id: meeting.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (meeting.recording_type === "cloud") {
|
||||
console.log("Starting dual recording via REST API", {
|
||||
cloudInstanceId,
|
||||
@@ -308,8 +384,10 @@ export default function DailyRoom({ meeting, room }: DailyRoomProps) {
|
||||
startRecordingWithRetry("raw-tracks", rawTracksInstanceId);
|
||||
}
|
||||
}, [
|
||||
meeting.recording_type,
|
||||
joinedMutation,
|
||||
roomName,
|
||||
meeting.id,
|
||||
meeting.recording_type,
|
||||
startRecordingMutation,
|
||||
cloudInstanceId,
|
||||
rawTracksInstanceId,
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import "@testing-library/jest-dom";
|
||||
|
||||
// --- Module mocks (hoisted before imports) ---
|
||||
|
||||
jest.mock("../apiClient", () => ({
|
||||
client: {
|
||||
GET: jest.fn(),
|
||||
POST: jest.fn(),
|
||||
PUT: jest.fn(),
|
||||
PATCH: jest.fn(),
|
||||
DELETE: jest.fn(),
|
||||
use: jest.fn(),
|
||||
},
|
||||
$api: {
|
||||
useQuery: jest.fn(),
|
||||
useMutation: jest.fn(),
|
||||
queryOptions: (method: string, path: string, init?: unknown) =>
|
||||
init === undefined
|
||||
? { queryKey: [method, path] }
|
||||
: { queryKey: [method, path, init] },
|
||||
},
|
||||
API_URL: "http://test",
|
||||
WEBSOCKET_URL: "ws://test",
|
||||
configureApiAuth: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("../AuthProvider", () => ({
|
||||
useAuth: () => ({
|
||||
status: "authenticated" as const,
|
||||
accessToken: "test-token",
|
||||
accessTokenExpires: Date.now() + 3600000,
|
||||
user: { id: "user1", name: "Test User" },
|
||||
update: jest.fn(),
|
||||
signIn: jest.fn(),
|
||||
signOut: jest.fn(),
|
||||
lastUserId: "user1",
|
||||
}),
|
||||
}));
|
||||
|
||||
// Recreate the batcher with a 0ms window. setTimeout(fn, 0) defers to the next
|
||||
// macrotask boundary — after all synchronous React rendering completes. All
|
||||
// useQuery queryFns fire within the same macrotask, so they all queue into one
|
||||
// batch before the timer fires. This is deterministic and avoids fake timers.
|
||||
jest.mock("../meetingStatusBatcher", () => {
|
||||
const actual = jest.requireActual("../meetingStatusBatcher");
|
||||
return {
|
||||
...actual,
|
||||
meetingStatusBatcher: actual.createMeetingStatusBatcher(0),
|
||||
};
|
||||
});
|
||||
|
||||
// --- Imports (after mocks) ---
|
||||
|
||||
import React from "react";
|
||||
import { render, waitFor, screen } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useRoomActiveMeetings, useRoomUpcomingMeetings } from "../apiHooks";
|
||||
import { client } from "../apiClient";
|
||||
import { ErrorProvider } from "../../(errors)/errorContext";
|
||||
|
||||
const mockClient = client as { POST: jest.Mock };
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
function mockBulkStatusEndpoint(
|
||||
roomData?: Record<
|
||||
string,
|
||||
{ active_meetings: unknown[]; upcoming_events: unknown[] }
|
||||
>,
|
||||
) {
|
||||
mockClient.POST.mockImplementation(
|
||||
async (_path: string, options: { body: { room_names: string[] } }) => {
|
||||
const roomNames: string[] = options.body.room_names;
|
||||
const src = roomData ?? {};
|
||||
const data = Object.fromEntries(
|
||||
roomNames.map((name) => [
|
||||
name,
|
||||
src[name] ?? { active_meetings: [], upcoming_events: [] },
|
||||
]),
|
||||
);
|
||||
return { data, error: undefined, response: {} };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// --- Test component: renders N room cards, each using both hooks ---
|
||||
|
||||
function RoomCard({ roomName }: { roomName: string }) {
|
||||
const active = useRoomActiveMeetings(roomName);
|
||||
const upcoming = useRoomUpcomingMeetings(roomName);
|
||||
|
||||
if (active.isLoading || upcoming.isLoading) {
|
||||
return <div data-testid={`room-${roomName}`}>loading</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-testid={`room-${roomName}`}>
|
||||
{active.data?.length ?? 0} active, {upcoming.data?.length ?? 0} upcoming
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RoomList({ roomNames }: { roomNames: string[] }) {
|
||||
return (
|
||||
<>
|
||||
{roomNames.map((name) => (
|
||||
<RoomCard key={name} roomName={name} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
});
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ErrorProvider>{children}</ErrorProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
// --- Tests ---
|
||||
|
||||
describe("meeting status batcher integration", () => {
|
||||
afterEach(() => jest.clearAllMocks());
|
||||
|
||||
it("batches multiple room queries into a single POST request", async () => {
|
||||
const rooms = Array.from({ length: 10 }, (_, i) => `room-${i}`);
|
||||
|
||||
mockBulkStatusEndpoint();
|
||||
|
||||
render(<RoomList roomNames={rooms} />, { wrapper: createWrapper() });
|
||||
|
||||
await waitFor(() => {
|
||||
for (const name of rooms) {
|
||||
expect(screen.getByTestId(`room-${name}`)).toHaveTextContent(
|
||||
"0 active, 0 upcoming",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const postCalls = mockClient.POST.mock.calls.filter(
|
||||
([path]: [string]) => path === "/v1/rooms/meetings/bulk-status",
|
||||
);
|
||||
|
||||
// Without batching this would be 20 calls (2 hooks x 10 rooms).
|
||||
expect(postCalls).toHaveLength(1);
|
||||
|
||||
// The single call should contain all 10 rooms (deduplicated)
|
||||
const requestedRooms: string[] = postCalls[0][1].body.room_names;
|
||||
for (const name of rooms) {
|
||||
expect(requestedRooms).toContain(name);
|
||||
}
|
||||
});
|
||||
|
||||
it("batcher fetcher returns room-specific data", async () => {
|
||||
const {
|
||||
meetingStatusBatcher: batcher,
|
||||
} = require("../meetingStatusBatcher");
|
||||
|
||||
mockBulkStatusEndpoint({
|
||||
"room-a": {
|
||||
active_meetings: [{ id: "m1", room_name: "room-a" }],
|
||||
upcoming_events: [],
|
||||
},
|
||||
"room-b": {
|
||||
active_meetings: [],
|
||||
upcoming_events: [{ id: "e1", title: "Standup" }],
|
||||
},
|
||||
});
|
||||
|
||||
const [resultA, resultB] = await Promise.all([
|
||||
batcher.fetch("room-a"),
|
||||
batcher.fetch("room-b"),
|
||||
]);
|
||||
|
||||
expect(mockClient.POST).toHaveBeenCalledTimes(1);
|
||||
expect(resultA.active_meetings).toEqual([
|
||||
{ id: "m1", room_name: "room-a" },
|
||||
]);
|
||||
expect(resultA.upcoming_events).toEqual([]);
|
||||
expect(resultB.active_meetings).toEqual([]);
|
||||
expect(resultB.upcoming_events).toEqual([{ id: "e1", title: "Standup" }]);
|
||||
});
|
||||
|
||||
it("renders room-specific meeting data through hooks", async () => {
|
||||
mockBulkStatusEndpoint({
|
||||
"room-a": {
|
||||
active_meetings: [{ id: "m1", room_name: "room-a" }],
|
||||
upcoming_events: [],
|
||||
},
|
||||
"room-b": {
|
||||
active_meetings: [],
|
||||
upcoming_events: [{ id: "e1", title: "Standup" }],
|
||||
},
|
||||
});
|
||||
|
||||
render(<RoomList roomNames={["room-a", "room-b"]} />, {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("room-room-a")).toHaveTextContent(
|
||||
"1 active, 0 upcoming",
|
||||
);
|
||||
expect(screen.getByTestId("room-room-b")).toHaveTextContent(
|
||||
"0 active, 1 upcoming",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { $api } from "./apiClient";
|
||||
import { $api, API_URL } from "./apiClient";
|
||||
import { useError } from "../(errors)/errorContext";
|
||||
import { QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { components } from "../reflector-api";
|
||||
import { QueryClient, useQueryClient } from "@tanstack/react-query";
|
||||
import type { components, operations } from "../reflector-api";
|
||||
import { useAuth } from "./AuthProvider";
|
||||
import { meetingStatusBatcher } from "./meetingStatusBatcher";
|
||||
import { MeetingId } from "./types";
|
||||
import { NonEmptyString } from "./utils";
|
||||
import { createFinalURL, createQuerySerializer } from "openapi-fetch";
|
||||
|
||||
/*
|
||||
* XXX error types returned from the hooks are not always correct; declared types are ValidationError but real type could be string or any other
|
||||
@@ -698,7 +698,15 @@ export function useRoomsCreateMeeting() {
|
||||
queryKey: $api.queryOptions("get", "/v1/rooms").queryKey,
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: meetingStatusKeys.active(roomName),
|
||||
queryKey: $api.queryOptions(
|
||||
"get",
|
||||
"/v1/rooms/{room_name}/meetings/active" satisfies `/v1/rooms/{room_name}/${typeof MEETINGS_ACTIVE_PATH_PARTIAL}`,
|
||||
{
|
||||
params: {
|
||||
path: { room_name: roomName },
|
||||
},
|
||||
},
|
||||
).queryKey,
|
||||
}),
|
||||
]);
|
||||
},
|
||||
@@ -727,39 +735,42 @@ export function useRoomGetByName(roomName: string | null) {
|
||||
export function useRoomUpcomingMeetings(roomName: string | null) {
|
||||
const { isAuthenticated } = useAuthReady();
|
||||
|
||||
return useQuery({
|
||||
queryKey: meetingStatusKeys.upcoming(roomName!),
|
||||
queryFn: async () => {
|
||||
const result = await meetingStatusBatcher.fetch(roomName!);
|
||||
return result.upcoming_events;
|
||||
return $api.useQuery(
|
||||
"get",
|
||||
"/v1/rooms/{room_name}/meetings/upcoming" satisfies `/v1/rooms/{room_name}/${typeof MEETINGS_UPCOMING_PATH_PARTIAL}`,
|
||||
{
|
||||
params: {
|
||||
path: { room_name: roomName! },
|
||||
},
|
||||
},
|
||||
enabled: !!roomName && isAuthenticated,
|
||||
});
|
||||
{
|
||||
enabled: !!roomName && isAuthenticated,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Query keys reuse $api.queryOptions so cache identity matches the original
|
||||
// per-room GET endpoints. The actual fetch goes through the batcher, but the
|
||||
// keys stay consistent with the rest of the codebase.
|
||||
const meetingStatusKeys = {
|
||||
active: (roomName: string) =>
|
||||
$api.queryOptions("get", "/v1/rooms/{room_name}/meetings/active", {
|
||||
params: { path: { room_name: roomName } },
|
||||
}).queryKey,
|
||||
upcoming: (roomName: string) =>
|
||||
$api.queryOptions("get", "/v1/rooms/{room_name}/meetings/upcoming", {
|
||||
params: { path: { room_name: roomName } },
|
||||
}).queryKey,
|
||||
};
|
||||
const MEETINGS_PATH_PARTIAL = "meetings" as const;
|
||||
const MEETINGS_ACTIVE_PATH_PARTIAL = `${MEETINGS_PATH_PARTIAL}/active` as const;
|
||||
const MEETINGS_UPCOMING_PATH_PARTIAL =
|
||||
`${MEETINGS_PATH_PARTIAL}/upcoming` as const;
|
||||
const MEETING_LIST_PATH_PARTIALS = [
|
||||
MEETINGS_ACTIVE_PATH_PARTIAL,
|
||||
MEETINGS_UPCOMING_PATH_PARTIAL,
|
||||
];
|
||||
|
||||
export function useRoomActiveMeetings(roomName: string | null) {
|
||||
return useQuery({
|
||||
queryKey: meetingStatusKeys.active(roomName!),
|
||||
queryFn: async () => {
|
||||
const result = await meetingStatusBatcher.fetch(roomName!);
|
||||
return result.active_meetings;
|
||||
return $api.useQuery(
|
||||
"get",
|
||||
"/v1/rooms/{room_name}/meetings/active" satisfies `/v1/rooms/{room_name}/${typeof MEETINGS_ACTIVE_PATH_PARTIAL}`,
|
||||
{
|
||||
params: {
|
||||
path: { room_name: roomName! },
|
||||
},
|
||||
},
|
||||
enabled: !!roomName,
|
||||
});
|
||||
{
|
||||
enabled: !!roomName,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function useRoomGetMeeting(
|
||||
@@ -797,6 +808,44 @@ export function useRoomJoinMeeting() {
|
||||
);
|
||||
}
|
||||
|
||||
export const LEAVE_ROOM_POST_URL_TEMPLATE =
|
||||
"/v1/rooms/{room_name}/meetings/{meeting_id}/leave" as const;
|
||||
|
||||
export const leaveRoomPostUrl = (
|
||||
path: operations["v1_rooms_leave_meeting"]["parameters"]["path"],
|
||||
query?: operations["v1_rooms_leave_meeting"]["parameters"]["query"],
|
||||
): string =>
|
||||
createFinalURL(LEAVE_ROOM_POST_URL_TEMPLATE, {
|
||||
baseUrl: API_URL,
|
||||
params: { path, query },
|
||||
querySerializer: createQuerySerializer(),
|
||||
});
|
||||
|
||||
export type LeaveRoomBody = operations["v1_rooms_leave_meeting"]["requestBody"];
|
||||
|
||||
export function useRoomLeaveMeeting() {
|
||||
return $api.useMutation("post", LEAVE_ROOM_POST_URL_TEMPLATE);
|
||||
}
|
||||
|
||||
export const JOINED_ROOM_POST_URL_TEMPLATE =
|
||||
"/v1/rooms/{room_name}/meetings/{meeting_id}/joined" as const;
|
||||
|
||||
export const joinedRoomPostUrl = (
|
||||
params: operations["v1_rooms_joined_meeting"]["parameters"]["path"],
|
||||
): string =>
|
||||
createFinalURL(JOINED_ROOM_POST_URL_TEMPLATE, {
|
||||
baseUrl: API_URL,
|
||||
params: { path: params },
|
||||
querySerializer: () => "",
|
||||
});
|
||||
|
||||
export type JoinedRoomBody =
|
||||
operations["v1_rooms_joined_meeting"]["requestBody"];
|
||||
|
||||
export function useRoomJoinedMeeting() {
|
||||
return $api.useMutation("post", JOINED_ROOM_POST_URL_TEMPLATE);
|
||||
}
|
||||
|
||||
export function useRoomIcsSync() {
|
||||
const { setError } = useError();
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { create, keyResolver, windowScheduler } from "@yornaath/batshit";
|
||||
import { client } from "./apiClient";
|
||||
import type { components } from "../reflector-api";
|
||||
|
||||
type MeetingStatusResult = {
|
||||
roomName: string;
|
||||
active_meetings: components["schemas"]["Meeting"][];
|
||||
upcoming_events: components["schemas"]["CalendarEventResponse"][];
|
||||
};
|
||||
|
||||
const BATCH_WINDOW_MS = 10;
|
||||
|
||||
export function createMeetingStatusBatcher(windowMs: number = BATCH_WINDOW_MS) {
|
||||
return create({
|
||||
fetcher: async (roomNames: string[]): Promise<MeetingStatusResult[]> => {
|
||||
const unique = [...new Set(roomNames)];
|
||||
const { data, error } = await client.POST(
|
||||
"/v1/rooms/meetings/bulk-status",
|
||||
{ body: { room_names: unique } },
|
||||
);
|
||||
if (error || !data) {
|
||||
throw new Error(
|
||||
`bulk-status fetch failed: ${JSON.stringify(error ?? "no data")}`,
|
||||
);
|
||||
}
|
||||
return roomNames.map((name) => ({
|
||||
roomName: name,
|
||||
active_meetings: data[name]?.active_meetings ?? [],
|
||||
upcoming_events: data[name]?.upcoming_events ?? [],
|
||||
}));
|
||||
},
|
||||
resolver: keyResolver("roomName"),
|
||||
scheduler: windowScheduler(windowMs),
|
||||
});
|
||||
}
|
||||
|
||||
export const meetingStatusBatcher = createMeetingStatusBatcher();
|
||||
172
www/app/reflector-api.d.ts
vendored
172
www/app/reflector-api.d.ts
vendored
@@ -118,23 +118,6 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/rooms/meetings/bulk-status": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Rooms Bulk Meeting Status */
|
||||
post: operations["v1_rooms_bulk_meeting_status"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/rooms/{room_id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -188,6 +171,48 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/rooms/{room_name}/meetings/{meeting_id}/joined": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Rooms Joined Meeting
|
||||
* @description Trigger presence poll (ideally when user actually joins meeting in Daily iframe)
|
||||
*/
|
||||
post: operations["v1_rooms_joined_meeting"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/rooms/{room_name}/meetings/{meeting_id}/leave": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Rooms Leave Meeting
|
||||
* @description Trigger presence recheck when user leaves meeting (e.g., tab close/navigation).
|
||||
*
|
||||
* Queues presence poll with optional delay to allow Daily.co to detect disconnect.
|
||||
*/
|
||||
post: operations["v1_rooms_leave_meeting"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/v1/rooms/{room_id}/webhook/test": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -816,11 +841,6 @@ export interface components {
|
||||
*/
|
||||
chunk: string;
|
||||
};
|
||||
/** BulkStatusRequest */
|
||||
BulkStatusRequest: {
|
||||
/** Room Names */
|
||||
room_names: string[];
|
||||
};
|
||||
/** CalendarEventResponse */
|
||||
CalendarEventResponse: {
|
||||
/** Id */
|
||||
@@ -1757,13 +1777,6 @@ export interface components {
|
||||
/** Webhook Secret */
|
||||
webhook_secret: string | null;
|
||||
};
|
||||
/** RoomMeetingStatus */
|
||||
RoomMeetingStatus: {
|
||||
/** Active Meetings */
|
||||
active_meetings: components["schemas"]["Meeting"][];
|
||||
/** Upcoming Events */
|
||||
upcoming_events: components["schemas"]["CalendarEventResponse"][];
|
||||
};
|
||||
/** RtcOffer */
|
||||
RtcOffer: {
|
||||
/** Sdp */
|
||||
@@ -2301,41 +2314,6 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
v1_rooms_bulk_meeting_status: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["BulkStatusRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description Successful Response */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
[key: string]: components["schemas"]["RoomMeetingStatus"];
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @description Validation Error */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["HTTPValidationError"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
v1_rooms_get: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -2499,6 +2477,72 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
v1_rooms_joined_meeting: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
room_name: string;
|
||||
meeting_id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Successful Response */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": unknown;
|
||||
};
|
||||
};
|
||||
/** @description Validation Error */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["HTTPValidationError"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
v1_rooms_leave_meeting: {
|
||||
parameters: {
|
||||
query?: {
|
||||
delay_seconds?: number;
|
||||
};
|
||||
header?: never;
|
||||
path: {
|
||||
room_name: string;
|
||||
meeting_id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description Successful Response */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": unknown;
|
||||
};
|
||||
};
|
||||
/** @description Validation Error */
|
||||
422: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["HTTPValidationError"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
v1_rooms_test_webhook: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -1,22 +1,8 @@
|
||||
module.exports = {
|
||||
testEnvironment: "jest-environment-jsdom",
|
||||
preset: "ts-jest",
|
||||
testEnvironment: "node",
|
||||
roots: ["<rootDir>/app"],
|
||||
testMatch: ["**/__tests__/**/*.test.ts", "**/__tests__/**/*.test.tsx"],
|
||||
collectCoverage: false,
|
||||
transform: {
|
||||
"^.+\\.[jt]sx?$": [
|
||||
"ts-jest",
|
||||
{
|
||||
tsconfig: {
|
||||
jsx: "react-jsx",
|
||||
module: "esnext",
|
||||
moduleResolution: "bundler",
|
||||
esModuleInterop: true,
|
||||
strict: true,
|
||||
downlevelIteration: true,
|
||||
lib: ["dom", "dom.iterable", "esnext"],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
testMatch: ["**/__tests__/**/*.test.ts"],
|
||||
collectCoverage: true,
|
||||
collectCoverageFrom: ["app/**/*.ts", "!app/**/*.d.ts"],
|
||||
};
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
"@tanstack/react-query": "^5.85.9",
|
||||
"@types/ioredis": "^5.0.0",
|
||||
"@whereby.com/browser-sdk": "^3.3.4",
|
||||
"@yornaath/batshit": "^0.14.0",
|
||||
"autoprefixer": "10.4.20",
|
||||
"axios": "^1.8.2",
|
||||
"eslint": "^9.33.0",
|
||||
@@ -62,13 +61,9 @@
|
||||
"author": "Andreas <andreas@monadical.com>",
|
||||
"license": "All Rights Reserved",
|
||||
"devDependencies": {
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/react": "18.2.20",
|
||||
"jest": "^30.1.3",
|
||||
"jest-environment-jsdom": "^30.2.0",
|
||||
"openapi-typescript": "^7.9.1",
|
||||
"prettier": "^3.0.0",
|
||||
"ts-jest": "^29.4.1"
|
||||
|
||||
808
www/pnpm-lock.yaml
generated
808
www/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user