PeaBox Lab › PeaLang › Learn › Chapter 17 › Lesson 3

Part III — Advanced Systems · Chapter 17 · Lesson 3 of 7 · 7 min read

Lesson 3: Connector SDK, Transport Injection, Retries, Errors, and Pagination

Lesson level: Advanced

Purpose: Design external-service connectors that are testable, bounded, observable, and safe to operate.

Release note. The project materials describe a connector SDK core with a connector registry, injectable transport, runtime authentication headers, retries and backoff, errors, DataFrame conversion, REST pagination, and GraphQL cursor pagination. API names below remain illustrative unless verified in the installed reference.

Learning objectives

By the end of this lesson, you will be able to:

3.1 What a connector is

A connector translates between an external service protocol and PeaLang’s portable values or DataFrames. It manages request construction, authentication, response parsing, error mapping, pagination, retries, and resource limits.

A connector should not hide business decisions. Its job is to retrieve or send data according to an explicit contract. Validation, enrichment, and policy decisions should remain visible in the pipeline or domain module.

Connector contract fields: service name, operations, required capabilities, authentication method, request limits, response schema, pagination model, retry policy, error categories, timeout, and certification status.

Common mistake. Treating a successful status code as proof of valid data. A service can return a successful response with missing fields, an empty page, a changed schema, or an error envelope in the body.

3.2 Registry and capability declarations

A connector registry maps approved connector names to implementations and descriptors. The descriptor should state supported operations and limitations so that a workflow can check compatibility before execution.

Registration is not authorization. A connector may be installed while a specific module remains denied network access or a particular service profile. The host should decide which registered connectors and profiles each module can use.

Illustrative descriptor. Connector: inventory_rest; operations: list_items and get_item; authentication: bearer token from secret reference; pagination: next-link; maximum page size: bounded; retry: transient network and documented throttling responses only; output: approved item schema.

3.3 Transport injection

Transport injection separates protocol logic from the mechanism that sends requests. Production uses a real HTTP transport. Tests use a fake transport that returns recorded or synthetic responses without network access.

This makes connector behavior deterministic. Tests can simulate successful pages, malformed JSON, throttling, timeouts, authentication failure, and changed schemas. The test can also assert that the connector sent the expected method, path, parameters, and non-secret headers.

Illustrative fake transport. Return page one with two items and a next token; return page two with one item and no next token; then raise an error if a third request occurs. The test proves that pagination stops correctly.

Never place real credentials in recorded responses or request snapshots. Redact authorization headers, cookies, signed URLs, account identifiers, and personal data before storing test fixtures.

Common mistake. Mocking the entire connector rather than the transport. That tests the mock, not the connector’s request construction, parsing, error mapping, or pagination.

Guided practice. List five fake-transport scenarios for an inventory connector and state the expected connector outcome for each.

Review prompt. Why does transport injection make the network boundary easier to secure as well as easier to test?

3.4 Error classification

A connector should convert transport and service failures into stable categories. Callers can then make policy decisions without parsing provider-specific messages.

Useful categories: invalid request, authentication failure, authorization failure, not found, conflict, throttled, transient service failure, timeout, malformed response, schema mismatch, limit exceeded, and unknown failure. Preserve a safe provider status and correlation identifier where available.

Do not expose secrets or full response bodies by default. Error bodies may contain tokens, internal URLs, personal data, or attacker-controlled text. Retain only the fields needed for diagnosis and log them according to policy.

Illustrative mapping. A rejected token becomes authentication failure; a valid identity without permission becomes authorization failure; a documented throttling response becomes throttled; malformed JSON becomes malformed response; a missing required field becomes schema mismatch.

3.5 Retries and backoff

Retries can recover from brief network or service disruption. They can also amplify an outage, duplicate writes, exceed budgets, and hide persistent faults. Every retry policy needs eligibility rules, a maximum attempt count, backoff, total deadline, and observability.

Retry idempotent reads more freely than writes. For a write, retry only when the operation is idempotent or protected by an idempotency key accepted by the service. Do not retry validation, authentication, authorization, or conflict errors unless the policy explicitly defines a corrective step.

Use exponential backoff with jitter where appropriate to reduce synchronized retry storms. Respect a provider’s documented retry-after information when available, subject to the caller’s total deadline.

Illustrative policy. Retry read requests after timeout or transient service failure up to three attempts within an overall deadline; increase delay between attempts; stop immediately for authentication, authorization, invalid request, and schema errors; record attempt count and final category.

Common mistakes. Unlimited retries; retrying each page independently without a total deadline; ignoring cancellation; retrying a non-idempotent payment request; and counting a delayed success as if no service issue occurred.

Review prompt. Why must retry limits be combined with an overall deadline?

3.6 Pagination models

Large services return results in pages. Common models include offset and limit, page numbers, next links, and opaque cursors. The materials identify REST pagination and GraphQL cursor pagination in the connector foundation.

A pagination contract must define the first request, the continuation token or link, the stopping condition, maximum page size, maximum total pages or records, and duplicate handling. An empty page, missing continuation, repeated continuation, or unexpected loop needs a clear outcome.

Offset pagination can skip or repeat records when data changes during traversal. Cursor or snapshot-based traversal can be more stable, but only if the service documents that behavior. Never assume consistency that the provider does not guarantee.

Illustrative cursor traversal. Request the first page; validate records; append them; read the next cursor; stop when no cursor is returned; fail if the same cursor repeats; fail if record or page limits are exceeded; reconcile unique keys at the end.

Next links deserve security review. Follow only links within the approved service origin and path policy. A malicious or misconfigured response must not redirect the connector to an arbitrary host with the caller’s credentials.

3.7 DataFrame conversion

Convert responses into DataFrames only after validating the response contract. Flatten nested records deliberately, preserve keys, and keep representation decisions from Chapter 16: grain, null policy, units, timestamps, and identifiers.

Paginated data should share one schema. If page two adds or changes a field, the connector must apply the schema-evolution policy rather than silently producing inconsistent columns.

Guided practice. Design a pagination and conversion contract for a service returning orders with nested customer data. State page limits, cursor rules, origin validation, schema checks, duplicate-key reconciliation, and failure categories.

Common mistakes. Using a next link from another host; failing to detect cursor loops; concatenating pages with incompatible schemas; retaining all raw pages unnecessarily; and treating a partial traversal as a complete extract.

Review prompt. What evidence distinguishes a complete paginated extract from one that stopped early because of a limit or failure?

3.8 Hands-on lab: A fake-transport connector test suite

Scenario. Build or adapt a connector for a hypothetical inventory REST service. Do not call a live service. Inject a fake transport that serves synthetic responses.

Required scenarios. Two-page success; empty first page; malformed JSON; missing required field; repeated cursor; next link to an unapproved host; throttling followed by success; persistent timeout; authentication failure; authorization failure; and record limit exceeded.

For each scenario, assert the requests sent, number of attempts, final result or error category, validated row count, and absence of secrets in logs. Use deterministic backoff timing in tests rather than real sleeps.

Acceptance criteria. The connector never follows unapproved links; retries only eligible failures; respects attempt and deadline limits; detects cursor loops; validates the response schema; preserves keys; and reports partial traversal clearly.

Review questions. What is a connector registry? Why is transport injection useful? Which failures are retryable? Why must writes use idempotency protection before retry? How can pagination become infinite? Why should next links be origin-checked?

Applied challenge. Add a write operation that creates inventory adjustments. Require an idempotency key, define its uniqueness window, and describe how the connector reports an ambiguous timeout after the request may have reached the service.

Lesson summary. A sound connector separates protocol mechanics from business logic, injects transport for testing, classifies errors, retries conservatively, traverses pagination safely, and validates data before conversion.

Common mistakes

Review questions

Applied challenge

Write a connector for a paginated JSON API using an injected fake transport. Simulate a rate-limit response, a timeout, and an authentication failure, and show that only the first two are retried. Convert all pages into one DataFrame with a declared schema.

Lesson summary

Connectors isolate external systems behind a tested contract. Inject transports, classify errors, retry only transient failures with bounded backoff, follow pagination to the end, and convert results with explicit schemas.

Lesson status: Ready for review.

← Previous Next →