Test iOS NDJSON stream framing on a cloud Mac

Test iOS NDJSON stream framing on a cloud Mac

Test iOS NDJSON stream framing on a cloud Mac

A studio integrates a streaming task API for two clients. Progress updates display reliably on the local machine, but regression tests on a cloud Mac occasionally report truncated JSON. Start by checking the framing: a single network delivery may contain only part of a record, or several records combined. Treating a callback as a message boundary is the most common starting point for this kind of failure.

Define the line-delimited record contract first

This article covers NDJSON: one JSON value per line, separated by LF. It is neither an event-stream protocol nor a continuously growing JSON array. To make client handoffs straightforward, the project also specifies that only top-level objects are accepted, CRLF is allowed, blank lines are rejected, and the final line must end with a newline too.

The maximum record size is 65536 bytes, excluding LF but including the optional CR. This is a policy for the example project, not a universal protocol limit. Measure the limit in bytes; counting Chinese characters is no substitute for measuring the transmitted length.

Receiving a complete line only means it is ready to decode. It does not mean the business operation has succeeded. Syntax validation, field validation, and committing business operations must remain separate.

These checks require only the command-line toolchain; there is no need to launch a simulator. Before running them remotely, save the output of xcrun swift --version so colleagues can reproduce the behavior with the same toolchain.

Build a bounded framer

Save the following code as NDJSONCheck.swift. The buffer grows byte by byte, and decoding happens only when LF arrives. Exceeding the limit causes an immediate failure. Finding delimiters at the byte level also avoids attempting string conversion in the middle of a multibyte character.

import Foundation

enum FrameError: Error {
    case tooLong, empty, invalidUTF8, notObject, unfinished
}

struct Framer {
    let limit: Int
    private var pending = Data()

    init(limit: Int = 65536) {
        precondition(limit > 0)
        self.limit = limit
    }

    mutating func feed(
        _ chunk: Data,
        emit: ([String: Any]) throws -> Void
    ) throws {
        for byte in chunk {
            if byte == 0x0A {
                var line = pending
                pending.removeAll(keepingCapacity: true)
                if line.last == 0x0D {
                    line.removeLast()
                }
                guard !line.isEmpty else {
                    throw FrameError.empty
                }
                guard String(data: line, encoding: .utf8) != nil else {
                    throw FrameError.invalidUTF8
                }
                let value = try JSONSerialization.jsonObject(
                    with: line,
                    options: [.fragmentsAllowed]
                )
                guard let object = value as? [String: Any] else {
                    throw FrameError.notObject
                }
                try emit(object)
            } else {
                guard pending.count < limit else {
                    throw FrameError.tooLong
                }
                pending.append(byte)
            }
        }
    }

    func finish() throws {
        guard pending.isEmpty else {
            throw FrameError.unfinished
        }
    }
}

When integrating this into a client, pass each received Data chunk to the same instance. Calls must run in a serial execution context; multiple concurrent tasks must not modify the buffer. Any parsing or callback error invalidates the current stream. Cancel the transfer and discard the instance rather than catching the error and continuing to reuse it.

Test every split point to verify record preservation

Do not rely on a real network to produce the right conditions by chance. Append the following code to the same file. It tests every possible split into two chunks, then adds a byte-by-byte input test. Together, these cover splits within characters, separation of CR from LF, and multiple records arriving in a single chunk.

func decode(_ chunks: [Data]) throws -> [Int] {
    var parser = Framer()
    var ids: [Int] = []
    for chunk in chunks {
        try parser.feed(chunk) { object in
            guard let id = object["id"] as? Int else {
                throw FrameError.notObject
            }
            ids.append(id)
        }
    }
    try parser.finish()
    return ids
}

let wire = Data(
    "{\"id\":1,\"text\":\"客户甲\"}\r\n{\"id\":2}\n".utf8
)

for cut in 0...wire.count {
    let chunks = [
        Data(wire.prefix(cut)),
        Data(wire.dropFirst(cut))
    ]
    precondition(try decode(chunks) == [1, 2])
}
precondition(
    try decode(wire.map { Data([$0]) }) == [1, 2]
)

Run xcrun swift NDJSONCheck.swift. A successful run produces no output; a failure returns a nonzero exit status. To run the example, first evaluate the throwing expressions used in the two precondition calls above: Swift assertion autoclosures do not accept throwing calls. Replace the corresponding statements with the following forms:

let actual = try decode(chunks)
precondition(actual == [1, 2])

For the byte-by-byte test, use:

let bytewise = try decode(wire.map { Data([$0]) })
precondition(bytewise == [1, 2])

Make invalid input part of the delivery gate

Once the valid samples pass, add at least five sets of failure fixtures: a newline with no content, a top-level array, invalid UTF-8, malformed JSON, and a missing final LF. Each set must assert that an error is actually thrown; merely checking that the program does not crash is not enough. An escaped newline inside a JSON string is a two-byte escape sequence and must not be treated as an actual LF that splits a line.

Test three length boundaries separately: valid content exactly at the limit must pass, one extra byte must fail, and input that keeps arriving without LF must also fail at the limit. The CR in CRLF counts toward the allowance, so changing the line-ending style can affect boundary fixtures.

Also construct a sequence of “valid line, bad line, valid line.” The first line may already have been delivered, but the bad line must terminate the stream, and the final line must never reach the business layer. Do not silently skip bad lines: clients would receive fewer records without any traceable failure signal.

Define the boundaries between disconnection and business completion

A bounded parser does not make the entire client bounded. If the receiving layer keeps appending every object to an array, a long-running task can still exhaust memory. A production implementation should limit the capacity of its consumer queue and pause reads or cancel the request when consumption cannot keep up.

Call finish() only after a normal end to the network stream. Treat network errors directly as failures; an empty buffer is not grounds for declaring the business operation complete. The API should also define a separate completion record and validate the task identifier and final count, so an early server disconnect is not mistaken for a complete result.

Keep the protocol version, length policy, split tests, and error fixtures for each client. Log only the error category, the number of records delivered, and the current line length—not the raw business payload. When moving to another cloud Mac later, rerun the same fixtures to verify the framing contract instead of relying on a single network demonstration that happens to go smoothly.

Frequently asked questions

Can each network callback be decoded as one NDJSON record?

No. A callback may contain part of a record or several records. Frame complete records using LF before decoding their JSON.

Should the final record be accepted without a newline?

This article uses a strict contract requiring LF after every record. Remaining bytes at completion are an error, not a complete record to deliver.

A dedicated Mac for every client project

Rent a dedicated physical Mac mini to keep each client's build environment separate. Choose daily, weekly, monthly, or quarterly billing; service stops at the end of your term unless you renew.

Rent a Mac

Rent a Mac for your next client project

Choose from two dedicated Mac mini plans and four billing periods. Match your setup to each project, with service stopping at the end of your term unless you renew.