code: def maybe_compress(
      payload: bytes | bytearray | memoryview,
      *,
      min_size: int = 10_000,
      sample_size: int = 10_000,
      nsamples: int = 5,
      min_ratio: float = 0.7,
      compression: str | None | Literal[False] = "auto",
  ) -> tuple[str | None, AnyBytes]:
      """Maybe compress payload
  
      1. Don't compress payload if smaller than min_size
      2. Sample the payload in <nsamples> spots, compress those, and if it doesn't
         compress to at least <min_ratio> to the original, return the original
      3. Then compress the full original; it doesn't compress at least to <min_ratio>,
         return the original
      4. Return the compressed output
  
      Returns
      -------
      - Name of compression algorithm used
      - Either compressed or original payload
      """
      comp = compressions[compression]
      if not comp.name:
          return None, payload
      if not (min_size <= nbytes(payload) <= 2**31):
          # Either too small to bother
          # or too large (compression libraries often fail)
          return None, payload
  
      # Take a view of payload for efficient usage
      mv = ensure_memoryview(payload)
  
      # Try compressing a sample to see if it compresses well
      sample = byte_sample(mv, sample_size, nsamples)
      if len(comp.compress(sample)) <= min_ratio * sample.nbytes:
          # Try compressing the real thing and check how compressed it is
          compressed = comp.compress(mv)
          if len(compressed) <= min_ratio * mv.nbytes:
              return comp.name, compressed
      # Skip compression as the sample or the data didn't compress well
      return None, payload
  
file_path: distributed/distributed/protocol/compression.py
imports: from __future__ import annotations
  import zlib
  from collections.abc import Callable, Iterable
  from contextlib import suppress
  from functools import partial
  from random import randint
  from typing import TYPE_CHECKING, Any, Literal, NamedTuple
  from packaging.version import parse
  from tlz import identity
  import dask
  from distributed.metrics import context_meter
  from distributed.utils import ensure_memoryview, nbytes
label_desc: Use image node_id 3 for calling a global function with example usage: maybe_compress(payload) and returns: None,  payload, None,  payload, None,  payload, comp,  compressed