Skip to content

d3m.core

DomainName

Bases: str

DomainName class represents a domain name string. It extends the built-in str class and adds validation for domain name format.

Attributes:

Name Type Description
part_of Optional[DomainName]

Gets the parent DomainName of a sub-domain.

Raises:

Type Description
ValueError

If the domain name contains disallowed symbols.

part_of property

Gets the parent DomainName of a sub-domain.

Returns:

Type Description
Optional[DomainName]

The parent DomainName instance or None if it's not a sub-domain.

MessageName

Bases: str

Class representing a message name. It extends the built-in str class and adds validation for message name format.

Raises:

Type Description
ValueError

If the message name contains disallowed symbols.

MessageType

Bases: str, Enum

This class represents different types of message.

Attributes:

Name Type Description
COMMAND MessageType

The command type.

EVENT MessageType

The event type.

MessagebusEvents

Bases: str, Enum

This class representing different events that can occur in a Messagebus.

Attributes:

Name Type Description
BEFORE_RUN str

Event triggered before running the Messagebus.

AFTER_RUN str

Event triggered after running the Messagebus.

BEFORE_STOP str

Event triggered before stopping the Messagebus.

AFTER_STOP str

Event triggered after stopping the Messagebus.

BEFORE_CLOSE str

Event triggered before closing the Messagebus.

AFTER_CLOSE str

Event triggered after closing the Messagebus.

IMessageMeta

Bases: ABCMeta

This class is a metaclass for defining message classes. It is meant to be inherited by a message class definitions.

Attributes:

Name Type Description
__domain_name__ DomainName

The name of the message domain. Should be of type DomainName.

__message_name__ MessageName

The name of the message. Should be of type MessageName.

__type__ MessageType

The type of the message. Should be of type MessageType.

Methods:

Name Description
load

Constructs a new message object.

__domain_name__: DomainName abstractmethod property

Get the domain name of the message.

Returns:

Name Type Description
DomainName DomainName

The name of the message domain.

__message_name__: MessageName abstractmethod property

Get the name of the message.

Returns:

Name Type Description
MessageName MessageName

The name of the message.

__type__: MessageType abstractmethod property

Get the type of the message.

Returns:

Name Type Description
MessageType MessageType

The MessageType of the message.

load(payload, reference=None, timestamp=None) abstractmethod

Constructs a new message object.

Parameters:

Name Type Description Default
payload Union[Mapping, str, bytes]

The payload of the message. Any of a dictionary, json string, or bytes.

required
reference Optional[UUID]

The reference identifier of the message. If not provided, a new UUID will be generated.

None
timestamp Optional[datetime]

The creation timestamp of the message. If not provided, the current time will be used.

None

Returns:

Name Type Description
IMessage IMessage

The newly created message object.

IMessage

Bases: ABC

Metaclass: IMessageMeta

Abstract base class for defining message objects.

Attributes:

Name Type Description
__domain_name__ DomainName

The name of the subject area.

__message_name__ MessageName

The name of the message.

__type__ MessageType

The type of the message.

__reference__ UUID

The identifier of the message.

__timestamp__ datetime

The creation time of the message.

__payload__ dict

The payload of the message.

Methods:

Name Description
load

Constructs a new message object.

to_dict

Returns a JSON serializable dictionary of the payload.

to_json

Returns a JSON string representation of the payload.

__domain_name__: DomainName abstractmethod property

Get the domain name of the message.

Returns:

Name Type Description
DomainName DomainName

The name of the message domain.

__message_name__: MessageName abstractmethod property

Get the name of the message.

Returns:

Name Type Description
MessageName MessageName

The name of the message.

__payload__: dict abstractmethod property

Get the payload of the message Returns: dict: The payload of the message.

__reference__: UUID abstractmethod property

Get the reference of the message.

Returns:

Name Type Description
UUID UUID

The reference of the message.

__timestamp__: dt.datetime abstractmethod property

Get the creation time of the message

Returns:

Type Description
datetime

datetime.datetime: The creation of the message with timezone information.

__type__: MessageType abstractmethod property

Get the type of the message.

Returns:

Name Type Description
MessageType MessageType

The MessageType of the message.

to_dict() abstractmethod

Converts the message's payload to a json-serializable dictionary.

Returns:

Name Type Description
dict dict

A dictionary representation of the message's payload.

to_json() abstractmethod

Converts the message's payload to a json string.

Returns:

Name Type Description
str str

A json string representation of the message's payload.

AbstractCommand

Bases: IMessage, ABC

This class represents an abstract command.

Attributes:

Name Type Description
__domain_name__ DomainName

The name of the subject area.

__message_name__ MessageName

The name of the message.

__type__ MessageType

The type of the message.

__reference__ UUID

The identifier of the message.

__timestamp__ datetime

The creation time of the message.

__payload__ dict

The payload of the message.

Methods:

Name Description
load

Constructs a new message object.

to_dict

Returns a JSON serializable dictionary of the payload.

to_json

Returns a JSON string representation of the payload.

__type__: MessageType property

Get the type of the command.

Returns:

Name Type Description
MessageType MessageType

MessageType.COMMAND.

AbstractEvent

Bases: IMessage, ABC

This class represents an abstract event.

Attributes:

Name Type Description
__domain_name__ DomainName

The name of the subject area.

__message_name__ MessageName

The name of the message.

__type__ MessageType

The type of the message.

__reference__ UUID

The identifier of the message.

__timestamp__ datetime

The creation time of the message.

__payload__ dict

The payload of the message.

Methods:

Name Description
load

Constructs a new message object.

to_dict

Returns a JSON serializable dictionary of the payload.

to_json

Returns a JSON string representation of the payload.

__type__: MessageType property

Get the type of the command.

Returns:

Name Type Description
MessageType MessageType

MessageType.EVENT.

UniversalMessage

Bases: IMessage

A universal class for create domain's messages.

Parameters:

Name Type Description Default
full_message_name str

The full name of the message, including the domain and name.

required
message_type MessageType | str

The type of the message, either as an instance of MessageType or a string representing the type.

required
payload dict

The payload of the message as a dictionary.

required
reference UUID | None

Optional. A UUID representing the reference of the message. If not provided, a new UUID will be generated.

None
timestamp datetime | None

Optional. The timestamp of the message. If not provided, the current time in UTC will be used.

None

Attributes:

Name Type Description
__domain_name__ DomainName

The domain name of the message.

__message_name__ MessageName

The name of the message.

__type__ MessageType

The type of the message.

__reference__ UUID

The reference of the message.

__timestamp__ datetime

The timestamp of the message.

__payload__ dict

The payload of the message.

Methods:

Name Description
to_dict

Returns the payload of the message as a dictionary.

to_json

Returns the payload of the message as a JSON string.

Examples:

Create command

>>> command = UniversalMessage('custom-domain.subdomain.CommandName', 'command', {'arg1': 123})
>>> command
UniversalMessage("custom-domain.subdomain.CommandName", <MessageType.COMMAND: 'COMMAND'>, {'arg1': 123}, UUID('a19019fc-5e55-4b4c-9620-4e1cbf01e73a'), datetime.datetime(2024, 2, 14, 11, 58, 5, 244542, tzinfo=datetime.timezone.utc)))
>>> assert isinstance(event, AbstractCommand)
>>> assert command.__domain_name__ == 'custom-domain.subdomain'
>>> assert command.__message_name__ == 'CommandName'
>>> assert command.__type__ == MessageType.COMMAND
>>> assert command.__payload__ == dict(arg1=123)
>>> assert isinstance(command.__reference__, UUID)
>>> assert isinstance(command.__timestamp__, datetime)
>>> command.to_json()
'{"arg1": 123}'
>>> command.to_dict()
{'arg1': 123}

Create event

>>> event = UniversalMessage('custom-domain.subdomain.EventName', 'event', {'arg': "abc"})
>>> event
UniversalMessage("custom-domain.subdomain.EventName", <MessageType.EVENT: 'EVENT'>, {'arg1': 123}, UUID('a19019fc-5e55-4b4c-9620-4e1cbf01e73a'), datetime.datetime(2024, 2, 14, 11, 58, 5, 244542, tzinfo=datetime.timezone.utc)))
>>> assert isinstance(event, AbstractEvent)
>>> assert event.__domain_name__ == 'custom-domain.subdomain'
>>> assert event.__message_name__ == 'EventName'
>>> assert event.__type__ == MessageType.EVENT
>>> assert event.__payload__ == dict(arg1=123)
>>> assert isinstance(event.__reference__, UUID)
>>> assert isinstance(event.__timestamp__, datetime)
>>> event.to_json()
'{"arg": "abc"}'
>>> event.to_dict()
{'arg': 'abc'}

IDefaultDependency

Bases: ABC

Abstract class for setting default dependencies for domain command handlers.

This class provides a method set_defaults that allows users to set default dependencies for command handlers associated with a specific domain.

set_defaults(__domain, **defaults) abstractmethod

Set defaults dependencies for domain command handlers

Parameters:

Name Type Description Default
__domain DomainName | str
required
**defaults
{}

IHandlersCollection

Bases: IDefaultDependency, ABC

IHandlersCollection is an abstract base class that defines the interface for a collection of message handlers.

Methods:

Name Description
get_command_handler

Get the registered handler for a command.

get_event_handlers

Get the registered handlers for commands caused by an event.

get_command_handler(__command, /, **dependencies) abstractmethod

Get registered command's handler for the command

Parameters:

Name Type Description Default
__command AbstractCommand

domain's command object

required
dependencies

dependencies for command's handler

{}

Returns:

Type Description
Callable[[], Coroutine]

Callable[[], Coroutine]: command's handler.

get_event_handlers(__event, /, **dependencies) abstractmethod

Get registered command's handlers for commands caused to event

Parameters:

Name Type Description Default
__event AbstractEvent

domain's event object

required
dependencies

dependencies for the event's handlers.

{}

Returns:

Type Description
tuple[Callable[[], Coroutine], ...]

event's handlers

IEventsOfMessagebusManager

Bases: ABC

subscribe(*events, listener) abstractmethod

Subscribe a listener to one or more events of messagebus

Parameters:

Name Type Description Default
*events MessagebusEvents

A variable number of MessagebusEvents objects representing the events that the listener will subscribe to.

()
listener Callable[[IMessagebus, MessagebusEvents], Coroutine]

A callable object that takes two arguments: 1. An instance of the IMessagebus interface. 2. A MessagebusEvents object representing the event that occurred. This callable object should return a coroutine.

required

unsubscribe(*events, listener) abstractmethod

Unsubscribe a listener from one or more events.

Parameters:

Name Type Description Default
*events MessagebusEvents

One or more events to unsubscribe the listener from.

()
listener Callable[[IMessagebus, MessagebusEvents], Coroutine]

The listener to unsubscribe from the events.

required

IMessagesPublisher

Bases: ABC

handle_message(message, **dependencies) abstractmethod

Handles a message and returns a future representing the completion of the message handling.

Parameters:

Name Type Description Default
message IMessage

The message to be handled. Must implement the IMessage interface.

required
**dependencies

Additional dependencies required for handling the message.

{}

Returns:

Type Description
Future

asyncio.Future: An asyncio future representing the completion of the message handling.

IMessagebus

Bases: IMessagesPublisher, IEventsOfMessagebusManager, IDefaultDependency, ABC

Represents the interface for a message bus.

Methods:

Name Description
subscribe

Subscribe a listener to one or more events of the message bus.

unsubscribe

Unsubscribe a listener from one or more events of the message bus.

run

Run the message bus.

run_until_complete

Run the message bus until the execution of a specified command.

stop

Stop the message bus.

close

Close the message bus.

is_running

Check if the message bus is running.

is_closed

Check if the message bus is closed.

include_collection

Include a collection of handlers in the message bus.

handle_message

Handle a message and return a future representing the completion of the handling.

get_context

Get the context of the current instance.

set_defaults

Set defaults for the domain's command's handlers.

close() abstractmethod async

Close the messagebus. This method blocked handle any message to messagebus. This method should call before-close and after-close events subscribed listeners.

get_context() abstractmethod

Get the context of the current instance.

Returns:

Name Type Description
Context Context

The context of the current environment.

include_collection(collection) abstractmethod

Include a collection of handlers.

Parameters:

Name Type Description Default
collection IHandlersCollection

An instance of the IHandlersCollection class that contains a collection of handlers.

required

is_closed() abstractmethod

Checks if the messagebus is closed.

Returns:

Name Type Description
bool bool

True if the messagebus is closed, False otherwise.

is_running() abstractmethod

Check if the messagebus is running.

This method returns a boolean value indicating whether the messagebus is currently running.

Returns:

Name Type Description
bool

True if the messagebus is running, False otherwise.

run() abstractmethod async

Run the messagebus. This method calls before-run and after-run events subscribed listeners. This method should be idempotent behaviour.

Raises:

Type Description
RuntimeError

if messagebus is closed.

run_until_complete(command, **dependencies) abstractmethod async

Runs the messagebus until given command's handler execution.

Parameters:

Name Type Description Default
command AbstractCommand

A IMessage object representing the command to be executed.

required
**dependencies Any

Additional dependencies that may be required by the command.

{}

Returns:

Name Type Description
Any Any

The result of the command execution, which may vary depending on the command.

stop() abstractmethod async

Stops the messagebus. This method blocked handle the message to messagebus, exclude the messages generated by current messages handlers. Stops the current operation. This method should call before-stop and after-stop events subscribed listeners. This method should be idempotent call behaviour. This method return after finished all messages handlers.

IMessagebusPolicy

Bases: ABC

This class represents an abstract policy interface for managing messagebus in a system.

Methods:

Name Description
get_messagebus

Get the messagebus for the current context.

set_messagebus

Set the messagebus for the current context.

new_messagebus

Create and return a new messagebus object, according to this policy's rules.

get_messagebus() abstractmethod

Get or create a messagebus for current context.

Returns:

Name Type Description
IMessagebus IMessagebus

The messagebus for current context

new_messagebus() abstractmethod

Create and return a new messagebus object according to this policy's rules. If there's need to set this messagebus as the messagebus for the current context, set_messagebus must be called explicitly.

Returns:

Name Type Description
IMessagebus IMessagebus

The new messagebus instance

set_messagebus(messagebus) abstractmethod

Set the messagebus for the current context.

Parameters:

Name Type Description Default
messagebus IMessagebus | None

The messagebus for set to current context.

required

IEntity

Bases: ABC, Generic[_ReferenceType]

Abstract base class for all entity classes.

Attributes:

Name Type Description
__reference__ _ReferenceType

Property that represents the reference of the entity.

__reference__: _ReferenceType abstractmethod property

Property that represents the reference of the entity.

Returns:

Type Description
_ReferenceType

entity reference

IRootEntity

Bases: IEntity[_ReferenceType], ABC, Generic[_ReferenceType]

This class represents an abstract root entity in a domain-driven design architecture. It is a base class for all root entities in the domain.

Attributes:

Name Type Description
__reference__ _ReferenceType

Property that represents the reference of the root entity.

__version__ Version

Property that represents the version of the root entity.

__domain_name__ DomainName

Property that represents the domain name of the root entity.

Methods:

Name Description
collect_events

Collects domain events from the root entity and removes them after the call.

__domain_name__: DomainName abstractmethod property

Represents the domain name of the root entity.

Returns:

Name Type Description
DomainName DomainName

entity domain

__version__: Version abstractmethod property

Property that represents the version of the root entity.

Returns:

Name Type Description
Version Version

root entity version

collect_events() abstractmethod

Collects domain events from the root entity and removes them after the call.

Returns:

Type Description
Iterable[AbstractEvent]

Iterable[IMessage]: domain events

get_messagebus()

Returns the current IMessagebus instance.

If there is a running IMessagebus instance, it returns that instance. Otherwise, it retrieves the IMessagebus instance using the get_messagebus method from the message bus policy.

Returns:

Name Type Description
IMessagebus IMessagebus

The current IMessagebus instance.

get_running_messagebus()

Returns the running instance of the messagebus.

Returns:

Name Type Description
IMessagebus IMessagebus

The running instance of the messagebus.

Raises:

Type Description
RuntimeError

If there is no running messagebus instance.

new_messagebus()

Returns a new instance of the MessageBus class.

This method retrieves the message bus policy using the get_messagebus_policy() function, and calls the new_messagebus() method of the policy to create a new message bus instance.

Returns:

Name Type Description
IMessagebus

A new instance of the MessageBus class.

set_messagebus(messagebus)

Set the messagebus for the messagebus policy.

Parameters:

Name Type Description Default
messagebus IMessagebus

The message bus object to set.

required

get_messagebus_policy()

Retrieves the messagebus policy.

If the message bus policy is not initialized, it will be initialized first.

Returns:

Name Type Description
IMessagebusPolicy IMessagebusPolicy

The messagebus policy.

set_messagebus_policy(policy)

Set the messagebus policy.

Parameters:

Name Type Description Default
policy IMessagebusPolicy | None

If None, no policy will be set. Otherwise, the specified policy will be set as the messagebus policy.

required

Raises:

Type Description
TypeError

If policy is not an instance of IMessagebusPolicy or None.