├── .flake8 ├── .gitignore ├── .pre-commit-config.yaml ├── .pylintrc ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yaml ├── install.sh ├── mypy.ini ├── pyproject.toml ├── scripts └── pre-commit │ ├── configure.sh │ ├── run.sh │ └── run_all.sh ├── setup.cfg ├── sonar-project.properties ├── src ├── __init__.py ├── adapters │ ├── __init__.py │ └── redis_adapter.py ├── app.py ├── bootstrap.py ├── domain │ ├── __init__.py │ ├── base │ │ ├── __init__.py │ │ ├── dto.py │ │ ├── entity.py │ │ ├── event.py │ │ ├── model.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ └── event_adapter_interface.py │ │ └── value_object.py │ ├── delivery │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── cost_calculator_adapter.py │ │ └── ports │ │ │ ├── __init__.py │ │ │ └── cost_calculator_interface.py │ ├── maps │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── google_maps_adapter.py │ │ ├── model │ │ │ ├── __init__.py │ │ │ └── value_objects.py │ │ └── ports │ │ │ ├── __init__.py │ │ │ └── maps_adapter_interface.py │ ├── order │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ ├── kafka_publisher_adapter.py │ │ │ ├── mongo_db_connector_adapter.py │ │ │ └── order_event_publisher_adapter.py │ │ ├── controllers │ │ │ ├── __init__.py │ │ │ └── order_controller.py │ │ ├── dtos │ │ │ ├── __init__.py │ │ │ └── order_dtos.py │ │ ├── exceptions │ │ │ ├── __init__.py │ │ │ └── order_exceptions.py │ │ ├── model │ │ │ ├── __init__.py │ │ │ ├── entities.py │ │ │ ├── events.py │ │ │ └── value_objects.py │ │ ├── ports │ │ │ ├── __init__.py │ │ │ ├── event_publisher_interface.py │ │ │ ├── order_aggregate_repository_interface.py │ │ │ ├── order_command_interface.py │ │ │ ├── order_event_store_repository_interface.py │ │ │ ├── order_mediator_interface.py │ │ │ ├── order_query_interface.py │ │ │ └── store_connector_adapter_interface.py │ │ ├── repositories │ │ │ ├── __init__.py │ │ │ ├── order_aggregate_cache_repository.py │ │ │ ├── order_aggregate_repository.py │ │ │ └── order_event_store_repository.py │ │ └── services │ │ │ ├── __init__.py │ │ │ ├── order_command.py │ │ │ ├── order_mediator.py │ │ │ └── order_query.py │ ├── payment │ │ ├── __init__.py │ │ ├── adapters │ │ │ ├── __init__.py │ │ │ └── paypal_adapter.py │ │ ├── model │ │ │ ├── __init__.py │ │ │ └── value_objects.py │ │ └── ports │ │ │ ├── __init__.py │ │ │ └── payment_adapter_interface.py │ └── product │ │ ├── __init__.py │ │ ├── adapters │ │ ├── __init__.py │ │ └── product_adapter.py │ │ ├── model │ │ ├── __init__.py │ │ ├── entities.py │ │ └── value_objects.py │ │ └── ports │ │ ├── __init__.py │ │ └── product_adapter_interface.py ├── exceptions.py ├── ports │ ├── __init__.py │ └── cache_interface.py └── settings.py └── start.sh /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .git, *migrations*, manage.py, ignore/, venv, *_pb2* 3 | max-line-length = 100 4 | extend-ignore = E203 5 | per-file-ignores = 6 | __init__.py:F401 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # MacOS 10 | .DS_Store 11 | 12 | # PyCharm 13 | .idea 14 | .idea/ 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.4.0 6 | hooks: 7 | - id: trailing-whitespace 8 | - id: end-of-file-fixer 9 | - id: check-yaml 10 | args: [--unsafe] 11 | - id: check-toml 12 | - id: check-added-large-files 13 | - id: check-merge-conflict 14 | - id: no-commit-to-branch 15 | args: [--branch, master, --branch, main] 16 | - id: double-quote-string-fixer 17 | files: \.py$ 18 | - repo: https://github.com/asottile/pyupgrade 19 | rev: v2.37.3 20 | hooks: 21 | - id: pyupgrade 22 | args: [--py310-plus] 23 | - repo: https://github.com/charliermarsh/ruff-pre-commit 24 | rev: v0.0.254 25 | hooks: 26 | - id: ruff 27 | args: [ 28 | --line-length, 29 | "100", 30 | --target-version, 31 | py310, 32 | --fix 33 | ] 34 | - repo: https://github.com/pycqa/isort 35 | rev: 5.12.0 36 | hooks: 37 | - id: isort 38 | - repo: https://github.com/psf/black 39 | rev: 22.8.0 40 | hooks: 41 | - id: black 42 | args: [ 43 | --line-length, 44 | "100", 45 | --target-version, 46 | py310, 47 | --skip-string-normalization 48 | ] 49 | - repo: local 50 | hooks: 51 | - id: pylint 52 | name: pylint 53 | entry: pylint 54 | language: system 55 | types: [python] 56 | args: [ 57 | --rcfile=.pylintrc, 58 | --output-format=colorized, 59 | ] 60 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # Analyse import fallback blocks. This can be used to support both Python 2 and 4 | # 3 compatible code, which means that the block might have code that exists 5 | # only in one or another interpreter, leading to false positives when analysed. 6 | analyse-fallback-blocks=no 7 | 8 | # Load and enable all available extensions. Use --list-extensions to see a list 9 | # all available extensions. 10 | #enable-all-extensions= 11 | 12 | # In error mode, messages with a category besides ERROR or FATAL are 13 | # suppressed, and no reports are done by default. Error mode is compatible with 14 | # disabling specific errors. 15 | #errors-only= 16 | 17 | # Always return a 0 (non-error) status code, even if lint errors are found. 18 | # This is primarily useful in continuous integration scripts. 19 | #exit-zero= 20 | 21 | # A comma-separated list of package or module names from where C extensions may 22 | # be loaded. Extensions are loading into the active Python interpreter and may 23 | # run arbitrary code. 24 | extension-pkg-allow-list= 25 | 26 | # A comma-separated list of package or module names from where C extensions may 27 | # be loaded. Extensions are loading into the active Python interpreter and may 28 | # run arbitrary code. (This is an alternative name to extension-pkg-allow-list 29 | # for backward compatibility.) 30 | extension-pkg-whitelist= 31 | 32 | # Return non-zero exit code if any of these messages/categories are detected, 33 | # even if score is above --fail-under value. Syntax same as enable. Messages 34 | # specified are enabled, while categories only check already-enabled messages. 35 | fail-on= 36 | 37 | # Specify a score threshold to be exceeded before program exits with error. 38 | fail-under=10 39 | 40 | # Interpret the stdin as a python script, whose filename needs to be passed as 41 | # the module_or_package argument. 42 | #from-stdin= 43 | 44 | # Files or directories to be skipped. They should be base names, not paths. 45 | ignore=CVS 46 | 47 | # Add files or directories matching the regex patterns to the ignore-list. The 48 | # regex matches against paths and can be in Posix or Windows format. 49 | ignore-paths=migrations,tests,mocks 50 | 51 | # Files or directories matching the regex patterns are skipped. The regex 52 | # matches against base names, not paths. The default value ignores Emacs file 53 | # locks 54 | ignore-patterns=^\.# 55 | 56 | # List of module names for which member attributes should not be checked 57 | # (useful for modules/projects where namespaces are manipulated during runtime 58 | # and thus existing member attributes cannot be deduced by static analysis). It 59 | # supports qualified module names, as well as Unix pattern matching. 60 | ignored-modules= 61 | 62 | # Python code to execute, usually for sys.path manipulation such as 63 | # pygtk.require(). 64 | #init-hook= 65 | 66 | # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the 67 | # number of processors available to use. 68 | jobs=1 69 | 70 | # Control the amount of potential inferred values when inferring a single 71 | # object. This can help the performance when dealing with large functions or 72 | # complex, nested conditions. 73 | limit-inference-results=100 74 | 75 | # List of plugins (as comma separated values of python module names) to load, 76 | # usually to register additional checkers. 77 | load-plugins=pylint_pydantic 78 | 79 | # Pickle collected data for later comparisons. 80 | persistent=yes 81 | 82 | # Minimum Python version to use for version dependent checks. Will default to 83 | # the version used to run pylint. 84 | py-version=3.10 85 | 86 | # Discover python modules and packages in the file system subtree. 87 | recursive=no 88 | 89 | # When enabled, pylint would attempt to guess common misconfiguration and emit 90 | # user-friendly hints instead of false-positive error messages. 91 | suggestion-mode=yes 92 | 93 | # Allow loading of arbitrary C extensions. Extensions are imported into the 94 | # active Python interpreter and may run arbitrary code. 95 | unsafe-load-any-extension=no 96 | 97 | # In verbose mode, extra non-checker-related info will be displayed. 98 | #verbose= 99 | 100 | 101 | [REPORTS] 102 | 103 | # Python expression which should return a score less than or equal to 10. You 104 | # have access to the variables 'fatal', 'error', 'warning', 'refactor', 105 | # 'convention', and 'info' which contain the number of messages in each 106 | # category, as well as 'statement' which is the total number of statements 107 | # analyzed. This score is used by the global evaluation report (RP0004). 108 | evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) 109 | 110 | # Template used to display messages. This is a python new-style format string 111 | # used to format the message information. See doc for all details. 112 | msg-template= 113 | 114 | # Set the output format. Available formats are text, parseable, colorized, json 115 | # and msvs (visual studio). You can also give a reporter class, e.g. 116 | # mypackage.mymodule.MyReporterClass. 117 | output-format=parseable 118 | 119 | # Tells whether to display a full report or only the messages. 120 | reports=no 121 | 122 | # Activate the evaluation score. 123 | score=yes 124 | 125 | 126 | [MESSAGES CONTROL] 127 | 128 | # Only show warnings with the listed confidence levels. Leave empty to show 129 | # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, 130 | # UNDEFINED. 131 | confidence= 132 | 133 | # Disable the message, report, category or checker with the given id(s). You 134 | # can either give multiple identifiers separated by comma (,) or put this 135 | # option multiple times (only on the command line, not in the configuration 136 | # file where it should appear only once). You can also use "--disable=all" to 137 | # disable everything first and then re-enable specific checks. For example, if 138 | # you want to run only the similarities checker, you can use "--disable=all 139 | # --enable=similarities". If you want to run only the classes checker, but have 140 | # no Warning level messages displayed, use "--disable=all --enable=classes 141 | # --disable=W". 142 | disable= 143 | E0401, # import-error 144 | W0231, # super-init-not-called 145 | C0114, # missing-module-docstring 146 | C0115, # missing-class-docstring 147 | C0116, # missing-function-docstring 148 | W0511, # todos 149 | E0601, # used-before-assignment 150 | W0150, # lost-exception 151 | W0703, # broad-except 152 | C0413, # wrong-import-order 153 | W0613, # unused-argument 154 | W0611, # unused-import 155 | W0105, # pointles-string-statement 156 | E0110, # abstract-class-instantiated 157 | C0201, # consider-using-enumerate 158 | C0411, # wrong-import-order 159 | C0301, # line-too-long 160 | R0903, # too-few-public-methods 161 | R1710, # inconsistent-return-statements, 162 | C0412, # ungrouped-imports, 163 | E0611, # no-name-in-module, 164 | C0103, # invalid-name 165 | R0914, # too-many-locals 166 | R0913, # too-many-arguments 167 | R0902, # too-many-instance-attributes 168 | W0201, # attribute-defined-outside-init 169 | C0415, # import-outside-toplevel 170 | R0912, # too-many-branches, 171 | R0915, # too-many-statements 172 | invalid-unary-operand-type, 173 | raw-checker-failed, 174 | bad-inline-option, 175 | locally-disabled, 176 | file-ignored, 177 | suppressed-message, 178 | useless-suppression, 179 | deprecated-pragma, 180 | use-symbolic-message-instead, 181 | no-member, 182 | too-many-public-methods, 183 | logging-fstring-interpolation, 184 | duplicate-code, 185 | too-many-function-args 186 | 187 | # Enable the message, report, category or checker with the given id(s). You can 188 | # either give multiple identifier separated by comma (,) or put this option 189 | # multiple time (only on the command line, not in the configuration file where 190 | # it should appear only once). See also the "--disable" option for examples. 191 | enable=c-extension-no-member 192 | 193 | 194 | [LOGGING] 195 | 196 | # The type of string formatting that logging methods do. `old` means using % 197 | # formatting, `new` is for `{}` formatting. 198 | ; logging-format-style=old 199 | 200 | # Logging modules to check that the string format arguments are in logging 201 | # function parameter format. 202 | logging-modules=logging 203 | 204 | 205 | [SPELLING] 206 | 207 | # Limits count of emitted suggestions for spelling mistakes. 208 | max-spelling-suggestions=4 209 | 210 | # Spelling dictionary name. Available dictionaries: none. To make it work, 211 | # install the 'python-enchant' package. 212 | spelling-dict= 213 | 214 | # List of comma separated words that should be considered directives if they 215 | # appear at the beginning of a comment and should not be checked. 216 | spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: 217 | 218 | # List of comma separated words that should not be checked. 219 | spelling-ignore-words= 220 | 221 | # A path to a file that contains the private dictionary; one word per line. 222 | spelling-private-dict-file= 223 | 224 | # Tells whether to store unknown words to the private dictionary (see the 225 | # --spelling-private-dict-file option) instead of raising a message. 226 | spelling-store-unknown-words=no 227 | 228 | 229 | [MISCELLANEOUS] 230 | 231 | # List of note tags to take in consideration, separated by a comma. 232 | notes=FIXME, 233 | XXX, 234 | TODO 235 | 236 | # Regular expression of note tags to take in consideration. 237 | notes-rgx= 238 | 239 | 240 | [TYPECHECK] 241 | 242 | # Tells whether missing members accessed in mixin class should be ignored. A 243 | # mixin class is detected if its name ends with "mixin" (case insensitive). 244 | ignore-mixin-members=yes 245 | 246 | # List of decorators that produce context managers, such as 247 | # contextlib.contextmanager. Add to this list to register other decorators that 248 | # produce valid context managers. 249 | contextmanager-decorators=contextlib.contextmanager 250 | 251 | # List of members which are set dynamically and missed by pylint inference 252 | # system, and so shouldn't trigger E1101 when accessed. Python regular 253 | # expressions are accepted. 254 | generated-members= 255 | 256 | # Tells whether to warn about missing members when the owner of the attribute 257 | # is inferred to be None. 258 | ignore-none=yes 259 | 260 | # This flag controls whether pylint should warn about no-member and similar 261 | # checks whenever an opaque object is returned when inferring. The inference 262 | # can return multiple potential results while evaluating a Python object, but 263 | # some branches might not be evaluated, which results in partial inference. In 264 | # that case, it might be useful to still emit no-member and other checks for 265 | # the rest of the inferred objects. 266 | ignore-on-opaque-inference=yes 267 | 268 | # List of symbolic message names to ignore for Mixin members. 269 | ignored-checks-for-mixins=no-member, 270 | not-async-context-manager, 271 | not-context-manager, 272 | attribute-defined-outside-init 273 | 274 | # List of class names for which member attributes should not be checked (useful 275 | # for classes with dynamically set attributes). This supports the use of 276 | # qualified names. 277 | ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace 278 | 279 | # Show a hint with possible names when a member name was not found. The aspect 280 | # of finding the hint is based on edit distance. 281 | missing-member-hint=yes 282 | 283 | # The minimum edit distance a name should have in order to be considered a 284 | # similar match for a missing member name. 285 | missing-member-hint-distance=1 286 | 287 | # The total number of similar names that should be taken in consideration when 288 | # showing a hint for a missing member. 289 | missing-member-max-choices=1 290 | 291 | # Regex pattern to define which classes are considered mixins. 292 | mixin-class-rgx=.*[Mm]ixin 293 | 294 | # List of decorators that change the signature of a decorated function. 295 | signature-mutators= 296 | 297 | 298 | [CLASSES] 299 | 300 | # Warn about protected attribute access inside special methods 301 | check-protected-access-in-special-methods=no 302 | 303 | # List of method names used to declare (i.e. assign) instance attributes. 304 | defining-attr-methods=__init__, 305 | __new__, 306 | setUp, 307 | __post_init__ 308 | 309 | # List of member names, which should be excluded from the protected access 310 | # warning. 311 | exclude-protected=_asdict, 312 | _fields, 313 | _replace, 314 | _source, 315 | _make 316 | 317 | # List of valid names for the first argument in a class method. 318 | valid-classmethod-first-arg=cls 319 | 320 | # List of valid names for the first argument in a metaclass class method. 321 | valid-metaclass-classmethod-first-arg=cls 322 | 323 | 324 | [VARIABLES] 325 | 326 | # List of additional names supposed to be defined in builtins. Remember that 327 | # you should avoid defining new builtins when possible. 328 | additional-builtins= 329 | 330 | # Tells whether unused global variables should be treated as a violation. 331 | allow-global-unused-variables=yes 332 | 333 | # List of names allowed to shadow builtins 334 | allowed-redefined-builtins= 335 | 336 | # List of strings which can identify a callback function by name. A callback 337 | # name must start or end with one of those strings. 338 | callbacks=cb_, 339 | _cb 340 | 341 | # A regular expression matching the name of dummy variables (i.e. expected to 342 | # not be used). 343 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 344 | 345 | # Argument names that match this expression will be ignored. Default to name 346 | # with leading underscore. 347 | ignored-argument-names=_.*|^ignored_|^unused_ 348 | 349 | # Tells whether we should check for unused import in __init__ files. 350 | init-import=no 351 | 352 | # List of qualified module names which can have objects that can redefine 353 | # builtins. 354 | redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io 355 | 356 | 357 | [FORMAT] 358 | 359 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 360 | expected-line-ending-format= 361 | 362 | # Regexp for a line that is allowed to be longer than the limit. 363 | ignore-long-lines=^\s*(# )??$ 364 | 365 | # Number of spaces of indent required inside a hanging or continued line. 366 | indent-after-paren=4 367 | 368 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 369 | # tab). 370 | indent-string=' ' 371 | 372 | # Maximum number of characters on a single line. 373 | max-line-length=100 374 | 375 | # Maximum number of lines in a module. 376 | max-module-lines=1000 377 | 378 | # Allow the body of a class to be on the same line as the declaration if body 379 | # contains single statement. 380 | single-line-class-stmt=no 381 | 382 | # Allow the body of an if to be on the same line as the test if there is no 383 | # else. 384 | single-line-if-stmt=no 385 | 386 | 387 | [IMPORTS] 388 | 389 | # List of modules that can be imported at any level, not just the top level 390 | # one. 391 | allow-any-import-level= 392 | 393 | # Allow wildcard imports from modules that define __all__. 394 | allow-wildcard-with-all=no 395 | 396 | # Deprecated modules which should not be used, separated by a comma. 397 | deprecated-modules= 398 | 399 | # Output a graph (.gv or any supported image format) of external dependencies 400 | # to the given file (report RP0402 must not be disabled). 401 | ext-import-graph= 402 | 403 | # Output a graph (.gv or any supported image format) of all (i.e. internal and 404 | # external) dependencies to the given file (report RP0402 must not be 405 | # disabled). 406 | import-graph= 407 | 408 | # Output a graph (.gv or any supported image format) of internal dependencies 409 | # to the given file (report RP0402 must not be disabled). 410 | int-import-graph= 411 | 412 | # Force import order to recognize a module as part of the standard 413 | # compatibility libraries. 414 | known-standard-library= 415 | 416 | # Force import order to recognize a module as part of a third party library. 417 | known-third-party=enchant 418 | 419 | # Couples of modules and preferred modules, separated by a comma. 420 | preferred-modules= 421 | 422 | 423 | [EXCEPTIONS] 424 | 425 | # Exceptions that will emit a warning when caught. 426 | overgeneral-exceptions=builtins.CommonExceptions, 427 | builtins.Exception, 428 | builtins.BaseException, 429 | 430 | [REFACTORING] 431 | 432 | # Maximum number of nested blocks for function / method body 433 | max-nested-blocks=5 434 | 435 | # Complete name of functions that never returns. When checking for 436 | # inconsistent-return-statements if a never returning function is called then 437 | # it will be considered as an explicit return statement and no message will be 438 | # printed. 439 | never-returning-functions=sys.exit,argparse.parse_error 440 | 441 | 442 | [SIMILARITIES] 443 | # Comments are removed from the similarity computation 444 | ignore-comments=yes 445 | 446 | # Docstrings are removed from the similarity computation 447 | ignore-docstrings=yes 448 | 449 | # Imports are removed from the similarity computation 450 | ignore-imports=yes 451 | 452 | # Signatures are removed from the similarity computation 453 | ignore-signatures=yes 454 | 455 | # Minimum lines number of a similarity. 456 | min-similarity-lines=4 457 | 458 | 459 | [DESIGN] 460 | 461 | # List of regular expressions of class ancestor names to ignore when counting 462 | # public methods (see R0903) 463 | exclude-too-few-public-methods= 464 | 465 | # List of qualified class names to ignore when counting class parents (see 466 | # R0901) 467 | ignored-parents= 468 | 469 | # Maximum number of arguments for function / method. 470 | max-args=5 471 | 472 | # Maximum number of attributes for a class (see R0902). 473 | max-attributes=7 474 | 475 | # Maximum number of boolean expressions in an if statement (see R0916). 476 | max-bool-expr=5 477 | 478 | # Maximum number of branch for function / method body. 479 | max-branches=12 480 | 481 | # Maximum number of locals for function / method body. 482 | max-locals=15 483 | 484 | # Maximum number of parents for a class (see R0901). 485 | max-parents=7 486 | 487 | # Maximum number of public methods for a class (see R0904). 488 | max-public-methods=20 489 | 490 | # Maximum number of return / yield for function / method body. 491 | max-returns=6 492 | 493 | # Maximum number of statements in function / method body. 494 | max-statements=50 495 | 496 | # Minimum number of public methods for a class (see R0903). 497 | min-public-methods=2 498 | 499 | 500 | [STRING] 501 | 502 | # This flag controls whether inconsistent-quotes generates a warning when the 503 | # character used as a quote delimiter is used inconsistently within a module. 504 | check-quote-consistency=no 505 | 506 | # This flag controls whether the implicit-str-concat should generate a warning 507 | # on implicit string concatenation in sequences defined over several lines. 508 | check-str-concat-over-line-jumps=no 509 | 510 | 511 | [BASIC] 512 | 513 | # Naming style matching correct argument names. 514 | argument-naming-style=snake_case 515 | 516 | # Regular expression matching correct argument names. Overrides argument- 517 | # naming-style. If left empty, argument names will be checked with the set 518 | # naming style. 519 | #argument-rgx= 520 | 521 | # Naming style matching correct attribute names. 522 | attr-naming-style=snake_case 523 | 524 | # Regular expression matching correct attribute names. Overrides attr-naming- 525 | # style. If left empty, attribute names will be checked with the set naming 526 | # style. 527 | #attr-rgx= 528 | 529 | # Bad variable names which should always be refused, separated by a comma. 530 | bad-names=foo, 531 | bar, 532 | baz, 533 | toto, 534 | tutu, 535 | tata 536 | 537 | # Bad variable names regexes, separated by a comma. If names match any regex, 538 | # they will always be refused 539 | bad-names-rgxs= 540 | 541 | # Naming style matching correct class attribute names. 542 | class-attribute-naming-style=any 543 | 544 | # Regular expression matching correct class attribute names. Overrides class- 545 | # attribute-naming-style. If left empty, class attribute names will be checked 546 | # with the set naming style. 547 | #class-attribute-rgx= 548 | 549 | # Naming style matching correct class constant names. 550 | class-const-naming-style=UPPER_CASE 551 | 552 | # Regular expression matching correct class constant names. Overrides class- 553 | # const-naming-style. If left empty, class constant names will be checked with 554 | # the set naming style. 555 | #class-const-rgx= 556 | 557 | # Naming style matching correct class names. 558 | class-naming-style=PascalCase 559 | 560 | # Regular expression matching correct class names. Overrides class-naming- 561 | # style. If left empty, class names will be checked with the set naming style. 562 | #class-rgx= 563 | 564 | # Naming style matching correct constant names. 565 | const-naming-style=UPPER_CASE 566 | 567 | # Regular expression matching correct constant names. Overrides const-naming- 568 | # style. If left empty, constant names will be checked with the set naming 569 | # style. 570 | #const-rgx= 571 | 572 | # Minimum line length for functions/classes that require docstrings, shorter 573 | # ones are exempt. 574 | docstring-min-length=-1 575 | 576 | # Naming style matching correct function names. 577 | function-naming-style=snake_case 578 | 579 | # Regular expression matching correct function names. Overrides function- 580 | # naming-style. If left empty, function names will be checked with the set 581 | # naming style. 582 | #function-rgx= 583 | 584 | # Good variable names which should always be accepted, separated by a comma. 585 | good-names=i, 586 | j, 587 | k, 588 | ex, 589 | Run, 590 | _, 591 | logger, 592 | T 593 | 594 | # Good variable names regexes, separated by a comma. If names match any regex, 595 | # they will always be accepted 596 | good-names-rgxs= 597 | 598 | # Include a hint for the correct naming format with invalid-name. 599 | include-naming-hint=no 600 | 601 | # Naming style matching correct inline iteration names. 602 | inlinevar-naming-style=any 603 | 604 | # Regular expression matching correct inline iteration names. Overrides 605 | # inlinevar-naming-style. If left empty, inline iteration names will be checked 606 | # with the set naming style. 607 | #inlinevar-rgx= 608 | 609 | # Naming style matching correct method names. 610 | method-naming-style=snake_case 611 | 612 | # Regular expression matching correct method names. Overrides method-naming- 613 | # style. If left empty, method names will be checked with the set naming style. 614 | #method-rgx= 615 | 616 | # Naming style matching correct module names. 617 | module-naming-style=snake_case 618 | 619 | # Regular expression matching correct module names. Overrides module-naming- 620 | # style. If left empty, module names will be checked with the set naming style. 621 | #module-rgx= 622 | 623 | # Colon-delimited sets of names that determine each other's naming style when 624 | # the name regexes allow several styles. 625 | name-group= 626 | 627 | # Regular expression which should only match function or class names that do 628 | # not require a docstring. 629 | no-docstring-rgx=^_ 630 | 631 | # List of decorators that produce properties, such as abc.abstractproperty. Add 632 | # to this list to register other decorators that produce valid properties. 633 | # These decorators are taken in consideration only for invalid-name. 634 | property-classes=abc.abstractproperty 635 | 636 | # Regular expression matching correct type variable names. If left empty, type 637 | # variable names will be checked with the set naming style. 638 | #typevar-rgx= 639 | 640 | # Naming style matching correct variable names. 641 | variable-naming-style=snake_case 642 | 643 | # Regular expression matching correct variable names. Overrides variable- 644 | # naming-style. If left empty, variable names will be checked with the set 645 | # naming style. 646 | #variable-rgx= 647 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use a specific Python image 2 | FROM python:3.10 3 | 4 | # Create a non-privileged user for running the application 5 | RUN useradd -m -s /bin/bash userapp 6 | 7 | # Update and install necessary packages 8 | RUN apt update \ 9 | && apt install -y make \ 10 | && apt install --no-install-recommends -y ca-certificates locales locales-all \ 11 | && update-ca-certificates \ 12 | && rm -rf /var/lib/apt/lists/* 13 | 14 | # Set up locale settings 15 | RUN locale-gen pt_BR.UTF-8 16 | ENV LANG pt_BR.UTF-8 17 | ENV LANGUAGE pt_BR:pt_br 18 | ENV LC_ALL pt_BR.UTF-8 19 | 20 | # Remove log delay 21 | ENV PYTHONUNBUFFERED 1 22 | ENV PYTHONPATH /home/userapp/app/src/ 23 | 24 | # Set the working directory 25 | WORKDIR /home/userapp/app 26 | 27 | # Copy only necessary files to install dependencies 28 | COPY --chown=userapp:userapp ./pyproject.toml ./poetry.lock /home/userapp/app/ 29 | 30 | # Install Poetry and dependencies 31 | RUN pip install poetry \ 32 | && poetry config virtualenvs.create false \ 33 | && poetry install --no-interaction --no-cache -vvv 34 | 35 | # Copy the rest of the application 36 | COPY --chown=userapp:userapp . . 37 | 38 | # Set the default user for running the application 39 | USER userapp 40 | 41 | # Set the entry point and default command 42 | ENTRYPOINT ["poetry", "run", "--"] 43 | CMD ["./start.sh"] 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | rest-up: 2 | docker-compose -f rest.docker-compose.yml up --build 3 | 4 | rest-down: 5 | docker-compose -f rest.docker-compose.yml down 6 | 7 | test-domain: 8 | pytest tests/domain/ 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cqrs-architecture-with-python 2 | Applying pattern Ports and Adapters + CQRS with Python Fastapi. 3 | 4 | 5 | ## Bounded Contexts 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Domain:Ordering
Concepts:Domain Driven Design (Subdomains, Bounded Contexts, Ubiquitous Language, Aggregates, Value Objects)
Architecture style:Event Driven Microservices
Architectural patterns:Event Sourcing, Hexagonal Architecture and CQRS
Technology:Python with (FastAPI), MongoDB and Redis
29 | 30 | ## Domain 31 | Customers use the website application(s) to place orders. Application coordinates order preparation and delivery. 32 | 33 | ## Sub-domains 34 | - **Order**: This domain is responsible for managing and processing orders placed by customers, including product selection, pricing, and payment completion. 35 | - **Product**: This domain is responsible for managing and providing information about the products available for sale, including descriptions, prices and images. 36 | - **Delivery**: This domain is responsible for managing and tracking deliveries, including scheduling deliveries, tracking carrier location, and processing returns. 37 | - **Maps**: This domain is responsible for providing geographic information including delivery routes, delivery locations and estimated travel time. 38 | - **Payment**: This domain is responsible for processing payments, including credit card authorizations, balance checks and payment confirmations 39 | 40 | 41 | ## Domain model 42 | 43 | Sub-domain *software programing* models: 44 | 45 | - [ordering](https://github.com/marcosvs98/hexagonal-architecture-with-python/tree/main/src/domain) 46 | 47 | > Domain model is mainly a software programing model which is applied to a specific sub-domain. 48 | > It defines the vocabulary and acts as a communication tool for everyone involved (business and IT), deriving a [Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html). 49 | 50 | ## Bounded Context 51 | 52 | Each of this group of applications/services belongs to a specific bounded context: 53 | - [ordering](https://github.com/marcosvs98/hexagonal-architecture-with-python/tree/main/src/domain) - Order bounded context, with messages serialized to JSON 54 | 55 | 56 | > A goal is to develop a [Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html) as our domain (sub-domain) model within an explicitly Bounded Context. 57 | > Therefore, there are a number of rules for Models and Contexts 58 | > - Explicitly define the context within which a model applies 59 | > - Ideally, keep one sub-domain model per one Bounded Context 60 | > - Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas 61 | 62 | 63 | 64 | ## Technologies and patterns used 65 | 66 | - **Python 3.10** 67 | - **FastAPI (Rest API)** 68 | - **MongoDB** 69 | - **Pydantic 2.5** 70 | - **Redis** 71 | - **CQRS** 72 | - **Ports & Adapters** 73 | - **Event Sourcing** 74 | 75 | In addition to others, the main pattern that guides this project is the Ports & Adapter + CQRS. In summary, this pattern provides a way to organize code so that business logic is encapsulated, but separated from the underlying delivery mechanism. This allows for better maintenance and fewer dependencies. 76 | 77 | With CQRS, we have a clear separation of concerns, making the codebase easier to understand and maintain.Developers can more easily reason about how changes to the codebase will affect the overall system. Additionally, its use allows each model to evolve independently since they are not strongly coupled. This means changes to one model can be made without affecting the other model. 78 | 79 | 80 | --- 81 | ## Running the project 82 | 83 | ### Option 1 - Via Docker Compose 84 | 85 | #### Run docker-compose 86 | 87 | Finally, run the project and its dependencies in the background using the command 88 | ```bash 89 | docker-compose up -d 90 | ``` 91 | 92 | ## References 93 | 94 | - [Hexagonal Architecture](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) 95 | - [Domain Driven Design - DDD](https://lyz-code.github.io/blue-book/architecture/domain_driven_design/) 96 | - [Repository Pattern](https://lyz-code.github.io/blue-book/architecture/repository_pattern/) 97 | - [Service Layer Pattern](https://www.cosmicpython.com/book/chapter_04_service_layer.html) 98 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | 3 | services: 4 | ordering-service: 5 | container_name: ordering-service 6 | build: 7 | context: . 8 | volumes: 9 | - .:/home/userapp/app/. 10 | env_file: 11 | - .env 12 | ports: 13 | - '8000:8000' 14 | environment: 15 | MONGO_SERVER: order-aggregate-repository_mongo-db 16 | MONGO_PORT: '27017' 17 | MONGO_USERNAME: root 18 | MONGO_PASSWORD: admin 19 | ENVIRONMENT: development 20 | restart: always 21 | depends_on: 22 | - order-aggregate-repository_mongo-db 23 | - ordering-event-bus 24 | 25 | order-aggregate-repository_mongo-db: 26 | image: mongo:5.0 27 | container_name: order-aggregate-repository_mongo-db 28 | environment: 29 | MONGO_INITDB_ROOT_USERNAME: admin 30 | MONGO_INITDB_ROOT_PASSWORD: root 31 | ports: 32 | - '27018:27017' 33 | restart: always 34 | 35 | ordering-event-store-repository_mongo-db: 36 | image: mongo:5.0 37 | container_name: ordering-event-store-repository_mongo-db 38 | environment: 39 | MONGO_INITDB_ROOT_USERNAME: admin 40 | MONGO_INITDB_ROOT_PASSWORD: root 41 | ports: 42 | - '27019:27017' 43 | restart: always 44 | 45 | ordering-redis: 46 | image: "redis:alpine" 47 | container_name: ordering-redis 48 | command: redis-server 49 | ports: 50 | - "6379:6379" 51 | 52 | ordering-event-store-repository_admin-mongo: 53 | image: 0x59/admin-mongo:latest 54 | container_name: ordering-event-store-repository_admin-mongo 55 | environment: 56 | PORT: 1234 57 | CONN_NAME: ordering-event-store-repository_mongo-db 58 | DB_HOST: 27017 59 | restart: unless-stopped 60 | ports: 61 | - "1234:1234" 62 | links: 63 | - ordering-event-store-repository_mongo-db 64 | depends_on: 65 | - ordering-event-store-repository_mongo-db 66 | 67 | zookeeper: 68 | image: confluentinc/cp-zookeeper:latest 69 | ports: 70 | - "2181:2181" 71 | environment: 72 | ZOOKEEPER_CLIENT_PORT: 2181 73 | ZOOKEEPER_TICK_TIME: 2000 74 | 75 | ordering-event-bus-kafka: 76 | image: confluentinc/cp-kafka:latest 77 | container_name: ordering-event-bus-kafka 78 | ports: 79 | - "9092:9092" 80 | environment: 81 | KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181" 82 | KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://ordering-event-bus-kafka:9092 83 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 84 | depends_on: 85 | - zookeeper 86 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Installing development dependencies..." 3 | poetry install -vvv 4 | echo "Installing development dependencies... Done!" 5 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | python_version=3.10 3 | mypy_path=src 4 | incremental=True 5 | ignore_missing_imports=True 6 | follow_imports=skip 7 | check_untyped_defs=True 8 | warn_redundant_casts=True 9 | warn_unused_ignores=False 10 | no_implicit_reexport=False 11 | show_error_context=True 12 | strict_optional=True 13 | pretty=True 14 | plugins = pydantic.mypy 15 | show_error_codes = True 16 | 17 | [mypy-src.*.tests.*] 18 | allow_untyped_defs = True 19 | allow_untyped_calls = True 20 | disable_error_code = var-annotated, has-type, assignment 21 | 22 | [pydantic-mypy] 23 | init_forbid_extra = True 24 | init_typed = True 25 | warn_required_dynamic_aliases = True 26 | warn_untyped_fields = True 27 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "cqrs-architecture-with-python-event-sourcing" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Marcos Silveira <47537283+MarcosVs98@users.noreply.github.com>"] 6 | readme = "README.md" 7 | packages = [{include = "cqrs_architecture_with_python_event_sourcing"}] 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.9" 11 | aioredis = "^2.0.1" 12 | dnspython = "^2.4.2" 13 | fastapi = "^0.104.1" 14 | fastapi-pagination = "^0.12.12" 15 | motor = "^3.3.2" 16 | pydantic = "^2.5.1" 17 | pymongo = "^4.6.0" 18 | python-decouple = "^3.8" 19 | uvicorn = {extras = ["standard"], version = "^0.18.3"} 20 | requests = "^2.31.0" 21 | aiohttp = "^3.9.0" 22 | aiokafka = "^0.8.1" 23 | 24 | 25 | [build-system] 26 | requires = ["poetry-core"] 27 | build-backend = "poetry.core.masonry.api" 28 | -------------------------------------------------------------------------------- /scripts/pre-commit/configure.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Inserindo hooks no git" 3 | pre-commit install --install-hooks 4 | -------------------------------------------------------------------------------- /scripts/pre-commit/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Rodando pre-commit" 3 | pre-commit run --from-ref origin/HEAD --to-ref HEAD 4 | -------------------------------------------------------------------------------- /scripts/pre-commit/run_all.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Rodando pre-commit" 3 | pre-commit run --all-files 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | testpaths = tests 3 | addopts = -p no:warnings 4 | asyncio_mode = auto 5 | env = 6 | PYTEST_RUNNING = 1 7 | 8 | [coverage:run] 9 | branch = True 10 | omit = 11 | src/tests/* 12 | src/*/__init__.py 13 | src/database/migrations/* 14 | src/scripts/* 15 | src/*/ports/* 16 | source = 17 | ./src 18 | 19 | [pytest] 20 | asyncio_mode = auto 21 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | sonar.projectKey= 2 | 3 | sonar.python.coverage.reportPaths=coverage.xml 4 | sonar.python.version=3 5 | 6 | # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. 7 | sonar.sources=./src 8 | 9 | # Encoding of the source code. Default is default system encoding 10 | sonar.sourceEncoding=UTF-8 11 | 12 | sonar.python.xunit.reportPath=tests_execution_report.xml 13 | sonar.coverage.exclusions=**docs**,**tests**,__init__.py,**ports**,**schemas** 14 | sonar.exclusions=**docs**,**tests** 15 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/__init__.py -------------------------------------------------------------------------------- /src/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/adapters/__init__.py -------------------------------------------------------------------------------- /src/adapters/redis_adapter.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import aioredis 4 | 5 | from ports.cache_interface import CacheInterface 6 | from settings import REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REDIS_SSL 7 | 8 | 9 | def silent_mode_wrapper(function): 10 | async def wrapper(*args, **kwargs): 11 | silent_mode = args[0].silent_mode 12 | if silent_mode: 13 | try: 14 | return await function(*args, **kwargs) 15 | except Exception: 16 | return False 17 | else: 18 | return await function(*args, **kwargs) 19 | 20 | return wrapper 21 | 22 | 23 | class RedisAdapter(CacheInterface): 24 | @staticmethod 25 | def __open_connection(): 26 | redis_url = 'redis://' 27 | if REDIS_SSL: 28 | redis_url = 'rediss://' 29 | if REDIS_PASSWORD: 30 | redis_url += f':{REDIS_PASSWORD}@' 31 | 32 | redis_url += f'{REDIS_HOST}:{REDIS_PORT}/0' 33 | 34 | return aioredis.from_url(redis_url, decode_responses=True, encoding='utf8') # noqa: E501 35 | 36 | @silent_mode_wrapper 37 | async def get(self, key: str): 38 | redis = self.__open_connection() 39 | return json.loads(await redis.get(key)) 40 | 41 | @silent_mode_wrapper 42 | async def set(self, key: str, data: dict, ttl: int = 300): 43 | redis = self.__open_connection() 44 | await redis.set(key, json.dumps(data, default=str), ex=300) 45 | 46 | @silent_mode_wrapper 47 | async def delete(self, key: str): 48 | redis = self.__open_connection() 49 | await redis.delete(key) 50 | -------------------------------------------------------------------------------- /src/app.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI, Request 2 | from fastapi.middleware.cors import CORSMiddleware 3 | from fastapi.responses import JSONResponse 4 | from fastapi_pagination import add_pagination 5 | 6 | from bootstrap import initialize_order_controller 7 | from exceptions import CommonException 8 | from settings import APPLICATION_NAME 9 | 10 | 11 | def init_middlewares(app: FastAPI): 12 | # Configuration of CORS middleware 13 | app.add_middleware( 14 | CORSMiddleware, 15 | allow_origins=['*'], 16 | allow_credentials=False, 17 | allow_methods=['*'], 18 | allow_headers=['*'], 19 | ) 20 | 21 | 22 | def init_routes(app: FastAPI): 23 | # Definition of the health check endpoint 24 | @app.get('/', status_code=200, response_model=dict) 25 | async def health_check() -> dict: 26 | return {'status': 200} 27 | 28 | # Initialization of the order controller and definition of routes 29 | order_controller = initialize_order_controller() 30 | app.include_router(order_controller.router, tags=['order'], prefix='/api/v1/order') 31 | 32 | # Custom exception handlers 33 | @app.exception_handler(CommonException) 34 | async def service_exception_handler(request: Request, error: CommonException) -> JSONResponse: 35 | return JSONResponse(error.to_dict(), status_code=error.code) 36 | 37 | @app.exception_handler(NotImplementedError) 38 | async def not_implemented_error_handler(request, exc: NotImplementedError) -> JSONResponse: 39 | return JSONResponse(content={'error': 'Method Not Allowed.'}, status_code=405) 40 | 41 | 42 | def create_app(): 43 | # Creation of the FastAPI application instance 44 | app = FastAPI( 45 | title=APPLICATION_NAME, 46 | description='FastAPI application using hexagonal architecture', 47 | ) 48 | 49 | # Initialization of middlewares and routes 50 | init_middlewares(app) 51 | init_routes(app) 52 | 53 | # Addition of pagination support 54 | add_pagination(app) 55 | 56 | return app 57 | -------------------------------------------------------------------------------- /src/bootstrap.py: -------------------------------------------------------------------------------- 1 | import settings 2 | from adapters.redis_adapter import RedisAdapter 3 | from domain.delivery.adapters.cost_calculator_adapter import DeliveryCostCalculatorAdapter 4 | from domain.maps.adapters.google_maps_adapter import GoogleMapsAdapter 5 | from domain.order.adapters.kafka_publisher_adapter import KafkaEventPublisher 6 | from domain.order.adapters.mongo_db_connector_adapter import AsyncMongoDBConnectorAdapter 7 | from domain.order.adapters.order_event_publisher_adapter import OrderEventPublisher 8 | from domain.order.controllers.order_controller import OrderController 9 | from domain.order.repositories.order_aggregate_cache_repository import OrderAggregateCacheRepository 10 | from domain.order.repositories.order_aggregate_repository import OrderAggregateRepository 11 | from domain.order.repositories.order_event_store_repository import OrderEventStoreRepository 12 | from domain.order.services.order_command import OrderCommand 13 | from domain.order.services.order_mediator import OrderMediator 14 | from domain.order.services.order_query import OrderQuery 15 | from domain.payment.adapters.paypal_adapter import PayPalPaymentAdapter 16 | from domain.product.adapters.product_adapter import ProductAdapter 17 | 18 | 19 | def initialize_order_controller(): 20 | # Initialize MongoDB connection for Order Event Store 21 | order_event_store_repository = OrderEventStoreRepository( 22 | db_connection=AsyncMongoDBConnectorAdapter( 23 | connection_str=settings.ORDER_EVENT_STORE_CONNECTION, 24 | database_name=settings.ORDER_EVENT_STORE_DATABASE_NAME, 25 | ), 26 | collection_name=settings.ORDER_EVENT_STORE_COLLECTION_NAME, 27 | ) 28 | 29 | # Initialize Kafka Event Publisher 30 | kafka_event_publisher = KafkaEventPublisher(config=settings.KAFKA_SETTINGS) 31 | 32 | # Initialize Order Event Publisher 33 | event_publisher = OrderEventPublisher( 34 | repository=order_event_store_repository, publisher=kafka_event_publisher 35 | ) 36 | 37 | # Initialize MongoDB connection for Order Repository 38 | order_repository = OrderAggregateRepository( 39 | db_connection=AsyncMongoDBConnectorAdapter( 40 | connection_str=settings.ORDER_REPOSITORY_CONNECTION, 41 | database_name=settings.ORDER_REPOSITORY_DATABASE_NAME, 42 | ), 43 | collection_name=settings.ORDER_REPOSITORY_COLLECTION_NAME, 44 | ) 45 | 46 | # Initialize Redis Cache Adapter 47 | redis_cache_adapter = RedisAdapter(silent_mode=settings.CACHE_SILENT_MODE) 48 | 49 | # Initialize Order Cache Repository 50 | cache_repository = OrderAggregateCacheRepository(cache_adapter=redis_cache_adapter) 51 | 52 | # Initialize Google Maps Adapter for Delivery Cost Calculator 53 | delivery_cost_calculator_adapter = DeliveryCostCalculatorAdapter( 54 | maps_service=GoogleMapsAdapter() 55 | ) 56 | 57 | # Initialize Order Command Service 58 | order_command = OrderCommand( 59 | repository=order_repository, 60 | payment_service=PayPalPaymentAdapter(), 61 | product_service=ProductAdapter(), 62 | delivery_service=delivery_cost_calculator_adapter, 63 | event_publisher=event_publisher, 64 | ) 65 | 66 | # Initialize Order Query Service 67 | order_query = OrderQuery(repository=order_repository) 68 | 69 | # Initialize Order Mediator 70 | order_mediator = OrderMediator( 71 | command=order_command, query=order_query, cache_repository=cache_repository 72 | ) 73 | 74 | # Initialize Order Controller 75 | order_controller = OrderController(order_mediator) 76 | 77 | return order_controller 78 | -------------------------------------------------------------------------------- /src/domain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/__init__.py -------------------------------------------------------------------------------- /src/domain/base/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/base/__init__.py -------------------------------------------------------------------------------- /src/domain/base/dto.py: -------------------------------------------------------------------------------- 1 | from pydantic import ConfigDict 2 | 3 | from domain.base.model import Model 4 | 5 | 6 | class DataTransferObject(Model): 7 | """Base class for data transfer objects (DTOs)""" 8 | 9 | model_config = ConfigDict(arbitrary_types_allowed=True) 10 | 11 | def __eq__(self, other: object) -> bool: 12 | if not isinstance(other, DataTransferObject): 13 | return False 14 | 15 | for field_name in self.__fields__: 16 | if getattr(self, field_name) != getattr(other, field_name): 17 | return False 18 | return True 19 | -------------------------------------------------------------------------------- /src/domain/base/entity.py: -------------------------------------------------------------------------------- 1 | import json 2 | from uuid import uuid4 3 | 4 | from pydantic import Field 5 | 6 | from domain.base.model import Model 7 | 8 | 9 | class Entity(Model): 10 | """Base class for domain entitie objects.""" 11 | 12 | id: str = Field(default_factory=lambda: uuid4().hex) 13 | version: int = 0 14 | 15 | def increase_version(self): 16 | self.version += 1 17 | 18 | def to_dict(self): 19 | return json.loads(self.json()) 20 | 21 | def __str__(self): 22 | return f'{type(self).__name__}' 23 | 24 | def __repr__(self): 25 | return self.__str__() 26 | 27 | 28 | class AggregateRoot(Entity): 29 | """Base class for domain aggregate objects. Consits of 1+ entities""" 30 | -------------------------------------------------------------------------------- /src/domain/base/event.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime as dt 2 | from typing import Any 3 | from uuid import UUID, uuid4 4 | 5 | from pydantic import ConfigDict, Field 6 | 7 | from domain.base.entity import Entity 8 | 9 | 10 | class DomainEvent(Entity): 11 | """Base class for domain events objects""" 12 | 13 | event_name: str 14 | tracker_id: UUID = Field(default_factory=uuid4) 15 | datetime: dt = Field(default_factory=dt.now) 16 | aggregate: Any 17 | 18 | @classmethod 19 | def domain_event_name(cls): 20 | return cls.__name__ 21 | 22 | def __eq__(self, other: 'DomainEvent'): 23 | if type(self) is not type(other): 24 | return False 25 | return self.serialize() == other.serialize() 26 | 27 | model_config = ConfigDict(arbitrary_types_allowed=True) 28 | -------------------------------------------------------------------------------- /src/domain/base/model.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, ConfigDict 2 | 3 | 4 | class Model(BaseModel): 5 | """Base class for model objects""" 6 | 7 | model_config = ConfigDict(extra='allow') 8 | -------------------------------------------------------------------------------- /src/domain/base/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/base/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/base/ports/event_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.base.event import DomainEvent 4 | 5 | 6 | class DomainEventPublisher(metaclass=abc.ABCMeta): 7 | """Base domain event publisher.""" 8 | 9 | @abc.abstractmethod 10 | async def publish(self, event: DomainEvent): 11 | raise NotImplementedError 12 | -------------------------------------------------------------------------------- /src/domain/base/value_object.py: -------------------------------------------------------------------------------- 1 | from typing import Any, TypeVar, Union 2 | 3 | from pydantic import ConfigDict, GetCoreSchemaHandler, ValidationError, ValidationInfo 4 | from pydantic_core import CoreSchema, core_schema 5 | 6 | from domain.base.model import Model 7 | 8 | ImplementationType = TypeVar('ImplementationType', bound='ValueObject') 9 | 10 | 11 | class ValueObject(Model): 12 | """Base class for value objects""" 13 | 14 | def __eq__(self: ImplementationType, other: ImplementationType): 15 | if type(self) is not type(other): 16 | return False 17 | 18 | for attr_name in getattr(self, '__attrs'): 19 | if getattr(self, attr_name) != getattr(other, attr_name): 20 | return False 21 | 22 | return True 23 | 24 | model_config = ConfigDict(arbitrary_types_allowed=True) 25 | 26 | 27 | class StrIdValueObject(str): 28 | """Base class for string value objects""" 29 | 30 | value: Union[str, 'StrIdValueObject'] 31 | 32 | def __init__(self, value: Union[str, 'StrIdValueObject'], field_name: str | None = None): 33 | self.value = value 34 | self.field_name = field_name 35 | 36 | def __repr__(self) -> str: 37 | return str(self) 38 | 39 | def __str__(self) -> str: 40 | return str(self.value) 41 | 42 | @classmethod 43 | def validate( 44 | cls, value: Union[str, 'StrIdValueObject'], info: ValidationInfo 45 | ) -> 'StrIdValueObject': 46 | if isinstance(value, str): 47 | return value 48 | raise ValidationError() 49 | 50 | @classmethod 51 | def __get_pydantic_core_schema__( 52 | cls, source_type: Any, handler: GetCoreSchemaHandler 53 | ) -> CoreSchema: 54 | return core_schema.with_info_after_validator_function( 55 | cls.validate, handler(str), field_name=handler.field_name 56 | ) 57 | -------------------------------------------------------------------------------- /src/domain/delivery/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/delivery/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/delivery/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/adapters/cost_calculator_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.delivery.ports.cost_calculator_interface import ( 2 | DeliveryCostCalculatorAdapterInterface, 3 | ) # noqa: E501 4 | from domain.maps.model.value_objects import Address 5 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 6 | 7 | ORDER_PRICE_THRESHOLD = 500.0 8 | FREE_DISTANCE_THRESHOLD = 10.0 9 | FREE = 0.0 10 | FLAT_PRICE = 50.0 11 | BASE_PRICE = 50.0 12 | FREE_DISTANCE_THRESHOLD = 30.0 13 | PRICE_PER_EXTRA_DISTANCE = 15.0 14 | 15 | 16 | class DeliveryCostCalculatorAdapter(DeliveryCostCalculatorAdapterInterface): 17 | def __init__(self, maps_service: MapsAdapterInterface): 18 | self.maps_service = maps_service 19 | 20 | async def calculate_cost(self, total_product_cost: float, destination: Address) -> float: 21 | if total_product_cost >= ORDER_PRICE_THRESHOLD: 22 | return await self._large_delivery_calculate_cost(destination) 23 | return await self._small_delivery_calculate_cost(destination) 24 | 25 | async def _large_delivery_calculate_cost(self, destination: Address) -> float: 26 | distance_from_warehouse = await self.maps_service.calculate_distance_from_warehouses( 27 | destination 28 | ) 29 | 30 | if distance_from_warehouse <= FREE_DISTANCE_THRESHOLD: 31 | return FREE 32 | 33 | return FLAT_PRICE 34 | 35 | async def _small_delivery_calculate_cost(self, destination: Address) -> float: 36 | distance_from_warehouse = await self.maps_service.calculate_distance_from_warehouses( 37 | destination 38 | ) 39 | 40 | if distance_from_warehouse <= FREE_DISTANCE_THRESHOLD: 41 | return BASE_PRICE 42 | 43 | distance_extra = distance_from_warehouse - FREE_DISTANCE_THRESHOLD 44 | cost_extra = PRICE_PER_EXTRA_DISTANCE * distance_extra 45 | 46 | return BASE_PRICE + cost_extra 47 | -------------------------------------------------------------------------------- /src/domain/delivery/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/delivery/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/delivery/ports/cost_calculator_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.maps.model.value_objects import Address 4 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 5 | 6 | 7 | class DeliveryCostCalculatorAdapterInterface(abc.ABC): 8 | @abc.abstractmethod 9 | def __init__(self, maps_service: MapsAdapterInterface): 10 | raise NotImplementedError 11 | 12 | @abc.abstractmethod 13 | async def calculate_cost(self, total_product_cost: float, destination: Address) -> float: 14 | raise NotImplementedError 15 | 16 | @abc.abstractmethod 17 | async def _large_delivery_calculate_cost(self, destination: Address) -> float: 18 | raise NotImplementedError 19 | 20 | @abc.abstractmethod 21 | async def _small_delivery_calculate_cost(self, destination: Address) -> float: 22 | raise NotImplementedError 23 | -------------------------------------------------------------------------------- /src/domain/maps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/maps/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/maps/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/adapters/google_maps_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.maps.model.value_objects import Address 2 | from domain.maps.ports.maps_adapter_interface import MapsAdapterInterface 3 | 4 | 5 | class GoogleMapsAdapter(MapsAdapterInterface): 6 | async def calculate_distance_from_warehouses(self, destination: Address) -> float: 7 | house_number = str(destination.house_number).split('/', maxsplit=1)[0] 8 | return float(house_number) 9 | -------------------------------------------------------------------------------- /src/domain/maps/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/maps/model/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/model/value_objects.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | from pydantic import validator 4 | 5 | from domain.base.value_object import ValueObject 6 | 7 | 8 | class StatesEnum(str, Enum): 9 | RS: str = 'Rio Grande do Sul' 10 | SP: str = 'São Paulo' 11 | SC: str = 'Santa Catarina' 12 | 13 | @classmethod 14 | def has_value(cls, value): 15 | return value in cls._member_map_.values() 16 | 17 | 18 | class State(ValueObject): 19 | enum: str = StatesEnum 20 | 21 | def states(self) -> bool: 22 | return self.value in [state.value for state in StatesEnum] 23 | 24 | @validator('enum', check_fields=False) 25 | def validate(cls, value): 26 | if not StatesEnum.has_value(value): 27 | raise ValueError(f'State named "{value}" not exists') 28 | return value 29 | 30 | 31 | class Address(ValueObject): 32 | house_number: str 33 | road: str 34 | sub_district: str 35 | district: str 36 | state: str 37 | postcode: str 38 | country: str 39 | 40 | def states(self) -> bool: 41 | return self.state.states() 42 | -------------------------------------------------------------------------------- /src/domain/maps/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/maps/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/maps/ports/maps_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.maps.model.value_objects import Address 4 | 5 | 6 | class MapsAdapterInterface(abc.ABC): 7 | @abc.abstractmethod 8 | async def calculate_distance_from_warehouses(self, destination: Address) -> float: 9 | raise NotImplementedError 10 | -------------------------------------------------------------------------------- /src/domain/order/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/__init__.py -------------------------------------------------------------------------------- /src/domain/order/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/order/adapters/kafka_publisher_adapter.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from aiokafka import AIOKafkaProducer 4 | 5 | from domain.base.event import DomainEvent 6 | from domain.order.ports.event_publisher_interface import EventPublisherInterface 7 | 8 | 9 | class KafkaEventPublisher(EventPublisherInterface): 10 | def __init__(self, config: dict): 11 | self.config = config 12 | self.producer = None 13 | 14 | async def _initialize_producer(self): 15 | if self.producer is None: 16 | self.producer = AIOKafkaProducer(loop=asyncio.get_event_loop(), **self.config) 17 | await self.producer.start() 18 | 19 | async def publish_event(self, event: DomainEvent): 20 | await self._initialize_producer() 21 | await self.producer.send_and_wait(event.event_name, event.json().encode('utf-8')) 22 | 23 | async def close(self): 24 | if self.producer is not None: 25 | await self.producer.stop() 26 | self.producer = None 27 | -------------------------------------------------------------------------------- /src/domain/order/adapters/mongo_db_connector_adapter.py: -------------------------------------------------------------------------------- 1 | import motor.motor_asyncio 2 | import pymongo 3 | 4 | from domain.order.ports.store_connector_adapter_interface import StoreConnectorAdapterInterface 5 | 6 | 7 | class MongoDBAdapterException(Exception): 8 | pass 9 | 10 | 11 | class AsyncMongoDBConnectorAdapter(StoreConnectorAdapterInterface): 12 | def __init__(self, connection_str: str, database_name: str, server_timeout: int = 60000): 13 | self.connection_str = connection_str 14 | self.database_name = database_name 15 | self.server_timeout = server_timeout 16 | 17 | async def get_connection(self): 18 | client = motor.motor_asyncio.AsyncIOMotorClient( 19 | self.connection_str, serverSelectionTimeoutMS=self.server_timeout 20 | ) 21 | try: 22 | # creating a reference to a database 23 | connection = client[self.database_name] 24 | except pymongo.errors.ServerSelectionTimeoutError as exc: 25 | raise MongoDBAdapterException( 26 | 'Unable to connect to the server: server selection timeout' 27 | ) from exc 28 | except pymongo.errors.ConnectionFailure as exc: 29 | raise MongoDBAdapterException( 30 | 'Unable to connect to the server: connection failure' 31 | ) from exc 32 | 33 | return connection 34 | -------------------------------------------------------------------------------- /src/domain/order/adapters/order_event_publisher_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.base.event import DomainEvent 2 | from domain.base.ports.event_adapter_interface import DomainEventPublisher 3 | from domain.order.ports.event_publisher_interface import EventPublisherInterface 4 | from domain.order.ports.order_event_store_repository_interface import ( 5 | OrderEventStoreRepositoryInterface, 6 | ) 7 | 8 | 9 | class OrderEventPublisher(DomainEventPublisher): 10 | def __init__( 11 | self, 12 | repository: OrderEventStoreRepositoryInterface, 13 | publisher: EventPublisherInterface, 14 | ): 15 | self.repository = repository 16 | self.publisher = publisher 17 | 18 | async def publish(self, event: DomainEvent) -> None: 19 | await self.repository.save(event) 20 | await self.publisher.publish_event(event) 21 | -------------------------------------------------------------------------------- /src/domain/order/controllers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/controllers/__init__.py -------------------------------------------------------------------------------- /src/domain/order/controllers/order_controller.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, HTTPException, Request 2 | 3 | from domain.order.dtos.order_dtos import ( 4 | OrderCreateRequest, 5 | OrderCreateResponse, 6 | OrderDetail, 7 | OrderStatus, 8 | OrderUpdateStatusRequest, 9 | OrderUpdateStatusResponse, 10 | ) 11 | from domain.order.exceptions.order_exceptions import ( 12 | OrderAlreadyCancelledException, 13 | OrderAlreadyPaidException, 14 | PaymentNotVerifiedException, 15 | ) 16 | from domain.order.model.value_objects import BuyerId, OrderId 17 | from domain.order.ports.order_mediator_interface import OrderMediatorInterface 18 | 19 | 20 | class OrderController: 21 | def __init__(self, order_mediator: OrderMediatorInterface): 22 | self.service = order_mediator 23 | self.router = APIRouter() 24 | self.router.add_api_route( 25 | '/', self.create_order, methods=['POST'], response_model=OrderCreateResponse 26 | ) # noqa: E501 27 | self.router.add_api_route( 28 | '/{order_id}', self.get_order, methods=['GET'], response_model=OrderDetail 29 | ) # noqa: F541 30 | self.router.add_api_route( 31 | '/{order_id}', 32 | self.update_order, 33 | methods=['PATCH'], 34 | response_model=OrderUpdateStatusResponse, 35 | ) # noqa: F541 36 | 37 | async def create_order(self, request: Request, order: OrderCreateRequest): 38 | buyer_id = BuyerId(order.buyer_id) 39 | order_id = await self.service.create_new_order(buyer_id, order.items, order.destination) 40 | return OrderCreateResponse(order_id=str(order_id)) 41 | 42 | async def get_order(self, request: Request, order_id): 43 | order = await self.service.get_order_from_id(order_id=order_id) 44 | return OrderDetail.from_order(order) 45 | 46 | async def update_order( 47 | self, request: Request, order_id, order_status: OrderUpdateStatusRequest 48 | ): 49 | order_id = OrderId(order_id) 50 | 51 | if order_status.status == OrderStatus.paid: 52 | await self._pay_order(order_id) 53 | order = OrderUpdateStatusResponse(order_id=str(order_id), status='paid') 54 | elif order_status.status == OrderStatus.cancelled: 55 | await self._cancel_order(order_id) 56 | order = OrderUpdateStatusResponse(order_id=str(order_id), status='cancelled') 57 | else: 58 | error_detail = f"Cannot update Order's status to {order_status.status}" 59 | raise HTTPException(status_code=403, detail=error_detail) 60 | return order 61 | 62 | async def _pay_order(self, order_id: OrderId): 63 | try: 64 | return await self.service.pay_order(order_id) 65 | except OrderAlreadyCancelledException as e: 66 | error_detail = "Cannot pay for Order when it's already cancelled" 67 | raise HTTPException(status_code=409, detail=error_detail) from e 68 | except OrderAlreadyPaidException as e: 69 | error_detail = "Cannot pay for Order when it's already paid" 70 | raise HTTPException(status_code=409, detail=error_detail) from e 71 | except PaymentNotVerifiedException as e: 72 | error_detail = 'Payment verification failed' 73 | raise HTTPException(status_code=403, detail=error_detail) from e 74 | 75 | async def _cancel_order(self, order_id: OrderId): 76 | try: 77 | return await self.service.cancel_order(order_id) 78 | except OrderAlreadyCancelledException as e: 79 | error_detail = "Cannot cancel Order when it's already cancelled" 80 | raise HTTPException(status_code=409, detail=error_detail) from e 81 | except OrderAlreadyPaidException as e: 82 | error_detail = "Cannot cancel Order when it's already paid" 83 | raise HTTPException(status_code=409, detail=error_detail) from e 84 | -------------------------------------------------------------------------------- /src/domain/order/dtos/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/dtos/__init__.py -------------------------------------------------------------------------------- /src/domain/order/dtos/order_dtos.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from enum import Enum 3 | 4 | from bson import ObjectId 5 | from pydantic import ConfigDict 6 | 7 | from domain.base.dto import DataTransferObject 8 | from domain.order.model.entities import Order 9 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem 10 | from domain.payment.model.value_objects import PaymentId 11 | 12 | 13 | class Address(DataTransferObject): 14 | house_number: str 15 | road: str 16 | sub_district: str 17 | district: str 18 | state: str 19 | postcode: str 20 | country: str 21 | 22 | model_config = ConfigDict( 23 | json_schema_extra={ 24 | 'example': { 25 | 'house_number': '70', 26 | 'road': 'Rua Afonso Charlier', 27 | 'sub_district': 'SUB_DISTRICT', 28 | 'district': 'Porto Alegre', 29 | 'state': 'RS', 30 | 'postcode': '92310010', 31 | 'country': 'Brazil', 32 | } 33 | } 34 | ) 35 | 36 | 37 | class OrderCreateRequest(DataTransferObject): 38 | buyer_id: BuyerId 39 | items: list[OrderItem] 40 | destination: Address 41 | 42 | model_config = ConfigDict( 43 | arbitrary_types_allowed=True, 44 | json_schema_extra={ 45 | 'example': { 46 | 'buyer_id': str(ObjectId()), 47 | 'items': [{'product_id': '63ce91dc6a4c8287bfdde046', 'amount': 200}], 48 | 'destination': Address.schema()['example'], 49 | } 50 | }, 51 | ) 52 | 53 | 54 | class OrderCreateResponse(DataTransferObject): 55 | order_id: OrderId 56 | 57 | model_config = ConfigDict( 58 | json_schema_extra={ 59 | 'example': { 60 | 'order_id': str(ObjectId()), 61 | } 62 | } 63 | ) 64 | 65 | 66 | class OrderStatus(str, Enum): 67 | waiting: str = 'waiting' 68 | paid: str = 'paid' 69 | cancelled: str = 'cancelled' 70 | 71 | 72 | class OrderUpdateStatusRequest(DataTransferObject): 73 | status: str 74 | 75 | model_config = ConfigDict(json_schema_extra={'example': {'status': 'paid'}}) 76 | 77 | 78 | class OrderUpdateStatusResponse(DataTransferObject): 79 | order_id: OrderId 80 | status: OrderStatus 81 | 82 | model_config = ConfigDict( 83 | json_schema_extra={ 84 | 'example': { 85 | 'order_id': str(ObjectId()), 86 | 'status': 'paid', 87 | } 88 | } 89 | ) 90 | 91 | @classmethod 92 | def from_order_id(cls, order_id: OrderId): 93 | return cls(order_id=str(order_id)) 94 | 95 | 96 | class OrderDetail(DataTransferObject): 97 | buyer_id: BuyerId 98 | payment_id: PaymentId 99 | items: list[OrderItem] 100 | product_cost: float 101 | delivery_cost: float 102 | total_cost: float 103 | status: OrderStatus 104 | 105 | model_config = ConfigDict( 106 | json_schema_extra={ 107 | 'example': { 108 | 'buyer_id': str(ObjectId()), 109 | 'payment_id': str(uuid.uuid4()), 110 | 'items': [{'product_id': '63ce91dc6a4c8287bfdde046', 'amount': 200}], 111 | 'product_cost': 424.2, 112 | 'delivery_cost': 42.42, 113 | 'total_cost': 466.62, 114 | 'status': 'waiting', 115 | } 116 | } 117 | ) 118 | 119 | @classmethod 120 | def from_order(cls, order: Order): 121 | return cls(**order.dict(), total_cost=order.total_cost) 122 | -------------------------------------------------------------------------------- /src/domain/order/exceptions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/exceptions/__init__.py -------------------------------------------------------------------------------- /src/domain/order/exceptions/order_exceptions.py: -------------------------------------------------------------------------------- 1 | from exceptions import CommonException 2 | 3 | 4 | class OrderAlreadyCancelledException(CommonException): 5 | """Exception raised when attempting to cancel an order that has already been cancelled.""" 6 | 7 | 8 | class OrderAlreadyPaidException(CommonException): 9 | """Exception raised when attempting to pay for an order that has already been paid.""" 10 | 11 | 12 | class PaymentNotVerifiedException(CommonException): 13 | """Exception raised when a payment is not verified for an order.""" 14 | 15 | 16 | class EntityNotFound(CommonException): 17 | """Exception raised when attempting to access an entity that does not exist.""" 18 | 19 | 20 | class EntityOutdated(CommonException): 21 | """Exception raised when attempting to perform an operation on an outdated entity.""" 22 | 23 | 24 | class PersistenceError(CommonException): 25 | """Exception raised for errors related to persistence (e.g., database errors).""" 26 | -------------------------------------------------------------------------------- /src/domain/order/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/model/__init__.py -------------------------------------------------------------------------------- /src/domain/order/model/entities.py: -------------------------------------------------------------------------------- 1 | from domain.base.entity import AggregateRoot 2 | from domain.order.exceptions.order_exceptions import ( 3 | OrderAlreadyCancelledException, 4 | OrderAlreadyPaidException, 5 | PaymentNotVerifiedException, 6 | ) 7 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem, OrderStatus 8 | from domain.payment.model.value_objects import PaymentId 9 | 10 | 11 | class Order(AggregateRoot): 12 | """Represents an order in the system.""" 13 | 14 | order_id: OrderId 15 | buyer_id: BuyerId 16 | items: list[OrderItem] 17 | product_cost: float 18 | delivery_cost: float 19 | payment_id: PaymentId 20 | status: OrderStatus = OrderStatus(OrderStatus.Enum.WAITING) 21 | version: int = 0 22 | 23 | def pay(self, is_payment_verified: bool): 24 | if self.is_cancelled(): 25 | raise OrderAlreadyCancelledException(detail="Order's already cancelled") 26 | if self.is_paid(): 27 | raise OrderAlreadyPaidException(detail="Order's already paid") 28 | if not is_payment_verified: 29 | raise PaymentNotVerifiedException(detail=f'Payment {self.payment_id} must be verified') 30 | 31 | self.status = OrderStatus(OrderStatus.Enum.PAID) 32 | 33 | def cancel(self): 34 | if self.is_cancelled(): 35 | raise OrderAlreadyCancelledException(detail="Order's already cancelled") 36 | if self.is_paid(): 37 | raise OrderAlreadyPaidException(detail="Order's already paid") 38 | 39 | self.status = OrderStatus(OrderStatus.Enum.CANCELLED) 40 | 41 | def is_waiting(self) -> bool: 42 | return self._get_order_status(self.status).is_waiting() 43 | 44 | def is_paid(self) -> bool: 45 | return self._get_order_status(self.status).is_paid() 46 | 47 | def is_cancelled(self) -> bool: 48 | return self._get_order_status(self.status).is_cancelled() 49 | 50 | def _get_order_status(self, value): 51 | return OrderStatus(value) 52 | 53 | @property 54 | def total_cost(self) -> float: 55 | return self.product_cost + self.delivery_cost 56 | -------------------------------------------------------------------------------- /src/domain/order/model/events.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | from pydantic import Field 4 | 5 | from domain.base.event import DomainEvent 6 | 7 | 8 | class OrderEventName(Enum): 9 | 10 | CREATED = 'payment_order_created' 11 | CANCELLED = 'payment_order_cancelled' 12 | PAID = 'payment_order_paid' 13 | 14 | 15 | class OrderCreated(DomainEvent): 16 | event_name: str = Field(OrderEventName.CREATED.value) 17 | 18 | 19 | class OrderPaid(DomainEvent): 20 | event_name: str = Field(OrderEventName.PAID.value) 21 | 22 | 23 | class OrderCancelled(DomainEvent): 24 | event_name: str = Field(OrderEventName.CANCELLED.value) 25 | 26 | 27 | class OrderEvent(Enum): 28 | """Domain Event raised for special order use cases""" 29 | 30 | CREATED = 'CREATED' 31 | CANCELLED = 'CANCELLED' 32 | PAID = 'PAID' 33 | -------------------------------------------------------------------------------- /src/domain/order/model/value_objects.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Union 3 | 4 | from pydantic import ValidationInfo, field_validator 5 | 6 | from domain.base.value_object import StrIdValueObject, ValueObject 7 | 8 | 9 | class OrderStatusEnum(str, Enum): 10 | WAITING = 'waiting' 11 | PAID = 'paid' 12 | CANCELLED = 'cancelled' 13 | 14 | def __str__(self) -> str: 15 | return self.value 16 | 17 | @classmethod 18 | def has_value(cls, value): 19 | return value in cls._member_map_.values() 20 | 21 | 22 | class BuyerId(StrIdValueObject): 23 | value: Union[str, 'BuyerId'] 24 | 25 | 26 | class OrderItem(ValueObject): 27 | product_id: str 28 | amount: int 29 | 30 | @field_validator('amount') 31 | @classmethod 32 | def validate(cls, value: str | int, info: ValidationInfo) -> 'OrderStatusEnum': 33 | if value < 0: 34 | raise ValueError(f'Expected Order.amount >= 0, got {value}') 35 | return value 36 | 37 | 38 | class OrderId(StrIdValueObject): 39 | value: Union[str, 'OrderId'] 40 | 41 | 42 | class OrderStatus(StrIdValueObject): 43 | Enum = OrderStatusEnum 44 | 45 | def is_waiting(self) -> bool: 46 | return self.value == OrderStatus.Enum.WAITING 47 | 48 | def is_paid(self) -> bool: 49 | return self.value == OrderStatus.Enum.PAID 50 | 51 | def is_cancelled(self) -> bool: 52 | return self.value == OrderStatus.Enum.CANCELLED 53 | 54 | @field_validator('value') 55 | @classmethod 56 | def validate(cls, value: str | OrderStatusEnum, info: ValidationInfo) -> 'OrderStatusEnum': 57 | if not OrderStatusEnum.has_value(value): 58 | raise ValueError(f'OrderStatus named "{value}" not exists') 59 | return value 60 | -------------------------------------------------------------------------------- /src/domain/order/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/order/ports/event_publisher_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.base.event import DomainEvent 4 | 5 | 6 | class EventPublisherInterface(abc.ABC): 7 | """interface for publishing domain events.""" 8 | 9 | @abc.abstractmethod 10 | async def publish_event(self, event: DomainEvent) -> None: 11 | raise NotImplementedError 12 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_aggregate_repository_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.order.model.entities import Order 4 | from domain.order.model.value_objects import OrderId 5 | from domain.order.ports.store_connector_adapter_interface import StoreConnectorAdapterInterface 6 | 7 | 8 | class OrderAggregateRepositoryInterface(abc.ABC): 9 | """Interface for managing order aggregates.""" 10 | 11 | def __init__(self, db_connection: StoreConnectorAdapterInterface, collection_name: str): 12 | self.db_connection = db_connection 13 | self.collection_name = collection_name 14 | 15 | @abc.abstractmethod 16 | async def from_id(self, order_id: OrderId) -> Order | None: 17 | raise NotImplementedError 18 | 19 | @abc.abstractmethod 20 | async def save(self, order: Order) -> None: 21 | raise NotImplementedError 22 | 23 | @abc.abstractmethod 24 | async def delete(self, order_id: OrderId) -> None: 25 | raise NotImplementedError 26 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_command_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.base.ports.event_adapter_interface import DomainEventPublisher 4 | from domain.delivery.ports.cost_calculator_interface import ( 5 | DeliveryCostCalculatorAdapterInterface, 6 | ) # noqa: E501 7 | from domain.maps.model.value_objects import Address 8 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem 9 | from domain.order.ports.order_aggregate_repository_interface import ( 10 | OrderAggregateRepositoryInterface, 11 | ) 12 | from domain.order.ports.order_mediator_interface import AbstractComponent # noqa: E501 13 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface # noqa: E501 14 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface # noqa: E501 15 | 16 | 17 | class OrderCommandInterface(AbstractComponent): 18 | """Interface for command orders.""" 19 | 20 | @abc.abstractmethod 21 | def __init__( 22 | self, 23 | repository: OrderAggregateRepositoryInterface, 24 | payment_service: PaymentAdapterInterface, 25 | product_service: ProductAdapterInterface, 26 | delivery_service: DeliveryCostCalculatorAdapterInterface, 27 | event_publisher: DomainEventPublisher, 28 | ): 29 | raise NotImplementedError 30 | 31 | @abc.abstractmethod 32 | async def create_new_order( 33 | self, order_id: OrderId, buyer_id: BuyerId, items: list[OrderItem], destination: Address 34 | ) -> None: 35 | raise NotImplementedError 36 | 37 | @abc.abstractmethod 38 | async def pay_order(self, order_id: OrderId): 39 | raise NotImplementedError 40 | 41 | @abc.abstractmethod 42 | async def cancel_order(self, order_id: OrderId): 43 | raise NotImplementedError 44 | 45 | @abc.abstractmethod 46 | async def _pay_order_tnx(self, order_id, is_payment_verified): 47 | raise NotImplementedError 48 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_event_store_repository_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.base.entity import AggregateRoot 4 | from domain.base.event import DomainEvent 5 | from domain.order.model.value_objects import OrderId 6 | 7 | 8 | class OrderEventStoreRepositoryInterface(abc.ABC): 9 | """Interface for managing order context events.""" 10 | 11 | @abc.abstractmethod 12 | async def from_id(self, order_id: OrderId) -> AggregateRoot | None: 13 | raise NotImplementedError 14 | 15 | @abc.abstractmethod 16 | async def save(self, event: DomainEvent) -> None: 17 | raise NotImplementedError 18 | 19 | @abc.abstractmethod 20 | async def get_all_events_by_tracker_id(self, tracker_id: str) -> list[DomainEvent]: 21 | raise NotImplementedError 22 | 23 | @abc.abstractmethod 24 | async def get_last_event_version_from_entity(self, order_id: OrderId) -> DomainEvent | None: 25 | raise NotImplementedError 26 | 27 | @abc.abstractmethod 28 | async def rebuild_aggregate_root( 29 | self, event: DomainEvent, aggregate_class: AggregateRoot 30 | ) -> AggregateRoot: 31 | raise NotImplementedError 32 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_mediator_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.maps.model.value_objects import Address 4 | from domain.order.model.entities import Order 5 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem 6 | 7 | 8 | class OrderMediatorInterface(abc.ABC): 9 | """The Mediator interface declares a method used by components to notify the 10 | mediator about various events. The Mediator may react to these events and 11 | pass the execution to other components.""" 12 | 13 | @abc.abstractmethod 14 | async def next_identity(self) -> OrderId: 15 | raise NotImplementedError 16 | 17 | @abc.abstractmethod 18 | async def create_new_order( 19 | self, buyer_id: BuyerId, items: list[OrderItem], destination: Address 20 | ) -> OrderId: 21 | raise NotImplementedError 22 | 23 | @abc.abstractmethod 24 | async def pay_order(self, order_id: OrderId): 25 | raise NotImplementedError 26 | 27 | @abc.abstractmethod 28 | async def cancel_order(self, order_id: OrderId): 29 | raise NotImplementedError 30 | 31 | @abc.abstractmethod 32 | async def get_order_from_id(self, order_id: OrderId) -> Order: 33 | raise NotImplementedError 34 | 35 | 36 | class AbstractComponent(metaclass=abc.ABCMeta): 37 | """The Base Component provides the basic functionality of storing a mediator's 38 | instance inside component objects.""" 39 | 40 | def __init__(self, mediator: OrderMediatorInterface = None) -> None: 41 | self._mediator = mediator 42 | 43 | @property 44 | def mediator(self) -> OrderMediatorInterface: 45 | return self._mediator 46 | 47 | @mediator.setter 48 | def mediator(self, mediator: OrderMediatorInterface) -> None: 49 | self._mediator = mediator 50 | 51 | def __repr__(self): 52 | return type(self).__name__ 53 | -------------------------------------------------------------------------------- /src/domain/order/ports/order_query_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.order.model.entities import Order 4 | from domain.order.model.value_objects import OrderId 5 | from domain.order.ports.order_aggregate_repository_interface import ( 6 | OrderAggregateRepositoryInterface, 7 | ) 8 | from domain.order.ports.order_mediator_interface import AbstractComponent # noqa: E501 9 | 10 | 11 | class OrderQueryInterface(AbstractComponent): 12 | """Interface for querying orders.""" 13 | 14 | @abc.abstractmethod 15 | def __init__(self, repository: OrderAggregateRepositoryInterface): 16 | raise NotImplementedError 17 | 18 | @abc.abstractmethod 19 | async def get_order_from_id(self, order_id: OrderId) -> Order: 20 | raise NotImplementedError 21 | -------------------------------------------------------------------------------- /src/domain/order/ports/store_connector_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | 4 | class StoreConnectorAdapterInterface(abc.ABC): 5 | @abc.abstractmethod 6 | async def get_connection(self): 7 | raise NotImplementedError 8 | -------------------------------------------------------------------------------- /src/domain/order/repositories/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/repositories/__init__.py -------------------------------------------------------------------------------- /src/domain/order/repositories/order_aggregate_cache_repository.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | import aioredis 5 | 6 | from domain.order.exceptions.order_exceptions import ( 7 | EntityNotFound, 8 | EntityOutdated, 9 | PersistenceError, 10 | ) 11 | from domain.order.model.entities import Order 12 | from domain.order.model.value_objects import OrderId 13 | from domain.order.ports.order_aggregate_repository_interface import ( 14 | OrderAggregateRepositoryInterface, 15 | ) 16 | from ports.cache_interface import CacheInterface 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | class OrderAggregateCacheRepository(OrderAggregateRepositoryInterface): 22 | """Repository for storing and retrieving order aggregates.""" 23 | 24 | def __init__(self, cache_adapter: CacheInterface): 25 | self.cache_adapter = cache_adapter 26 | 27 | async def from_id(self, order_id: OrderId) -> Order | None: 28 | try: 29 | logger.info(f'Retrieving order from cache for ID: {order_id}') 30 | key = f'order:{order_id}' 31 | 32 | cached_order = await self.cache_adapter.get(key=key) 33 | 34 | if cached_order: 35 | logger.info(f'Retrieved order from cache for ID: {order_id}') 36 | return Order.parse_obj(cached_order) 37 | 38 | logger.info(f'Order not found in cache for ID: {order_id}') 39 | raise EntityNotFound(f'Order with ID {order_id} not found in cache') 40 | except (json.JSONDecodeError, aioredis.RedisError) as e: 41 | error_message = ( 42 | f'Failed to retrieve order from ' f'cache for ID: {order_id}. Error: {e}' 43 | ) 44 | logger.error(error_message) 45 | raise EntityOutdated(error_message) from e 46 | 47 | async def save(self, order: Order) -> None: 48 | try: 49 | await self.cache_adapter.set(key=f'order:{order.order_id}', data=order.dict()) 50 | logger.info(f'Saved order with ID: {order.order_id} in cache') 51 | except aioredis.RedisError as e: 52 | error_message = ( 53 | f'Failed to persist order with ' f'ID: {order.order_id} in cache. Error: {e}' 54 | ) 55 | logger.error(error_message) 56 | raise PersistenceError(error_message) from e 57 | 58 | async def delete(self, order_id: OrderId) -> None: 59 | try: 60 | await self.cache_adapter.delete(key=f'order:{order_id}') 61 | logger.info(f'Deleted order with ID: {order_id} in cache') 62 | except aioredis.RedisError as e: 63 | error_message = f'Failed to delete order with ' f'ID: {order_id} in cache. Error: {e}' 64 | raise PersistenceError(error_message) from e 65 | -------------------------------------------------------------------------------- /src/domain/order/repositories/order_aggregate_repository.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from domain.order.model.entities import Order 4 | from domain.order.model.value_objects import OrderId 5 | from domain.order.ports.order_aggregate_repository_interface import ( 6 | OrderAggregateRepositoryInterface, 7 | ) 8 | from domain.order.ports.store_connector_adapter_interface import StoreConnectorAdapterInterface 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | class OrderAggregateRepository(OrderAggregateRepositoryInterface): 14 | """Repository for storing and retrieving order aggregates.""" 15 | 16 | def __init__(self, db_connection: StoreConnectorAdapterInterface, collection_name: str): 17 | self.db_connection = db_connection 18 | self.collection_name = collection_name 19 | 20 | async def from_id(self, order_id: OrderId) -> Order | None: 21 | connection = await self.db_connection.get_connection() 22 | document = await connection[self.collection_name].find_one({'_id': order_id}) 23 | if document: 24 | logger.info(f'Retrieved aggregate with ID: {order_id}') 25 | return Order.model_validate(document) 26 | return None 27 | 28 | async def save(self, order: Order) -> None: 29 | connection = await self.db_connection.get_connection() 30 | 31 | # Obtain the current aggregate from the database 32 | current_order = await self.from_id(order.order_id) 33 | 34 | if current_order: 35 | if current_order.version > order.version: 36 | error_message = ( 37 | f'Cannot save the aggregate with ID: {order.order_id}. ' 38 | f'Existing aggregate version {current_order.version} is ' 39 | f'equal or greater than the new version {order.version}.' 40 | ) 41 | raise ValueError(error_message) 42 | 43 | order.version = current_order.version 44 | 45 | order.increase_version() 46 | 47 | try: 48 | await connection[self.collection_name].replace_one( 49 | {'_id': order.order_id}, order.model_dump(), upsert=True 50 | ) 51 | logger.info(f'Successfully saved aggregate with ID: {order.order_id}') 52 | except Exception as e: 53 | logger.error(f'Error saving aggregate with ID: {order.order_id}') 54 | raise e 55 | 56 | async def delete(self, order_id: OrderId) -> None: 57 | connection = await self.db_connection.get_connection() 58 | await connection[self.collection_name].delete_one({'_id': order_id}) 59 | logger.info(f'Deleted aggregate with ID: {order_id}') 60 | -------------------------------------------------------------------------------- /src/domain/order/repositories/order_event_store_repository.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from pydantic import ValidationError 4 | from pymongo.errors import DuplicateKeyError 5 | 6 | from domain.base.event import DomainEvent 7 | from domain.order.model.entities import Order 8 | from domain.order.model.value_objects import OrderId 9 | from domain.order.ports.order_event_store_repository_interface import ( 10 | OrderEventStoreRepositoryInterface, 11 | ) 12 | from domain.order.ports.store_connector_adapter_interface import StoreConnectorAdapterInterface 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | class OrderEventStoreRepository(OrderEventStoreRepositoryInterface): 18 | """ 19 | Repository for storing and retrieving order domain 20 | events using event sourcing. 21 | """ 22 | 23 | def __init__(self, db_connection: StoreConnectorAdapterInterface, collection_name: str): 24 | self.db_connection = db_connection 25 | self.collection_name = collection_name 26 | 27 | async def from_id(self, order_id: OrderId) -> list[DomainEvent] | None: 28 | connection = await self.db_connection.get_connection() 29 | events = [] 30 | result = connection[self.collection_name].find({'aggregate.order_id': order_id}) 31 | events_list = await result.to_list(length=None) 32 | if events_list: 33 | logger.info(f'Retrieved all events for order_id: {order_id}') 34 | events = [DomainEvent.parse_obj(event) for event in events_list] 35 | return events or None 36 | 37 | async def save(self, event: DomainEvent) -> None: 38 | aggregate_root = event.aggregate 39 | 40 | event_old = await self.get_last_event_version_from_entity(aggregate_root.order_id) 41 | if event_old: 42 | aggregate_root_old = Order.model_validate(event_old.aggregate) 43 | 44 | if aggregate_root_old and aggregate_root_old.version > aggregate_root.version: 45 | error_message = ( 46 | f'Aggregate Root version needs to be greater than ' 47 | f'the current one: {aggregate_root.version} > {aggregate_root_old.version}.' 48 | ) 49 | logger.warning(error_message, exc_info=True) 50 | raise ValueError(error_message) 51 | 52 | event.version = event_old.version 53 | event.increase_version() 54 | event.tracker_id = event_old.tracker_id 55 | else: 56 | event.increase_version() 57 | 58 | connection = await self.db_connection.get_connection() 59 | try: 60 | await connection[self.collection_name].insert_one(event.to_dict()) 61 | logger.info(f'Successfully saved event with ID: {event.id}') 62 | except DuplicateKeyError as e: 63 | error_message = f'Duplicate event found with ID: {event.id}' 64 | raise e from e 65 | 66 | async def get_all_events_by_tracker_id(self, tracker_id: str) -> list[DomainEvent]: 67 | connection = await self.db_connection.get_connection() 68 | events = [] 69 | result = connection[self.collection_name].find({'tracker_id': tracker_id}) 70 | events_list = await result.to_list(length=None) 71 | if events_list: 72 | logger.info(f'Retrieved all events for tracker_id: {tracker_id}') 73 | events = [DomainEvent.parse_obj(event) for event in events_list] 74 | return events 75 | 76 | async def get_last_event_version_from_entity(self, order_id: OrderId) -> DomainEvent | None: 77 | connection = await self.db_connection.get_connection() 78 | events = connection[self.collection_name].find( 79 | {'aggregate.order_id': order_id}, sort=[('version', -1)], limit=1 80 | ) 81 | events_list = await events.to_list(length=None) 82 | if events_list: 83 | event = events_list[0] 84 | event.pop('_id', None) 85 | logger.info(f'Retrieved last aggregate version event for order id: {order_id}') 86 | return DomainEvent.parse_obj(event) 87 | return None 88 | 89 | async def rebuild_aggregate_root(self, event: DomainEvent, aggregate_class: Order) -> Order: 90 | try: 91 | aggregate_root = aggregate_class.parse_obj(event.aggregate.dict()) 92 | except ValidationError as e: 93 | logger.error(f'Error rebuilding aggregate root from event: {event.id}') 94 | raise e 95 | logger.info(f'Aggregate root rebuilt successfully from event: {event.id}') 96 | return aggregate_root 97 | -------------------------------------------------------------------------------- /src/domain/order/services/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/order/services/__init__.py -------------------------------------------------------------------------------- /src/domain/order/services/order_command.py: -------------------------------------------------------------------------------- 1 | from domain.base.ports.event_adapter_interface import DomainEventPublisher 2 | from domain.delivery.ports.cost_calculator_interface import DeliveryCostCalculatorAdapterInterface 3 | from domain.maps.model.value_objects import Address 4 | from domain.order.model.entities import Order 5 | from domain.order.model.events import OrderCancelled, OrderCreated, OrderPaid 6 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem 7 | from domain.order.ports.order_aggregate_repository_interface import ( 8 | OrderAggregateRepositoryInterface, 9 | ) 10 | from domain.order.ports.order_command_interface import OrderCommandInterface 11 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface 12 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface 13 | 14 | 15 | class OrderCommand(OrderCommandInterface): 16 | """Handles commands related to order operations, such as creating, 17 | paying, and canceling orders.""" 18 | 19 | def __init__( 20 | self, 21 | repository: OrderAggregateRepositoryInterface, 22 | payment_service: PaymentAdapterInterface, 23 | product_service: ProductAdapterInterface, 24 | delivery_service: DeliveryCostCalculatorAdapterInterface, 25 | event_publisher: DomainEventPublisher, 26 | ): 27 | self.repository = repository 28 | self.payment_service = payment_service 29 | self.product_service = product_service 30 | self.delivery_service = delivery_service 31 | self.event_publisher = event_publisher 32 | 33 | async def create_new_order( 34 | self, order_id: OrderId, buyer_id: BuyerId, items: list[OrderItem], destination: Address 35 | ) -> None: 36 | 37 | product_counts = [(item.product_id, int(item.amount)) for item in items] 38 | total_product_cost = await self.product_service.total_price(product_counts) 39 | payment_id = await self.payment_service.new_payment(total_product_cost) 40 | delivery_cost = await self.delivery_service.calculate_cost(total_product_cost, destination) 41 | 42 | order = Order( 43 | order_id=order_id, 44 | buyer_id=buyer_id, 45 | items=items, 46 | product_cost=float(total_product_cost), 47 | delivery_cost=float(delivery_cost), 48 | payment_id=payment_id, 49 | ) 50 | await self.repository.save(order) 51 | await self.mediator.cache_repository.save(order) 52 | 53 | event = OrderCreated(aggregate=order) 54 | 55 | await self.event_publisher.publish(event) 56 | 57 | async def pay_order(self, order_id: OrderId) -> None: 58 | order = await self.repository.from_id(order_id=order_id) 59 | payment_id = order.payment_id 60 | 61 | is_payment_verified = await self.payment_service.verify_payment(payment_id=payment_id) 62 | await self._pay_order_tnx(order_id, is_payment_verified) 63 | 64 | async def cancel_order(self, order_id: OrderId) -> None: 65 | order = await self.repository.from_id(order_id) 66 | order.cancel() 67 | 68 | await self.repository.save(order) 69 | await self.mediator.cache_repository.save(order) 70 | event = OrderCancelled(aggregate=order) 71 | 72 | await self.event_publisher.publish(event) 73 | 74 | async def _pay_order_tnx(self, order_id, is_payment_verified) -> None: 75 | order = await self.repository.from_id(order_id=order_id) 76 | order.pay(is_payment_verified=is_payment_verified) 77 | 78 | await self.repository.save(order) 79 | await self.mediator.cache_repository.save(order) 80 | event = OrderPaid(aggregate=order) 81 | 82 | await self.event_publisher.publish(event) 83 | -------------------------------------------------------------------------------- /src/domain/order/services/order_mediator.py: -------------------------------------------------------------------------------- 1 | from bson.objectid import ObjectId 2 | 3 | from domain.maps.model.value_objects import Address 4 | from domain.order.model.entities import Order 5 | from domain.order.model.value_objects import BuyerId, OrderId, OrderItem 6 | from domain.order.ports.order_aggregate_repository_interface import ( 7 | OrderAggregateRepositoryInterface, 8 | ) 9 | from domain.order.ports.order_command_interface import OrderCommandInterface # noqa: E501 10 | from domain.order.ports.order_mediator_interface import OrderMediatorInterface # noqa: E501 11 | from domain.order.ports.order_query_interface import OrderQueryInterface # noqa: E501 12 | 13 | 14 | class OrderMediator(OrderMediatorInterface): 15 | """Mediates communication between the order command 16 | and query interfaces.""" 17 | 18 | def __init__( 19 | self, 20 | command: OrderCommandInterface, 21 | query: OrderQueryInterface, 22 | cache_repository: OrderAggregateRepositoryInterface, 23 | ) -> None: 24 | self.cache_repository = cache_repository 25 | self._command = command 26 | self._command.mediator = self 27 | self._query = query 28 | self._query.mediator = self 29 | 30 | async def next_identity(self) -> OrderId: 31 | return OrderId(str(ObjectId())) 32 | 33 | async def create_new_order( 34 | self, buyer_id: BuyerId, items: list[OrderItem], destination: Address 35 | ) -> OrderId: 36 | 37 | order_id = await self.next_identity() 38 | 39 | await self._command.create_new_order( 40 | order_id=order_id, buyer_id=buyer_id, items=items, destination=destination 41 | ) 42 | 43 | return order_id 44 | 45 | async def pay_order(self, order_id: OrderId): 46 | await self._command.pay_order(order_id=order_id) 47 | 48 | async def cancel_order(self, order_id: OrderId): 49 | await self._command.cancel_order(order_id=order_id) 50 | 51 | async def get_order_from_id(self, order_id: OrderId) -> Order: 52 | return await self._query.get_order_from_id(order_id=order_id) 53 | -------------------------------------------------------------------------------- /src/domain/order/services/order_query.py: -------------------------------------------------------------------------------- 1 | from domain.order.exceptions.order_exceptions import EntityNotFound 2 | from domain.order.model.entities import Order 3 | from domain.order.model.value_objects import OrderId 4 | from domain.order.ports.order_aggregate_repository_interface import ( 5 | OrderAggregateRepositoryInterface, 6 | ) 7 | from domain.order.ports.order_query_interface import OrderQueryInterface # noqa: E501 8 | 9 | 10 | class OrderQuery(OrderQueryInterface): 11 | """Handles queries for retrieving order information.""" 12 | 13 | def __init__(self, repository: OrderAggregateRepositoryInterface): 14 | self.repository = repository 15 | 16 | async def get_order_from_id(self, order_id: OrderId) -> Order: 17 | try: 18 | order = await self.mediator.cache_repository.from_id(order_id=order_id) 19 | except EntityNotFound: 20 | order = await self.repository.from_id(order_id) 21 | return order 22 | -------------------------------------------------------------------------------- /src/domain/payment/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/payment/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/payment/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/adapters/paypal_adapter.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | from domain.payment.model.value_objects import PaymentId 4 | from domain.payment.ports.payment_adapter_interface import PaymentAdapterInterface 5 | 6 | 7 | class PayPalPaymentAdapter(PaymentAdapterInterface): 8 | async def new_payment(self, total_price: float) -> PaymentId: 9 | return PaymentId(str(uuid.uuid4())) 10 | 11 | async def verify_payment(self, payment_id: PaymentId) -> bool: 12 | return True 13 | -------------------------------------------------------------------------------- /src/domain/payment/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/payment/model/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/model/value_objects.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | from domain.base.value_object import StrIdValueObject 4 | 5 | 6 | class PaymentId(StrIdValueObject): 7 | value: Union[str, 'PaymentId'] 8 | -------------------------------------------------------------------------------- /src/domain/payment/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/payment/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/payment/ports/payment_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.payment.model.value_objects import PaymentId 4 | 5 | 6 | class PaymentAdapterInterface(abc.ABC): 7 | @abc.abstractmethod 8 | async def new_payment(self, total_price: float) -> PaymentId: 9 | raise NotImplementedError 10 | 11 | @abc.abstractmethod 12 | async def verify_payment(self, payment_id: PaymentId) -> bool: 13 | raise NotImplementedError 14 | -------------------------------------------------------------------------------- /src/domain/product/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/product/__init__.py -------------------------------------------------------------------------------- /src/domain/product/adapters/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/product/adapters/__init__.py -------------------------------------------------------------------------------- /src/domain/product/adapters/product_adapter.py: -------------------------------------------------------------------------------- 1 | from domain.product.model.value_objects import ProductId 2 | from domain.product.ports.product_adapter_interface import ProductAdapterInterface 3 | 4 | 5 | class ProductAdapter(ProductAdapterInterface): 6 | async def total_price(self, product_counts: list[tuple[ProductId, int]]) -> float: 7 | price_list = [12.0 * count for product, count in product_counts] 8 | return float(sum(price_list)) 9 | -------------------------------------------------------------------------------- /src/domain/product/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/product/model/__init__.py -------------------------------------------------------------------------------- /src/domain/product/model/entities.py: -------------------------------------------------------------------------------- 1 | from domain.base.entity import Entity 2 | from domain.product.model.value_objects import ProductId 3 | 4 | 5 | class Product(Entity): 6 | product_id: ProductId 7 | price: float 8 | -------------------------------------------------------------------------------- /src/domain/product/model/value_objects.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | from domain.base.value_object import StrIdValueObject 4 | 5 | 6 | class ProductId(StrIdValueObject): 7 | id: Union[str, 'ProductId'] 8 | -------------------------------------------------------------------------------- /src/domain/product/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/domain/product/ports/__init__.py -------------------------------------------------------------------------------- /src/domain/product/ports/product_adapter_interface.py: -------------------------------------------------------------------------------- 1 | import abc 2 | 3 | from domain.product.model.value_objects import ProductId 4 | 5 | 6 | class ProductAdapterInterface(abc.ABC): 7 | @abc.abstractmethod 8 | async def total_price(self, product_counts: list[tuple[ProductId, int]]) -> float: 9 | raise NotImplementedError 10 | -------------------------------------------------------------------------------- /src/exceptions.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | 4 | class CommonException(Exception): 5 | """Base exception class for all exceptions in this project.""" 6 | 7 | code: int = 400 8 | message: str 9 | detail: Any | None 10 | 11 | def __init__(self, code: int = 400, message: str = 'Bad Request', detail: Any | None = None): 12 | self.code = code 13 | self.message = message 14 | self.detail = detail 15 | 16 | def __str__(self): 17 | return f''' 18 | code: {self.code} 19 | message: {self.message} 20 | detail: {self.detail} 21 | traceback: {self.__traceback__} 22 | ''' 23 | 24 | def to_dict(self): 25 | return { 26 | 'code': self.code, 27 | 'message': self.message, 28 | 'detail': self.detail, 29 | } 30 | -------------------------------------------------------------------------------- /src/ports/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marcosvs98/cqrs-architecture-with-python/aedc37cacc0a1bcee5fd8558b3890fc0a4947c8b/src/ports/__init__.py -------------------------------------------------------------------------------- /src/ports/cache_interface.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class CacheInterface(ABC): 5 | 6 | silent_mode: bool 7 | 8 | def __init__(self, silent_mode: bool): 9 | self.silent_mode = silent_mode 10 | 11 | @abstractmethod 12 | async def get(self, key: str) -> dict | None: 13 | raise NotImplementedError 14 | 15 | @abstractmethod 16 | async def set(self, key: str, data: dict, ttl: int) -> None: 17 | raise NotImplementedError 18 | 19 | @abstractmethod 20 | async def delete(self, key: str) -> None: 21 | raise NotImplementedError 22 | -------------------------------------------------------------------------------- /src/settings.py: -------------------------------------------------------------------------------- 1 | from decouple import config 2 | 3 | APPLICATION_NAME = config('APPLICATION_NAME', default='ordering-service') 4 | PORT = config('PORT', default=8090, cast=int) 5 | UVICORN_WORKERS = config('UVICORN_WORKERS', default=1, cast=int) 6 | 7 | 8 | REDIS_HOST = config('REDIS_HOST', default='ordering-redis') 9 | REDIS_PORT = config('REDIS_PORT', default=6379, cast=int) 10 | REDIS_PASSWORD = config('REDIS_PASSWORD', None) 11 | REDIS_SSL = config('REDIS_SSL', default=False, cast=bool) 12 | CACHE_SILENT_MODE = config('CACHE_SILENT_MODE', default=False, cast=bool) 13 | 14 | 15 | ORDER_REPOSITORY_CONNECTION = config( 16 | 'ORDER_REPOSITORY_CONNECTION', 17 | default='mongodb://admin:root@order-aggregate-repository_mongo-db:27017/', 18 | ) 19 | ORDER_REPOSITORY_DATABASE_NAME = config( 20 | 'ORDER_REPOSITORY_DATABASE_NAME', default='order_aggregates' 21 | ) 22 | ORDER_REPOSITORY_COLLECTION_NAME = config( 23 | 'ORDER_REPOSITORY_COLLECTION_NAME', default='order_aggregates' 24 | ) 25 | 26 | ORDER_EVENT_STORE_CONNECTION = config( 27 | 'ORDER_EVENT_STORE_CONNECTION', 28 | default='mongodb://admin:root@ordering-event-store-repository_mongo-db:27017/', 29 | ) 30 | ORDER_EVENT_STORE_DATABASE_NAME = config('ORDER_EVENT_STORE_DATABASE_NAME', default='order_events') 31 | ORDER_EVENT_STORE_COLLECTION_NAME = config( 32 | 'ORDER_EVENT_STORE_COLLECTION_NAME', default='ordering_events' 33 | ) 34 | 35 | KAFKA_SETTINGS = {'bootstrap_servers': 'ordering-event-bus-kafka:9092'} 36 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Set default environment variables 4 | export ENVIRONMENT=${ENVIRONMENT:-development} 5 | export PORT=${PORT:-8000} 6 | export WORKERS=${WORKERS:-1} 7 | export LOG_LEVEL=${LOG_LEVEL:-INFO} 8 | export TIMEOUT=${TIMEOUT:-120} 9 | 10 | echo "Rodando o servidor" 11 | uvicorn src.app:create_app --factory \ 12 | --host 0.0.0.0 --port 8000 \ 13 | --log-level debug \ 14 | --reload 15 | --------------------------------------------------------------------------------