import re, datetime, sqlite3, collections, statistics as st LOG = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\logs\attendancehub_sync.log" DB = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\attendancehub_v2.db" NOW = datetime.datetime.now(datetime.timezone.utc) print(f"NOW(UTC) = {NOW.isoformat()} local = {datetime.datetime.now().strftime('%H:%M:%S')}") # ---- 1) parse ReadAttendance ops with startUtc + duration ---- pat = re.compile( r"^(\d{2}:\d{2}:\d{2})\.\d+ .*COM_OP device=([^:]+):read api=ReadAttendance " r".*?startUtc=(\S+) endUtc=(\S+) durationMs=(\d+) ok=(\S+)") ops = [] # (logtime, dev, start_utc, end_utc, ms, ok) with open(LOG, "r", encoding="utf-8", errors="replace") as f: for ln in f: if "api=ReadAttendance" not in ln: continue m = pat.match(ln) if not m: continue t, dev, su, eu, ms, ok = m.groups() try: s = datetime.datetime.fromisoformat(su) e = datetime.datetime.fromisoformat(eu) except Exception: continue ops.append((t, dev, s, e, int(ms), ok)) long_ops = [o for o in ops if o[4] >= 20000] # >= 20s : device visibly busy print(f"\nReadAttendance ops parsed = {len(ops)}; >=20s = {len(long_ops)}") # ---- 2) parse LivenessPing ops (device responsiveness) ---- patp = re.compile( r"COM_OP device=([^:]+):live api=LivenessPing .*startUtc=(\S+) endUtc=(\S+) " r"durationMs=(\d+) ok=(\S+)") pings = [] with open(LOG, "r", encoding="utf-8", errors="replace") as f: for ln in f: if "api=LivenessPing" not in ln: continue m = patp.search(ln) if m: dev, su, eu, ms, ok = m.groups() try: pings.append((dev, datetime.datetime.fromisoformat(su), datetime.datetime.fromisoformat(eu), int(ms), ok)) except Exception: pass # pings that fell INSIDE a long read (device busy) vs outside def inside(dt, ops_list): for o in ops_list: if o[2] <= dt <= o[3]: return o return None print("\n=== A) LivenessPing latency: INSIDE a >=20s read vs OUTSIDE ===") inn, out = [], [] for dev, s, e, ms, ok in pings: o = inside(s, long_ops) (inn if o else out).append(ms) def desc(v, label): if not v: print(f" {label}: (none)"); return sv = sorted(v) p95 = sv[min(len(sv)-1, int(round(.95*(len(sv)-1))))] print(f" {label}: n={len(v)} p50={st.median(v):.0f}ms p95={p95}ms max={max(v)}ms " f"over_3s={sum(1 for x in v if x>3000)}") desc(inn, "INSIDE long read") desc(out, "OUTSIDE long read") # ---- 3) punches today, with ingest time ---- con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=15) def parse(s): if s is None: return None s = s.rstrip("Z") if "." in s: whole, frac = s.split("."); frac = (frac + "0000000")[:7] else: whole, frac = s, "0000000" return (datetime.datetime.fromisoformat(whole) .replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(microseconds=int(frac) / 10)) today = NOW.strftime("%Y-%m-%d") rows = con.execute( "SELECT personnel_code, device_id, punch_time, first_seen_at, source, upload_state " "FROM punches WHERE first_seen_at >= ? ORDER BY first_seen_at", (today + "T00:00:00.0000000Z",)).fetchall() print(f"\n=== B) punches ingested today = {len(rows)} ===") # classify each punch by whether it landed during a long read during, after = [], [] for pc, dev, pt, fs, src, stt in rows: f = parse(fs) if not f: continue o = inside(f, long_ops) (during if o else after).append((pc, dev, f, src, o[4] if o else 0)) print(f" punches ingested DURING a >=20s device-busy read : {len(during)}") print(f" punches ingested while device idle : {len(after)}") if during: print("\n --- samples DURING long reads (proves device still captures) ---") for pc, dev, f, src, ms in during[:15]: print(f" pin={pc:<8} dev={dev:<16} ingest={f.strftime('%H:%M:%S')} " f"src={src:<14} readBusy={ms/1000:.0f}s") # live latency of punches during long reads lat_d = [] for pc, dev, f, src, ms in during: if src == "Realtime": # raw delta vs punch label (site local) -> correct p = None for r in rows: if r[0] == pc and r[3] and parse(r[3]) == f: p = r[2]; break if p: try: pl = parse(p) lat_d.append((f - pl).total_seconds() + 12600 - 84) except Exception: pass if lat_d: print(f"\n realtime ingest latency for those: n={len(lat_d)} " f"p50={st.median(lat_d):.1f}s min={min(lat_d):.1f}s max={max(lat_d):.1f}s") # ---- 4) any punch MISSING during long reads? (gaps) ---- print("\n=== C) per-device: long-read seconds vs punches during ===") byd = collections.defaultdict(lambda: [0, 0]) for o in long_ops: byd[o[1]][0] += o[4] / 1000 for pc, dev, f, src, ms in during: byd[dev][1] += 1 for d in sorted(byd): busy, n = byd[d] print(f" {d:<16} busySec={busy:>7.0f} punchesDuringRead={n}") # ---- 5) FRESH live-path proof: last 20 minutes ---- print("\n=== D) FRESH live-path proof — last 20 min ===") cut = NOW - datetime.timedelta(minutes=20) recent = [(pc, dev, pt, parse(fs), src, stt) for pc, dev, pt, fs, src, stt in rows if parse(fs) and parse(fs) >= cut] print(f" punches = {len(recent)}") for pc, dev, pt, f, src, stt in recent[-12:]: try: pl = parse(pt) raw = (f - pl).total_seconds() lat = raw + 12600 - 84 ltxt = f"{lat:6.1f}s" except Exception as ex: ltxt = f"err:{ex}" print(f" {f.strftime('%H:%M:%S')} pin={pc:<8} dev={dev:<16} " f"src={src:<14} {stt:<8} dev->ingest={ltxt}") print("\n=== E) source mix of ALL punches today ===") for r in con.execute("SELECT source, COUNT(*) FROM punches WHERE first_seen_at >= ? GROUP BY source", (today + "T00:00:00.0000000Z",)): print(f" {r[0]}: {r[1]}") con.close() # ---- 6) current health RIGHT NOW ---- print("\n=== F) DUAL_HEALTH (last sample per device) ===") latest = {} with open(LOG, "r", encoding="utf-8", errors="replace") as f: for ln in f: if "DUAL_HEALTH device=" in ln: m = re.search(r"device=(\S+)", ln) if m: latest[m.group(1)] = ln.strip() g = lambda ln, p: (re.search(p, ln).group(1) if re.search(p, ln) else "-") for d in sorted(latest): ln = latest[d] print(f" {d:<16} {ln[:8]} live={g(ln,'liveC=(\\S+)')}/{g(ln,'livePump=(\\S+)')} " f"read={g(ln,'readC=(\\S+)')}/{g(ln,'readPump=(\\S+)')} " f"evD={g(ln,'evDirect=(\\S+)')} evDrop={g(ln,'evDropped=(\\S+)')}")