Sincpro framework to use DDD, Clean architecture, Hexagonal architecture
Project description
๐ Sincpro Framework: Application Layer Framework within Hexagonal Architecture
โก Quick Start
Here's a quick example to get you started with the Sincpro Framework:
๐ Quick Example
from sincpro_framework import UseFramework, Feature, DataTransferObject
# 1. Initialize the framework
framework = UseFramework(logger_name="cybersource")
# 2. Add Dependencies (Example dependencies)
from sincpro_framework import Database
db = Database()
framework.add_dependency("db", db)
# 3. Error Handler (Optional, use the built-in error handling feature)
framework.set_global_error_handler(lambda e: print(f"Error: {e}"))
# 4. Create a Use Case with DTOs
class GreetingParams(DataTransferObject):
name: str
@framework.feature(GreetingParams)
class GreetingFeature(Feature):
def execute(self, dto: GreetingParams) -> str:
self.db.store(f"Greeting {dto.name}")
return f"Hello, {dto.name}!"
# 5. Execute the Use Case
if __name__ == "__main__":
# Create an instance of the parameter DTO
greeting_dto = GreetingParams(name="Alice")
# Execute the feature
result = framework(greeting_dto)
print(result) # Output: Hello, Alice!
Now you are ready to explore more complex use cases! ๐
๐ Table of Contents
- Overview of Hexagonal Architecture
- Key Features of the Sincpro Framework
- Features vs. Application Service
- Example Usage for a Payment Gateway
- Creating a Feature
- Creating an Application Service
- Executing a Use Case
- Summary
- Configuration or settings
- Variables
๐ Overview of Hexagonal Architecture
Hexagonal Architecture, also known as Ports and Adapters, is an architectural approach that aims to decouple core business logic from external dependencies. It organizes the system into distinct layers: domain, application, and infrastructure, enhancing maintainability, scalability, and adaptability.
๐๏ธ Key Layers of Hexagonal Architecture
- Core Domain: This layer encapsulates essential entities, value objects, and domain services representing the core business rules and behaviors. It is kept strictly independent from infrastructure concerns, preserving business logic integrity.
- Application Layer: Orchestrates user requests, processes domain responses, and mediates interactions between domain and external systems to ensure effective workflow execution.
- Infrastructure Layer: Contains adapters for interacting with databases, APIs, messaging systems, and other services. It handles data transformation to ensure compatibility with the domain and application layers.
๐ค Why Use a Unified Bus Pattern?
The Sincpro Framework adopts a unified bus pattern as a single point of entry for managing use cases, dependencies, and services within a bounded context. This simplifies the architecture by encapsulating all requirements of a given context, ensuring a clear and consistent structure.
Using a unified bus allows developers to access all dependencies through a single environment, eliminating the need for repeated imports or initialization. This approach ensures each bounded context is self-sufficient, independently scalable, and minimizes coupling while enhancing modularity.
๐ Key Features of the Sincpro Framework
The Sincpro Framework follows hexagonal architecture principles, promoting modularity, scalability, and development efficiency. Here are its core features:
โ DTO Validation with Pydantic
- Utilizes Pydantic to validate Data Transfer Objects (DTOs).
- Ensures only well-structured data is allowed into core business logic, reducing errors and maintaining data integrity.
๐งฉ Dependency Injection
- Facilitates integration of user-defined dependencies, promoting modular design.
- Enhances unit testing by allowing easy mocking or replacement of dependencies.
๐ Inversion of Control (IoC)
- Automates the instantiation and configuration of components, reducing boilerplate code.
- Encourages loose coupling, making systems more adaptable and maintainable.
โ ๏ธ Error Handling at Different Levels
- Provides centralized error handling at multiple levels: global, Service Application, and Feature levels.
- Ensures consistent error management, improving overall reliability.
๐ Bus Pattern for Component Communication
- Implements a bus mechanism to facilitate communication between Feature and ApplicationService components.
- Decouples component interactions, resulting in more flexible and scalable business logic.
๐งฉ Decoupled Logic Execution
- Supports independent execution of use cases through the Feature component, promoting separation of concerns.
- For example, a user registration workflow can be broken down into steps like input validation, profile creation, and email notification.
๐ป Application Service Orchestration
- Uses a feature bus to orchestrate multiple features into complex business workflows (e.g., customer onboarding).
- Integrates smaller use cases into cohesive flows to manage entire business processes effectively.
๐ป IDE Support with Typing
- Uses type hints to enhance code quality and support features like autocompletion and type checking.
- Improves development efficiency and reliability.
โ๏ธ Features vs. Application Service
- Feature: Represents a discrete, self-contained use case focused on specific functionality, easy to develop and maintain.
- ApplicationService: Orchestrates multiple features for broader business objectives, providing reusable components and workflows.
๐ณ Example Usage for a Payment Gateway
The following example shows how to configure the Sincpro Framework for a payment gateway integration, such as CyberSource. It is recommended to name the framework instance to clearly represent the bounded context it serves.
๐ง Configuring the Framework
To set up the Sincpro Framework, configuration should be performed at the application layer within the use_cases
directory of each bounded context.
sincpro_payments_sdk/
โโโ pyproject.toml
โโโ README.md
โโโ apps/
โ โโโ cybersource/
โ โ โโโ adapters/
โ โ โ โโโ cybersource_rest_api_adapter.py
โ โ โ โโโ __init__.py
โ โ โโโ domain/
โ โ โ โโโ card.py
โ โ โ โโโ customer.py
โ โ โ โโโ __init__.py
โ โ โโโ infrastructure/
โ โ โ โโโ logger.py
โ โ โ โโโ aws_services.py
โ โ โ โโโ orm.py
โ โ โ โโโ __init__.py
โ โ โโโ use_cases/
โ โ โโโ tokenization/
โ โ โ โโโ new_tokenization_feature.py
โ โ โ โโโ __init__.py
โ โ โโโ payments/
โ โ โ โโโ token_and_payment_service.py
โ โ โ โโโ __init__.py
โ โ โโโ __init__.py
โ โโโ qr/
โ โโโ sms_payment/
โ โโโ bank_api/
โ โโโ online_payment_gateway/
โ โโโ paypal_integration/
โโโ tests
๐ Best Practices for Imports
Each use case should import both the DTO for input parameters and the DTO for responses to maintain clarity and consistency.
๐ Sample Configuration in __init__.py
from typing import Type
from sincpro_framework import Feature as _Feature
from sincpro_framework import UseFramework as _UseFramework
from sincpro_framework import ApplicationService as _ApplicationService
from sincpro_payments_sdk.apps.cybersource.adapters.cybersource_rest_api_adapter import (
ESupportedCardType,
TokenizationAdapter,
)
from sincpro_payments_sdk.infrastructure.orm import with_transaction as db_session
from sincpro_payments_sdk.infrastructure.aws_services import AwsService as aws_service
# Create an instance of the framework
cybersource = _UseFramework()
# Register dependencies
cybersource.add_dependency("token_adapter", TokenizationAdapter())
cybersource.add_dependency("ECardType", ESupportedCardType)
cybersource.add_dependency("db_session", db_session)
cybersource.add_dependency("aws_service", aws_service)
# Define a custom Feature class to access the dependencies
class Feature(_Feature):
token_adapter: TokenizationAdapter
ECardType: Type[ESupportedCardType]
db_session: ...
aws_service: ...
logger: ...
# Define a custom Application Service class to access dependencies
class ApplicationService(_ApplicationService):
token_adapter: TokenizationAdapter
ECardType: Type[ESupportedCardType]
db_session: ...
aws_service: ...
logger: ...
feature_bus: ...
# Add use cases (Application Services and Features)
from . import tokenization
__all__ = ["cybersource", "tokenization", "Feature"]
๐ ๏ธ Creating a Feature
To create a new Feature, follow these steps:
- Create a Module for the Feature: Add a new Python file in the appropriate folder under
use_cases. - Import the Framework and Required Classes: Import the configured framework instance and
DataTransferObject. - Define the Parameter and Response DTOs: Use
DataTransferObjectto create classes for input parameters and responses. - Create the Feature Class: Define the
Featureclass by inheriting from the customFeatureclass.
๐๏ธ Example of Creating a Feature
from sincpro_payments_sdk.apps.cybersource import cybersource, DataTransferObject, Feature
# Define parameter DTO
class TokenizationParams(DataTransferObject):
card_number: str
expiration_date: str
cardholder_name: str
# Define response DTO
class TokenizationResponse(DataTransferObject):
token: str
status: str
# Create the Feature class
@cybersource.feature(TokenizationParams)
class NewTokenizationFeature(Feature):
def execute(self, dto: TokenizationParams) -> TokenizationResponse:
# Example usage of dependencies
cybersource.logger.info("Starting tokenization process")
token = self.token_adapter.create_token(
card_number=dto.card_number,
expiration_date=dto.expiration_date,
cardholder_name=dto.cardholder_name
)
return TokenizationResponse(token=token, status="success")
๐ Creating an Application Service
ApplicationService is used to coordinate multiple features while maintaining reusability and consistency. It orchestrates features into cohesive workflows.
๐ก Example of Creating an Application Service
from sincpro_payments_sdk.apps.cybersource import cybersource, DataTransferObject, ApplicationService
from sincpro_payments_sdk.apps.cybersource.use_cases.tokenization import TokenizationParams
# Define parameter DTO
class PaymentServiceParams(DataTransferObject):
card_number: str
expiration_date: str
cardholder_name: str
amount: float
# Define response DTO
class PaymentServiceResponse(DataTransferObject):
status: str
transaction_id: str
# Create the Application Service class
@cybersource.app_service(PaymentServiceParams)
class PaymentOrchestrationService(ApplicationService):
def execute(self, dto: PaymentServiceParams) -> PaymentServiceResponse:
# Create the command DTO for tokenization
tokenization_command = TokenizationParams(
card_number=dto.card_number,
expiration_date=dto.expiration_date,
cardholder_name=dto.cardholder_name
)
tokenization_result = self.feature_bus.execute(tokenization_command)
# Example usage of dependencies
cybersource.logger.info("Proceeding with payment after tokenization")
# Proceed with payment using the token (pseudo code for payment processing)
transaction_id = "12345" # Simulated transaction ID
return PaymentServiceResponse(status="success", transaction_id=transaction_id)
โ๏ธ Executing a Use Case
Once a Feature or ApplicationService is defined, it can be executed by passing the appropriate DTO instance.
๐ Example of Executing a Use Case
from sincpro_payments_sdk.apps.cybersource import cybersource
from sincpro_payments_sdk.apps.cybersource.use_cases.tokenization import TokenizationParams
from sincpro_payments_sdk.apps.cybersource.use_cases.payments import PaymentServiceParams
# Example of executing a Feature
feature_dto = TokenizationParams(
card_number="4111111111111111",
expiration_date="12/25",
cardholder_name="John Doe"
)
# Execute the feature
feature_result = cybersource.feature_bus.execute(feature_dto)
print(f"Tokenization Result: {feature_result.token}, Status: {feature_result.status}")
# Example of executing an Application Service
service_dto = PaymentServiceParams(
card_number="4111111111111111",
expiration_date="12/25",
cardholder_name="John Doe",
amount=100.00
)
# Execute the application service
service_result = cybersource(service_dto)
print(f"Payment Status: {service_result.status}, Transaction ID: {service_result.transaction_id}")
๐ Summary
The Sincpro Framework provides a robust solution for managing the application layer within a hexagonal architecture. By focusing on decoupling business logic from external dependencies, the framework promotes modularity, scalability, and maintainability.
- Features: Handle specific, self-contained business actions.
- ApplicationServices: Orchestrate multiple features for cohesive workflows.
This structured approach ensures high-quality, maintainable software that can adapt to evolving business needs. ๐
Configuration or settings
The framework comes with a module or component to allow us to create configuratio or settings based on files or
environment variables.
You need to inherit from SincproConfig from module sincpro_framework.sincpro_conf
from sincpro_framework.sincpro_conf import SincproConfig
class PostgresConf(SincproConfig):
host: str = "localhost"
port: int = 5432
user: str = "my_user"
class MyConfig(SincproConfig):
log_level: str = "DEBUG"
token: str = "defult_my_token"
postgresql: PostgresConf = PostgresConf()
This class should be mapped based on yaml file like this, we have a feature to use ENV variables in the yaml file
using the prefix $ENV:
log_level: "INFO"
token: "$ENV:MY_SECRET_TOKEN"
postgresql:
host: localhost
port: 12345
user: custom_user
Then you can use the config object in your code where it will be loaded all the settings from the yaml file
for that you will require use the following funciton build_config_obj
from sincpro_framework.sincpro_conf import build_config_obj
from .my_config import MyConfig
config = build_config_obj(MyConfig, '/path/to/your/config.yml')
assert isinstance(config.log_level, str)
assert isinstance(config.postgresql, PostgresConf)
๐ฆ Variables
The framework use a default setting file where live in the module folder inside of
sincpro_framework/conf/sincpro_framework_conf.yml
where you can define some behavior currently we support the following settings:
- log level(
sincpro_framework_log_level): Define the log level for the logger, the default isDEBUG
Override the config file using another
export SINCPRO_FRAMEWORK_CONFIG_FILE = /path/to/your/config.yml
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sincpro_framework-1.3.0.tar.gz.
File metadata
- Download URL: sincpro_framework-1.3.0.tar.gz
- Upload date:
- Size: 17.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.6 Linux/6.8.0-47-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1b39b92753f6b269718ab66be2ac3c8cd7032eca2194fb23739b2c64d4169ef8
|
|
| MD5 |
86e19555fe424b33823f366b9ce731a5
|
|
| BLAKE2b-256 |
1c593710318242b805a3d96e350dedf0094c8ca4437979f2de41a3cdd444d084
|
File details
Details for the file sincpro_framework-1.3.0-py3-none-any.whl.
File metadata
- Download URL: sincpro_framework-1.3.0-py3-none-any.whl
- Upload date:
- Size: 14.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.6 Linux/6.8.0-47-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d9cf86007ad64d53f58b99f5b2b6df160c205e35820d1078121ab469dba45abe
|
|
| MD5 |
759b393294d2f12d5d6668d55e1a2bc2
|
|
| BLAKE2b-256 |
254bd9320842cf6da501b659c77baa67cf669d2bd04ead14c5aff1feb0e76323
|