{"id":"6b093dc191bd8fbaf2a0c8d0","slug":"inventory-cqrs","title":"Magazyn z CQRS – osobny model zapisu i odczytu","summary":"Komendy magazynowe walidowane na własnym modelu zapisu, zdarzenia na szynie i projekcja budująca model odczytu z raportem niskich stanów. Model odczytu da się odtworzyć z samych zdarzeń.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"medium","topics":["cqrs","event-driven-architecture"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["cqrs","read-model","projection","events","inventory"],"languages":[{"lang":"typescript","runner":"browser","starter":"type InventoryEvent =\n  | { type: 'ProductRegistered'; sku: string; name: string }\n  | { type: 'StockReceived'; sku: string; quantity: number }\n  | { type: 'StockShipped'; sku: string; quantity: number };\n\n/** In-process event bus (ready). */\nclass EventBus {\n  private readonly handlers: ((event: InventoryEvent) => void)[] = [];\n\n  subscribe(handler: (event: InventoryEvent) => void): void {\n    this.handlers.push(handler);\n  }\n\n  publish(event: InventoryEvent): void {\n    for (const handler of this.handlers) handler(event);\n  }\n}\n\n/**\n * WRITE side. Validates commands against its OWN state (never the read model), publishes events, returns nothing.\n * Errors: 'Product already registered: <sku>', 'Unknown product: <sku>', 'Quantity must be positive',\n * 'Insufficient stock for <sku>' (checked in this order). A rejected command publishes nothing.\n */\nclass InventoryCommands {\n  constructor(private readonly bus: EventBus) {}\n\n  registerProduct(sku: string, name: string): void {\n    throw new Error('Not implemented');\n  }\n\n  receiveStock(sku: string, quantity: number): void {\n    throw new Error('Not implemented');\n  }\n\n  shipStock(sku: string, quantity: number): void {\n    throw new Error('Not implemented');\n  }\n}\n\ninterface ProductView {\n  sku: string;\n  name: string;\n  onHand: number;\n  shipped: number;\n}\n\n/** READ side: a projection built only from events, plus queries that return copies. */\nclass InventoryReadModel {\n  apply(event: InventoryEvent): void {\n    throw new Error('Not implemented');\n  }\n\n  getProduct(sku: string): ProductView | null {\n    throw new Error('Not implemented');\n  }\n\n  /** Products with onHand < threshold, sorted by onHand, then by sku. */\n  lowStock(threshold: number): ProductView[] {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function inventory() {\n  const bus = new EventBus();\n  const readModel = new InventoryReadModel();\n  const published = [];\n  bus.subscribe((event) => readModel.apply(event));\n  bus.subscribe((event) => published.push(event));\n  return { bus, readModel, published, commands: new InventoryCommands(bus) };\n}\n\ntest('a registered product appears in the read model with no stock', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 0, shipped: 0 });\n  expect(readModel.getProduct('NOPE')).toBeNull();\n});\n\ntest('receiving and shipping stock update the view', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 10);\n  commands.shipStock('MUG-1', 3);\n  commands.receiveStock('MUG-1', 5);\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 12, shipped: 3 });\n});\n\ntest('commands publish events and return nothing', () => {\n  const { commands, published } = inventory();\n  expect(commands.registerProduct('MUG-1', 'Mug')).toBeUndefined();\n  expect(commands.receiveStock('MUG-1', 10)).toBeUndefined();\n  expect(published).toEqual([\n    { type: 'ProductRegistered', sku: 'MUG-1', name: 'Mug' },\n    { type: 'StockReceived', sku: 'MUG-1', quantity: 10 },\n  ]);\n});\n\ntest('invalid commands are rejected and publish nothing', () => {\n  const { commands, published } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  expect(() => commands.registerProduct('MUG-1', 'Another mug')).toThrow('Product already registered: MUG-1');\n  expect(() => commands.receiveStock('NOPE', 1)).toThrow('Unknown product: NOPE');\n  expect(() => commands.receiveStock('MUG-1', 0)).toThrow('Quantity must be positive');\n  expect(() => commands.shipStock('MUG-1', -2)).toThrow('Quantity must be positive');\n  expect(published).toHaveLength(1);\n});\n\ntest('shipping more than is on hand is rejected and the view stays unchanged', () => {\n  const { commands, readModel, published } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 2);\n  expect(() => commands.shipStock('MUG-1', 5)).toThrow('Insufficient stock for MUG-1');\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 2, shipped: 0 });\n  expect(published).toHaveLength(2);\n});\n\ntest('the write side validates with its own state, without any read model', () => {\n  const commands = new InventoryCommands(new EventBus());\n  commands.registerProduct('LAMP', 'Lamp');\n  commands.receiveStock('LAMP', 3);\n  expect(() => commands.shipStock('LAMP', 4)).toThrow('Insufficient stock for LAMP');\n  expect(() => commands.shipStock('LAMP', 3)).not.toThrow();\n  expect(() => commands.shipStock('LAMP', 1)).toThrow('Insufficient stock for LAMP');\n});\n\ntest('the read model can be rebuilt from stored events alone', () => {\n  const stored = [\n    { type: 'ProductRegistered', sku: 'A', name: 'Anchor' },\n    { type: 'ProductRegistered', sku: 'B', name: 'Bell' },\n    { type: 'StockReceived', sku: 'A', quantity: 7 },\n    { type: 'StockShipped', sku: 'A', quantity: 2 },\n  ];\n  const rebuilt = new InventoryReadModel();\n  for (const event of stored) rebuilt.apply(event);\n  expect(rebuilt.getProduct('A')).toEqual({ sku: 'A', name: 'Anchor', onHand: 5, shipped: 2 });\n  expect(rebuilt.lowStock(1).map((v) => v.sku)).toEqual(['B']);\n});\n\ntest('lowStock lists products below the threshold, lowest first', () => {\n  const { commands, readModel } = inventory();\n  for (const [sku, qty] of [['D', 20], ['C', 5], ['B', 1], ['A', 5]]) {\n    commands.registerProduct(sku, 'Product ' + sku);\n    commands.receiveStock(sku, qty);\n  }\n  expect(readModel.lowStock(10).map((v) => v.sku)).toEqual(['B', 'A', 'C']);\n  expect(readModel.lowStock(1)).toEqual([]);\n});\n\ntest('queries return copies, so the read model cannot be changed through them', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 4);\n  const view = readModel.getProduct('MUG-1');\n  view.onHand = 999;\n  const low = readModel.lowStock(10);\n  low[0].shipped = 50;\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 4, shipped: 0 });\n});\n"},{"lang":"javascript","runner":"browser","starter":"// Events: { type: 'ProductRegistered', sku, name } | { type: 'StockReceived', sku, quantity } | { type: 'StockShipped', sku, quantity }\n\n/** In-process event bus (ready). */\nclass EventBus {\n  #handlers = [];\n\n  subscribe(handler) {\n    this.#handlers.push(handler);\n  }\n\n  publish(event) {\n    for (const handler of this.#handlers) handler(event);\n  }\n}\n\n/**\n * WRITE side. Validates commands against its OWN state (never the read model), publishes events, returns nothing.\n * Errors: 'Product already registered: <sku>', 'Unknown product: <sku>', 'Quantity must be positive',\n * 'Insufficient stock for <sku>' (checked in this order). A rejected command publishes nothing.\n */\nclass InventoryCommands {\n  constructor(bus) {\n    this.bus = bus;\n  }\n\n  registerProduct(sku, name) {\n    throw new Error('Not implemented');\n  }\n\n  receiveStock(sku, quantity) {\n    throw new Error('Not implemented');\n  }\n\n  shipStock(sku, quantity) {\n    throw new Error('Not implemented');\n  }\n}\n\n/** READ side: a projection built only from events, plus queries that return copies of { sku, name, onHand, shipped }. */\nclass InventoryReadModel {\n  apply(event) {\n    throw new Error('Not implemented');\n  }\n\n  getProduct(sku) {\n    throw new Error('Not implemented');\n  }\n\n  /** Products with onHand < threshold, sorted by onHand, then by sku. */\n  lowStock(threshold) {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"function inventory() {\n  const bus = new EventBus();\n  const readModel = new InventoryReadModel();\n  const published = [];\n  bus.subscribe((event) => readModel.apply(event));\n  bus.subscribe((event) => published.push(event));\n  return { bus, readModel, published, commands: new InventoryCommands(bus) };\n}\n\ntest('a registered product appears in the read model with no stock', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 0, shipped: 0 });\n  expect(readModel.getProduct('NOPE')).toBeNull();\n});\n\ntest('receiving and shipping stock update the view', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 10);\n  commands.shipStock('MUG-1', 3);\n  commands.receiveStock('MUG-1', 5);\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 12, shipped: 3 });\n});\n\ntest('commands publish events and return nothing', () => {\n  const { commands, published } = inventory();\n  expect(commands.registerProduct('MUG-1', 'Mug')).toBeUndefined();\n  expect(commands.receiveStock('MUG-1', 10)).toBeUndefined();\n  expect(published).toEqual([\n    { type: 'ProductRegistered', sku: 'MUG-1', name: 'Mug' },\n    { type: 'StockReceived', sku: 'MUG-1', quantity: 10 },\n  ]);\n});\n\ntest('invalid commands are rejected and publish nothing', () => {\n  const { commands, published } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  expect(() => commands.registerProduct('MUG-1', 'Another mug')).toThrow('Product already registered: MUG-1');\n  expect(() => commands.receiveStock('NOPE', 1)).toThrow('Unknown product: NOPE');\n  expect(() => commands.receiveStock('MUG-1', 0)).toThrow('Quantity must be positive');\n  expect(() => commands.shipStock('MUG-1', -2)).toThrow('Quantity must be positive');\n  expect(published).toHaveLength(1);\n});\n\ntest('shipping more than is on hand is rejected and the view stays unchanged', () => {\n  const { commands, readModel, published } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 2);\n  expect(() => commands.shipStock('MUG-1', 5)).toThrow('Insufficient stock for MUG-1');\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 2, shipped: 0 });\n  expect(published).toHaveLength(2);\n});\n\ntest('the write side validates with its own state, without any read model', () => {\n  const commands = new InventoryCommands(new EventBus());\n  commands.registerProduct('LAMP', 'Lamp');\n  commands.receiveStock('LAMP', 3);\n  expect(() => commands.shipStock('LAMP', 4)).toThrow('Insufficient stock for LAMP');\n  expect(() => commands.shipStock('LAMP', 3)).not.toThrow();\n  expect(() => commands.shipStock('LAMP', 1)).toThrow('Insufficient stock for LAMP');\n});\n\ntest('the read model can be rebuilt from stored events alone', () => {\n  const stored = [\n    { type: 'ProductRegistered', sku: 'A', name: 'Anchor' },\n    { type: 'ProductRegistered', sku: 'B', name: 'Bell' },\n    { type: 'StockReceived', sku: 'A', quantity: 7 },\n    { type: 'StockShipped', sku: 'A', quantity: 2 },\n  ];\n  const rebuilt = new InventoryReadModel();\n  for (const event of stored) rebuilt.apply(event);\n  expect(rebuilt.getProduct('A')).toEqual({ sku: 'A', name: 'Anchor', onHand: 5, shipped: 2 });\n  expect(rebuilt.lowStock(1).map((v) => v.sku)).toEqual(['B']);\n});\n\ntest('lowStock lists products below the threshold, lowest first', () => {\n  const { commands, readModel } = inventory();\n  for (const [sku, qty] of [['D', 20], ['C', 5], ['B', 1], ['A', 5]]) {\n    commands.registerProduct(sku, 'Product ' + sku);\n    commands.receiveStock(sku, qty);\n  }\n  expect(readModel.lowStock(10).map((v) => v.sku)).toEqual(['B', 'A', 'C']);\n  expect(readModel.lowStock(1)).toEqual([]);\n});\n\ntest('queries return copies, so the read model cannot be changed through them', () => {\n  const { commands, readModel } = inventory();\n  commands.registerProduct('MUG-1', 'Mug');\n  commands.receiveStock('MUG-1', 4);\n  const view = readModel.getProduct('MUG-1');\n  view.onHand = 999;\n  const low = readModel.lowStock(10);\n  low[0].shipped = 50;\n  expect(readModel.getProduct('MUG-1')).toEqual({ sku: 'MUG-1', name: 'Mug', onHand: 4, shipped: 0 });\n});\n"},{"lang":"python","runner":"browser","starter":"from dataclasses import dataclass\nfrom typing import Callable\n\n\n@dataclass(frozen=True)\nclass ProductRegistered:\n    sku: str\n    name: str\n\n\n@dataclass(frozen=True)\nclass StockReceived:\n    sku: str\n    quantity: int\n\n\n@dataclass(frozen=True)\nclass StockShipped:\n    sku: str\n    quantity: int\n\n\nclass EventBus:\n    \"\"\"In-process event bus (ready).\"\"\"\n\n    def __init__(self):\n        self._handlers: list[Callable] = []\n\n    def subscribe(self, handler: Callable) -> None:\n        self._handlers.append(handler)\n\n    def publish(self, event) -> None:\n        for handler in self._handlers:\n            handler(event)\n\n\nclass InventoryCommands:\n    \"\"\"WRITE side. Validates commands against its OWN state (never the read model), publishes events,\n    returns None. ValueError messages: 'Product already registered: <sku>', 'Unknown product: <sku>',\n    'Quantity must be positive', 'Insufficient stock for <sku>' (checked in this order).\n    A rejected command publishes nothing.\"\"\"\n\n    def __init__(self, bus: EventBus):\n        self.bus = bus\n\n    def register_product(self, sku: str, name: str) -> None:\n        raise NotImplementedError\n\n    def receive_stock(self, sku: str, quantity: int) -> None:\n        raise NotImplementedError\n\n    def ship_stock(self, sku: str, quantity: int) -> None:\n        raise NotImplementedError\n\n\n@dataclass\nclass ProductView:\n    sku: str\n    name: str\n    on_hand: int = 0\n    shipped: int = 0\n\n\nclass InventoryReadModel:\n    \"\"\"READ side: a projection built only from events, plus queries that return copies.\"\"\"\n\n    def apply(self, event) -> None:\n        raise NotImplementedError\n\n    def get_product(self, sku: str) -> ProductView | None:\n        raise NotImplementedError\n\n    def low_stock(self, threshold: int) -> list[ProductView]:\n        \"\"\"Products with on_hand < threshold, sorted by on_hand, then by sku.\"\"\"\n        raise NotImplementedError\n","testCount":9,"tests":"def inventory():\n    bus = EventBus()\n    read_model = InventoryReadModel()\n    published = []\n    bus.subscribe(read_model.apply)\n    bus.subscribe(published.append)\n    return InventoryCommands(bus), read_model, published\n\n\ndef test_a_registered_product_appears_in_the_read_model_with_no_stock():\n    commands, read_model, _ = inventory()\n    commands.register_product(\"MUG-1\", \"Mug\")\n    got = read_model.get_product(\"MUG-1\")\n    assert got == ProductView(\"MUG-1\", \"Mug\", 0, 0), f\"got {got}\"\n    assert read_model.get_product(\"NOPE\") is None\n\n\ndef test_receiving_and_shipping_stock_update_the_view():\n    commands, read_model, _ = inventory()\n    commands.register_product(\"MUG-1\", \"Mug\")\n    commands.receive_stock(\"MUG-1\", 10)\n    commands.ship_stock(\"MUG-1\", 3)\n    commands.receive_stock(\"MUG-1\", 5)\n    got = read_model.get_product(\"MUG-1\")\n    assert got == ProductView(\"MUG-1\", \"Mug\", 12, 3), f\"got {got}\"\n\n\ndef test_commands_publish_events_and_return_nothing():\n    commands, _, published = inventory()\n    assert commands.register_product(\"MUG-1\", \"Mug\") is None\n    assert commands.receive_stock(\"MUG-1\", 10) is None\n    assert published == [ProductRegistered(\"MUG-1\", \"Mug\"), StockReceived(\"MUG-1\", 10)], f\"got {published}\"\n\n\ndef test_invalid_commands_are_rejected_and_publish_nothing():\n    commands, _, published = inventory()\n    commands.register_product(\"MUG-1\", \"Mug\")\n    with raises(ValueError, match=\"Product already registered: MUG-1\"):\n        commands.register_product(\"MUG-1\", \"Another mug\")\n    with raises(ValueError, match=\"Unknown product: NOPE\"):\n        commands.receive_stock(\"NOPE\", 1)\n    with raises(ValueError, match=\"Quantity must be positive\"):\n        commands.receive_stock(\"MUG-1\", 0)\n    with raises(ValueError, match=\"Quantity must be positive\"):\n        commands.ship_stock(\"MUG-1\", -2)\n    assert len(published) == 1, f\"rejected commands published events: {published}\"\n\n\ndef test_shipping_more_than_is_on_hand_is_rejected_and_the_view_stays_unchanged():\n    commands, read_model, published = inventory()\n    commands.register_product(\"MUG-1\", \"Mug\")\n    commands.receive_stock(\"MUG-1\", 2)\n    with raises(ValueError, match=\"Insufficient stock for MUG-1\"):\n        commands.ship_stock(\"MUG-1\", 5)\n    assert read_model.get_product(\"MUG-1\") == ProductView(\"MUG-1\", \"Mug\", 2, 0)\n    assert len(published) == 2\n\n\ndef test_the_write_side_validates_with_its_own_state_without_any_read_model():\n    commands = InventoryCommands(EventBus())\n    commands.register_product(\"LAMP\", \"Lamp\")\n    commands.receive_stock(\"LAMP\", 3)\n    with raises(ValueError, match=\"Insufficient stock for LAMP\"):\n        commands.ship_stock(\"LAMP\", 4)\n    commands.ship_stock(\"LAMP\", 3)\n    with raises(ValueError, match=\"Insufficient stock for LAMP\"):\n        commands.ship_stock(\"LAMP\", 1)\n\n\ndef test_the_read_model_can_be_rebuilt_from_stored_events_alone():\n    stored = [\n        ProductRegistered(\"A\", \"Anchor\"),\n        ProductRegistered(\"B\", \"Bell\"),\n        StockReceived(\"A\", 7),\n        StockShipped(\"A\", 2),\n    ]\n    rebuilt = InventoryReadModel()\n    for event in stored:\n        rebuilt.apply(event)\n    assert rebuilt.get_product(\"A\") == ProductView(\"A\", \"Anchor\", 5, 2)\n    assert [v.sku for v in rebuilt.low_stock(1)] == [\"B\"]\n\n\ndef test_low_stock_lists_products_below_the_threshold_lowest_first():\n    commands, read_model, _ = inventory()\n    for sku, qty in [(\"D\", 20), (\"C\", 5), (\"B\", 1), (\"A\", 5)]:\n        commands.register_product(sku, f\"Product {sku}\")\n        commands.receive_stock(sku, qty)\n    got = [v.sku for v in read_model.low_stock(10)]\n    assert got == [\"B\", \"A\", \"C\"], f\"got {got}\"\n    assert read_model.low_stock(1) == []\n\n\ndef test_queries_return_copies_so_the_read_model_cannot_be_changed_through_them():\n    commands, read_model, _ = inventory()\n    commands.register_product(\"MUG-1\", \"Mug\")\n    commands.receive_stock(\"MUG-1\", 4)\n    view = read_model.get_product(\"MUG-1\")\n    view.on_hand = 999\n    read_model.low_stock(10)[0].shipped = 50\n    got = read_model.get_product(\"MUG-1\")\n    assert got == ProductView(\"MUG-1\", \"Mug\", 4, 0), f\"the read model changed: {got}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic abstract class InventoryEvent\n{\n    protected InventoryEvent(string sku) { Sku = sku; }\n    public string Sku { get; }\n}\n\npublic sealed class ProductRegistered : InventoryEvent\n{\n    public ProductRegistered(string sku, string name) : base(sku) { Name = name; }\n    public string Name { get; }\n}\n\npublic sealed class StockReceived : InventoryEvent\n{\n    public StockReceived(string sku, int quantity) : base(sku) { Quantity = quantity; }\n    public int Quantity { get; }\n}\n\npublic sealed class StockShipped : InventoryEvent\n{\n    public StockShipped(string sku, int quantity) : base(sku) { Quantity = quantity; }\n    public int Quantity { get; }\n}\n\n/// <summary>In-process event bus (ready).</summary>\npublic class EventBus\n{\n    private readonly List<Action<InventoryEvent>> handlers = new List<Action<InventoryEvent>>();\n    public void Subscribe(Action<InventoryEvent> handler) { handlers.Add(handler); }\n    public void Publish(InventoryEvent e) { foreach (var handler in handlers) handler(e); }\n}\n\n/// <summary>\n/// WRITE side. Validates commands against its OWN state (never the read model), publishes events, returns nothing.\n/// InvalidOperationException messages: \"Product already registered: sku\", \"Unknown product: sku\",\n/// \"Quantity must be positive\", \"Insufficient stock for sku\" (checked in this order). A rejected command publishes nothing.\n/// </summary>\npublic class InventoryCommands\n{\n    private readonly EventBus bus;\n\n    public InventoryCommands(EventBus bus) { this.bus = bus; }\n\n    public void RegisterProduct(string sku, string name) { throw new NotImplementedException(); }\n    public void ReceiveStock(string sku, int quantity) { throw new NotImplementedException(); }\n    public void ShipStock(string sku, int quantity) { throw new NotImplementedException(); }\n}\n\npublic class ProductView\n{\n    public string Sku { get; set; }\n    public string Name { get; set; }\n    public int OnHand { get; set; }\n    public int Shipped { get; set; }\n\n    public override string ToString() { return Sku + \"|\" + Name + \"|\" + OnHand + \"|\" + Shipped; }\n}\n\n/// <summary>READ side: a projection built only from events, plus queries that return copies.</summary>\npublic class InventoryReadModel\n{\n    public void Apply(InventoryEvent e) { throw new NotImplementedException(); }\n\n    /// <summary>A copy of the view, or null.</summary>\n    public ProductView GetProduct(string sku) { throw new NotImplementedException(); }\n\n    /// <summary>Products with OnHand &lt; threshold, sorted by OnHand, then by Sku (copies).</summary>\n    public IReadOnlyList<ProductView> LowStock(int threshold) { throw new NotImplementedException(); }\n}\n","testCount":9},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Consumer;\n\nabstract class InventoryEvent {\n    final String sku;\n    InventoryEvent(String sku) { this.sku = sku; }\n}\n\nfinal class ProductRegistered extends InventoryEvent {\n    final String name;\n    ProductRegistered(String sku, String name) { super(sku); this.name = name; }\n}\n\nfinal class StockReceived extends InventoryEvent {\n    final int quantity;\n    StockReceived(String sku, int quantity) { super(sku); this.quantity = quantity; }\n}\n\nfinal class StockShipped extends InventoryEvent {\n    final int quantity;\n    StockShipped(String sku, int quantity) { super(sku); this.quantity = quantity; }\n}\n\n/** In-process event bus (ready). */\nclass EventBus {\n    private final List<Consumer<InventoryEvent>> handlers = new ArrayList<>();\n    void subscribe(Consumer<InventoryEvent> handler) { handlers.add(handler); }\n    void publish(InventoryEvent event) { for (Consumer<InventoryEvent> h : handlers) h.accept(event); }\n}\n\n/**\n * WRITE side. Validates commands against its OWN state (never the read model), publishes events, returns nothing.\n * Messages: \"Product already registered: sku\", \"Unknown product: sku\" (IllegalStateException),\n * \"Quantity must be positive\" (IllegalArgumentException), \"Insufficient stock for sku\" (IllegalStateException),\n * checked in this order. A rejected command publishes nothing.\n */\nclass InventoryCommands {\n    private final EventBus bus;\n\n    InventoryCommands(EventBus bus) { this.bus = bus; }\n\n    void registerProduct(String sku, String name) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void receiveStock(String sku, int quantity) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void shipStock(String sku, int quantity) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\nclass ProductView {\n    String sku;\n    String name;\n    int onHand;\n    int shipped;\n\n    ProductView(String sku, String name, int onHand, int shipped) {\n        this.sku = sku;\n        this.name = name;\n        this.onHand = onHand;\n        this.shipped = shipped;\n    }\n\n    @Override\n    public String toString() { return sku + \"|\" + name + \"|\" + onHand + \"|\" + shipped; }\n}\n\n/** READ side: a projection built only from events, plus queries that return copies. */\nclass InventoryReadModel {\n    void apply(InventoryEvent event) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    Optional<ProductView> getProduct(String sku) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** Products with onHand < threshold, sorted by onHand, then by sku (copies). */\n    List<ProductView> lowStock(int threshold) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":9},{"lang":"go","runner":"judge0","starter":"package main\n\n// Event is something that happened to a product.\ntype Event interface{ SKU() string }\n\n// ProductRegistered, StockReceived and StockShipped are the events of the inventory.\ntype ProductRegistered struct{ Sku, Name string }\ntype StockReceived struct {\n\tSku      string\n\tQuantity int\n}\ntype StockShipped struct {\n\tSku      string\n\tQuantity int\n}\n\nfunc (e ProductRegistered) SKU() string { return e.Sku }\nfunc (e StockReceived) SKU() string     { return e.Sku }\nfunc (e StockShipped) SKU() string      { return e.Sku }\n\n// EventBus is an in-process event bus (ready).\ntype EventBus struct{ handlers []func(Event) }\n\nfunc (b *EventBus) Subscribe(handler func(Event)) { b.handlers = append(b.handlers, handler) }\nfunc (b *EventBus) Publish(e Event) {\n\tfor _, h := range b.handlers {\n\t\th(e)\n\t}\n}\n\n// InventoryCommands is the WRITE side. It validates commands against its OWN state (never the read model)\n// and publishes events. Errors: \"product already registered: <sku>\", \"unknown product: <sku>\",\n// \"quantity must be positive\", \"insufficient stock for <sku>\" (checked in this order).\n// A rejected command publishes nothing.\ntype InventoryCommands struct {\n\tbus *EventBus\n\t// TODO: the write model\n}\n\n// NewInventoryCommands creates the write side.\nfunc NewInventoryCommands(bus *EventBus) *InventoryCommands {\n\treturn &InventoryCommands{bus: bus}\n}\n\nfunc (c *InventoryCommands) RegisterProduct(sku, name string) error  { return nil } // TODO\nfunc (c *InventoryCommands) ReceiveStock(sku string, qty int) error { return nil } // TODO\nfunc (c *InventoryCommands) ShipStock(sku string, qty int) error    { return nil } // TODO\n\n// ProductView is one row of the read model.\ntype ProductView struct {\n\tSku     string\n\tName    string\n\tOnHand  int\n\tShipped int\n}\n\n// InventoryReadModel is the READ side: a projection built only from events, plus queries.\ntype InventoryReadModel struct {\n\t// TODO\n}\n\n// NewInventoryReadModel creates an empty read model.\nfunc NewInventoryReadModel() *InventoryReadModel { return &InventoryReadModel{} }\n\n// Apply updates the projection with one event.\nfunc (m *InventoryReadModel) Apply(e Event) {} // TODO\n\n// Product returns a copy of the view; false when unknown.\nfunc (m *InventoryReadModel) Product(sku string) (ProductView, bool) { return ProductView{}, false } // TODO\n\n// LowStock returns products with OnHand < threshold, sorted by OnHand, then by Sku.\nfunc (m *InventoryReadModel) LowStock(threshold int) []ProductView { return nil } // TODO\n","testCount":9}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.519Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hurtownia ceramiki ma jeden model "},{"type":"text","text":"Product","marks":[{"type":"code"}]},{"type":"text","text":" z ORM-a, który obsługuje i przyjęcia towaru, i raport „co trzeba domówić”. Raport robi złączenia i sortowania na tabelach, których potrzebuje też zapis, a reguły biznesowe (nie wysyłamy więcej, niż jest na stanie) mieszają się z formatowaniem widoków. "},{"type":"text","text":"CQRS","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Command Query Responsibility Segregation","marks":[{"type":"italic"}]},{"type":"text","text":") rozdziela te odpowiedzialności: strona zapisu przyjmuje komendy i pilnuje reguł, strona odczytu buduje widoki skrojone pod zapytania – a łączą je zdarzenia."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Szyna zdarzeń "},{"type":"text","text":"EventBus","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"subscribe","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"publish","marks":[{"type":"code"}]},{"type":"text","text":") i typy zdarzeń są gotowe: "},{"type":"text","text":"ProductRegistered(sku, name)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"StockReceived(sku, quantity)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"StockShipped(sku, quantity)","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strona zapisu – ","marks":[{"type":"bold"}]},{"type":"text","text":"InventoryCommands(bus)","marks":[{"type":"code"}]},{"type":"text","text":" z komendami "},{"type":"text","text":"registerProduct(sku, name)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"receiveStock(sku, quantity)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"shipStock(sku, quantity)","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"waliduje na "},{"type":"text","text":"własnym","marks":[{"type":"bold"}]},{"type":"text","text":" stanie (np. słownik "},{"type":"text","text":"sku → stan","marks":[{"type":"code"}]},{"type":"text","text":"), nigdy na modelu odczytu – musi działać nawet wtedy, gdy nikt nie subskrybuje szyny;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"błędy w tej kolejności: "},{"type":"text","text":"Product already registered: <sku>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Unknown product: <sku>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Quantity must be positive","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Insufficient stock for <sku>","marks":[{"type":"code"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"po udanej walidacji publikuje jedno zdarzenie; odrzucona komenda nie publikuje niczego;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"komendy nic nie zwracają (w Go – tylko "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Strona odczytu – ","marks":[{"type":"bold"}]},{"type":"text","text":"InventoryReadModel","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"apply(event)","marks":[{"type":"code"}]},{"type":"text","text":" – projekcja aktualizująca widoki "},{"type":"text","text":"{ sku, name, onHand, shipped }","marks":[{"type":"code"}]},{"type":"text","text":" wyłącznie na podstawie zdarzeń;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"getProduct(sku)","marks":[{"type":"code"}]},{"type":"text","text":" – kopia widoku albo „brak”;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"lowStock(threshold)","marks":[{"type":"code"}]},{"type":"text","text":" – produkty z "},{"type":"text","text":"onHand < threshold","marks":[{"type":"code"}]},{"type":"text","text":", posortowane rosnąco po stanie, a przy remisie po "},{"type":"text","text":"sku","marks":[{"type":"code"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"zapytania zwracają "},{"type":"text","text":"kopie","marks":[{"type":"bold"}]},{"type":"text","text":" – zmiana zwróconego obiektu nie zmienia modelu."}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Testy łączą obie strony przez szynę, ale sprawdzają też każdą osobno: komendy bez żadnego subskrybenta i model odczytu odbudowany z zapisanej listy zdarzeń. Nazwy w językach: "},{"type":"text","text":"register_product","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"low_stock","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"on_hand","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":" (Python); "},{"type":"text","text":"InvalidOperationException","marks":[{"type":"code"}]},{"type":"text","text":" (C#); "},{"type":"text","text":"IllegalStateException","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"IllegalArgumentException","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"Optional<ProductView>","marks":[{"type":"code"}]},{"type":"text","text":" (Java); w Go "},{"type":"text","text":"NewInventoryCommands","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"NewInventoryReadModel","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Product(sku) (ProductView, bool)","marks":[{"type":"code"}]},{"type":"text","text":", komunikaty błędów małą literą, a zdarzenia publikowane jako wartości ("},{"type":"text","text":"ProductRegistered{...}","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b09417c5ce40d447918f299","slug":"aws-sqs","title":"Amazon SQS w praktyce – kolejki standard i FIFO, long polling, DLQ, idempotencja, SNS fan-out i Lambda (Node.js, C#, Python)"},{"id":"6b08bd3e80884893657cca2e","slug":"vertical-slice-architecture","title":"Architektura pionowych wycinków: kod według funkcji, nie według warstw"},{"id":"6b08bd3c80884893657cc9dd","slug":"observer","title":"Obserwator (Observer): powiadom wszystkich, nie znając nikogo"},{"id":"6b08bd3a80884893657cc9be","slug":"microservices","title":"Mikroserwisy: niezależne wdrożenia, prawdziwe koszty i kiedy to się opłaca"},{"id":"6b08bd3a80884893657cc9aa","slug":"mediator","title":"Mediator: komponenty rozmawiają przez koordynatora"},{"id":"6b08bd3380884893657cc94c","slug":"event-sourcing","title":"Event sourcing: zapisuj fakty, a nie tylko ostatni stan"}],"topicsInfo":[{"slug":"cqrs","title":"CQRS","group":"architecture","icon":"split"},{"slug":"event-driven-architecture","title":"Architektura sterowana zdarzeniami","group":"architecture","icon":"zap"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:25.520Z","updatedAt":"2026-11-27T08:22:25.520Z"}