สำหรับ Agile Project Management Context นั้น จำเป็นต้องจัดการ pool ของ Scrum product owners และ team members ของแต่ละ tenant ที่สมัครใช้บริการ และในเวลาใดก็ตามที่ product owner สร้าง product ใหม่ขึ้นมา มันก็จะ assign สมาชิกเข้าไปในทีม แอปพลิเคชันจัดการโปรเจกต์แบบ Scrum จะรู้ได้อย่างไรว่าใครทำหน้าที่ในแต่ละ role เหล่านี้ คำตอบก็คือ มันจะไม่จัดการเรื่องนี้เพียงลำพัง

ที่จริงแล้ว Agile Project Management Context จะปล่อยให้บทบาทเหล่านี้ถูกจัดการโดย Identity and Access Context ซึ่งเป็นตัวเลือกที่เป็นธรรมชาติและลงตัวดี ในระบบนั้น แต่ละ tenant ที่สมัครใช้บริการ Scrum จะมี Role ถูกสร้างขึ้นมาสอง instance ได้แก่ ScrumProductOwner และ ScrumTeamMember ซึ่ง User ที่ต้องเล่นหนึ่งในบทบาทเหล่านี้ก็จะถูก assign เข้ากับมัน นี่คือ method ของ Application Service ใน Identity and Access Context ที่คอยจัดการงานในการ assign User ให้กับ Role :

package com.saasovation.identityaccess.application;
...
public class AccessService ... {
    ...
    @Transactional
    public void assignUserToRole(AssignUserToRoleCommand aCommand) {

        TenantId tenantId =
                new TenantId(aCommand.getTenantId());

        User user =
                this.userRepository
                    .userWithUsername(
                            tenantId,
                            aCommand.getUsername());

        if (user != null) {
            Role role =
                    this.roleRepository
                        .roleNamed(
                                tenantId,
                                aCommand.getRoleName());

            if (role != null) {
                role.assignUser(user);
            }
        }
    }
    ...
}

เยี่ยมมาก แต่สิ่งนี้จะช่วยให้ Agile Project Management Context รู้ได้อย่างไรว่าใครอยู่ในบทบาท ScrumTeamMember หรือ ScrumProductOwner ? นี่คือวิธีการ เมื่อ method assignUser() ของ Role ทำงานเสร็จสิ้น หน้าที่สุดท้ายของมันคือการ publish Event:

package com.saasovation.identityaccess.domain.model.access;
...
public class Role extends Entity {
    ...
    public void assignUser(User aUser) {
        if (aUser == null) {
            throw new NullPointerException("User must not be null.");
        }
        if (!this.tenantId().equals(aUser.tenantId())) {
            throw new IllegalArgumentException(
                    "Wrong tenant for this user.");
        }

        this.group().addUser(aUser);

        DomainEventPublisher
            .instance()
            .publish(new UserAssignedToRole(
                    this.tenantId(),
                    this.name(),
                    aUser.username(),
                    aUser.person().name().firstName(),
                    aUser.person().name().lastName(),
                    aUser.person().emailAddress()));
    }
    ...
}

Event UserAssignedToRole ที่ถูก enrich ด้วยข้อมูล User อันได้แก่ name และ e-mail address แล้วมันก็จะถูกส่งต่อไปยังทุกฝ่ายที่เกี่ยวข้องในที่สุด เมื่อ Agile Project Management Context ได้รับ Event มันก็จะใช้ข้อมูลนี้เพื่อให้แน่ใจว่าจะมี TeamMember หรือ ProductOwner ตัวใหม่ถูกสร้างขึ้นใน model ของตน นี่ไม่ใช่ use case ที่ยากเย็นอะไรนัก ทว่ายังมีรายละเอียดที่ต้องจัดการอยู่อีกมาก เกินกว่าที่เห็นเผิน ๆ ในตอนแรก เราลองมาแยกแยะเรื่องเหล่านี้กัน

ปรากฏว่าการคอยรับฟัง notification จาก RabbitMQ มีส่วนที่นำกลับมาใช้ซ้ำได้สูงอยู่หลายจุด และเรา มี library แบบ object-oriented ง่าย ๆ ที่ช่วยให้ใช้งาน RabbitMQ Java client ได้ง่ายขึ้นอยู่แล้ว ตอนนี้เราจะเพิ่ม class ง่าย ๆ อีกหนึ่ง class เพื่อให้การเป็น consumer ของ exchange queue ง่ายขึ้นอย่างแท้จริง:

package com.saasovation.common.port.adapter.messaging.rabbitmq;
...
public abstract class ExchangeListener {

    private MessageConsumer messageConsumer;
    private Queue queue;

    public ExchangeListener() {
        super();

        this.attachToQueue();

        this.registerConsumer();
    }

    protected abstract String exchangeName();

    protected abstract void filteredDispatch(
            String aType, String aTextMessage);

    protected abstract String[] listensToEvents();

    protected String queueName() {
        return this.getClass().getSimpleName();
    }

    private void attachToQueue() {
        Exchange exchange =
                Exchange.fanOutInstance(
                        ConnectionSettings.instance(),
                        this.exchangeName(),
                        true);

        this.queue =
                Queue.individualExchangeSubscriberInstance(
                        exchange,
                        this.exchangeName() + "." + this.queueName());
    }

    private Queue queue() {
        return this.queue;
    }

    private void registerConsumer() {
        this.messageConsumer =
                MessageConsumer.instance(this.queue(), false);

        this.messageConsumer.receiveOnly(
                this.listensToEvents(),
                new MessageListener(MessageListener.Type.TEXT) {

            @Override
            public void handleMessage(
                    String aType,
                    String aMessageId,
                    Date aTimestamp,
                    String aTextMessage,
                    long aDeliveryTag,
                    boolean isRedelivery)
            throws Exception {
                filteredDispatch(aType, aTextMessage);
            }
        });
    }
}

ExchangeListener เป็น abstract base class ที่ concrete listener subclass ต่างๆ ใช้ร่วมกันได้ โดย concrete subclass เพียงแค่ต้องเพิ่มโค้ดอีกนิดหน่อยเท่านั้น นอกเหนือจากการ extend abstract base class นี้ อย่างแรก มันก็แค่การันตีว่า default constructor ของ base class ถูกเรียกใช้ ซึ่งจริงๆ แล้วมันก็ถูกเรียกใช้เองอยู่แล้ว ที่เหลือก็คือ implement abstract method อีกสามตัว ซึ่งสองตัวในจำนวนนั้น implement ง่ายมาก: exchangeName() , filteredDispatch() และ listensToEvents() .

ในการ implement exchangeName() สิ่งที่ต้องทำก็แค่ return ค่า String ซึ่งเป็นชื่อของ exchange ที่ concrete listener ตัวนั้นใช้ consume notification อยู่ ส่วน abstract method listensToEvents() นั้นต้อง return ค่า String[] ของ notification type ที่เราต้องการจะรับ ซึ่ง listener ส่วนใหญ่จะ consume notification เพียงแค่ type เดียว จึงมักจะ return array ที่มีสมาชิกแค่ตัวเดียว ส่วน method ที่เหลืออีกตัวคือ filteredDispatch() ซึ่งซับซ้อนที่สุดในสามตัวนี้ เพราะมันเป็นตัวรับผิดชอบงานหนักทั้งหมดในการจัดการกับ message ที่ได้รับมา เพื่อให้เห็นภาพว่ามันทำงานอย่างไร ลองมาดู listener ของ notification ที่นำพา Event ของ UserAssignedToRole กัน:

package com.saasovation.agilepm.infrastructure.messaging;
...
public class TeamMemberEnablerListener extends ExchangeListener {

    @Autowired
    private TeamService teamService;

    public TeamMemberEnablerListener() {
        super();
    }

    @Override
    protected String exchangeName() {
        return Exchanges.IDENTITY_ACCESS_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(
                String aType,
                String aTextMessage) {
        NotificationReader reader =
                new NotificationReader(aTextMessage);

        String roleName = reader.eventStringValue("roleName");

        if (!roleName.equals("ScrumProductOwner") &&
            !roleName.equals("ScrumTeamMember")) {
            return;
        }

        String emailAddress = reader.eventStringValue("emailAddress");
        String firstName = reader.eventStringValue("firstName");
        String lastName = reader.eventStringValue("lastName");
        String tenantId = reader.eventStringValue("tenantId.id");
        String username = reader.eventStringValue("username");
        Date occurredOn = reader.occurredOn();

        if (roleName.equals("ScrumProductOwner")) {
            this.teamService.enableProductOwner(
                    new EnableProductOwnerCommand(
                        tenantId,
                        username,
                        firstName,
                        lastName,
                        emailAddress,
                        occurredOn));
        } else {
            this.teamService.enableTeamMember(
                    new EnableTeamMemberCommand(
                        tenantId,
                        username,
                        firstName,
                        lastName,
                        emailAddress,
                        occurredOn));
        }
    }

    @Override
    protected String[] listensToEvents() {
        return new String[] {
                "com.saasovation.identityaccess.domain.model. ↵
access.UserAssignedToRole"
                };
    }
}

default constructor ของ ExchangeListener ถูกเรียกใช้อย่างถูกต้อง exchangeName() จะตอบกลับชื่อของ exchange ซึ่ง Identity and Access Context เป็นผู้ publish ข้อมูลไปยัง และ method listensToEvents() จะตอบกลับเป็น array ที่มีสมาชิกตัวเดียว ซึ่งบรรจุ fully qualified class name ของ Event User-AssignedToRole เอาไว้ โปรดสังเกตว่า publisher และ subscriber ควรพิจารณาใช้ fully qualified class name ซึ่งรวมทั้งชื่อ Module และชื่อ class เข้าด้วยกัน วิธีนี้จะช่วยขจัดความเป็นไปได้ที่จะเกิดการชนกันหรือความกำกวมกับ Event ที่มีชื่อเดียวกันหรือใกล้เคียงกันจาก Bounded Context คนละแห่ง

ก็เช่นกัน filteredDispatch() ต่างหากที่มีเนื้อหาพฤติกรรมหลักเกือบทั้งหมดอยู่ภายใน method ตัวนี้ได้ชื่อนี้มาเพราะมันสามารถ filter notification เพิ่มเติมได้ ก่อนที่จะ dispatch ไปยัง Application Service API ในกรณีนี้มันก็ filter ก่อน dispatch จริงๆ ด้วยการไม่สนใจ notification type UserAssignedToRole ทั้งหมดที่ไม่ได้นำพา Event เกี่ยวกับ role ที่ชื่อ ScrumProductOwner และ ScrumTeamMember ในทางกลับกัน ถ้า role ที่มาเป็น role ที่เราสนใจจะรับ Event เกี่ยวกับ เราก็จะดึงรายละเอียดของ UserAssignedToRole ออกจาก notification แล้ว dispatch ไปยัง Application Service ที่ชื่อ TeamService โดย method ของ Service แต่ละตัว อย่าง enableProductOwner() และ enableTeamMember() ต่างก็รับ command object คือ EnableProductOwnerCommand หรือ EnableTeamMemberCommand ตามลำดับ

ตอนแรกเราอาจคิดว่าสมาชิกคนหนึ่งจะถูกสร้างขึ้นมาก็ต่อเมื่อเกิด Event เหล่านี้ขึ้นเท่านั้น อย่างไรก็ตาม เนื่องจาก User แต่ละคนอาจถูกกำหนดให้อยู่ใน Roles เหล่านี้ แล้วต่อมาถูกถอดออก แล้วก็ถูกกำหนดกลับเข้ามาใหม่ได้ ดังนั้นสมาชิกซึ่งถูกแทนด้วย User ใน notification ที่เราได้รับมาอาจมีตัวตนอยู่แล้วก็เป็นได้ นี่คือวิธีที่ TeamService จัดการกับสถานการณ์แบบนี้:

package com.saasovation.agilepm.application;
...
public class TeamService ... {

    @Autowired
    private ProductOwnerRepository productOwnerRepository;

    @Autowired
    private TeamMemberRepository teamMemberRepository;

    ...

    @Transactional
    public void enableProductOwner(
                EnableProductOwnerCommand aCommand) {
        TenantId tenantId = new TenantId(aCommand.getTenantId());

        ProductOwner productOwner =
                this.productOwnerRepository.productOwnerOfIdentity(
                        tenantId,
                        aCommand.getUsername());

        if (productOwner != null) {
            productOwner.enable(aCommand.getOccurredOn());
        } else {
            productOwner =
                    new ProductOwner(
                            tenantId,
                            aCommand.getUsername(),
                            aCommand.getFirstName(),
                            aCommand.getLastName(),
                            aCommand.getEmailAddress(),
                            aCommand.getOccurredOn());

            this.productOwnerRepository.add(productOwner);
        }
    }
}

ตัวอย่างเช่น method enableProductOwner() ใน Service จะรองรับกรณีที่ ProductOwner รายนั้นมีตัวตนอยู่แล้ว ถ้ามันมีอยู่จริง เราก็ถือว่าอาจต้องเปิดใช้งานมันอีกครั้ง จึงส่งต่อ (dispatch) ไปยัง command operation ที่เกี่ยวข้อง แต่ถ้า ProductOwner ยังไม่มีตัวตน เราก็จะสร้าง Aggregate ใหม่ขึ้นมาแล้วเพิ่มเข้าไปใน Repository ของมัน ที่จริงแล้วเราจัดการกับ TeamMember ในลักษณะเดียวกัน enableTeamMember() จึงถูก implement ในแบบเดียวกัน