Buckets:

download
raw
6.41 kB
"""Long polling HTTP endpoint as WebSocket fallback."""
import logging
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field
from pulsar_relay.auth.dependencies import get_current_user, get_topic_storage, require_permission
from pulsar_relay.auth.models import User
from pulsar_relay.core.polling import PollManager, PollWaiterLimitExceededError
from pulsar_relay.models import TopicName
from pulsar_relay.storage.base import StorageBackend
logger = logging.getLogger(__name__)
router = APIRouter()
class PollRequest(BaseModel):
"""Request model for long polling."""
# ``max_length=20`` caps the number of topics one waiter can fan out
# over — defends against a single caller exhausting the poll-manager
# subscription map (API H#8).
topics: list[TopicName] = Field(..., description="Topics to subscribe to", min_length=1, max_length=20)
since: Optional[dict[str, str]] = Field(
default=None,
description="Last message ID seen per topic for catching up on missed messages",
)
timeout: int = Field(
default=30,
description="Maximum seconds to wait for new messages",
ge=1,
le=60,
)
class PollResponse(BaseModel):
"""Response model for long polling."""
messages: list[dict[str, Any]] = Field(default_factory=list, description="Messages received")
has_more: bool = Field(
default=False,
description="Whether there might be more messages available immediately",
)
@router.post("/poll", response_model=PollResponse)
async def long_poll(
poll_request: PollRequest,
request: Request,
current_user: User = Depends(require_permission("read")),
) -> PollResponse:
"""Long polling endpoint for receiving messages.
This endpoint allows clients to receive messages without WebSocket support.
The server will hold the connection open until messages arrive or timeout.
Args:
poll_request: Polling request with topics and parameters
request: FastAPI request object for accessing app state
Returns:
PollResponse with any messages received
Raises:
HTTPException: If storage is unavailable or invalid parameters
"""
# Get dependencies from app state
poll_manager: PollManager = request.app.state.poll_manager
storage: StorageBackend = request.app.state.storage
# Validate topics
if not poll_request.topics:
raise HTTPException(status_code=400, detail="At least one topic required")
# Validate access to ALL requested topics upfront - fail early if any are denied
topic_storage = get_topic_storage()
denied_topics = []
for topic in poll_request.topics:
can_access = await topic_storage.user_can_access(
owner_id=current_user.user_id,
topic_name=topic,
user_id=current_user.user_id,
permission_type="read",
user_permissions=current_user.permissions,
)
if not can_access:
denied_topics.append(topic)
# Fail fast if any topics are denied. The error message intentionally
# does NOT echo the denied topic names back (Medium #11: avoiding a
# topic-existence enumeration oracle).
if denied_topics:
raise HTTPException(
status_code=403,
detail="Access denied to one or more requested topics",
)
messages = []
owner_id = current_user.user_id
# First, check for any recent messages the client hasn't seen
if poll_request.since:
# Client wants to catch up on messages
# The message IDs in `since` are now the same as the storage IDs (stream IDs for Valkey)
for topic in poll_request.topics:
since_message_id = poll_request.since.get(topic)
recent_messages = await storage.get_messages(
owner_id=owner_id, topic=topic, since=since_message_id, limit=100
)
for msg in recent_messages:
messages.append(
{
"topic": topic,
"message_id": msg["message_id"],
"payload": msg["payload"],
"timestamp": msg["timestamp"],
"metadata": msg.get("metadata", {}),
"stream_id": msg.get("stream_id"),
}
)
# If we already have messages, return immediately
if messages:
logger.debug(f"Returning {len(messages)} cached messages immediately")
return PollResponse(messages=messages, has_more=len(messages) >= 100)
# No cached messages, create waiter for new messages. Subscribe
# under the composite ``{owner_id}/{topic}`` channel so a publish
# to A's "jobs" doesn't deliver to B's "jobs" subscribers (API H#5).
composite_topics = [f"{owner_id}/{t}" for t in poll_request.topics]
try:
waiter = await poll_manager.create_waiter(composite_topics, user_id=current_user.user_id)
except PollWaiterLimitExceededError as exc:
logger.warning("Poll waiter limit exceeded for user %s: %s", current_user.user_id, exc)
raise HTTPException(
status_code=429,
detail="Too many concurrent poll connections",
) from exc
try:
# Wait for new messages with timeout
logger.debug(
f"Waiting for new messages on topics {poll_request.topics} " f"with timeout {poll_request.timeout}s"
)
new_messages = await waiter.wait_for_messages(timeout=float(poll_request.timeout))
if new_messages:
logger.info(f"Returning {len(new_messages)} new messages to poll client")
messages.extend(new_messages)
finally:
# Always clean up the waiter
await poll_manager.remove_waiter(waiter.client_id)
return PollResponse(messages=messages, has_more=False)
@router.get("/poll/stats")
async def get_poll_stats(
request: Request,
current_user: User = Depends(get_current_user),
) -> dict[str, Any]:
"""Get statistics about active long polling clients.
Args:
request: FastAPI request object
Returns:
Statistics about poll manager
"""
poll_manager: PollManager = request.app.state.poll_manager
return poll_manager.get_stats()

Xet Storage Details

Size:
6.41 kB
·
Xet hash:
7625e33931c559d91411625345d0c525f56f93f27c77a6f64697735c746fc5ec

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.