pingerplot 1.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pingerplot/tray.py ADDED
@@ -0,0 +1,373 @@
1
+ """The notification-area icon, its menu, and its notifications (Windows).
2
+
3
+ Shell_NotifyIconW through ctypes, on a thread of its own with its own hidden
4
+ window and message loop. Notifications are the icon's balloons, which Windows
5
+ 10 and 11 show as toasts under the app's name; a click on one runs that
6
+ notification's callback. Icons are made in memory from the app's own drawing
7
+ (CreateIconFromResourceEx takes PNG bytes), so no image file ships.
8
+
9
+ Every callback runs on the tray thread: the window marshals them onto Tk's.
10
+
11
+ The hidden window is a top-level one (not message-only) so that it receives
12
+ broadcasts: TaskbarCreated, to put the icon back after Explorer restarts, and
13
+ WM_SETTINGCHANGE, when Windows switches between light and dark. A second copy
14
+ of the app finds it by class name and posts WM_SHOW_WINDOW to it.
15
+
16
+ Adapted from UniFi Stock Watcher, a sibling project with the same conventions.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import ctypes
21
+ import logging
22
+ import queue
23
+ import sys
24
+ import threading
25
+ from typing import Callable, Dict, List, Optional
26
+
27
+ from . import winplatform
28
+ from .winplatform import WM_SHOW_WINDOW
29
+
30
+ log = logging.getLogger("pingerplot.tray")
31
+
32
+ AVAILABLE = sys.platform == "win32"
33
+
34
+ WM_DESTROY, WM_CLOSE, WM_NULL = 0x0002, 0x0010, 0x0000
35
+ WM_SETTINGCHANGE, WM_CONTEXTMENU, WM_LBUTTONDBLCLK = 0x001A, 0x007B, 0x0203
36
+ WM_APP = 0x8000
37
+ WM_TRAY_CALLBACK = WM_APP + 0x41
38
+ WM_TRAY_WAKE = WM_APP + 0x43 # work queued for this thread
39
+ NIN_SELECT, NIN_KEYSELECT = 0x0400, 0x0401
40
+ NIN_BALLOONUSERCLICK = 0x0405
41
+ NIM_ADD, NIM_MODIFY, NIM_DELETE, NIM_SETVERSION = 0, 1, 2, 4
42
+ NIF_MESSAGE, NIF_ICON, NIF_TIP, NIF_INFO, NIF_SHOWTIP = 0x1, 0x2, 0x4, 0x10, 0x80
43
+ NIIF_USER, NIIF_NOSOUND, NIIF_LARGE_ICON = 0x4, 0x10, 0x20
44
+ NOTIFYICON_VERSION_4 = 4
45
+ MF_STRING, MF_SEPARATOR, MF_GRAYED, MF_CHECKED = 0x0, 0x800, 0x1, 0x8
46
+ TPM_RIGHTBUTTON, TPM_RETURNCMD, TPM_NONOTIFY = 0x2, 0x100, 0x80
47
+ SM_CXSMICON, SM_CXICON = 49, 11
48
+
49
+ if AVAILABLE:
50
+ from ctypes import wintypes
51
+
52
+ LRESULT = ctypes.c_ssize_t
53
+ WNDPROC = ctypes.WINFUNCTYPE(LRESULT, wintypes.HWND, wintypes.UINT,
54
+ wintypes.WPARAM, wintypes.LPARAM)
55
+
56
+ class GUID(ctypes.Structure):
57
+ _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD),
58
+ ("Data3", wintypes.WORD), ("Data4", ctypes.c_ubyte * 8)]
59
+
60
+ class NOTIFYICONDATAW(ctypes.Structure):
61
+ _fields_ = [("cbSize", wintypes.DWORD), ("hWnd", wintypes.HWND),
62
+ ("uID", wintypes.UINT), ("uFlags", wintypes.UINT),
63
+ ("uCallbackMessage", wintypes.UINT), ("hIcon", wintypes.HICON),
64
+ ("szTip", wintypes.WCHAR * 128), ("dwState", wintypes.DWORD),
65
+ ("dwStateMask", wintypes.DWORD), ("szInfo", wintypes.WCHAR * 256),
66
+ ("uVersion", wintypes.UINT), ("szInfoTitle", wintypes.WCHAR * 64),
67
+ ("dwInfoFlags", wintypes.DWORD), ("guidItem", GUID),
68
+ ("hBalloonIcon", wintypes.HICON)]
69
+
70
+ class WNDCLASSW(ctypes.Structure):
71
+ _fields_ = [("style", wintypes.UINT), ("lpfnWndProc", WNDPROC),
72
+ ("cbClsExtra", ctypes.c_int), ("cbWndExtra", ctypes.c_int),
73
+ ("hInstance", wintypes.HINSTANCE), ("hIcon", wintypes.HICON),
74
+ ("hCursor", wintypes.HANDLE), ("hbrBackground", wintypes.HBRUSH),
75
+ ("lpszMenuName", wintypes.LPCWSTR), ("lpszClassName", wintypes.LPCWSTR)]
76
+
77
+ _u32 = ctypes.WinDLL("user32", use_last_error=True)
78
+ _s32 = ctypes.WinDLL("shell32", use_last_error=True)
79
+ _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
80
+
81
+ _u32.DefWindowProcW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
82
+ _u32.DefWindowProcW.restype = LRESULT
83
+ _u32.CreateWindowExW.argtypes = [wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR,
84
+ wintypes.DWORD, ctypes.c_int, ctypes.c_int,
85
+ ctypes.c_int, ctypes.c_int, wintypes.HWND,
86
+ wintypes.HMENU, wintypes.HINSTANCE, wintypes.LPVOID]
87
+ _u32.CreateWindowExW.restype = wintypes.HWND
88
+ _u32.RegisterClassW.argtypes = [ctypes.POINTER(WNDCLASSW)]
89
+ _u32.RegisterClassW.restype = wintypes.ATOM
90
+ _u32.RegisterWindowMessageW.argtypes = [wintypes.LPCWSTR]
91
+ _u32.RegisterWindowMessageW.restype = wintypes.UINT
92
+ _u32.CreateIconFromResourceEx.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.BOOL,
93
+ wintypes.DWORD, ctypes.c_int, ctypes.c_int,
94
+ wintypes.UINT]
95
+ _u32.CreateIconFromResourceEx.restype = wintypes.HICON
96
+ _u32.DestroyIcon.argtypes = [wintypes.HICON]
97
+ _u32.GetSystemMetrics.argtypes = [ctypes.c_int]
98
+ _u32.GetMessageW.argtypes = [ctypes.POINTER(wintypes.MSG), wintypes.HWND,
99
+ wintypes.UINT, wintypes.UINT]
100
+ _u32.TranslateMessage.argtypes = [ctypes.POINTER(wintypes.MSG)]
101
+ _u32.DispatchMessageW.argtypes = [ctypes.POINTER(wintypes.MSG)]
102
+ _u32.DispatchMessageW.restype = LRESULT
103
+ _u32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
104
+ _u32.DestroyWindow.argtypes = [wintypes.HWND]
105
+ _u32.CreatePopupMenu.restype = wintypes.HMENU
106
+ _u32.AppendMenuW.argtypes = [wintypes.HMENU, wintypes.UINT, ctypes.c_size_t, wintypes.LPCWSTR]
107
+ _u32.SetMenuDefaultItem.argtypes = [wintypes.HMENU, wintypes.UINT, wintypes.UINT]
108
+ _u32.TrackPopupMenuEx.argtypes = [wintypes.HMENU, wintypes.UINT, ctypes.c_int,
109
+ ctypes.c_int, wintypes.HWND, wintypes.LPVOID]
110
+ _u32.TrackPopupMenuEx.restype = wintypes.UINT
111
+ _u32.DestroyMenu.argtypes = [wintypes.HMENU]
112
+ _u32.SetForegroundWindow.argtypes = [wintypes.HWND]
113
+ _u32.GetCursorPos.argtypes = [ctypes.POINTER(wintypes.POINT)]
114
+ _s32.Shell_NotifyIconW.argtypes = [wintypes.DWORD, ctypes.POINTER(NOTIFYICONDATAW)]
115
+ _s32.Shell_NotifyIconW.restype = wintypes.BOOL
116
+ _k32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
117
+ _k32.GetModuleHandleW.restype = wintypes.HMODULE
118
+
119
+
120
+ def hicon_from_png(png: bytes, size: int):
121
+ """An HICON from PNG bytes (Vista+ accepts PNG-compressed icon images).
122
+ The caller owns it: DestroyIcon when done."""
123
+ buf = ctypes.create_string_buffer(png, len(png))
124
+ return _u32.CreateIconFromResourceEx(buf, len(png), True, 0x00030000, size, size, 0)
125
+
126
+
127
+ # One window procedure for the class, for the life of the process: a class
128
+ # keeps the procedure it was registered with, so a per-instance callback would
129
+ # be called after its TrayIcon (and the ctypes thunk) had been collected.
130
+ _instances: Dict[int, "TrayIcon"] = {}
131
+ _creating: Optional["TrayIcon"] = None
132
+ _class_registered = False
133
+
134
+
135
+ def _dispatch(hwnd, msg, wparam, lparam):
136
+ inst = _instances.get(hwnd) or _creating
137
+ if inst is not None:
138
+ return inst._proc(hwnd, msg, wparam, lparam)
139
+ return _u32.DefWindowProcW(hwnd, msg, wparam, lparam)
140
+
141
+
142
+ if AVAILABLE:
143
+ _DISPATCH = WNDPROC(_dispatch)
144
+
145
+
146
+ class MenuItem:
147
+ """A tray menu entry. text=None is a separator."""
148
+
149
+ def __init__(self, text=None, action=None, enabled=True, checked=False, default=False):
150
+ self.text, self.action = text, action
151
+ self.enabled, self.checked, self.default = enabled, checked, default
152
+
153
+
154
+ class TrayIcon:
155
+ """TrayIcon(icon_png, tooltip, menu_fn, on_open, on_show, on_theme).start()
156
+
157
+ icon_png(state, size): PNG bytes for the icon in ``state`` ("idle",
158
+ "normal", "alert") at ``size`` pixels
159
+ menu_fn(): the list of MenuItem to show, built fresh each time
160
+ on_open(): the icon was clicked
161
+ on_show(): another copy of the app asked this one to show itself
162
+ on_theme(): Windows' light/dark setting changed
163
+ """
164
+
165
+ def __init__(self, icon_png: Callable[[str, int], bytes], tooltip: str,
166
+ menu_fn: Callable[[], List[MenuItem]], on_open=None, on_show=None,
167
+ on_theme=None) -> None:
168
+ self.icon_png, self.tooltip = icon_png, tooltip
169
+ self.menu_fn = menu_fn
170
+ self.on_open, self.on_show, self.on_theme = on_open, on_show, on_theme
171
+ self.state = "idle"
172
+ self.hwnd = None
173
+ self._handles: Dict[tuple, int] = {}
174
+ self._jobs: "queue.Queue" = queue.Queue()
175
+ self._balloon_click = None
176
+ self._ready = threading.Event()
177
+ self._thread: Optional[threading.Thread] = None
178
+ self._taskbar_created = None
179
+ self.ok = False
180
+
181
+ # Public, thread-safe ------------------------------------------------------
182
+
183
+ def start(self, timeout: float = 5) -> bool:
184
+ if not AVAILABLE:
185
+ return False
186
+ self._thread = threading.Thread(target=self._run, name="pingerplot-tray", daemon=True)
187
+ self._thread.start()
188
+ self._ready.wait(timeout)
189
+ return self.ok
190
+
191
+ def set_state(self, state: str, tooltip: Optional[str] = None) -> None:
192
+ self._call(self._apply_state, state, tooltip)
193
+
194
+ def notify(self, title: str, text: str, on_click=None, sound: bool = False) -> None:
195
+ self._call(self._notify, title, text, on_click, sound)
196
+
197
+ def stop(self) -> None:
198
+ if self.hwnd:
199
+ _u32.PostMessageW(self.hwnd, WM_CLOSE, 0, 0)
200
+ if self._thread:
201
+ self._thread.join(timeout=3)
202
+
203
+ # Tray thread ----------------------------------------------------------------
204
+
205
+ def _call(self, fn, *args) -> None:
206
+ if not (AVAILABLE and self.hwnd):
207
+ return
208
+ self._jobs.put((fn, args))
209
+ _u32.PostMessageW(self.hwnd, WM_TRAY_WAKE, 0, 0)
210
+
211
+ def _icon(self, state: str, size_metric: int = SM_CXSMICON):
212
+ key = (state, size_metric)
213
+ if key not in self._handles:
214
+ size = _u32.GetSystemMetrics(size_metric) or 16
215
+ self._handles[key] = hicon_from_png(self.icon_png(state, size), size)
216
+ return self._handles[key]
217
+
218
+ def _nid(self, flags: int = 0):
219
+ nid = NOTIFYICONDATAW()
220
+ nid.cbSize = ctypes.sizeof(NOTIFYICONDATAW)
221
+ nid.hWnd = self.hwnd
222
+ nid.uID = 1
223
+ nid.uFlags = flags
224
+ nid.uCallbackMessage = WM_TRAY_CALLBACK
225
+ return nid
226
+
227
+ def _add_icon(self) -> bool:
228
+ nid = self._nid(NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP)
229
+ nid.hIcon = self._icon(self.state)
230
+ nid.szTip = self.tooltip[:127]
231
+ ok = _s32.Shell_NotifyIconW(NIM_ADD, ctypes.byref(nid))
232
+ nid.uVersion = NOTIFYICON_VERSION_4
233
+ _s32.Shell_NotifyIconW(NIM_SETVERSION, ctypes.byref(nid))
234
+ return bool(ok)
235
+
236
+ def _apply_state(self, state, tooltip) -> None:
237
+ self.state = state
238
+ if tooltip:
239
+ self.tooltip = tooltip
240
+ nid = self._nid(NIF_ICON | NIF_TIP | NIF_SHOWTIP)
241
+ nid.hIcon = self._icon(self.state)
242
+ nid.szTip = self.tooltip[:127]
243
+ _s32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(nid))
244
+
245
+ def _notify(self, title, text, on_click, sound) -> None:
246
+ self._balloon_click = on_click
247
+ nid = self._nid(NIF_INFO)
248
+ nid.szInfoTitle = str(title)[:63]
249
+ nid.szInfo = str(text)[:255] or " "
250
+ big = self._icon("normal", SM_CXICON)
251
+ if big:
252
+ nid.hBalloonIcon = big
253
+ nid.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON
254
+ if not sound:
255
+ nid.dwInfoFlags |= NIIF_NOSOUND
256
+ _s32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(nid))
257
+
258
+ def _show_menu(self, x=None, y=None) -> None:
259
+ items = self.menu_fn() or []
260
+ menu = _u32.CreatePopupMenu()
261
+ actions = {}
262
+ for i, item in enumerate(items, start=1):
263
+ if item.text is None:
264
+ _u32.AppendMenuW(menu, MF_SEPARATOR, 0, None)
265
+ continue
266
+ flags = MF_STRING | (0 if item.enabled else MF_GRAYED) | (MF_CHECKED if item.checked else 0)
267
+ _u32.AppendMenuW(menu, flags, i, item.text)
268
+ actions[i] = item.action
269
+ if item.default:
270
+ _u32.SetMenuDefaultItem(menu, i, False)
271
+ if x is None:
272
+ pt = wintypes.POINT()
273
+ _u32.GetCursorPos(ctypes.byref(pt))
274
+ x, y = pt.x, pt.y
275
+ # Without the foreground, the menu doesn't close on a click elsewhere.
276
+ _u32.SetForegroundWindow(self.hwnd)
277
+ cmd = _u32.TrackPopupMenuEx(menu, TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY,
278
+ x, y, self.hwnd, None)
279
+ _u32.PostMessageW(self.hwnd, WM_NULL, 0, 0)
280
+ _u32.DestroyMenu(menu)
281
+ self._safe(actions.get(cmd))
282
+
283
+ @staticmethod
284
+ def _safe(fn, *args) -> None:
285
+ if fn:
286
+ try:
287
+ fn(*args)
288
+ except Exception: # a callback must never take the message loop down
289
+ log.exception("tray callback failed")
290
+
291
+ def _proc(self, hwnd, msg, wparam, lparam):
292
+ try:
293
+ if msg == WM_TRAY_CALLBACK:
294
+ event = lparam & 0xFFFF
295
+ if event in (NIN_SELECT, NIN_KEYSELECT, WM_LBUTTONDBLCLK):
296
+ self._safe(self.on_open)
297
+ elif event == WM_CONTEXTMENU:
298
+ x = ctypes.c_short(wparam & 0xFFFF).value
299
+ y = ctypes.c_short((wparam >> 16) & 0xFFFF).value
300
+ self._show_menu(x, y)
301
+ elif event == NIN_BALLOONUSERCLICK:
302
+ self._safe(self._balloon_click)
303
+ return 0
304
+ if msg == WM_TRAY_WAKE:
305
+ while True:
306
+ try:
307
+ fn, args = self._jobs.get_nowait()
308
+ except queue.Empty:
309
+ break
310
+ self._safe(fn, *args)
311
+ return 0
312
+ if msg == WM_SHOW_WINDOW:
313
+ self._safe(self.on_show)
314
+ return 0
315
+ if msg == self._taskbar_created:
316
+ self._add_icon()
317
+ return 0
318
+ if msg == WM_SETTINGCHANGE and lparam:
319
+ if ctypes.wstring_at(lparam) == "ImmersiveColorSet":
320
+ self._safe(self.on_theme)
321
+ if msg == WM_CLOSE:
322
+ _u32.DestroyWindow(hwnd)
323
+ return 0
324
+ if msg == WM_DESTROY:
325
+ _s32.Shell_NotifyIconW(NIM_DELETE, ctypes.byref(self._nid()))
326
+ _u32.PostQuitMessage(0)
327
+ return 0
328
+ except Exception: # same: the procedure must always return
329
+ log.exception("tray window procedure failed")
330
+ return _u32.DefWindowProcW(hwnd, msg, wparam, lparam)
331
+
332
+ def _run(self) -> None:
333
+ global _creating, _class_registered
334
+ try:
335
+ hinst = _k32.GetModuleHandleW(None)
336
+ if not _class_registered:
337
+ wc = WNDCLASSW()
338
+ wc.lpfnWndProc = _DISPATCH
339
+ wc.hInstance = hinst
340
+ wc.lpszClassName = winplatform.TRAY_CLASS
341
+ if not _u32.RegisterClassW(ctypes.byref(wc)):
342
+ raise OSError(ctypes.get_last_error(), "RegisterClassW failed")
343
+ _class_registered = True
344
+ self._taskbar_created = _u32.RegisterWindowMessageW("TaskbarCreated")
345
+ # WS_POPUP, never shown: a top-level window, so broadcasts reach it.
346
+ _creating = self
347
+ try:
348
+ self.hwnd = _u32.CreateWindowExW(0, winplatform.TRAY_CLASS, "PingerPlot",
349
+ 0x80000000, 0, 0, 0, 0, None, None, hinst, None)
350
+ finally:
351
+ _creating = None
352
+ if not self.hwnd:
353
+ raise OSError(ctypes.get_last_error(), "CreateWindowExW failed")
354
+ winplatform.allow_show_message(self.hwnd)
355
+ _instances[self.hwnd] = self
356
+ self.ok = self._add_icon()
357
+ except OSError:
358
+ log.exception("tray icon unavailable")
359
+ self.ok = False
360
+ finally:
361
+ self._ready.set()
362
+ if not self.hwnd:
363
+ return
364
+ msg = wintypes.MSG()
365
+ while _u32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
366
+ _u32.TranslateMessage(ctypes.byref(msg))
367
+ _u32.DispatchMessageW(ctypes.byref(msg))
368
+ for h in self._handles.values():
369
+ if h:
370
+ _u32.DestroyIcon(h)
371
+ self._handles.clear()
372
+ _instances.pop(self.hwnd, None)
373
+ self.hwnd = None
pingerplot/trouble.py ADDED
@@ -0,0 +1,129 @@
1
+ """Where on the path the trouble is: which place adds the delay, and where the
2
+ loss starts that reaches the destination.
3
+
4
+ The rule is the one mtr users learn the hard way. Loss at a router in the
5
+ middle of the path is usually that router declining to answer pings it's
6
+ busy forwarding past, not lost traffic: if it were, every hop after it would
7
+ show it too. So a hop's loss only counts as far as it carries: the least
8
+ loss of that hop and every hop after it, destination included. Delay is
9
+ counted the same way, for the same reason: a router slow to answer its own
10
+ pings shows delay that the hops after it don't have. So a hop's latency
11
+ counts as the least average of that hop and every hop after it, and what a
12
+ hop adds is the step from the hop before; the steps add up to the last
13
+ answering hop's latency, so nothing is blamed for delay that never reaches
14
+ the destination.
15
+
16
+ A destination that never answers (one that drops pings, or a trace that
17
+ never reaches it) has no loss to carry, so none is placed: the last router
18
+ that answers is usually just rate-limiting its replies.
19
+
20
+ Hops are grouped by place (from the router's name or the IP database), so
21
+ "loss starts entering Denver, +31 ms in Chicago" reads straight off the
22
+ result. The two witnesses name one metro differently ("New York" from a
23
+ router's name, "New York City" from the database), so places within
24
+ MERGE_KM of each other are one row, under the first one's name. No Tk: the
25
+ map draws it, the tests check it, a report can print it.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass, field
30
+ from typing import Callable, List, Optional, Sequence, Tuple, Union
31
+
32
+ from .locating import distance_km
33
+
34
+ MERGE_KM = 25.0
35
+
36
+
37
+ @dataclass
38
+ class PlaceRow:
39
+ place: str
40
+ ttls: List[int] = field(default_factory=list)
41
+ delay_added: float = 0.0 # ms added by the links into this place's hops
42
+ loss_starts: float = 0.0 # % of probes lost from here to the destination
43
+ point: Optional[Tuple[float, float]] = None
44
+
45
+ @property
46
+ def score(self) -> float:
47
+ # Loss outranks delay: 1% of lost packets matters more than 1 ms.
48
+ return self.loss_starts * 10 + self.delay_added
49
+
50
+
51
+ def carried(values: Sequence[float]) -> List[float]:
52
+ """Each hop's loss or latency, counted only as far as it reaches: the
53
+ least of that hop's and every later hop's."""
54
+ out: List[float] = []
55
+ floor = float("inf")
56
+ for value in reversed(values):
57
+ floor = min(floor, value)
58
+ out.append(floor)
59
+ return list(reversed(out))
60
+
61
+
62
+ carried_loss = carried
63
+
64
+
65
+ def destination_silent(hops: Sequence) -> bool:
66
+ """Whether the last hop (the destination, or the last one probed) never
67
+ answered."""
68
+ return bool(hops) and hops[-1].avg is None
69
+
70
+
71
+ Place = Union[None, str, Tuple[str, Optional[Tuple[float, float]]]]
72
+
73
+
74
+ def rank(hops: Sequence, locate: Callable[[object], Place]) -> List[PlaceRow]:
75
+ """``hops`` in path order, each with ``ttl``, ``loss_pct``, ``avg`` (None
76
+ for a hop that never answered) and whatever ``locate`` needs, which gives
77
+ a hop's place as text or as ``(text, (lat, lon))``. Returns one row per
78
+ place, worst first; hops with no place are left out (they still count
79
+ for the hops around them). With the destination silent, no place gets
80
+ any loss."""
81
+ answered = [h for h in hops if h.avg is not None]
82
+ if not answered:
83
+ return []
84
+ silent = destination_silent(hops)
85
+ ttls = [h.ttl for h in answered]
86
+ loss = dict(zip(ttls, carried([h.loss_pct for h in answered])))
87
+ delay = dict(zip(ttls, carried([max(0.0, h.avg) for h in answered])))
88
+ rows: dict = {}
89
+ prev_delay = prev_loss = 0.0
90
+ for h in answered:
91
+ place, point = _place(locate(h))
92
+ if place:
93
+ row = rows.get(place)
94
+ if row is None and point is not None:
95
+ row = next((r for r in rows.values()
96
+ if r.point is not None and distance_km(r.point, point) <= MERGE_KM), None)
97
+ if row is None:
98
+ row = rows[place] = PlaceRow(place, point=point)
99
+ row.ttls.append(h.ttl)
100
+ row.delay_added += delay[h.ttl] - prev_delay
101
+ row.loss_starts += 0.0 if silent else max(0.0, loss[h.ttl] - prev_loss)
102
+ prev_delay, prev_loss = delay[h.ttl], loss[h.ttl]
103
+ return sorted(rows.values(), key=lambda r: -r.score)
104
+
105
+
106
+ def _place(found: Place) -> Tuple[Optional[str], Optional[Tuple[float, float]]]:
107
+ if isinstance(found, tuple):
108
+ return found[0], found[1]
109
+ return found, None
110
+
111
+
112
+ def verdict(rows: Sequence[PlaceRow], silent: bool = False) -> str:
113
+ """One line for the top of the list, or "" when there's nothing to rank.
114
+ ``silent``: the destination never answered (destination_silent)."""
115
+ if not rows:
116
+ return ""
117
+ lossy = max(rows, key=lambda r: r.loss_starts)
118
+ slow = max(rows, key=lambda r: r.delay_added)
119
+ parts = []
120
+ if silent:
121
+ parts.append("the destination doesn't answer, so where loss starts can't be told")
122
+ if lossy.loss_starts >= 1.0:
123
+ parts.append(f"loss reaching the destination starts in {lossy.place} "
124
+ f"(hop {lossy.ttls[0]}, {lossy.loss_starts:.0f}%)")
125
+ if slow.delay_added >= 10.0:
126
+ parts.append(f"the most delay is added in {slow.place} (+{slow.delay_added:.0f} ms)")
127
+ if not parts:
128
+ return "Nothing on the path stands out."
129
+ return parts[0][0].upper() + parts[0][1:] + ("; " + parts[1] if len(parts) > 1 else "") + "."
@@ -0,0 +1,8 @@
1
+ """Public half of the release-signing key (packaging/signing.py new-key).
2
+
3
+ The updater installs only releases whose latest.json is signed by the
4
+ matching private key, which lives on the maintainer's PC and in the
5
+ repository secret UPDATE_SIGNING_KEY, never in the repository.
6
+ """
7
+
8
+ UPDATE_PUBLIC_KEY = "Zt+m/5tNeng4C3M8udzVifsyFPqHRGMJNuMWehLyKQ8="