-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcli_client.py
More file actions
79 lines (66 loc) · 2.9 KB
/
Copy pathcli_client.py
File metadata and controls
79 lines (66 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import base64
import json
import logging
from typing import Dict, List, Optional, Union
import requests
from socketsecurity import USER_AGENT
from .exceptions import APIFailure
from .socket_config import SocketConfig
logger = logging.getLogger("socketdev")
class CliClient:
def __init__(self, config: SocketConfig):
self.config = config
self._encoded_key = self._encode_key(config.api_key)
@staticmethod
def _encode_key(token: str) -> str:
return base64.b64encode(f"{token}:".encode()).decode('ascii')
def request(
self,
path: str,
method: str = "GET",
headers: Optional[Dict] = None,
payload: Optional[Union[Dict, str]] = None,
files: Optional[List] = None,
base_url: Optional[str] = None
) -> requests.Response:
url = f"{base_url or self.config.api_url}/{path}"
default_headers = {
'Authorization': f"Basic {self._encoded_key}",
'User-Agent': USER_AGENT,
"accept": "application/json"
}
headers = headers or default_headers
try:
response = requests.request(
method=method.upper(),
url=url,
headers=headers,
data=payload,
files=files,
timeout=self.config.timeout,
verify=not self.config.allow_unverified_ssl
)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
logger.error(f"API request failed: {str(e)}")
# Carry the status forward. Callers that need to react to a specific
# code -- the GitLab auth fallback to the other token scheme, and
# APIFailure.is_transient_error -- have no other way to recover it
# once the requests exception has been translated.
status_code = e.response.status_code if e.response is not None else None
raise APIFailure(f"Request failed: {str(e)}", status_code=status_code) from e
def post_telemetry_events(self, org_slug: str, events: List[Dict]) -> None:
"""Post telemetry events one at a time to the v0 telemetry API. Fire-and-forget — logs errors but never raises."""
logger.debug(f"Sending {len(events)} telemetry event(s) to v0/orgs/{org_slug}/telemetry")
for i, event in enumerate(events):
try:
logger.debug(f"Telemetry event {i+1}/{len(events)}: {json.dumps(event)}")
resp = self.request(
path=f"orgs/{org_slug}/telemetry",
method="POST",
payload=json.dumps(event),
)
logger.debug(f"Telemetry event {i+1}/{len(events)} sent: status={resp.status_code}")
except Exception as e:
logger.warning(f"Failed to send telemetry event {i+1}/{len(events)}: {e}")