展示 HN:通过示例学习 CEL
Show HN: CEL by Example

原始链接: https://celbyexample.com/

## 通用表达式语言 (CEL) 总结 CEL 是一种快速、可移植且安全的语言,用于评估表达式与数据(如 Protobuf 消息或 JSON 对象)的匹配情况。它被用于 Kubernetes 和 Google Cloud IAM 等重要系统中。 CEL 支持基本数据类型(字符串、数字)和操作,如比较和字符串函数。它擅长使用 `in`(成员资格)、`exists`(任何匹配)和 `filter`(缩小列表)等函数处理 **集合**。**时间戳和时长** 本身就得到原生处理,用于基于时间的逻辑。 表达式可以与 **逻辑运算符** (`&&`, `||`) 和条件逻辑 (`? :`) 结合使用。重要的是,CEL 允许 **数据转换** – 基于条件创建新的数据结构,如映射和列表。`map` 等函数能够实现强大的操作,包括同时过滤和修改集合元素。 最终,CEL 提供了一种安全高效的方式来定义基于数据的动态规则和策略。

## CEL 示例:总结 这次黑客新闻讨论围绕 CEL(通用表达式语言),这是一种设计用于在应用程序中嵌入计算的语言,尤其适用于策略决策和数据过滤。用户强调 CEL 的优势在于提供了一种定义明确、速度合理且*安全*可嵌入的语言——避免了通常在使用更通用的语言时发现的临时实现的陷阱。 关键点包括:CEL 的非图灵完备性是故意的,旨在保证终止和可预测的性能(微秒级评估时间)。虽然不如 Rego(OPA 使用)等替代方案强大,但 CEL 在更简单、程序化的逻辑方面表现出色。它被用于 Kubernetes 的验证规则和 FHIR 的路径表达式。 一个核心优势是它可以进行静态分析以进行成本估算,从而允许开发人员在运行时*之前*拒绝潜在的昂贵表达式。这与图灵完备的语言形成对比,在图灵完备的语言中,保证终止或限制执行时间是困难的。CEL 并非旨在成为通用的配置语言,而是用于更大系统中的受限表达式。
相关文章

原文

CEL (Common Expression Language) evaluates expressions against data—simple values, a Protobuf message, or a JSON object.

CEL's fast, portable, and safe: it's used in Kubernetes admission control, Google Cloud IAM conditions, Firebase security rules, Envoy Proxy routing, and Protovalidate's constraint rules.

Let's explore CEL together, starting with a simple User message:

Strings and numbers

A basic comparison: is the user over 18?

Check the user's email domain with a string function.

Collections

Does the user have a specific role? in checks membership in a list.

What if the match isn't exact? exists() tests whether any element satisfies a condition.

The user has three roles—what if we only want the elevated ones? filter() narrows a list to matching elements.

Timestamps and durations

Did the user verify their email within 24 hours of signing up? CEL handles time natively—subtract two timestamps to get a duration, then compare.

Logical operators

Logical operators combine checks into a single expression.

The conditional operator allows branching logic.

Transforming data

CEL expressions return any type. Build a map that strips PII from the user.

Annotate each role with whether it's elevated. map() transforms a collection into a new one.

map() can also filter—select elevated roles and grant write access in one step.

联系我们 contact @ memedata.com