Skip to content

Trace a Command Through the Files

The Course
•
20 min study

The ledger is split into files by responsibility, so that each rule lives in one place and can be checked on its own:

  • main.go connects run to stdin, stdout and a background context, and turns a returned error into a message and exit status 1.
  • types.go holds the limits, the sentinel errors, Line and ShortageError.
  • parse.go turns one line of text into a Command. It validates names and quantities, joins every problem in an order, and sorts order lines.
  • ledger.go owns the state. Stock, Order and Cancel each apply their whole change or none, and Items and Snapshot read it.
  • pool.go holds the generic mapConcurrent.
  • app.go reads the bounded input, runs the pipeline and writes the output.

The pipeline in run

run has three stages, and each has its own kind of failure:

  1. Read. readCommands ranges over numberedLines, an iter.Seq2 over a scanner whose buffer enforces the 200-byte limit. It skips blank lines and counts commands. A limit failure ends the run before anything else happens.
  2. Parse. mapConcurrent runs parseCommand on four workers. A parse error does not stop the pool: it is stored in that command's parsed value. Only cancellation of the context ends this stage early.
  3. Apply. One loop applies each command to a fresh Ledger in input order, through execute, and writes one line per command to a bufio.Writer. A deferred Flush reports a late write failure through the named result err.

Open each file in the editor below as you read, and find the function each stage calls.

Trace the ledger 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

Why parsing is concurrent and applying is not

Parsing a line needs nothing but the line, so the four workers can parse in any order without affecting one another, and the results are stored by index. Applying a command depends on every command before it: whether order A2 tent:4 fits depends on what A1 reserved. So the ledger applies commands strictly in order, on one goroutine, and never needs a lock. The design keeps all shared state out of the concurrent part.

Exercise

Trace a rejected order

Follow order A2 tent:4 on line 6 of the sample. Which function decides it is valid input? Which one rejects it, with what error value, and how does that value become the printed line? Why does the rejection leave the drill stock untouched, even in an order that also asks for a drill?

Hint 1: the idea

Valid input and an acceptable request are different questions, answered in different files.

Hint 2: a first step

Start in parseOrder in parse.go, then find where ShortageError is created in ledger.go, then look at the loop at the end of run.

Worked solution

parseOrder accepts the line: A2 is a valid ID, tent a valid item and 4 a valid quantity. The ledger's Order then stages the reservation on maps.Clone(l.stock), finds 3 tents where 4 are needed, and returns fmt.Errorf("order %s: %w", id, &ShortageError{...}). execute passes that error back to run, which formats it as Line 6: followed by the message, replacing any newlines from joined errors with "; ".

An order that also listed a drill would have staged the drill on the copy before failing on the tent. The copy is dropped when Order returns the error, and l.stock is only replaced after every line has passed. So no other line of a rejected order is ever reserved.

Was this article helpful?

Your response is saved on this device.