Skip to content

[Improve][Connector-V2] Migrate SensorsData validation to OptionRule - #12315

Merged
davidzollo merged 1 commit into
apache:devfrom
Nikk8091:issue-11007-sensorsdata-validation
Sep 24, 2026
Merged

davidzollo merged 1 commit into
apache:devfrom
Nikk8091:issue-11007-sensorsdata-validation

Conversation

@Nikk8091

Copy link
Copy Markdown
Contributor

Purpose of this pull request

This PR handles the connector-sensorsdata sink slice of #11007.

It registers server_url as a required option with a declarative nonblank constraint and registers consumer as an optional option. The existing consumer = batch default and the existing batch/console runtime behavior are unchanged. No SDK, format, network, timeout, retry, or runtime validation is added.

The existing English and Chinese connector documentation already describes server_url as required and consumer as optional with the batch default.

Does this PR introduce any user-facing change?

Yes. Missing, empty, and whitespace-only server_url values are now rejected during factory configuration validation. Existing nonblank URLs and both batch and console consumer configurations remain valid.

How was this patch tested?

Added focused SensorsDataSDKFactoryTest coverage for:

  • valid batch and console configurations;
  • missing server_url;
  • empty server_url;
  • whitespace-only server_url;
  • omitted consumer, confirming it still defaults to batch.

Validation results:

  • ./mvnw spotless:apply — passed.
  • ./mvnw -pl seatunnel-connectors-v2/connector-sensorsdata -DskipITs verify — passed (13 tests, 0 failures, 0 errors).
  • git diff --check — passed.
  • ./mvnw -q -DskipTests verify — attempted; it reached connector-jdbc-e2e-part-2 and stopped on a Maven Central connection reset while resolving error_prone_annotations:2.38.0. No SensorsData failure was reported.

Check list

  • No new Jar binary package is added.
  • Existing English and Chinese SensorsData documentation already matches this validation contract.
  • No incompatible configuration name, default, or runtime behavior is introduced.
  • No connector registration, distribution, label, E2E, or plugin configuration changes are required because this updates validation for an existing connector only.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution! I went through the full diff and traced how optionRule() is actually used at runtime, and this is a real, useful fix — nice catch.

What Problem Does This PR Solve?

User pain point: server_url is an absolutely required field for the SensorsData sink (the connector cannot connect to anything without it, and the docs already describe it as "Required: Yes"), and consumer is a documented, supported option with a default of batch. Neither of them, however, was actually declared in SensorsDataSDKSinkFactory#optionRule() before this PR — only bulk_size, max_cache_row_size, skip_error_record, and instant_events were listed. Because SeaTunnel's --check / conf-validate dry-run path (ConfigValidator.validateUnknownKeys, wired up in ConfigValidationUtils.validateSinks for the Flink/Spark starters, and in SeaTunnelConfValidateCommand for the Zeta starter) rejects any config key that isn't declared in the connector's OptionRule, any user who ran the config-validate/dry-run command with a legitimate server_url or consumer key in their SensorsData sink config would get a false-positive unknown option keys error — even though the exact same config would run fine. Worse, a user who genuinely forgot server_url entirely would pass that same dry-run check and only discover the mistake much later, when the job actually starts and the SDK client has no server to talk to.

Fix approach: register SERVER_URL as .required(..., notBlank(SERVER_URL)) (rejects both a missing key and a present-but-blank/whitespace-only value) and register CONSUMER as .optional(...), so the OptionRule now matches what SensorsDataSDKSinkConfig already reads and what the docs already promise.

One-sentence summary: this makes the SensorsData sink's declared OptionRule finally match its actual, documented configuration contract, so config validation catches a missing server_url early instead of silently letting it through to fail at runtime.

1. Code Change Review

1.1 Core Logic Analysis

Files/methods with the core change:

  • SensorsDataSDKSinkFactory.java:optionRule() — the actual fix (6 lines).
  • SensorsDataSDKFactoryTest.java — 5 new tests plus 2 shared helpers.

Before:

public OptionRule optionRule() {
    return SensorsDataBaseOptionRules.getBaseOptionRuleBuilder()
            .optional(
                    SensorsDataSDKSinkOptions.BULK_SIZE,
                    SensorsDataSDKSinkOptions.MAX_CACHE_ROW_SIZE,
                    SensorsDataOptions.SKIP_ERROR_RECORD,
                    SensorsDataSDKSinkOptions.INSTANT_EVENT_LIST)
            .build();
}

SERVER_URL and CONSUMER are both defined in SensorsDataSDKSinkOptions and both are actually consumed by SensorsDataSDKSinkConfig (config.get(SensorsDataSDKSinkOptions.SERVER_URL) / .CONSUMER), but neither appears anywhere in this OptionRule — they were simply missing.

After:

public OptionRule optionRule() {
    return SensorsDataBaseOptionRules.getBaseOptionRuleBuilder()
            .required(
                    SensorsDataSDKSinkOptions.SERVER_URL,
                    notBlank(SensorsDataSDKSinkOptions.SERVER_URL))
            .optional(
                    SensorsDataSDKSinkOptions.BULK_SIZE,
                    SensorsDataSDKSinkOptions.MAX_CACHE_ROW_SIZE,
                    SensorsDataSDKSinkOptions.CONSUMER,
                    SensorsDataOptions.SKIP_ERROR_RECORD,
                    SensorsDataSDKSinkOptions.INSTANT_EVENT_LIST)
            .build();
}

Key findings:

  • This is the normal path, not a boundary path: optionRule() is called on every config validation, both at job submission time (indirectly, since SensorsDataSDKSinkConfig always reads these two keys) and, more importantly for this bug, directly by the config-validate/dry-run tooling described above.
  • I confirmed ConfigValidator.validate(OptionRule) (the "value/required constraint" check, used generally) does not filter or strip config keys that aren't declared — ReadonlyConfig.get(Option) reads straight from the raw source map regardless of what's in OptionRule. So this bug never broke the connector's actual data-plane behavior (the sink always worked correctly if server_url was supplied) — it only broke: (a) the separate validateUnknownKeys dry-run check (false-positive rejection of valid configs), and (b) the ability to fail fast on a genuinely missing server_url instead of failing later inside the SDK client.
  • SensorsDataBaseOptionRules.getBaseOptionRuleBuilder() (the shared base used by this sink) only registers entity_name/record_type/their conditionals — server_url and consumer are sink-specific and correctly scoped to SensorsDataSDKSinkOptions, so this change has no blast radius into any other SensorsData entry point (e.g. a source, if one exists) that shares the base builder.
  • The .required(option, notBlank(option)) pattern used here is exactly the documented pattern from Conditions.java's own class-level example (.required(HOST, notBlank(HOST))), and I traced ConfigValidator.collectErrors/isConstraintApplicable/structurallyAbsentKeys to confirm the two failure modes are correctly separated: a missing key produces exactly the "required option is not configured" error (the notBlank value-constraint is correctly skipped via structurallyAbsentKeys so there's no confusing double error), while a present-but-blank value correctly falls through to the notBlank value-constraint error instead.
  • Precise fix, not a workaround — it makes the code match behavior the documentation already promised; it introduces no new validation semantics beyond what docs/en/connectors/sink/SensorsData.md and docs/zh/connectors/sink/SensorsData.md already describe (server_url: Required = Yes; consumer: Required = No, default batch).

Runtime path — why a user could previously get a false "unknown option" rejection:

User runs `bin/seatunnel.sh --config sensorsdata-sink.conf --check`
  (or Flink/Spark `... check` command)
  -> SeaTunnelConfValidateCommand / ConfigValidationUtils.validateSinks() [pre-existing, not part of this diff]
      -> for each sink config: ConfigValidator.validateUnknownKeys(readonlyConfig, sinkFactory.optionRule(), pluginName)
          -> declaredKeys = collectDeclaredKeys(SensorsDataSDKSinkFactory.optionRule())
              -- before this PR: declaredKeys does NOT contain "server_url" or "consumer" --
          -> user's config contains "server_url" (required!) and/or "consumer"
          -> validatePaths(...) finds "server_url" not in declaredKeys -> unknownKeys.add("server_url")
          -> throw OptionValidationException("... has unknown option keys: [server_url] ...")
      -- a perfectly valid, working SensorsData sink config is rejected by the dry-run checker --

Separately, real job-submission path (Zeta engine, normal run, not --check):
  -> SensorsDataSDKSinkConfig(ReadonlyConfig config)
      -> this.serverUrl = config.get(SensorsDataSDKSinkOptions.SERVER_URL)
          -- reads directly from the raw map regardless of OptionRule declaration --
          -- if server_url was omitted entirely, this returns null, and the job only fails
             later when the SDK client tries to connect with a null server URL --

1.2 Compatibility Impact

Fully compatible. No default value, protocol, or serialization change. bulk_size, max_cache_row_size, skip_error_record, instant_events are untouched. The only externally observable change is that config validation now:

  1. Correctly accepts server_url/consumer in the --check/dry-run path (previously a false-positive rejection — strictly a fix, not a behavior change for any config that was actually working).
  2. Correctly rejects a sink config that omits server_url (or sets it to blank/whitespace) at validation time instead of only at runtime. Any config that omitted server_url was already guaranteed to fail once the job actually ran (the SDK client has nothing to connect to), so this cannot turn a previously-working job into a failing one — it only moves the failure earlier and makes it clearer.

No entry in incompatible-changes.md is needed since no previously-working configuration is affected.

1.3 Performance / Side-Effect Analysis

Zero runtime/data-path impact — this only changes a static OptionRule definition evaluated once at connector-factory construction/validation time, not per-record. No CPU, memory, GC, networking, locking, or concurrency implications.

1.4 Error Handling and Logging

OptionValidationException is the existing, correct mechanism for surfacing this (same exception type used by every other connector's required-option validation). No new exception types, no swallowed exceptions, nothing sensitive logged.

No blocking issues found. One low-severity, non-blocking observation:

Issue 1: notBlank only checks for a non-empty/non-whitespace string, not a syntactically valid URL

  • Location: seatunnel-connectors-v2/connector-sensorsdata/src/main/java/org/apache/seatunnel/connectors/sensorsdata/sdk/sink/SensorsDataSDKSinkFactory.java:46-48
  • Problem description: server_url is validated for presence/non-blankness only; a garbage non-blank string (e.g. "x") still passes config validation and only fails later when the SDK actually tries to connect.
  • Potential risk: minor UX gap only — it does not regress anything (this exact gap already existed for every other required string option in this connector, e.g. entity_name/record_type also get no format validation), and it's consistent with how this project's OptionRule framework is typically used elsewhere (deep format validation is usually left to the connector's own runtime/client, not the config layer).
  • Best improvement: optional follow-up only — e.g. Conditions.matches(SERVER_URL, urlPattern) if the project wants stronger fail-fast guarantees for this field. Not necessary for this PR's stated scope (migrating existing, documented behavior into OptionRule).
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Follows the existing style of this factory class and matches the documented usage pattern for .required(option, condition) from Conditions.java. No new core methods or nontrivial fields were introduced that would require additional Javadoc — the change is confined to registering pre-existing, already-documented options.

2.2 Test Coverage and Test Stability

Five new tests were added to SensorsDataSDKFactoryTest.java, all driven through the real ConfigValidator.of(readonlyConfig).validate(OPTION_RULE) path (not a hand-rolled check), which is the right level to test at:

  • testValidServerUrlAndConsumerConfigurations — both consumer=batch and consumer=console pass validation with a valid server_url.
  • testMissingServerUrlRejected — key entirely absent is rejected.
  • testEmptyServerUrlRejected — empty string is rejected.
  • testWhitespaceOnlyServerUrlRejected — whitespace-only string is rejected (I confirmed ConditionOperator.NOT_BLANK's evaluator uses .trim().isEmpty(), so this genuinely exercises different logic than the empty-string case, not a duplicate assertion).
  • testOmittedConsumerDefaultsToBatch — omitting consumer still resolves to the documented default batch.

This is solid coverage of the critical path (required-vs-absent, blank-vs-whitespace, default-value resolution) and the base-required fields (entity_name/record_type) are correctly included in the shared validConfig() helper so the new assertions aren't accidentally passing for unrelated reasons.

Mandatory test-stability analysis (Section 5.10.2): this PR only touches unit-test code with no timing, concurrency, containers, network, or shared/static state involved — every assertion is a synchronous call against an in-memory ReadonlyConfig/OptionRule. No Thread.sleep, no nondeterministic data, no ordering dependencies between tests.

Stability rating: Stable. No flaky-test anti-patterns present.

One minor, non-blocking gap: there's no explicit test for server_url present with only leading/trailing whitespace around an otherwise-valid URL (e.g. " https://host:8106/sa ") actually being accepted after a hypothetical trim — but that's out of scope since this connector doesn't trim the value before use, so it's not a regression, just a coverage note.

2.3 Documentation Updates

No documentation changes are needed. I checked docs/en/connectors/sink/SensorsData.md and docs/zh/connectors/sink/SensorsData.md, and both already correctly describe server_url as Required: Yes and consumer as Required: No, default: batch — the docs and this code change are now consistent (they were previously describing a contract the code didn't actually enforce). No English/Chinese doc inconsistency found.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. It closes the gap between the documented contract, the actually-consumed config keys, and the declared OptionRule with the smallest possible change, using the framework's own intended idiom.

3.2 Maintainability

Straightforward and self-explanatory; future readers of optionRule() will now see an accurate picture of this connector's real configuration surface, which also makes any auto-generated option documentation/tables correct.

3.3 Extensibility

No new pattern introduced beyond what OptionRule/Conditions already provide; nothing hard-coded that would need generalizing later.

3.4 Historical-Version Compatibility

Fully compatible with historical versions/configs; no upgrade action required. Any config that was already functioning (i.e. already included a non-blank server_url) is unaffected.

4. Issue Summary

# Issue Location Severity
1 notBlank validates presence, not URL format, for server_url SensorsDataSDKSinkFactory.java:46-48 Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed

    • None.
  2. Recommended fixes — non-blocking

    • Issue 1 (Low): optional follow-up if stronger fail-fast URL-format validation is ever desired; not required for this PR's scope.

Overall assessment: small, well-scoped, well-tested fix that brings the connector's OptionRule in line with its already-documented and already-implemented configuration contract. I don't see a better alternative approach — this is exactly the right, minimal fix.

On CI: the "Build" check is currently showing FAILURE, but I traced it to the actual failing job (unit-test (8, ubuntu-latest)) and it is a pure infrastructure flake unrelated to this PR: Maven failed to resolve io.kubernetes:client-java:19.0.1 from Maven Central for the unrelated seatunnel-engine-k8s-e2e module (Connection reset during artifact download). Notably, the SensorsData-specific jobs in the same run (E2E : Connector V2 : SensorsData and connector-sensorsdata-it on both JDK 8 and 11) all passed. This isn't something a dev sync would fix — it's a one-off network blip — so the simplest next step is just re-running the failed job. Happy to take another look if it fails again for a different reason.

Thanks again for cleaning this up!

@Nikk8091

Copy link
Copy Markdown
Contributor Author

Confirmed:

I will keep further SensorsData scope and review discussion on #12315. Thank you.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for confirming, @Nikk8091 — that matches what I traced in my review: the change is scoped to SensorsDataSDKSinkFactory#optionRule() plus the SensorsDataSDKFactoryTest coverage, and the existing EN/ZH docs already described this contract (server_url required, consumer optional with the batch default), so no doc changes were needed.

My conclusion from before stands — ready to merge, no blockers, Issue 1 (no URL-format validation on server_url, only presence/non-blankness) remains an optional, non-blocking follow-up if you or a future contributor ever want it. CI is green on this head (5eab743f), so this is mergeable from my side whenever a maintainer picks it up.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick follow-up, no new code to review here — nothing has changed since my last pass. My last review already concluded "Ready to merge" with no blockers, and the only open item was the unit-test job failure that I traced to an unrelated Maven-resolution network blip (io.kubernetes:client-java:19.0.1 failing to download for the unrelated seatunnel-engine-k8s-e2e module), not anything in this PR's own SensorsData-specific jobs. I just rechecked the current head (5eab743f7) and the required Build check is now SUCCESS. Formally updating my review to approve, since that was the only thing this PR was waiting on.

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1
LGTM

Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

@davidzollo
davidzollo added this pull request to the merge queue Sep 24, 2026
Merged via the queue into apache:dev with commit 6fac4cc Sep 24, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants