connector-sink
Author a new Apache Iggy connector sink plugin under sinks/. Sinks consume messages from Apache Iggy streams and push them to an external system (DB, search engine, HTTP endpoint, object store). Load when creating, modifying, or reviewing a sink crate. Use for sink plugin authoring. NOT for runtime internals (see connector-runtime).
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-14
- Stars
- ★ 5
- Forks
- 9
01 前言 Front Matter
- name
- connector-sink
- description
- Author a new Apache Iggy connector sink plugin under sinks/. Sinks consume messages from Apache Iggy streams and push them to an external system (DB, search engine, HTTP endpoint, object store). Load when creating, modifying, or reviewing a sink crate. Use for sink plugin authoring. NOT for runtime internals (see connector-runtime).
02 资源文件 1
- 参考文档TEMPLATE.md5.9 KB
03 SKILL.md 正文
Writing an Apache Iggy Connector Sink
A sink is a Rust cdylib that implements iggy_connector_sdk::Sink
and exposes FFI symbols via the sink_connector! macro. The runtime
loads it as .so/.dylib/.dll, polls Apache Iggy on its behalf,
runs the transform chain, decodes via the configured Schema, and
hands the sink batches of ConsumedMessage. The sink is responsible
for getting them to the external system reliably and efficiently.
Universal connector rules (SecretString, benchmark, verbose flag, drop accounting, filter contract, exemplar patterns) live in connectors-overview. This skill covers only what's sink-specific.
Contents
STOP and ask the user before
- Changing the SDK trait surface (
Sink::open/consume/close) - that's an SDK change, not a plugin one. - Touching default
batch_size, retry caps, or backoff defaults baked into existing in-tree sinks. - Promoting an
Errvariant to retryable when it previously was not - retrying bad data trips circuit breakers. - Adding a new sink that introduces a backend the runtime doesn't yet integration-test for.
Quick reference
- Skeleton: TEMPLATE.md (load on demand when authoring).
- Exemplars:
stdout_sink(minimal),postgres_sink(DB + transient detection),http_sink(validation, batch modes, retry middleware),mongodb_sink(atomic counters),elasticsearch_sink/iceberg_sink(backend-specific idioms).
Hard rules
Lifecycle
Sink::consumetakes&self- never&mut self. Mutable state goes behindtokio::sync::Mutex/AtomicU64. Prefer atomics for hot counters -mongodb_sinkusesmessages_processed: AtomicU64+insertion_errors: AtomicU64and avoids a state lock on the hot path entirely.Sink::openbuilds the client AND tests connectivity. Fail fast withError::InitError.Sink::closeflushes + drops resources. Take ownership viaclient: Option<Client>+.take(). sqlx pools have.close().await. reqwest/mongodb/elasticsearch clients just drop. Log final stats either way.
Config
- Every runtime-tunable field is
Option<T>with a default applied innew(). Forward-compat: adding a field doesn't break existing TOML. - Durations:
Option<String>, parsed viahumantime::Durationinnew(). Two equivalent in-tree idioms - inlineHumanDuration::from_str(&raw).map(|d| *d).unwrap_or_else(..)(random_source,postgres_source) or a localparse_durationhelper (http_sink,sdk/src/retry.rs). Fall back to a default on parse failure withwarn!- never panic. We do not usehumantime_serde. - Conflict resolution: if two config fields can be in invalid relative ordering, fix it in
new()+warn!- don't error.http_sinkswapsretry_delayandmax_retry_delaywhen reversed to avoid anExponentialBackoffpanic downstream. - Validation order: structural in
new(), connectivity inopen(), never inconsume().
Payloads (efficiency-critical)
- Dispatch on the
Payloadvariant. HandleJson,Raw,TextandProtoat minimum.Protoholds text that is a JSON document whenproto_converthad no descriptor or could not encode, and arbitrary text otherwise: callPayload::json_document()first and fall back to the text handling when it returnsNone. Unsupported ->Error::InvalidPayloadTypeor fall back to base64 (elasticsearch_sink). - For
Payload::Json, calltry_to_bytes(&self)- single-pass serialization without cloning theOwnedValuetree (sdk/src/lib.rs::Payload::try_to_bytes). Neverpayload.clone().try_into_vec(). - To take a payload out of
ConsumedMessagewithout cloning:std::mem::replace(&mut message.payload, Payload::Raw(vec![])). Standard pattern acrosshttp_sink::send_individual/send_ndjson/send_json_array. - Pre-allocate per-batch buffers with
Vec::with_capacity(messages.len())(or* factorfor serialized bodies). Used acrosspostgres_sink,mongodb_sink,quickwit_sink,elasticsearch_sink,http_sink.
Headers
message.headers: Option<BTreeMap<HeaderKey, HeaderValue>>. Check.is_empty()before iterating - runtime treats empty asNone.- Name every header with
iggy_connector_sdk::HeaderName, never withto_string_value(), which collides1with"1"and renders raw keys as Debug text.HeaderNamegives each key one stable, unique name. - For a new sink that writes JSON, write the whole map with
iggy_connector_sdk::JsonHeaders({data, data_encoding}per value). For another value shape, take the text fromheaders::HeaderDataand the base64 check fromheaders::JsonHeaderValue::data_encoding. Seemeilisearch_sink::headers_document. - Released sinks keep their documented value shape: binary values as
v.as_raw()+ base64 (http_sink::EncodedHeader), text asv.to_string_value(). - Test header naming with the shared cases in
testing/src/headers.rs(header_cases,header_case_map). A sink that cannot write a case skips it by label, as RabbitMQ does withLONG_RAW_KEY_CASE. BTreeMapfor deterministic ordering. Don't collect intoHashMap.
Errors
| Scenario | SDK variant | Retry? |
|---|---|---|
| Init / connectivity failure | Error::InitError |
n/a (fails open) |
| Bad config value | Error::InvalidConfigValue(field) |
n/a |
| Single-message validation failure | Error::InvalidRecordValue(reason) |
no - skip + log; under at-least-once, fail the call (stops the sink) |
| Transient backend (5xx, conn reset, ...) | Error::HttpRequestFailed / Error::Connection / Error::CannotStoreData |
yes |
| Permanent 4xx, schema mismatch, constraint | Error::PermanentHttpError / Error::SchemaMismatch |
no - retrying trips circuit breakers |
| I/O failure mid-write (parquet/iceberg) | Error::WriteFailure |
caller decides |
| Catalog commit failure (Iceberg) | Error::CatalogCommitError |
not in place (txn consumed); under at-least-once, the runtime redelivers |
Error::is_permanent() (sdk/src/lib.rs) is the class the runtime acts on for an at-least-once sink: a permanent error stops the delivery, a transient one hands the messages over again. CatalogCommitError is transient there, because the redelivered messages rebuild the transaction, and a commit that did land shows up as a duplicate, which at-least-once allows.
Retry
- SDK helpers cover the simple case:
iggy_connector_sdk::retry::check_connectivity_with_retry(...)foropen(),HttpRetryMiddlewarefor default 429/5xx/network policy on reqwest clients. - Custom strategies:
reqwest-middleware+reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy.http_sinkdefines its ownHttpSinkRetryStrategy(honorssuccess_status_codes, per-status decisions). - Non-HTTP clients: write
is_transient_error(&e)mapping driver-specific codes.postgres_sink::is_transient_errormaps SQLSTATEs40001,40P01,57P01-03,08000/03/06. - Retry loop: new connectors use
iggy_connector_sdk::retry::retry_async(policy, context, should_retry, op)for anything that fails asErr. It owns attempt counting, backoff and the per-retry log, and returnsRetryFailure { error, attempts, exhausted }; the caller logs the terminal failure. - Backoff only, for a loop that computes its own delay (it retries on an
Okresponse, carries a deadline, or reconnects between attempts):retry_backoff(base, retry, max), whereretryis 1-based.exponential_backoffis the 0-based primitive underneath, and it applies no jitter; call it directly only when the delay must be exact, assdk/src/source.rs::nack_retry_delayneeds for its tests. - Cap retries at 3 total attempts.
Idempotency
Runtime retries on any Err - same batch can be redelivered. In-tree guarantees:
- Postgres (
postgres_sink::build_batch_insert_query): PK onid, but plainINSERT(noON CONFLICT). Duplicate retry triggers23505,is_transient_errordoes NOT mark it transient -> error propagates. AddingON CONFLICT (id) DO NOTHINGis a known improvement. - MongoDB: composite
_idfromstream:topic:partition:message_id, viainsert_many(docs).ordered(false). Per-document duplicate-key errors don't abort the batch - effective idempotency under retry. - Elasticsearch (
bulk_index_documents): bulk action specifies only_index, no_id-> ES auto-generates ids -> NOT idempotent. Extensions should add"_id". - HTTP: endpoint-dependent. Document in the plugin README.
- Iceberg: transactional commit per table.
router/commit.rstags each snapshot withiggy.commit-id, and a commit retry first checks whether the catalog already holds it. At least once,router/redelivery.rsrecords the first offset and the last message of each source partition in the snapshot summary. A redelivered batch that carries the last message of an append on the current snapshot history skips the start of the batch that such appends cover without a gap.
When writing a new sink, prefer dedup-on-write using the message id field. Mongo's upsert-style is the cleanest reference.
Batching
- Default
batch_size: 100. Tune per-backend. - Chunk via
messages.chunks(self.batch_size). Do not buffer acrossconsume()- runtime already batches at the consumer-poll boundary. - For HTTP backends support multiple batch modes when applicable (individual / ndjson / json_array / raw). See
http_sink::BatchMode.
Logging
info!("Opened <connector> connector ID: {}, endpoint: <redacted>", self.id);
debug!("Processing batch of {} messages, offset: {}", batch.len(), offset);
warn!("Retry {attempt}/{max} for <connector> ID: {}, reason: {error}", self.id);
error!("Failed to <op> for <connector> ID: {}, error: {error}", self.id);
info!("Closed <connector> connector ID: {}, processed: {}", self.id, count);
Use literal API field names as labels (offset=, current_offset=).
Common pitfalls
- Missing
[lib] crate-type = ["cdylib", "lib"]- runtime can't dlopen a regular rlib. - Cloning the whole
Payload::Jsonto serialize - usetry_to_bytes(&self). - Holding
Mutexacross.awaitwhen the locked region does I/O. &mut selfonconsume- won't compile. you need interior mutability.- Returning the first error and dropping subsequent batches - track
last_err, process all, return. - Forgetting to map
PermanentHttpError- retries hammer the backend with bad data. - Mutating config in
consume()- config is a snapshot fromnew(). Reload requires runtime restart. - Logging the connection string. Redact at construction:
http_sink::sanitize_url_for_logpopulatesHttpSink.log_url.
Tests
Unit tests at EOF of src/lib.rs. See connector-testing for BDD naming + test_config() helper.
Real-infra integration tests live in the sink's own test target sinks/<name>_sink/tests/<backend>/ (entry main.rs) using #[iggy_harness] + a backend fixture that spins up Docker via testcontainers-modules. Plugins integrating with external services must have an integration test. Reference: sinks/postgres_sink/tests/postgres/postgres_sink.rs + fixtures/.
Before declaring done
cargo fmt --all
cargo sort --no-format --grouped --workspace
cargo clippy -p iggy_connector_<name>_sink --all-targets -- -D warnings
cargo nextest run -p iggy_connector_<name>_sink --lib
# Integration tests (Docker, ./scripts/build-test-server.sh once per core pin).
# The harness launches target/debug/iggy-connectors, which loads the plugin from target/debug/:
cargo build -p iggy-connectors -p iggy_connector_<name>_sink
cargo nextest run -p iggy_connector_<name>_sink --test <backend> <test_name>
A new sink also needs its directory in members of the root Cargo.toml (new dependencies go to [workspace.dependencies]), a row for its test target in .config/rail.toml, a row in the sinks table of the root README.md, and a sample TOML under runtime/example_config/connectors/.
Discussion / help: see AGENTS.md.
04 同仓库更多 Skills
team-review
Four expert review of a PR, branch, or ref range. Use only when the user explicitly requests team-review.
connector-review
Adversarial review of a connectors PR, branch, or ref range, with clean-room validation of every finding. Experts work alone and use the focused connector skills as their source of subsystem rules. Use only when the user explicitly requests connector-review.
connectors-overview
Entry point and index for the Apache Iggy Connectors repository. Load this first when working anywhere in it - runtime, SDK, sinks, sources, transforms, or their tests. Routes to the focused per-area skills.
connector-transform
Add a new transform under `sdk/src/transforms/`. Transforms mutate, filter, or convert messages between source/encode and decode/sink. Use when adding field-level transforms (add/delete/update/filter), format conversions, envelope unwrapping, or similar config-driven message manipulations for Apache Iggy connectors. Use for transform authoring. NOT for runtime internals or sink/source loops.
connector-testing
Write tests for Apache Iggy connectors - sinks, sources, transforms, SDK, runtime. Covers BDD unit-test naming, the canonical source state round-trip tests, and the real-infra integration test targets under `<package>/tests/<suite>/` with `testcontainers-modules` + `#[iggy_harness]`. Load when writing or reviewing tests anywhere in this repository (`src/` unit tests, `tests/` targets, `testing/`). Use for connector test authoring. NOT for runtime internals or non-connector test patterns.
connector-source
Author a new Apache Iggy connector source plugin under sources/. Sources poll an external system (DB, API, queue) and produce messages into Apache Iggy streams. Load when creating, modifying, or reviewing a source crate. Use for source plugin authoring. NOT for runtime internals (see connector-runtime).