-
Notifications
You must be signed in to change notification settings - Fork 2.1k
chore: Endpoints cleanup ✨ #42216
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
Merged
Merged
chore: Endpoints cleanup ✨ #42216
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d851ee4
chore: run endpoint inline when materialization is stale
sakce 78c48cc
chore: endpoints frontend cleanup
sakce ad8de3c
chore: standardize exception capturing
cursoragent 0ae05cf
fix: security exception detail fix thanks copilot
sakce e047516
chore: remove new-endpoint URL thingz
sakce 779dee3
fix: cleanup exception handling on endpoint run()
sakce d21aea5
fix: don't expose exception string
sakce 7826b79
fix: lint and stuff
sakce File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
|
|
||
| from django.core.cache import cache | ||
| from django.shortcuts import get_object_or_404 | ||
| from django.utils import timezone | ||
|
|
||
| from django_filters.rest_framework import DjangoFilterBackend | ||
| from loginas.utils import is_impersonated_session | ||
|
|
@@ -24,10 +25,13 @@ | |
| QueryRequest, | ||
| QueryStatus, | ||
| QueryStatusResponse, | ||
| RefreshType, | ||
| ) | ||
|
|
||
| from posthog.hogql import ast | ||
| from posthog.hogql.constants import LimitContext | ||
| from posthog.hogql.errors import ExposedHogQLError, ResolutionError | ||
| from posthog.hogql.property import property_to_expr | ||
|
|
||
| from posthog.api.documentation import extend_schema | ||
| from posthog.api.mixins import PydanticModelMixin | ||
|
|
@@ -218,9 +222,15 @@ | |
|
|
||
| return Response(self._serialize_endpoint(endpoint), status=status.HTTP_201_CREATED) | ||
|
|
||
| # We should expose if the query name is duplicate | ||
| except Exception as e: | ||
| capture_exception(e) | ||
| capture_exception( | ||
| e, | ||
| { | ||
| "product": Product.ENDPOINTS, | ||
| "team_id": self.team_id, | ||
| "endpoint_name": data.name, | ||
| }, | ||
| ) | ||
| raise ValidationError("Failed to create endpoint.") | ||
|
|
||
| def validate_update_request( | ||
|
|
@@ -315,7 +325,15 @@ | |
| return Response(self._serialize_endpoint(endpoint)) | ||
|
|
||
| except Exception as e: | ||
| capture_exception(e) | ||
| capture_exception( | ||
| e, | ||
| { | ||
| "product": Product.ENDPOINTS, | ||
| "team_id": self.team_id, | ||
| "endpoint_id": endpoint.id, | ||
| "saved_query_id": endpoint.saved_query.id if endpoint.saved_query else None, | ||
| }, | ||
| ) | ||
| raise ValidationError("Failed to update endpoint.") | ||
|
|
||
| def _enable_materialization( | ||
|
|
@@ -372,6 +390,7 @@ | |
| Returns False if: | ||
| - Not materialized | ||
| - Materialization incomplete/failed | ||
| - Materialized data is stale (older than sync frequency) | ||
| - User overrides present (variables, filters, query) | ||
| - Force refresh requested | ||
| """ | ||
|
|
@@ -385,6 +404,12 @@ | |
| if not saved_query.table: | ||
| return False | ||
|
|
||
| # Check if materialized data is stale | ||
|
Contributor
Author
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. @orian this 🎀 is for you |
||
| if saved_query.last_run_at and saved_query.sync_frequency_interval: | ||
| next_refresh_due = saved_query.last_run_at + saved_query.sync_frequency_interval | ||
| if timezone.now() >= next_refresh_due: | ||
| return False | ||
|
|
||
| if data.variables: | ||
| return False | ||
|
|
||
|
|
@@ -443,49 +468,55 @@ | |
| self, endpoint: Endpoint, data: EndpointRunRequest, request: Request | ||
| ) -> Response: | ||
| """Execute against a materialized table in S3.""" | ||
| from posthog.schema import RefreshType | ||
|
|
||
| from posthog.hogql import ast | ||
| from posthog.hogql.property import property_to_expr | ||
| try: | ||
| saved_query = endpoint.saved_query | ||
| if not saved_query: | ||
| raise ValidationError("No materialized query found for this endpoint") | ||
|
|
||
| saved_query = endpoint.saved_query | ||
| if not saved_query: | ||
| raise ValidationError("No materialized query found for this endpoint") | ||
| select_query = ast.SelectQuery( | ||
| select=[ast.Field(chain=["*"])], | ||
| select_from=ast.JoinExpr(table=ast.Field(chain=[saved_query.name])), | ||
| ) | ||
|
|
||
| # Build AST for SELECT * FROM table | ||
| select_query = ast.SelectQuery( | ||
| select=[ast.Field(chain=["*"])], | ||
| select_from=ast.JoinExpr(table=ast.Field(chain=[saved_query.name])), | ||
| ) | ||
| if data.filters_override and data.filters_override.properties: | ||
| try: | ||
| property_expr = property_to_expr(data.filters_override.properties, self.team) | ||
| select_query.where = property_expr | ||
| except Exception: | ||
| raise ValidationError("Failed to apply property filters.") | ||
sakce marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if data.filters_override and data.filters_override.properties: | ||
| try: | ||
| property_expr = property_to_expr(data.filters_override.properties, self.team) | ||
| select_query.where = property_expr | ||
| except Exception as e: | ||
| capture_exception(e) | ||
| raise ValidationError(f"Failed to apply property filters.") | ||
|
|
||
| materialized_hogql_query = HogQLQuery( | ||
| query=select_query.to_hogql(), modifiers=HogQLQueryModifiers(useMaterializedViews=True) | ||
| ) | ||
| materialized_hogql_query = HogQLQuery( | ||
| query=select_query.to_hogql(), modifiers=HogQLQueryModifiers(useMaterializedViews=True) | ||
| ) | ||
|
|
||
| query_request_data = { | ||
| "client_query_id": data.client_query_id, | ||
| "name": f"{endpoint.name}_materialized", | ||
| "refresh": data.refresh or RefreshType.BLOCKING, | ||
| "query": materialized_hogql_query.model_dump(), | ||
| } | ||
| query_request_data = { | ||
| "client_query_id": data.client_query_id, | ||
| "name": f"{endpoint.name}_materialized", | ||
| "refresh": data.refresh or RefreshType.BLOCKING, | ||
| "query": materialized_hogql_query.model_dump(), | ||
| } | ||
|
|
||
| extra_fields = { | ||
| "_materialized": True, | ||
| "_materialized_at": saved_query.last_run_at.isoformat() if saved_query.last_run_at else None, | ||
| } | ||
| tag_queries(workload=Workload.ENDPOINTS, warehouse_query=True) | ||
| extra_fields = { | ||
| "endpoint_materialized": True, | ||
| "endpoint_materialized_at": saved_query.last_run_at.isoformat() if saved_query.last_run_at else None, | ||
| } | ||
| tag_queries(workload=Workload.ENDPOINTS, warehouse_query=True) | ||
|
|
||
| return self._execute_query_and_respond( | ||
| query_request_data, data.client_query_id, request, extra_result_fields=extra_fields | ||
| ) | ||
| return self._execute_query_and_respond( | ||
| query_request_data, data.client_query_id, request, extra_result_fields=extra_fields | ||
| ) | ||
| except Exception as e: | ||
| capture_exception( | ||
| e, | ||
| { | ||
| "product": Product.ENDPOINTS, | ||
| "team_id": self.team_id, | ||
| "endpoint_name": endpoint.name, | ||
| "materialized": True, | ||
| "saved_query_id": saved_query.id if saved_query else None, | ||
| }, | ||
| ) | ||
| raise | ||
|
|
||
| def _parse_variables(self, query: dict[str, dict], variables: dict[str, str]) -> dict[str, dict] | None: | ||
| query_variables = query.get("variables", None) | ||
|
|
@@ -507,7 +538,6 @@ | |
| variableId=variable_id, | ||
| code_name=variable_code_name, | ||
| value=variable_value, | ||
| # TODO: this needs more attention! | ||
| isNull=True if variable_value is None else None, | ||
| ).model_dump() | ||
| return variables_override | ||
|
|
@@ -535,15 +565,17 @@ | |
| query_request_data, data.client_query_id, request, cache_age_seconds=endpoint.cache_age_seconds | ||
| ) | ||
|
|
||
| except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e: | ||
| raise ValidationError(str(e), getattr(e, "code_name", None)) | ||
| except ResolutionError as e: | ||
| raise ValidationError(str(e)) | ||
| except ConcurrencyLimitExceeded as c: | ||
| raise Throttled(detail=str(c)) | ||
| except Exception as e: | ||
| self.handle_column_ch_error(e) | ||
| capture_exception(e) | ||
| capture_exception( | ||
| e, | ||
| { | ||
| "product": Product.ENDPOINTS, | ||
| "team_id": self.team_id, | ||
| "materialized": False, | ||
| "endpoint_name": endpoint.name, | ||
| }, | ||
| ) | ||
| raise | ||
|
|
||
| @extend_schema( | ||
|
|
@@ -588,16 +620,22 @@ | |
| # Only the latest version is materialized | ||
| use_materialized = version_number is None and self._should_use_materialized_table(endpoint, data) | ||
|
|
||
| if use_materialized: | ||
| result = self._execute_materialized_endpoint(endpoint, data, request) | ||
| else: | ||
| # Use version's query if available, otherwise use endpoint.query | ||
| query_to_use = version_obj.query if version_obj else endpoint.query.copy() | ||
| result = self._execute_inline_endpoint(endpoint, data, request, query_to_use) | ||
|
|
||
| try: | ||
| if use_materialized: | ||
| result = self._execute_materialized_endpoint(endpoint, data, request) | ||
| else: | ||
| # Use version's query if available, otherwise use endpoint.query | ||
| query_to_use = version_obj.query if version_obj else endpoint.query.copy() | ||
| result = self._execute_inline_endpoint(endpoint, data, request, query_to_use) | ||
| except (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e: | ||
| raise ValidationError(str(e), getattr(e, "code_name", None)) | ||
| except ResolutionError as e: | ||
| raise ValidationError(str(e)) | ||
|
||
| except ConcurrencyLimitExceeded: | ||
| raise Throttled(detail="Too many concurrent requests. Please try again later.") | ||
| if version_obj and isinstance(result.data, dict): | ||
| result.data["_version"] = version_obj.version | ||
| result.data["_version_created_at"] = version_obj.created_at.isoformat() | ||
| result.data["endpoint_version"] = version_obj.version | ||
| result.data["endpoint_version_created_at"] = version_obj.created_at.isoformat() | ||
|
|
||
| return result | ||
|
|
||
|
|
@@ -648,7 +686,7 @@ | |
| except ConcurrencyLimitExceeded as c: | ||
| raise Throttled(detail=str(c)) | ||
| except Exception as e: | ||
| capture_exception(e) | ||
| capture_exception(e, {"product": Product.ENDPOINTS, "team_id": self.team_id}) | ||
| raise | ||
|
|
||
| def handle_column_ch_error(self, error): | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.