event
/event
Definiuje zdarzenie domenowe w Protean, czyli niezmienny fakt o zmianie stanu agregatu, nazwany w czasie przeszłym.
- Autor
- proteanhq ↗
- Repozytorium
- protean ↗
- Licencja
- Apache-2.0
- Ostatnia zmiana repozytorium
- 11.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 14
- Skrypty
- 7
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 1
Brak sygnałów. Repozytorium zmienione 11.11.2026, bez odwołań do wycofanych modeli i API.
Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.
- 7 skryptów w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.
Skrypty: __init__.py, assets/__init__.py, assets/event_fact.py, assets/event_simple.py, assets/event_versioning.py, assets/event_with_value_object.py, assets/raising_events.py
Co robi i kiedy
Definiuje zdarzenie domenowe w Protean, czyli niezmienny fakt o zmianie stanu agregatu, nazwany w czasie przeszłym.
Wyzwalacze z opisu
Oryginalny opis (EN)
Define a Protean domain event, an immutable fact representing a state change in the business domain. Events capture meaningful changes to aggregates and enable decoupled communication between system components. Events are always associated with aggregates and are named in past-tense (OrderPlaced, CustomerRegistered). Use when you need to record what happened in your domain, when you want to communicate state changes to other parts of the system, when the user asks to "create an event", "define a domain event", "add an event", when implementing event sourcing or CQRS patterns, or when they desc
Jak działa
- Basic structure
- Key rules
- Event types
- Fields and versioning
- Raising events from aggregates
- Common mistakes
- Detailed references
- Verify your work
Podgląd SKILL.md
---
name: event
description: Define a Protean domain event, an immutable fact representing a state change in the business domain. Events capture meaningful changes to aggregates and enable decoupled communication between system components. Events are always associated with aggregates and are named in past-tense (OrderPlaced, CustomerRegistered). Use when you need to record what happened in your domain, when you want to communicate state changes to other parts of the system, when the user asks to "create an event", "define a domain event", "add an event", when implementing event sourcing or CQRS patterns, or when they describe something that occurred (like "order was placed", "payment confirmed", "inventory depleted"). Events can be delta events (incremental changes) or fact events (complete state snapshots).
license: Apache-2.0
compatibility: Requires Python 3.11+, protean framework
metadata:
author: proteanhq
version: "0.1"
category: element
diagnostic_codes:
- EVENT_NOT_PAST_TENSE
- EVENT_WITHOUT_DATA
- UNRAISED_EVENT
- UNHANDLED_EVENT
---
# Event
An event records a change that has happened to one aggregate, so other parts of the system can react to it. This skill defines events: fields, versioning, and how aggregates raise them.
## Basic structure
An event is defined using the `@domain.event(part_of="...")` decorator:
```python
from protean import Domain
from protean.fields import String, DateTime
domain = Domain()
@domain.event(part_of="Order")
class OrderPlaced:
__version__ = 1
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
placed_at: DateTime(required=True)
```
## Key rules
1. **Events must be associated with aggregates**: Always specify `part_of` parameter with the aggregate name. A process manager's own events name the process manager. Never name an entity: an entity raises its events through the aggregate
2. **Events are named in past-tense**: Use past-tense verbs: `OrderPlaced`, not `PlaceOrder`
3. **Events are immutable**: Once created, events cannot be modified (they are facts)
4. **Events are DTOs**: Can contain simple fields and value objects, but NOT entities or aggregates
5. **Events should be lightweight**: Include only data necessary to describe what happened
6. **Events are versioned**: Use `__version__` class attribute for schema evolution (defaults to `1`)
7. **Events have metadata**: Protean automatically adds timestamps, unique IDs, and versioning
8. **Events are raised from aggregates**: Use `self.raise_()` method within aggregate methods
9. **Events are persisted to streams**: Events are written to aggregate-specific streams
10. **Events enable decoupling**: Other components react to events via event handlers
## Event types
### Delta Events
Delta events capture incremental changes to aggregate state. Most events are delta events.
```python
@domain.event(part_of="Order")
class OrderPlaced:
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
total_amount: Decimal(precision=19, scale=4, required=True)
```
### Fact Events
Fact events contain complete aggregate state at a point in time (Event-carried State Transfer pattern). You do not write a fact event class. Turn them on with `fact_events=True`, and Protean generates an `<Aggregate>FactEvent` class from the aggregate's fields. For `Order`, the class is `OrderFactEvent`.
```python
@domain.aggregate(fact_events=True)
class Order:
customer_id: String(required=True)
status: String(default="draft")
```
The repository writes a fact event each time it saves a new or changed aggregate. Saving an unchanged aggregate writes none. The event goes to the `<stream_category>-fact-<id>` stream. Your code never raises it: the repository raises it on the aggregate as it saves, and the unit of work stores it on commit.
```python
domain.init(traverse=False)
with domain.domain_context():
order = Order(customer_id="CUST-123")
domain.repository_for(Order).add(order)
stream = f"{Order.meta_.stream_category}-fact-{order.id}"
fact = domain.event_store.store.read_last_message(stream).to_domain_object()
print(type(fact).__name__) # OrderFactEvent
print(fact.id == order.id, fact.customer_id, fact.status) # True CUST-123 draft
```
## Fields and versioning
### With Value Objects
Events can contain value objects for complex immutable data:
```python
@domain.value_object
class Money:
amount: Decimal(precision=19, scale=4, required=True)
currency: String(max_length=3, default="USD")
@domain.event(part_of="Order")
class OrderPlaced:
__version__ = 1
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
total = ValueObject(Money, required=True)
placed_at: DateTime(required=True)
```
### Event Versioning
Use `__version__` for schema evolution:
```python
@domain.event(part_of="Order")
class OrderPlaced:
__version__ = 1
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
# Later, when schema evolves
@domain.event(part_of="Order")
class OrderPlaced:
__version__ = 2
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
total = ValueObject(Money) # New field in v2
```
## Raising events from aggregates
Events are raised within aggregate methods using `self.raise_()`:
```python
from datetime import datetime, timezone
@domain.aggregate
class Order:
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
status: String(default="draft")
total = ValueObject(Money)
def place(self):
if self.status != "draft":
raise ValueError("Order already placed")
self.status = "placed"
placed_at = datetime.now(timezone.utc)
# Raise event - automatically associated with this aggregate instance
self.raise_(OrderPlaced(
order_id=self.order_id,
customer_id=self.customer_id,
total=self.total,
placed_at=placed_at
))
```
This aggregate stores its state, so the method changes the state first and then raises the event. An event-sourced aggregate works the other way. The business method raises the event, and an `@apply` method changes the state. See the `event-sourced-aggregate` skill.
## Common mistakes
### ❌ Including entities in events
```python
# fragment
@domain.event(part_of="Order")
class OrderPlaced:
order_entity = HasOne(OrderEntity) # Wrong! Events can't contain entities
```
✅ **Instead: Only fields and value objects**, as in [With Value Objects](#with-value-objects).
### ❌ Including too much unnecessary data
```python
@domain.event(part_of="Order")
class OrderPlaced:
# Including entire customer object when only ID is needed
customer_name: String()
customer_email: String()
customer_address: String()
customer_phone: String()
```
✅ **Instead: Only necessary information**
```python
@domain.event(part_of="Order")
class OrderPlaced:
customer_id: String(required=True) # Just the ID
```
### ❌ Making events mutable
```python
# fragment
event = OrderPlaced(order_id="123", customer_id="456")
event.order_id = "789" # Wrong! Events are immutable
```
✅ **Instead: Events are immutable facts**
Assigning to a field of an event raises `IncorrectUsageError`. To record a different fact, raise a new event.
```python
from protean.exceptions import IncorrectUsageError
@domain.event(part_of="Order")
class OrderPlaced:
order_id: String(required=True, identifier=True)
customer_id: String(required=True)
domain.init(traverse=False)
with domain.domain_context():
event = OrderPlaced(order_id="123", customer_id="456")
try:
event.order_id = "789"
except IncorrectUsageError as exc:
print(exc) # Event/Command Objects are immutable and cannot be modified once created
```
### What `check` reports
`check` inspects your events and reports these diagnostics:
- `EVENT_NOT_PAST_TENSE`: the event is named as a gerund (`OrderPlacing`), so it describes an in-flight action and reads like a command. Rename it to the past tense (`OrderPlaced`).
- `EVENT_WITHOUT_DATA`: the event declares no fields, so it carries nothing about the state change. Add fields capturing what changed, or confirm the event is intentionally a bare signal.
- `UNRAISED_EVENT`: no aggregate or entity method raises the event. The check reads only aggregate and entity method bodies, so an event raised from a command handler, subscriber, or module-level factory still shows here. Raise it from the aggregate or entity method that makes the change it records, or remove the event if nothing produces it.
- `UNHANDLED_EVENT`: the event has no registered handler, projector, or process manager, so nothing reacts to it. Register a consumer for it, or mark it `published=True` if it is meant only for external subscribers.
## Detailed references
### Core Concepts
- [Delta Events](references/delta-events.md): Incremental state changes
- [Fact Events](references/fact-events.md): Complete state snapshots (Event-carried State Transfer)
- [Events with Value Objects](references/with-value-objects.md): Using value objects in events
- [Event Versioning](references/event-versioning.md): Schema evolution and version management
- [Raising Events](references/raising-events.md): How to raise events from aggregates
- [Anti-patterns](references/anti-patterns.md): Common mistakes and how to avoid them
### Complete Examples
- [Simple Delta Event](assets/event_simple.py): Basic event with minimal fields
- [Event with Value Objects](assets/event_with_value_object.py): Events containing value objects
- [Fact Event](assets/event_fact.py): Fact events generated with `fact_events=True`
- [Event Versioning](assets/event_versioning.py): Schema evolution examples
- [Raising Events](assets/raising_events.py): Complete example with aggregate raising events
### Related Skills
- `aggregate`: Events are always part of aggregates
- `value-object`: Events can contain value objects
- `event-handler`: How events are consumed and processed
- `event-sourced-aggregate`: Using events as the source of truth
- [CQRS](https://docs.proteanhq.com/concepts/architecture/cqrs/): Using events for read model updates
## Verify your work
- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Pliki w paczce (14)
- SKILL.md 10 KB
- __init__.py 1 KB
- assets/__init__.py 1 KB
- assets/event_fact.py 6 KB
- assets/event_simple.py 3 KB
- assets/event_versioning.py 8 KB
- assets/event_with_value_object.py 5 KB
- assets/raising_events.py 10 KB
- references/anti-patterns.md 9 KB
- references/delta-events.md 2 KB
- references/event-versioning.md 9 KB
- references/fact-events.md 7 KB
- references/raising-events.md 9 KB
- references/with-value-objects.md 6 KB
Wersje
| Repozytorium | Wynik | Licencja |
|---|---|---|
| Ta strona · proteanhq/protean | 100 | Apache-2.0 |
| proteanhq/protean | 100 | Apache-2.0 |
Migawka bazy z 13.11.2026 · wersja paczki f1ec27e8f5f7 (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100command
Definiuje komendę w Protean jako niezmienny obiekt DTO, wyrażający zamiar zmiany stanu agregatu i przetwarzany przez obsługę komend. - 100command
Definiuje komendę Protean, niezmienny DTO opisujący zamiar zmiany stanu agregatu, nazywany czasownikiem w trybie rozkazującym (PlaceOrder, RegisterUser, CancelReservation). - 100domain-driven-design
Pomaga modelować domenę biznesową i strukturyzować backend wokół reguł biznesowych: agregaty, encje, value objects, zdarzenia domenowe, repozytoria, CQRS, event sourcing, konteksty ograniczone i architektura heksagonalna. - 100cqrs-event-sourcing-patterns
Rozdziela modele odczytu i zapisu danych oraz zapisuje stany encji jako niezmienne strumienie zdarzeń w architekturze CQRS i event sourcing. - 100ddd
Opisuje wzorce Domain-Driven Design: konteksty ograniczone, agregaty, encje, obiekty wartości, zdarzenia domenowe, repozytoria i serwisy aplikacyjne w strategicznym oraz taktycznym ujęciu. - 90event-sourcing-architect
Projektuje systemy oparte na event sourcingu z CQRS, magazynami zdarzeń, projekcjami i wzorcami spójności ostatecznej.