Skip to content

Report Low Stock and Download the Project

The Course
•
22 min study

A report that only prints JSON makes people search for what matters. Extend it so that, after the snapshot, it prints a second line naming every item with fewer than 2 units, in name order, or none. The change belongs in execute in app.go, and it reads the ledger only through Items, the sorted iterator from Day 3, so it cannot change any state.

In the case "report": branch, replace the line return string(data), nil with:

Go
var low []string
for item, quantity := range l.Items() {
	if quantity < 2 {
		low = append(low, item)
	}
}
if len(low) == 0 {
	return string(data) + "\nLow stock: none", nil
}
return string(data) + "\nLow stock: " + strings.Join(low, ", "), nil

app.go already imports strings. The output stays one block per command, because run prints whatever execute returns with a single Fprintln.

Extend the report Go
package main import ( "context" "fmt" "os" ) func main() { if err := run(context.Background(), os.Stdin, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } package main import ( "errors" "fmt" ) // Limits that bound every input before it can change the ledger. const ( maxQuantity = 1000 // per stock command or order line maxStock = 10000 // per item, at any time maxOrderLines = 8 maxLineBytes = 200 maxCommands = 1000 ) var ( errItem = errors.New("item names use 1-20 lowercase letters, digits or hyphens") errOrderID = errors.New("order IDs use 1-12 letters or digits") errQuantity = errors.New("quantity must be 1-1000") errDuplicateItem = errors.New("item is listed twice") errOrderLines = errors.New("orders take 1-8 lines") errCapacity = errors.New("stock would exceed 10000") errConflict = errors.New("order ID reused with different lines") errUnknownOrder = errors.New("order not found") errCancelled = errors.New("order is cancelled") errLineTooLong = errors.New("line is longer than 200 bytes") errTooManyCommands = errors.New("input has more than 1000 commands") ) // Line is one item and quantity in a stock command or an order. type Line struct { Item string Quantity int } // ShortageError reports the first item an order could not reserve. type ShortageError struct { Item string Have int Need int } func (e *ShortageError) Error() string { return fmt.Sprintf("not enough %s: have %d, need %d", e.Item, e.Have, e.Need) } package main import ( "cmp" "errors" "fmt" "slices" "strconv" "strings" ) // Command is one parsed input line. type Command struct { Verb string ID string // the order ID, for order and cancel Lines []Line // one line for stock, sorted by item for order } func validItem(name string) bool { if len(name) < 1 || len(name) > 20 { return false } for _, r := range name { if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') { return false } } return true } func validOrderID(id string) bool { if len(id) < 1 || len(id) > 12 { return false } for _, r := range id { if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') { return false } } return true } func parseQuantity(text string) (int, error) { n, err := strconv.Atoi(text) if err != nil || n < 1 || n > maxQuantity { return 0, errQuantity } return n, nil } // parseOrder reports every bad entry at once, joined into one error. func parseOrder(id string, entries []string) (Command, error) { if !validOrderID(id) { return Command{}, fmt.Errorf("%q: %w", id, errOrderID) } if len(entries) < 1 || len(entries) > maxOrderLines { return Command{}, fmt.Errorf("order %s: %w", id, errOrderLines) } var problems []error seen := make(map[string]bool) lines := make([]Line, 0, len(entries)) for _, entry := range entries { item, quantity, ok := strings.Cut(entry, ":") if !ok { problems = append(problems, fmt.Errorf("%q: use ITEM:QUANTITY", entry)) continue } if !validItem(item) { problems = append(problems, fmt.Errorf("%q: %w", item, errItem)) continue } if seen[item] { problems = append(problems, fmt.Errorf("%q: %w", item, errDuplicateItem)) continue } seen[item] = true n, err := parseQuantity(quantity) if err != nil { problems = append(problems, fmt.Errorf("%q: %w", item, err)) continue } lines = append(lines, Line{Item: item, Quantity: n}) } if err := errors.Join(problems...); err != nil { return Command{}, fmt.Errorf("order %s: %w", id, err) } // Sorting makes the line order irrelevant, so a reordered retry still matches. slices.SortFunc(lines, func(a, b Line) int { return cmp.Compare(a.Item, b.Item) }) return Command{Verb: "order", ID: id, Lines: lines}, nil } func parseCommand(text string) (Command, error) { fields := strings.Fields(text) verb, args := fields[0], fields[1:] switch verb { case "stock": if len(args) != 2 { return Command{}, errors.New("use stock ITEM QUANTITY") } if !validItem(args[0]) { return Command{}, fmt.Errorf("%q: %w", args[0], errItem) } n, err := parseQuantity(args[1]) if err != nil { return Command{}, err } return Command{Verb: verb, Lines: []Line{{Item: args[0], Quantity: n}}}, nil case "order": if len(args) == 0 { return Command{}, errors.New("use order ID ITEM:QUANTITY ...") } return parseOrder(args[0], args[1:]) case "cancel": if len(args) != 1 || !validOrderID(args[0]) { return Command{}, errors.New("use cancel ID") } return Command{Verb: verb, ID: args[0]}, nil case "report": if len(args) != 0 { return Command{}, errors.New("report takes no arguments") } return Command{Verb: verb}, nil default: return Command{}, fmt.Errorf("unknown command %q", verb) } } package main import ( "fmt" "iter" "maps" "slices" ) type order struct { lines []Line cancelled bool } // Ledger tracks stock and the orders that reserved it. Every method either // applies its whole change or returns an error and changes nothing. type Ledger struct { stock map[string]int orders map[string]order } func NewLedger() *Ledger { return &Ledger{stock: make(map[string]int), orders: make(map[string]order)} } // addStock returns have+n, or errCapacity if the sum would pass maxStock. // Comparing with maxStock-have cannot overflow, unlike computing have+n first. func addStock(have, n int) (int, error) { if n > maxStock-have { return 0, errCapacity } return have + n, nil } // Stock adds quantity to an item and returns its new total. func (l *Ledger) Stock(item string, quantity int) (int, error) { total, err := addStock(l.stock[item], quantity) if err != nil { return 0, fmt.Errorf("stock %s: %w", item, err) } l.stock[item] = total return total, nil } type Outcome int const ( Reserved Outcome = iota Replayed ) // Order reserves every line or none. Sending the same order ID with the same // lines again is a retry: it is recognized and reserves nothing more. func (l *Ledger) Order(id string, lines []Line) (Outcome, error) { if previous, exists := l.orders[id]; exists { if previous.cancelled { return 0, fmt.Errorf("order %s: %w", id, errCancelled) } if !slices.Equal(previous.lines, lines) { return 0, fmt.Errorf("order %s: %w", id, errConflict) } return Replayed, nil } staged := maps.Clone(l.stock) for _, line := range lines { have := staged[line.Item] if line.Quantity > have { return 0, fmt.Errorf("order %s: %w", id, &ShortageError{Item: line.Item, Have: have, Need: line.Quantity}) } staged[line.Item] = have - line.Quantity } l.stock = staged l.orders[id] = order{lines: slices.Clone(lines)} return Reserved, nil } // Cancel returns an open order's stock. It fails without changes if that // would take any item past maxStock. func (l *Ledger) Cancel(id string) error { previous, exists := l.orders[id] if !exists { return fmt.Errorf("order %s: %w", id, errUnknownOrder) } if previous.cancelled { return fmt.Errorf("order %s: %w", id, errCancelled) } staged := maps.Clone(l.stock) for _, line := range previous.lines { total, err := addStock(staged[line.Item], line.Quantity) if err != nil { return fmt.Errorf("cancel %s: %s: %w", id, line.Item, err) } staged[line.Item] = total } l.stock = staged previous.cancelled = true l.orders[id] = previous return nil } // Items yields each item and its quantity in name order. func (l *Ledger) Items() iter.Seq2[string, int] { return func(yield func(string, int) bool) { for _, item := range slices.Sorted(maps.Keys(l.stock)) { if !yield(item, l.stock[item]) { return } } } } // Snapshot is the ledger's state in a form encoding/json writes canonically: // map keys come out sorted, so equal ledgers produce identical bytes. type Snapshot struct { Stock map[string]int `json:"stock"` Orders map[string]string `json:"orders"` } func (l *Ledger) Snapshot() Snapshot { orders := make(map[string]string, len(l.orders)) for id, o := range l.orders { orders[id] = "open" if o.cancelled { orders[id] = "cancelled" } } return Snapshot{Stock: maps.Clone(l.stock), Orders: orders} } package main import ( "context" "sync" ) // mapConcurrent applies f to every item on up to workers goroutines and // returns the results in input order. If ctx is cancelled first, it returns // ctx.Err() and no results. func mapConcurrent[T, R any](ctx context.Context, items []T, workers int, f func(T) R) ([]R, error) { workers = max(1, min(workers, len(items))) results := make([]R, len(items)) jobs := make(chan int) var wg sync.WaitGroup for range workers { wg.Add(1) go func() { defer wg.Done() for i := range jobs { results[i] = f(items[i]) // each index has exactly one writer } }() } send: for i := range items { select { case jobs <- i: case <-ctx.Done(): break send } } close(jobs) wg.Wait() if err := ctx.Err(); err != nil { return nil, err } return results, nil } package main import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "iter" "strings" ) const workers = 4 type numbered struct { line int text string } type parsed struct { line int cmd Command err error } // numberedLines yields every line with its 1-based number. Check // scanner.Err after the loop. func numberedLines(scanner *bufio.Scanner) iter.Seq2[int, string] { return func(yield func(int, string) bool) { for number := 1; scanner.Scan(); number++ { if !yield(number, scanner.Text()) { return } } } } // readCommands reads all input before anything runs, so input that breaks a // limit is rejected as a whole. func readCommands(r io.Reader) ([]numbered, error) { scanner := bufio.NewScanner(r) // A scanner returns lines shorter than its buffer, with or without a final // newline. Both the initial capacity and the maximum count, so setting // both to one byte over the limit enforces the limit exactly. scanner.Buffer(make([]byte, 0, maxLineBytes+1), maxLineBytes+1) var input []numbered last := 0 for number, text := range numberedLines(scanner) { last = number text = strings.TrimSpace(text) if text == "" { continue } if len(input) == maxCommands { return nil, fmt.Errorf("line %d: %w", number, errTooManyCommands) } input = append(input, numbered{line: number, text: text}) } if err := scanner.Err(); err != nil { if errors.Is(err, bufio.ErrTooLong) { return nil, fmt.Errorf("line %d: %w", last+1, errLineTooLong) } return nil, err } return input, nil } func execute(l *Ledger, cmd Command) (string, error) { switch cmd.Verb { case "stock": line := cmd.Lines[0] total, err := l.Stock(line.Item, line.Quantity) if err != nil { return "", err } return fmt.Sprintf("Stocked %s: %d", line.Item, total), nil case "order": outcome, err := l.Order(cmd.ID, cmd.Lines) if err != nil { return "", err } if outcome == Replayed { return "Replayed " + cmd.ID, nil } return "Reserved " + cmd.ID, nil case "cancel": if err := l.Cancel(cmd.ID); err != nil { return "", err } return "Cancelled " + cmd.ID, nil case "report": data, err := json.Marshal(l.Snapshot()) if err != nil { return "", err } return string(data), nil default: return "", fmt.Errorf("unknown command %q", cmd.Verb) } } // run parses every command concurrently, then applies them one at a time in // input order. Rejected commands are reported and skipped. Read, write and // cancellation failures end the run. func run(ctx context.Context, r io.Reader, w io.Writer) (err error) { input, err := readCommands(r) if err != nil { return fmt.Errorf("read input: %w", err) } commands, err := mapConcurrent(ctx, input, workers, func(n numbered) parsed { cmd, err := parseCommand(n.text) return parsed{line: n.line, cmd: cmd, err: err} }) if err != nil { return err } out := bufio.NewWriter(w) defer func() { if flushErr := out.Flush(); flushErr != nil && err == nil { err = fmt.Errorf("write output: %w", flushErr) } }() ledger := NewLedger() for _, p := range commands { text, cmdErr := "", p.err if cmdErr == nil { text, cmdErr = execute(ledger, p.cmd) } if cmdErr != nil { // errors.Join separates problems with newlines; keep one line per command. text = fmt.Sprintf("Line %d: %s", p.line, strings.ReplaceAll(cmdErr.Error(), "\n", "; ")) } if _, err := fmt.Fprintln(out, text); err != nil { return fmt.Errorf("write output: %w", err) } } return nil } stock tent 5 stock drill 2 order A1 tent:2 drill:1 order A1 drill:1 tent:2 order A2 tent:4 order A1 tent:3 cancel A1 order A3 lamp:0 Tent:1 report

Check the extension

With the sample input, the last line is Low stock: none, because the cancel returned all the stock. That alone does not test much. Change the input and check the edges of the rule:

  • Only report: there are no items at all, so the answer is none.
  • stock lamp 3, order A1 lamp:2, then report: the lamp has exactly 1 unit and is listed.
  • stock tent 2 and report: 2 units is not fewer than 2, so the tent is not listed.
  • stock tent 1, stock lamp 1, then report: both are listed, as lamp, tent, in name order.
Exercise

Make the threshold a rule

Change the extension so the threshold is a named constant, lowStockLimit, defined in types.go with the other limits. Then explain why the report uses l.Items() instead of ranging over l.stock directly.

Hint 1: the idea

Limits that describe the program's promises live together in one place, where a reader can find them.

Hint 2: a first step

Add lowStockLimit = 2 to the const block in types.go and compare quantity < lowStockLimit.

Worked solution

With lowStockLimit = 2 in the constant block, the comparison reads quantity < lowStockLimit, and anyone reviewing the limits sees the new rule next to maxStock and the others.

Ranging over l.stock would visit the items in a different order on different runs, so the low-stock line would change while the ledger stayed the same, and transcript checks would fail at random. Items yields the items sorted by name, and it keeps the report independent of how the ledger stores its stock.

Download the project

Download the order ledger to work with it locally. Extract it, then from the order-ledger folder, run:

Shell
go run . < sample.txt
go test -race .

The download needs Go 1.24 or newer. It contains the same six source files as the editor, plus checks.go, ledger_test.go, which runs checkLedger under go test, the sample input, and a README describing the commands and limits. Make the low-stock change again locally, and add a check for it to checks.go, so that go test protects the new rule the way it protects the others.

Expect go test to fail first

Right after you make the low-stock change, before writing any new check, go test . fails:

Text
--- FAIL: TestLedgerContract (0.00s)
    ledger_test.go:7: unexpected transcript: "Stocked tent: 5\n ... \"orders\":{\"A1\":\"cancelled\"}}\nLow stock: none\n"
FAIL

Your edit didn't break the ledger. checkRun in checks.go compares the program's complete output for a fixed input with a want string, and the report now has one more line. That is the transcript check doing its job: it notices any change to the output, intended or not. Read the transcript it printed, confirm the only difference is the new Low stock: none line at the end, and then add that line to want, so it ends with `...{"A1":"cancelled"}}` + "\nLow stock: none\n". go test -race . passes again. Then add your own check for the edges listed above.

Was this article helpful?

Your response is saved on this device.