SPB Git

Repository Public

test-server.py 7.9 KB 207 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             : sdk/ios/Scripts/test-server.py11# Description      : Serveur d'essai local pour les téléchargements d'archives12#                    du SDK iOS (simulateur → 127.0.0.1).13# Module           : sdk14# Repository       : https://git.spboucher.ai/ka-maps-engine15# Created          : 2026-12-0116# Last Modified    : 2026-12-0117#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: support@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Serveur d'essai local pour les téléchargements d'archives du SDK iOS (simulateur → 127.0.0.1).9192  test-server.py <dossier> <port> [journal]9394  /<fichier>          servi normalement (plages d'octets acceptées)95  /slow/<fichier>     servi à débit limité (KAMAPS_RATE octets/s, défaut 100000), plages acceptées :96                      laisse le temps de suspendre ou de tuer l'application en cours de transfert97  /flaky/<fichier>    la PREMIÈRE demande est coupée après quelques kilo-octets (connexion fermée) ;98                      les suivantes aboutissent : reprise au « retour du réseau »99100Chaque demande est consignée dans le journal (JSON par ligne : heure, chemin, plage demandée, octets101envoyés, terminée ou non) pour prouver ce qui s'est passé pendant que l'application était arrêtée.102"""103import json104import os105import sys106import threading107import time108from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer109110ROOT = sys.argv[1]111PORT = int(sys.argv[2])112LOG = sys.argv[3] if len(sys.argv) > 3 else None113RATE = int(os.environ.get("KAMAPS_RATE", "100000"))114flaky_seen = set()115lock = threading.Lock()116117118def log(entry):119    if not LOG:120        return121    entry["t"] = round(time.time(), 3)122    with lock, open(LOG, "a") as f:123        f.write(json.dumps(entry) + "\n")124125126class Handler(BaseHTTPRequestHandler):127    protocol_version = "HTTP/1.1"128129    def log_message(self, *a):130        pass131132    def do_HEAD(self):133        self.serve(head=True)134135    def do_GET(self):136        self.serve(head=False)137138    def serve(self, head):139        path = self.path.split("?")[0]140        mode = "plain"141        for m in ("slow", "flaky"):142            if path.startswith(f"/{m}/"):143                mode, path = m, path[len(m) + 1:]144        name = os.path.basename(path)145        full = os.path.join(ROOT, name)146        if not name or not os.path.isfile(full):147            self.send_response(404)148            self.send_header("Content-Length", "0")149            self.end_headers()150            return151        size = os.path.getsize(full)152        start, end, status = 0, size - 1, 200153        rng = self.headers.get("Range")154        if rng and rng.startswith("bytes="):155            a, _, b = rng[6:].partition("-")156            start = int(a) if a else max(size - int(b), 0)157            end = int(b) if (a and b) else size - 1158            if start >= size:159                self.send_response(416)160                self.send_header("Content-Range", f"bytes */{size}")161                self.send_header("Content-Length", "0")162                self.end_headers()163                return164            end = min(end, size - 1)165            status = 206166        length = end - start + 1167        self.send_response(status)168        self.send_header("Content-Type", "application/octet-stream")169        self.send_header("Accept-Ranges", "bytes")170        self.send_header("ETag", f'"{size}-{int(os.path.getmtime(full))}"')171        self.send_header("Last-Modified", self.date_time_string(os.path.getmtime(full)))172        self.send_header("Content-Length", str(length))173        if status == 206:174            self.send_header("Content-Range", f"bytes {start}-{end}/{size}")175        self.end_headers()176        if head:177            return178        cut = mode == "flaky" and name not in flaky_seen179        if cut:180            flaky_seen.add(name)181        sent, done = 0, False182        try:183            with open(full, "rb") as f:184                f.seek(start)185                chunk = 8192 if mode != "plain" else 65536186                while sent < length:187                    data = f.read(min(chunk, length - sent))188                    if not data:189                        break190                    self.wfile.write(data)191                    self.wfile.flush()192                    sent += len(data)193                    if cut and sent >= 16384:194                        self.connection.shutdown(2)195                        self.connection.close()196                        break197                    if mode == "slow":198                        time.sleep(len(data) / RATE)199            done = sent == length200        except (BrokenPipeError, ConnectionResetError, OSError):201            pass202        log({"path": self.path, "range": rng, "status": status, "sent": sent, "length": length, "done": done, "cut": cut})203204205if __name__ == "__main__":206    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()207
Files main
Menu

Theme