การมอง A+ES ผ่าน Application Service (4, 14) จะช่วยให้เห็นภาพรวมของระบบทั้งหมด เป็นเรื่องปกติที่ Aggregates จะอาศัยอยู่ภายใน domain model โดยมี Application Services ทำหน้าที่เป็น client โดยตรงของ domain model คอยรองรับการทำงานอยู่เบื้องหลัง

เมื่อ Application Service รับช่วงการทำงาน มันจะโหลด Aggregate ขึ้นมาและดึง Domain Services (7) ที่ business operation ของ Aggregate จำเป็นต้องใช้มาสนับสนุน จากนั้นเมื่อ Application Service ส่งต่องานให้กับ business operation ของ Aggregate เมธอดของ Aggregate จะสร้าง Events ออกมาเป็นผลลัพธ์ ซึ่ง Events เหล่านั้นจะ mutate สถานะของ Aggregate และถูก publish เป็น notification ไปยัง subscriber ทุกตัว business method ของ Aggregate อาจต้องรับ Domain Services หนึ่งตัวหรือมากกว่าเป็นพารามิเตอร์ การใช้งาน Domain Services ดังกล่าว อาจใช้คำนวณค่าที่ก่อให้เกิด side effects ต่อสถานะของ Aggregate การทำงานบางอย่างของ Domain Service อาจรวมถึงการเรียก payment gateway การขอ identity ที่ไม่ซ้ำกัน หรือการ query ข้อมูลจากระบบระยะไกล Figure A.2 แสดงให้เห็นว่ากลไกทั้งหมดนี้ทำงานอย่างไร

Image

Figure A.2. Application Service ควบคุมการเข้าถึงและการใช้งาน Aggregate

ตัวอย่าง Application Service ต่อไปนี้ซึ่ง implement ด้วย C# จะแสดงให้เห็นว่าขั้นตอนของ Figure A.2 นั้นมีแนวทางรองรับการทำงานอย่างไร:

public class CustomerApplicationService
{
  // event store for accessing event streams
  IEventStore _eventStore;

  // domain service that is neeeded by aggregate
  IPricingService _pricingService;

  // pass dependencies for this application service via constructor
  public CustomerApplicationService(
    IEventStore eventStore,
    IPricingService pricing)
  {
    _eventStore = eventStore;
    _pricingService = pricing;
  }

  // Step 1: LockForAccountOverdraft method of
  // Customer Application Service is called
  public void LockForAccountOverdraft(
    CustomerId customerId, string comment)
  {
    // Step 2.1: Load event stream for Customer, given its id
    var stream = _eventStore.LoadEventStream(customerId);
    // Step 2.2: Build aggregate from event stream
    var customer = new Customer(stream.Events);
    // Step 3: Call aggregate method, passing it arguments and
    // pricing domain service
    customer.LockForAccountOverdraft(comment, _pricingService);
    // Step 4: Commit changes to the event stream by id
    _eventStore.AppendToStream(
      customerId, stream.Version, customer.Changes);
  }

  public void LockCustomer(CustomerId customerId, string reason)
  {
    var stream = _eventStore.LoadEventStream(customerId);
    var customer = new Customer(stream.Events);
    customer.Lock(reason);
    _eventStore.AppendToStream(
      customerId, stream.Version, customer.Changes);
  }

  // other methods on this application service
}

คลาส CustomerApplicationService ถูก initialize ด้วย dependencies สองตัวผ่าน constructor ได้แก่ IEventStore และ IPricingService การ initialize ผ่าน constructor ถือเป็นแนวทางที่เหมาะสมในการจัดหา dependencies แต่เราอาจดึง dependencies เหล่านั้นมาจาก Service Factory หรือใช้ dependency injection ก็ได้ ท้ายที่สุด มาตรฐานและแนวปฏิบัติของทีมของคุณ เป็นผู้ชี้ขาด


Where Can I Find the Sample Code? (จะหาตัวอย่างโค้ดได้จากที่ไหน)

ซอร์สโค้ดทั้งหมดของตัวอย่าง A+ES สามารถดาวน์โหลดได้จากที่นี่:

http://lokad.github.com/lokad-iddd-sample/ .


ส่วน IEventStore ของเราสามารถมี interface definition ที่เรียบง่ายได้ และ EventStream ของเราก็เป็นไปในแนวทางเดียวกัน:

public interface IEventStore
{
    EventStream LoadEventStream(IIdentity id);

    EventStream LoadEventStream(
        IIdentity id, int skipEvents, int maxCount);

    void AppendToStream(
        IIdentity id, int expectedVersion, ICollection<IEvent> events);
}

public class EventStream
{
    // version of the event stream returned
    public int Version;

    // all events in the stream
    public List<IEvent> Events;
}

Event Store นี้สามารถ implement ได้โดยไม่ยากนักด้วย relational database (Microsoft SQL, Oracle หรือ MySQL) หรือกับ NoSQL store ที่มีการันตีความสอดคล้องในระดับสูง (file system, MongoDB, RavenDB หรือ Azure Blob storage)

เราโหลด Events จาก Event Store โดยใช้ unique identity ของ Aggregate instance ที่ต้องการจะ reconstitute มาดูกันว่า จะทำเช่นนี้กับ Aggregate ที่ชื่อ Customer ได้อย่างไร แม้ unique identity จะเป็น type แบบใดก็ได้ แต่เพื่อให้เห็นภาพ เราจะใช้ IIdentity interface ซึ่งถูก implement โดย CustomerId .

เราจำเป็นต้องโหลด Events ที่เป็นของ Customer โดย Events ที่โหลดมาได้จะถูกส่งเข้าไปใน constructor ของ Customer เพื่อทำการ instantiate Aggregate:

var eventStream = _eventStore.LoadEventStream(customerId);

var customer = new Customer(eventStream.Events);

อย่างที่เห็นใน Figure A.3 Aggregate จะ apply Events ด้วยการ replay Events เหล่านั้นผ่าน method Mutate() มาดูวิธีการทำงานของมัน:

public partial class Customer
{
  public Customer(IEnumerable<IEvent> events)
  {
    // reinstate this aggregate to the latest version
    foreach (var @event in events)
    {
      Mutate(@event);
    }
  }

  public bool ConsumptionLocked { get; private set; }

  public void Mutate(IEvent e)
  {
    // .NET magic to call one of 'When' handlers with
    // matching signature
    ((dynamic) this).When((dynamic)e);
  }

  public void When(CustomerLocked e)
  {
    ConsumptionLocked = true;
  }

  public void When(CustomerUnlocked e)
  {
    ConsumptionLocked = false;
  }

  // etc.

Image

Figure A.3. state ของ Aggregate ถูก reconstitute ขึ้นมาใหม่โดยใช้ Events ที่ถูก apply ตามลำดับที่เกิดขึ้นจริง

Mutate() จะทำหน้าที่หาว่า (โดยใช้ .NET dynamics) method When() ที่ overloaded ไว้อย่างเหมาะสมโดยดูจาก type ของ Event parameter จากนั้นก็ execute method นั้นด้วยการส่ง Event เข้าไป หลังจาก Mutate() ทำงานเสร็จสิ้นแล้ว Customer instance ก็จะมี state ที่ถูก reconstitute กลับมาอย่างครบถ้วนสมบูรณ์

เราสามารถสร้าง query operation ที่ใช้ซ้ำได้สำหรับการ reconstitute Aggregate instance จาก Event Store:

public Customer LoadCustomerById(CustomerId id)
{
    var eventStream = _eventStore.LoadEventStream(id);
    var customer = new Customer(eventStream.Events);
    return customer;
}

หลังจากที่ได้เห็นว่า Aggregate instance ถูก reconstitute จาก Stream ของ Events ในอดีตได้อย่างไร ก็ไม่ยากที่จะ นึกถึงการนำบันทึกทางประวัติศาสตร์เหล่านี้ไปใช้ประโยชน์อย่างอื่น เราใช้มันเพื่อย้อนเวลากลับไปดูว่าเกิดอะไรขึ้นบ้าง และเกิดขึ้น เมื่อใด ความสามารถในการมองย้อนหลังนี้จะยิ่งมีพลังมากขึ้นเมื่อเราต้อง debug การทำงานใน production deployments

แล้ว business operations ทำงานกันอย่างไร? เมื่อ Aggregate ถูก reconstitute จาก Event Store แล้ว Application Service จะ delegate งานไปยัง command operation บน Aggregate instance โดย operation จะใช้ state ปัจจุบันของ Aggregate และ Domain Services ใดๆ ที่ contract กำหนดไว้เพื่อดำเนินการ เมื่อ behavior ถูก execute การเปลี่ยนแปลงของ state จะถูก แสดงออกมาเป็น Events ใหม่ โดย Event ใหม่แต่ละตัวจะถูกส่งให้ method Apply() ของ Aggregate ตามที่แสดงใน Figure A.4 .

Image

Figure A.4. state ของ Aggregate อิงจาก Events ในอดีต และผลลัพธ์ของ behavior จะสร้าง Events ใหม่ขึ้นมา

อย่างที่เห็นในโค้ดด้านล่าง Events ใหม่จะถูกสะสมไว้ใน Changes collection แล้วจึงใช้ Events เหล่านี้เพื่อ mutate state ปัจจุบันของ Aggregate:

public partial class Customer
{
  ...
  void Apply(IEvent event)
  {
    // append event to change list for further persistence
    Changes.Add(event);

    // pass each event to modify current in-memory state
    Mutate(event);
  }
  ...
}

Events ทั้งหมดที่ถูกเพิ่มเข้าไปใน Changes collection จะถูก persist ด้วยการ append ต่อท้าย และเนื่องจาก Event แต่ละตัวยังถูกใช้เพื่อ mutate state ของ Aggregate ทันทีด้วย ถ้า behavior มีหลายขั้นตอน ขั้นตอนถัดไปแต่ละขั้นก็จะมี state ที่เป็นปัจจุบันล่าสุดไว้ใช้ทำงาน

ต่อไป เรามาดู business behavior บางส่วนของ Customer Aggregate:

public partial class Customer
{
  // Second part of aggregate class
  public List<IEvent> Changes = new List<IEvent>();

  public void LockForAccountOverdraft(
    string comment, IPricingService pricing)
  {
    if (!ManualBilling)
    {
      var balance = pricing.GetOverdraftThreshold(Currency);
      if (Balance < balance)
      {
        LockCustomer("Overdraft. " + comment);
      }
    }
  }

  public void LockCustomer(string reason)
  {
    if (!ConsumptionLocked)
    {
      Apply(new CustomerLocked(_state.Id, reason));
    }
  }

  // Other business methods are not shown ...

  void Apply(IEvent e)
  {
    Changes.Add(e);
    Mutate(e);
  }
}

Consider Using Two Implementation Classes (ลองพิจารณาใช้สองคลาสสำหรับการนำไปใช้งาน)

เพื่อให้โค้ดของคุณอ่านเข้าใจง่ายขึ้น คุณสามารถแยก a+es implementation ออกเป็นสอง class ที่แตกต่างกัน โดย class หนึ่งไว้เก็บ state และอีก class หนึ่งไว้จัดการ behavior โดย object ที่เก็บ state จะถูกถือครองโดย object ฝั่ง behavior วัตถุทั้งสองจะทำงาน ร่วมกันผ่าน Apply() method เท่านั้น ซึ่งการันตีว่า state จะถูก mutate ได้ด้วย events เท่านั้น


เมื่อ behavior ต่างๆ ที่ทำการ mutate ทำงานเสร็จสิ้นแล้ว เราต้อง commit collection Changes ลงใน Event Store โดยเราจะ append การเปลี่ยนแปลงใหม่ทั้งหมด พร้อมการันตีว่าจะไม่มี concurrency conflict กับเธรดอื่นที่กำลัง เขียนข้อมูล การตรวจสอบนี้เป็นไปได้เพราะเราส่งตัวแปร concurrency version จาก method Load() ไปยัง method Append()

ในการนำไปใช้งานแบบง่ายที่สุด จะมี background processor คอยติดตาม Events ที่ถูก append เข้ามาใหม่ และ publish ออกไปยัง messaging infrastructure (เช่น RabbitMQ, JMS, MSMQ หรือ cloud queues) เพื่อส่งมอบให้ทุกฝ่ายที่สนใจ ดู Figure A.5

Image

Figure A.5. Events ซึ่งเป็นผลลัพธ์ทางพฤติกรรมของ Aggregate ที่ถูก append ใหม่ทั้งหมดจะถูก publish ไปยัง subscribers

implementation แบบง่ายนี้สามารถแทนที่ด้วยแบบที่ซับซ้อนยิ่งขึ้นได้ หนึ่งในวิธีดังกล่าวคือ replication ของ Events ไปยัง clone หนึ่งตัวหรือมากกว่า ไม่ว่าจะทันทีหรือในภายหลังก็ตาม ซึ่งช่วยเพิ่ม fault tolerance Figure A.6 แสดง replication ของ Events แบบทันทีไปยัง clone หนึ่งตัว ในกรณีนี้ Master Event Store จะถือว่า Events ของตัวเองถูกบันทึกแล้ว ก็ต่อเมื่อการ replication ไปยัง Clone Event Store สำเร็จแล้วเท่านั้น ซึ่งเป็นกลยุทธ์แบบ write-through

Image

Figure A.6. Write through: Master Event Store จะ replicate Events ที่ถูก append ใหม่ทั้งหมดไปยัง Clone Event Store ทันที

อีกทางเลือกหนึ่งคือ replicate Events ไปยัง Clone หลังจากที่ Master บันทึกการเปลี่ยนแปลงแล้วโดยใช้เธรดแยกต่างหาก ซึ่งเป็น กลยุทธ์แบบ write-behind แนวทางนี้แสดงไว้ใน Figure A.7 ในกรณีนี้ Clone อาจไม่สอดคล้องกับ Master ได้ ซึ่งเป็นจริงโดยเฉพาะเมื่อ server crash หรือเมื่อ partitioning ได้รับผลกระทบ จาก network latency

Image

Figure A.7. Write behind: Master Event Store จะ replicate Events ที่ถูก append ใหม่ทั้งหมดไปยัง Clone Event Store ในภายหลัง

เพื่อสรุปสิ่งที่ได้กล่าวถึงมา ลองเดินดู execution sequence ที่เริ่มต้นจากการเรียกใช้ operation บน Application Service กัน

1. client เรียกใช้ method บน Application Service ตัวหนึ่ง

2. นำ Domain Services ที่จำเป็นต่อการทำงาน business operation มาใช้

3. ใช้ identity ของ Aggregate instance ที่ client ส่งมา เพื่อดึง Event Stream ของมัน

4. ทำการ reconstitute Aggregate instance ขึ้นมาใหม่ โดย apply Events ทั้งหมดจาก Stream เข้ากับมัน

5. execute business operation ที่ Aggregate จัดเตรียมไว้ โดยส่งพารามิเตอร์ครบถ้วนตามที่ contract ของ interface กำหนด

6. Aggregate อาจทำ double-dispatch ไปยัง Domain Services ที่ส่งให้, instance ของ Aggregate อื่นๆ และอื่นๆ ที่เกี่ยวข้อง แล้วจะสร้าง Events ใหม่ขึ้นมาเป็นผลลัพธ์ของ operation

7. เมื่อไม่มี business operation ใดล้มเหลว ให้ append Events ใหม่ที่สร้างขึ้นทั้งหมดเข้ากับ Stream โดยใช้ Stream version เป็น guard เพื่อป้องกัน concurrency conflicts

8. publish Events ที่ถูก append ใหม่จาก Event Store ไปยัง subscribers ด้วย messaging infrastructure ที่คุณเลือกใช้

เราสามารถเสริมความสามารถของ A+ES implementation ได้ด้วยตัวเลือกต่างๆ มากมาย ตัวอย่างเช่น เราอาจใช้ Repository (12) เพื่อ encapsulate การเข้าถึง Event Store และรายละเอียดของการ reconstitute Aggregate instances เมื่อพิจารณา จากโค้ดตัวอย่างก่อนหน้านี้ คุณจะสร้าง Repository base class ที่นำกลับมาใช้ซ้ำได้โดยไม่ยาก ให้เรามุ่งไปที่ optional enhancement ที่ใช้งานได้จริงเพียงสองอย่างซึ่งช่วย A+ES designs ได้มาก นั่นคือ Command Handlers และ lambdas