-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: shared session load path for session and export APIs #125
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
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """Shared resolve/load/exclude/error helpers for session API handlers.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from collections.abc import Callable | ||
| from dataclasses import dataclass | ||
|
|
||
| from flask import current_app | ||
|
|
||
| from api._flask_types import FlaskReturn | ||
| from api.error_codes import ErrorCode, error_response | ||
| from models.session import SessionDict | ||
| from models.stats import SessionStatsDict | ||
| from utils.exclusion_rules import is_session_excluded | ||
| from utils.session_cache import get_cached_session | ||
| from utils.session_errors import SESSION_LOAD_ERRORS | ||
| from utils.session_path import get_claude_projects_dir, safe_join | ||
| from utils.session_stats import compute_stats | ||
|
|
||
| __all__ = [ | ||
| "SESSION_LOAD_ERRORS", | ||
| "LoadedSession", | ||
| "resolve_loaded_session", | ||
| "compute_stats_or_error", | ||
| ] | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class LoadedSession: | ||
| session: SessionDict | ||
| filepath: str | ||
|
|
||
|
|
||
| def resolve_loaded_session( | ||
| project_name: str, | ||
| session_id: str, | ||
| *, | ||
| missing_file_message: str | Callable[[str], str], | ||
| parse_log_action: str = "Failed to parse session %s", | ||
| ) -> LoadedSession | FlaskReturn: | ||
| """Resolve path, load session, and apply exclusion rules. | ||
|
|
||
| Returns ``LoadedSession`` on success or an ``error_response`` tuple/Response. | ||
| """ | ||
| base = current_app.config.get("CLAUDE_PROJECTS_DIR") or get_claude_projects_dir() | ||
| try: | ||
| filepath = safe_join(base, project_name, f"{session_id}.jsonl") | ||
| except ValueError: | ||
| return error_response(ErrorCode.INVALID_PATH, "Invalid path", 400) | ||
|
|
||
| if not os.path.isfile(filepath): | ||
| msg = ( | ||
| missing_file_message(session_id) | ||
| if callable(missing_file_message) | ||
| else missing_file_message | ||
| ) | ||
| return error_response(ErrorCode.SESSION_NOT_FOUND, msg, 404) | ||
|
|
||
| try: | ||
| session = get_cached_session(filepath) | ||
| rules = current_app.config.get("EXCLUSION_RULES") or [] | ||
| if is_session_excluded(rules, session, project_name): | ||
| return error_response( | ||
| ErrorCode.SESSION_NOT_FOUND, | ||
| "Session not found", | ||
| 404, | ||
| ) | ||
| except SESSION_LOAD_ERRORS: | ||
| current_app.logger.exception(parse_log_action, session_id) | ||
| return error_response( | ||
| ErrorCode.PARSE_ERROR, | ||
| "Failed to parse session", | ||
| 500, | ||
| ) | ||
|
|
||
| return LoadedSession(session=session, filepath=filepath) | ||
|
|
||
|
|
||
| def compute_stats_or_error( | ||
| session: SessionDict, | ||
| session_id: str, | ||
| *, | ||
| log_action: str, | ||
| ) -> SessionStatsDict | FlaskReturn: | ||
| try: | ||
| return compute_stats(session) | ||
| except SESSION_LOAD_ERRORS: | ||
| current_app.logger.exception(log_action, session_id) | ||
| return error_response( | ||
| ErrorCode.INTERNAL_ERROR, | ||
| "Failed to compute session stats", | ||
| 500, | ||
| ) | ||
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 |
|---|---|---|
| @@ -1,101 +1,47 @@ | ||
| """Session detail and stats endpoints.""" | ||
|
|
||
| import json | ||
| import os | ||
|
|
||
| from flask import Blueprint, current_app | ||
| from flask import Blueprint | ||
|
|
||
| from api._flask_types import FlaskReturn, json_response | ||
| from api.error_codes import ErrorCode, error_response | ||
| from utils.exclusion_rules import is_session_excluded | ||
| from utils.session_cache import get_cached_session | ||
| from utils.session_path import get_claude_projects_dir, safe_join | ||
| from utils.session_stats import compute_stats | ||
| from api._session_handlers import ( | ||
| LoadedSession, | ||
| compute_stats_or_error, | ||
| resolve_loaded_session, | ||
| ) | ||
|
|
||
| sessions_bp = Blueprint("sessions", __name__) | ||
|
|
||
| _PARSE_ERRORS = ( | ||
| json.JSONDecodeError, | ||
| KeyError, | ||
| ValueError, | ||
| OSError, | ||
| FileNotFoundError, | ||
| ) | ||
|
|
||
| def _missing_session_message(session_id: str) -> str: | ||
| return f"Session {session_id} not found" | ||
|
|
||
|
|
||
| @sessions_bp.route("/api/sessions/<path:project_name>/<session_id>") | ||
| def get_session(project_name: str, session_id: str) -> FlaskReturn: | ||
| base = current_app.config.get("CLAUDE_PROJECTS_DIR") or get_claude_projects_dir() | ||
| try: | ||
| filepath = safe_join(base, project_name, f"{session_id}.jsonl") | ||
| except ValueError: | ||
| return error_response(ErrorCode.INVALID_PATH, "Invalid path", 400) | ||
|
|
||
| if not os.path.isfile(filepath): | ||
| return error_response( | ||
| ErrorCode.SESSION_NOT_FOUND, | ||
| f"Session {session_id} not found", | ||
| 404, | ||
| ) | ||
|
|
||
| try: | ||
| session = get_cached_session(filepath) | ||
| rules = current_app.config.get("EXCLUSION_RULES") or [] | ||
| if is_session_excluded(rules, session, project_name): | ||
| return error_response( | ||
| ErrorCode.SESSION_NOT_FOUND, | ||
| "Session not found", | ||
| 404, | ||
| ) | ||
| return json_response(session) | ||
| except _PARSE_ERRORS: | ||
| current_app.logger.exception("Failed to parse session %s", session_id) | ||
| return error_response( | ||
| ErrorCode.PARSE_ERROR, | ||
| "Failed to parse session", | ||
| 500, | ||
| ) | ||
| loaded = resolve_loaded_session( | ||
| project_name, | ||
| session_id, | ||
| missing_file_message=_missing_session_message, | ||
| ) | ||
| if isinstance(loaded, LoadedSession): | ||
| return json_response(loaded.session) | ||
| return loaded | ||
|
|
||
|
|
||
| @sessions_bp.route("/api/sessions/<path:project_name>/<session_id>/stats") | ||
| def get_session_stats(project_name: str, session_id: str) -> FlaskReturn: | ||
| base = current_app.config.get("CLAUDE_PROJECTS_DIR") or get_claude_projects_dir() | ||
| try: | ||
| filepath = safe_join(base, project_name, f"{session_id}.jsonl") | ||
| except ValueError: | ||
| return error_response(ErrorCode.INVALID_PATH, "Invalid path", 400) | ||
|
|
||
| if not os.path.isfile(filepath): | ||
| return error_response( | ||
| ErrorCode.SESSION_NOT_FOUND, | ||
| f"Session {session_id} not found", | ||
| 404, | ||
| ) | ||
|
|
||
| try: | ||
| session = get_cached_session(filepath) | ||
| rules = current_app.config.get("EXCLUSION_RULES") or [] | ||
| if is_session_excluded(rules, session, project_name): | ||
| return error_response( | ||
| ErrorCode.SESSION_NOT_FOUND, | ||
| "Session not found", | ||
| 404, | ||
| ) | ||
| except _PARSE_ERRORS: | ||
| current_app.logger.exception("Failed to parse session %s", session_id) | ||
| return error_response( | ||
| ErrorCode.PARSE_ERROR, | ||
| "Failed to parse session", | ||
| 500, | ||
| ) | ||
|
|
||
| try: | ||
| stats = compute_stats(session) | ||
| return json_response(stats) | ||
| except _PARSE_ERRORS: | ||
| current_app.logger.exception("Failed to compute stats for %s", session_id) | ||
| return error_response( | ||
| ErrorCode.INTERNAL_ERROR, | ||
| "Failed to compute session stats", | ||
| 500, | ||
| loaded = resolve_loaded_session( | ||
| project_name, | ||
| session_id, | ||
| missing_file_message=_missing_session_message, | ||
| ) | ||
| if isinstance(loaded, LoadedSession): | ||
| stats = compute_stats_or_error( | ||
| loaded.session, | ||
| session_id, | ||
| log_action="Failed to compute stats for %s", | ||
| ) | ||
| if isinstance(stats, dict): | ||
| return json_response(stats) | ||
| return stats | ||
| return loaded |
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
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.