-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexample_catalog.py
More file actions
218 lines (188 loc) · 7.55 KB
/
example_catalog.py
File metadata and controls
218 lines (188 loc) · 7.55 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""Example & schema catalog utilities.
Builds a catalog of example KQL queries (parsed from markdown assets) and
optionally enriches them with live column schema retrieved from Azure Monitor.
Lightweight parsing intentionally conservative: we extract candidate KQL lines
that look query-like (contain a pipe `|`) or code fenced blocks.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Any
import re
try:
from azure.identity import DefaultAzureCredential # type: ignore
from azure.monitor.query import LogsQueryClient # type: ignore
except Exception: # pragma: no cover - optional during docs-only use
DefaultAzureCredential = None # type: ignore
LogsQueryClient = None # type: ignore
# Mapping of logical table names to example file & metadata
TABLE_EXAMPLE_MAP: Dict[str, Dict[str, str]] = {
"AppRequests": {
"file": "app_insights_capsule/kql_examples/app_requests_kql_examples.md",
"category": "Application Insights",
"description": "HTTP requests to your application",
},
"AppExceptions": {
"file": "app_insights_capsule/kql_examples/app_exceptions_kql_examples.md",
"category": "Application Insights",
"description": "Exceptions thrown by your application",
},
"AppTraces": {
"file": "app_insights_capsule/kql_examples/app_traces_kql_examples.md",
"category": "Application Insights",
"description": "Custom trace logs from your application",
},
"AppDependencies": {
"file": "app_insights_capsule/kql_examples/app_dependencies_kql_examples.md",
"category": "Application Insights",
"description": "External dependencies called by your application",
},
"AppPageViews": {
"file": "app_insights_capsule/kql_examples/app_page_views_kql_examples.md",
"category": "Application Insights",
"description": "Page views in your web application",
},
"AppCustomEvents": {
"file": "app_insights_capsule/kql_examples/app_custom_events_kql_examples.md",
"category": "Application Insights",
"description": "Custom events tracked by your application",
},
"AppPerformanceCounters": {
"file": "app_insights_capsule/kql_examples/app_performance_kql_examples.md",
"category": "Application Insights",
"description": "Performance counters and metrics",
},
"Usage": {
"file": "usage_kql_examples.md",
"category": "Usage Analytics",
"description": "User behavior and usage patterns",
},
}
KQL_LINE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\s*\|.*")
@dataclass
class ExampleEntry:
kql: str
title: Optional[str] = None
@dataclass
class TableCatalog:
table: str
description: str
category: str
columns: List[str] = field(default_factory=list)
examples: List[ExampleEntry] = field(default_factory=list)
_CACHE: Dict[str, Dict[str, Any]] = {}
_SCHEMA_TTL = timedelta(minutes=15)
def _parse_examples(md_path: Path, limit: int = 8) -> List[ExampleEntry]:
if not md_path.exists():
return []
text = md_path.read_text(encoding="utf-8", errors="ignore")
examples: List[ExampleEntry] = []
current_title: Optional[str] = None
in_code = False
code_buf: List[str] = []
for line in text.splitlines():
stripped = line.strip()
# Headings become potential titles
if stripped.startswith("#"):
if code_buf and in_code:
# finalize existing code block
joined = "\n".join(code_buf).strip()
if "|" in joined:
examples.append(ExampleEntry(kql=joined, title=current_title))
code_buf.clear()
current_title = stripped.lstrip("# ")
continue
if stripped.startswith("```"):
if not in_code:
in_code = True
code_buf = []
else:
in_code = False
joined = "\n".join(code_buf).strip()
if "|" in joined:
examples.append(ExampleEntry(kql=joined, title=current_title))
code_buf = []
continue
if in_code:
code_buf.append(stripped)
continue
# Fallback: single-line candidate
if KQL_LINE_RE.match(stripped):
examples.append(ExampleEntry(kql=stripped, title=current_title))
if len(examples) >= limit:
break
return examples[:limit]
def _get_logs_client() -> Optional[LogsQueryClient]: # pragma: no cover
if LogsQueryClient is None or DefaultAzureCredential is None:
return None
try:
return LogsQueryClient(DefaultAzureCredential(exclude_interactive_browser_credential=False))
except Exception:
return None
def _fetch_table_columns(workspace_id: str, table: str, client: LogsQueryClient) -> List[str]: # pragma: no cover network
try:
# Minimal schema hint: no row retrieval cost (should be metadata only)
query = f"{table} | take 0"
# azure-monitor-query requires a timespan; use 1h baseline
from datetime import timedelta
resp = client.query_workspace(workspace_id=workspace_id, query=query, timespan=timedelta(hours=1))
if hasattr(resp, "tables") and resp.tables: # type: ignore[attr-defined]
tbl = resp.tables[0]
cols = [getattr(c, "name", str(c)) for c in getattr(tbl, "columns", [])]
# Filter obviously synthetic columns
return [c for c in cols if c]
except Exception:
return []
return []
def load_example_catalog(workspace_id: Optional[str], include_schema: bool = True, force: bool = False) -> Dict[str, Any]:
"""Return catalog structure.
Caches per workspace id (schema may differ by workspace). If workspace is None
only file examples are returned.
"""
cache_key = workspace_id or "__no_workspace__"
now = datetime.utcnow()
cached = _CACHE.get(cache_key)
if cached and not force:
# Expire schema portion only; examples rarely change
if include_schema:
age = now - cached["generated"]
if age < _SCHEMA_TTL:
return cached["data"]
else:
return cached["data"]
tables: Dict[str, TableCatalog] = {}
for table, meta in TABLE_EXAMPLE_MAP.items():
examples = _parse_examples(Path(meta["file"]))
tables[table] = TableCatalog(
table=table,
description=meta["description"],
category=meta["category"],
examples=examples,
)
if include_schema and workspace_id:
client = _get_logs_client()
if client:
for tname, tc in tables.items():
cols = _fetch_table_columns(workspace_id, tname, client)
if cols:
# Limit to first 40 columns to keep payload compact
tc.columns = cols[:40]
catalog = {
"workspace_id": workspace_id,
"generated_at": now.isoformat() + "Z",
"tables": {
t.table: {
"description": t.description,
"category": t.category,
"columns": t.columns,
"examples": [
{"title": e.title, "kql": e.kql} for e in t.examples
],
}
for t in tables.values()
},
}
_CACHE[cache_key] = {"generated": now, "data": catalog}
return catalog
__all__ = ["load_example_catalog", "TABLE_EXAMPLE_MAP"]