Skip to content

Checkpoint: Safe Import and Replay

The Course
•
40 min study

The input adapter is where text becomes engine calls, and it is where most real-world surprises arrive: Windows line endings, stray blank lines, a typo in the middle of a batch, a file with no final newline. This checkpoint builds the adapter's core with today's tools. Lines are borrowed and parsed into owned events; events collect into a pending batch; a blank line or end of input hands the batch to a staged apply. Three stages, kept separate, so that each one has a single job.

One rule shapes the design: if any line in an input batch is malformed, the whole batch is rejected, even its valid lines. The person who wrote those lines meant them as a unit. Applying the parts that happened to parse would commit a change nobody asked for.

Predict and run

Predict before running C++
#include <iostream>
#include <vector>

int main() {
    std::vector<int> deltas{-3,-3};
    int quantity = 10;
    for (int delta : deltas) { quantity += delta; }
    std::cout << quantity << "\n";
    return 0;
}
Check your prediction
Text
4

The same adjustment applied twice takes effect twice. That is what replaying a log does in this engine: it is not idempotent. Repeating a Create is rejected as a duplicate, but repeating adjust|2|-3 subtracts again. Canonical text does not change that, because two identical lines are two requests. Making retries safe would need a request ID that the engine remembers and refuses to apply twice, a deduplication token. The project deliberately does not implement one, and the brief says so, so that no consumer mistakes "same text" for "same request". An item ID identifies the item, not the request.

What you will use

  • std::getline over a stream. Here a prefilled std::istringstream, so the program needs no keyboard input; the real adapter reads std::cin the same way.
  • CRLF handling. A line that ends in \r came from a Windows file; drop that one character before parsing.
  • A strict parser returning an optional or a variant. Each line becomes an owned event or a failure.
  • A pending batch and a malformed flag. After a malformed line, the adapter consumes lines until the next blank line and rejects the batch.
  • A staged apply. The batch either commits whole or leaves the inventory untouched.

Plan before you type

  1. Read each line. Strip one trailing \r.
  2. On a blank line, flush: if the batch was malformed, count a rejection; else if it has events, apply it and count the result; if it was empty and clean, count nothing. Then clear the pending state.
  3. On a non-blank line while malformed, skip it.
  4. Otherwise parse it. On failure, set the malformed flag; on success, append the event.
  5. At end of input, flush once more, so a final batch without a trailing blank line still counts.
  6. Run the same input twice and watch the replay apply its adjustments again.
Prove it can fail

Change step 4 so that a malformed line is skipped but the flag is not set. The second batch then applies adjust|1|-2 and adjust|2|1, the counts become accepted 3, rejected 0, and the inventory changes to 1:4 2:6. Then restore the flag and remove the final flush after the loop: the last batch, which has no blank line after it, silently disappears, and item 1 stays at 7.

Mistakes worth checking for

  • Every batch after a Windows file's first line is malformed. The \r was left on the line, so -3\r is not a number. Strip it before parsing.
  • Two blank lines in a row count as a rejected or accepted batch. The flush counted an empty, clean batch. Count only batches that had events or a malformed line.
  • The last batch is ignored. There is no flush after the loop. End of input is a separator too.
  • Lines after a malformed line are applied as a new batch. The malformed flag was reset on the next line instead of at the next blank line.
  • implicit instantiation of undefined template 'std::tuple_size<...>' at a call to apply. A free function named apply called with standard library arguments can lose to std::apply, found through argument-dependent lookup. Give the helper a more specific name, such as apply_batch.
  • Parsed events point into the line buffer. An event that stores a std::string_view of line changes or dangles when getline overwrites it. Events own their data.

Practice

Exercise

Your turn

Write void import(std::istream& input, std::map<int,int>& inventory, int& accepted, int& rejected) for adjust|id|delta lines, using the plan. Apply each batch to a staged copy and reject a missing ID or a quantity outside 0..1000. Start from {1:10, 2:0} and import the text below twice, printing the counts and inventory after each import:

Shell
first import: accepted 2, rejected 1 | 1:6 2:5
after replay: accepted 4, rejected 2 | 1:2 2:10
Your workspace C++
#include <charconv>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

const std::string text = "adjust|1|-3\nadjust|2|5\n\nadjust|1|-2\nbogus\nadjust|2|1\n\n\nadjust|1|-1\r\n";

int main() {
    std::map<int,int> inventory{{1, 10}, {2, 0}};
    int accepted = 0, rejected = 0;
    // Write import, then run it twice on text.
    return 0;
}
Hint 1: the idea

The adapter has three pieces of state: the pending events, the malformed flag and the counters. A blank line and the end of input both run the same flush.

Hint 2: a first step

Write std::optional<std::pair<int,int>> parse(std::string_view line) that requires the adjust| prefix and two strict numbers, and a flush lambda inside import that captures the pending vector and flag by reference.

Show one solution
Run the solution C++
#include <charconv>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

const std::string text = "adjust|1|-3\nadjust|2|5\n\nadjust|1|-2\nbogus\nadjust|2|1\n\n\nadjust|1|-1\r\n";

std::optional<int> number(std::string_view field) {
    int value = 0;
    const auto [end, error] = std::from_chars(field.data(), field.data() + field.size(), value);
    if (error != std::errc{} || end != field.data() + field.size()) { return std::nullopt; }
    return value;
}

std::optional<std::pair<int,int>> parse(std::string_view line) {
    if (!line.starts_with("adjust|")) { return std::nullopt; }
    line.remove_prefix(7);
    const auto bar = line.find('|');
    if (bar == std::string_view::npos) { return std::nullopt; }
    const auto id = number(line.substr(0, bar));
    const auto delta = number(line.substr(bar + 1));
    if (!id || !delta || *delta < -1000 || *delta > 1000) { return std::nullopt; }
    return std::pair{*id, *delta};
}

bool apply_batch(std::map<int,int>& live, const std::vector<std::pair<int,int>>& batch) {
    auto staged = live;
    for (const auto& [id, delta] : batch) {
        auto found = staged.find(id);
        if (found == staged.end()) { return false; }
        const int next = found->second + delta;
        if (next < 0 || next > 1000) { return false; }
        found->second = next;
    }
    live.swap(staged);
    return true;
}

void import(std::istream& input, std::map<int,int>& inventory, int& accepted, int& rejected) {
    std::vector<std::pair<int,int>> pending;
    bool malformed = false;
    auto flush = [&] {
        if (malformed) { ++rejected; }
        else if (!pending.empty()) { (apply_batch(inventory, pending) ? accepted : rejected) += 1; }
        pending.clear();
        malformed = false;
    };
    std::string line;
    while (std::getline(input, line)) {
        if (!line.empty() && line.back() == '\r') { line.pop_back(); }
        if (line.empty()) { flush(); continue; }
        if (malformed) { continue; }
        if (auto event = parse(line)) { pending.push_back(*event); } else { malformed = true; }
    }
    flush();
}

void report(const char* label, const std::map<int,int>& inventory, int accepted, int rejected) {
    std::cout << label << ": accepted " << accepted << ", rejected " << rejected << " |";
    for (const auto& [id, quantity] : inventory) { std::cout << " " << id << ":" << quantity; }
    std::cout << "\n";
}

int main() {
    std::map<int,int> inventory{{1, 10}, {2, 0}};
    int accepted = 0, rejected = 0;
    std::istringstream first(text);
    import(first, inventory, accepted, rejected);
    report("first import", inventory, accepted, rejected);
    std::istringstream again(text);
    import(again, inventory, accepted, rejected);
    report("after replay", inventory, accepted, rejected);
    return 0;
}
Text
first import: accepted 2, rejected 1 | 1:6 2:5
after replay: accepted 4, rejected 2 | 1:2 2:10

The two blank lines before the last batch produced no count, and the CRLF on the last line was harmless. The replay applied both valid batches a second time, so item 2 went from 5 to 10: correct behavior for this engine, and exactly why it must be documented. The project's main.cpp has the same structure, with a flush function, a 256-event cap that marks an oversized batch malformed, and a final flush after the loop. Day 6 asks how you know all of this is right, and answers with tests designed to fail.

Was this article helpful?

Your response is saved on this device.