jupyter / jupyter_events

Configurable event system for Jupyter applications and extensions.
https://jupyter-events.readthedocs.io/en/latest/
BSD 3-Clause "New" or "Revised" License
12 stars 21 forks source link

Feature request: add modifier API to mutate an event before emitting #11

Closed Zsailer closed 2 years ago

Zsailer commented 2 years ago

The modifier API would provide a hook for extension authors to modify an event in-place before it is validated and emitted.

A modifier would a be callable that would take the raw event data, modify it in-place, and return the modified version.

def modifier(event_data: dict) -> dict:
    ...

The immediate use-case for the modifier API would be to apply "redactors" to the EventLogger that remove properties from the event before they were emitted.

The EventLogger would need a new method to add these modifiers, e.g.

class EventLogger(...):

    ...

    def add_modifier(self, modifier: Callable[[dict], dict]):
        # Adds modifier to list of modifiers
        ...

    def emit(self, ..., data: dict, ...):
        # Should modify the data in-place.
        for modifier in self._modifiers:
            data = modifier(data)

        # Validate after. Ensures that validators return a valid schema to emit.
        self.validate(..., data)

        # Emit the event
        self.emit(...)

The public API would look something like:

def my_redactor(event_data: dict) -> dict:
    # Redact sensitive data.
    if "username" in event_data:
        event_data["username"] = "<masked>"
    return event_data

logger = EventLogger()
logger.add_modifier(my_redactor)
Zsailer commented 2 years ago

Done in #12