Skip to content

Commit fc8147e

Browse files
committed
Prepare Transcript Dock Ruby client with local fixture checks and release workflow
0 parents  commit fc8147e

9 files changed

Lines changed: 431 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(['ruby', 'test/client_check.rb'], 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: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
name: Check and release
2+
on:
3+
push:
4+
branches: [main]
5+
pull_request:
6+
workflow_dispatch:
7+
inputs:
8+
publish:
9+
description: Publish the checked package
10+
type: boolean
11+
default: false
12+
permissions:
13+
contents: read
14+
jobs:
15+
check:
16+
runs-on: ubuntu-latest
17+
steps:
18+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
19+
- uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199
20+
with:
21+
ruby-version: '3.2'
22+
bundler-cache: false
23+
- run: python3 .ci/check.py
24+
- run: mkdir -p artifacts && gem build transcriptdock.gemspec --output artifacts/transcriptdock-0.1.0.gem
25+
publish:
26+
if: github.event_name == 'workflow_dispatch' && inputs.publish && github.ref == 'refs/heads/main'
27+
needs: check
28+
runs-on: ubuntu-latest
29+
environment: rubygems
30+
permissions:
31+
contents: read
32+
id-token: write
33+
steps:
34+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
35+
- uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199
36+
with:
37+
ruby-version: '3.2'
38+
bundler-cache: false
39+
- run: mkdir -p artifacts && gem build transcriptdock.gemspec --output artifacts/transcriptdock-0.1.0.gem
40+
- uses: rubygems/configure-rubygems-credentials@17e51a8c9fcf6d5f709e04cc612fd105f9273170
41+
- run: gem push artifacts/transcriptdock-0.1.0.gem

‎.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
dist/
2+
*.gem
3+
4+
__pycache__/
5+
artifacts/

‎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: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Transcript Dock for Ruby
2+
3+
A synchronous client using Ruby's standard libraries. Requires Ruby 3.2 or
4+
newer. Version 0.1.0.
5+
6+
Install:
7+
8+
```sh
9+
gem install transcriptdock
10+
```
11+
12+
```ruby
13+
require 'transcriptdock'
14+
require 'securerandom'
15+
16+
client = TranscriptDock::Client.new(ENV.fetch('TRANSCRIPTDOCK_API_KEY'))
17+
# Generate once per intended operation; save with the returned job ID.
18+
key = SecureRandom.uuid
19+
job = client.create_job(
20+
{source: {url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'},
21+
mode: 'captions_only', max_credits: 1},
22+
idempotency_key: key
23+
)
24+
job = client.wait_for_job(job['id'], timeout: 120)
25+
if job['status'] == 'succeeded'
26+
puts client.export_transcript(job['result_id'], format: 'srt')
27+
end
28+
```
29+
30+
Creating a job can spend credits. This example requests captions only with a
31+
one credit ceiling. It does not enable AI fallback. Save the operation key and
32+
reuse the exact body and same key to recover a lost response. There are no
33+
automatic retries, including in the underlying HTTP transport.
34+
35+
`capabilities`, `create_job`, `get_job`, `get_transcript`, `export_transcript`
36+
and `wait_for_job` provide the core flow. All public endpoints are available
37+
through `request(method, path, body: nil, query: {}, idempotency_key: nil)`.
38+
Use the exact fields in the [API contract](https://www.transcriptdock.com/docs/openapi.yaml)
39+
for batches, discovery, usage, upload slots and webhook endpoints.
40+
41+
Responses are hashes retaining future fields and original timing units.
42+
Exports return the raw JSON, TXT, SRT or VTT string. Polling returns failed and
43+
cancelled terminal jobs normally; inspect status first. `JobTimeoutError#job`
44+
retains the last observed response. `ApiError` exposes `code`, `status`,
45+
`retryable`, `request_id` and `retry_after_seconds`. Error messages redact bearer
46+
keys and do not expose raw gateway pages.
47+
48+
The default per request timeout is 30 seconds. The constructor accepts
49+
`base_url:` and `timeout:`. Custom origins require HTTPS, except loopback HTTP
50+
for development. Redirects are not followed. Upload signed storage URLs
51+
separately without the API key. Store webhook secrets privately and implement
52+
callback signature checks following the API documentation.
53+
54+
## Check and build
55+
56+
From the application repository root with Ruby and Python 3 installed:
57+
58+
```sh
59+
python3 .ci/check.py
60+
mkdir -p dist
61+
gem build transcriptdock.gemspec --output dist/transcriptdock-0.1.0.gem
62+
```
63+
64+
The shared fixture uses loopback HTTP and spends no credits. No lockfile is
65+
needed for third party dependencies because this library has none. Release workflow: https://github.com/TranscriptDock/transcriptdock-ruby/actions.

‎lib/transcriptdock.rb‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
# frozen_string_literal: true
2+
require 'net/http'
3+
require 'json'
4+
require 'uri'
5+
require 'ipaddr'
6+
7+
module TranscriptDock
8+
VERSION = '0.1.0'
9+
10+
class ApiError < StandardError
11+
attr_reader :code, :status, :retryable, :request_id, :retry_after_seconds
12+
def initialize(code, message, status: nil, retryable: false, request_id: nil, retry_after_seconds: nil)
13+
super(message)
14+
@code, @status, @retryable = code, status, retryable
15+
@request_id, @retry_after_seconds = request_id, retry_after_seconds
16+
end
17+
end
18+
19+
class JobTimeoutError < StandardError
20+
attr_reader :job
21+
def initialize(job)
22+
super('The job is still running. Check it again using its ID.')
23+
@job = job
24+
end
25+
end
26+
27+
class Client
28+
def initialize(api_key, base_url: 'https://www.transcriptdock.com', timeout: 30)
29+
raise ArgumentError, 'Provide an API key without whitespace or control characters.' unless api_key.is_a?(String) && api_key.match?(/\A[!-~]+\z/)
30+
origin = URI.parse(base_url)
31+
begin
32+
loopback = origin.hostname == 'localhost' || IPAddr.new(origin.hostname).loopback?
33+
rescue IPAddr::InvalidAddressError, ArgumentError
34+
loopback = false
35+
end
36+
unless origin.is_a?(URI::HTTP) && origin.hostname && (origin.scheme == 'https' || (origin.scheme == 'http' && loopback)) && origin.userinfo.nil? && origin.query.nil? && origin.fragment.nil? && ['', '/'].include?(origin.path)
37+
raise ArgumentError, 'Use an HTTPS origin, or loopback HTTP, without credentials, path, query or fragment.'
38+
end
39+
@api_key, @base_url = api_key, base_url.sub(%r{/\z}, '')
40+
@timeout = positive(timeout, 'timeout')
41+
rescue URI::InvalidURIError
42+
raise ArgumentError, 'Provide a valid API origin.'
43+
end
44+
45+
def request(method, path, body: nil, query: {}, idempotency_key: nil, text: false, timeout: @timeout)
46+
raise ArgumentError, 'Provide a supported HTTP method.' unless method.is_a?(String) && %w[GET POST PUT PATCH DELETE HEAD OPTIONS].include?(method.upcase)
47+
method = method.upcase
48+
unless path.is_a?(String) && path.start_with?('/v1/') && !path.match?(/[?#\\]/) && !URI::DEFAULT_PARSER.unescape(path).split('/').any? { |s| ['.', '..'].include?(s) }
49+
raise ArgumentError, 'Use a /v1/ path and pass query parameters separately.'
50+
end
51+
needs_key = method == 'POST' && (%w[/v1/jobs /v1/batches /v1/video-discoveries /v1/language-discoveries].include?(path) || path.end_with?('/retry'))
52+
if needs_key || !idempotency_key.nil?
53+
raise ArgumentError, 'Idempotency keys need 8 to 128 printable ASCII characters.' unless idempotency_key.is_a?(String) && idempotency_key.match?(/\A[ -~]{8,128}\z/)
54+
end
55+
uri = URI.parse(@base_url + path)
56+
uri.query = URI.encode_www_form(query.reject { |_, v| v.nil? }) unless query.empty?
57+
headers = {'Authorization' => "Bearer #{@api_key}", 'Accept' => 'application/json', 'User-Agent' => "transcriptdock-ruby/#{VERSION}"}
58+
headers['Idempotency-Key'] = idempotency_key if idempotency_key
59+
headers['Content-Type'] = 'application/json' unless body.nil?
60+
req = Net::HTTPGenericRequest.new(method, !body.nil?, method != 'HEAD', uri.request_uri, headers)
61+
req.body = JSON.generate(body) unless body.nil?
62+
http = Net::HTTP.new(uri.hostname, uri.port, nil)
63+
http.use_ssl = uri.scheme == 'https'
64+
http.max_retries = 0
65+
http.open_timeout = http.read_timeout = http.write_timeout = positive(timeout, 'timeout')
66+
begin
67+
response = http.start { |connection| connection.request(req) }
68+
rescue IOError, SystemCallError, Timeout::Error, SocketError, OpenSSL::SSL::SSLError
69+
raise ApiError.new('NETWORK_ERROR', 'Could not reach the API. Check the job before retrying a submission.', retryable: true), cause: nil
70+
end
71+
status = response.code.to_i
72+
if status < 200 || status >= 300
73+
begin
74+
envelope = JSON.parse(response.body)
75+
rescue JSON::ParserError
76+
envelope = {}
77+
end
78+
envelope = {} unless envelope.is_a?(Hash)
79+
error = envelope['error'].is_a?(Hash) ? envelope['error'] : {}
80+
raise ApiError.new(redact(error['code'] || 'HTTP_ERROR'), redact(error['message'] || "Request failed with status #{status}."), status: status,
81+
retryable: error.fetch('retryable', status == 429 || status >= 500), request_id: envelope['request_id'] && redact(envelope['request_id']), retry_after_seconds: error['retry_after_seconds'])
82+
end
83+
return response.body if text
84+
begin
85+
result = JSON.parse(response.body)
86+
rescue JSON::ParserError
87+
raise ApiError.new('INVALID_RESPONSE', 'The API did not return JSON.'), cause: nil
88+
end
89+
raise ApiError.new('INVALID_RESPONSE', 'The API did not return a JSON object.') unless result.is_a?(Hash)
90+
result
91+
end
92+
93+
def capabilities = request('GET', '/v1/capabilities')
94+
def create_job(body, idempotency_key:) = request('POST', '/v1/jobs', body: body, idempotency_key: idempotency_key)
95+
def get_job(id) = request('GET', "/v1/jobs/#{encode_id(id)}")
96+
def get_transcript(id) = request('GET', "/v1/transcripts/#{encode_id(id)}")
97+
def export_transcript(id, format: 'txt')
98+
raise ArgumentError, 'Choose json, txt, srt or vtt.' unless %w[json txt srt vtt].include?(format)
99+
request('GET', "/v1/transcripts/#{encode_id(id)}/export", query: {format: format}, text: true)
100+
end
101+
102+
def wait_for_job(id, timeout: 120, poll_interval: 3)
103+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + positive(timeout, 'timeout')
104+
positive(poll_interval, 'poll_interval')
105+
last = nil
106+
loop do
107+
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
108+
raise JobTimeoutError, last if remaining <= 0
109+
last = request('GET', "/v1/jobs/#{encode_id(id)}", timeout: [remaining, @timeout].min)
110+
return last if %w[succeeded failed cancelled].include?(last['status'])
111+
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
112+
raise JobTimeoutError, last if remaining <= 0
113+
sleep [remaining, poll_interval].min
114+
end
115+
end
116+
117+
private
118+
def positive(value, name)
119+
raise ArgumentError, "#{name} must be a finite positive number." unless value.is_a?(Numeric) && value.finite? && value > 0
120+
value
121+
end
122+
def encode_id(id)
123+
raise ArgumentError, 'Provide a nonempty ID.' unless id.is_a?(String) && !id.empty? && !['.', '..'].include?(id)
124+
URI.encode_www_form_component(id).gsub('+', '%20')
125+
end
126+
def redact(value)
127+
value.to_s.gsub(@api_key, '[REDACTED]').gsub(/td_live_[A-Za-z0-9_-]+|Bearer\s+\S+/i, '[REDACTED]')
128+
end
129+
end
130+
end

0 commit comments

Comments
 (0)