|
| 1 | +import logging |
| 2 | +from typing import Any, Callable, TypeVar |
| 3 | + |
| 4 | +from fastapi import Request |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +from codegen.extensions.events.interface import EventHandlerManagerProtocol |
| 8 | +from codegen.extensions.github.types.base import GitHubInstallation, GitHubWebhookPayload |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | +logger.setLevel(logging.DEBUG) |
| 12 | + |
| 13 | + |
| 14 | +# Type variable for event types |
| 15 | +T = TypeVar("T", bound=BaseModel) |
| 16 | + |
| 17 | + |
| 18 | +class GitHub(EventHandlerManagerProtocol): |
| 19 | + def __init__(self, app): |
| 20 | + self.app = app |
| 21 | + self.registered_handlers = {} |
| 22 | + |
| 23 | + # TODO - add in client info |
| 24 | + # @property |
| 25 | + # def client(self) -> Github: |
| 26 | + # if not self._client: |
| 27 | + # self._client = Github(os.environ["GITHUB_TOKEN"]) |
| 28 | + # return self._client |
| 29 | + |
| 30 | + def unsubscribe_all_handlers(self): |
| 31 | + logger.info("[HANDLERS] Clearing all handlers") |
| 32 | + self.registered_handlers.clear() |
| 33 | + |
| 34 | + def event(self, event_name: str): |
| 35 | + """Decorator for registering a GitHub event handler. |
| 36 | +
|
| 37 | + Example: |
| 38 | + @app.github.event('push') |
| 39 | + def handle_push(event: PushEvent): # Can be typed with Pydantic model |
| 40 | + logger.info(f"Received push to {event.ref}") |
| 41 | +
|
| 42 | + @app.github.event('pull_request:opened') |
| 43 | + def handle_pr(event: dict): # Or just use dict for raw event |
| 44 | + logger.info(f"Received PR") |
| 45 | + """ |
| 46 | + logger.info(f"[EVENT] Registering handler for {event_name}") |
| 47 | + |
| 48 | + def register_handler(func: Callable[[T], Any]): |
| 49 | + # Get the type annotation from the first parameter |
| 50 | + event_type = func.__annotations__.get("event") |
| 51 | + func_name = func.__qualname__ |
| 52 | + logger.info(f"[EVENT] Registering function {func_name} for {event_name}") |
| 53 | + |
| 54 | + def new_func(raw_event: dict): |
| 55 | + # Only validate if a Pydantic model was specified |
| 56 | + if event_type and issubclass(event_type, BaseModel): |
| 57 | + try: |
| 58 | + parsed_event = event_type.model_validate(raw_event) |
| 59 | + return func(parsed_event) |
| 60 | + except Exception as e: |
| 61 | + logger.exception(f"Error parsing event: {e}") |
| 62 | + raise |
| 63 | + else: |
| 64 | + # Pass through raw dict if no type validation needed |
| 65 | + return func(raw_event) |
| 66 | + |
| 67 | + self.registered_handlers[event_name] = new_func |
| 68 | + return new_func |
| 69 | + |
| 70 | + return register_handler |
| 71 | + |
| 72 | + def handle(self, event: dict, request: Request): |
| 73 | + """Handle both webhook events and installation callbacks.""" |
| 74 | + logger.info("[HANDLER] Handling GitHub event") |
| 75 | + |
| 76 | + # Check if this is an installation event |
| 77 | + if "installation_id" in event and "code" in event: |
| 78 | + installation = GitHubInstallation.model_validate(event) |
| 79 | + logger.info("=====[GITHUB APP INSTALLATION]=====") |
| 80 | + logger.info(f"Code: {installation.code}") |
| 81 | + logger.info(f"Installation ID: {installation.installation_id}") |
| 82 | + logger.info(f"Setup Action: {installation.setup_action}") |
| 83 | + return { |
| 84 | + "message": "GitHub app installation details received", |
| 85 | + "details": { |
| 86 | + "code": installation.code, |
| 87 | + "installation_id": installation.installation_id, |
| 88 | + "setup_action": installation.setup_action, |
| 89 | + }, |
| 90 | + } |
| 91 | + |
| 92 | + # Extract headers for webhook events |
| 93 | + headers = { |
| 94 | + "x-github-event": request.headers.get("x-github-event"), |
| 95 | + "x-github-delivery": request.headers.get("x-github-delivery"), |
| 96 | + "x-github-hook-id": request.headers.get("x-github-hook-id"), |
| 97 | + "x-github-hook-installation-target-id": request.headers.get("x-github-hook-installation-target-id"), |
| 98 | + "x-github-hook-installation-target-type": request.headers.get("x-github-hook-installation-target-type"), |
| 99 | + } |
| 100 | + print(headers) |
| 101 | + |
| 102 | + # Handle webhook events |
| 103 | + try: |
| 104 | + webhook = GitHubWebhookPayload.model_validate({"headers": headers, "event": event}) |
| 105 | + |
| 106 | + # Get base event type and action |
| 107 | + event_type = webhook.headers.event_type |
| 108 | + action = webhook.event.action |
| 109 | + |
| 110 | + # Combine event type and action if both exist |
| 111 | + full_event_type = f"{event_type}:{action}" if action else event_type |
| 112 | + |
| 113 | + if full_event_type not in self.registered_handlers: |
| 114 | + logger.info(f"[HANDLER] No handler found for event type: {full_event_type}") |
| 115 | + return {"message": "Event type not handled"} |
| 116 | + |
| 117 | + else: |
| 118 | + logger.info(f"[HANDLER] Handling event: {full_event_type}") |
| 119 | + handler = self.registered_handlers[full_event_type] |
| 120 | + return handler(event) # TODO - pass through typed values |
| 121 | + except Exception as e: |
| 122 | + logger.exception(f"Error handling webhook: {e}") |
| 123 | + raise |
0 commit comments