|
| 1 | +"""Stage-based builder for ``Pipeline``. |
| 2 | +
|
| 3 | +Alternative to the dead-simple ``Pipeline(client, policies=[...])`` list |
| 4 | +constructor. Policies declare their ``STAGE``; the builder slots them into |
| 5 | +stage buckets and at ``build()`` time flattens to a list in stage order. |
| 6 | +
|
| 7 | +Pillar stages (`REDIRECT`, `RETRY`, `AUTH`, `LOGGING`, `SERDE`) admit at |
| 8 | +most one policy. A second `append` of a pillar raises by default — use |
| 9 | +``replace(target, new)`` for explicit swaps or ``append(p, force=True)`` |
| 10 | +for the rare legitimate use case (test fixtures, runtime composition). |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from typing import TYPE_CHECKING, Self |
| 16 | + |
| 17 | +from .pipeline import Pipeline |
| 18 | +from .policy import Policy |
| 19 | +from .stage import Stage |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from ..client.http_client import HttpClient |
| 23 | + |
| 24 | + |
| 25 | +class StagedPipelineBuilder: |
| 26 | + """Build a :class:`Pipeline` by stage rather than user-specified order. |
| 27 | +
|
| 28 | + Surgical edits (``replace`` / ``insert_after`` / ``insert_before`` / |
| 29 | + ``remove``) take a policy *type* and operate on the first matching |
| 30 | + instance — useful for tweaking an already-built pipeline obtained via |
| 31 | + :meth:`from_pipeline`. |
| 32 | +
|
| 33 | + Thread-safety: not thread-safe. Construct on one thread, then call |
| 34 | + :meth:`build` — the resulting :class:`Pipeline` is independent. |
| 35 | + """ |
| 36 | + |
| 37 | + __slots__ = ("_buckets", "_client", "_pillars") |
| 38 | + |
| 39 | + def __init__(self, client: HttpClient) -> None: |
| 40 | + self._client = client |
| 41 | + self._pillars: dict[Stage, Policy] = {} |
| 42 | + self._buckets: dict[Stage, list[Policy]] = {} |
| 43 | + |
| 44 | + def append(self, policy: Policy, *, force: bool = False) -> Self: |
| 45 | + """Append ``policy`` to the tail of its stage's bucket. |
| 46 | +
|
| 47 | + Args: |
| 48 | + policy: Concrete policy declaring ``STAGE: ClassVar[Stage]``. |
| 49 | + force: When the policy's stage is a pillar and another policy |
| 50 | + already occupies it, ``force=True`` silently overwrites. |
| 51 | + Default is to raise ``ValueError`` so accidental double-fills |
| 52 | + surface immediately. |
| 53 | +
|
| 54 | + Returns: |
| 55 | + ``self`` for chaining. |
| 56 | +
|
| 57 | + Raises: |
| 58 | + ValueError: When ``policy.STAGE`` is a pillar already filled |
| 59 | + and ``force`` is False. |
| 60 | + """ |
| 61 | + stage = policy.STAGE |
| 62 | + if stage.is_pillar: |
| 63 | + self._install_pillar(policy, stage, force=force) |
| 64 | + else: |
| 65 | + self._buckets.setdefault(stage, []).append(policy) |
| 66 | + return self |
| 67 | + |
| 68 | + def prepend(self, policy: Policy, *, force: bool = False) -> Self: |
| 69 | + """Prepend ``policy`` to the head of its stage's bucket. |
| 70 | +
|
| 71 | + Pillar behaviour mirrors :meth:`append`. |
| 72 | + """ |
| 73 | + stage = policy.STAGE |
| 74 | + if stage.is_pillar: |
| 75 | + self._install_pillar(policy, stage, force=force) |
| 76 | + else: |
| 77 | + self._buckets.setdefault(stage, []).insert(0, policy) |
| 78 | + return self |
| 79 | + |
| 80 | + def replace(self, target: type[Policy], new: Policy) -> Self: |
| 81 | + """Replace the first instance of ``target`` with ``new``. |
| 82 | +
|
| 83 | + The replacement is by-type, so ``replace(RetryPolicy, custom)`` |
| 84 | + swaps the existing retry policy regardless of whether it sits in |
| 85 | + the pillar slot or a non-pillar bucket. |
| 86 | +
|
| 87 | + Args: |
| 88 | + target: Type whose first matching instance is replaced. |
| 89 | + new: Replacement policy. Must declare a ``STAGE`` — typically |
| 90 | + the same stage as ``target`` but not enforced. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + ``self`` for chaining. |
| 94 | +
|
| 95 | + Raises: |
| 96 | + ValueError: If no instance of ``target`` exists in the builder. |
| 97 | + """ |
| 98 | + for stage, pillar in self._pillars.items(): |
| 99 | + if isinstance(pillar, target): |
| 100 | + # Install new at its declared stage; remove the old pillar. |
| 101 | + del self._pillars[stage] |
| 102 | + self.append(new, force=True) |
| 103 | + return self |
| 104 | + for stage, bucket in self._buckets.items(): |
| 105 | + for i, p in enumerate(bucket): |
| 106 | + if isinstance(p, target): |
| 107 | + if stage == new.STAGE: |
| 108 | + bucket[i] = new |
| 109 | + else: |
| 110 | + del bucket[i] |
| 111 | + self.append(new) |
| 112 | + return self |
| 113 | + raise ValueError(f"No instance of {target.__name__} in the builder.") |
| 114 | + |
| 115 | + def insert_after(self, target: type[Policy], new: Policy) -> Self: |
| 116 | + """Insert ``new`` immediately after the first ``target`` instance.""" |
| 117 | + return self._splice(target, new, offset=1) |
| 118 | + |
| 119 | + def insert_before(self, target: type[Policy], new: Policy) -> Self: |
| 120 | + """Insert ``new`` immediately before the first ``target`` instance.""" |
| 121 | + return self._splice(target, new, offset=0) |
| 122 | + |
| 123 | + def remove(self, target: type[Policy]) -> Self: |
| 124 | + """Remove every instance of ``target`` from the builder. No-op if absent.""" |
| 125 | + self._pillars = {s: p for s, p in self._pillars.items() if not isinstance(p, target)} |
| 126 | + for stage in list(self._buckets): |
| 127 | + self._buckets[stage] = [p for p in self._buckets[stage] if not isinstance(p, target)] |
| 128 | + if not self._buckets[stage]: |
| 129 | + del self._buckets[stage] |
| 130 | + return self |
| 131 | + |
| 132 | + def build(self) -> Pipeline: |
| 133 | + """Flatten the builder's contents into a :class:`Pipeline`.""" |
| 134 | + return Pipeline(self._client, policies=self._flatten()) |
| 135 | + |
| 136 | + @classmethod |
| 137 | + def from_pipeline(cls, pipeline: Pipeline) -> Self: |
| 138 | + """Seed a builder from an existing :class:`Pipeline`'s policies. |
| 139 | +
|
| 140 | + Walks the pipeline's policy chain (skipping the internal transport |
| 141 | + runner) and re-slots each policy into its declared stage. Useful |
| 142 | + for "build a default pipeline, then surgically swap one piece" |
| 143 | + workflows. |
| 144 | +
|
| 145 | + Raises: |
| 146 | + ValueError: If the input pipeline's policies do not satisfy |
| 147 | + stage ordering — i.e. their declared stages do not appear |
| 148 | + in non-decreasing order in the chain. |
| 149 | + """ |
| 150 | + from ._transport_runner import _TransportRunner |
| 151 | + |
| 152 | + builder = cls(pipeline.transport) |
| 153 | + chain: list[Policy] = [] |
| 154 | + node: Policy | None = pipeline._chain |
| 155 | + while node is not None and not isinstance(node, _TransportRunner): |
| 156 | + chain.append(node) |
| 157 | + node = getattr(node, "next", None) |
| 158 | + last_stage: Stage | None = None |
| 159 | + for policy in chain: |
| 160 | + if last_stage is not None and last_stage > policy.STAGE: |
| 161 | + raise ValueError( |
| 162 | + f"Pipeline policy {type(policy).__name__} at stage {policy.STAGE} " |
| 163 | + f"comes after stage {last_stage}; staged builder requires " |
| 164 | + f"non-decreasing stage order. Use the list constructor instead." |
| 165 | + ) |
| 166 | + last_stage = policy.STAGE |
| 167 | + builder.append(policy, force=True) |
| 168 | + return builder |
| 169 | + |
| 170 | + def _install_pillar(self, policy: Policy, stage: Stage, *, force: bool) -> None: |
| 171 | + if stage in self._pillars and not force: |
| 172 | + existing = type(self._pillars[stage]).__name__ |
| 173 | + raise ValueError( |
| 174 | + f"Pillar stage {stage.name} is already filled by {existing}. " |
| 175 | + f"Use replace({type(policy).__name__}, new) to swap, or " |
| 176 | + f"force=True to overwrite." |
| 177 | + ) |
| 178 | + self._pillars[stage] = policy |
| 179 | + |
| 180 | + def _splice(self, target: type[Policy], new: Policy, *, offset: int) -> Self: |
| 181 | + # Splice operates on the flattened order; the result is re-bucketed. |
| 182 | + flat = self._flatten() |
| 183 | + for i, p in enumerate(flat): |
| 184 | + if isinstance(p, target): |
| 185 | + flat.insert(i + offset, new) |
| 186 | + self._reload(flat) |
| 187 | + return self |
| 188 | + raise ValueError(f"No instance of {target.__name__} in the builder.") |
| 189 | + |
| 190 | + def _flatten(self) -> list[Policy]: |
| 191 | + out: list[Policy] = [] |
| 192 | + for stage in Stage: |
| 193 | + if stage is Stage.SEND: |
| 194 | + continue # terminal — reserved for the transport |
| 195 | + if stage.is_pillar: |
| 196 | + if stage in self._pillars: |
| 197 | + out.append(self._pillars[stage]) |
| 198 | + else: |
| 199 | + out.extend(self._buckets.get(stage, ())) |
| 200 | + return out |
| 201 | + |
| 202 | + def _reload(self, policies: list[Policy]) -> None: |
| 203 | + self._pillars.clear() |
| 204 | + self._buckets.clear() |
| 205 | + for p in policies: |
| 206 | + if p.STAGE.is_pillar: |
| 207 | + self._pillars[p.STAGE] = p |
| 208 | + else: |
| 209 | + self._buckets.setdefault(p.STAGE, []).append(p) |
| 210 | + |
| 211 | + |
| 212 | +__all__ = ["StagedPipelineBuilder"] |
0 commit comments