schema_registry.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """"An event schema registry."""
  2. from __future__ import annotations
  3. from typing import Any
  4. from .schema import EventSchema
  5. class SchemaRegistryException(Exception):
  6. """Exception class for Jupyter Events Schema Registry Errors."""
  7. class SchemaRegistry:
  8. """A convenient API for storing and searching a group of schemas."""
  9. def __init__(self, schemas: dict[str, EventSchema] | None = None):
  10. """Initialize the registry."""
  11. self._schemas: dict[str, EventSchema] = schemas or {}
  12. def __contains__(self, key: str) -> bool:
  13. """Syntax sugar to check if a schema is found in the registry"""
  14. return key in self._schemas
  15. def __repr__(self) -> str:
  16. """The str repr of the registry."""
  17. return ",\n".join([str(s) for s in self._schemas.values()])
  18. def _add(self, schema_obj: EventSchema) -> None:
  19. if schema_obj.id in self._schemas:
  20. msg = (
  21. f"The schema, {schema_obj.id}, is already "
  22. "registered. Try removing it and registering it again."
  23. )
  24. raise SchemaRegistryException(msg)
  25. self._schemas[schema_obj.id] = schema_obj
  26. @property
  27. def schema_ids(self) -> list[str]:
  28. return list(self._schemas.keys())
  29. def register(self, schema: dict[str, Any] | (str | EventSchema)) -> EventSchema:
  30. """Add a valid schema to the registry.
  31. All schemas are validated against the Jupyter Events meta-schema
  32. found here:
  33. """
  34. if not isinstance(schema, EventSchema):
  35. schema = EventSchema(schema)
  36. self._add(schema)
  37. return schema
  38. def get(self, id_: str) -> EventSchema:
  39. """Fetch a given schema. If the schema is not found,
  40. this will raise a KeyError.
  41. """
  42. try:
  43. return self._schemas[id_]
  44. except KeyError:
  45. msg = (
  46. f"The requested schema, {id_}, was not found in the "
  47. "schema registry. Are you sure it was previously registered?"
  48. )
  49. raise KeyError(msg) from None
  50. def remove(self, id_: str) -> None:
  51. """Remove a given schema. If the schema is not found,
  52. this will raise a KeyError.
  53. """
  54. try:
  55. del self._schemas[id_]
  56. except KeyError:
  57. msg = (
  58. f"The requested schema, {id_}, was not found in the "
  59. "schema registry. Are you sure it was previously registered?"
  60. )
  61. raise KeyError(msg) from None
  62. def validate_event(self, id_: str, data: dict[str, Any]) -> None:
  63. """Validate an event against a schema within this
  64. registry.
  65. """
  66. schema = self.get(id_)
  67. schema.validate(data)