|
17 | 17 | This module provides helper functions for common proto type operations. |
18 | 18 | """ |
19 | 19 |
|
20 | | -from typing import TYPE_CHECKING, Any |
| 20 | +from typing import TYPE_CHECKING, Any, TypedDict |
21 | 21 |
|
| 22 | +from google.api.field_behavior_pb2 import FieldBehavior, field_behavior |
| 23 | +from google.protobuf.descriptor import FieldDescriptor |
22 | 24 | from google.protobuf.json_format import ParseDict |
23 | 25 | from google.protobuf.message import Message as ProtobufMessage |
24 | 26 |
|
| 27 | +from a2a.utils.errors import InvalidParamsError |
| 28 | + |
25 | 29 |
|
26 | 30 | if TYPE_CHECKING: |
27 | 31 | from starlette.datastructures import QueryParams |
@@ -189,3 +193,106 @@ def parse_params(params: QueryParams, message: ProtobufMessage) -> None: |
189 | 193 | processed[k] = parsed_val |
190 | 194 |
|
191 | 195 | ParseDict(processed, message, ignore_unknown_fields=True) |
| 196 | + |
| 197 | + |
| 198 | +class ValidationDetail(TypedDict): |
| 199 | + """Structured validation error detail.""" |
| 200 | + |
| 201 | + field: str |
| 202 | + message: str |
| 203 | + |
| 204 | + |
| 205 | +def _check_required_field_violation( |
| 206 | + msg: ProtobufMessage, field: FieldDescriptor |
| 207 | +) -> ValidationDetail | None: |
| 208 | + """Check if a required field is missing or invalid.""" |
| 209 | + val = getattr(msg, field.name) |
| 210 | + if field.is_repeated: |
| 211 | + if not val: |
| 212 | + return ValidationDetail( |
| 213 | + field=field.name, |
| 214 | + message='Field must contain at least one element.', |
| 215 | + ) |
| 216 | + elif field.has_presence: |
| 217 | + if not msg.HasField(field.name): |
| 218 | + return ValidationDetail( |
| 219 | + field=field.name, message='Field is required.' |
| 220 | + ) |
| 221 | + elif val == field.default_value: |
| 222 | + return ValidationDetail(field=field.name, message='Field is required.') |
| 223 | + return None |
| 224 | + |
| 225 | + |
| 226 | +def _append_nested_errors( |
| 227 | + errors: list[ValidationDetail], |
| 228 | + prefix: str, |
| 229 | + sub_errs: list[ValidationDetail], |
| 230 | +) -> None: |
| 231 | + """Format nested validation errors and append to errors list.""" |
| 232 | + for sub in sub_errs: |
| 233 | + sub_field = sub['field'] |
| 234 | + errors.append( |
| 235 | + ValidationDetail( |
| 236 | + field=f'{prefix}.{sub_field}' if sub_field else prefix, |
| 237 | + message=sub['message'], |
| 238 | + ) |
| 239 | + ) |
| 240 | + |
| 241 | + |
| 242 | +def _recurse_validation( |
| 243 | + msg: ProtobufMessage, field: FieldDescriptor |
| 244 | +) -> list[ValidationDetail]: |
| 245 | + """Recurse validation for nested messages and map fields.""" |
| 246 | + errors: list[ValidationDetail] = [] |
| 247 | + if field.type != FieldDescriptor.TYPE_MESSAGE: |
| 248 | + return errors |
| 249 | + |
| 250 | + val = getattr(msg, field.name) |
| 251 | + if not field.is_repeated: |
| 252 | + if msg.HasField(field.name): |
| 253 | + sub_errs = _validate_proto_required_fields_internal(val) |
| 254 | + _append_nested_errors(errors, field.name, sub_errs) |
| 255 | + elif field.message_type.GetOptions().map_entry: |
| 256 | + for k, v in val.items(): |
| 257 | + if isinstance(v, ProtobufMessage): |
| 258 | + sub_errs = _validate_proto_required_fields_internal(v) |
| 259 | + _append_nested_errors(errors, f'{field.name}[{k}]', sub_errs) |
| 260 | + else: |
| 261 | + for i, item in enumerate(val): |
| 262 | + sub_errs = _validate_proto_required_fields_internal(item) |
| 263 | + _append_nested_errors(errors, f'{field.name}[{i}]', sub_errs) |
| 264 | + return errors |
| 265 | + |
| 266 | + |
| 267 | +def _validate_proto_required_fields_internal( |
| 268 | + msg: ProtobufMessage, |
| 269 | +) -> list[ValidationDetail]: |
| 270 | + """Internal validation that returns a list of error dictionaries.""" |
| 271 | + desc = msg.DESCRIPTOR |
| 272 | + errors: list[ValidationDetail] = [] |
| 273 | + |
| 274 | + for field in desc.fields: |
| 275 | + options = field.GetOptions() |
| 276 | + if FieldBehavior.REQUIRED in options.Extensions[field_behavior]: |
| 277 | + violation = _check_required_field_violation(msg, field) |
| 278 | + if violation: |
| 279 | + errors.append(violation) |
| 280 | + errors.extend(_recurse_validation(msg, field)) |
| 281 | + return errors |
| 282 | + |
| 283 | + |
| 284 | +def validate_proto_required_fields(msg: ProtobufMessage) -> None: |
| 285 | + """Validate that all fields marked as REQUIRED are present on the proto message. |
| 286 | +
|
| 287 | + Args: |
| 288 | + msg: The Protobuf message to validate. |
| 289 | +
|
| 290 | + Raises: |
| 291 | + InvalidParamsError: If a required field is missing or empty. |
| 292 | + """ |
| 293 | + errors = _validate_proto_required_fields_internal(msg) |
| 294 | + |
| 295 | + if errors: |
| 296 | + raise InvalidParamsError( |
| 297 | + message='Validation failed', data={'errors': errors} |
| 298 | + ) |
0 commit comments