iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐁

Implementation Example: Applying DDD to File-Based Batch Processing in Python

に公開

Background

Due to various circumstances, there are cases where we cannot directly access the database containing the data required for processing, and instead, the data is shared via files. In such cases, the results of the processing are also often shared with other systems by outputting them as files.

While file-based integration is a long-standing and common method, the implementation tends to be procedural. Consequently, aspects like "where to get the file from," "how to process it," and "where to share the results" can be difficult for new members to understand. This often leads to missed steps during maintenance or operational updates, resulting in (minor) bugs or regressions.

Therefore, I tried to shift from a procedural implementation to one more focused on the objects involved in the processing—similar to DDD—and translate it into more object-oriented code. You could say I'm turning my own tacit knowledge about file integration batches into explicit knowledge in the form of code. While it requires the ability to read code, it should help new members grasp the specifications more easily and enable safer and faster modifications.

Reading "The Principles of System Design for the Field: Object-Oriented Practical Techniques for Making Changes Easy and Safe" was a major motivation for this.

https://www.amazon.co.jp/dp/B073GSDBGT/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1

The reason I'm using Python is that a predecessor project involved quite simple batch processing where Java wasn't necessary, so I used Python, and subsequent projects followed suit.

Pros and Cons of File-Based Integration

As a bit of a tangent, let me organize the advantages and disadvantages of file-based integration. Most of the disadvantages can be largely avoided by refining the implementation. (Conversely, if you do it without knowing them, you will run into problems.)

Pros

  • Loose coupling with the integrated system
    • Once the file is output, processing can start or continue even if the other system is down
  • No need for servers or mocks equivalent to the integrated system in the development environment
    • It can be run simply by placing files in a designated location
  • It can handle cases where the timing of the integration is irregular by periodically checking for files (e.g., every 5 minutes)

Cons

  • Trouble is likely to occur unless the responsibilities of the side placing the files and the side collecting them are clearly defined
    • Example
      • The disk becomes full because files remain on the integrated system
      • Picking up a file that is still being created
  • You will run into issues before processing even begins if file specifications such as line endings and character encoding are not clearly decided
  • If the file size is large, simply moving the file takes time
    • This often makes production tasks take longer
  • If the file size is large, disk or memory space is likely to overflow unless managed carefully
    • Handle files while they are gzip-compressed
    • In some cases, OS commands are more efficient than (naive) code

Process Overview

This process takes order history data with purchase amounts and entry data, and awards points equal to 1% of the purchase amount to those who have entered.

To give the process a certain degree of complexity, we exchange flat CSVs with the integrated system, while we process them in a gzip-compressed state on our end. Ideally, we would receive files already gzip-compressed. If that's not possible for various reasons, it's a good idea to compress them while copying them to our server.

Side Placing the Files

  1. Place the files required for processing (input files) in the integrated system's location.
  2. Place a trigger file to signal the completion of file placement.

Side Collecting the Files (The Part Implemented as a Batch)

  1. Periodically check (using cron, etc.) if a trigger file exists in the integrated system's location.
  2. If no trigger file exists, do nothing.
  3. If a trigger file exists, start processing.
    4. Delete the trigger file.
    5. Gzip-compress the input files and move them to the working directory.
    6. Create result files in a gzip-compressed state in the working directory based on the input files.
    7. Copy the result files to the integrated system's location while decompressing them.
    8. Move the input and result files to the backup directory.
    9. Delete the working directory.

Sample Code

https://github.com/JunNakamura/file-base-python-batch

Package Structure

I'm doing this in almost the same spirit as Java. Since Python files are treated as modules, unlike Java, it shouldn't be necessary to have one class per file. However, I tried to basically do one class per file because it makes the specifications easier to grasp from the file list and should make differences easier to see in Git management.

└── src
    ├── app_name.py
    ├── batch
    │   ├── batch.py
    │   ├── file_base_batch.py
    │   └── file_lock.py
    ├── decorator
    │   └── logging.py
    ├── domain
    │   ├── backup
    │   │   └── backup_directory.py
    │   ├── input
    │   │   ├── entry_file.py
    │   │   ├── input_directory.py
    │   │   ├── input_file.py
    │   │   └── order_history_file.py
    │   ├── output
    │   │   ├── output_directory.py
    │   │   └── result_file.py
    │   └── work
    │       ├── work_directory.py
    │       ├── work_entry_file.py
    │       ├── work_input_file.py
    │       └── work_order_history_file.py
    ├── logging.yaml
    ├── main.py
    ├── mixin
    │   └── direcotry
    │       ├── existence_assured_directory.py
    │       └── removable_directory.py
    └── setup.py
Package Name Overview
batch A collection of classes representing batches with exclusive control using lock files
decorator A collection of decorators, such as for measuring method execution time
domain A collection of classes representing files and directories, which are at the heart of the process
mixin A collection of traits and abstract classes used to represent the properties of files and directories

Domain in File-Integrated Batches

At this point, focusing on the "files used for processing" and the "directories where they are placed" seems to work well. By extracting these as classes, it becomes easier to express the movement of files.

  • Input Directory: InputDirectory
  • Input File: InputFile

By breaking down the classes this way, the structure becomes clearer (it is partly through defining these classes that we are able to use such terminology).

Directory movement looks like this:

The relationship between input files -> working files -> result files can also be easily expressed by extracting classes as follows:

The implementation of the series of processes is as follows:

    def execute(self):
        input_directory = InputDirectory()
        if not input_directory.trigger_file.exists():
            logger.info(f'trigger file({input_directory.trigger_file}) does not exist. nothing to do.')
            return
        input_directory.trigger_file.unlink()
        logger.info('start process since trigger file exists')
        order_history_file = OrderHistoryFile(input_directory)
        entry_file = EntryFile(input_directory)
        input_files = [order_history_file, entry_file]
        for input_file in input_files:
            logger.info(f'checksum of {input_file.name}: {input_file.md5_checksum()}')

        work_directory = WorkDirectory()
        work_order_history_file = WorkOrderHistoryFile(order_history_file, work_directory)
        work_entry_file = WorkEntryFile(entry_file, work_directory)

        output_directory = OutputDirectory()
        output_directory.trigger_file.unlink(missing_ok=True)

        result_file = ResultFile(output_directory, work_directory)
        result_file.create(work_order_history_file, work_entry_file)
        output_directory.trigger_file.touch()

        backup_directory = BackupDirectory()
        work_directory.move_files_to(backup_directory)
        work_directory.remove_if_exists()

Properties of Directories

Regardless of the timing, files are placed under the directories involved in the processing. Therefore, the "existence of the directory" must be guaranteed. While creating a directory itself is easy using Path.mkdir, calling it frequently is difficult to manage. If someone who doesn't know the background modifies the code, the directory creation part is likely to be missed.

To address this, I decided to introduce an abstract class called "Existence-Assured Directory" (ExistenceAssuredDirectory). The directory is created in the constructor of this class. Therefore, by inheriting from this class, the directory is created at the moment the instance is generated, without having to explicitly think about it.

from abc import ABC
from pathlib import Path


class ExistenceAssuredDirectory(ABC):

    def __init__(self, *segments: str):
        self.__path = Path(*segments)
        self.__path.mkdir(exist_ok=True, parents=True)
        assert self.__path.exists()
        assert self.__path.is_dir()

    @property
    def path(self):
        return self.__path

Although not implemented in this sample code, if you want to perform tasks like "monthly rotation of backup directories such as backup/{yyyymm} and deleting directories from one month ago," it would be easier to implement by providing an abstract class called "Removable Directory" (RemovableDirectory).

Useful Features from a Maintenance and Operation Perspective

In practice, mechanisms for making code easier to edit and for executing batches safely are required.
While there are various other considerations, the following features have been included in the sample code:

  1. Exclusive control using lock files
    2. To prevent another process from starting while the current one is running.
  2. Externalizing log configuration to YAML.
  3. Application logger
    4. By making each file's logger a child of the application logger, editing the log configuration file is generally unnecessary even when adding or editing classes/packages.
  4. Decorator for logging method execution time.

Summary

I believe that DDD techniques are difficult to adopt unless the web application is of a certain scale (e.g., it is monetized or handles critical business operations). Furthermore, most literature seems to assume web application scenarios.
Implementing this for batch processing involved some "birth pangs" in determining how to structure the classes. However, this process allowed me to deepen my understanding and improve my proficiency with Python.
In the case of batch processing, it's actually easier to experiment with DDD because you can establish a Ubiquitous Language even without necessarily involving the business side.

To be honest, I feel that static typing languages like Java are better suited for what I am trying to achieve here. Although Python supports Generics, it feels somewhat more cumbersome to write compared to Java. Since I will likely need to continue with this approach for a while, I plan to eventually compile these successful patterns into a book.

Discussion