@redocly/client-generator 0.9.3 → 0.10.1
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.
- package/eject-assets/generators/cli/docs.ts +1 -1
- package/eject-assets/generators/cli/engine-source.ts +1 -1
- package/eject-assets/generators/cli/index.ts +2 -2
- package/eject-assets/generators/cli/render.ts +1 -1
- package/eject-assets/generators/go/client.ts +1 -1
- package/eject-assets/generators/go/descriptor.ts +1 -1
- package/eject-assets/generators/go/index.ts +2 -2
- package/eject-assets/generators/go/models.ts +1 -1
- package/eject-assets/generators/go/naming.ts +1 -1
- package/eject-assets/generators/go/operations.ts +1 -1
- package/eject-assets/generators/go/pagination.ts +1 -1
- package/eject-assets/generators/go/types.ts +1 -1
- package/eject-assets/generators/java/client.ts +1 -1
- package/eject-assets/generators/java/descriptor.ts +1 -1
- package/eject-assets/generators/java/index.ts +2 -2
- package/eject-assets/generators/java/models.ts +1 -1
- package/eject-assets/generators/java/naming.ts +1 -1
- package/eject-assets/generators/java/operations.ts +1 -1
- package/eject-assets/generators/java/pagination.ts +1 -1
- package/eject-assets/generators/java/types.ts +1 -1
- package/eject-assets/generators/mock/faker.ts +1 -1
- package/eject-assets/generators/mock/index.ts +2 -2
- package/eject-assets/generators/mock/render.ts +1 -1
- package/eject-assets/generators/mock/sample.ts +1 -1
- package/eject-assets/generators/mock/values.ts +1 -1
- package/eject-assets/generators/php/client.ts +1 -1
- package/eject-assets/generators/php/descriptor.ts +1 -1
- package/eject-assets/generators/php/index.ts +2 -2
- package/eject-assets/generators/php/models.ts +1 -1
- package/eject-assets/generators/php/naming.ts +1 -1
- package/eject-assets/generators/php/operations.ts +1 -1
- package/eject-assets/generators/php/pagination.ts +1 -1
- package/eject-assets/generators/php/types.ts +1 -1
- package/eject-assets/generators/python/client.ts +1 -1
- package/eject-assets/generators/python/descriptor.ts +1 -1
- package/eject-assets/generators/python/index.ts +2 -2
- package/eject-assets/generators/python/models.ts +1 -1
- package/eject-assets/generators/python/naming.ts +1 -1
- package/eject-assets/generators/python/operations.ts +1 -1
- package/eject-assets/generators/python/pagination.ts +1 -1
- package/eject-assets/generators/python/types.ts +1 -1
- package/eject-assets/generators/swr/index.ts +2 -2
- package/eject-assets/generators/swr/render.ts +1 -1
- package/eject-assets/generators/tanstack-query/index.ts +2 -2
- package/eject-assets/generators/tanstack-query/render.ts +1 -1
- package/eject-assets/generators/transformers/index.ts +2 -2
- package/eject-assets/generators/transformers/render.ts +1 -1
- package/eject-assets/generators/typescript/banner.ts +1 -1
- package/eject-assets/generators/typescript/client.ts +1 -1
- package/eject-assets/generators/typescript/descriptor.ts +1 -1
- package/eject-assets/generators/typescript/index.ts +2 -2
- package/eject-assets/generators/typescript/inline-runtime.ts +1 -1
- package/eject-assets/generators/typescript/operation-signature.ts +1 -1
- package/eject-assets/generators/typescript/operation-types.ts +1 -1
- package/eject-assets/generators/typescript/operations.ts +1 -1
- package/eject-assets/generators/typescript/response-headers.ts +1 -1
- package/eject-assets/generators/typescript/type-guards.ts +1 -1
- package/eject-assets/generators/typescript/types.ts +1 -1
- package/eject-assets/generators/zod/index.ts +2 -2
- package/eject-assets/generators/zod/schemas.ts +1 -1
- package/eject-assets/skills/typescript-generator/SKILL.md +2 -1
- package/lib/generators/typescript/telemetry/telemetry.d.ts +4 -12
- package/lib/generators/typescript/telemetry/telemetry.d.ts.map +1 -1
- package/lib/generators/typescript/telemetry/telemetry.js +53 -21
- package/lib/generators/typescript/telemetry/telemetry.js.map +1 -1
- package/lib/runtime-sources/go-telemetry.d.ts +1 -1
- package/lib/runtime-sources/go-telemetry.d.ts.map +1 -1
- package/lib/runtime-sources/go-telemetry.js +1 -1
- package/lib/runtime-sources/go-telemetry.js.map +1 -1
- package/lib/runtime-sources/php-telemetry.d.ts +1 -1
- package/lib/runtime-sources/php-telemetry.d.ts.map +1 -1
- package/lib/runtime-sources/php-telemetry.js +1 -1
- package/lib/runtime-sources/php-telemetry.js.map +1 -1
- package/lib/runtime-sources/python-telemetry.d.ts +1 -1
- package/lib/runtime-sources/python-telemetry.d.ts.map +1 -1
- package/lib/runtime-sources/python-telemetry.js +1 -1
- package/lib/runtime-sources/python-telemetry.js.map +1 -1
- package/lib/runtime-sources/telemetry.d.ts +1 -1
- package/lib/runtime-sources/telemetry.d.ts.map +1 -1
- package/lib/runtime-sources/telemetry.js +1 -1
- package/lib/runtime-sources/telemetry.js.map +1 -1
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"python-telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/python-telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,uBAAuB,
|
|
1
|
+
{"version":3,"file":"python-telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/python-telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,uBAAuB,82aACu9Z,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// GENERATED by scripts/generate-runtime-sources.mjs — do not edit. Regenerated on install (`prepare`); manually: `npm run prepare -w @redocly/client-generator`.
|
|
2
|
-
export const PYTHON_TELEMETRY_SOURCE = '# Usage telemetry for a generated Python SDK, written beside the client by\n# `client.telemetry: on`. It counts calls per operation through the runtime\'s\n# on_settled hook and sends one event per operation and window. An event holds\n# only the operation id, the counts, the window, and the SDK identity.\nfrom __future__ import annotations\n\nimport asyncio\nimport atexit\nimport json\nimport math\nimport os\nimport platform\nimport secrets\nimport threading\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Any, Callable, Dict, List, Optional, Set\n\nimport httpx\n\nGENERATOR_VERSION = "dev"\n_DEFAULT_ENDPOINT = "https://otel.cloud.redocly.com/v1/traces"\n_EVENT_TYPE = "com.redocly.sdkUsage.aggregated"\n_SEND_TIMEOUT_S = 3.0\n_SERVICE_NAME = "redocly-sdk"\n_STATUS_CLASSES = ["2xx", "3xx", "4xx", "5xx", "network_error", "timeout", "aborted"]\n_LATENCY_BUCKETS = [\n ("lt_100ms", 100),\n ("lt_300ms", 300),\n ("lt_1s", 1000),\n ("lt_3s", 3000),\n ("lt_10s", 10000),\n ("gte_10s", math.inf),\n]\n\nSdkUsageEvent = Dict[str, Any]\nSink = Callable[[List[SdkUsageEvent]], None]\n\n\nclass _RejectedSend(Exception):\n def __init__(self, status: int) -> None:\n super().__init__(f"The telemetry endpoint answered {status}.")\n self.status = status\n\n\ndef _disabled() -> bool:\n return os.environ.get("REDOCLY_SDK_TELEMETRY") == "off" or os.environ.get("DO_NOT_TRACK") == "1"\n\n\ndef _empty_counts() -> Dict[str, Any]:\n return {"calls": 0, "attempts": 0, "duration_sum_ms": 0, "status": {}, "latency": {}}\n\n\nclass UsageTelemetry:\n """The middleware that `telemetry()` returns. Safe to share across threads and clients."""\n\n def __init__(self, sdk: Dict[str, str], sink: Sink, flush_interval_ms: int, enabled: bool) -> None:\n self._enabled = enabled\n self._sdk = sdk\n self._sink = sink\n self._interval_s = flush_interval_ms / 1000\n self._lock = threading.Lock()\n self._counts: Dict[str, Dict[str, Any]] = {}\n self._window_start = 0.0\n self._timer: Optional[threading.Timer] = None\n\n def on_settled(self, context: Dict[str, Any], call: Dict[str, Any]) -> None:\n if not self._enabled:\n return\n with self._lock:\n if not self._counts:\n self._open_window()\n operation = self._counts.setdefault(context["operation"]["id"], _empty_counts())\n duration_ms: int = call["duration_ms"]\n operation["calls"] += 1\n operation["attempts"] += call["attempts"]\n operation["duration_sum_ms"] += duration_ms\n status = _status_class(call)\n operation["status"][status] = operation["status"].get(status, 0) + 1\n for bucket, below_ms in _LATENCY_BUCKETS:\n if duration_ms < below_ms:\n operation["latency"][bucket] = operation["latency"].get(bucket, 0) + 1\n break\n\n def flush(self, keep_on_failure: bool = True) -> None:\n timer = self._timer\n self._flush_window(keep_on_failure)\n # A timer that already fired may still be sending its window.\n if timer is not None:\n timer.join(_SEND_TIMEOUT_S + 1)\n\n def _open_window(self) -> None:\n self._window_start = time.time()\n self._timer = threading.Timer(self._interval_s, self._flush_window)\n self._timer.daemon = True\n self._timer.start()\n with _open_windows_lock:\n _open_windows.add(self)\n\n def _flush_window(self, keep_on_failure: bool = True) -> None:\n with self._lock:\n if not self._counts:\n return\n if self._timer is not None:\n self._timer.cancel()\n sent_counts = self._counts\n sent_start = self._window_start\n self._counts = {}\n try:\n if not _disabled():\n self._sink(_to_events(sent_counts, sent_start, time.time() - sent_start, self._sdk))\n except Exception as error:\n if keep_on_failure and _keep_after(error):\n with self._lock:\n if not self._counts:\n self._open_window()\n self._window_start = min(self._window_start, sent_start)\n for operation_id, sent in sent_counts.items():\n operation = self._counts.setdefault(operation_id, _empty_counts())\n for key in ("calls", "attempts", "duration_sum_ms"):\n operation[key] += sent[key]\n for group in ("status", "latency"):\n for key, count in sent[group].items():\n operation[group][key] = operation[group].get(key, 0) + count\n with self._lock:\n # A call during the send can open the next window.\n if not self._counts:\n with _open_windows_lock:\n _open_windows.discard(self)\n\n\n# The instances with an open window or a send in progress.\n_open_windows: Set[UsageTelemetry] = set()\n_open_windows_lock = threading.Lock()\n\n\ndef _open_windows_now() -> List[UsageTelemetry]:\n with _open_windows_lock:\n return list(_open_windows)\n\n\ndef telemetry(\n *,\n sdk_name: str,\n sdk_version: str,\n client: str,\n sink: Optional[Sink] = None,\n endpoint: Optional[str] = None,\n flush_interval_ms: int = 60_000,\n) -> UsageTelemetry:\n """The usage telemetry middleware. REDOCLY_SDK_TELEMETRY=off or DO_NOT_TRACK=1 makes it record nothing."""\n target = endpoint or _DEFAULT_ENDPOINT\n sdk = {\n "name": sdk_name,\n "version": sdk_version,\n "generator_version": GENERATOR_VERSION,\n "language": "python",\n "runtime": platform.python_implementation().lower(),\n "runtime_version": platform.python_version(),\n "client": client,\n }\n enabled = not _disabled()\n return UsageTelemetry(sdk, sink or (lambda events: _send_otlp(target, events)), flush_interval_ms, enabled)\n\n\ndef flush() -> None:\n """Send every open window now and wait for the sends, for example before os._exit()."""\n for instance in _open_windows_now():\n instance.flush()\n\n\n@atexit.register\ndef _flush_at_exit() -> None:\n # There is no later window at exit, so a failed send drops its counts.\n for instance in _open_windows_now():\n instance.flush(keep_on_failure=False)\n\n\ndef _status_class(call: Dict[str, Any]) -> str:\n response: Optional[httpx.Response] = call.get("response")\n if response is None:\n error = call.get("error")\n # The runtime\'s own timeout error, matched by name: this module imports nothing from the client.\n if type(error).__name__ == "ApiTimeoutError":\n return "timeout"\n if isinstance(error, asyncio.CancelledError):\n return "aborted"\n return "network_error"\n if response.status_code >= 500:\n return "5xx"\n if response.status_code >= 400:\n return "4xx"\n if response.status_code >= 300:\n return "3xx"\n return "2xx"\n\n\ndef _keep_after(error: Exception) -> bool:\n # The endpoint can have stored the counts of a send that timed out.\n if isinstance(error, httpx.TimeoutException):\n return False\n if isinstance(error, _RejectedSend):\n return error.status in (408, 429) or error.status >= 500\n return True\n\n\ndef _to_events(\n counts: Dict[str, Dict[str, Any]], window_start: float, window_s: float, sdk: Dict[str, str]\n) -> List[SdkUsageEvent]:\n started = datetime.fromtimestamp(window_start, tz=timezone.utc)\n events: List[SdkUsageEvent] = []\n for operation_id, operation in counts.items():\n usage: Dict[str, Any] = {\n "operation_id": operation_id,\n "window_ms": int(window_s * 1000),\n "calls": operation["calls"],\n "attempts": operation["attempts"],\n "duration_sum_ms": operation["duration_sum_ms"],\n }\n for status in _STATUS_CLASSES:\n if status in operation["status"]:\n usage[f"status_{status}"] = operation["status"][status]\n for bucket, _ in _LATENCY_BUCKETS:\n if bucket in operation["latency"]:\n usage[f"latency_{bucket}"] = operation["latency"][bucket]\n events.append(\n {\n "id": f"evt_{secrets.token_hex(16)}",\n "type": _EVENT_TYPE,\n "source": sdk["name"],\n "time": started.isoformat(timespec="milliseconds").replace("+00:00", "Z"),\n "data": {"usage": usage, "sdk": sdk},\n }\n )\n return events\n\n\ndef _send_otlp(endpoint: str, events: List[SdkUsageEvent]) -> None:\n response = httpx.post(\n endpoint,\n content=json.dumps(_to_otlp_request(events)),\n # One send per window, so the connection is never reused.\n headers={"Content-Type": "application/json", "Connection": "close"},\n timeout=_SEND_TIMEOUT_S,\n )\n if not response.is_success:\n raise _RejectedSend(response.status_code)\n\n\ndef _to_otlp_request(events: List[SdkUsageEvent]) -> Dict[str, Any]:\n spans: List[Dict[str, Any]] = []\n for event in events:\n started = datetime.fromisoformat(event["time"].replace("Z", "+00:00"))\n time_unix_nano = f"{int(started.timestamp() * 1000)}000000"\n attributes = [\n _attribute("cloudevents.event_id", event["id"]),\n _attribute("cloudevents.event_type", event["type"]),\n _attribute("cloudevents.event_source", event["source"]),\n _attribute("cloudevents.event_spec_version", "1.0"),\n _attribute("cloudevents.event_data_content_type", "application/json; charset=utf-8"),\n _attribute("cloudevents.event_time", event["time"]),\n _attribute("cloudevents.event_subject", ""),\n _attribute("cloudevents.event_origin", _SERVICE_NAME),\n _attribute("cloudevents.event_object", "event"),\n _attribute("cloudevents.event_category", "product"),\n _attribute("cloudevents.event_signal", "metric"),\n ]\n for key, value in event["data"]["usage"].items():\n attributes.append(_attribute(f"cloudevents.event_data.usage.{key}", value))\n for key, value in event["data"]["sdk"].items():\n attributes.append(_attribute(f"cloudevents.event_data.sdk.{key}", value))\n spans.append(\n {\n "traceId": secrets.token_hex(16),\n "spanId": secrets.token_hex(8),\n "name": f"event.{event[\'type\']}",\n "kind": 1,\n "startTimeUnixNano": time_unix_nano,\n "endTimeUnixNano": time_unix_nano,\n "attributes": attributes,\n }\n )\n return {\n "resourceSpans": [\n {\n "resource": {\n "attributes": [\n _attribute("service.name", _SERVICE_NAME),\n _attribute("service.version", GENERATOR_VERSION),\n ]\n },\n "scopeSpans": [{"scope": {"name": "redocly-sdk-telemetry"}, "spans": spans}],\n }\n ]\n }\n\n\ndef _attribute(key: str, value: Any) -> Dict[str, Any]:\n if isinstance(value, str):\n return {"key": key, "value": {"stringValue": value}}\n if isinstance(value, int):\n return {"key": key, "value": {"intValue": value}}\n return {"key": key, "value": {"doubleValue": value}}\n';
|
|
2
|
+
export const PYTHON_TELEMETRY_SOURCE = '# Usage telemetry for a generated Python SDK, written beside the client by\n# `client.telemetry: on`. It counts calls per operation through the runtime\'s\n# on_settled hook and sends one event per operation and window. An event holds\n# only the operation id, the counts, the window, and the SDK identity.\nfrom __future__ import annotations\n\nimport asyncio\nimport atexit\nimport json\nimport math\nimport os\nimport platform\nimport secrets\nimport threading\nimport time\nfrom datetime import datetime, timezone\nfrom typing import Any, Callable, Dict, List, Optional, Set\n\nimport httpx\n\nGENERATOR_VERSION = "dev"\n_DEFAULT_ENDPOINT = "https://otel.cloud.redocly.com/v1/traces"\n_EVENT_TYPE = "com.redocly.sdkUsage.aggregated"\n_SEND_TIMEOUT_S = 3.0\n_SERVICE_NAME = "redocly-sdk"\n_SDK_URN_PREFIX = "urn:redocly:cli:sdk:python:"\n_CROCKFORD_BASE32 = "0123456789abcdefghjkmnpqrstvwxyz"\n_STATUS_CLASSES = ["2xx", "3xx", "4xx", "5xx", "network_error", "timeout", "aborted"]\n_LATENCY_BUCKETS = [\n ("lt_100ms", 100),\n ("lt_300ms", 300),\n ("lt_1s", 1000),\n ("lt_3s", 3000),\n ("lt_10s", 10000),\n ("gte_10s", math.inf),\n]\n\n# A com.redocly.sdkUsage.aggregated CloudEvent. Its "data" holds the operation, then the SDK.\n# The OpenTelemetry collector sets the "env" of the event.\nSdkUsageEvent = Dict[str, Any]\nSink = Callable[[List[SdkUsageEvent]], None]\n\n\nclass _RejectedSend(Exception):\n def __init__(self, status: int) -> None:\n super().__init__(f"The telemetry endpoint answered {status}.")\n self.status = status\n\n\ndef _disabled() -> bool:\n return os.environ.get("REDOCLY_SDK_TELEMETRY") == "off" or os.environ.get("DO_NOT_TRACK") == "1"\n\n\ndef _empty_counts() -> Dict[str, Any]:\n return {"calls": 0, "attempts": 0, "duration_sum_ms": 0, "status": {}, "latency": {}}\n\n\nclass UsageTelemetry:\n """The middleware that `telemetry()` returns. Safe to share across threads and clients."""\n\n def __init__(self, sdk: Dict[str, Any], sink: Sink, flush_interval_ms: int, enabled: bool) -> None:\n self._enabled = enabled\n self._sdk = sdk\n self._sink = sink\n self._interval_s = flush_interval_ms / 1000\n self._lock = threading.Lock()\n self._counts: Dict[str, Dict[str, Any]] = {}\n self._window_start = 0.0\n self._timer: Optional[threading.Timer] = None\n\n def on_settled(self, context: Dict[str, Any], call: Dict[str, Any]) -> None:\n if not self._enabled:\n return\n with self._lock:\n if not self._counts:\n self._open_window()\n operation = self._counts.setdefault(context["operation"]["id"], _empty_counts())\n duration_ms: int = call["duration_ms"]\n operation["calls"] += 1\n operation["attempts"] += call["attempts"]\n operation["duration_sum_ms"] += duration_ms\n status = _status_class(call)\n operation["status"][status] = operation["status"].get(status, 0) + 1\n for bucket, below_ms in _LATENCY_BUCKETS:\n if duration_ms < below_ms:\n operation["latency"][bucket] = operation["latency"].get(bucket, 0) + 1\n break\n\n def flush(self, keep_on_failure: bool = True) -> None:\n timer = self._timer\n self._flush_window(keep_on_failure)\n # A timer that already fired may still be sending its window.\n if timer is not None:\n timer.join(_SEND_TIMEOUT_S + 1)\n\n def _open_window(self) -> None:\n self._window_start = time.time()\n self._timer = threading.Timer(self._interval_s, self._flush_window)\n self._timer.daemon = True\n self._timer.start()\n with _open_windows_lock:\n _open_windows.add(self)\n\n def _flush_window(self, keep_on_failure: bool = True) -> None:\n with self._lock:\n if not self._counts:\n return\n if self._timer is not None:\n self._timer.cancel()\n sent_counts = self._counts\n sent_start = self._window_start\n self._counts = {}\n try:\n if not _disabled():\n self._sink(_to_events(sent_counts, sent_start, time.time() - sent_start, self._sdk))\n except Exception as error:\n if keep_on_failure and _keep_after(error):\n with self._lock:\n if not self._counts:\n self._open_window()\n self._window_start = min(self._window_start, sent_start)\n for operation_id, sent in sent_counts.items():\n operation = self._counts.setdefault(operation_id, _empty_counts())\n for key in ("calls", "attempts", "duration_sum_ms"):\n operation[key] += sent[key]\n for group in ("status", "latency"):\n for key, count in sent[group].items():\n operation[group][key] = operation[group].get(key, 0) + count\n with self._lock:\n # A call during the send can open the next window.\n if not self._counts:\n with _open_windows_lock:\n _open_windows.discard(self)\n\n\n# The instances with an open window or a send in progress.\n_open_windows: Set[UsageTelemetry] = set()\n_open_windows_lock = threading.Lock()\n\n\ndef _open_windows_now() -> List[UsageTelemetry]:\n with _open_windows_lock:\n return list(_open_windows)\n\n\ndef telemetry(\n *,\n sdk_name: str,\n sdk_version: str,\n client: str,\n sink: Optional[Sink] = None,\n endpoint: Optional[str] = None,\n flush_interval_ms: int = 60_000,\n) -> UsageTelemetry:\n """The usage telemetry middleware. REDOCLY_SDK_TELEMETRY=off or DO_NOT_TRACK=1 makes it record nothing."""\n target = endpoint or _DEFAULT_ENDPOINT\n sdk: Dict[str, Any] = {\n "id": sdk_name,\n "object": "sdk",\n "uri": f"{_SDK_URN_PREFIX}{sdk_name}",\n "version": sdk_version,\n "generator_version": GENERATOR_VERSION,\n "language": "python",\n "runtime": platform.python_implementation().lower(),\n "runtime_version": platform.python_version(),\n "client": client,\n }\n enabled = not _disabled()\n return UsageTelemetry(sdk, sink or (lambda events: _send_otlp(target, events)), flush_interval_ms, enabled)\n\n\ndef flush() -> None:\n """Send every open window now and wait for the sends, for example before os._exit()."""\n for instance in _open_windows_now():\n instance.flush()\n\n\n@atexit.register\ndef _flush_at_exit() -> None:\n # There is no later window at exit, so a failed send drops its counts.\n for instance in _open_windows_now():\n instance.flush(keep_on_failure=False)\n\n\ndef _status_class(call: Dict[str, Any]) -> str:\n response: Optional[httpx.Response] = call.get("response")\n if response is None:\n error = call.get("error")\n # The runtime\'s own timeout error, matched by name: this module imports nothing from the client.\n if type(error).__name__ == "ApiTimeoutError":\n return "timeout"\n if isinstance(error, asyncio.CancelledError):\n return "aborted"\n return "network_error"\n if response.status_code >= 500:\n return "5xx"\n if response.status_code >= 400:\n return "4xx"\n if response.status_code >= 300:\n return "3xx"\n return "2xx"\n\n\ndef _keep_after(error: Exception) -> bool:\n # The endpoint can have stored the counts of a send that timed out.\n if isinstance(error, httpx.TimeoutException):\n return False\n if isinstance(error, _RejectedSend):\n return error.status in (408, 429) or error.status >= 500\n return True\n\n\ndef _to_events(\n counts: Dict[str, Dict[str, Any]], window_start: float, window_s: float, sdk: Dict[str, Any]\n) -> List[SdkUsageEvent]:\n started = datetime.fromtimestamp(window_start, tz=timezone.utc)\n events: List[SdkUsageEvent] = []\n for operation_id, operation in counts.items():\n operation_item: Dict[str, Any] = {\n "id": operation_id,\n "object": "operation",\n "uri": f"{sdk[\'uri\']}:operation:{operation_id}",\n "window_ms": int(window_s * 1000),\n "calls": operation["calls"],\n "attempts": operation["attempts"],\n "duration_sum_ms": operation["duration_sum_ms"],\n }\n for status in _STATUS_CLASSES:\n if status in operation["status"]:\n operation_item[f"status_{status}"] = operation["status"][status]\n for bucket, _ in _LATENCY_BUCKETS:\n if bucket in operation["latency"]:\n operation_item[f"latency_{bucket}"] = operation["latency"][bucket]\n events.append(\n {\n "id": _event_id(),\n "object": "event",\n "specversion": "1.0",\n "datacontenttype": "application/json; charset=utf-8",\n "type": _EVENT_TYPE,\n "source": "urn:redocly:cli",\n "time": started.isoformat(timespec="milliseconds").replace("+00:00", "Z"),\n "origin": "redocly-sdk",\n "category": "product",\n "signal": "metric",\n "data": [operation_item, sdk],\n }\n )\n return events\n\n\ndef _event_id() -> str:\n """evt_ and a lowercase ULID: 10 characters of the time in milliseconds, then 16 random ones."""\n millis = time.time_ns() // 1_000_000\n time_part = ""\n for _ in range(10):\n time_part = _CROCKFORD_BASE32[millis % 32] + time_part\n millis //= 32\n random_part = ""\n for byte in secrets.token_bytes(16):\n random_part += _CROCKFORD_BASE32[byte % 32]\n return f"evt_{time_part}{random_part}"\n\n\ndef _send_otlp(endpoint: str, events: List[SdkUsageEvent]) -> None:\n response = httpx.post(\n endpoint,\n content=json.dumps(_to_otlp_request(events)),\n # One send per window, so the connection is never reused.\n headers={"Content-Type": "application/json", "Connection": "close"},\n timeout=_SEND_TIMEOUT_S,\n )\n if not response.is_success:\n raise _RejectedSend(response.status_code)\n\n\ndef _to_otlp_request(events: List[SdkUsageEvent]) -> Dict[str, Any]:\n spans: List[Dict[str, Any]] = []\n for event in events:\n started = datetime.fromisoformat(event["time"].replace("Z", "+00:00"))\n time_unix_nano = f"{int(started.timestamp() * 1000)}000000"\n # The attributes that processCloudEventAttributes of @redocly/cli-otel gives for the event.\n attributes = [\n _attribute("cloudevents.event_id", event["id"]),\n _attribute("cloudevents.event_type", event["type"]),\n _attribute("cloudevents.event_source", event["source"]),\n _attribute("cloudevents.event_spec_version", event["specversion"]),\n _attribute("cloudevents.event_data_content_type", event["datacontenttype"]),\n _attribute("cloudevents.event_time", event["time"]),\n _attribute("cloudevents.event_subject", event["data"][0]["id"]),\n _attribute("cloudevents.event_origin", event["origin"]),\n _attribute("cloudevents.event_object", event["object"]),\n _attribute("cloudevents.event_category", event["category"]),\n _attribute("cloudevents.event_signal", event["signal"]),\n _attribute("cloudevents.event_request_id", ""),\n ]\n for item in event["data"]:\n for key, value in item.items():\n attributes.append(_attribute(f"cloudevents.event_data.{item[\'object\']}.{key}", value))\n for item in event["data"]:\n for key in ("id", "object", "uri"):\n attributes.append(_attribute(f"cloudevents.event_subjects.{item[\'object\']}.{key}", item[key]))\n spans.append(\n {\n "traceId": secrets.token_hex(16),\n "spanId": secrets.token_hex(8),\n "name": f"event.{event[\'type\']}",\n "kind": 1,\n "startTimeUnixNano": time_unix_nano,\n "endTimeUnixNano": time_unix_nano,\n "attributes": attributes,\n }\n )\n return {\n "resourceSpans": [\n {\n "resource": {\n "attributes": [\n _attribute("service.name", _SERVICE_NAME),\n _attribute("service.version", GENERATOR_VERSION),\n ]\n },\n "scopeSpans": [{"scope": {"name": "redocly-sdk-telemetry"}, "spans": spans}],\n }\n ]\n }\n\n\ndef _attribute(key: str, value: Any) -> Dict[str, Any]:\n if isinstance(value, str):\n return {"key": key, "value": {"stringValue": value}}\n if isinstance(value, int):\n return {"key": key, "value": {"intValue": value}}\n return {"key": key, "value": {"doubleValue": value}}\n';
|
|
3
3
|
//# sourceMappingURL=python-telemetry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"python-telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/python-telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,uBAAuB,GAClC,
|
|
1
|
+
{"version":3,"file":"python-telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/python-telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,uBAAuB,GAClC,y/ZAAy/Z,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n // A call aborted before its first attempt settles with 0 attempts. It counts as 1, as in the\n // other languages, so the attempts of an event are never fewer than its calls.\n operation.attempts += Math.max(call.attempts, 1);\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
|
|
1
|
+
export declare const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\nconst CROCKFORD_BASE32 = '0123456789abcdefghjkmnpqrstvwxyz';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageAggregatedMessage = BaseEventMessage & {\n type: \"com.redocly.sdkUsage.aggregated\";\n category: \"product\";\n signal: \"metric\";\n /**\n * The calls of one API operation through one generated SDK in one usage window. An event holds exactly one operation, so a usage window with several operations sends one event per operation, each with the same SDK item.\n *\n * @minItems 2\n * @maxItems 2\n */\n data: [\n {\n /**\n * The `operationId` of the operation, or the name that the generator gives to an operation without an `operationId`.\n */\n id: string;\n /**\n * Type of the resource associated with this event.\n */\n object: \"operation\";\n /**\n * Canonical URN of the operation in the SDK (`urn:redocly:cli:sdk:<language>:<package name>:operation:<operation id>`).\n */\n uri: string;\n /**\n * Length of the usage window in milliseconds.\n */\n window_ms: number;\n /**\n * Number of calls of the operation in the usage window.\n */\n calls: number;\n /**\n * Number of HTTP attempts, retries included. It is never less than `calls`.\n */\n attempts: number;\n /**\n * Sum of the call durations in milliseconds.\n */\n duration_sum_ms: number;\n /**\n * Number of calls that ended with a 2xx response.\n */\n status_2xx?: number;\n /**\n * Number of calls that ended with a 3xx response.\n */\n status_3xx?: number;\n /**\n * Number of calls that ended with a 4xx response.\n */\n status_4xx?: number;\n /**\n * Number of calls that ended with a 5xx response.\n */\n status_5xx?: number;\n /**\n * Number of calls that ended without a response because of a network error.\n */\n status_network_error?: number;\n /**\n * Number of calls that ended because of a timeout.\n */\n status_timeout?: number;\n /**\n * Number of calls that the application aborted.\n */\n status_aborted?: number;\n /**\n * Number of calls that took less than 100 ms.\n */\n latency_lt_100ms?: number;\n /**\n * Number of calls that took 100 ms or more and less than 300 ms.\n */\n latency_lt_300ms?: number;\n /**\n * Number of calls that took 300 ms or more and less than 1 s.\n */\n latency_lt_1s?: number;\n /**\n * Number of calls that took 1 s or more and less than 3 s.\n */\n latency_lt_3s?: number;\n /**\n * Number of calls that took 3 s or more and less than 10 s.\n */\n latency_lt_10s?: number;\n /**\n * Number of calls that took 10 s or more.\n */\n latency_gte_10s?: number;\n },\n {\n /**\n * The package name of the SDK.\n */\n id: string;\n /**\n * Type of the resource associated with this event.\n */\n object: \"sdk\";\n /**\n * Canonical URN of the SDK package (`urn:redocly:cli:sdk:<language>:<package name>`). A package name is unique only in the registry of one language.\n */\n uri: string;\n /**\n * The version of the SDK package.\n */\n version: string;\n /**\n * The version of the Redocly client generator that generated the SDK. Redocly CLI contains the generator.\n */\n generator_version: string;\n /**\n * The language of the SDK.\n */\n language: \"typescript\" | \"python\" | \"go\" | \"php\";\n /**\n * The runtime that runs the SDK. TypeScript sends `node`, `bun`, or `deno`. Python sends the implementation in lowercase, for example `cpython`. Go sends `go` and PHP sends `php`.\n */\n runtime: string;\n /**\n * The version of the runtime.\n */\n runtime_version: string;\n /**\n * The name and version of the application that uses the SDK, as the application registered them.\n */\n client: string;\n }\n ];\n};\n\nexport interface BaseEventMessage {\n /**\n * Event ID.\n */\n id: string;\n /**\n * Object type.\n */\n object: \"event\";\n /**\n * CloudEvents specification version.\n */\n specversion: \"1.0\";\n /**\n * Data content type.\n */\n datacontenttype: \"application/json; charset=utf-8\";\n /**\n * Context in which the event happened (producer component), not the actor and not the page.\n * Format: urn:redocly:{product}:{component}\n *\n */\n source: \"urn:redocly:cli\";\n actor?: null | {\n /**\n * Anonymous Id of the user that the event is associated with, doesn't contain any personal data.\n */\n id?: string;\n /**\n * Type of the object that the event is associated with.\n */\n object?: \"user\";\n /**\n * URL of the user, for CLI events it will be empty since we don't have user profiles in the CLI.\n */\n uri?: string;\n };\n /**\n * Timestamp of when the event happened.\n */\n time: string;\n /**\n * Origin of the event. `redocly-cli` is a CLI command. `redocly-sdk` is an SDK that Redocly CLI generated.\n */\n origin: \"redocly-cli\" | \"redocly-sdk\";\n /**\n * Telemetry signal kind: log (fire-and-forget event), trace (correlated span), or metric (aggregated counts).\n */\n signal?: \"log\" | \"trace\" | \"metric\";\n /**\n * Operating system platform.\n */\n osPlatform?: string;\n /**\n * Deployment environment. When the producer does not set it, the OpenTelemetry collector sets `otel_collector_<environment>`, so every stored event has it.\n */\n env: string;\n}\n\n/** The `com.redocly.sdkUsage.aggregated` CloudEvent. The OpenTelemetry collector sets `env`. */\nexport type SdkUsageEvent = Omit<SdkUsageAggregatedMessage, 'env'>;\ntype OperationItem = SdkUsageEvent['data'][0];\ntype SdkItem = SdkUsageEvent['data'][1];\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: SdkItem = {\n id: options.sdkName,\n object: 'sdk',\n uri: `urn:redocly:cli:sdk:typescript:${options.sdkName}`,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n // A call aborted before its first attempt settles with 0 attempts. It counts as 1, as in the\n // other languages, so the attempts of an event are never fewer than its calls.\n operation.attempts += Math.max(call.attempts, 1);\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n sdk: SdkItem\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const operationItem: OperationItem = {\n id: operationId,\n object: 'operation',\n uri: `${sdk.uri}:operation:${operationId}`,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n operationItem[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n operationItem[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: eventId(),\n object: 'event',\n specversion: '1.0',\n datacontenttype: 'application/json; charset=utf-8',\n type: EVENT_TYPE,\n source: 'urn:redocly:cli',\n time: new Date(windowStart).toISOString(),\n origin: 'redocly-sdk',\n category: 'product',\n signal: 'metric',\n data: [operationItem, sdk],\n });\n }\n return events;\n}\n\n/** `evt_` and a lowercase ULID: 10 characters of the time in milliseconds, then 16 random ones. */\nfunction eventId(): string {\n let time = Date.now();\n let id = '';\n for (let index = 0; index < 10; index++) {\n id = CROCKFORD_BASE32[time % 32] + id;\n time = Math.floor(time / 32);\n }\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n id += CROCKFORD_BASE32[byte % 32];\n }\n return `evt_${id}`;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n // The attributes that `processCloudEventAttributes` of @redocly/cli-otel gives for the event.\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', event.specversion),\n attribute('cloudevents.event_data_content_type', event.datacontenttype),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', event.data[0].id),\n attribute('cloudevents.event_origin', event.origin),\n attribute('cloudevents.event_object', event.object),\n attribute('cloudevents.event_category', event.category),\n attribute('cloudevents.event_signal', event.signal),\n attribute('cloudevents.event_request_id', ''),\n ];\n for (const item of event.data) {\n for (const [key, value] of Object.entries(item)) {\n if (value !== undefined) {\n attributes.push(attribute(`cloudevents.event_data.${item.object}.${key}`, value));\n }\n }\n }\n for (const item of event.data) {\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.id`, item.id));\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.object`, item.object));\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.uri`, item.uri));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
|
|
2
2
|
//# sourceMappingURL=telemetry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,wBAAwB,
|
|
1
|
+
{"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,wBAAwB,skoBACgioB,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// GENERATED by scripts/generate-runtime-sources.mjs — do not edit. Regenerated on install (`prepare`); manually: `npm run prepare -w @redocly/client-generator`.
|
|
2
|
-
export const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageEvent = {\n id: string;\n type: typeof EVENT_TYPE;\n source: string;\n time: string;\n data: {\n usage: Record<string, string | number>;\n sdk: Record<string, string>;\n };\n};\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: Record<string, string> = {\n name: options.sdkName,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, options.sdkName, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n // A call aborted before its first attempt settles with 0 attempts. It counts as 1, as in the\n // other languages, so the attempts of an event are never fewer than its calls.\n operation.attempts += Math.max(call.attempts, 1);\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n source: string,\n sdk: Record<string, string>\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const usage: Record<string, string | number> = {\n operation_id: operationId,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n usage[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n usage[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: `evt_${randomHex(16)}`,\n type: EVENT_TYPE,\n source,\n time: new Date(windowStart).toISOString(),\n data: { usage, sdk },\n });\n }\n return events;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', '1.0'),\n attribute('cloudevents.event_data_content_type', 'application/json; charset=utf-8'),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', ''),\n attribute('cloudevents.event_origin', SERVICE_NAME),\n attribute('cloudevents.event_object', 'event'),\n attribute('cloudevents.event_category', 'product'),\n attribute('cloudevents.event_signal', 'metric'),\n ];\n for (const [key, value] of Object.entries(event.data.usage)) {\n attributes.push(attribute(`cloudevents.event_data.usage.${key}`, value));\n }\n for (const [key, value] of Object.entries(event.data.sdk)) {\n attributes.push(attribute(`cloudevents.event_data.sdk.${key}`, value));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
|
|
2
|
+
export const TELEMETRY_RUNTIME_SOURCE = "import type { Middleware, SettledCall } from '../../../runtime-contract.js';\n\nconst GENERATOR_VERSION: string = 'dev';\nconst DEFAULT_ENDPOINT = 'https://otel.cloud.redocly.com/v1/traces';\nconst EVENT_TYPE = 'com.redocly.sdkUsage.aggregated';\nconst SEND_TIMEOUT_MS = 3000;\nconst SERVICE_NAME = 'redocly-sdk';\nconst CROCKFORD_BASE32 = '0123456789abcdefghjkmnpqrstvwxyz';\n\ntype StatusClass = '2xx' | '3xx' | '4xx' | '5xx' | 'network_error' | 'timeout' | 'aborted';\ntype LatencyBucket = 'lt_100ms' | 'lt_300ms' | 'lt_1s' | 'lt_3s' | 'lt_10s' | 'gte_10s';\n\nconst STATUS_CLASSES: StatusClass[] = [\n '2xx',\n '3xx',\n '4xx',\n '5xx',\n 'network_error',\n 'timeout',\n 'aborted',\n];\nconst LATENCY_BUCKETS: Array<{ bucket: LatencyBucket; belowMs: number }> = [\n { bucket: 'lt_100ms', belowMs: 100 },\n { bucket: 'lt_300ms', belowMs: 300 },\n { bucket: 'lt_1s', belowMs: 1000 },\n { bucket: 'lt_3s', belowMs: 3000 },\n { bucket: 'lt_10s', belowMs: 10000 },\n { bucket: 'gte_10s', belowMs: Infinity },\n];\n\nexport type SdkUsageAggregatedMessage = BaseEventMessage & {\n type: \"com.redocly.sdkUsage.aggregated\";\n category: \"product\";\n signal: \"metric\";\n /**\n * The calls of one API operation through one generated SDK in one usage window. An event holds exactly one operation, so a usage window with several operations sends one event per operation, each with the same SDK item.\n *\n * @minItems 2\n * @maxItems 2\n */\n data: [\n {\n /**\n * The `operationId` of the operation, or the name that the generator gives to an operation without an `operationId`.\n */\n id: string;\n /**\n * Type of the resource associated with this event.\n */\n object: \"operation\";\n /**\n * Canonical URN of the operation in the SDK (`urn:redocly:cli:sdk:<language>:<package name>:operation:<operation id>`).\n */\n uri: string;\n /**\n * Length of the usage window in milliseconds.\n */\n window_ms: number;\n /**\n * Number of calls of the operation in the usage window.\n */\n calls: number;\n /**\n * Number of HTTP attempts, retries included. It is never less than `calls`.\n */\n attempts: number;\n /**\n * Sum of the call durations in milliseconds.\n */\n duration_sum_ms: number;\n /**\n * Number of calls that ended with a 2xx response.\n */\n status_2xx?: number;\n /**\n * Number of calls that ended with a 3xx response.\n */\n status_3xx?: number;\n /**\n * Number of calls that ended with a 4xx response.\n */\n status_4xx?: number;\n /**\n * Number of calls that ended with a 5xx response.\n */\n status_5xx?: number;\n /**\n * Number of calls that ended without a response because of a network error.\n */\n status_network_error?: number;\n /**\n * Number of calls that ended because of a timeout.\n */\n status_timeout?: number;\n /**\n * Number of calls that the application aborted.\n */\n status_aborted?: number;\n /**\n * Number of calls that took less than 100 ms.\n */\n latency_lt_100ms?: number;\n /**\n * Number of calls that took 100 ms or more and less than 300 ms.\n */\n latency_lt_300ms?: number;\n /**\n * Number of calls that took 300 ms or more and less than 1 s.\n */\n latency_lt_1s?: number;\n /**\n * Number of calls that took 1 s or more and less than 3 s.\n */\n latency_lt_3s?: number;\n /**\n * Number of calls that took 3 s or more and less than 10 s.\n */\n latency_lt_10s?: number;\n /**\n * Number of calls that took 10 s or more.\n */\n latency_gte_10s?: number;\n },\n {\n /**\n * The package name of the SDK.\n */\n id: string;\n /**\n * Type of the resource associated with this event.\n */\n object: \"sdk\";\n /**\n * Canonical URN of the SDK package (`urn:redocly:cli:sdk:<language>:<package name>`). A package name is unique only in the registry of one language.\n */\n uri: string;\n /**\n * The version of the SDK package.\n */\n version: string;\n /**\n * The version of the Redocly client generator that generated the SDK. Redocly CLI contains the generator.\n */\n generator_version: string;\n /**\n * The language of the SDK.\n */\n language: \"typescript\" | \"python\" | \"go\" | \"php\";\n /**\n * The runtime that runs the SDK. TypeScript sends `node`, `bun`, or `deno`. Python sends the implementation in lowercase, for example `cpython`. Go sends `go` and PHP sends `php`.\n */\n runtime: string;\n /**\n * The version of the runtime.\n */\n runtime_version: string;\n /**\n * The name and version of the application that uses the SDK, as the application registered them.\n */\n client: string;\n }\n ];\n};\n\nexport interface BaseEventMessage {\n /**\n * Event ID.\n */\n id: string;\n /**\n * Object type.\n */\n object: \"event\";\n /**\n * CloudEvents specification version.\n */\n specversion: \"1.0\";\n /**\n * Data content type.\n */\n datacontenttype: \"application/json; charset=utf-8\";\n /**\n * Context in which the event happened (producer component), not the actor and not the page.\n * Format: urn:redocly:{product}:{component}\n *\n */\n source: \"urn:redocly:cli\";\n actor?: null | {\n /**\n * Anonymous Id of the user that the event is associated with, doesn't contain any personal data.\n */\n id?: string;\n /**\n * Type of the object that the event is associated with.\n */\n object?: \"user\";\n /**\n * URL of the user, for CLI events it will be empty since we don't have user profiles in the CLI.\n */\n uri?: string;\n };\n /**\n * Timestamp of when the event happened.\n */\n time: string;\n /**\n * Origin of the event. `redocly-cli` is a CLI command. `redocly-sdk` is an SDK that Redocly CLI generated.\n */\n origin: \"redocly-cli\" | \"redocly-sdk\";\n /**\n * Telemetry signal kind: log (fire-and-forget event), trace (correlated span), or metric (aggregated counts).\n */\n signal?: \"log\" | \"trace\" | \"metric\";\n /**\n * Operating system platform.\n */\n osPlatform?: string;\n /**\n * Deployment environment. When the producer does not set it, the OpenTelemetry collector sets `otel_collector_<environment>`, so every stored event has it.\n */\n env: string;\n}\n\n/** The `com.redocly.sdkUsage.aggregated` CloudEvent. The OpenTelemetry collector sets `env`. */\nexport type SdkUsageEvent = Omit<SdkUsageAggregatedMessage, 'env'>;\ntype OperationItem = SdkUsageEvent['data'][0];\ntype SdkItem = SdkUsageEvent['data'][1];\n\nexport type TelemetryOptions = {\n sdkName: string;\n sdkVersion: string;\n client: string;\n sink?: (events: SdkUsageEvent[]) => void | Promise<void>;\n endpoint?: string;\n flushIntervalMs?: number;\n};\n\ntype OperationCounts = {\n calls: number;\n attempts: number;\n durationSumMs: number;\n status: Record<StatusClass, number>;\n latency: Record<LatencyBucket, number>;\n};\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n versions?: { node?: string; bun?: string; deno?: string };\n on?: (event: 'beforeExit', listener: () => void) => void;\n};\n\ntype OnFailedSend = 'keep' | 'drop';\n\nconst activeWindows = new Set<(onFailedSend: OnFailedSend) => Promise<void>>();\nconst pendingSends = new Set<Promise<void>>();\nlet exitHookInstalled = false;\n\nfunction nodeProcess(): ProcessLike | undefined {\n return (globalThis as { process?: ProcessLike }).process;\n}\n\nfunction telemetryDisabled(): boolean {\n const runtimeProcess = nodeProcess();\n if (runtimeProcess === undefined) return true;\n // A browser bundle can add a `process` shim, so also check for `document`.\n if (typeof document !== 'undefined') return true;\n const env = runtimeProcess.env ?? {};\n if (env.REDOCLY_SDK_TELEMETRY === 'off') return true;\n if (env.DO_NOT_TRACK === '1') return true;\n return false;\n}\n\nexport function flush(): Promise<void> {\n return flushWindows('keep');\n}\n\nasync function flushWindows(onFailedSend: OnFailedSend): Promise<void> {\n for (const flushWindow of activeWindows) void flushWindow(onFailedSend);\n await Promise.all(pendingSends);\n}\n\nexport function telemetry(options: TelemetryOptions): Middleware {\n if (telemetryDisabled()) return {};\n const intervalMs = options.flushIntervalMs ?? 60_000;\n const endpoint = options.endpoint ?? DEFAULT_ENDPOINT;\n const sink = options.sink ?? ((events: SdkUsageEvent[]) => sendOtlp(endpoint, events));\n const versions = nodeProcess()?.versions ?? {};\n let runtime = 'node';\n let runtimeVersion = versions.node ?? '';\n if (versions.bun !== undefined) {\n runtime = 'bun';\n runtimeVersion = versions.bun;\n } else if (versions.deno !== undefined) {\n runtime = 'deno';\n runtimeVersion = versions.deno;\n }\n const sdk: SdkItem = {\n id: options.sdkName,\n object: 'sdk',\n uri: `urn:redocly:cli:sdk:typescript:${options.sdkName}`,\n version: options.sdkVersion,\n generator_version: GENERATOR_VERSION,\n language: 'typescript',\n runtime,\n runtime_version: runtimeVersion,\n client: options.client,\n };\n let counts = new Map<string, OperationCounts>();\n let windowStart = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n function openWindow(): void {\n windowStart = Date.now();\n timer = setTimeout(() => void flushWindow('keep'), intervalMs);\n unrefTimer(timer);\n activeWindows.add(flushWindow);\n }\n\n async function flushWindow(onFailedSend: OnFailedSend): Promise<void> {\n if (counts.size === 0) return;\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n activeWindows.delete(flushWindow);\n const events = toEvents(counts, windowStart, Date.now() - windowStart, sdk);\n const sentCounts = counts;\n const sentWindowStart = windowStart;\n counts = new Map();\n if (telemetryDisabled()) return;\n let action: OnFailedSend | undefined;\n const send = Promise.resolve()\n .then(() => sink(events))\n .catch((error: unknown) => {\n action = actionForFailedSend(error);\n });\n pendingSends.add(send);\n await send;\n pendingSends.delete(send);\n if (action !== 'keep' || onFailedSend === 'drop') return;\n\n if (counts.size === 0) openWindow();\n if (sentWindowStart < windowStart) windowStart = sentWindowStart;\n for (const [operationId, sentOperation] of sentCounts) {\n const operation = counts.get(operationId);\n if (operation === undefined) {\n counts.set(operationId, sentOperation);\n } else {\n addCounts(operation, sentOperation);\n }\n }\n }\n\n installExitHook();\n\n return {\n onSettled: (ctx, call) => {\n if (counts.size === 0) openWindow();\n let operation = counts.get(ctx.operation.id);\n if (operation === undefined) {\n operation = emptyCounts();\n counts.set(ctx.operation.id, operation);\n }\n record(operation, call);\n },\n };\n}\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // Node emits `beforeExit` again after each send at exit.\n // Kept counts then cause one more send each time, so a failed send here drops its counts.\n nodeProcess()?.on?.('beforeExit', () => void flushWindows('drop'));\n}\n\nfunction unrefTimer(timer: unknown): void {\n if (timer instanceof Object && 'unref' in timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n}\n\nfunction emptyCounts(): OperationCounts {\n return {\n calls: 0,\n attempts: 0,\n durationSumMs: 0,\n status: { '2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, network_error: 0, timeout: 0, aborted: 0 },\n latency: { lt_100ms: 0, lt_300ms: 0, lt_1s: 0, lt_3s: 0, lt_10s: 0, gte_10s: 0 },\n };\n}\n\nfunction record(operation: OperationCounts, call: SettledCall): void {\n operation.calls += 1;\n // A call aborted before its first attempt settles with 0 attempts. It counts as 1, as in the\n // other languages, so the attempts of an event are never fewer than its calls.\n operation.attempts += Math.max(call.attempts, 1);\n operation.durationSumMs += call.durationMs;\n operation.status[statusClass(call)] += 1;\n for (const { bucket, belowMs } of LATENCY_BUCKETS) {\n if (call.durationMs < belowMs) {\n operation.latency[bucket] += 1;\n break;\n }\n }\n}\n\nfunction addCounts(target: OperationCounts, source: OperationCounts): void {\n target.calls += source.calls;\n target.attempts += source.attempts;\n target.durationSumMs += source.durationSumMs;\n for (const statusClass of STATUS_CLASSES) {\n target.status[statusClass] += source.status[statusClass];\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n target.latency[bucket] += source.latency[bucket];\n }\n}\n\nfunction statusClass(call: SettledCall): StatusClass {\n if (call.response === undefined) {\n if (call.error instanceof Error && call.error.name === 'TimeoutError') return 'timeout';\n if (call.error instanceof Error && call.error.name === 'AbortError') return 'aborted';\n return 'network_error';\n }\n const status = call.response.status;\n if (status >= 500) return '5xx';\n if (status >= 400) return '4xx';\n if (status >= 300) return '3xx';\n return '2xx';\n}\n\nfunction toEvents(\n counts: Map<string, OperationCounts>,\n windowStart: number,\n windowMs: number,\n sdk: SdkItem\n): SdkUsageEvent[] {\n const events: SdkUsageEvent[] = [];\n for (const [operationId, operation] of counts) {\n const operationItem: OperationItem = {\n id: operationId,\n object: 'operation',\n uri: `${sdk.uri}:operation:${operationId}`,\n window_ms: windowMs,\n calls: operation.calls,\n attempts: operation.attempts,\n duration_sum_ms: operation.durationSumMs,\n };\n for (const statusClass of STATUS_CLASSES) {\n const count = operation.status[statusClass];\n if (count > 0) {\n operationItem[`status_${statusClass}`] = count;\n }\n }\n for (const { bucket } of LATENCY_BUCKETS) {\n const count = operation.latency[bucket];\n if (count > 0) {\n operationItem[`latency_${bucket}`] = count;\n }\n }\n events.push({\n id: eventId(),\n object: 'event',\n specversion: '1.0',\n datacontenttype: 'application/json; charset=utf-8',\n type: EVENT_TYPE,\n source: 'urn:redocly:cli',\n time: new Date(windowStart).toISOString(),\n origin: 'redocly-sdk',\n category: 'product',\n signal: 'metric',\n data: [operationItem, sdk],\n });\n }\n return events;\n}\n\n/** `evt_` and a lowercase ULID: 10 characters of the time in milliseconds, then 16 random ones. */\nfunction eventId(): string {\n let time = Date.now();\n let id = '';\n for (let index = 0; index < 10; index++) {\n id = CROCKFORD_BASE32[time % 32] + id;\n time = Math.floor(time / 32);\n }\n for (const byte of crypto.getRandomValues(new Uint8Array(16))) {\n id += CROCKFORD_BASE32[byte % 32];\n }\n return `evt_${id}`;\n}\n\nasync function sendOtlp(endpoint: string, events: SdkUsageEvent[]): Promise<void> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // One send per window, so the socket is never reused: close it instead of keeping it idle.\n headers: { 'Content-Type': 'application/json', Connection: 'close' },\n body: JSON.stringify(toOtlpRequest(events)),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n await response.body?.cancel();\n if (!response.ok) {\n throw new RejectedSendError(response.status);\n }\n}\n\nclass RejectedSendError extends Error {\n public readonly status: number;\n constructor(status: number) {\n super(`The telemetry endpoint answered ${status}.`);\n this.name = 'RejectedSendError';\n this.status = status;\n }\n}\n\nfunction actionForFailedSend(error: unknown): OnFailedSend {\n // The endpoint can have stored the counts of a send that timed out.\n if (error instanceof Error && error.name === 'TimeoutError') return 'drop';\n if (error instanceof RejectedSendError) {\n if (error.status === 408 || error.status === 429 || error.status >= 500) return 'keep';\n // The endpoint refuses the same counts again.\n return 'drop';\n }\n return 'keep';\n}\n\ntype OtlpValue = { stringValue: string } | { intValue: number } | { doubleValue: number };\ntype OtlpAttribute = { key: string; value: OtlpValue };\n\nfunction toOtlpRequest(events: SdkUsageEvent[]) {\n const spans = [];\n for (const event of events) {\n const timeUnixNano = `${Date.parse(event.time)}000000`;\n // The attributes that `processCloudEventAttributes` of @redocly/cli-otel gives for the event.\n const attributes: OtlpAttribute[] = [\n attribute('cloudevents.event_id', event.id),\n attribute('cloudevents.event_type', event.type),\n attribute('cloudevents.event_source', event.source),\n attribute('cloudevents.event_spec_version', event.specversion),\n attribute('cloudevents.event_data_content_type', event.datacontenttype),\n attribute('cloudevents.event_time', event.time),\n attribute('cloudevents.event_subject', event.data[0].id),\n attribute('cloudevents.event_origin', event.origin),\n attribute('cloudevents.event_object', event.object),\n attribute('cloudevents.event_category', event.category),\n attribute('cloudevents.event_signal', event.signal),\n attribute('cloudevents.event_request_id', ''),\n ];\n for (const item of event.data) {\n for (const [key, value] of Object.entries(item)) {\n if (value !== undefined) {\n attributes.push(attribute(`cloudevents.event_data.${item.object}.${key}`, value));\n }\n }\n }\n for (const item of event.data) {\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.id`, item.id));\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.object`, item.object));\n attributes.push(attribute(`cloudevents.event_subjects.${item.object}.uri`, item.uri));\n }\n spans.push({\n traceId: randomHex(16),\n spanId: randomHex(8),\n name: `event.${event.type}`,\n kind: 1,\n startTimeUnixNano: timeUnixNano,\n endTimeUnixNano: timeUnixNano,\n attributes,\n });\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n attribute('service.name', SERVICE_NAME),\n attribute('service.version', GENERATOR_VERSION),\n ],\n },\n scopeSpans: [{ scope: { name: 'redocly-sdk-telemetry' }, spans }],\n },\n ],\n };\n}\n\nfunction attribute(key: string, value: string | number): OtlpAttribute {\n if (typeof value === 'string') return { key, value: { stringValue: value } };\n if (Number.isInteger(value)) return { key, value: { intValue: value } };\n return { key, value: { doubleValue: value } };\n}\n\nfunction randomHex(byteCount: number): string {\n const bytes = crypto.getRandomValues(new Uint8Array(byteCount));\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return hex;\n}\n";
|
|
3
3
|
//# sourceMappingURL=telemetry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,wBAAwB,GACnC,
|
|
1
|
+
{"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../src/runtime-sources/telemetry.ts"],"names":[],"mappings":"AAAA,iKAAiK;AACjK,MAAM,CAAC,MAAM,wBAAwB,GACnC,mkoBAAmkoB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@redocly/client-generator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.1",
|
|
4
4
|
"description": "Generate typed, zero-dependency TypeScript clients (fetch, auth, retries, middleware, SSE) from OpenAPI descriptions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "lib/index.d.ts",
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"Roman Marshevskyi <roman.marshevskyy@redocly.com> (https://redocly.com/)"
|
|
88
88
|
],
|
|
89
89
|
"dependencies": {
|
|
90
|
-
"@redocly/openapi-core": "2.
|
|
90
|
+
"@redocly/openapi-core": "2.78.0"
|
|
91
91
|
},
|
|
92
92
|
"peerDependencies": {
|
|
93
93
|
"typescript": ">=5.5.0"
|
|
@@ -98,6 +98,7 @@
|
|
|
98
98
|
}
|
|
99
99
|
},
|
|
100
100
|
"devDependencies": {
|
|
101
|
+
"@redocly/cli-otel": "0.4.0",
|
|
101
102
|
"typescript": "6.0.2"
|
|
102
103
|
},
|
|
103
104
|
"files": [
|