async Task HandleRequest(IConn conn) { using (conn) { var req = await conn.Read(5.Sec()); try { _env.Debug($"{req}"); await _env.SimulateWork(35.Ms()); switch (req) { case AddItemRequest r: await AddItem(conn, r); break; case MoveItemRequest r: await MoveItem(conn, r); break; case CountRequest r: var amount = _store.Count(); await conn.Write(new CountResponse(amount)); break; } } catch (Exception ex) { _env.Error($"Error while processing {req}", ex); } } }
async Task MoveItem(IConn conn, MoveItemRequest moveItemRequest) { var wasFrom = _store.GetItemQuantity(moveItemRequest.FromItemID); var wasTo = _store.GetItemQuantity(moveItemRequest.ToItemID); if (wasFrom < moveItemRequest.Amount) { await conn.Write(new ArgumentException("Insufficient amount")); return; } await Commit( new ItemAdded(moveItemRequest.ToItemID, moveItemRequest.Amount, wasTo + moveItemRequest.Amount), new ItemRemoved(moveItemRequest.FromItemID, moveItemRequest.Amount, wasFrom - moveItemRequest.Amount)); await conn.Write(new MoveItemResponse()); }
async Task AddItem(IConn conn, AddItemRequest addItemRequest) { var quantity = _store.GetItemQuantity(addItemRequest.ItemID); var total = quantity + addItemRequest.Amount; var evt = new ItemAdded(addItemRequest.ItemID, addItemRequest.Amount, total); await Commit(evt); await conn.Write(new AddItemResponse(addItemRequest.ItemID, addItemRequest.Amount, total)); }
async Task HandleAsync(IConn conn) { try { using (conn) { var req = await conn.Read(5.Sec()); switch (req) { case DownloadRequest dr: await conn.Write(_stored.Skip((int)dr.From).Take(dr.Count).ToList()); return; case CommitRequest cr: await _env.SimulateWork(5.Ms()); foreach (var e in cr.Events) { _buffer.Enqueue(e); } ScheduleStore(); await conn.Write("OK"); return; default: conn.Write($"Unknown request {req}"); return; } } } catch (Exception ex) { _env.Debug($"Error: {ex.Message}"); } }