Skip to content

Commit 2fabfee

Browse files
volodstaimiclaude
andcommitted
Java client for the Transcript Dock API
Java 11 client with no runtime dependencies. Uses java.net.http with redirects disabled, a strict internal JSON reader and writer, explicit idempotency keys and bounded job polling. Includes the shared loopback fixture contract checks, JUnit tests, and a workflow that checks on Temurin 11, 17 and 21 and uploads signed artifacts to the Central Portal for manual review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
0 parents  commit 2fabfee

15 files changed

Lines changed: 2528 additions & 0 deletions

File tree

‎.ci/check.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from fixture import Fixture
2+
import os, subprocess, threading
3+
from http.server import ThreadingHTTPServer
4+
Fixture.calls = []
5+
server = ThreadingHTTPServer(('127.0.0.1', 0), Fixture)
6+
thread = threading.Thread(target=server.serve_forever, daemon=True)
7+
thread.start()
8+
try:
9+
env = dict(os.environ, TRANSCRIPTDOCK_TEST_BASE_URL=f'http://127.0.0.1:{server.server_port}')
10+
subprocess.run(['java', '-cp', os.pathsep.join(['target/classes', 'target/test-classes']), 'com.transcriptdock.ClientCheck'], env=env, check=True, timeout=120)
11+
assert not any('/credential-leak' in path for _, path in Fixture.calls), 'redirect leaked a request'
12+
assert sum(path == '/v1/rate-limit' for _, path in Fixture.calls) == 1, 'unexpected automatic retry'
13+
print(f'{len(Fixture.calls)} local fixture requests checked')
14+
finally:
15+
server.shutdown()
16+
server.server_close()
17+
thread.join()

‎.ci/fixture.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""Run SDK contract checks against local fixtures, never production."""
2+
import argparse
3+
import json
4+
import os
5+
from pathlib import Path
6+
import subprocess
7+
import threading
8+
import time
9+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10+
from urllib.parse import urlsplit, parse_qs
11+
12+
ROOT = Path(__file__).resolve().parents[2]
13+
KEY = 'td_live_fixture_only'
14+
15+
16+
class Fixture(BaseHTTPRequestHandler):
17+
calls = []
18+
19+
def log_message(self, *args):
20+
pass
21+
22+
def do_GET(self): self.respond()
23+
def do_POST(self): self.respond()
24+
def do_DELETE(self): self.respond()
25+
def do_PATCH(self): self.respond()
26+
27+
def respond(self):
28+
self.calls.append((self.command, self.path))
29+
raw = self.rfile.read(int(self.headers.get('Content-Length', '0')))
30+
path = urlsplit(self.path).path
31+
status = 200
32+
content_type = 'application/json; charset=utf-8'
33+
payload = {'id': 'fixture', 'status': 'succeeded', 'result_id': 'transcript', 'future_field': 42,
34+
'words': [{'start_ms': 123, 'end_ms': 456}],
35+
'request': {'method': self.command, 'path': path, 'query': parse_qs(urlsplit(self.path).query),
36+
'body': json.loads(raw) if raw else None,
37+
'idempotency_key': self.headers.get('Idempotency-Key'),
38+
'authorized': self.headers.get('Authorization') == 'Bearer ' + KEY}}
39+
if path == '/v1/redirect':
40+
self.send_response(302)
41+
self.send_header('Location', '/v1/credential-leak')
42+
self.send_header('Content-Length', '0')
43+
self.end_headers()
44+
return
45+
if path == '/v1/rate-limit':
46+
status = 429
47+
payload = {'error': {'code': 'RATE_LIMITED', 'message': KEY, 'retryable': True, 'retry_after_seconds': 4}, 'request_id': 'fixture-request'}
48+
elif path in ('/v1/budget', '/v1/conflict', '/v1/jobs/not-owned'):
49+
status, code = {'/v1/budget': (402, 'BUDGET_EXCEEDED'), '/v1/conflict': (409, 'IDEMPOTENCY_CONFLICT'), '/v1/jobs/not-owned': (404, 'NOT_FOUND')}[path]
50+
payload = {'error': {'code': code, 'message': 'Fixture rejection', 'retryable': False}}
51+
elif path == '/v1/gateway':
52+
status, payload = 502, b'<html>gateway failed</html>'
53+
elif path == '/v1/error-shape':
54+
status, payload = 500, ['not an error object']
55+
elif path == '/v1/malformed':
56+
payload = b'not-json'
57+
elif path == '/v1/array':
58+
payload = []
59+
elif path == '/v1/slow':
60+
time.sleep(.3)
61+
elif path.endswith('/export'):
62+
content_type = 'text/plain; charset=utf-8'
63+
payload = '1\n00:00:00,000 --> 00:00:01,000\nCafé fixture\n'.encode()
64+
elif path.startswith('/v1/jobs/'):
65+
name = path.rsplit('/', 1)[-1]
66+
payload['status'] = name if name in ('succeeded', 'failed', 'cancelled', 'processing') else 'succeeded'
67+
if self.command == 'POST':
68+
status = 202
69+
data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
70+
try:
71+
self.send_response(status)
72+
self.send_header('Content-Type', content_type)
73+
self.send_header('Content-Length', str(len(data)))
74+
self.end_headers()
75+
self.wfile.write(data)
76+
except (BrokenPipeError, ConnectionResetError):
77+
pass

‎.github/workflows/release.yml‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
name: Check and release
2+
on:
3+
push:
4+
branches: [main]
5+
pull_request:
6+
workflow_dispatch:
7+
inputs:
8+
publish:
9+
description: Upload the checked version to the Maven Central Portal for review
10+
type: boolean
11+
default: false
12+
permissions:
13+
contents: read
14+
env:
15+
MAVEN_VERSION: 3.9.16
16+
MAVEN_SHA512: 831a8591fe20c8243b1dbe7d71e3244f31d1665b0804b2e825e38cbbe5ce0cafb8338851f90780735568773e0a6cd07bbec107cda0b896b008b861075358b6f6
17+
jobs:
18+
check:
19+
runs-on: ubuntu-latest
20+
strategy:
21+
matrix:
22+
java: ['11', '17', '21']
23+
steps:
24+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
25+
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
26+
with:
27+
distribution: temurin
28+
java-version: ${{ matrix.java }}
29+
cache: maven
30+
- name: Install pinned Maven
31+
run: |
32+
curl -fsSLo "$RUNNER_TEMP/maven.tar.gz" "https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/$MAVEN_VERSION/apache-maven-$MAVEN_VERSION-bin.tar.gz"
33+
echo "$MAVEN_SHA512 $RUNNER_TEMP/maven.tar.gz" | sha512sum -c -
34+
tar -xzf "$RUNNER_TEMP/maven.tar.gz" -C "$RUNNER_TEMP"
35+
echo "$RUNNER_TEMP/apache-maven-$MAVEN_VERSION/bin" >> "$GITHUB_PATH"
36+
- run: mvn -B -ntp verify
37+
- run: python3 .ci/check.py
38+
publish:
39+
# Maven Central has no OIDC trusted publishing, so this job uses a Central Portal user token
40+
# and a GPG signing key stored as secrets of the maven-central environment.
41+
if: github.event_name == 'workflow_dispatch' && inputs.publish && github.ref == 'refs/heads/main'
42+
needs: check
43+
runs-on: ubuntu-latest
44+
environment: maven-central
45+
permissions:
46+
contents: read
47+
steps:
48+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
49+
- uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
50+
with:
51+
distribution: temurin
52+
java-version: '21'
53+
server-id: central
54+
server-username-env-var: CENTRAL_TOKEN_USERNAME
55+
server-password-env-var: CENTRAL_TOKEN_PASSWORD
56+
gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }}
57+
gpg-passphrase-env-var: MAVEN_GPG_PASSPHRASE
58+
- name: Install pinned Maven
59+
run: |
60+
curl -fsSLo "$RUNNER_TEMP/maven.tar.gz" "https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/$MAVEN_VERSION/apache-maven-$MAVEN_VERSION-bin.tar.gz"
61+
echo "$MAVEN_SHA512 $RUNNER_TEMP/maven.tar.gz" | sha512sum -c -
62+
tar -xzf "$RUNNER_TEMP/maven.tar.gz" -C "$RUNNER_TEMP"
63+
echo "$RUNNER_TEMP/apache-maven-$MAVEN_VERSION/bin" >> "$GITHUB_PATH"
64+
- name: Sign and upload for review
65+
env:
66+
CENTRAL_TOKEN_USERNAME: ${{ secrets.CENTRAL_TOKEN_USERNAME }}
67+
CENTRAL_TOKEN_PASSWORD: ${{ secrets.CENTRAL_TOKEN_PASSWORD }}
68+
MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
69+
run: mvn -B -ntp -P release deploy

‎.gitignore‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
target/
2+
__pycache__/
3+
*.class
4+
.idea/
5+
*.iml
6+
.vscode/

‎LICENSE‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Transcript Dock
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

‎README.md‎

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
# Transcript Dock for Java
2+
3+
A synchronous client for the [Transcript Dock API](https://www.transcriptdock.com/docs).
4+
Java 11 or newer, also usable from Kotlin on the JVM. No runtime dependencies: it
5+
uses the JDK's `java.net.http.HttpClient` and a small built in JSON reader.
6+
7+
Maven coordinates are `com.transcriptdock:transcriptdock:0.1.0`.
8+
9+
```xml
10+
<dependency>
11+
<groupId>com.transcriptdock</groupId>
12+
<artifactId>transcriptdock</artifactId>
13+
<version>0.1.0</version>
14+
</dependency>
15+
```
16+
17+
Gradle:
18+
19+
```kotlin
20+
implementation("com.transcriptdock:transcriptdock:0.1.0")
21+
```
22+
23+
The first release to Maven Central is awaiting review. Until it appears there, run
24+
`mvn install` in this directory to use the library from your local repository.
25+
26+
## Submit and read a transcript
27+
28+
Set `TRANSCRIPTDOCK_API_KEY` in your environment. Keep it out of source control.
29+
30+
```java
31+
import com.transcriptdock.JobTimeoutException;
32+
import com.transcriptdock.TranscriptDock;
33+
import java.time.Duration;
34+
import java.util.Map;
35+
import java.util.UUID;
36+
37+
TranscriptDock client = new TranscriptDock(System.getenv("TRANSCRIPTDOCK_API_KEY"));
38+
System.out.println(client.capabilities());
39+
40+
// Generate once per intended operation. Save this key and the returned job ID.
41+
// Reuse the same key and exact body if a submission's response is lost.
42+
String submissionKey = UUID.randomUUID().toString();
43+
Map<String, Object> job = client.createJob(Map.of(
44+
"source", Map.of("url", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
45+
"mode", "captions_only",
46+
"max_credits", 1), submissionKey);
47+
try {
48+
job = client.waitForJob((String) job.get("id"), Duration.ofSeconds(120), Duration.ofSeconds(3));
49+
if ("succeeded".equals(job.get("status"))) {
50+
String transcriptId = (String) job.get("result_id");
51+
System.out.println(client.getTranscript(transcriptId));
52+
System.out.println(client.exportTranscript(transcriptId, "srt"));
53+
} else {
54+
System.out.println(job.get("status") + " " + job.get("error"));
55+
}
56+
} catch (JobTimeoutException error) {
57+
System.out.println("Still running " + error.getJob());
58+
}
59+
```
60+
61+
Kotlin:
62+
63+
```kotlin
64+
val client = TranscriptDock(System.getenv("TRANSCRIPTDOCK_API_KEY"))
65+
val key = java.util.UUID.randomUUID().toString()
66+
val job = client.createJob(
67+
mapOf("source" to mapOf("url" to "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
68+
"mode" to "captions_only", "max_credits" to 1),
69+
key,
70+
)
71+
val done = client.waitForJob(job["id"] as String)
72+
if (done["status"] == "succeeded") println(client.exportTranscript(done["result_id"] as String, "srt"))
73+
```
74+
75+
Creating a job can spend credits. This example caps the request at one credit
76+
and requests captions only. It does not enable AI fallback. Check capabilities
77+
and your plan before selecting other modes. Never blindly resubmit after a
78+
network failure: check the job ID or replay the same body with the same
79+
idempotency key. The client does not retry requests automatically.
80+
81+
## Supported operations
82+
83+
All responses are `Map<String, Object>` values that keep every field the API
84+
returns, including fields added later. Nested objects are maps, arrays are lists,
85+
integers are `Long`, other numbers are `Double` (or `BigDecimal` when too large).
86+
Request bodies use the API's exact field names; the server validates supported
87+
options. See the [OpenAPI definition](https://www.transcriptdock.com/docs/openapi.yaml)
88+
for bodies.
89+
90+
* `capabilities()`, `usage()`
91+
* `createJob(body, idempotencyKey)`, `getJob(id)`, `getJob(id, wait)`,
92+
`listJobs()`, `listJobs(limit, cursor)`, `cancelJob(id)`,
93+
`retryJob(id, idempotencyKey)`, `retryJob(id, idempotencyKey, maxCredits)`,
94+
`waitForJob(id)`, `waitForJob(id, timeout, pollInterval)`
95+
* `getTranscript(id)`, `exportTranscript(id)`, `exportTranscript(id, format)`, `deleteTranscript(id)`
96+
* `createBatch(body, idempotencyKey)`, `getBatch(id)`
97+
* `createVideoDiscovery(body, idempotencyKey)`, `getVideoDiscovery(id)`
98+
* `createLanguageDiscovery(body, idempotencyKey)`, `getLanguageDiscovery(id)`
99+
* `createUpload(body)`, `completeUpload(id)`
100+
* `listWebhookEndpoints()`, `createWebhookEndpoint(body)`, `deleteWebhookEndpoint(id)`
101+
102+
`exportTranscript` returns a `String` for JSON, TXT, SRT and VTT, preserving the
103+
export response. `getTranscript` preserves raw timing fields without converting
104+
units. `waitForJob` returns succeeded, failed or cancelled jobs; inspect status
105+
before using `result_id`. Its defaults are 120 seconds and a 3 second poll
106+
interval. A timeout leaves the job running and throws `JobTimeoutException`,
107+
whose `getJob()` returns the last observed response (or `null` if no poll was
108+
possible). A response with no content, such as 204, returns an empty map.
109+
110+
`createUpload` creates an upload slot only. Transfer bytes to the returned signed
111+
upload URL separately following the API instructions, without sending your
112+
Transcript Dock API key to the storage host. Then call `completeUpload`.
113+
Webhook secrets are sensitive; store them privately and verify callback
114+
signatures in your receiver according to the API documentation.
115+
116+
`request(method, "/v1/...", body, query, idempotencyKey)` supports public
117+
endpoints added later. Use `requestText` or the seven argument `request` with
118+
`text` set to `true` for non JSON responses. Methods must be uppercase. Paths
119+
cannot contain a query, fragment, backslash or dot segments, even percent
120+
encoded. Submissions to `/v1/jobs`, `/v1/batches`, `/v1/video-discoveries`,
121+
`/v1/language-discoveries` and any `/retry` path require an idempotency key of 8
122+
to 128 printable ASCII characters. Redirects are never followed.
123+
124+
The client is immutable and thread safe; share one instance. The default request
125+
timeout is 30 seconds. Use the builder for another origin or timeout:
126+
127+
```java
128+
TranscriptDock client = TranscriptDock.builder(apiKey)
129+
.baseUrl("https://www.transcriptdock.com")
130+
.timeout(Duration.ofSeconds(10))
131+
.build();
132+
```
133+
134+
Custom API origins must use HTTPS, except loopback HTTP for local development.
135+
The default origin is `https://www.transcriptdock.com`; the apex domain redirects.
136+
137+
## Errors
138+
139+
```java
140+
import com.transcriptdock.ApiException;
141+
142+
try {
143+
Map<String, Object> jobs = client.listJobs(10, null);
144+
} catch (ApiException error) {
145+
System.out.println(error.getCode() + " " + error.getStatus() + " " + error.getRequestId());
146+
// isRetryable() and getRetryAfterSeconds() describe the API response.
147+
// Decide whether to retry using the operation's idempotency rules.
148+
}
149+
```
150+
151+
`ApiException` is unchecked. Transport failures and timeouts use `NETWORK_ERROR`
152+
with a null status; malformed responses use `INVALID_RESPONSE`. A redirect is an
153+
`ApiException` with its 3xx status. API messages redact bearer tokens. Error
154+
responses do not expose raw HTML pages. Invalid arguments throw
155+
`IllegalArgumentException` before any request is sent.
156+
157+
The client itself never retries. The JDK HTTP client can retry a failed
158+
connection attempt, and can resend a GET or HEAD once when a reused pooled
159+
connection turns out to be closed. It does not resend a POST unless you set the
160+
`jdk.httpclient.enableAllMethodRetry` system property, so leave it unset.
161+
162+
## Platform support
163+
164+
Desktop and server JVMs running Java 11 or newer, from Java or Kotlin. Android
165+
does not ship `java.net.http`, so this library does not run on Android.
166+
167+
## Development and release
168+
169+
```sh
170+
mvn -B -ntp verify
171+
python3 .ci/check.py
172+
```
173+
174+
`mvn verify` compiles for Java 11, runs the JUnit tests and builds the main,
175+
sources and javadoc jars. `.ci/check.py` runs the contract checks in
176+
`src/test/java/com/transcriptdock/ClientCheck.java` against a loopback fixture
177+
server; run it after `mvn verify`. Tests spend no credits and never call
178+
production. Every Maven plugin version is pinned in `pom.xml`; CI installs a
179+
pinned, checksum verified Maven. Maven has no lockfile format; the only
180+
dependency is JUnit in test scope.
181+
182+
Maven Central has no OIDC trusted publishing, so the publish job uses a Central
183+
Portal user token and a GPG key. One time setup by the founder:
184+
185+
1. Sign in at https://central.sonatype.com and add the namespace `com.transcriptdock`.
186+
2. Verify it by adding the DNS TXT record the portal shows to `transcriptdock.com`.
187+
3. Generate a user token in the portal.
188+
4. Create a GPG signing key and upload the public key to https://keys.openpgp.org.
189+
5. In this repository, create the `maven-central` environment and add the secrets
190+
`CENTRAL_TOKEN_USERNAME`, `CENTRAL_TOKEN_PASSWORD`, `GPG_PRIVATE_KEY`
191+
(ASCII armored, from `gpg --armor --export-secret-keys KEY_ID`) and `GPG_PASSPHRASE`.
192+
193+
Run the GitHub Actions workflow on `main` with `publish` enabled for an
194+
authorized new release. It signs the artifacts and uploads them as a deployment
195+
that is not published automatically. Review it in the Central Portal and press
196+
Publish. The normal push workflow checks and builds only. Never put registry or
197+
API credentials in this directory. A local build is not a release.

0 commit comments

Comments
 (0)