Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 152 additions & 14 deletions sdk/openapi.json

Large diffs are not rendered by default.

52 changes: 37 additions & 15 deletions sdk/python/src/provableio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json
from dataclasses import dataclass
from typing import Any, Dict, Generic, Iterator, Mapping, Optional, TypedDict, TypeVar, Union
from typing import Any, Dict, Generic, Iterator, List, Mapping, Optional, Tuple, TypedDict, TypeVar, Union
try:
from typing import Unpack
except ImportError:
Expand Down Expand Up @@ -68,7 +68,7 @@ def __init__(
auth_headers["Authorization"] = f"Bearer {bearer_token}"
self.base_url = base_url.rstrip("/")
self._owns_client = http_client is None
self._client = http_client or httpx.Client(headers=auth_headers, timeout=timeout)
self._client = http_client or httpx.Client(headers=auth_headers, timeout=timeout, follow_redirects=True)
self._headers = auth_headers

def close(self) -> None:
Expand Down Expand Up @@ -193,6 +193,9 @@ def increment_cursor(self, query: models.IncrementCursorParams, **options: Unpac
def list_outcomes(self, query: Optional[models.ListOutcomesParams] = None, **options: Unpack[RequestOptions]) -> ApiResult[models.ListOutcomesResponse]:
return self._operation("listOutcomes", query=query, options=options)

def list_sealed_commits(self, query: Optional[models.ListSealedCommitsParams] = None, **options: Unpack[RequestOptions]) -> ApiResult[models.ListSealedCommitsResponse]:
return self._operation("listSealedCommits", query=query, options=options)

def list_merkle_roots(self, query: Optional[models.ListMerkleRootsParams] = None, **options: Unpack[RequestOptions]) -> ApiResult[models.ListMerkleRootsResponse]:
return self._operation("listMerkleRoots", query=query, options=options)

Expand Down Expand Up @@ -237,18 +240,37 @@ def stream_outcomes(
operation["method"], self.base_url + operation["path"], params=query, headers=stream_headers,
) as response:
response.raise_for_status()
for event_name, data in _sse_events(response):
if event_name == "done":
return
if event_name in ("message", "outcome"):
yield json.loads(data)

def stream_public_draws(self, *, headers: Optional[Mapping[str, str]] = None) -> Iterator[Dict[str, Any]]:
"""Every public draw as it is made (GET /o/stream on provable.io; the API host redirects there).

No history is replayed: read /o.json for the latest 8. The server ends each
connection after 5 minutes, so call this in a loop to keep following.
"""
operation = OPERATIONS["streamPublicDraws"]
stream_headers = {**self._headers, **dict(headers or {}), "Accept": "text/event-stream"}
with self._client.stream(operation["method"], self.base_url + operation["path"], headers=stream_headers) as response:
response.raise_for_status()
for event_name, data in _sse_events(response):
if event_name == "draw":
yield json.loads(data)


def _sse_events(response: httpx.Response) -> Iterator[Tuple[str, str]]:
"""(event, data) pairs from a text/event-stream response."""
data_lines: List[str] = []
event_name = "message"
for line in response.iter_lines():
if line.startswith("event:"):
event_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
elif not line and data_lines:
yield event_name, "\n".join(data_lines)
data_lines = []
event_name = "message"
for line in response.iter_lines():
if line.startswith("event:"):
event_name = line[6:].strip()
elif line.startswith("data:"):
data_lines.append(line[5:].lstrip())
elif not line and data_lines:
data = "\n".join(data_lines)
data_lines = []
if event_name == "done":
return
if event_name in ("message", "outcome"):
yield json.loads(data)
event_name = "message"
29 changes: 29 additions & 0 deletions sdk/python/src/provableio/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@ class Commit(TypedDict, total=False):
commitId: Required[str]
serverHash: Required[str]
expiresAt: Required[int]
serverSeed: str
label: str
sealed: bool
created: int
revealedAt: int

class SealedCommit(TypedDict, total=False):
commitId: Required[str]
keyId: Required[str]
label: Required[str]
serverHash: Required[str]
serverSeed: Required[str]
created: Required[int]
expiresAt: Required[int]
revealedAt: Required[int]

class RevealRequest(TypedDict, total=False):
commitId: Required[str]
Expand Down Expand Up @@ -251,8 +266,18 @@ class GetBytesParams(TypedDict, total=False):

GetBytesResponse = BytesOutcome

class CreateCommitBody(TypedDict, total=False):
sealed: bool
label: str

CreateCommitResponse = Commit

class ListSealedCommitsParams(TypedDict, total=False):
label: Required[str]
limit: int

ListSealedCommitsResponse = List[SealedCommit]

class RollDiceParams(TypedDict, total=False):
clientSeed: str
notation: Required[str]
Expand Down Expand Up @@ -372,10 +397,12 @@ class VerifyShortIdParams(TypedDict, total=False):

class VerifyShortIdResponse(TypedDict, total=False):
verified: Required[bool]
status: Literal['verified', 'committed', 'revealed', 'mismatch']
reason: Required[str]
shortId: Required[str]
clientSeed: str
serverHash: str
serverSeed: str
cursor: int
nonce: int
endpoint: str
Expand All @@ -389,6 +416,8 @@ class VerifyShortIdResponse(TypedDict, total=False):
redacted: bool
permalink: str

StreamPublicDrawsResponse = str

class GetOutcomePermalinkParams(TypedDict, total=False):
id: Required[str]

Expand Down
4 changes: 2 additions & 2 deletions sdk/python/src/provableio/operations.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Generated operation-to-method map. Do not edit by hand."""

OPERATION_METHODS = {'batchDraw': 'batch', 'getBytes': 'get_bytes', 'createCommit': 'create_commit', 'rollDice': 'roll_dice', 'getFloats': 'get_floats', 'gaussian': 'gaussian', 'getHealth': 'get_health', 'getPublicMetrics': 'get_public_metrics', 'incrementCursor': 'increment_cursor', 'getInts': 'get_ints', 'listOutcomes': 'list_outcomes', 'listMerkleRoots': 'list_merkle_roots', 'getMerkleRoot': 'get_merkle_root', 'getMerkleProof': 'get_merkle_proof', 'getOutcome': 'get_outcome', 'pickItem': 'pick', 'revealCommit': 'reveal_commit', 'rotateServerSeed': 'rotate_server_seed', 'shuffleItems': 'shuffle', 'streamOutcomes': 'stream_outcomes', 'verifyServerHash': 'verify_server_hash', 'verifyShortId': 'verify_short_id', 'getOutcomePermalink': 'get_outcome_permalink', 'getOutcomeOgImage': 'get_outcome_og_image'}
OPERATION_METHODS = {'batchDraw': 'batch', 'getBytes': 'get_bytes', 'createCommit': 'create_commit', 'listSealedCommits': 'list_sealed_commits', 'rollDice': 'roll_dice', 'getFloats': 'get_floats', 'gaussian': 'gaussian', 'getHealth': 'get_health', 'getPublicMetrics': 'get_public_metrics', 'incrementCursor': 'increment_cursor', 'getInts': 'get_ints', 'listOutcomes': 'list_outcomes', 'listMerkleRoots': 'list_merkle_roots', 'getMerkleRoot': 'get_merkle_root', 'getMerkleProof': 'get_merkle_proof', 'getOutcome': 'get_outcome', 'pickItem': 'pick', 'revealCommit': 'reveal_commit', 'rotateServerSeed': 'rotate_server_seed', 'shuffleItems': 'shuffle', 'streamOutcomes': 'stream_outcomes', 'verifyServerHash': 'verify_server_hash', 'verifyShortId': 'verify_short_id', 'streamPublicDraws': 'stream_public_draws', 'getOutcomePermalink': 'get_outcome_permalink', 'getOutcomeOgImage': 'get_outcome_og_image'}

OPERATIONS = {'batchDraw': {'method': 'POST', 'path': '/api/batch', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'getBytes': {'method': 'GET', 'path': '/api/bytes', 'query': ('clientSeed', 'count', 'encoding'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'createCommit': {'method': 'POST', 'path': '/api/commit', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'rollDice': {'method': 'GET', 'path': '/api/dice', 'query': ('clientSeed', 'notation'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getFloats': {'method': 'GET', 'path': '/api/floats', 'query': ('clientSeed', 'count'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'gaussian': {'method': 'GET', 'path': '/api/gaussian', 'query': ('clientSeed', 'count', 'distribution', 'mean', 'stddev', 'lambda'), 'query_aliases': {'lambda_': 'lambda'}, 'path_params': (), 'has_body': False}, 'getHealth': {'method': 'GET', 'path': '/api/health', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getPublicMetrics': {'method': 'GET', 'path': '/api/public-metrics', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'incrementCursor': {'method': 'GET', 'path': '/api/incrementCursor', 'query': ('clientSeed',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getInts': {'method': 'GET', 'path': '/api/ints', 'query': ('clientSeed', 'count', 'min', 'max', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listOutcomes': {'method': 'GET', 'path': '/api/listOutcomes', 'query': ('clientSeed', 'limit', 'before'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listMerkleRoots': {'method': 'GET', 'path': '/api/merkle', 'query': ('limit',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getMerkleRoot': {'method': 'GET', 'path': '/api/merkle/{date}', 'query': (), 'query_aliases': {}, 'path_params': ('date',), 'has_body': False}, 'getMerkleProof': {'method': 'GET', 'path': '/api/merkle/{date}/proof/{outcomeId}', 'query': (), 'query_aliases': {}, 'path_params': ('date', 'outcomeId'), 'has_body': False}, 'getOutcome': {'method': 'GET', 'path': '/api/outcome', 'query': ('clientSeed', 'cursor', 'nonce'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'pickItem': {'method': 'GET', 'path': '/api/pick', 'query': ('clientSeed', 'items', 'weights'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'revealCommit': {'method': 'POST', 'path': '/api/reveal', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'rotateServerSeed': {'method': 'POST', 'path': '/api/rotate', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'shuffleItems': {'method': 'GET', 'path': '/api/shuffle', 'query': ('clientSeed', 'items', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'streamOutcomes': {'method': 'GET', 'path': '/api/stream', 'query': ('clientSeed', 'endpoint', 'intervalMs', 'lastEventId'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyServerHash': {'method': 'GET', 'path': '/api/verifyServerHash', 'query': ('clientSeed', 'serverHash'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyShortId': {'method': 'GET', 'path': '/api/verifyShortId', 'query': ('shortId',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getOutcomePermalink': {'method': 'GET', 'path': '/o/{id}', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}, 'getOutcomeOgImage': {'method': 'GET', 'path': '/o/{id}/og.png', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}}
OPERATIONS = {'batchDraw': {'method': 'POST', 'path': '/api/batch', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'getBytes': {'method': 'GET', 'path': '/api/bytes', 'query': ('clientSeed', 'count', 'encoding'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'createCommit': {'method': 'POST', 'path': '/api/commit', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'listSealedCommits': {'method': 'GET', 'path': '/api/commits', 'query': ('label', 'limit'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'rollDice': {'method': 'GET', 'path': '/api/dice', 'query': ('clientSeed', 'notation'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getFloats': {'method': 'GET', 'path': '/api/floats', 'query': ('clientSeed', 'count'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'gaussian': {'method': 'GET', 'path': '/api/gaussian', 'query': ('clientSeed', 'count', 'distribution', 'mean', 'stddev', 'lambda'), 'query_aliases': {'lambda_': 'lambda'}, 'path_params': (), 'has_body': False}, 'getHealth': {'method': 'GET', 'path': '/api/health', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getPublicMetrics': {'method': 'GET', 'path': '/api/public-metrics', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'incrementCursor': {'method': 'GET', 'path': '/api/incrementCursor', 'query': ('clientSeed',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getInts': {'method': 'GET', 'path': '/api/ints', 'query': ('clientSeed', 'count', 'min', 'max', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listOutcomes': {'method': 'GET', 'path': '/api/listOutcomes', 'query': ('clientSeed', 'limit', 'before'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listMerkleRoots': {'method': 'GET', 'path': '/api/merkle', 'query': ('limit',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getMerkleRoot': {'method': 'GET', 'path': '/api/merkle/{date}', 'query': (), 'query_aliases': {}, 'path_params': ('date',), 'has_body': False}, 'getMerkleProof': {'method': 'GET', 'path': '/api/merkle/{date}/proof/{outcomeId}', 'query': (), 'query_aliases': {}, 'path_params': ('date', 'outcomeId'), 'has_body': False}, 'getOutcome': {'method': 'GET', 'path': '/api/outcome', 'query': ('clientSeed', 'cursor', 'nonce'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'pickItem': {'method': 'GET', 'path': '/api/pick', 'query': ('clientSeed', 'items', 'weights'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'revealCommit': {'method': 'POST', 'path': '/api/reveal', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'rotateServerSeed': {'method': 'POST', 'path': '/api/rotate', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'shuffleItems': {'method': 'GET', 'path': '/api/shuffle', 'query': ('clientSeed', 'items', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'streamOutcomes': {'method': 'GET', 'path': '/api/stream', 'query': ('clientSeed', 'endpoint', 'intervalMs', 'lastEventId'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyServerHash': {'method': 'GET', 'path': '/api/verifyServerHash', 'query': ('clientSeed', 'serverHash'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyShortId': {'method': 'GET', 'path': '/api/verifyShortId', 'query': ('shortId',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'streamPublicDraws': {'method': 'GET', 'path': '/o/stream', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getOutcomePermalink': {'method': 'GET', 'path': '/o/{id}', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}, 'getOutcomeOgImage': {'method': 'GET', 'path': '/o/{id}/og.png', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}}
56 changes: 47 additions & 9 deletions sdk/typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,17 @@ export class ProvableClient {
});
}

/** Public sealed commits under a label (GET /api/commits). */
listSealedCommits(
query: Query<OpGet<"/api/commits">>,
opts?: RequestOptions,
): Promise<ApiResult<OkResponse<OpGet<"/api/commits">>>> {
return this.request("GET", "/api/commits", {
query: query as Record<string, unknown>,
...opts,
});
}

getOutcomePermalink(
pathParams: PathParams<OpGet<"/o/{id}">>,
opts?: RequestOptions,
Expand Down Expand Up @@ -381,11 +392,34 @@ export class ProvableClient {
headers.set("Accept", "text/event-stream");
if (opts.lastEventId) headers.set("Last-Event-ID", opts.lastEventId);

const response = await this.fetchImpl(url, {
method: "GET",
headers,
signal: opts.signal,
});
for await (const ev of this.sse(url, headers, opts.signal)) yield ev.data;
}

/**
* Every public draw as it is made (GET /o/stream on provable.io; the API
* host redirects there). No history is replayed: read `/o.json` for the
* latest 8. The server ends each connection after 5 minutes, so loop.
*
* @example
* ```ts
* for await (const draw of client.streamPublicDraws()) console.log(draw);
* ```
*/
async *streamPublicDraws(opts: RequestOptions = {}): AsyncGenerator<unknown, void, void> {
const headers = this.buildHeaders(opts.headers);
headers.set("Accept", "text/event-stream");
for await (const ev of this.sse(this.baseUrl + "/o/stream", headers, opts.signal)) {
if (ev.event === "draw") yield ev.data;
}
}

/** Parsed `{ event, data }` frames of a text/event-stream response. */
private async *sse(
url: string,
headers: Headers,
signal?: AbortSignal,
): AsyncGenerator<{ event: string; data: unknown }, void, void> {
const response = await this.fetchImpl(url, { method: "GET", headers, signal });
if (!response.ok || !response.body) {
throw new Error(`Stream failed: HTTP ${response.status}`);
}
Expand All @@ -402,17 +436,21 @@ export class ProvableClient {
while ((idx = buf.indexOf("\n\n")) !== -1) {
const raw = buf.slice(0, idx);
buf = buf.slice(idx + 2);
const dataLines = raw
.split("\n")
const lines = raw.split("\n");
const dataLines = lines
.filter((l) => l.startsWith("data:"))
.map((l) => l.slice(5).trimStart());
if (dataLines.length === 0) continue;
const eventLine = lines.find((l) => l.startsWith("event:"));
const event = eventLine ? eventLine.slice(6).trim() : "message";
const dataStr = dataLines.join("\n");
let data: unknown = dataStr;
try {
yield JSON.parse(dataStr);
data = JSON.parse(dataStr);
} catch {
yield dataStr;
/* not JSON: pass the text through */
}
yield { event, data };
}
}
} finally {
Expand Down
Loading
Loading