human hand off

This commit is contained in:
debu-2 2026-10-06 07:12:55 +05:30
parent d0fee5c8f7
commit 7af776196a
34 changed files with 2941 additions and 195 deletions

View file

@ -23,6 +23,7 @@ from app.routers import (
)
from app.services.thread_service import create_thread, message_event_at
from app.services.domain_provisioning import ensure_platform_domain
from app.services.handoff_delivery import handoff_delivery_worker
from app.services.inbound_smtp import InboundSMTPServer
settings = get_settings()
@ -208,6 +209,11 @@ async def lifespan(_: FastAPI):
sparse=True,
unique=True,
)
await mongo_db.messages.create_index(
[("handoff_delivery_key", 1)],
sparse=True,
unique=True,
)
await mongo_db.mailbox_entries.create_index(
[("account_id", 1), ("thread_id", 1), ("event_at", -1), ("_id", -1)]
)
@ -217,18 +223,54 @@ async def lifespan(_: FastAPI):
await mongo_db.human_handoff_rules.create_index(
[("account_id", 1), ("updated_at", -1)]
)
account_ids = await mongo_db.human_handoff_rules.distinct("account_id")
for account_id in account_ids:
existing_rules = (
await mongo_db.human_handoff_rules.find({"account_id": account_id})
.sort([("priority", 1), ("created_at", 1), ("_id", 1)])
.to_list(length=1000)
)
for index, rule in enumerate(existing_rules):
if rule.get("priority") != index:
await mongo_db.human_handoff_rules.update_one(
{"_id": rule["_id"]},
{"$set": {"priority": index}},
)
await mongo_db.human_handoff_rules.create_index(
[("account_id", 1), ("priority", 1)],
unique=True,
)
await mongo_db.human_handoff_rules.create_index(
[("account_id", 1), ("name_key", 1)],
unique=True,
sparse=True,
)
await mongo_db.human_handoffs.create_index(
[("account_id", 1), ("updated_at", -1)]
)
await mongo_db.human_handoffs.create_index(
[("account_id", 1), ("external_thread_id", 1)]
[("account_id", 1), ("external_thread_id", 1)],
unique=True,
)
await mongo_db.human_handoffs.create_index(
[("account_id", 1), ("handoff_thread_id", 1)]
[("account_id", 1), ("handoff_thread_id", 1)],
unique=True,
)
await mongo_db.handoff_message_links.create_index(
[("handoff_id", 1), ("created_at", -1)]
)
await mongo_db.handoff_message_links.create_index(
[("handoff_id", 1), ("source_message_id", 1), ("relationship", 1)],
unique=True,
sparse=True,
)
await mongo_db.handoff_delivery_jobs.create_index(
[("idempotency_key", 1)],
unique=True,
)
await mongo_db.handoff_delivery_jobs.create_index(
[("status", 1), ("next_attempt_at", 1), ("created_at", 1)]
)
await mongo_db.mailbox_entries.create_index(
[("account_id", 1), ("message_scope", 1), ("mailbox", 1), ("event_at", -1)]
)
@ -239,9 +281,11 @@ async def lifespan(_: FastAPI):
await backfill_missing_thread_ids(mongo_db)
if settings.inbound_smtp_enabled:
await inbound_server.start()
await handoff_delivery_worker.start()
try:
yield
finally:
await handoff_delivery_worker.stop()
await inbound_server.stop()
await engine.dispose()
await mongo_client.close()