diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..ed211da --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,79 @@ +name: Main + +# Runs only on push to main (i.e. when a PR is merged or someone pushes +# directly). This is where the full forward-compat JDK matrix runs and +# where we publish the canonical coverage snapshot that Codecov uses as +# the base for PR diffs. +on: + push: + branches: ['main'] + +permissions: + contents: read + +# Don't cancel main runs against each other — we want every merge to +# produce a coverage baseline. Sequential is fine; main pushes are rare. +concurrency: + group: main + cancel-in-progress: false + +jobs: + verify: + name: Verify (JDK ${{ matrix.java }}) + runs-on: ubuntu-latest + strategy: + # Don't cancel siblings: if JDK 21 fails, we still want to know + # whether 17 and 25 pass. + fail-fast: false + matrix: + # ADR-002: tests run on JDK 17, 21, 25 to catch forward-compat + # regressions. Compilation is always pinned to --release 17. + java: ['17', '21', '25'] + + steps: + - name: Checkout + uses: actions/checkout@v4 + + # Install both JDK 17 (for compilation) and the matrix JDK (for + # test execution). setup-java exports JAVA_HOME__; + # Gradle's toolchain auto-detection picks them up. + - name: Set up JDKs (compile=17, test=${{ matrix.java }}) + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 17 + ${{ matrix.java }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build, test, lint, coverage + run: ./gradlew build -PtestJdk=${{ matrix.java }} --stacktrace + + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports-jdk${{ matrix.java }} + path: | + build/reports/tests/ + build/test-results/ + retention-days: 14 + + # The JDK 17 entry of the matrix is the canonical run for coverage: + # its JaCoCo XML is uploaded to Codecov and becomes the base that + # subsequent PR runs compare against (see codecov.yml). + - name: Upload coverage to Codecov (JDK 17 only) + if: success() && matrix.java == '17' + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: build/reports/jacoco/test/jacocoTestReport.xml + fail_ci_if_error: true + + # Integration-tests job is intentionally not wired up yet: + # SDK requirements §13 says they run on PRs and release pipelines, but + # they hit the live API and require a MARKETDATA_TOKEN secret. Add this + # job (gated on `if: ${{ secrets.MARKETDATA_TOKEN != '' }}`) once the + # token is configured in the repo's GitHub Actions secrets. diff --git a/.github/workflows/pr-matrix-on-demand.yml b/.github/workflows/pr-matrix-on-demand.yml new file mode 100644 index 0000000..6c309ad --- /dev/null +++ b/.github/workflows/pr-matrix-on-demand.yml @@ -0,0 +1,159 @@ +name: PR matrix (on demand) + +# Manually triggered by commenting one of these slash commands on an +# open PR: +# /run-all-jdks +# /jdk-matrix +# /test-all +# Runs the forward-compat matrix (JDK 21, 25) — JDK 17 already runs +# automatically on every PR open/sync via pull-request.yml. +# +# Important security note: workflows triggered by `issue_comment` always +# run from the *default branch's* version of the workflow file, not from +# the PR. So adding/changing this file on a feature branch has no effect +# until it lands on main. +on: + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write # to react to the trigger comment + +# Multiple "run all versions" comments on the same PR cancel earlier runs. +concurrency: + group: pr-on-demand-${{ github.event.issue.number }} + cancel-in-progress: true + +jobs: + guard: + name: Guard + runs-on: ubuntu-latest + # Only fire on PR comments (not generic issue comments) that contain + # one of the three accepted slash commands. `contains` is substring + # match — false positives are possible but unlikely in practice given + # the leading slash and hyphen-rich shape of these tokens. + if: | + github.event.issue.pull_request != null && ( + contains(github.event.comment.body, '/run-all-jdks') || + contains(github.event.comment.body, '/jdk-matrix') || + contains(github.event.comment.body, '/test-all') + ) + outputs: + head_sha: ${{ steps.pr.outputs.head_sha }} + steps: + # Reject comments from anyone without write access. Otherwise an + # external user commenting on a fork PR could burn our CI minutes + # and potentially exfiltrate secrets via a malicious build. + - name: Verify commenter has write permission + uses: actions/github-script@v7 + with: + script: | + const { data: perm } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: context.payload.comment.user.login, + }); + const allowed = ['write', 'maintain', 'admin'].includes(perm.permission); + if (!allowed) { + core.setFailed( + `@${context.payload.comment.user.login} (${perm.permission}) ` + + `cannot trigger CI; write access required.` + ); + } + + # Visible feedback to the commenter that we picked up the trigger. + - name: React 👀 to the trigger comment + uses: actions/github-script@v7 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'eyes', + }); + + # The issue_comment event payload doesn't include the PR's head SHA, + # so look it up via the pulls API. We also confirm the PR is open; + # firing on closed PRs is almost always a mistake. + - name: Resolve PR head SHA + id: pr + uses: actions/github-script@v7 + with: + script: | + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.issue.number, + }); + if (pr.state !== 'open') { + core.setFailed(`PR #${pr.number} is ${pr.state}; refusing to run.`); + return; + } + core.setOutput('head_sha', pr.head.sha); + + verify: + name: Verify (JDK ${{ matrix.java }}) + needs: guard + runs-on: ubuntu-latest + strategy: + # If JDK 21 fails, we still want to know whether 25 passes. + fail-fast: false + matrix: + java: ['21', '25'] + + steps: + # Check out exactly the PR's HEAD commit, not the merge ref. + - name: Checkout PR head + uses: actions/checkout@v4 + with: + ref: ${{ needs.guard.outputs.head_sha }} + + # Compile=17, test=matrix JDK; same shape as main.yml. + - name: Set up JDKs (compile=17, test=${{ matrix.java }}) + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 17 + ${{ matrix.java }} + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Test on JDK ${{ matrix.java }} + run: ./gradlew test -PtestJdk=${{ matrix.java }} --stacktrace + + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports-jdk${{ matrix.java }} + path: | + build/reports/tests/ + build/test-results/ + retention-days: 14 + + # Post a single comment summarizing the on-demand matrix result so it's + # visible on the PR without diving into the Actions tab. + report: + name: Report + needs: verify + if: always() && needs.guard.result == 'success' + runs-on: ubuntu-latest + steps: + - name: Comment outcome + uses: actions/github-script@v7 + with: + script: | + const ok = '${{ needs.verify.result }}' === 'success'; + const emoji = ok ? '✅' : '❌'; + const status = ok ? 'passed' : 'failed'; + const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.issue.number, + body: `${emoji} On-demand JDK matrix \`{21, 25}\` ${status}. [View run](${runUrl}).`, + }); diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml new file mode 100644 index 0000000..0ced2ec --- /dev/null +++ b/.github/workflows/pull-request.yml @@ -0,0 +1,65 @@ +name: Pull Request + +# Triggers only on pull request lifecycle events: +# - opened (PR creation) +# - synchronize (push to the PR branch while the PR is open) +# - reopened +# These are the default `pull_request` activity types — listed explicitly +# here for clarity. Pre-PR pushes don't run CI by design (saves minutes +# during early WIP commits). +on: + pull_request: + types: [opened, synchronize, reopened] + branches: ['**'] + +permissions: + contents: read + +# Cancel an in-progress run when a new commit lands on the same PR. +concurrency: + group: pr-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + verify: + name: Verify (JDK 17) + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + # PRs only run on JDK 17 (the minimum target). Forward-compat + # regressions on JDK 21/25 are caught post-merge by main.yml. + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + # Validates the wrapper jar hash and caches Gradle home + wrapper + # dists between runs. + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build, test, lint, coverage + run: ./gradlew build --stacktrace + + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: | + build/reports/tests/ + build/test-results/ + retention-days: 14 + + # Coverage ratchet lives in Codecov: codecov.yml at the repo root + # configures `threshold: 5%` so a PR fails the Codecov status check + # if line coverage drops more than 5 pp vs the base branch. + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: build/reports/jacoco/test/jacocoTestReport.xml + fail_ci_if_error: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a958c90 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar + +# IDE — IntelliJ +.idea/ +*.iml +*.ipr +*.iws +out/ + +# IDE — Eclipse / VS Code +.classpath +.project +.settings/ +bin/ +.vscode/ + +# OS +.DS_Store +Thumbs.db + +# Local env +.env +.env.local + +# Logs / coverage +*.log +hs_err_pid* +replay_pid* diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4a4bb2e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Project scaffold per ADRs 001–006: Gradle Kotlin DSL build, JDK 17 toolchain, + `integrationTest` source set, Spotless + JaCoCo, Vanniktech Maven Publish. +- `MarketDataClient` skeleton with builder, default base URL + (`https://api.marketdata.app`), default API version (`v1`), 99 s request / + 2 s connect timeouts, HTTP/2, demo mode, `validateOnStartup` toggle, and a + 50-permit concurrency semaphore (wiring lands with the request layer). +- Configuration cascade: explicit builder values → `MARKETDATA_*` environment + variables → `.env` file in CWD → built-in defaults. +- Sealed `MarketDataException` hierarchy with the seven canonical subtypes + (`AuthenticationError`, `BadRequestError`, `NotFoundError`, `RateLimitError`, + `ServerError`, `NetworkError`, `ParseError`), each carrying support context + (`requestId`, `requestUrl`, `statusCode`, `timestamp`) and a + `getSupportInfo()` helper. +- `RateLimits` record exposed via `MarketDataClient.getRateLimits()`. +- JSpecify `@NullMarked` on every public package; JSpecify on `compileOnlyApi` + so consumers get the annotations at compile time without a runtime dep. +- Token redaction utility (`internal.Tokens`) for log output. +- MIT license; SDK version auto-detected from the JAR manifest + (`Implementation-Version`). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..39e7e02 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,92 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Repository state + +This repo currently contains **documentation only** — no Java sources, no build scripts. Branch `00_base_setup` is the pre-implementation phase: all foundational technical decisions are being captured as ADRs *before* code lands. There is therefore nothing to build, lint, or test yet. When implementation starts, the build will be Gradle (Kotlin DSL) per ADR-003 — see "Locked-in tech stack" below. + +Sibling repo: `../api/` is the backend (Python/Django). The Python SDK lives at `../../sdk-py/` (referenced from ADRs). The cross-language `sdk-requirements.md` is referenced as `../sdk-requirements.md` from inside `docs/`; it is canonical but not committed in this repo. + +## How decisions get made here + +The repo follows a strict **ADR-first** workflow: + +1. A new architectural choice is captured as `docs/adr/ADR-NNN-*.md` and reviewed. +2. Once the ADR is **Accepted**, the corresponding section is added to `docs/java-sdk-requirements.md` with a citation back to the ADR. +3. New requirements should not be added to `java-sdk-requirements.md` without an accepted source ADR. + +`docs/java-sdk-requirements.md` **supplements, not replaces**, the cross-language `sdk-requirements.md`. When the two conflict, the Java doc wins for the Java SDK only. + +When asked to make architectural changes, prefer updating an existing ADR or proposing a new one (status `Proposed`) over silently editing requirements. + +## Locked-in tech stack (ADRs 001–006, all Accepted) + +These decisions are not up for debate without amending the corresponding ADR: + +- **Java only.** Single artifact, no Kotlin sources. Published JAR must not bring `kotlin-stdlib` as a transitive dep. JSpecify is compile-time only and doesn't count. (ADR-001) +- **Kotlin consumers are first-class via interop, not via a Kotlin artifact.** A separate `marketdata-sdk-java-kotlin` extensions JAR (Option E) is deferred. (ADR-001) +- **JDK 17 minimum.** Build with `javac --release 17`; no multi-release JAR. CI test matrix is `{17, 21, 25}` for forward-compat. (ADR-002) +- **Gradle, Kotlin DSL.** `build.gradle.kts`, `settings.gradle.kts`, version catalog at `gradle/libs.versions.toml`. Standard plugins: `java-library`, `maven-publish`, Vanniktech Maven Publish (or Gradle Nexus Publish), Spotless, JaCoCo. Integration tests live in a separate `integrationTest` source set, env-var-gated. (ADR-003) +- **`java.net.http.HttpClient` exclusively.** No third-party HTTP client (OkHttp, Apache) as a runtime dep — ever. HTTP/2 on (default). One shared `HttpClient` per `MarketDataClient`. Timeouts: 99s request, 2s connect. (ADR-004) +- **Jackson (`jackson-databind`) for JSON.** Records-based response models (Jackson record support, 2.12+). The API's parallel-arrays wire format (e.g. `{"s":"ok","symbol":["AAPL","MSFT"],"price":[150.0,400.0]}`) is decoded via custom `JsonDeserializer` classes, *not* default reflection. Jackson is **not shaded** in v1; shading is held in reserve. (ADR-005) +- **Sync + async parity per endpoint.** Every public endpoint exposes both `quote(...)` and `quoteAsync(...)`; async returns `CompletableFuture`. **Internal logic is async-first.** Sync methods are thin wrappers that call `.join()` and unwrap `CompletionException` to surface the underlying cause directly. Both surfaces share validation, retry, rate-limit, and concurrency-pool logic — no parallel implementations. Tests must cover both variants for every endpoint. (ADR-006) + +## Kotlin-interop rules for the public API + +Even though sources are Java-only, Kotlin consumers are a first-class audience. Anything you put on the public API must satisfy these (see `docs/java-sdk-requirements.md` §2 for the full list): + +- `@NullMarked` at the package level (in `package-info.java`) so non-null is the default; mark nullable items explicitly with JSpecify `@Nullable`. Without these, Kotlin sees Java values as platform types (`String!`). +- **No Kotlin reserved words** as public method or parameter names: `object`, `is`, `in`, `fun`, `when`, `as`, `val`, `var`, `typealias`, `interface`, `package`, `typeof`, `out`, `super`. They force Kotlin callers into backticks. +- **Getters are property reads in Kotlin.** No expensive work, I/O, or observable side effects in `getFoo()` / `isFoo()`. Use consistent `getFoo` / `isFoo` naming. +- **Callbacks must be SAM** (single abstract method, no `default` second method). Prefer `java.util.function.*` types where applicable. +- **Wildcards on generic public APIs.** Producer params: `? extends T`. Consumer params: `? super T`. Missing wildcards translate to invariant Kotlin types. +- **Return standard JVM collections** (`List`, `Map`, `Set`); never arrays for variable-length results; return empty collections rather than `null`. +- **No `Optional` in fields or parameters.** `Optional` is only acceptable as a return type on Java-facing methods; Kotlin callers prefer nullable returns. +- **No `kotlinx-coroutines` dependency.** Kotlin consumers bridge `CompletableFuture` via `kotlinx-coroutines-jdk8`'s `await()` themselves. +- README and per-method docs must include a Kotlin example alongside the Java example for the quick-start path. + +## Why the JDK-17 features matter (don't second-guess them) + +ADR-002 picked JDK 17 specifically to enable two features that shape the public API: + +- **Records** for response models — collapses ~30 lines of POJO boilerplate per model. Use records by default for response shapes. +- **Sealed exception hierarchy** rooted at `MarketDataException`, permitting the closed set of error subtypes (`AuthenticationError`, `RateLimitError`, etc.). The point is compiler-enforced exhaustive `switch` at consumer call sites — adding a new subtype in a future major version must break consumer switches at compile time. + +If you find yourself reaching for Lombok, AutoValue, or an abstract-base exception class, stop — that's reverting an explicit ADR-002 decision. + +## Cross-language SDK requirements + +The Java SDK must also satisfy the canonical, cross-language [SDK Requirements](https://www.marketdata.app/docs/sdk/sdk-requirements/) (referenced from inside the ADRs as `../sdk-requirements.md`). The current scaffold applies the **foundational** rules from that doc; per-endpoint and per-request rules land alongside the request layer. Specifically: + +**Already wired in:** +- §1.1 client object — `MarketDataClient` builder, default base URL `https://api.marketdata.app`, default API version `v1`, single shared `HttpClient`, `User-Agent: marketdata-sdk-java/{version}` (version auto-detected from JAR manifest), `close()` for resource release, `getRateLimits()` accessor. +- §4 configuration cascade — `Configuration.resolve(...)` does explicit → `MARKETDATA_*` env var → `.env` in CWD → default. Env var names live in `internal.EnvVars`. +- §5 demo mode + `validateOnStartup` toggle on the builder; token redaction via `internal.Tokens.redact` (matches the spec example `***…***YKT0`). +- §6 sealed `MarketDataException` hierarchy with the 7 canonical subtypes and full support context (`requestId`, `requestUrl`, `statusCode`, `timestamp`, `exceptionType`) + `getSupportInfo()`. +- §10 timeouts: `REQUEST_TIMEOUT = 99s` and `CONNECT_TIMEOUT = 2s` exposed as constants on `MarketDataClient`. Connect timeout is wired into the `HttpClient`; the per-request 99 s timeout is a constant ready to be applied to `HttpRequest.Builder#timeout` when the request layer lands. +- §12 concurrency: `Semaphore(50)` field on `MarketDataClient` (wiring of acquire/release lands with the request layer). +- §15 packaging: SemVer, MIT `LICENSE`, `CHANGELOG.md` in Keep a Changelog format, version auto-detected via JAR manifest (`Implementation-Version`). +- §16 security: tokens never logged verbatim (use `Tokens.redact`); TLS validated by default (`HttpClient` does not expose a skip-verify option). +- ADR-002 CI: split into three workflows. + - `.github/workflows/pull-request.yml` — runs on PR `opened`/`synchronize`/`reopened` (no pre-PR push trigger by design). JDK 17 only. Runs `./gradlew build` and uploads `build/reports/jacoco/test/jacocoTestReport.xml` to Codecov. + - `.github/workflows/main.yml` — runs only on `push` to `main`. Full forward-compat matrix `{17, 21, 25}` via `-PtestJdk=N` (wired into `tasks.test.javaLauncher` in `build.gradle.kts`). The JDK 17 matrix entry also uploads coverage to Codecov, establishing the base coverage that PRs compare against. + - `.github/workflows/pr-matrix-on-demand.yml` — manually triggered by commenting one of `/run-all-jdks`, `/jdk-matrix`, or `/test-all` on an open PR. Runs JDK 21 and 25 (17 already ran via `pull-request.yml`). Gated to commenters with write/maintain/admin permission. Reacts 👀 to the trigger comment and posts a result summary comment when the matrix finishes. Note: `issue_comment` workflows always execute from the default branch's copy of the file — feature-branch edits to this workflow have no effect until merged to main. + - Coverage ratchet lives in `codecov.yml`: project status with `target: auto, threshold: 5%` (cannot drop >5 pp vs base branch) plus a patch-coverage requirement of 70 % on new code. Requires a `CODECOV_TOKEN` repo secret — without it the upload step fails because workflows pass `fail_ci_if_error: true`. + +**Deliberately deferred (require the request/endpoint layer to land first):** +- §1.2 resource groupings (`client.stocks`, `client.options`, `client.funds`, `client.markets`, `client.utilities`). +- §2 endpoint method coverage; §3 universal parameters; §11 wire-format decoding. +- §5 actual `/user/` startup validation call (the `validateOnStartup` flag is the seam; the call itself comes with the request layer). +- §7 honoring `MARKETDATA_LOGGING_LEVEL` and the spec's exact `{timestamp} - {logger_name} - {level} - {message}` format. Currently the SDK uses `java.util.logging` with default formatting; consumers can attach their own handler. +- §8 rate-limit header parsing, pre-flight check, request-scoped attachment. +- §9 retry/backoff policy and `/status/` cache workflow. +- §12 acquire/release of the concurrency semaphore around dispatched requests. +- §13 100% coverage threshold via JaCoCo `violationRules`; deferred until there is functional code worth the threshold. +- §13 integration-test CI job: stubbed at the bottom of `ci.yml` with a comment. Gating on a `MARKETDATA_TOKEN` GitHub Actions secret; will be wired up once the secret exists. + +When picking up new work, check this list before reaching for the SDK requirements doc — most foundational rules are already encoded in code; missing pieces are deferred deliberately, not by accident. + +## Acceptance checklist + +`docs/java-sdk-requirements.md` ends with an "Acceptance Checklist" mapping each Java-specific requirements section to verifiable items. Treat it as the definition of done for v1: when implementing, work toward making each box checkable, and use it as a self-review pass before declaring a section complete. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ee2ae98 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MARKET DATA + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a77e2db --- /dev/null +++ b/README.md @@ -0,0 +1,157 @@ +# Market Data Java SDK + +Java SDK for the [Market Data API](https://www.marketdata.app/). **Pre-release +scaffold** — endpoints are not yet implemented; this iteration sets up the +build, package layout, configuration cascade, exception taxonomy, and +Kotlin-interop foundations from the [ADRs](docs/adr/) and the canonical +[SDK Requirements](https://www.marketdata.app/docs/sdk/sdk-requirements/). + +## Requirements + +- **JDK 17 or newer** (ADR-002). The published artifact is compiled with + `javac --release 17`. Tests run on JDK 17, 21, and 25. +- **Jackson 2.18+** on the runtime classpath (ADR-005). Pulled transitively; + consumers may align to a newer 2.x. + +## Install (planned) + +```kotlin +// build.gradle.kts +dependencies { + implementation("com.marketdata:marketdata-sdk-java:0.1.0") +} +``` + +Coordinates are placeholders until the first publication to Maven Central. + +## Quick start + +The SDK reads `MARKETDATA_TOKEN` from the environment by default, so the +common path is two lines (per SDK requirements §"Easy Default Requests"): + +### Java + +```java +try (var client = MarketDataClient.builder().build()) { + // endpoint methods land in subsequent iterations +} +``` + +### Kotlin + +```kotlin +MarketDataClient.builder().build().use { client -> + // endpoint methods land in subsequent iterations +} +``` + +## Configuration + +Values are resolved through this cascade (highest priority first), per +SDK requirements §4: + +1. Explicit builder methods — `apiKey(...)`, `baseUrl(...)`, `apiVersion(...)` +2. Environment variables (table below) +3. `.env` file in the current working directory +4. Built-in defaults + +### Environment variables + +| Variable | Purpose | Default | +|----------|---------|---------| +| `MARKETDATA_TOKEN` | API authentication token | (none — demo mode) | +| `MARKETDATA_BASE_URL` | API base URL | `https://api.marketdata.app` | +| `MARKETDATA_API_VERSION` | API version | `v1` | +| `MARKETDATA_LOGGING_LEVEL` | SDK logging level | `INFO` | +| `MARKETDATA_OUTPUT_FORMAT` | Default output format | (language default) | +| `MARKETDATA_DATE_FORMAT` | Default date format | `timestamp` | +| `MARKETDATA_COLUMNS` | Columns to include | (all) | +| `MARKETDATA_ADD_HEADERS` | Include headers in CSV | `true` | +| `MARKETDATA_USE_HUMAN_READABLE` | Human-readable field names | `false` | +| `MARKETDATA_MODE` | Data mode (live/cached/delayed) | `live` | + +Endpoint-shape variables (`OUTPUT_FORMAT`, `DATE_FORMAT`, `COLUMNS`, +`ADD_HEADERS`, `USE_HUMAN_READABLE`, `MODE`) are reserved here and will be +honored when the request layer lands. + +### Demo mode + +Building a client without a token (no explicit `apiKey()`, no env var, no +`.env` entry) puts the client in **demo mode**: the `Authorization` header +is omitted from outbound requests and the SDK logs a warning at INFO +level. Authenticated endpoints will fail. Use this for read-only, public +endpoints only. + +## Error handling + +All SDK errors extend the sealed [`MarketDataException`](src/main/java/com/marketdata/sdk/exception/MarketDataException.java) +hierarchy and carry support context (`requestId`, `requestUrl`, +`statusCode`, `timestamp`) plus a `getSupportInfo()` helper for support +tickets: + +```java +try { + // call endpoint method (forthcoming) +} catch (RateLimitError e) { + System.err.println(e.getSupportInfo()); +} +``` + +The seven permitted subtypes — `AuthenticationError`, `BadRequestError`, +`NotFoundError`, `RateLimitError`, `ServerError`, `NetworkError`, +`ParseError` — match SDK requirements §6.1. The hierarchy is sealed so +`switch` over the subtypes is compile-time exhaustive (ADR-002). + +## Build + +The repo uses **Gradle (Kotlin DSL)** with a version catalog at +[`gradle/libs.versions.toml`](gradle/libs.versions.toml). + +The Gradle wrapper is committed (`gradlew`, `gradlew.bat`, +`gradle/wrapper/gradle-wrapper.jar`, `gradle/wrapper/gradle-wrapper.properties`), +so any JDK 17+ environment can build the project without a separate Gradle +install — the wrapper downloads the right Gradle version on first run. + +```bash +./gradlew build # compile + unit tests + spotless + jacoco +./gradlew test # unit tests only +./gradlew spotlessApply # auto-format +./gradlew jacocoTestReport # coverage report → build/reports/jacoco/ + +# Integration tests hit the live API — gated by env var (ADR-003 §13). +MARKETDATA_RUN_INTEGRATION_TESTS=true ./gradlew integrationTest +``` + +## Package layout + +``` +com.marketdata.sdk # MarketDataClient, RateLimits (public surface) +com.marketdata.sdk.exception # Sealed MarketDataException hierarchy + ErrorContext +com.marketdata.sdk.internal # Tokens, EnvVars, Configuration, Version (do not depend on) +``` + +Every public package is `@NullMarked` (JSpecify): non-null is the default; +nullable items are tagged explicitly. This is what makes Kotlin's null +safety work against this Java API (ADR-001 §2.1). + +## Architectural decisions + +All foundational decisions are captured as ADRs and are **Accepted**: + +| ADR | Decision | +|-----|----------| +| [001](docs/adr/ADR-001-java-only-vs-multi-language-sdk.md) | Java only; Kotlin consumers via interop, not a Kotlin artifact | +| [002](docs/adr/ADR-002-minimum-jdk-version.md) | Minimum JDK 17; CI matrix `{17, 21, 25}` | +| [003](docs/adr/ADR-003-build-tool.md) | Gradle (Kotlin DSL) + version catalog | +| [004](docs/adr/ADR-004-http-client.md) | `java.net.http.HttpClient` exclusively | +| [005](docs/adr/ADR-005-json-library.md) | Jackson (`jackson-databind`) | +| [006](docs/adr/ADR-006-async-api-surface.md) | Sync + async parity, async-first internally | + +Java-specific requirements derived from the ADRs live in +[`docs/java-sdk-requirements.md`](docs/java-sdk-requirements.md). The +canonical, cross-language requirements are at +[marketdata.app/docs/sdk/sdk-requirements](https://www.marketdata.app/docs/sdk/sdk-requirements/). + +## License + +[MIT](LICENSE). diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..995403f --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,135 @@ +plugins { + `java-library` + jacoco + alias(libs.plugins.spotless) + alias(libs.plugins.vanniktech.publish) +} + +group = "com.marketdata" +version = "0.1.0-SNAPSHOT" + +// ADR-002: minimum JDK 17, build with --release 17, single bytecode level. +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + // Sources/Javadoc jars are produced by the Vanniktech publish plugin + // (see mavenPublishing block below). Duplicating them via + // withJavadocJar()/withSourcesJar() here causes "multiple artifacts + // with classifier 'javadoc'" failures at publish time. +} + +tasks.withType().configureEach { + options.release = 17 + options.encoding = "UTF-8" + options.compilerArgs.add("-Xlint:all") +} + +tasks.withType().configureEach { + options.encoding = "UTF-8" +} + +// SDK requirements §15: version must be auto-detected from package +// metadata. Internal Version.current() reads this attribute at runtime. +tasks.jar { + manifest { + attributes( + "Implementation-Title" to "marketdata-sdk-java", + "Implementation-Version" to project.version, + ) + } +} + +// ADR-003: integration tests live in a separate, env-var-gated source set. +val integrationTest by sourceSets.creating + +val integrationTestImplementation by configurations.getting { + extendsFrom(configurations.testImplementation.get()) +} +val integrationTestRuntimeOnly by configurations.getting { + extendsFrom(configurations.testRuntimeOnly.get()) +} + +val integrationTestTask = tasks.register("integrationTest") { + description = "Runs integration tests against the live Market Data API." + group = "verification" + testClassesDirs = integrationTest.output.classesDirs + classpath = integrationTest.runtimeClasspath + useJUnitPlatform() + onlyIf { + System.getenv("MARKETDATA_RUN_INTEGRATION_TESTS") == "true" + } + shouldRunAfter(tasks.test) +} + +tasks.check { dependsOn(integrationTestTask) } + +dependencies { + // ADR-001 §2.1: JSpecify nullability annotations are compile-time only. + // compileOnlyApi makes them visible to consumers' compilers without a runtime dep. + compileOnlyApi(libs.jspecify) + + // ADR-005: Jackson is the JSON library. Implementation (not api) since + // consumers see typed records, not Jackson types directly. + implementation(libs.jackson.databind) + + testImplementation(libs.junit.jupiter) + testImplementation(libs.assertj.core) + testRuntimeOnly(libs.junit.platform.launcher) +} + +tasks.test { + useJUnitPlatform() + finalizedBy(tasks.jacocoTestReport) + + // ADR-002 CI matrix: optionally run tests on a specific JDK while + // compilation stays pinned to --release 17. The CI workflow passes + // -PtestJdk=17|21|25; locally you can do ./gradlew test -PtestJdk=21 + // (Gradle will provision the JDK via the foojay resolver if missing). + val testJdk = providers.gradleProperty("testJdk").orNull + if (testJdk != null) { + javaLauncher.set( + javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(testJdk.toInt()) + } + ) + } +} + +tasks.jacocoTestReport { + dependsOn(tasks.test) + reports { + xml.required = true + html.required = true + } +} + +// Coverage ratchet (line coverage cannot drop more than 5 pp below +// main's last value) is enforced in CI — see .github/workflows/pull-request.yml +// and .github/scripts/check-coverage-delta.py. Not enforced locally so that +// dev iteration isn't blocked while coverage is in flux. + +spotless { + java { + target("src/**/*.java") + googleJavaFormat() + removeUnusedImports() + trimTrailingWhitespace() + endWithNewline() + } + kotlinGradle { + target("*.gradle.kts", "**/*.gradle.kts") + } +} + +// ADR-003 / requirements §15: Maven Central publishing via Vanniktech. +// Coordinates and POM metadata below are placeholders — fill in before +// the first publication. +mavenPublishing { + coordinates(group.toString(), "marketdata-sdk-java", version.toString()) + pom { + name.set("Market Data Java SDK") + description.set("Java SDK for the Market Data API.") + // TODO: set url, scm, license, developers before publishing. + } +} diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..3d0e6bc --- /dev/null +++ b/codecov.yml @@ -0,0 +1,29 @@ +# Codecov configuration. +# Docs: https://docs.codecov.com/docs/codecov-yaml + +coverage: + status: + project: + default: + # Compare against the base branch's coverage automatically. + target: auto + # Allow up to 5 percentage points of drop before failing the + # status check. Mirrors the project's "no >5pp regression vs main" + # rule that previously lived in .github/scripts/check-coverage-delta.py. + threshold: 5% + # Don't run on draft commits / forks of forks. + if_ci_failed: error + patch: + default: + # Patch coverage = coverage of the lines this PR added/changed. + # Require at least 70% coverage on new code to nudge contributors + # toward writing tests for new logic, while leaving room for + # mechanical / boilerplate diffs. + target: 70% + threshold: 5% + +# Pull request comment from the Codecov bot. +comment: + layout: "header, diff, files, footer" + behavior: default + require_changes: false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..c061390 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,21 @@ +[versions] +jspecify = "1.0.0" +jackson = "2.18.2" +junit = "5.11.4" +junit-platform = "1.11.4" +assertj = "3.27.0" + +spotless = "7.0.2" +vanniktech-publish = "0.30.0" + +[libraries] +jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } +jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } + +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } +junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junit-platform" } +assertj-core = { module = "org.assertj:assertj-core", version.ref = "assertj" } + +[plugins] +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } +vanniktech-publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktech-publish" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..cea7a79 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f3b75f3 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..3c6df81 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,11 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0" +} + +rootProject.name = "marketdata-sdk-java" + +dependencyResolutionManagement { + repositories { + mavenCentral() + } +} diff --git a/src/integrationTest/java/com/marketdata/sdk/PlaceholderIT.java b/src/integrationTest/java/com/marketdata/sdk/PlaceholderIT.java new file mode 100644 index 0000000..b336e45 --- /dev/null +++ b/src/integrationTest/java/com/marketdata/sdk/PlaceholderIT.java @@ -0,0 +1,16 @@ +package com.marketdata.sdk; + +import org.junit.jupiter.api.Test; + +/** + * Placeholder so the {@code integrationTest} source set compiles before any real integration tests + * exist. Replace with live-API tests in subsequent iterations. Gated by {@code + * MARKETDATA_RUN_INTEGRATION_TESTS=true}. + */ +class PlaceholderIT { + + @Test + void sourceSetCompiles() { + // Intentionally empty. + } +} diff --git a/src/main/java/com/marketdata/sdk/MarketDataClient.java b/src/main/java/com/marketdata/sdk/MarketDataClient.java new file mode 100644 index 0000000..b4ab403 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/MarketDataClient.java @@ -0,0 +1,170 @@ +package com.marketdata.sdk; + +import com.marketdata.sdk.internal.Configuration; +import com.marketdata.sdk.internal.EnvVars; +import com.marketdata.sdk.internal.Tokens; +import com.marketdata.sdk.internal.Version; +import java.net.http.HttpClient; +import java.time.Duration; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.jspecify.annotations.Nullable; + +/** + * Entry point to the Market Data Java SDK. + * + *

One {@code MarketDataClient} per application. Holds a single shared {@link HttpClient} + * (HTTP/2, 2 s connect timeout) for connection pooling (ADR-004) and a 50-permit semaphore that + * gates the global concurrency pool required by SDK requirements §12. + * + *

Construction follows the configuration cascade in §4: explicit builder values → {@code + * MARKETDATA_*} environment variables → values in a {@code .env} file in the working directory → + * built-in defaults. Pass no token to enter demo mode (authenticated endpoints will fail; + * the {@code Authorization} header is omitted). + */ +public final class MarketDataClient implements AutoCloseable { + + /** SDK requirements §10: fixed 99-second per-request timeout. */ + public static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(99); + + /** SDK requirements §10: fixed 2-second connect timeout. */ + public static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(2); + + /** SDK requirements §12: maximum concurrent in-flight requests per client. */ + public static final int CONCURRENCY_LIMIT = 50; + + private static final Logger LOG = Logger.getLogger(MarketDataClient.class.getName()); + + private final HttpClient httpClient; + private final Semaphore concurrencyPermits; + private final AtomicReference<@Nullable RateLimits> latestRateLimits = new AtomicReference<>(); + + private final @Nullable String token; + private final String baseUrl; + private final String apiVersion; + private final String userAgent; + private final boolean demoMode; + private final boolean validateOnStartup; + + private MarketDataClient(Builder builder) { + Configuration config = Configuration.loadFromProcess(); + this.token = config.resolve(builder.apiKey, EnvVars.TOKEN); + this.baseUrl = + trimTrailingSlash( + config.resolveOrDefault( + builder.baseUrl, EnvVars.BASE_URL, Configuration.DEFAULT_BASE_URL)); + this.apiVersion = + config.resolveOrDefault( + builder.apiVersion, EnvVars.API_VERSION, Configuration.DEFAULT_API_VERSION); + this.demoMode = this.token == null; + this.validateOnStartup = builder.validateOnStartup; + this.userAgent = "marketdata-sdk-java/" + Version.current(); + + this.httpClient = + HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .version(HttpClient.Version.HTTP_2) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + this.concurrencyPermits = new Semaphore(CONCURRENCY_LIMIT); + + LOG.log( + Level.INFO, + "Initialized Market Data SDK {0} (baseUrl={1}, apiVersion={2}, demoMode={3})", + new Object[] {Version.current(), baseUrl, apiVersion, demoMode}); + if (demoMode) { + LOG.warning( + "No API token provided — running in demo mode. Authenticated endpoints will" + + " fail; rate-limit initialization is skipped."); + } else if (LOG.isLoggable(Level.FINE)) { + LOG.log(Level.FINE, "Token: {0}", Tokens.redact(token)); + } + + // SDK requirements §5: validate on startup by default. The actual + // /user/ call lands with the request layer; this flag is the seam. + } + + public static Builder builder() { + return new Builder(); + } + + public String getBaseUrl() { + return baseUrl; + } + + public String getApiVersion() { + return apiVersion; + } + + public String getUserAgent() { + return userAgent; + } + + public boolean isDemoMode() { + return demoMode; + } + + public boolean isValidateOnStartup() { + return validateOnStartup; + } + + /** Latest client-level rate-limit snapshot, or {@code null} if none has been received yet. */ + public @Nullable RateLimits getRateLimits() { + return latestRateLimits.get(); + } + + @Override + public void close() { + // java.net.http.HttpClient gained explicit close() in JDK 21. + // While the minimum target is JDK 17 (ADR-002), this method is a + // no-op: the JVM releases the executor and connection pool on + // process exit. Revisit if/when the minimum bumps to 21+. + } + + private static String trimTrailingSlash(String url) { + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } + + public static final class Builder { + private @Nullable String apiKey; + private @Nullable String baseUrl; + private @Nullable String apiVersion; + private boolean validateOnStartup = true; + + private Builder() {} + + /** Override the API token; otherwise resolved from {@code MARKETDATA_TOKEN} or {@code .env}. */ + public Builder apiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + + /** Override the base URL (default {@value Configuration#DEFAULT_BASE_URL}). */ + public Builder baseUrl(String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + /** Override the API version (default {@value Configuration#DEFAULT_API_VERSION}). */ + public Builder apiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + /** + * Whether to validate the token at construction by calling {@code /user/} (SDK requirements + * §5). Defaults to {@code true}. Disable for short-lived runtimes where the startup hit is + * undesirable. + */ + public Builder validateOnStartup(boolean validateOnStartup) { + this.validateOnStartup = validateOnStartup; + return this; + } + + public MarketDataClient build() { + return new MarketDataClient(this); + } + } +} diff --git a/src/main/java/com/marketdata/sdk/RateLimits.java b/src/main/java/com/marketdata/sdk/RateLimits.java new file mode 100644 index 0000000..ef8b12a --- /dev/null +++ b/src/main/java/com/marketdata/sdk/RateLimits.java @@ -0,0 +1,16 @@ +package com.marketdata.sdk; + +import java.time.Instant; + +/** + * Snapshot of the API rate-limit state, parsed from the {@code x-api-ratelimit-*} response headers. + * + *

Per SDK requirements §8, this is a client-level snapshot and is non-deterministic under + * concurrent use; per-request metadata is attached to each response separately. + * + * @param limit total credits available in the current window + * @param remaining credits left in the current window + * @param reset instant at which {@code remaining} resets to {@code limit} + * @param consumed credits consumed by the most recent request + */ +public record RateLimits(long limit, long remaining, Instant reset, long consumed) {} diff --git a/src/main/java/com/marketdata/sdk/exception/AuthenticationError.java b/src/main/java/com/marketdata/sdk/exception/AuthenticationError.java new file mode 100644 index 0000000..6efa76f --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/AuthenticationError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** The API rejected the credentials (HTTP 401). */ +public final class AuthenticationError extends MarketDataException { + + public AuthenticationError(String message, ErrorContext context) { + super(message, context, null); + } + + public AuthenticationError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/BadRequestError.java b/src/main/java/com/marketdata/sdk/exception/BadRequestError.java new file mode 100644 index 0000000..9e4ae68 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/BadRequestError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** The request was malformed or invalid (HTTP 400 / 422). */ +public final class BadRequestError extends MarketDataException { + + public BadRequestError(String message, ErrorContext context) { + super(message, context, null); + } + + public BadRequestError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/ErrorContext.java b/src/main/java/com/marketdata/sdk/exception/ErrorContext.java new file mode 100644 index 0000000..b84e509 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/ErrorContext.java @@ -0,0 +1,24 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** + * Diagnostic context attached to a {@link MarketDataException}, carrying the fields required by SDK + * requirements §6.2. + * + *

Use {@link #empty()} for client-side errors that occur before any HTTP request is dispatched + * (e.g. parameter validation). + * + * @param requestId value of the {@code cf-ray} response header, if any + * @param requestUrl full URL of the request that produced the error + * @param statusCode HTTP status code returned by the server + */ +public record ErrorContext( + @Nullable String requestId, @Nullable String requestUrl, @Nullable Integer statusCode) { + + private static final ErrorContext EMPTY = new ErrorContext(null, null, null); + + public static ErrorContext empty() { + return EMPTY; + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/MarketDataException.java b/src/main/java/com/marketdata/sdk/exception/MarketDataException.java new file mode 100644 index 0000000..f5b427b --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/MarketDataException.java @@ -0,0 +1,80 @@ +package com.marketdata.sdk.exception; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import org.jspecify.annotations.Nullable; + +/** + * Root of the SDK exception hierarchy. + * + *

Sealed (ADR-002) so consumer {@code switch} statements over its subtypes are compile-time + * exhaustive. Every instance carries the support context fields required by SDK requirements §6.2 + * and exposes a {@link #getSupportInfo()} string per §6.3. + * + *

Subtypes use {@link ErrorContext#empty()} for client-side validation errors that occur before + * any HTTP request is dispatched. + */ +public abstract sealed class MarketDataException extends RuntimeException + permits AuthenticationError, + BadRequestError, + NotFoundError, + RateLimitError, + ServerError, + NetworkError, + ParseError { + + private static final ZoneId EASTERN = ZoneId.of("America/New_York"); + private static final DateTimeFormatter TIMESTAMP_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final @Nullable String requestId; + private final @Nullable String requestUrl; + private final @Nullable Integer statusCode; + private final ZonedDateTime timestamp; + + protected MarketDataException(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, cause); + this.requestId = context.requestId(); + this.requestUrl = context.requestUrl(); + this.statusCode = context.statusCode(); + this.timestamp = ZonedDateTime.now(EASTERN); + } + + public @Nullable String getRequestId() { + return requestId; + } + + public @Nullable String getRequestUrl() { + return requestUrl; + } + + public @Nullable Integer getStatusCode() { + return statusCode; + } + + public ZonedDateTime getTimestamp() { + return timestamp; + } + + public String getExceptionType() { + return getClass().getSimpleName(); + } + + /** + * Multi-line, human-readable summary of the error and its context, intended to be copy-pasted + * into a support ticket. Never contains the API token or request body. + */ + public String getSupportInfo() { + StringBuilder sb = new StringBuilder(256); + sb.append("Market Data SDK Error\n"); + sb.append("---------------------\n"); + sb.append("Type: ").append(getExceptionType()).append('\n'); + sb.append("Message: ").append(getMessage()).append('\n'); + sb.append("Status code: ").append(statusCode != null ? statusCode : "(n/a)").append('\n'); + sb.append("Request ID: ").append(requestId != null ? requestId : "(n/a)").append('\n'); + sb.append("Request URL: ").append(requestUrl != null ? requestUrl : "(n/a)").append('\n'); + sb.append("Timestamp: ").append(timestamp.format(TIMESTAMP_FORMAT)).append(" (US/Eastern)"); + return sb.toString(); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/NetworkError.java b/src/main/java/com/marketdata/sdk/exception/NetworkError.java new file mode 100644 index 0000000..8d318de --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/NetworkError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** Transport-level failure: connection refused, DNS error, timeout, TLS, etc. */ +public final class NetworkError extends MarketDataException { + + public NetworkError(String message, ErrorContext context) { + super(message, context, null); + } + + public NetworkError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/NotFoundError.java b/src/main/java/com/marketdata/sdk/exception/NotFoundError.java new file mode 100644 index 0000000..3f050cd --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/NotFoundError.java @@ -0,0 +1,21 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** + * The requested resource was not found (HTTP 404). + * + *

Per SDK requirements §9.1, most endpoints translate 404 into an empty no-data response rather + * than throwing this exception. It exists for the cases where 404 truly indicates a programming + * error. + */ +public final class NotFoundError extends MarketDataException { + + public NotFoundError(String message, ErrorContext context) { + super(message, context, null); + } + + public NotFoundError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/ParseError.java b/src/main/java/com/marketdata/sdk/exception/ParseError.java new file mode 100644 index 0000000..205c59c --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/ParseError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** The API response could not be decoded into the expected model. */ +public final class ParseError extends MarketDataException { + + public ParseError(String message, ErrorContext context) { + super(message, context, null); + } + + public ParseError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/RateLimitError.java b/src/main/java/com/marketdata/sdk/exception/RateLimitError.java new file mode 100644 index 0000000..ba4ca54 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/RateLimitError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** The client exceeded the API's rate limit (HTTP 429). */ +public final class RateLimitError extends MarketDataException { + + public RateLimitError(String message, ErrorContext context) { + super(message, context, null); + } + + public RateLimitError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/ServerError.java b/src/main/java/com/marketdata/sdk/exception/ServerError.java new file mode 100644 index 0000000..8ae929b --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/ServerError.java @@ -0,0 +1,15 @@ +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.Nullable; + +/** The API returned a 5xx response. */ +public final class ServerError extends MarketDataException { + + public ServerError(String message, ErrorContext context) { + super(message, context, null); + } + + public ServerError(String message, ErrorContext context, @Nullable Throwable cause) { + super(message, context, cause); + } +} diff --git a/src/main/java/com/marketdata/sdk/exception/package-info.java b/src/main/java/com/marketdata/sdk/exception/package-info.java new file mode 100644 index 0000000..3fb0727 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/exception/package-info.java @@ -0,0 +1,11 @@ +/** + * Sealed exception hierarchy thrown by the SDK. + * + *

The {@link com.marketdata.sdk.exception.MarketDataException} root is sealed (ADR-002) so + * consumer {@code switch} statements over the known subtypes are compiler-checked for + * exhaustiveness. Adding a new subtype is a breaking change. + */ +@NullMarked +package com.marketdata.sdk.exception; + +import org.jspecify.annotations.NullMarked; diff --git a/src/main/java/com/marketdata/sdk/internal/Configuration.java b/src/main/java/com/marketdata/sdk/internal/Configuration.java new file mode 100644 index 0000000..675dff6 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/internal/Configuration.java @@ -0,0 +1,107 @@ +package com.marketdata.sdk.internal; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * Resolves SDK configuration values per the cascade in SDK requirements §4: {@code explicit value → + * MARKETDATA_* env var → .env file in CWD → built-in default}. + * + *

The only public construction path is {@link #loadFromProcess()}, which snapshots the live + * environment and the {@code .env} file once. The constructor is strictly private — there is no + * production-callable backdoor for injecting arbitrary maps. Tests reach the private constructor + * via reflection (see {@code ConfigurationTest}); this is by design so a developer can't + * accidentally take a shortcut around the canonical load path. + */ +public final class Configuration { + + public static final String DEFAULT_BASE_URL = "https://api.marketdata.app"; + public static final String DEFAULT_API_VERSION = "v1"; + private static final Path DEFAULT_DOTENV_PATH = Paths.get(".env"); + + private final Map systemEnv; + private final Map dotEnv; + + private Configuration(Map systemEnv, Map dotEnv) { + this.systemEnv = Map.copyOf(systemEnv); + this.dotEnv = Map.copyOf(dotEnv); + } + + /** + * Production factory: snapshots {@code System.getenv()} and reads {@code ./.env} once. Call + * during client construction. + */ + public static Configuration loadFromProcess() { + return new Configuration(System.getenv(), readDotEnvFile(DEFAULT_DOTENV_PATH)); + } + + /** Cascade: explicit → system env → .env → {@code null}. */ + public @Nullable String resolve(@Nullable String explicit, String envKey) { + if (isPresent(explicit)) { + return explicit; + } + String fromSystem = systemEnv.get(envKey); + if (isPresent(fromSystem)) { + return fromSystem; + } + String fromDotEnv = dotEnv.get(envKey); + return isPresent(fromDotEnv) ? fromDotEnv : null; + } + + /** Same as {@link #resolve} but returns {@code defaultValue} when the cascade yields nothing. */ + public String resolveOrDefault(@Nullable String explicit, String envKey, String defaultValue) { + String resolved = resolve(explicit, envKey); + return resolved != null ? resolved : defaultValue; + } + + private static boolean isPresent(@Nullable String value) { + return value != null && !value.isBlank(); + } + + /** + * Reads a {@code .env}-style file: lines like {@code KEY=value}, {@code #} for comments, + * surrounding single or double quotes stripped. Package-private so tests can target an arbitrary + * {@link Path} (e.g. inside a JUnit {@code @TempDir}) instead of CWD. + */ + static Map readDotEnvFile(Path path) { + if (!Files.isRegularFile(path)) { + return Map.of(); + } + Map result = new HashMap<>(); + try { + for (String raw : Files.readAllLines(path)) { + String line = raw.trim(); + if (line.isEmpty() || line.startsWith("#")) { + continue; + } + int eq = line.indexOf('='); + if (eq < 1) { + continue; + } + String key = line.substring(0, eq).trim(); + String value = stripQuotes(line.substring(eq + 1).trim()); + result.put(key, value); + } + } catch (IOException ignored) { + return Map.of(); + } + return Map.copyOf(result); + } + + private static String stripQuotes(String value) { + if (value.length() < 2) { + return value; + } + char first = value.charAt(0); + char last = value.charAt(value.length() - 1); + if ((first == '"' && last == '"') || (first == '\'' && last == '\'')) { + return value.substring(1, value.length() - 1); + } + return value; + } +} diff --git a/src/main/java/com/marketdata/sdk/internal/EnvVars.java b/src/main/java/com/marketdata/sdk/internal/EnvVars.java new file mode 100644 index 0000000..16f7e39 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/internal/EnvVars.java @@ -0,0 +1,21 @@ +package com.marketdata.sdk.internal; + +/** + * Names of the {@code MARKETDATA_*} environment variables consulted by the SDK. Mirrors SDK + * requirements §4. + */ +public final class EnvVars { + + public static final String TOKEN = "MARKETDATA_TOKEN"; + public static final String BASE_URL = "MARKETDATA_BASE_URL"; + public static final String API_VERSION = "MARKETDATA_API_VERSION"; + public static final String LOGGING_LEVEL = "MARKETDATA_LOGGING_LEVEL"; + public static final String OUTPUT_FORMAT = "MARKETDATA_OUTPUT_FORMAT"; + public static final String DATE_FORMAT = "MARKETDATA_DATE_FORMAT"; + public static final String COLUMNS = "MARKETDATA_COLUMNS"; + public static final String ADD_HEADERS = "MARKETDATA_ADD_HEADERS"; + public static final String USE_HUMAN_READABLE = "MARKETDATA_USE_HUMAN_READABLE"; + public static final String MODE = "MARKETDATA_MODE"; + + private EnvVars() {} +} diff --git a/src/main/java/com/marketdata/sdk/internal/Tokens.java b/src/main/java/com/marketdata/sdk/internal/Tokens.java new file mode 100644 index 0000000..b0cd604 --- /dev/null +++ b/src/main/java/com/marketdata/sdk/internal/Tokens.java @@ -0,0 +1,36 @@ +package com.marketdata.sdk.internal; + +import org.jspecify.annotations.Nullable; + +/** + * Token redaction helpers. SDK requirements §5 / §16: API tokens must never appear in log output + * verbatim. + */ +public final class Tokens { + + /** + * Minimum number of asterisks emitted before the trailing 4 chars, matching the SDK requirements + * §7 example ({@code ************************************YKT0}). + */ + private static final int MIN_MASK_LENGTH = 32; + + private static final int VISIBLE_TAIL = 4; + + private Tokens() {} + + /** + * Returns a redacted form of {@code token} suitable for logging. The last 4 characters are + * preserved; the rest is replaced with asterisks padded to at least {@value #MIN_MASK_LENGTH} + * characters. + */ + public static String redact(@Nullable String token) { + if (token == null || token.isBlank()) { + return "(none)"; + } + if (token.length() <= VISIBLE_TAIL) { + return "*".repeat(token.length()); + } + int hidden = Math.max(token.length() - VISIBLE_TAIL, MIN_MASK_LENGTH); + return "*".repeat(hidden) + token.substring(token.length() - VISIBLE_TAIL); + } +} diff --git a/src/main/java/com/marketdata/sdk/internal/Version.java b/src/main/java/com/marketdata/sdk/internal/Version.java new file mode 100644 index 0000000..3f9746a --- /dev/null +++ b/src/main/java/com/marketdata/sdk/internal/Version.java @@ -0,0 +1,20 @@ +package com.marketdata.sdk.internal; + +/** + * Reads the SDK's version from the JAR manifest's {@code Implementation-Version} attribute (SDK + * requirements §15: "version must be automatically detected from package metadata"). + * + *

Falls back to {@code "0.0.0-dev"} when the class is not loaded from a JAR (e.g. running tests + * from class files). + */ +public final class Version { + + private static final String FALLBACK = "0.0.0-dev"; + + private Version() {} + + public static String current() { + String version = Version.class.getPackage().getImplementationVersion(); + return version != null && !version.isBlank() ? version : FALLBACK; + } +} diff --git a/src/main/java/com/marketdata/sdk/internal/package-info.java b/src/main/java/com/marketdata/sdk/internal/package-info.java new file mode 100644 index 0000000..8f8cf2f --- /dev/null +++ b/src/main/java/com/marketdata/sdk/internal/package-info.java @@ -0,0 +1,11 @@ +/** + * Internal SDK utilities. Not part of the public API surface — types and methods here may change in + * any release without notice. + * + *

Java has no enforceable "internal" visibility across packages, so this boundary is convention + * only. + */ +@NullMarked +package com.marketdata.sdk.internal; + +import org.jspecify.annotations.NullMarked; diff --git a/src/main/java/com/marketdata/sdk/package-info.java b/src/main/java/com/marketdata/sdk/package-info.java new file mode 100644 index 0000000..c8dc2bb --- /dev/null +++ b/src/main/java/com/marketdata/sdk/package-info.java @@ -0,0 +1,11 @@ +/** + * Market Data Java SDK — public API entry point. + * + *

Per ADR-001 §2.1, the entire public API is {@code @NullMarked}: every type, parameter, return, + * and field is non-null by default. Mark nullable items explicitly with {@link + * org.jspecify.annotations.Nullable}. + */ +@NullMarked +package com.marketdata.sdk; + +import org.jspecify.annotations.NullMarked; diff --git a/src/test/java/com/marketdata/sdk/MarketDataClientTest.java b/src/test/java/com/marketdata/sdk/MarketDataClientTest.java new file mode 100644 index 0000000..8e9cfc8 --- /dev/null +++ b/src/test/java/com/marketdata/sdk/MarketDataClientTest.java @@ -0,0 +1,60 @@ +package com.marketdata.sdk; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.marketdata.sdk.internal.Configuration; +import org.junit.jupiter.api.Test; + +class MarketDataClientTest { + + @Test + void buildsWithExplicitToken() { + try (var client = MarketDataClient.builder().apiKey("test-key").build()) { + assertThat(client.isDemoMode()).isFalse(); + assertThat(client.getBaseUrl()).isEqualTo(Configuration.DEFAULT_BASE_URL); + assertThat(client.getApiVersion()).isEqualTo(Configuration.DEFAULT_API_VERSION); + } + } + + @Test + void demoModeWhenNoTokenAvailable() { + // No apiKey set on the builder. Demo mode iff the env/dotenv + // cascade also yields nothing — true on any CI environment that + // doesn't export MARKETDATA_TOKEN. This assertion is conditional + // so the test stays valid in both cases. + try (var client = MarketDataClient.builder().build()) { + String envToken = System.getenv("MARKETDATA_TOKEN"); + boolean expectDemo = envToken == null || envToken.isBlank(); + assertThat(client.isDemoMode()).isEqualTo(expectDemo); + } + } + + @Test + void overridesAreHonored() { + try (var client = + MarketDataClient.builder() + .apiKey("KEY") + .baseUrl("https://example.test/") + .apiVersion("v2") + .validateOnStartup(false) + .build()) { + assertThat(client.getBaseUrl()).isEqualTo("https://example.test"); // trailing slash trimmed + assertThat(client.getApiVersion()).isEqualTo("v2"); + assertThat(client.isValidateOnStartup()).isFalse(); + } + } + + @Test + void userAgentMatchesSpec() { + try (var client = MarketDataClient.builder().apiKey("KEY").build()) { + assertThat(client.getUserAgent()).startsWith("marketdata-sdk-java/"); + } + } + + @Test + void rateLimitsStartUnpopulated() { + try (var client = MarketDataClient.builder().apiKey("KEY").build()) { + assertThat(client.getRateLimits()).isNull(); + } + } +} diff --git a/src/test/java/com/marketdata/sdk/RateLimitsTest.java b/src/test/java/com/marketdata/sdk/RateLimitsTest.java new file mode 100644 index 0000000..84a7b41 --- /dev/null +++ b/src/test/java/com/marketdata/sdk/RateLimitsTest.java @@ -0,0 +1,20 @@ +package com.marketdata.sdk; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import org.junit.jupiter.api.Test; + +class RateLimitsTest { + + @Test + void recordExposesAllFields() { + Instant reset = Instant.parse("2026-05-04T12:00:00Z"); + var rl = new RateLimits(50_000L, 49_500L, reset, 1L); + + assertThat(rl.limit()).isEqualTo(50_000L); + assertThat(rl.remaining()).isEqualTo(49_500L); + assertThat(rl.reset()).isEqualTo(reset); + assertThat(rl.consumed()).isEqualTo(1L); + } +} diff --git a/src/test/java/com/marketdata/sdk/exception/MarketDataExceptionTest.java b/src/test/java/com/marketdata/sdk/exception/MarketDataExceptionTest.java new file mode 100644 index 0000000..9ce9f7b --- /dev/null +++ b/src/test/java/com/marketdata/sdk/exception/MarketDataExceptionTest.java @@ -0,0 +1,110 @@ +package com.marketdata.sdk.exception; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class MarketDataExceptionTest { + + @Test + void emptyContextLeavesFieldsNull() { + var error = new BadRequestError("symbol must not be blank", ErrorContext.empty()); + + assertThat(error.getRequestId()).isNull(); + assertThat(error.getRequestUrl()).isNull(); + assertThat(error.getStatusCode()).isNull(); + assertThat(error.getTimestamp()).isNotNull(); + assertThat(error.getExceptionType()).isEqualTo("BadRequestError"); + } + + @Test + void carriesContextFields() { + var ctx = + new ErrorContext( + "8a1b2c3d4e5f6g7h-SJC", "https://api.marketdata.app/v1/stocks/quotes/AAPL/", 429); + + var error = new RateLimitError("Rate limit exceeded", ctx); + + assertThat(error.getRequestId()).isEqualTo("8a1b2c3d4e5f6g7h-SJC"); + assertThat(error.getStatusCode()).isEqualTo(429); + assertThat(error.getExceptionType()).isEqualTo("RateLimitError"); + } + + @Test + void supportInfoIncludesAllRequiredFields() { + var ctx = new ErrorContext("RAY-1", "https://api.marketdata.app/v1/stocks/quotes/AAPL/", 429); + var error = new RateLimitError("Rate limit exceeded", ctx); + + String supportInfo = error.getSupportInfo(); + + assertThat(supportInfo) + .contains("RateLimitError") + .contains("Rate limit exceeded") + .contains("429") + .contains("RAY-1") + .contains("https://api.marketdata.app/v1/stocks/quotes/AAPL/") + .contains("US/Eastern"); + } + + @Test + void allSubtypesCarryContextAndCause() { + var ctx = new ErrorContext("RAY-X", "https://api.marketdata.app/v1/test/", 500); + var cause = new RuntimeException("root cause"); + + // The four subtypes not exercised by the other tests in this file. + var net = new NetworkError("network down", ctx, cause); + var nf = new NotFoundError("not found", ctx); + var pe = new ParseError("bad json", ctx, cause); + var se = new ServerError("internal", ctx); + + assertThat(net.getExceptionType()).isEqualTo("NetworkError"); + assertThat(net.getCause()).isSameAs(cause); + assertThat(nf.getExceptionType()).isEqualTo("NotFoundError"); + assertThat(nf.getCause()).isNull(); + assertThat(pe.getExceptionType()).isEqualTo("ParseError"); + assertThat(pe.getCause()).isSameAs(cause); + assertThat(se.getExceptionType()).isEqualTo("ServerError"); + assertThat(se.getCause()).isNull(); + + for (MarketDataException ex : List.of(net, nf, pe, se)) { + assertThat(ex.getStatusCode()).isEqualTo(500); + assertThat(ex.getRequestId()).isEqualTo("RAY-X"); + assertThat(ex.getRequestUrl()).isEqualTo("https://api.marketdata.app/v1/test/"); + assertThat(ex.getTimestamp()).isNotNull(); + } + } + + @Test + void everySubtypeExposesBothConstructors() { + var ctx = ErrorContext.empty(); + var cause = new RuntimeException("cause"); + + // Each subtype has two constructors: (msg, ctx) and (msg, ctx, cause). + // Exercise the one that the other tests in this file don't already hit. + List exhaustive = + List.of( + new AuthenticationError("a", ctx, cause), + new BadRequestError("b", ctx, cause), + new NotFoundError("n", ctx, cause), + new RateLimitError("r", ctx, cause), + new ServerError("s", ctx, cause), + new NetworkError("net", ctx), // cause-less variant + new ParseError("p", ctx)); // cause-less variant + + for (MarketDataException ex : exhaustive) { + assertThat(ex.getMessage()).isNotBlank(); + assertThat(ex.getTimestamp()).isNotNull(); + } + } + + @Test + void supportInfoNeverContainsSensitiveData() { + // The exception itself never receives the token; we just + // double-check that the canonical message+URL form doesn't leak. + var ctx = new ErrorContext("RAY-1", "https://api.marketdata.app/v1/user/", 401); + var error = new AuthenticationError("Invalid token", ctx); + + assertThat(error.getSupportInfo()).doesNotContain("token=").doesNotContain("Bearer "); + } +} diff --git a/src/test/java/com/marketdata/sdk/internal/ConfigurationTest.java b/src/test/java/com/marketdata/sdk/internal/ConfigurationTest.java new file mode 100644 index 0000000..f67093f --- /dev/null +++ b/src/test/java/com/marketdata/sdk/internal/ConfigurationTest.java @@ -0,0 +1,142 @@ +package com.marketdata.sdk.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ConfigurationTest { + + /** + * Reflection bridge to {@code Configuration}'s private constructor. Tests need to inject custom + * environment maps; production code cannot — that's the entire point of keeping the constructor + * private. Encapsulating the reflection here keeps individual tests clean. + */ + private static Configuration newConfig( + Map systemEnv, Map dotEnv) { + try { + Constructor ctor = + Configuration.class.getDeclaredConstructor(Map.class, Map.class); + ctor.setAccessible(true); + return ctor.newInstance(systemEnv, dotEnv); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException( + "Could not construct Configuration via reflection — has the private ctor signature" + + " changed?", + e); + } + } + + @Test + void explicitWinsOverEverything() { + Configuration config = + newConfig( + Map.of("MARKETDATA_TOKEN", "from-env"), Map.of("MARKETDATA_TOKEN", "from-dotenv")); + + assertThat(config.resolve("explicit-value", "MARKETDATA_TOKEN")).isEqualTo("explicit-value"); + } + + @Test + void envVarWinsOverDotEnv() { + Configuration config = + newConfig( + Map.of("MARKETDATA_TOKEN", "from-env"), Map.of("MARKETDATA_TOKEN", "from-dotenv")); + + assertThat(config.resolve(null, "MARKETDATA_TOKEN")).isEqualTo("from-env"); + } + + @Test + void fallsBackToDotEnvWhenEnvVarMissing() { + Configuration config = newConfig(Map.of(), Map.of("MARKETDATA_TOKEN", "from-dotenv")); + + assertThat(config.resolve(null, "MARKETDATA_TOKEN")).isEqualTo("from-dotenv"); + } + + @Test + void blankExplicitDoesNotCount() { + Configuration config = newConfig(Map.of("MARKETDATA_TOKEN", "from-env"), Map.of()); + + assertThat(config.resolve(" ", "MARKETDATA_TOKEN")).isEqualTo("from-env"); + } + + @Test + void blankEnvVarFallsThroughToDotEnv() { + Configuration config = + newConfig(Map.of("MARKETDATA_TOKEN", " "), Map.of("MARKETDATA_TOKEN", "from-dotenv")); + + assertThat(config.resolve(null, "MARKETDATA_TOKEN")).isEqualTo("from-dotenv"); + } + + @Test + void resolveReturnsNullWhenAllSourcesEmpty() { + Configuration config = newConfig(Map.of(), Map.of()); + + assertThat(config.resolve(null, "MARKETDATA_TOKEN")).isNull(); + } + + @Test + void resolveOrDefaultReturnsDefaultWhenAllEmpty() { + Configuration config = newConfig(Map.of(), Map.of()); + + assertThat(config.resolveOrDefault(null, "MARKETDATA_BASE_URL", "https://default")) + .isEqualTo("https://default"); + } + + @Test + void resolveOrDefaultPrefersResolvedValue() { + Configuration config = newConfig(Map.of("MARKETDATA_BASE_URL", "https://explicit"), Map.of()); + + assertThat(config.resolveOrDefault(null, "MARKETDATA_BASE_URL", "https://default")) + .isEqualTo("https://explicit"); + } + + // ---------- .env file parsing ---------- + + @Test + void readsAndParsesDotEnvFile(@TempDir Path tmp) throws IOException { + Path dotenv = tmp.resolve(".env"); + Files.writeString( + dotenv, + """ + # comment line — should be ignored + MARKETDATA_TOKEN=plain-token + MARKETDATA_BASE_URL="https://staging.example.com" + QUOTED_SINGLE='single-quoted' + EMPTY_VALUE= + + # blank line above + BAD_LINE_NO_EQUALS + =BAD_LINE_NO_KEY + """); + + Map parsed = Configuration.readDotEnvFile(dotenv); + + assertThat(parsed) + .containsEntry("MARKETDATA_TOKEN", "plain-token") + .containsEntry("MARKETDATA_BASE_URL", "https://staging.example.com") + .containsEntry("QUOTED_SINGLE", "single-quoted") + .containsEntry("EMPTY_VALUE", "") + .doesNotContainKey("# comment line — should be ignored") + .doesNotContainKey("BAD_LINE_NO_EQUALS"); + } + + @Test + void missingDotEnvReturnsEmpty(@TempDir Path tmp) { + assertThat(Configuration.readDotEnvFile(tmp.resolve(".env"))).isEmpty(); + } + + @Test + void dotEnvParsingIntegratesWithCascade(@TempDir Path tmp) throws IOException { + Path dotenv = tmp.resolve(".env"); + Files.writeString(dotenv, "MARKETDATA_TOKEN=from-real-dotenv\n"); + + Configuration config = newConfig(Map.of(), Configuration.readDotEnvFile(dotenv)); + + assertThat(config.resolve(null, "MARKETDATA_TOKEN")).isEqualTo("from-real-dotenv"); + } +} diff --git a/src/test/java/com/marketdata/sdk/internal/TokensTest.java b/src/test/java/com/marketdata/sdk/internal/TokensTest.java new file mode 100644 index 0000000..b4d183f --- /dev/null +++ b/src/test/java/com/marketdata/sdk/internal/TokensTest.java @@ -0,0 +1,36 @@ +package com.marketdata.sdk.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class TokensTest { + + @Test + void redactsLongTokenKeepingLastFourChars() { + String redacted = Tokens.redact("0123456789abcdefghijklmnopqrstuvwxyzYKT0"); + assertThat(redacted).endsWith("YKT0"); + assertThat(redacted).matches("\\*+YKT0"); + assertThat(redacted).hasSize(40); + } + + @Test + void padsShortTokensToMinimumMaskLength() { + // 10-char token: 4 visible, 6 hidden — but mask floor is 32. + String redacted = Tokens.redact("ABCDEF1234"); + assertThat(redacted).endsWith("1234"); + assertThat(redacted).hasSize(36); // 32 asterisks + 4 visible + } + + @Test + void tokenShorterThanFourCharsIsFullyMasked() { + assertThat(Tokens.redact("abc")).isEqualTo("***"); + } + + @Test + void blankOrNullTokenRendersAsNone() { + assertThat(Tokens.redact(null)).isEqualTo("(none)"); + assertThat(Tokens.redact("")).isEqualTo("(none)"); + assertThat(Tokens.redact(" ")).isEqualTo("(none)"); + } +}