SPB Git

Repository Public

watch_swap.py 5.9 KB 130 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : KA Maps Engine10# File             : server/km-geo/tests/watch_swap.py11# Description      : Sonde de continuité : interroge km-geo sans arrêt12#                    (recherche, inverse, proximité, limites) et compte tout ce13#                    qui n'est pas un 200.14# Module           : server15# Repository       : https://git.spboucher.ai/ka-maps-engine16# Created          : 2026-12-0117# Last Modified    : 2026-12-0118#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author           : Simon-Pierre Boucher24# Position         : Professor of Finance25# Institution      : Université du Québec en Outaouais (UQO)26# Department       : Département des sciences administratives27# Organization     : SP Boucher28#29# Website          : https://spboucher.ai30# Git              : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General          : info@spboucher.ai37# Professional     : contact@spboucher.ai38# Direct           : simon@spboucher.ai39# Research         : research@spboucher.ai40# Development      : dev@spboucher.ai41# Support          : support@spboucher.ai42# Security/Admin   : admin@spboucher.ai43# Notifications    : notifications@spboucher.ai44#45# Preferred Contact: support@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification   : Public70# Distribution     : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License          : None specified (no license file in this repository)84# Maintainer       : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""Sonde de continuité : interroge km-geo sans arrêt (recherche, inverse, proximité, limites) et compte tout ce qui92n'est pas un 200. À lancer pendant une reconstruction pour prouver qu'aucune requête n'échoue à la bascule.93  watch_swap.py <fichier d'arrêt> [threads]   — s'arrête quand le fichier existe ; écrit un JSON."""94import json, os, sys, threading, time, urllib.parse, urllib.request95BASE = os.environ.get("KM_GEO_URL", "http://127.0.0.1:8902")96stop_file, nthreads = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 497URLS = ["/v1/search?" + urllib.parse.urlencode({"q": q}) for q in98        ["1000 rue de la gauchetiere ouest montreal", "rue saint-den", "universite laval", "plateau", "H3B 5H4", "455 rue lorquet quebec",99         "boul rene levesque", "chicoutimi", "station berri-uqam", "2500 boul de l universite sherbrooke"]] + \100       ["/v1/reverse?lon=-73.5673&lat=45.5017", "/v1/reverse?lon=-71.2280&lat=46.8290", "/v1/nearby?lon=-73.5815&lat=45.5245",101        "/v1/boundaries?lon=-71.2&lat=46.81", "/v1/boundaries/search?q=limoilou", "/v1/boundaries/municipalite/66023?zoom=10"]102lock = threading.Lock()103stats = {"requests": 0, "status": {}, "errors": [], "max_ms": 0.0, "slow_over_500ms": 0}104def work(k):105    i = k106    while not os.path.exists(stop_file):107        u = URLS[i % len(URLS)]; i += 1108        t = time.perf_counter()109        try:110            with urllib.request.urlopen(BASE + u, timeout=15) as r:111                r.read(); code = r.status112        except urllib.error.HTTPError as e:113            code = e.code114        except Exception as e:115            code = "exception"116        ms = (time.perf_counter() - t) * 1000117        with lock:118            stats["requests"] += 1119            stats["status"][str(code)] = stats["status"].get(str(code), 0) + 1120            stats["max_ms"] = max(stats["max_ms"], round(ms, 1))121            stats["slow_over_500ms"] += ms > 500122            if code != 200 and len(stats["errors"]) < 50:123                stats["errors"].append([time.strftime("%H:%M:%S"), code, u[:60]])124        time.sleep(0.004)125ts = [threading.Thread(target=work, args=(k,)) for k in range(nthreads)]126t0 = time.time()127[t.start() for t in ts]; [t.join() for t in ts]128stats["seconds"] = round(time.time() - t0)129print(json.dumps(stats, ensure_ascii=False))130
Files main
Menu

Theme