ebinex-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ebinex_sdk/__init__.py +117 -0
- ebinex_sdk/_clock.py +196 -0
- ebinex_sdk/_context.py +294 -0
- ebinex_sdk/_realtime.py +807 -0
- ebinex_sdk/_version.py +1 -0
- ebinex_sdk/client.py +103 -0
- ebinex_sdk/config.py +91 -0
- ebinex_sdk/exceptions.py +89 -0
- ebinex_sdk/models/__init__.py +64 -0
- ebinex_sdk/models/account.py +24 -0
- ebinex_sdk/models/base.py +7 -0
- ebinex_sdk/models/enums.py +13 -0
- ebinex_sdk/models/market.py +55 -0
- ebinex_sdk/models/order.py +70 -0
- ebinex_sdk/models/readiness.py +63 -0
- ebinex_sdk/models/reconcile.py +45 -0
- ebinex_sdk/models/report.py +75 -0
- ebinex_sdk/models/session.py +8 -0
- ebinex_sdk/models/surface.py +46 -0
- ebinex_sdk/protocols/__init__.py +4 -0
- ebinex_sdk/protocols/_errors.py +7 -0
- ebinex_sdk/protocols/sockjs.py +144 -0
- ebinex_sdk/protocols/stomp.py +222 -0
- ebinex_sdk/py.typed +1 -0
- ebinex_sdk/services/__init__.py +6 -0
- ebinex_sdk/services/_accounts.py +81 -0
- ebinex_sdk/services/_base.py +8 -0
- ebinex_sdk/services/_execution.py +755 -0
- ebinex_sdk/services/_history.py +216 -0
- ebinex_sdk/services/_report.py +227 -0
- ebinex_sdk/services/_wire.py +219 -0
- ebinex_sdk/services/accounts.py +148 -0
- ebinex_sdk/services/auth.py +221 -0
- ebinex_sdk/services/market.py +612 -0
- ebinex_sdk/services/orders.py +590 -0
- ebinex_sdk/storage/__init__.py +13 -0
- ebinex_sdk/storage/_perms.py +235 -0
- ebinex_sdk/storage/_records.py +93 -0
- ebinex_sdk/storage/_store.py +485 -0
- ebinex_sdk/transports/__init__.py +4 -0
- ebinex_sdk/transports/http.py +278 -0
- ebinex_sdk/transports/ws.py +343 -0
- ebinex_sdk-0.1.0.dist-info/METADATA +125 -0
- ebinex_sdk-0.1.0.dist-info/RECORD +46 -0
- ebinex_sdk-0.1.0.dist-info/WHEEL +4 -0
- ebinex_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
ebinex_sdk/__init__.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from ebinex_sdk._version import __version__
|
|
2
|
+
from ebinex_sdk.client import EbinexClient
|
|
3
|
+
from ebinex_sdk.config import (
|
|
4
|
+
AuthConfig,
|
|
5
|
+
Config,
|
|
6
|
+
Credentials,
|
|
7
|
+
JournalConfig,
|
|
8
|
+
StorageConfig,
|
|
9
|
+
)
|
|
10
|
+
from ebinex_sdk.exceptions import (
|
|
11
|
+
AuthError,
|
|
12
|
+
ChallengeError,
|
|
13
|
+
EbinexError,
|
|
14
|
+
FeatureNotImplementedError,
|
|
15
|
+
MarketError,
|
|
16
|
+
OrderConflictError,
|
|
17
|
+
OrderDeadlineError,
|
|
18
|
+
OrderError,
|
|
19
|
+
OrderUnknownError,
|
|
20
|
+
ScheduleMismatchError,
|
|
21
|
+
ScheduleUnverifiedError,
|
|
22
|
+
StorageBusyError,
|
|
23
|
+
StorageError,
|
|
24
|
+
TransportError,
|
|
25
|
+
)
|
|
26
|
+
from ebinex_sdk.models import (
|
|
27
|
+
Account,
|
|
28
|
+
AccountSurface,
|
|
29
|
+
Asset,
|
|
30
|
+
AssetMode,
|
|
31
|
+
AssetSurface,
|
|
32
|
+
Balance,
|
|
33
|
+
Candle,
|
|
34
|
+
CandleSlice,
|
|
35
|
+
ClockSample,
|
|
36
|
+
ConnState,
|
|
37
|
+
Correlation,
|
|
38
|
+
Direction,
|
|
39
|
+
Environment,
|
|
40
|
+
FilterOption,
|
|
41
|
+
Filters,
|
|
42
|
+
HistoryOrder,
|
|
43
|
+
InconclusiveError,
|
|
44
|
+
MarketEvent,
|
|
45
|
+
ModeSurface,
|
|
46
|
+
Order,
|
|
47
|
+
OrderRequest,
|
|
48
|
+
Profile,
|
|
49
|
+
Readiness,
|
|
50
|
+
ReconcileResult,
|
|
51
|
+
ReconcileStatus,
|
|
52
|
+
ReportPage,
|
|
53
|
+
ReportRow,
|
|
54
|
+
RevenuePoint,
|
|
55
|
+
Session,
|
|
56
|
+
Stats,
|
|
57
|
+
Surface,
|
|
58
|
+
TimeframeSurface,
|
|
59
|
+
Timing,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"Account",
|
|
64
|
+
"Environment",
|
|
65
|
+
"AccountSurface",
|
|
66
|
+
"Asset",
|
|
67
|
+
"AssetMode",
|
|
68
|
+
"AssetSurface",
|
|
69
|
+
"AuthError",
|
|
70
|
+
"AuthConfig",
|
|
71
|
+
"Balance",
|
|
72
|
+
"ClockSample",
|
|
73
|
+
"Candle",
|
|
74
|
+
"Config",
|
|
75
|
+
"ConnState",
|
|
76
|
+
"Credentials",
|
|
77
|
+
"RevenuePoint",
|
|
78
|
+
"Direction",
|
|
79
|
+
"EbinexClient",
|
|
80
|
+
"EbinexError",
|
|
81
|
+
"FeatureNotImplementedError",
|
|
82
|
+
"FilterOption",
|
|
83
|
+
"HistoryOrder",
|
|
84
|
+
"ChallengeError",
|
|
85
|
+
"MarketEvent",
|
|
86
|
+
"ModeSurface",
|
|
87
|
+
"Filters",
|
|
88
|
+
"ReportRow",
|
|
89
|
+
"Surface",
|
|
90
|
+
"ReportPage",
|
|
91
|
+
"Stats",
|
|
92
|
+
"Order",
|
|
93
|
+
"CandleSlice",
|
|
94
|
+
"OrderConflictError",
|
|
95
|
+
"Correlation",
|
|
96
|
+
"OrderDeadlineError",
|
|
97
|
+
"OrderError",
|
|
98
|
+
"JournalConfig",
|
|
99
|
+
"OrderRequest",
|
|
100
|
+
"ScheduleMismatchError",
|
|
101
|
+
"ScheduleUnverifiedError",
|
|
102
|
+
"OrderUnknownError",
|
|
103
|
+
"Timing",
|
|
104
|
+
"Profile",
|
|
105
|
+
"StorageConfig",
|
|
106
|
+
"Readiness",
|
|
107
|
+
"InconclusiveError",
|
|
108
|
+
"ReconcileResult",
|
|
109
|
+
"ReconcileStatus",
|
|
110
|
+
"Session",
|
|
111
|
+
"TimeframeSurface",
|
|
112
|
+
"StorageBusyError",
|
|
113
|
+
"StorageError",
|
|
114
|
+
"TransportError",
|
|
115
|
+
"MarketError",
|
|
116
|
+
"__version__",
|
|
117
|
+
]
|
ebinex_sdk/_clock.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Pure broker-time estimation and fixed, monotonic OPTION deadlines.
|
|
2
|
+
|
|
3
|
+
Samples must come from an authoritative source validated by the caller. This
|
|
4
|
+
module neither fetches time nor interprets a local timestamp as broker evidence.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import UTC, datetime, timedelta
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
from uuid import uuid4
|
|
14
|
+
|
|
15
|
+
from ebinex_sdk.config import Config
|
|
16
|
+
from ebinex_sdk.exceptions import OrderDeadlineError, OrderError
|
|
17
|
+
from ebinex_sdk.models import ClockSample, Timing
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from ebinex_sdk._context import Clock
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ClockError(OrderError):
|
|
24
|
+
"""No current, sufficiently precise broker-time sample is available."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
super().__init__("A fresh, trustworthy broker clock is required before dispatch.")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class EntryDeadline:
|
|
32
|
+
entry_at: datetime
|
|
33
|
+
expires_at: float
|
|
34
|
+
signal_id: str = field(repr=False)
|
|
35
|
+
|
|
36
|
+
def remaining(self, clock: Clock) -> float:
|
|
37
|
+
"""Wall time is intentionally never consulted after the deadline is fixed."""
|
|
38
|
+
current = clock.monotonic()
|
|
39
|
+
if not math.isfinite(current) or current < 0:
|
|
40
|
+
raise ClockError()
|
|
41
|
+
return max(0.0, self.expires_at - current)
|
|
42
|
+
|
|
43
|
+
def expired(self, clock: Clock) -> bool:
|
|
44
|
+
return self.remaining(clock) <= 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _utc(value: datetime) -> datetime:
|
|
48
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
49
|
+
raise ClockError()
|
|
50
|
+
return value.astimezone(UTC)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class BrokerClock:
|
|
54
|
+
def __init__(self, config: Config, clock: Clock) -> None:
|
|
55
|
+
self.config = config
|
|
56
|
+
self.clock = clock
|
|
57
|
+
self._sample: ClockSample | None = None
|
|
58
|
+
self._received_at = 0.0
|
|
59
|
+
self._wall_received_at: datetime | None = None
|
|
60
|
+
self._last_observed = 0.0
|
|
61
|
+
|
|
62
|
+
def invalidate(self) -> None:
|
|
63
|
+
self._sample = None
|
|
64
|
+
self._wall_received_at = None
|
|
65
|
+
|
|
66
|
+
def record_sample(
|
|
67
|
+
self,
|
|
68
|
+
server_time: datetime,
|
|
69
|
+
*,
|
|
70
|
+
sent_at: float,
|
|
71
|
+
received_at: float,
|
|
72
|
+
wall_received_at: datetime,
|
|
73
|
+
) -> ClockSample:
|
|
74
|
+
"""Anchor a broker timestamp at the request midpoint with RTT/2 uncertainty.
|
|
75
|
+
|
|
76
|
+
The wall timestamp was captured at receipt, not when processing this call.
|
|
77
|
+
Delayed delivery therefore consumes the sample's TTL instead of renewing it.
|
|
78
|
+
"""
|
|
79
|
+
self.invalidate()
|
|
80
|
+
try:
|
|
81
|
+
current = self.clock.monotonic()
|
|
82
|
+
if (
|
|
83
|
+
not all(math.isfinite(value) for value in (sent_at, received_at, current))
|
|
84
|
+
or not 0 <= sent_at <= received_at <= current
|
|
85
|
+
):
|
|
86
|
+
raise ClockError()
|
|
87
|
+
server_time = _utc(server_time)
|
|
88
|
+
wall_received_at = _utc(wall_received_at)
|
|
89
|
+
uncertainty = (received_at - sent_at) / 2
|
|
90
|
+
midpoint = sent_at + uncertainty
|
|
91
|
+
sample = ClockSample(
|
|
92
|
+
server_time=server_time,
|
|
93
|
+
sampled_at=wall_received_at - timedelta(seconds=uncertainty),
|
|
94
|
+
monotonic_at=midpoint,
|
|
95
|
+
uncertainty=uncertainty,
|
|
96
|
+
)
|
|
97
|
+
except (ValueError, OverflowError):
|
|
98
|
+
raise ClockError() from None
|
|
99
|
+
self._sample = sample
|
|
100
|
+
self._received_at = received_at
|
|
101
|
+
self._wall_received_at = wall_received_at
|
|
102
|
+
self._last_observed = received_at
|
|
103
|
+
return sample
|
|
104
|
+
|
|
105
|
+
def _observation(self) -> tuple[ClockSample, float] | None:
|
|
106
|
+
sample, wall_received = self._sample, self._wall_received_at
|
|
107
|
+
if sample is None or wall_received is None:
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
current = self.clock.monotonic()
|
|
111
|
+
wall = _utc(self.clock.utcnow())
|
|
112
|
+
if (
|
|
113
|
+
not math.isfinite(current)
|
|
114
|
+
or current < self._last_observed
|
|
115
|
+
or current >= sample.monotonic_at + self.config.clock_sample_ttl
|
|
116
|
+
or sample.uncertainty > self.config.clock_uncertainty_budget
|
|
117
|
+
):
|
|
118
|
+
self.invalidate()
|
|
119
|
+
return None
|
|
120
|
+
expected_wall = wall_received + timedelta(seconds=current - self._received_at)
|
|
121
|
+
if abs((wall - expected_wall).total_seconds()) > self.config.clock_uncertainty_budget:
|
|
122
|
+
self.invalidate()
|
|
123
|
+
return None
|
|
124
|
+
self._last_observed = current
|
|
125
|
+
return sample, current
|
|
126
|
+
except (ClockError, ValueError, OverflowError):
|
|
127
|
+
self.invalidate()
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
def snapshot(self) -> ClockSample | None:
|
|
131
|
+
"""Return the immutable sample anchor only while its lease is trustworthy."""
|
|
132
|
+
observation = self._observation()
|
|
133
|
+
return observation[0] if observation is not None else None
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def ready(self) -> bool:
|
|
137
|
+
return self.snapshot() is not None
|
|
138
|
+
|
|
139
|
+
def now(self) -> datetime:
|
|
140
|
+
observation = self._observation()
|
|
141
|
+
if observation is None:
|
|
142
|
+
raise ClockError()
|
|
143
|
+
sample, current = observation
|
|
144
|
+
try:
|
|
145
|
+
return sample.server_time + timedelta(seconds=current - sample.monotonic_at)
|
|
146
|
+
except OverflowError:
|
|
147
|
+
self.invalidate()
|
|
148
|
+
raise ClockError() from None
|
|
149
|
+
|
|
150
|
+
def deadline(self, timing: Timing | None = None, *, timeframe: str = "M1") -> EntryDeadline:
|
|
151
|
+
"""Fix one server-aligned target; supporting a clock frame never authorizes orders."""
|
|
152
|
+
intervals = {"M1": 60, "M5": 300, "M15": 900}
|
|
153
|
+
if timeframe not in intervals:
|
|
154
|
+
raise OrderDeadlineError("Unsupported OPTION deadline timeframe.")
|
|
155
|
+
interval = intervals[timeframe]
|
|
156
|
+
observation = self._observation()
|
|
157
|
+
if observation is None:
|
|
158
|
+
raise ClockError()
|
|
159
|
+
sample, current = observation
|
|
160
|
+
try:
|
|
161
|
+
broker_now = sample.server_time + timedelta(seconds=current - sample.monotonic_at)
|
|
162
|
+
uncertainty = timedelta(seconds=sample.uncertainty)
|
|
163
|
+
|
|
164
|
+
def floor(value: datetime) -> datetime:
|
|
165
|
+
return value.replace(
|
|
166
|
+
minute=(value.minute // (interval // 60)) * (interval // 60),
|
|
167
|
+
second=0,
|
|
168
|
+
microsecond=0,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
earliest = floor(broker_now - uncertainty)
|
|
172
|
+
latest = floor(broker_now + uncertainty)
|
|
173
|
+
if earliest != latest:
|
|
174
|
+
raise OrderDeadlineError("Clock uncertainty makes the next candle ambiguous.")
|
|
175
|
+
target = floor(broker_now) + timedelta(seconds=interval)
|
|
176
|
+
if timing is not None and timing.entry_at != target:
|
|
177
|
+
raise OrderDeadlineError("Signal target must be the next candle at receipt.")
|
|
178
|
+
closing = target - timedelta(seconds=self.config.entry_cutoff)
|
|
179
|
+
if timing is not None and timing.valid_until is not None:
|
|
180
|
+
closing = min(closing, timing.valid_until)
|
|
181
|
+
remaining = (
|
|
182
|
+
(closing - broker_now).total_seconds()
|
|
183
|
+
- self.config.transport_budget
|
|
184
|
+
- sample.uncertainty
|
|
185
|
+
)
|
|
186
|
+
expires_at = current + remaining
|
|
187
|
+
if remaining <= 0 or not math.isfinite(expires_at):
|
|
188
|
+
raise OrderDeadlineError("The fixed target's dispatch window has expired.")
|
|
189
|
+
except OverflowError:
|
|
190
|
+
self.invalidate()
|
|
191
|
+
raise ClockError() from None
|
|
192
|
+
return EntryDeadline(
|
|
193
|
+
entry_at=target,
|
|
194
|
+
expires_at=expires_at,
|
|
195
|
+
signal_id=timing.signal_id if timing is not None else uuid4().hex,
|
|
196
|
+
)
|
ebinex_sdk/_context.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Shared dependencies and state; constructing this context never opens resources."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from typing import Protocol
|
|
8
|
+
|
|
9
|
+
from ebinex_sdk._realtime import Realtime
|
|
10
|
+
from ebinex_sdk.config import Config
|
|
11
|
+
from ebinex_sdk.exceptions import AuthError, StorageError
|
|
12
|
+
from ebinex_sdk.models import Account, Environment, Session
|
|
13
|
+
from ebinex_sdk.models.readiness import ConnState, Readiness
|
|
14
|
+
from ebinex_sdk.storage import StorageBinding, Store, StoredSession
|
|
15
|
+
from ebinex_sdk.transports.http import HttpTransport
|
|
16
|
+
from ebinex_sdk.transports.ws import WebSocketTransport
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Clock(Protocol):
|
|
20
|
+
def monotonic(self) -> float: ...
|
|
21
|
+
|
|
22
|
+
def utcnow(self) -> datetime: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SystemClock:
|
|
26
|
+
def monotonic(self) -> float:
|
|
27
|
+
return time.monotonic()
|
|
28
|
+
|
|
29
|
+
def utcnow(self) -> datetime:
|
|
30
|
+
return datetime.now(UTC)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SessionStore(Protocol):
|
|
34
|
+
async def load(self) -> Session | None: ...
|
|
35
|
+
|
|
36
|
+
async def save(self, session: Session) -> None: ...
|
|
37
|
+
|
|
38
|
+
async def invalidate(self) -> None: ...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class OrderJournal(Protocol):
|
|
42
|
+
"""Only a protected, durable, exclusively owned journal may report available."""
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def available(self) -> bool: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _ProtectedJournal:
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
self.available = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ClientContext:
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
config: Config,
|
|
57
|
+
*,
|
|
58
|
+
http: HttpTransport | None = None,
|
|
59
|
+
websocket: WebSocketTransport | None = None,
|
|
60
|
+
websocket_factory: Callable[[], WebSocketTransport] | None = None,
|
|
61
|
+
clock: Clock | None = None,
|
|
62
|
+
auth_store: SessionStore | None = None,
|
|
63
|
+
journal: OrderJournal | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
self.config = config
|
|
66
|
+
self._http = http
|
|
67
|
+
self.websocket = websocket
|
|
68
|
+
if websocket is not None and websocket_factory is not None:
|
|
69
|
+
raise ValueError("Inject a WebSocket transport or a factory, not both.")
|
|
70
|
+
self.websocket_factory = websocket_factory
|
|
71
|
+
self.clock = clock if clock is not None else SystemClock()
|
|
72
|
+
self.auth_store = auth_store
|
|
73
|
+
self.journal = journal
|
|
74
|
+
self.session: Session | None = None
|
|
75
|
+
self.principal_id: str | None = None
|
|
76
|
+
self.account: Account | None = None
|
|
77
|
+
self.account_lock = asyncio.Lock()
|
|
78
|
+
self.active_attempts: int = 0
|
|
79
|
+
self.generation = 0
|
|
80
|
+
self.state = ConnState.DISCONNECTED
|
|
81
|
+
self.stomp_connected = False
|
|
82
|
+
self.heartbeat_ready = False
|
|
83
|
+
self.clock_ready = False
|
|
84
|
+
self.subscriptions_ready = False
|
|
85
|
+
self.handshake_ready = False
|
|
86
|
+
self.reconciliation_ready = False
|
|
87
|
+
self.proof_available = False
|
|
88
|
+
self.auth_storage: Store | None = None
|
|
89
|
+
self.journal_storage: Store | None = None
|
|
90
|
+
self._owned_stores: list[Store] = []
|
|
91
|
+
self._storage_ready = False
|
|
92
|
+
self._storage_lock = asyncio.Lock()
|
|
93
|
+
self._protected_journal: _ProtectedJournal | None = None
|
|
94
|
+
self._auth_binding: StorageBinding | None = None
|
|
95
|
+
self._close_task: asyncio.Task[None] | None = None
|
|
96
|
+
self._realtime: Realtime | None = None
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def realtime(self) -> Realtime:
|
|
100
|
+
if self._realtime is None:
|
|
101
|
+
injected = self.websocket
|
|
102
|
+
self._realtime = Realtime(
|
|
103
|
+
self,
|
|
104
|
+
transport_factory=(
|
|
105
|
+
self.websocket_factory
|
|
106
|
+
if self.websocket_factory is not None
|
|
107
|
+
else (lambda: injected)
|
|
108
|
+
if injected is not None
|
|
109
|
+
else None
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
return self._realtime
|
|
113
|
+
|
|
114
|
+
async def prepare_stores(self) -> None:
|
|
115
|
+
"""Acquire configured storage lazily; identical configs share one owner."""
|
|
116
|
+
async with self._storage_lock:
|
|
117
|
+
if self.state == ConnState.CLOSED:
|
|
118
|
+
raise AuthError("This client is closed; construct a new client.")
|
|
119
|
+
if self._storage_ready:
|
|
120
|
+
return
|
|
121
|
+
auth_config = (
|
|
122
|
+
self.config.auth_persistence.storage
|
|
123
|
+
if self.config.auth_persistence.enabled
|
|
124
|
+
else None
|
|
125
|
+
)
|
|
126
|
+
journal_config = self.config.order_journal.storage
|
|
127
|
+
if (auth_config is not None and self.auth_store is not None) or (
|
|
128
|
+
journal_config is not None and self.journal is not None
|
|
129
|
+
):
|
|
130
|
+
raise StorageError("Configured and injected storage roles conflict")
|
|
131
|
+
stores: list[tuple[object, Store]] = []
|
|
132
|
+
try:
|
|
133
|
+
for role, settings in (("auth", auth_config), ("journal", journal_config)):
|
|
134
|
+
if settings is None:
|
|
135
|
+
continue
|
|
136
|
+
store = next(
|
|
137
|
+
(store for existing, store in stores if existing == settings), None
|
|
138
|
+
)
|
|
139
|
+
if store is None:
|
|
140
|
+
store = Store(settings)
|
|
141
|
+
stores.append((settings, store))
|
|
142
|
+
self._owned_stores.append(store)
|
|
143
|
+
await store.open()
|
|
144
|
+
if role == "auth":
|
|
145
|
+
self.auth_storage = store
|
|
146
|
+
else:
|
|
147
|
+
self.journal_storage = store
|
|
148
|
+
self._protected_journal = _ProtectedJournal()
|
|
149
|
+
self.journal = self._protected_journal
|
|
150
|
+
if self.readiness.state == ConnState.CLOSED:
|
|
151
|
+
raise AuthError("Client closed while acquiring protected storage.")
|
|
152
|
+
self._storage_ready = True
|
|
153
|
+
except BaseException:
|
|
154
|
+
await self._close_stores()
|
|
155
|
+
raise
|
|
156
|
+
|
|
157
|
+
async def stored_session(self) -> StoredSession | None:
|
|
158
|
+
await self.prepare_stores()
|
|
159
|
+
if self.auth_storage is not None:
|
|
160
|
+
return await self.auth_storage.read_stored_session(allow_expired=True)
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
async def save_auth(self, binding: StorageBinding, session: Session) -> None:
|
|
164
|
+
if self.auth_storage is not None:
|
|
165
|
+
await self.auth_storage.write_session(binding, session)
|
|
166
|
+
elif self.auth_store is not None:
|
|
167
|
+
await self.auth_store.save(session)
|
|
168
|
+
self._auth_binding = binding
|
|
169
|
+
|
|
170
|
+
async def clear_persisted_auth(self, binding: StorageBinding | None = None) -> None:
|
|
171
|
+
if self.auth_storage is not None:
|
|
172
|
+
selected = binding if binding is not None else self._auth_binding
|
|
173
|
+
if selected is None:
|
|
174
|
+
stored = await self.auth_storage.read_stored_session(allow_expired=True)
|
|
175
|
+
selected = stored.binding if stored is not None else None
|
|
176
|
+
if selected is not None:
|
|
177
|
+
await self.auth_storage.invalidate_session(selected)
|
|
178
|
+
elif self.auth_store is not None:
|
|
179
|
+
await self.auth_store.invalidate()
|
|
180
|
+
self._auth_binding = None
|
|
181
|
+
|
|
182
|
+
async def validate_journal(self, binding: StorageBinding) -> None:
|
|
183
|
+
if self.journal_storage is not None:
|
|
184
|
+
entries = await self.journal_storage.list_journal(binding)
|
|
185
|
+
if self._protected_journal is not None:
|
|
186
|
+
self._protected_journal.available = True
|
|
187
|
+
# Durable ambiguous attempts require reconciliation before future sending.
|
|
188
|
+
if any(entry.state in {"DISPATCHING", "UNKNOWN", "ACCEPTED"} for entry in entries):
|
|
189
|
+
self.reconciliation_ready = False
|
|
190
|
+
|
|
191
|
+
async def _close_stores(self) -> None:
|
|
192
|
+
stores, self._owned_stores = self._owned_stores, []
|
|
193
|
+
if self._protected_journal is not None:
|
|
194
|
+
self._protected_journal.available = False
|
|
195
|
+
self.journal = None
|
|
196
|
+
self.auth_storage = self.journal_storage = None
|
|
197
|
+
self._protected_journal = None
|
|
198
|
+
self._storage_ready = False
|
|
199
|
+
first_error: BaseException | None = None
|
|
200
|
+
for store in reversed(stores):
|
|
201
|
+
try:
|
|
202
|
+
await store.close()
|
|
203
|
+
except BaseException as error:
|
|
204
|
+
if first_error is None:
|
|
205
|
+
first_error = error
|
|
206
|
+
if first_error is not None:
|
|
207
|
+
raise first_error
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def http(self) -> HttpTransport:
|
|
211
|
+
if self._http is None:
|
|
212
|
+
from ebinex_sdk.transports.http import HttpxTransport
|
|
213
|
+
|
|
214
|
+
self._http = HttpxTransport(
|
|
215
|
+
self.config, allowed_origins=(str(self.config.sockjs_base_url),)
|
|
216
|
+
)
|
|
217
|
+
return self._http
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def readiness(self) -> Readiness:
|
|
221
|
+
authenticated = self.session is not None
|
|
222
|
+
if self.session is not None and self.session.expires_at is not None:
|
|
223
|
+
authenticated = self.session.expires_at > self.clock.utcnow()
|
|
224
|
+
return Readiness(
|
|
225
|
+
state=self.state,
|
|
226
|
+
generation=self.generation,
|
|
227
|
+
authenticated=authenticated,
|
|
228
|
+
test_account_confirmed=(
|
|
229
|
+
self.account is not None and self.account.environment == Environment.TEST
|
|
230
|
+
),
|
|
231
|
+
stomp_connected=self.stomp_connected,
|
|
232
|
+
heartbeat_ready=self.heartbeat_ready,
|
|
233
|
+
clock_ready=(
|
|
234
|
+
self.clock_ready and (self._realtime is None or self._realtime.broker_clock.ready)
|
|
235
|
+
),
|
|
236
|
+
subscriptions_ready=self.subscriptions_ready,
|
|
237
|
+
handshake_ready=self.handshake_ready,
|
|
238
|
+
reconciliation_ready=self.reconciliation_ready,
|
|
239
|
+
journal_available=self.journal is not None and self.journal.available,
|
|
240
|
+
proof_available=self.proof_available,
|
|
241
|
+
authorization_ready=(
|
|
242
|
+
self.config.enable_test_orders
|
|
243
|
+
and self.config.environment == Environment.TEST
|
|
244
|
+
and authenticated
|
|
245
|
+
and self.session is not None
|
|
246
|
+
and bool(self.session.access_token.get_secret_value().strip())
|
|
247
|
+
and self.account is not None
|
|
248
|
+
and self.account.environment == Environment.TEST
|
|
249
|
+
and self.state != ConnState.CLOSED
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
async def close(self) -> None:
|
|
254
|
+
if self._close_task is None:
|
|
255
|
+
self._close_task = asyncio.create_task(self._close_resources())
|
|
256
|
+
cancelled = False
|
|
257
|
+
while not self._close_task.done():
|
|
258
|
+
try:
|
|
259
|
+
await asyncio.shield(self._close_task)
|
|
260
|
+
except asyncio.CancelledError:
|
|
261
|
+
cancelled = True
|
|
262
|
+
self._close_task.result()
|
|
263
|
+
if cancelled:
|
|
264
|
+
raise asyncio.CancelledError
|
|
265
|
+
|
|
266
|
+
async def _close_resources(self) -> None:
|
|
267
|
+
try:
|
|
268
|
+
if self._realtime is not None:
|
|
269
|
+
await self._realtime.stop()
|
|
270
|
+
finally:
|
|
271
|
+
await self._close_remaining_resources()
|
|
272
|
+
|
|
273
|
+
async def _close_remaining_resources(self) -> None:
|
|
274
|
+
self.state = ConnState.CLOSED
|
|
275
|
+
self.generation += 1
|
|
276
|
+
self.stomp_connected = False
|
|
277
|
+
self.heartbeat_ready = False
|
|
278
|
+
self.clock_ready = False
|
|
279
|
+
self.subscriptions_ready = False
|
|
280
|
+
self.handshake_ready = False
|
|
281
|
+
self.reconciliation_ready = False
|
|
282
|
+
self.session = None
|
|
283
|
+
self.principal_id = None
|
|
284
|
+
self.account = None
|
|
285
|
+
try:
|
|
286
|
+
if self.websocket is not None:
|
|
287
|
+
await self.websocket.close()
|
|
288
|
+
finally:
|
|
289
|
+
try:
|
|
290
|
+
if self._http is not None:
|
|
291
|
+
await self._http.close()
|
|
292
|
+
finally:
|
|
293
|
+
async with self._storage_lock:
|
|
294
|
+
await self._close_stores()
|