bneradt commented on code in PR #14025: URL: https://github.com/apache/trafficserver/pull/14025#discussion_r4568100327
########## tools/hrw4u/src/cachekey_section.py: ########## @@ -0,0 +1,234 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The CACHEKEY section: its collected body and its lowering to REMAP rules. + +The visitor collects the section into a CacheKeySection. render() turns it into +rule sets on REMAP_PSEUDO_HOOK: one per presence check, then one with one +run-plugin cachekey.so per branch. The branches are exclusive, so exactly one +cachekey.so instance runs per request. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from typing import Final + +from antlr4 import ParserRuleContext + +from hrw4u import cachekey +from hrw4u.cachekey import CacheKeyStatement, ConflictError +from hrw4u.common import SystemDefaults +from hrw4u.errors import SymbolResolutionError +from hrw4u.states import SectionType + +# cachekey.so sorts --include-headers as strings, so the numbers are zero-padded. +KEY_HEADER_FORMAT: Final[str] = "@Hrw4u-Key-{:02d}" +MAX_KEY_PARTS: Final[int] = 99 + +HOOK_LINE: Final[str] = f"cond %{{{SectionType.CACHEKEY.hook_name}}} [AND]" +INDENT: Final[str] = " " * SystemDefaults.INDENT_SPACES + + +@dataclass(frozen=True, slots=True) +class KeyPart: + """A `cache.key += "..."` value, carried to cachekey.so in an @ header.""" + + header: str + value: str # quoted HRW string, interpolations already resolved + + +@dataclass(slots=True) +class KeyParts: + """What one cachekey.so instance keys on. + + statements is in source order, a computed part counted as its --include-headers name. + computed holds the cache.key += values, each set into its header before cachekey.so runs. + """ + + statements: list[CacheKeyStatement] = field(default_factory=list) + computed: list[KeyPart] = field(default_factory=list) + + def add_computed(self, part: KeyPart) -> None: + self.computed.append(part) + self.statements.append(CacheKeyStatement(cachekey.HEADERS_ADD_NAME, (part.header,))) + + def __add__(self, other: KeyParts) -> KeyParts: + return KeyParts(self.statements + other.statements, self.computed + other.computed) + + def plugin_lines(self, depth: int) -> list[str]: + """The set-header for each computed part, then the run-plugin cachekey.so line.""" + pad = INDENT * depth + lines = [f"{pad}set-header {part.header} {part.value}" for part in self.computed] + lines.append(pad + cachekey.render(cachekey.merge(self.statements))) + return lines + + +@dataclass(frozen=True, slots=True) +class PresenceCheck: + """One name a cache.key.*.exists statement tests, set into its @ header before the chain runs.""" + + statement: CacheKeyStatement + name: str + + @property + def presence(self) -> cachekey.Presence: + return cachekey.PRESENCE_STATEMENTS[self.statement.name] + + @property + def header(self) -> str: + return self.presence.header(self.name) + + def rule_lines(self) -> list[str]: + return [HOOK_LINE, self.presence.cond_line(self.name), f'{INDENT}set-header {self.header} "1"'] + + +class BranchKeyword(str, Enum): + IF = "if" + ELIF = "elif" + ELSE = "else" + + @property + def has_condition(self) -> bool: + return self is not BranchKeyword.ELSE + + @property + def depth(self) -> int: + """The indent level of the arm's conditions and operators: header_rewrite nests an elif's one deeper.""" + return 2 if self is BranchKeyword.ELIF else 1 + + +@dataclass(slots=True) +class Branch: + """One arm of the CACHEKEY if/elif/else chain, keyed on the shared parts plus its own.""" + + keyword: BranchKeyword + ctx: ParserRuleContext | None = None # None for the else the lowering adds + cond_lines: list[str] = field(default_factory=list) # rendered at indent 0; empty for else + parts: KeyParts = field(default_factory=KeyParts) + + +@dataclass(slots=True) +class CacheKeySection: + """The collected CACHEKEY section: parts every request keys on, and at most one chain. + + shared holds the statements outside the chain, wherever they sit. presence holds + each tested name once, keyed by its header lowercased, wherever it is tested: + setting a header no branch keys on is harmless, so the checks run outside the chain. + A statement added while a branch is open goes to that branch, else to shared. + """ + + shared: KeyParts = field(default_factory=KeyParts) + chain: list[Branch] = field(default_factory=list) + key_part_count: int = 0 + presence: dict[str, PresenceCheck] = field(default_factory=dict) + _open: Branch | None = field(default=None, init=False, repr=False) + + @contextmanager + def branch(self, keyword: BranchKeyword, ctx: ParserRuleContext) -> Iterator[Branch]: + """Append an arm to the chain and keep it open for the statements in its block. + + Raises on an arm inside an open one, or on an if when the section already has a chain. + """ + if self._open is not None: + raise SymbolResolutionError("if", "nested conditionals not allowed in CACHEKEY") + if keyword is BranchKeyword.IF and self.chain: + raise SymbolResolutionError("if", "CACHEKEY allows one if/elif/else chain") + + self._open = Branch(keyword, ctx) + self.chain.append(self._open) + try: + yield self._open + finally: + self._open = None + + def add(self, statement: CacheKeyStatement) -> None: + """Key the open branch, or every branch outside the chain, on one parsed cache.* statement.""" + if statement.name in cachekey.PRESENCE_STATEMENTS: + self._add_presence(statement) + else: + self._target.statements.append(statement) + + def add_computed(self, value: str) -> None: + """Key the open branch, or every branch, on a cache.key += value: a quoted HRW string.""" + self._target.add_computed(self._new_key_part(value)) + + @property + def _target(self) -> KeyParts: + return self._open.parts if self._open is not None else self.shared + + def _new_key_part(self, value: str) -> KeyPart: + """Number the next key part. Numbers run across the whole section, not per branch.""" + if self.key_part_count == MAX_KEY_PARTS: + raise SymbolResolutionError(cachekey.KEY_NAME, f"CACHEKEY allows at most {MAX_KEY_PARTS} cache.key += values") + self.key_part_count += 1 + return KeyPart(KEY_HEADER_FORMAT.format(self.key_part_count), value) + + def _add_presence(self, statement: CacheKeyStatement) -> None: + """Test each name in a cache.key.*.exists statement, and key on its header. + + Raises if two names need one header: header names ignore case, cookie names don't. + """ + for name in statement.items: + check = PresenceCheck(statement, name) + first = self.presence.setdefault(check.header.lower(), check) + # The prefixes differ, so a clash is two spellings of one name in one statement kind. + # Both would set one @ header, since header names ignore case. + if first.name != name and not check.presence.case_insensitive: + raise SymbolResolutionError( + statement.name, + f'{statement.name}("{name}") and {first.statement.name}("{first.name}"): ' + f"the two {check.presence.names.noun}s can't be told apart in the key", + ) + self._target.statements.append(CacheKeyStatement(cachekey.HEADERS_ADD_NAME, (first.header,), statement.source)) + + @property + def adds_else(self) -> bool: + """True if the chain has no else, so the lowering adds one that keys on the shared parts.""" + return bool(self.chain) and self.chain[-1].keyword.has_condition Review Comment: When the chain has no `else` and there are no shared parts, the synthesized `else` is `run-plugin "cachekey.so" "--key-type=cache_key,parent_selection_url"` with nothing else (see `chain-elif-not.output.txt`). That isn't a no-op: every request that matches no branch moves from the ATS default cache key (the full URL) to cachekey.so's `/host/port/path?query` form, and gets a parent selection URL it didn't have before. So `CACHEKEY { if inbound.req.Host == "api.example.com" { cache.key.cookies.add("locale"); } }` re-keys every other host on the remap, and the first deploy is a cold cache for all of them. A user converting a hand-written per-branch `run-plugin cachekey.so` would not expect that. Should the `else` only be added when `self.shared.statements` is non-empty? The docs ("so every request gets a key") would then need to say that an unmatched request keeps the default key. ########## tools/hrw4u/src/visitor.py: ########## @@ -962,6 +1008,157 @@ def visitStatement(self, ctx) -> None: # Only reachable via parser error recovery, which already reported the error. return + # CACHEKEY: collected while visiting, emitted after the last REMAP rule set. + + def _visit_cachekey_section(self, ctx: hrw4uParser.SectionContext) -> None: + if self._cachekey is not None: + with self.trap(ctx): + raise SymbolResolutionError("CACHEKEY", "CACHEKEY may only appear once") + return + + self._cachekey = cachekey_section.CacheKeySection() + self._cachekey_items(ctx.sectionBody()) + + for error in self._cachekey.conflicts(): + with self.trap(error.statement.source or ctx): + raise error + + def _cachekey_items(self, items: Sequence[hrw4uParser.SectionBodyContext | hrw4uParser.BlockItemContext]) -> None: + """Collect section or block items. Comments are dropped: the body folds into flags.""" + for item in items: + if item.conditional(): + with self.trap(item.conditional()): + self._cachekey_chain(item.conditional()) + elif item.statement(): + with self.trap(item.statement()): + self._cachekey_statement(item.statement()) + + def _cachekey_chain(self, ctx: hrw4uParser.ConditionalContext) -> None: + arms = [(BranchKeyword.IF, ctx.ifStatement()), *((BranchKeyword.ELIF, arm) for arm in ctx.elifClause())] + if ctx.elseClause(): + arms.append((BranchKeyword.ELSE, ctx.elseClause())) + + for keyword, arm in arms: + if keyword is not BranchKeyword.IF: + self._sandbox_check(arm, lambda: self._sandbox.check_language(keyword.value)) + # Opened before its condition renders, so a chain whose condition fails still counts as the one. + with self._cachekey.branch(keyword, arm) as branch: + if keyword.has_condition: + branch.cond_lines = self._render_condition(arm.condition()) + self._cachekey_items(arm.block().blockItem()) + + def _render_condition(self, cond_ctx: hrw4uParser.ConditionContext) -> list[str]: + """Compile a condition at indent 0 into its own lines, off the main output.""" + with self.detached_output() as lines: + self.visit(cond_ctx) + return lines + + def _cachekey_statement(self, ctx: hrw4uParser.StatementContext) -> None: + """Add one CACHEKEY statement to the current branch, or to the shared parts outside the chain. + + Expands procedure calls. Raises for anything that isn't a cache.* key statement. + """ + if ctx.BREAK(): + raise SymbolResolutionError( + "break", "operator 'break' not allowed in CACHEKEY: it would end the rule set before cachekey.so runs" + ) + + if ctx.functionCall(): + func = ctx.functionCall().funcName.text + if func in self._proc_registry or '::' in func: + sig, bindings = self._resolve_procedure_call(ctx.functionCall()) + with self._proc_context(sig, bindings): + self._cachekey_items(sig.body_ctx.blockItem()) + return + if cachekey.is_key_name(func): + values = ctx.functionCall().argumentList().value() if ctx.functionCall().argumentList() else [] + self._cachekey.add(cachekey.parse_statement(func, [self._cachekey_arg(value) for value in values], ctx)) + return + raise SymbolResolutionError(func, f"operator '{func}' not allowed in CACHEKEY") + + if ctx.lhs is None: + # Only reachable via parser error recovery, which already reported the error. + return + + lhs = ctx.lhs.text + if ctx.EQUAL() and cachekey.is_key_name(lhs): + self._cachekey.add(cachekey.parse_assignment(lhs, self._cachekey_arg(ctx.value()), ctx)) + return + + if ctx.PLUSEQUAL() and lhs == cachekey.KEY_NAME: + value = ctx.value() + self._check_not_bare_param(value) + if value.str_ is None: + raise SymbolResolutionError(lhs, "cache.key += takes a quoted string") + self._cachekey.add_computed(self._substitute_strings(value.getText(), ctx)) + return + + op = lhs if ctx.EQUAL() else f"{lhs} +=" + raise SymbolResolutionError(lhs, f"operator '{op}' not allowed in CACHEKEY") + + def _cachekey_arg(self, value: hrw4uParser.ValueContext) -> str: + """Source text of a value in a cache.* call or assignment, with $params substituted in a string. + + Raises for a bare $param (see _check_not_bare_param). Any other value is returned as + written, for cachekey.parse_* to reject. + """ + self._check_not_bare_param(value) + if value.str_ is not None: + return self._substitute_params(value.getText()) + return value.getText() + + @staticmethod + def _check_not_bare_param(value: hrw4uParser.ValueContext) -> None: + """Raise for a bare $param in CACHEKEY: its binding has no quotes, so it can't be a string.""" + if value.paramRef(): + name = value.paramRef().IDENT().getText() + raise SymbolResolutionError(f"${name}", f"procedure parameter '${name}' must be quoted here: write \"${name}\"") + + @classmethod + def _precedes_cachekey(cls, items: Sequence[hrw4uParser.ProgramItemContext]) -> bool: + """True if the first item that isn't a comment is the CACHEKEY section.""" + for item in items: + if not item.commentLine(): + return bool(item.section()) and cls._is_cachekey_section(item.section()) + return False + + @staticmethod + def _is_cachekey_section(section_ctx: hrw4uParser.SectionContext) -> bool: + return section_ctx.name is not None and section_ctx.name.text == SectionType.CACHEKEY + + def _check_outside_cachekey(self, ctx: hrw4uParser.StatementContext) -> None: + """Raise if a statement outside CACHEKEY breaks a CACHEKEY rule. + + cache.* key operators belong in CACHEKEY. With a CACHEKEY section, a break in REMAP would + skip it, a hand-written run-plugin cachekey.so would set the key twice, the later + instance overriding the earlier, and a write to an @Hrw4u- header would forge a key part. Review Comment: `TSCacheUrlSet()` only succeeds once per transaction, so the first cachekey.so instance to run wins for the cache key, not the later one. The docs here say "Only the first `cachekey.so` to run sets the key", which is correct. `TSHttpTxnParentSelectionUrlSet()` overwrites, though, so the last instance wins for the parent selection URL. That split matters for a case the compiler can't see: a `@plugin=cachekey.so` ahead of header_rewrite in remap.config takes the cache key, and CACHEKEY's line then sets only the parent selection URL, so the two diverge. Could you fix this comment and add a sentence to the docs about other cachekey.so instances on the same remap rule? ########## tools/hrw4u/src/cachekey_section.py: ########## @@ -0,0 +1,234 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""The CACHEKEY section: its collected body and its lowering to REMAP rules. + +The visitor collects the section into a CacheKeySection. render() turns it into +rule sets on REMAP_PSEUDO_HOOK: one per presence check, then one with one +run-plugin cachekey.so per branch. The branches are exclusive, so exactly one +cachekey.so instance runs per request. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from typing import Final + +from antlr4 import ParserRuleContext + +from hrw4u import cachekey +from hrw4u.cachekey import CacheKeyStatement, ConflictError +from hrw4u.common import SystemDefaults +from hrw4u.errors import SymbolResolutionError +from hrw4u.states import SectionType + +# cachekey.so sorts --include-headers as strings, so the numbers are zero-padded. +KEY_HEADER_FORMAT: Final[str] = "@Hrw4u-Key-{:02d}" +MAX_KEY_PARTS: Final[int] = 99 + +HOOK_LINE: Final[str] = f"cond %{{{SectionType.CACHEKEY.hook_name}}} [AND]" +INDENT: Final[str] = " " * SystemDefaults.INDENT_SPACES + + +@dataclass(frozen=True, slots=True) +class KeyPart: + """A `cache.key += "..."` value, carried to cachekey.so in an @ header.""" + + header: str + value: str # quoted HRW string, interpolations already resolved + + +@dataclass(slots=True) +class KeyParts: + """What one cachekey.so instance keys on. + + statements is in source order, a computed part counted as its --include-headers name. + computed holds the cache.key += values, each set into its header before cachekey.so runs. + """ + + statements: list[CacheKeyStatement] = field(default_factory=list) + computed: list[KeyPart] = field(default_factory=list) + + def add_computed(self, part: KeyPart) -> None: + self.computed.append(part) + self.statements.append(CacheKeyStatement(cachekey.HEADERS_ADD_NAME, (part.header,))) + + def __add__(self, other: KeyParts) -> KeyParts: + return KeyParts(self.statements + other.statements, self.computed + other.computed) + + def plugin_lines(self, depth: int) -> list[str]: + """The set-header for each computed part, then the run-plugin cachekey.so line.""" + pad = INDENT * depth + lines = [f"{pad}set-header {part.header} {part.value}" for part in self.computed] + lines.append(pad + cachekey.render(cachekey.merge(self.statements))) + return lines + + +@dataclass(frozen=True, slots=True) +class PresenceCheck: + """One name a cache.key.*.exists statement tests, set into its @ header before the chain runs.""" + + statement: CacheKeyStatement + name: str + + @property + def presence(self) -> cachekey.Presence: + return cachekey.PRESENCE_STATEMENTS[self.statement.name] + + @property + def header(self) -> str: + return self.presence.header(self.name) + + def rule_lines(self) -> list[str]: + return [HOOK_LINE, self.presence.cond_line(self.name), f'{INDENT}set-header {self.header} "1"'] + + +class BranchKeyword(str, Enum): + IF = "if" + ELIF = "elif" + ELSE = "else" + + @property + def has_condition(self) -> bool: + return self is not BranchKeyword.ELSE + + @property + def depth(self) -> int: + """The indent level of the arm's conditions and operators: header_rewrite nests an elif's one deeper.""" + return 2 if self is BranchKeyword.ELIF else 1 + + +@dataclass(slots=True) +class Branch: + """One arm of the CACHEKEY if/elif/else chain, keyed on the shared parts plus its own.""" + + keyword: BranchKeyword + ctx: ParserRuleContext | None = None # None for the else the lowering adds + cond_lines: list[str] = field(default_factory=list) # rendered at indent 0; empty for else + parts: KeyParts = field(default_factory=KeyParts) + + +@dataclass(slots=True) +class CacheKeySection: + """The collected CACHEKEY section: parts every request keys on, and at most one chain. + + shared holds the statements outside the chain, wherever they sit. presence holds + each tested name once, keyed by its header lowercased, wherever it is tested: + setting a header no branch keys on is harmless, so the checks run outside the chain. + A statement added while a branch is open goes to that branch, else to shared. + """ + + shared: KeyParts = field(default_factory=KeyParts) + chain: list[Branch] = field(default_factory=list) + key_part_count: int = 0 + presence: dict[str, PresenceCheck] = field(default_factory=dict) + _open: Branch | None = field(default=None, init=False, repr=False) + + @contextmanager + def branch(self, keyword: BranchKeyword, ctx: ParserRuleContext) -> Iterator[Branch]: + """Append an arm to the chain and keep it open for the statements in its block. + + Raises on an arm inside an open one, or on an if when the section already has a chain. + """ + if self._open is not None: + raise SymbolResolutionError("if", "nested conditionals not allowed in CACHEKEY") + if keyword is BranchKeyword.IF and self.chain: + raise SymbolResolutionError("if", "CACHEKEY allows one if/elif/else chain") + + self._open = Branch(keyword, ctx) + self.chain.append(self._open) + try: + yield self._open + finally: + self._open = None + + def add(self, statement: CacheKeyStatement) -> None: + """Key the open branch, or every branch outside the chain, on one parsed cache.* statement.""" + if statement.name in cachekey.PRESENCE_STATEMENTS: + self._add_presence(statement) + else: + self._target.statements.append(statement) + + def add_computed(self, value: str) -> None: + """Key the open branch, or every branch, on a cache.key += value: a quoted HRW string.""" + self._target.add_computed(self._new_key_part(value)) + + @property + def _target(self) -> KeyParts: + return self._open.parts if self._open is not None else self.shared + + def _new_key_part(self, value: str) -> KeyPart: + """Number the next key part. Numbers run across the whole section, not per branch.""" Review Comment: cachekey.so's `captureWholeHeaders()` adds `name:value` to the key, so the generated header name is part of the cache key. Because the numbers run across the whole section in source order, adding, removing, or moving one `cache.key +=` renumbers every one after it. For example, a new `cache.key +=` in the `if` branch above a shared one turns the shared `@Hrw4u-Key-01` into `@Hrw4u-Key-02`, which re-keys every request, including the branches nobody touched. `Presence` avoids this on purpose ("named after the name, not numbered, so editing other statements never changes the key"). Could the computed parts get stable names too, for example derived from the value expression or from an optional label? If renumbering is acceptable, the docs should at least warn that editing `cache.key +=` lines can change every key. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
