You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

trace_id_helper.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import re
  2. from collections.abc import Mapping
  3. from typing import Any, Optional
  4. def is_valid_trace_id(trace_id: str) -> bool:
  5. """
  6. Check if the trace_id is valid.
  7. Requirements: 1-128 characters, only letters, numbers, '-', and '_'.
  8. """
  9. return bool(re.match(r"^[a-zA-Z0-9\-_]{1,128}$", trace_id))
  10. def get_external_trace_id(request: Any) -> Optional[str]:
  11. """
  12. Retrieve the trace_id from the request.
  13. Priority: header ('X-Trace-Id'), then parameters, then JSON body. Returns None if not provided or invalid.
  14. """
  15. trace_id = request.headers.get("X-Trace-Id")
  16. if not trace_id:
  17. trace_id = request.args.get("trace_id")
  18. if not trace_id and getattr(request, "is_json", False):
  19. json_data = getattr(request, "json", None)
  20. if json_data:
  21. trace_id = json_data.get("trace_id")
  22. if isinstance(trace_id, str) and is_valid_trace_id(trace_id):
  23. return trace_id
  24. return None
  25. def extract_external_trace_id_from_args(args: Mapping[str, Any]) -> dict:
  26. """
  27. Extract 'external_trace_id' from args.
  28. Returns a dict suitable for use in extras. Returns an empty dict if not found.
  29. """
  30. trace_id = args.get("external_trace_id")
  31. if trace_id:
  32. return {"external_trace_id": trace_id}
  33. return {}