zetaapi 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.
zeta/_client.py ADDED
@@ -0,0 +1,402 @@
1
+ """The synchronous client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Union, cast
8
+
9
+ import httpx
10
+
11
+ from . import _base as b
12
+ from ._base import UNSET, RequestSpec, Time
13
+ from ._errors import ZetaError, error_from_response
14
+ from ._sse import Event, SseMessage, SseParser
15
+ from ._types import (
16
+ Account, AccountInfo, AccountPage, Broker, Candles, Deals, InfoSnapshot, Order, OrdersSnapshot, PositionsSnapshot,
17
+ Quote, SymbolSpec, Timeframe, Usage,
18
+ )
19
+
20
+ Handler = Optional[Callable[[Any], None]]
21
+
22
+
23
+ class _Http:
24
+ def __init__(self, api_key: str, base_url: str, max_retries: int, timeout: float, retry_base: float, retry_max: float,
25
+ http_client: Optional[httpx.Client], transport: Optional[httpx.BaseTransport]) -> None:
26
+ self.api_key = api_key
27
+ self.base_url = base_url.rstrip("/")
28
+ self.max_retries = max_retries
29
+ self.timeout = timeout
30
+ self.retry_base = retry_base
31
+ self.retry_max = retry_max
32
+ self._own = http_client is None
33
+ self.client = http_client or httpx.Client(transport=transport, timeout=timeout)
34
+
35
+ def request(self, spec: RequestSpec) -> Any:
36
+ attempt = 0
37
+ while True:
38
+ try:
39
+ return self._once(spec)
40
+ except ZetaError as err:
41
+ if attempt >= self.max_retries or not b.should_retry(spec.retry, err):
42
+ raise err.with_key(spec.idempotency_key) from err.__cause__
43
+ time.sleep(b.retry_delay(attempt, err, self.retry_base, self.retry_max))
44
+ attempt += 1
45
+
46
+ def _once(self, spec: RequestSpec) -> Any:
47
+ try:
48
+ resp = self.client.request(
49
+ spec.method, self.base_url + spec.path, params=spec.params or None,
50
+ content=b.encode_body(spec.body), headers=b.headers(self.api_key, spec), timeout=self.timeout,
51
+ )
52
+ except httpx.TransportError as e:
53
+ raise b.transport_error(e) from e
54
+ return b.parse_response(resp)
55
+
56
+ def get(self, path: str, **params: Any) -> Any:
57
+ return self.request(RequestSpec("GET", path, b.params(**params), retry="safe"))
58
+
59
+ def close(self) -> None:
60
+ if self._own:
61
+ self.client.close()
62
+
63
+
64
+ class Zeta:
65
+ """The Zeta API client (synchronous).
66
+
67
+ >>> zeta = Zeta(api_key="zk_...")
68
+ >>> acc = zeta.account(account_id)
69
+ >>> acc.place_order(symbol="EURUSD", side="buy", volume=0.01)
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ api_key: str,
75
+ *,
76
+ base_url: str = b.DEFAULT_BASE_URL,
77
+ max_retries: int = 3,
78
+ timeout: float = 60.0,
79
+ retry_base: float = 0.5,
80
+ retry_max: float = 8.0,
81
+ http_client: Optional[httpx.Client] = None,
82
+ transport: Optional[httpx.BaseTransport] = None,
83
+ ) -> None:
84
+ if not api_key:
85
+ raise ZetaError(0, "missing_api_key", "api_key is required")
86
+ self._http = _Http(api_key, base_url, max_retries, timeout, retry_base, retry_max, http_client, transport)
87
+ self.accounts = Accounts(self._http)
88
+
89
+ def account(self, account_id: str) -> "AccountHandle":
90
+ """A handle for one account's data, trading and stream. No request is made."""
91
+ return AccountHandle(self._http, account_id)
92
+
93
+ def usage(self, from_: Optional[Time] = None, to: Optional[Time] = None) -> Usage:
94
+ """Daily usage (UTC days, at most 92; default the last 30)."""
95
+ return cast(Usage, self._http.get("/v1/usage", **{"from": b.day(from_), "to": b.day(to)}))
96
+
97
+ def me(self) -> Dict[str, Any]:
98
+ return cast(Dict[str, Any], self._http.get("/v1/me"))
99
+
100
+ def brokers(self) -> List[Broker]:
101
+ return cast(List[Broker], self._http.get("/v1/brokers")["data"])
102
+
103
+ def ws(self, **kwargs: Any) -> Any:
104
+ """An asyncio WebSocket client (needs ``pip install zetaapi[ws]``); use it inside ``async with``."""
105
+ from ._ws import ZetaSocket
106
+
107
+ return ZetaSocket(self._http.api_key, self._http.base_url, **kwargs)
108
+
109
+ def close(self) -> None:
110
+ self._http.close()
111
+
112
+ def __enter__(self) -> "Zeta":
113
+ return self
114
+
115
+ def __exit__(self, *exc: Any) -> None:
116
+ self.close()
117
+
118
+
119
+ class Accounts:
120
+ def __init__(self, http: _Http) -> None:
121
+ self._http = http
122
+
123
+ def create(self, login: int, password: str, server: str, *, platform: Optional[str] = None, external_ref: Optional[str] = None) -> Account:
124
+ """Adds an account. Returns at once with status "provisioning": see wait_until_connected."""
125
+ body = {"login": login, "password": password, "server": server, **b.params(platform=platform, externalRef=external_ref)}
126
+ return cast(Account, self._http.request(RequestSpec("POST", "/v1/accounts", body=body, retry="never")))
127
+
128
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, external_ref: Optional[str] = None) -> AccountPage:
129
+ return cast(AccountPage, self._http.get("/v1/accounts", limit=limit, cursor=cursor, externalRef=external_ref))
130
+
131
+ def list_all(self, *, limit: Optional[int] = None, external_ref: Optional[str] = None) -> Iterator[Account]:
132
+ """Every account, following nextCursor."""
133
+ cursor: Optional[str] = None
134
+ while True:
135
+ page = self.list(limit=limit, cursor=cursor, external_ref=external_ref)
136
+ yield from page["data"]
137
+ cursor = page.get("nextCursor")
138
+ if not cursor:
139
+ return
140
+
141
+ def get(self, account_id: str) -> Account:
142
+ return cast(Account, self._http.get(f"/v1/accounts/{b.seg(account_id)}"))
143
+
144
+ def update_credentials(self, account_id: str, password: str, *, server: Optional[str] = None) -> Account:
145
+ body = {"password": password, **b.params(server=server)}
146
+ return cast(Account, self._http.request(RequestSpec("PATCH", f"/v1/accounts/{b.seg(account_id)}/credentials", body=body, retry="never")))
147
+
148
+ def delete(self, account_id: str) -> None:
149
+ """Removes the account (its terminal stops; open positions stay open at the broker)."""
150
+ self._http.request(RequestSpec("DELETE", f"/v1/accounts/{b.seg(account_id)}", retry="never"))
151
+
152
+ def wait_until_connected(self, account_id: str, *, timeout: float = 600.0, interval: float = 3.0,
153
+ on_status: Optional[Callable[[Account], None]] = None) -> Account:
154
+ """Polls until connected. Raises ZetaError auth_failed, account_stopped or timeout."""
155
+ deadline = time.monotonic() + timeout
156
+ while True:
157
+ a = self.get(account_id)
158
+ if on_status:
159
+ on_status(a)
160
+ if b.check_wait_status(a):
161
+ return a
162
+ left = deadline - time.monotonic()
163
+ if left <= 0:
164
+ raise ZetaError(0, "timeout", f"Account still \"{a.get('status')}\" after the timeout", {"account": dict(a)})
165
+ time.sleep(min(interval, left))
166
+
167
+
168
+ class _History:
169
+ def __init__(self, http: _Http, base: str) -> None:
170
+ self._http = http
171
+ self._base = base
172
+
173
+ def deals(self, *, from_: Optional[Time] = None, to: Optional[Time] = None, limit: Optional[int] = None) -> Deals:
174
+ return cast(Deals, self._http.get(f"{self._base}/history/deals", **{"from": b.iso(from_), "to": b.iso(to), "limit": limit}))
175
+
176
+
177
+ class AccountHandle:
178
+ """One account: data, trading and live stream. Create it with ``zeta.account(id)``."""
179
+
180
+ def __init__(self, http: _Http, account_id: str) -> None:
181
+ self._http = http
182
+ self.id = account_id
183
+ self._base = f"/v1/accounts/{b.seg(account_id)}"
184
+ self.history = _History(http, self._base)
185
+
186
+ def get(self) -> Account:
187
+ return cast(Account, self._http.get(self._base))
188
+
189
+ def wait_until_connected(self, **kwargs: Any) -> Account:
190
+ return Accounts(self._http).wait_until_connected(self.id, **kwargs)
191
+
192
+ def info(self) -> InfoSnapshot:
193
+ """``{"asOf", "stale", "data": {balance, equity, margin, ...}}``"""
194
+ return cast(InfoSnapshot, self._http.get(f"{self._base}/info"))
195
+
196
+ def positions(self) -> PositionsSnapshot:
197
+ return cast(PositionsSnapshot, self._http.get(f"{self._base}/positions"))
198
+
199
+ def orders(self) -> OrdersSnapshot:
200
+ """Pending orders."""
201
+ return cast(OrdersSnapshot, self._http.get(f"{self._base}/orders"))
202
+
203
+ def quotes(self, symbols: Union[str, Iterable[str]]) -> List[Quote]:
204
+ return cast(List[Quote], self._http.get(f"{self._base}/quotes", symbols=b.csv(symbols))["data"])
205
+
206
+ def candles(self, symbol: str, timeframe: Timeframe, *, limit: Optional[int] = None,
207
+ from_: Optional[Time] = None, to: Optional[Time] = None) -> Candles:
208
+ """Price history bars, oldest first, in ``["data"]``."""
209
+ return cast(Candles, self._http.get(
210
+ f"{self._base}/candles", symbol=symbol, timeframe=timeframe, limit=limit, **{"from": b.iso(from_), "to": b.iso(to)},
211
+ ))
212
+
213
+ def symbols(self, search: Optional[str] = None) -> List[SymbolSpec]:
214
+ return cast(List[SymbolSpec], self._http.get(f"{self._base}/symbols", search=search)["data"])
215
+
216
+ # ---- trading ----
217
+
218
+ def place_order(
219
+ self, symbol: str, side: str, volume: float, *, type: str = "market", price: Optional[float] = None,
220
+ sl: Optional[float] = None, tp: Optional[float] = None, deviation: Optional[int] = None,
221
+ expiration: Optional[Time] = None, comment: Optional[str] = None, client_ref: Optional[str] = None,
222
+ idempotency_key: Optional[str] = None,
223
+ ) -> Order:
224
+ """Places an order. An Idempotency-Key is generated unless given, and reused for every retry.
225
+ Rejections raise ZetaError (``err.order`` has the record). Status "sent" / "unknown" = outcome
226
+ not known yet: poll ``get_order(order["id"])``."""
227
+ body = b.place_body(symbol, side, volume, type, price, sl, tp, deviation, expiration, comment, client_ref)
228
+ return self._trade("POST", "/orders", body, idempotency_key)
229
+
230
+ def close_position(self, ticket: int, *, volume: Optional[float] = None, comment: Optional[str] = None,
231
+ idempotency_key: Optional[str] = None) -> Order:
232
+ return self._trade("POST", f"/positions/{b.ticket_str(ticket)}/close", b.close_body(volume, comment), idempotency_key)
233
+
234
+ def modify_position(self, ticket: int, *, sl: Optional[float] = UNSET, tp: Optional[float] = UNSET,
235
+ idempotency_key: Optional[str] = None) -> Order:
236
+ """Changes SL / TP: not given = keep, None = remove."""
237
+ return self._trade("PATCH", f"/positions/{b.ticket_str(ticket)}", b.modify_body(sl=sl, tp=tp), idempotency_key)
238
+
239
+ def modify_order(self, ticket: int, *, price: Optional[float] = UNSET, sl: Optional[float] = UNSET,
240
+ tp: Optional[float] = UNSET, expiration: Optional[Time] = UNSET, idempotency_key: Optional[str] = None) -> Order:
241
+ body = b.modify_body(price=price, sl=sl, tp=tp, expiration=expiration)
242
+ return self._trade("PATCH", f"/orders/{b.ticket_str(ticket)}", body, idempotency_key)
243
+
244
+ def cancel_order(self, ticket: int, *, idempotency_key: Optional[str] = None) -> Order:
245
+ return self._trade("DELETE", f"/orders/{b.ticket_str(ticket)}", None, idempotency_key)
246
+
247
+ def get_order(self, order_id: str) -> Order:
248
+ return cast(Order, self._http.get(f"{self._base}/orders/{b.seg(order_id)}"))
249
+
250
+ def wait_for_order(self, order_id: str, *, timeout: float = 120.0, interval: float = 2.0) -> Order:
251
+ """Polls get_order until the outcome is known (not pending / sent / unknown) or the timeout."""
252
+ deadline = time.monotonic() + timeout
253
+ while True:
254
+ o = self.get_order(order_id)
255
+ if o["status"] not in ("pending", "sent", "unknown") or time.monotonic() >= deadline:
256
+ return o
257
+ time.sleep(interval)
258
+
259
+ def _trade(self, method: str, path: str, body: Any, key: Optional[str]) -> Order:
260
+ spec = RequestSpec(method, self._base + path, body=body, idempotency_key=b.new_key(key), retry="idempotent")
261
+ return cast(Order, self._http.request(spec))
262
+
263
+ # ---- streaming ----
264
+
265
+ def stream(
266
+ self, symbols: Optional[Iterable[str]] = None, *, on_tick: Handler = None, on_account: Handler = None,
267
+ on_positions: Handler = None, on_orders: Handler = None, on_status: Handler = None, on_subscribed: Handler = None,
268
+ on_event: Optional[Callable[[Event], None]] = None, on_error: Optional[Callable[[ZetaError, bool], None]] = None,
269
+ max_reconnect_delay: float = 30.0, idle_timeout: float = 45.0,
270
+ ) -> "Stream":
271
+ """Live events over Server-Sent Events, reconnecting by itself.
272
+
273
+ Iterate it (``for ev in acc.stream(["EURUSD"]): ...``) and/or give callbacks and call ``run()``.
274
+ """
275
+ handlers = {"on_tick": on_tick, "on_account": on_account, "on_positions": on_positions, "on_orders": on_orders,
276
+ "on_status": on_status, "on_subscribed": on_subscribed, "on_event": on_event}
277
+ return Stream(self._http, f"{self._base}/stream", b.stream_params(symbols), handlers, on_error, max_reconnect_delay, idle_timeout)
278
+
279
+
280
+ class Stream:
281
+ """A reconnecting SSE stream. Iterate for ``Event``s, or ``run()`` to just dispatch callbacks.
282
+ ``close()`` (from any thread) ends it."""
283
+
284
+ def __init__(self, http: _Http, path: str, params: Dict[str, Any], handlers: Dict[str, Any],
285
+ on_error: Optional[Callable[[ZetaError, bool], None]], max_delay: float, idle_timeout: float) -> None:
286
+ self._http = http
287
+ self._path = path
288
+ self._params = params
289
+ self._handlers = handlers
290
+ self._on_error = on_error
291
+ self._max_delay = max_delay
292
+ self._idle = idle_timeout
293
+ self._closed = threading.Event()
294
+ self._resp: Optional[httpx.Response] = None
295
+ self._lock = threading.Lock()
296
+
297
+ def close(self) -> None:
298
+ self._closed.set()
299
+ with self._lock:
300
+ resp = self._resp
301
+ if resp is not None:
302
+ try:
303
+ resp.close()
304
+ except Exception: # pragma: no cover
305
+ pass
306
+
307
+ @property
308
+ def closed(self) -> bool:
309
+ return self._closed.is_set()
310
+
311
+ def __enter__(self) -> "Stream":
312
+ return self
313
+
314
+ def __exit__(self, *exc: Any) -> None:
315
+ self.close()
316
+
317
+ def run(self) -> None:
318
+ """Dispatches callbacks until close() or a fatal error."""
319
+ for _ in self:
320
+ pass
321
+
322
+ def _report(self, err: ZetaError, will_retry: bool) -> None:
323
+ if self._on_error and not (self.closed and will_retry):
324
+ try:
325
+ self._on_error(err, will_retry)
326
+ except Exception:
327
+ pass
328
+
329
+ def __iter__(self) -> Iterator[Event]:
330
+ attempt = 0
331
+ retry_s = 1.0
332
+ while not self.closed:
333
+ pending: List[SseMessage] = []
334
+ parser = SseParser(pending.append)
335
+ try:
336
+ with self._http.client.stream(
337
+ "GET", self._http.base_url + self._path, params=self._params or None,
338
+ headers={**b.headers(self._http.api_key, accept="text/event-stream"), "Cache-Control": "no-cache"},
339
+ timeout=httpx.Timeout(self._http.timeout, read=self._idle),
340
+ ) as resp:
341
+ with self._lock:
342
+ self._resp = resp
343
+ if resp.status_code != 200:
344
+ resp.read()
345
+ try:
346
+ body = resp.json()
347
+ except ValueError:
348
+ body = None
349
+ err = error_from_response(resp.status_code, body, resp.headers.get("x-request-id"))
350
+ if resp.status_code in b.FATAL_STREAM_STATUS:
351
+ self._report(err, False)
352
+ break
353
+ raise err
354
+ got = False
355
+ for chunk in resp.iter_text():
356
+ parser.push(chunk)
357
+ if parser.retry_ms is not None:
358
+ retry_s = parser.retry_ms / 1000
359
+ while pending:
360
+ m = pending.pop(0)
361
+ if not got:
362
+ got, attempt = True, 0
363
+ ev = self._event(m)
364
+ if ev is not None and not self.closed:
365
+ yield ev
366
+ if self.closed:
367
+ break
368
+ if not self.closed:
369
+ self._report(ZetaError(0, "connection_lost", "The stream ended"), True)
370
+ except ZetaError as err:
371
+ self._report(err, True)
372
+ except (httpx.TransportError, httpx.StreamError) as e:
373
+ if self.closed:
374
+ break
375
+ self._report(b.transport_error(e), True)
376
+ finally:
377
+ with self._lock:
378
+ self._resp = None
379
+ if self.closed:
380
+ break
381
+ self._closed.wait(b.backoff(attempt, max(retry_s, 0.05), self._max_delay))
382
+ attempt += 1
383
+
384
+ def _event(self, m: SseMessage) -> Optional[Event]:
385
+ import json
386
+
387
+ try:
388
+ data = json.loads(m.data)
389
+ except ValueError:
390
+ self._report(ZetaError(0, "invalid_event", f'Event "{m.event}" is not JSON'), True)
391
+ return None
392
+ ev = Event(m.event, data)
393
+ try:
394
+ b.dispatch(self._handlers, ev)
395
+ except Exception as e: # a throwing callback must not kill the stream
396
+ err = ZetaError(0, "handler_error", str(e))
397
+ err.__cause__ = e
398
+ self._report(err, True)
399
+ return ev
400
+
401
+
402
+ __all__ = ["Zeta", "Accounts", "AccountHandle", "Stream", "AccountInfo"]
zeta/_errors.py ADDED
@@ -0,0 +1,78 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Mapping, Optional
4
+
5
+ _CODE_BY_STATUS = {
6
+ 400: "bad_request", 401: "unauthorized", 403: "forbidden", 404: "not_found", 409: "conflict",
7
+ 422: "rejected", 429: "rate_limited", 502: "bad_gateway", 503: "unavailable", 504: "timeout",
8
+ }
9
+
10
+
11
+ class ZetaError(Exception):
12
+ """Every failure the SDK reports. Branch on ``code``, never on ``message``.
13
+
14
+ ``status`` is the HTTP status, or 0 when no answer arrived (``network_error``,
15
+ ``timeout``, ``connection_lost``, ``closed``).
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ status: int,
21
+ code: str,
22
+ message: str,
23
+ details: Optional[Mapping[str, Any]] = None,
24
+ request_id: Optional[str] = None,
25
+ ) -> None:
26
+ super().__init__(message)
27
+ self.status = status
28
+ self.code = code
29
+ self.message = message
30
+ self.details: Optional[Dict[str, Any]] = dict(details) if details is not None else None
31
+ self.request_id = request_id
32
+
33
+ @property
34
+ def order(self) -> Optional[Dict[str, Any]]:
35
+ """For a rejected trade: Zeta's record of it (``error.details.order``)."""
36
+ o = (self.details or {}).get("order")
37
+ return o if isinstance(o, dict) else None
38
+
39
+ @property
40
+ def idempotency_key(self) -> Optional[str]:
41
+ """The Idempotency-Key the SDK used for a trading call (retry yourself with the same one)."""
42
+ k = (self.details or {}).get("idempotencyKey")
43
+ return k if isinstance(k, str) else None
44
+
45
+ @property
46
+ def retryable(self) -> bool:
47
+ return self.status == 0 or self.status == 429 or self.status >= 500
48
+
49
+ def with_key(self, key: Optional[str]) -> "ZetaError":
50
+ if not key or self.idempotency_key:
51
+ return self
52
+ err = ZetaError(self.status, self.code, self.message, {**(self.details or {}), "idempotencyKey": key}, self.request_id)
53
+ err.__cause__ = self.__cause__
54
+ return err
55
+
56
+ def __repr__(self) -> str:
57
+ return f"ZetaError(status={self.status}, code={self.code!r}, message={self.message!r}, request_id={self.request_id!r})"
58
+
59
+ def __str__(self) -> str:
60
+ return f"{self.code}: {self.message}" + (f" (status {self.status})" if self.status else "")
61
+
62
+
63
+ def error_from_response(status: int, body: Any, header_request_id: Optional[str] = None) -> ZetaError:
64
+ e = body.get("error") if isinstance(body, dict) else None
65
+ fallback = _CODE_BY_STATUS.get(status, "server_error" if status >= 500 else "http_error")
66
+ if isinstance(e, dict):
67
+ code = e.get("code")
68
+ msg = e.get("message")
69
+ rid = e.get("requestId")
70
+ details = e.get("details")
71
+ return ZetaError(
72
+ status,
73
+ code if isinstance(code, str) else fallback,
74
+ msg if isinstance(msg, str) else f"HTTP {status}",
75
+ details if isinstance(details, dict) else None,
76
+ rid if isinstance(rid, str) else header_request_id,
77
+ )
78
+ return ZetaError(status, fallback, f"HTTP {status}", None, header_request_id)
zeta/_sse.py ADDED
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable, List, Optional
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class SseMessage:
9
+ event: str
10
+ data: str
11
+ id: Optional[str] = None
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Event:
16
+ """A live event: ``type`` is status, account, positions, orders, tick or subscribed.
17
+
18
+ ``data`` is the parsed JSON. ``account_id`` is set on WebSocket events.
19
+ """
20
+
21
+ type: str
22
+ data: Any
23
+ account_id: Optional[str] = None
24
+
25
+
26
+ class SseParser:
27
+ """Incremental Server-Sent Events parser (WHATWG rules): \\n, \\r\\n and \\r line ends,
28
+ multi-line ``data:``, comments (``: keepalive``), ``retry:`` and frames split across chunks."""
29
+
30
+ def __init__(self, on_message: Callable[[SseMessage], None], on_comment: Optional[Callable[[str], None]] = None) -> None:
31
+ self._on_message = on_message
32
+ self._on_comment = on_comment
33
+ self._buf = ""
34
+ self._event = ""
35
+ self._data: List[str] = []
36
+ self._id: Optional[str] = None
37
+ self.retry_ms: Optional[int] = None
38
+ self.last_event_id: Optional[str] = None
39
+
40
+ def push(self, chunk: str) -> None:
41
+ self._buf += chunk
42
+ buf = self._buf
43
+ start = 0
44
+ n = len(buf)
45
+ while True:
46
+ i = start
47
+ while i < n and buf[i] != "\n" and buf[i] != "\r":
48
+ i += 1
49
+ if i >= n:
50
+ break
51
+ if buf[i] == "\r" and i == n - 1:
52
+ break # may be the first half of \r\n
53
+ line = buf[start:i]
54
+ start = i + 2 if buf[i] == "\r" and buf[i + 1] == "\n" else i + 1
55
+ self._line(line)
56
+ self._buf = buf[start:]
57
+
58
+ def _line(self, line: str) -> None:
59
+ if line == "":
60
+ self._dispatch()
61
+ return
62
+ if line.startswith(":"):
63
+ if self._on_comment:
64
+ self._on_comment(line[1:].lstrip())
65
+ return
66
+ field, sep, value = line.partition(":")
67
+ if sep and value.startswith(" "):
68
+ value = value[1:]
69
+ if field == "event":
70
+ self._event = value
71
+ elif field == "data":
72
+ self._data.append(value)
73
+ elif field == "id":
74
+ if "\0" not in value:
75
+ self._id = value
76
+ elif field == "retry":
77
+ if value.isdigit():
78
+ self.retry_ms = int(value)
79
+
80
+ def _dispatch(self) -> None:
81
+ if self._id is not None:
82
+ self.last_event_id = self._id
83
+ if self._data:
84
+ self._on_message(SseMessage(self._event or "message", "\n".join(self._data), self._id))
85
+ self._event = ""
86
+ self._data = []