"""
=============================================================================
Stanford CS144 · 第 8 讲 · 02_store_forward_packet_size.py —— 存储转发和分组的长度
=============================================================================

【这个脚本要回答的问题】（讲义 §4、§5）
    路由器为什么要收完整个分组才转发？大消息为什么要切成分组？切多大？分组长度为什么要有上限？

【四部分】
    A：存储转发 vs 直通：差多少，为什么还要存储转发。
    B：切成分组有什么用：消息过 H 跳，切得越小越快吗？（模拟 + 公式）
    C：比特错误：分组太长时，一个比特错了就要重传整个分组。
    D：长分组挡住短分组：语音分组排在 1500 字节和 64 KB 的分组后面要等多久。

【运行方式】
    python3 02_store_forward_packet_size.py      # 约 1 秒，结果每次相同
"""

import math
import random

import course_path
course_path.use("lecture01")

from console import print_header, print_table, observations, si_time, si_rate, si_bytes
from hopsim import Hop, StoreForwardPath, cut_through_delay, formula_delay
from netsim import Simulator


def part_a_cut_through():
    """
    存储转发 vs 直通。

    【返回】dict：(跳数, 大小) → (存储转发, 直通)
    """
    print_header("Part A · 存储转发 vs 直通（每跳 10 Gbit/s，传播 1 µs，交换机读 64 字节就能决定转发）")
    rows = []
    out = {}
    for n_hops in (1, 3, 5):
        hops = [Hop(10e9, 1e-6)] * n_hops
        for size in (64, 1500, 9000):
            sf = formula_delay(size, hops)
            ct = cut_through_delay(size, 64, hops)
            out[(n_hops, size)] = (sf, ct)
            rows.append([n_hops, size, si_time(sf), si_time(ct), f"{sf / ct:.1f}"])
    print_table(["跳数", "分组字节", "存储转发", "直通", "倍数"], rows)
    print("\n  存储转发在每一跳都要多花一次串行化时延。那为什么大多数路由器还是存储转发？")
    print("    1. 输出链路可能比输入链路慢，或者正忙：比特必须先存起来，这时候根本没法直通。")
    print("    2. 收完才能检查校验和。直通的交换机已经把坏分组转发出去了，错误一路传下去。")
    print("    3. 不同速率的链路之间不能直通。")
    print("  直通主要用在数据中心的交换机里：链路速率相同，时延按纳秒算，错误又很少。")
    return out


def message_time_formula(message, payload, header, n_hops, rate):
    """
    切成分组之后，一条消息走过 n_hops 跳的总时间（没有传播时延）。

    【思路】每个分组（payload + header）串行化时间 T = (payload+header)·8/rate。
        第一个分组要走 n_hops 跳：n_hops·T；后面每个分组紧跟着，每个多 T（流水线）。
        总时间 = (分组数 + n_hops - 1)·T。这和 CPU 的流水线是同一个道理。
    【参数】message：消息字节数；payload：每个分组的载荷；header：头部；n_hops：跳数；rate：速率
    【返回】秒
    """
    packets = math.ceil(message / payload)
    return (packets + n_hops - 1) * (payload + header) * 8.0 / rate


def simulate_message(message, payload, header, n_hops, rate):
    """
    用模拟器跑一遍，核对公式。

    【参数】同 message_time_formula
    【返回】最后一个分组到达的时刻
    """
    sim = Simulator()
    hops = [Hop(rate, 0.0)] * n_hops
    last = []
    path = StoreForwardPath(sim, hops, on_deliver=lambda r: last.append(r.delivered_at))
    remaining = message
    while remaining > 0:
        chunk = min(payload, remaining)
        path.send(chunk + header)
        remaining -= chunk
    sim.run()
    return max(last)


def part_b_message_split():
    """
    切成分组的好处：流水线。切得太小，头部开销又上来了。

    【返回】dict：实验结果
    """
    message = 1_000_000
    header = 40
    rate = 10e6
    n_hops = 5
    print_header(f"Part B · 把 {si_bytes(message)} 的消息切成分组，走 {n_hops} 跳（每跳 {si_rate(rate)}，头部 {header} 字节，不计传播）")
    rows = []
    results = {}
    for payload in (50, 100, 200, 500, 1000, 1460, 5000, 10000, 50000, 200000, 1000000):
        formula = message_time_formula(message, payload, header, n_hops, rate)
        measured = simulate_message(message, payload, header, n_hops, rate) if payload >= 200 else None
        results[payload] = formula
        rows.append([payload, math.ceil(message / payload), si_time(formula), si_time(measured) if measured else "—（太多，没跑）"])
    print_table(["每个分组的载荷", "分组数", "公式的总时间", "模拟的总时间"], rows)
    best = min(results, key=results.get)
    # 总时间对 payload 求导等于 0 的解：payload* = sqrt(message × header / (n_hops - 1))
    optimum = math.sqrt(message * header / (n_hops - 1))
    print(f"\n  整条消息一次发（不切）：{si_time(results[1000000])}。切成 1460 字节：{si_time(results[1460])}。")
    print(f"  最优值的公式：sqrt(M·h/(H-1)) = {optimum:.0f} 字节。")
    print("  公式假设每个分组都是满的，所以最后一个分组不满时，模拟的结果会小一点点（1460 那一行）。")
    print("  为什么切开更快？不切时，每一跳都要收完整条消息，别的链路都闲着。切开之后所有链路同时工作，就像流水线。")
    print("  切得太小又不行：头部开销上来了。所以有一个最优值。")
    return dict(results=results, optimum=optimum, best=best)


def part_c_bit_errors():
    """
    分组太长：一个比特错了要重传整个分组。

    【返回】dict：比特错误率 → 最优的分组长度
    【思路】分组长 L（含头部 h）的成功率是 (1-b)^(8L)。有效吞吐量正比于 (L-h)/L × (1-b)^(8L)。
        太短：头部开销大；太长：几乎总有比特错误。
    """
    print_header("Part C · 比特错误：有效吞吐量 = (载荷占比) × (成功率)，头部 40 字节")
    header = 40
    sizes = (64, 128, 256, 576, 1500, 4000, 9000, 16000, 64000)
    rows = []
    out = {}
    for ber in (1e-12, 1e-8, 1e-6, 1e-5, 1e-4):
        row = [f"{ber:.0e}"]
        best = (0.0, 0)
        for size in sizes:
            efficiency = (size - header) / size * (1 - ber) ** (8 * size)
            row.append(f"{efficiency * 100:.1f}")
            if efficiency > best[0]:
                best = (efficiency, size)
        # 精确的最优长度：对连续的 L 搜索一遍
        fine = max(range(41, 65536, 8), key=lambda L: (L - header) / L * (1 - ber) ** (8 * L))
        out[ber] = fine
        row.append(fine)
        rows.append(row)
    print_table(["比特错误率"] + [str(s) for s in sizes] + ["最优长度（字节）"], rows)
    print("\n  表里是有效吞吐量（%）。光纤的错误率非常低，长分组几乎没有代价，所以数据中心用 9000 字节的巨帧。")
    print("  无线的错误率高得多，所以 Wi-Fi 在链路层把大帧切小、自己重传（第 16 讲）。")
    print("  以太网的 1500 字节定于 1980 年前后，常见的说法是当时内存很贵（第 13 讲）。今天它已经很难改了。")
    return out


def part_d_long_blocks_short(seed=1):
    """
    长分组挡住短分组：语音分组和大块流量共享一条链路。

    【参数】seed：随机种子
    【返回】dict：大块流量的分组大小 → 语音分组时延的 (中位数, 99%)
    【思路】1 Mbit/s 的链路，语音每 20 ms 一个 100 字节的分组，大块流量占 60% 的负载，分组大小不同。
        FIFO 队列里，语音分组最坏要等一整个长分组发完。
    """
    print_header("Part D · 长分组挡住短分组：1 Mbit/s 链路，语音 + 60% 负载的大块流量（FIFO）")
    rate = 1e6
    rows = []
    out = {}
    for big in (100, 576, 1500, 4000, 9000):
        sim = Simulator(seed=seed)
        rng = random.Random(seed)
        delays = []
        path = StoreForwardPath(sim, [Hop(rate, 0.0)], on_deliver=lambda r: delays.append(r.delivered_at - r.sent_at) if r.tag == "voice" else None)
        duration = 200.0
        for i in range(int(duration / 0.02)):
            sim.at(i * 0.02, path.send, 100, "voice")

        def bulk():
            if sim.now > duration:
                return
            path.send(big, "bulk")
            sim.after(rng.expovariate(0.6 * rate / (big * 8)), bulk)

        sim.after(0.0, bulk)
        sim.run()
        delays.sort()
        out[big] = (delays[len(delays) // 2], delays[int(len(delays) * 0.99)])
        rows.append([big, si_time(big * 8 / rate), si_time(out[big][0]), si_time(out[big][1])])
    print_table(["大块流量的分组字节", "一个分组的串行化时延", "语音时延的中位数", "语音时延的 99%"], rows)
    print("\n  负载相同（都是 60%），只是切得更大，语音的时延就翻了很多倍。慢链路上这个问题很严重。")
    print("  这就是 ATM 把信元定为 53 字节的原因之一，也是分组要有上限的又一个理由（第 9 讲的优先级是另一种解法）。")
    return out


def main():
    """运行各部分，打印结论。"""
    a = part_a_cut_through()
    b = part_b_message_split()
    c = part_c_bit_errors()
    d = part_d_long_blocks_short()

    print_header("结论")
    observations([
        f"5 跳、1500 字节：存储转发 {si_time(a[(5, 1500)][0])}，直通 {si_time(a[(5, 1500)][1])}（{a[(5, 1500)][0] / a[(5, 1500)][1]:.1f} 倍）。代价是错误会被转发，而且要求链路速率不下降。",
        f"1 MB 的消息过 5 跳：不切 {si_time(b['results'][1000000])}，切成 1460 字节 {si_time(b['results'][1460])}。这张表里最快的是 {b['best']} 字节（连续的最优值 {b['optimum']:.0f} 字节）。",
        f"比特错误率 1e-12 时最优长度 {c[1e-12]} 字节（搜索上限 65535），1e-5 时 {c[1e-5]} 字节，1e-4 时 {c[1e-4]} 字节。错误越多，分组越短。",
        f"语音时延的 99% 分位：大块流量用 100 字节的分组时 {si_time(d[100][1])}，用 9000 字节时 {si_time(d[9000][1])}。负载相同，时延差了 {d[9000][1] / d[100][1]:.0f} 倍。",
    ])


if __name__ == "__main__":
    main()
