"""Small stdlib-only output utility, safe to import during core bootstrap."""

import os
import sys


def drop_output_nobody_reads(*, logger=None) -> None:
    """Flush stdout/stderr, discarding output only when its reader is gone.

    Used before the interpreter's final flush and before forking workers.
    The fork start method flushes both streams before every fork and lets an
    OSError out of submit(). Under systemd they are the agent's stream to the
    journal; once its reader is gone (journald was stopped; a journald
    restart keeps the stream), a line waiting in their buffer fails every
    worker the agent starts, and a failed flush keeps the line, so it never
    recovers. Nothing written there can be delivered any more: point the
    descriptor at /dev/null, which drains the buffer and keeps later writes
    from raising.
    """
    for name in ("stdout", "stderr"):
        stream = getattr(sys, name, None)
        try:
            stream.flush()
            continue
        except BrokenPipeError:
            pass
        except (AttributeError, ValueError, OSError):
            # Not a lost reader: leave normal error handling unchanged.
            continue
        try:
            devnull = os.open(os.devnull, os.O_WRONLY)
            try:
                os.dup2(devnull, stream.fileno())
            finally:
                os.close(devnull)
            stream.flush()
        except (AttributeError, ValueError, OSError):
            continue
        if logger is not None:
            logger.warning(
                "The reader of sys.%s is gone; its output is dropped from"
                " now on",
                name,
            )
