Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14593] feat(client-python): add policy API types and DTOs (#14544)

karmendra838663d4da6d23d1
diff --git a/clients/client-python/gravitino/api/authorization/privileges.py b/clients/client-python/gravitino/api/authorization/privileges.py
index c368167a46..ed2fb80271 100644
--- a/clients/client-python/gravitino/api/authorization/privileges.py
+++ b/clients/client-python/gravitino/api/authorization/privileges.py
@@ -198,6 +198,9 @@ class Privilege(ABC):
MODIFY_FUNCTION = (0, 1 << 32)
"""The privilege to alter a function's metadata."""
+ PROBE_TABLE_LIKE = (0, 1 << 33)
+ """The privilege to probe whether a table-like object exists."""
+
VIEW_SECRET_PROVIDERS = (0, 1 << 36)
"""The privilege to list configured secrets providers."""
@@ -1666,6 +1669,46 @@ class ModifyFunction(GenericPrivilege):
return obj_type in Privileges.FUNCTION_SUPPORTED_TYPES
+class ProbeTableLike(GenericPrivilege):
+ """
+ The privilege to probe whether a table-like object exists.
+ """
+
+ _ALLOW_INSTANCE: Optional[ProbeTableLike] = None
+ _DENY_INSTANCE: Optional[ProbeTableLike] = None
+
+ @staticmethod
+ def allow() -> ProbeTableLike:
+ """
+ Retrieve the instance with allow condition of the privilege.
+
+ Returns:
+ Privilege: The instance with allow condition of the privilege.
+ """
+ if ProbeTableLike._ALLOW_INSTANCE is None:
+ ProbeTableLike._ALLOW_INSTANCE = ProbeTableLike(
+ Privilege.Condition.ALLOW, Privilege.Name.PROBE_TABLE_LIKE
+ )
+ return ProbeTableLike._ALLOW_INSTANCE
+
+ @staticmethod
+ def deny() -> ProbeTableLike:
+ """
+ Retrieve the instance with deny condition of the privilege.
+
+ Returns:
+ Privilege: The instance with deny condition of the privilege.
+ """
+ if ProbeTableLike._DENY_INSTANCE is None:
+ ProbeTableLike._DENY_INSTANCE = ProbeTableLike(
+ Privilege.Condition.DENY, Privilege.Name.PROBE_TABLE_LIKE
+ )
+ return ProbeTableLike._DENY_INSTANCE
+
+ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:
+ return obj_type in Privileges.TABLE_LIKE_SUPPORTED_TYPES
+
+
class CreateSemanticModel(GenericPrivilege):
"""The privilege to create a Semantic Model."""
@@ -1865,6 +1908,7 @@ class Privileges:
Privilege.Name.REGISTER_FUNCTION: RegisterFunction,
Privilege.Name.EXECUTE_FUNCTION: ExecuteFunction,
Privilege.Name.MODIFY_FUNCTION: ModifyFunction,
+ Privilege.Name.PROBE_TABLE_LIKE: ProbeTableLike,
Privilege.Name.CREATE_SEMANTIC_MODEL: CreateSemanticModel,
Privilege.Name.USE_SEMANTIC_MODEL: UseSemanticModel,
Privilege.Name.MODIFY_SEMANTIC_MODEL: ModifySemanticModel,
@@ -1878,6 +1922,13 @@ class Privileges:
MetadataObject.Type.SCHEMA,
MetadataObject.Type.TABLE,
}
+ TABLE_LIKE_SUPPORTED_TYPES = {
+ MetadataObject.Type.METALAKE,
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ MetadataObject.Type.VIEW,
+ }
MODEL_SUPPORTED_TYPES = {
MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG,
diff --git a/clients/client-python/gravitino/api/policy/__init__.py b/clients/client-python/gravitino/api/policy/__init__.py
new file mode 100644
index 0000000000..e181ce507d
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/__init__.py
@@ -0,0 +1,56 @@
+# 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.
+
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_change import PolicyChange
+from gravitino.api.policy.policy_content import (
+ AccessControlContent,
+ ColumnMaskContent,
+ ExecutablePolicyContent,
+ IcebergDataCompactionContent,
+ IcebergOrphanFileRemovalContent,
+ IcebergRewriteManifestsContent,
+ IcebergSnapshotExpirationContent,
+ PolicyContent,
+ PolicyExecutionSpec,
+ RowFilterContent,
+)
+from gravitino.api.policy.policy_contents import PolicyContents
+from gravitino.api.policy.policy_list import PolicyList
+from gravitino.api.policy.policy_operations import PolicyOperations
+from gravitino.api.policy.policy_tag_association import PolicyTagAssociation
+from gravitino.api.policy.supports_policies import SupportsPolicies
+
+__all__ = [
+ "AccessControlContent",
+ "ColumnMaskContent",
+ "ExecutablePolicyContent",
+ "IcebergDataCompactionContent",
+ "IcebergOrphanFileRemovalContent",
+ "IcebergRewriteManifestsContent",
+ "IcebergSnapshotExpirationContent",
+ "Policy",
+ "PolicyChange",
+ "PolicyContent",
+ "PolicyContents",
+ "PolicyExecutionSpec",
+ "PolicyList",
+ "PolicyOperations",
+ "PolicyTagAssociation",
+ "RowFilterContent",
+ "SupportsPolicies",
+]
diff --git a/clients/client-python/gravitino/api/policy/policy.py b/clients/client-python/gravitino/api/policy/policy.py
new file mode 100644
index 0000000000..c8433644f7
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy.py
@@ -0,0 +1,181 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import abstractmethod
+from enum import Enum
+
+from gravitino.api.auditable import Auditable
+from gravitino.api.policy.policy_content import (
+ AccessControlContent,
+ ColumnMaskContent,
+ IcebergDataCompactionContent,
+ IcebergOrphanFileRemovalContent,
+ IcebergRewriteManifestsContent,
+ IcebergSnapshotExpirationContent,
+ PolicyContent,
+ RowFilterContent,
+)
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+class Policy(Auditable):
+ """A policy is a set of rules that can be associated with a set of
+ metadata objects, used for data governance such as data access control
+ and data retention.
+
+ A policy is uniquely identified by its name within a metalake.
+ """
+
+ BUILT_IN_TYPE_PREFIX = "system_"
+
+ @abstractmethod
+ def name(self) -> str:
+ """The name of the policy.
+
+ Returns:
+ str: The name of the policy.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def policy_type(self) -> str:
+ """The type of the policy, for example ``system_access_control`` for
+ built-in policies, or ``custom`` for user-defined policies. Built-in
+ policy types are defined in :class:`Policy.BuiltInType`.
+
+ Returns:
+ str: The type of the policy.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def comment(self) -> str | None:
+ """The comment of the policy.
+
+ Returns:
+ Optional[str]: The comment of the policy, None if not set.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def enabled(self) -> bool:
+ """Whether the policy is enabled.
+
+ Returns:
+ bool: True if the policy is enabled, False otherwise.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def content(self) -> PolicyContent:
+ """The content of the policy: the rules plus the object types and
+ properties that describe them. The concrete class of the content is
+ determined by the policy type.
+
+ Returns:
+ PolicyContent: The content of the policy.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def inherited(self) -> bool | None:
+ """Whether this policy is inherited from a parent metadata object,
+ when the policy is retrieved in the context of a metadata object.
+
+ Returns:
+ Optional[bool]: True if the policy is inherited, False if it is
+ directly associated, None if the inheritance information is
+ not applicable or not available.
+ """
+ raise NotImplementedError()
+
+ class BuiltInType(Enum):
+ """The built-in policy types, each paired with the content class that
+ carries its rules."""
+
+ ICEBERG_COMPACTION = (
+ "system_iceberg_compaction",
+ IcebergDataCompactionContent,
+ )
+ ICEBERG_ORPHAN_FILE_REMOVAL = (
+ "system_iceberg_orphan_file_removal",
+ IcebergOrphanFileRemovalContent,
+ )
+ ICEBERG_REWRITE_MANIFESTS = (
+ "system_iceberg_rewrite_manifests",
+ IcebergRewriteManifestsContent,
+ )
+ ICEBERG_SNAPSHOT_EXPIRATION = (
+ "system_iceberg_snapshot_expiration",
+ IcebergSnapshotExpirationContent,
+ )
+ ROW_FILTER = ("system_row_filter", RowFilterContent)
+ COLUMN_MASK = ("system_column_mask", ColumnMaskContent)
+ ACCESS_CONTROL = ("system_access_control", AccessControlContent)
+ # The content class of CUSTOM is PolicyContents.CustomContent; it is
+ # resolved lazily to avoid a circular import.
+ CUSTOM = ("custom", None)
+
+ def __init__(self, policy_type: str, content_class: type | None):
+ self._policy_type = policy_type
+ self._content_class = content_class
+
+ def policy_type(self) -> str:
+ """Returns the wire policy type string."""
+ return self._policy_type
+
+ def content_class(self) -> type[PolicyContent]:
+ """Returns the content class associated with this type."""
+ if self._content_class is not None:
+ return self._content_class
+ # Late import: policy_contents imports this module's Policy only
+ # for typing, but CustomContent lives there.
+ from gravitino.api.policy.policy_contents import ( # pylint: disable=import-outside-toplevel
+ PolicyContents,
+ )
+
+ return PolicyContents.CustomContent
+
+ @staticmethod
+ def from_policy_type(policy_type: str) -> Policy.BuiltInType:
+ """Resolves a policy type string to a built-in type.
+
+ Args:
+ policy_type: The policy type string.
+
+ Returns:
+ Policy.BuiltInType: The matching built-in type.
+
+ Raises:
+ IllegalArgumentException: If the policy type is null, is a
+ ``system_``-prefixed type that is not a known built-in
+ type, or cannot be mapped to a built-in type.
+ """
+ if policy_type is None:
+ raise IllegalArgumentException("Policy type cannot be null")
+ for built_in_type in Policy.BuiltInType:
+ if built_in_type.policy_type().lower() == policy_type.lower():
+ return built_in_type
+ if policy_type.lower().startswith(Policy.BUILT_IN_TYPE_PREFIX):
+ raise IllegalArgumentException(
+ f"Unknown built-in policy type: {policy_type}"
+ )
+ raise IllegalArgumentException(
+ f"Can't map policy type: {policy_type} to any built-in policy type"
+ )
diff --git a/clients/client-python/gravitino/api/policy/policy_association_selector.py b/clients/client-python/gravitino/api/policy/policy_association_selector.py
new file mode 100644
index 0000000000..d194c4c219
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_association_selector.py
@@ -0,0 +1,101 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+class PolicyAssociationSelector(ABC):
+ """Selects which tag assignments a policy association applies to."""
+
+ @abstractmethod
+ def type(self) -> str:
+ """Returns the selector type."""
+ raise NotImplementedError()
+
+
+class AllValuesSelector(PolicyAssociationSelector):
+ """A selector that applies the policy association to all values of the
+ tag."""
+
+ TYPE = "ALL_VALUES"
+
+ _INSTANCE = None
+
+ @staticmethod
+ def get() -> AllValuesSelector:
+ """Returns the singleton all-values selector."""
+ if AllValuesSelector._INSTANCE is None:
+ AllValuesSelector._INSTANCE = AllValuesSelector()
+ return AllValuesSelector._INSTANCE
+
+ def type(self) -> str:
+ return self.TYPE
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, AllValuesSelector)
+
+ def __hash__(self) -> int:
+ return hash(self.TYPE)
+
+ def __repr__(self) -> str:
+ return "AllValuesSelector{}"
+
+
+class TagValueSelector(PolicyAssociationSelector):
+ """A selector that applies the policy association to one specific value
+ of the tag."""
+
+ TYPE = "TAG_VALUE"
+
+ def __init__(self, value: str):
+ if value is None or value.strip() == "":
+ raise IllegalArgumentException("tag value cannot be blank")
+ self._value = value
+
+ @staticmethod
+ def of(value: str) -> TagValueSelector:
+ """Creates a selector for the given tag value.
+
+ Args:
+ value: The tag value the association applies to.
+
+ Returns:
+ TagValueSelector: The selector.
+ """
+ return TagValueSelector(value)
+
+ def type(self) -> str:
+ return self.TYPE
+
+ def value(self) -> str:
+ """Returns the tag value this selector applies to."""
+ return self._value
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, TagValueSelector):
+ return False
+ return self._value == other._value
+
+ def __hash__(self) -> int:
+ return hash(self._value)
+
+ def __repr__(self) -> str:
+ return f"TagValueSelector{{value='{self._value}'}}"
diff --git a/clients/client-python/gravitino/api/policy/policy_change.py b/clients/client-python/gravitino/api/policy/policy_change.py
new file mode 100644
index 0000000000..b724c21d98
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_change.py
@@ -0,0 +1,115 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import ABC
+from dataclasses import dataclass
+
+from gravitino.api.policy.policy_content import PolicyContent
+
+
+class PolicyChange(ABC):
+ """
+ A policy change is a change to a policy. It can be a rename, a comment
+ update, or a content update. A policy change is used to modify a policy
+ in the metalake, together with other policy changes in a single request.
+ """
+
+ @staticmethod
+ def rename(new_name: str) -> PolicyChange:
+ """Creates a new policy change to rename a policy.
+
+ Args:
+ new_name: The new name of the policy.
+
+ Returns:
+ PolicyChange: The policy change.
+ """
+ return PolicyChange.RenamePolicy(new_name)
+
+ @staticmethod
+ def update_comment(new_comment: str) -> PolicyChange:
+ """Creates a new policy change to update the comment of a policy.
+
+ Args:
+ new_comment: The new comment of the policy.
+
+ Returns:
+ PolicyChange: The policy change.
+ """
+ return PolicyChange.UpdatePolicyComment(new_comment)
+
+ @staticmethod
+ def update_content(policy_type: str, content: PolicyContent) -> PolicyChange:
+ """Creates a new policy change to update the content of a policy.
+
+ Args:
+ policy_type: The type of the policy.
+ content: The new content of the policy.
+
+ Returns:
+ PolicyChange: The policy change.
+ """
+ return PolicyChange.UpdateContent(policy_type, content)
+
+ @dataclass(frozen=True, eq=True)
+ class RenamePolicy:
+ """A policy change to rename a policy."""
+
+ _new_name: str
+
+ @property
+ def new_name(self) -> str:
+ return self._new_name
+
+ def __str__(self) -> str:
+ return f"RENAME POLICY {self._new_name}"
+
+ @dataclass(frozen=True, eq=True)
+ class UpdatePolicyComment:
+ """A policy change to update the comment of a policy."""
+
+ _new_comment: str
+
+ @property
+ def new_comment(self) -> str:
+ return self._new_comment
+
+ def __str__(self) -> str:
+ return f"UPDATE POLICY COMMENT {self._new_comment}"
+
+ @dataclass(frozen=True, eq=True)
+ class UpdateContent:
+ """A policy change to update the type and content of a policy."""
+
+ _policy_type: str
+ _content: PolicyContent
+
+ @property
+ def policy_type(self) -> str:
+ return self._policy_type
+
+ @property
+ def content(self) -> PolicyContent:
+ return self._content
+
+ def __str__(self) -> str:
+ return (
+ f"UPDATE POLICY CONTENT policyType={self._policy_type}, "
+ f"content={self._content}"
+ )
diff --git a/clients/client-python/gravitino/api/policy/policy_content.py b/clients/client-python/gravitino/api/policy/policy_content.py
new file mode 100644
index 0000000000..467a5d9574
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_content.py
@@ -0,0 +1,1163 @@
+# 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.
+
+# pylint: disable=too-many-lines
+
+from __future__ import annotations
+
+import re
+from abc import ABC, abstractmethod
+from typing import ClassVar
+
+from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.exceptions.base import (
+ IllegalArgumentException,
+ UnsupportedOperationException,
+)
+
+
+class PolicyExecutionSpec:
+ """Immutable maintenance execution peers for executable policy contents.
+
+ Every peer is optional: a spec with every peer unset is the empty spec.
+ """
+
+ def __init__(
+ self,
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ):
+ normalized_time_trigger = (
+ time_trigger
+ if time_trigger is not None and time_trigger.strip() != ""
+ else None
+ )
+ normalized_job_options = dict(job_options) if job_options else {}
+ normalized_updater_options = dict(updater_options) if updater_options else {}
+ if min_interval_ms is not None and min_interval_ms < 0:
+ raise IllegalArgumentException("minIntervalMs must be >= 0")
+ self._validate_option_map(normalized_job_options, "jobOptions")
+ self._validate_option_map(normalized_updater_options, "updaterOptions")
+ self._time_trigger = normalized_time_trigger
+ self._commit_trigger = commit_trigger
+ self._min_interval_ms = min_interval_ms
+ self._job_options = normalized_job_options
+ self._updater_options = normalized_updater_options
+
+ @staticmethod
+ def of(
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ) -> PolicyExecutionSpec:
+ """Creates an immutable execution spec.
+
+ Args:
+ time_trigger: Optional cron expression.
+ commit_trigger: Optional commit-trigger flag; any non-None value
+ (including False) is retained.
+ min_interval_ms: Optional cooldown in milliseconds.
+ job_options: Optional job options.
+ updater_options: Optional updater options.
+
+ Returns:
+ PolicyExecutionSpec: The execution spec, or the empty spec when
+ every peer is unset.
+
+ Raises:
+ IllegalArgumentException: If min_interval_ms is negative or an
+ option map has a blank key or value.
+ """
+ spec = PolicyExecutionSpec(
+ time_trigger,
+ commit_trigger,
+ min_interval_ms,
+ job_options,
+ updater_options,
+ )
+ return spec if spec.has_any() else PolicyExecutionSpec.empty()
+
+ @staticmethod
+ def empty() -> PolicyExecutionSpec:
+ """Returns the spec with every peer unset."""
+ return _EMPTY_SPEC
+
+ def time_trigger(self) -> str | None:
+ """Returns the cron expression, or None when unset."""
+ return self._time_trigger
+
+ def commit_trigger(self) -> bool | None:
+ """Returns the commit-trigger flag when explicitly supplied (including
+ False), or None when unset."""
+ return self._commit_trigger
+
+ def min_interval_ms(self) -> int | None:
+ """Returns the minimum interval in milliseconds, or None when unset."""
+ return self._min_interval_ms
+
+ def job_options(self) -> dict[str, str]:
+ """Returns the job options; never None."""
+ return dict(self._job_options)
+
+ def updater_options(self) -> dict[str, str]:
+ """Returns the updater options; never None."""
+ return dict(self._updater_options)
+
+ def has_any(self) -> bool:
+ """Returns True when any peer is set."""
+ return (
+ (self._time_trigger is not None and self._time_trigger.strip() != "")
+ or self._commit_trigger is not None
+ or self._min_interval_ms is not None
+ or len(self._job_options) > 0
+ or len(self._updater_options) > 0
+ )
+
+ @staticmethod
+ def _validate_option_map(options: dict[str, str], map_name: str) -> None:
+ for key, value in options.items():
+ if key is None or key.strip() == "":
+ raise IllegalArgumentException(f"{map_name} key is blank")
+ if value is None or value.strip() == "":
+ raise IllegalArgumentException(
+ f"{map_name} '{key}' must have non-empty value"
+ )
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, PolicyExecutionSpec):
+ return False
+ return (
+ self._time_trigger == other._time_trigger
+ and self._commit_trigger == other._commit_trigger
+ and self._min_interval_ms == other._min_interval_ms
+ and self._job_options == other._job_options
+ and self._updater_options == other._updater_options
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._time_trigger,
+ self._commit_trigger,
+ self._min_interval_ms,
+ frozenset(self._job_options.items()),
+ frozenset(self._updater_options.items()),
+ )
+ )
+
+ def __repr__(self) -> str:
+ # Never render option map values; credentials may appear in them.
+ return (
+ f"PolicyExecutionSpec{{timeTrigger='{self._time_trigger}', "
+ f"commitTrigger={self._commit_trigger}, "
+ f"minIntervalMs={self._min_interval_ms}, "
+ f"jobOptionsKeys={sorted(self._job_options.keys())}, "
+ f"updaterOptionsKeys={sorted(self._updater_options.keys())}}}"
+ )
+
+
+_EMPTY_SPEC = PolicyExecutionSpec()
+
+
+class PolicyContent(ABC):
+ """The content of a policy: the rules plus the object types and properties
+ that describe them."""
+
+ @abstractmethod
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ """Returns the set of metadata object types that the policy can be
+ applied to."""
+ raise NotImplementedError()
+
+ @abstractmethod
+ def properties(self) -> dict[str, str]:
+ """Returns the additional properties of the policy."""
+ raise NotImplementedError()
+
+ def rules(self) -> dict[str, object]:
+ """Returns all rules in the policy content, as a map of rule names to
+ their corresponding rule objects."""
+ # backward compatibility
+ raise UnsupportedOperationException("Does support get all rules.")
+
+ def validate(self) -> None:
+ """Validates the policy content.
+
+ Raises:
+ IllegalArgumentException: If the content is invalid.
+ """
+ if not self.supported_object_types():
+ raise IllegalArgumentException("supportedObjectTypes cannot be empty")
+
+
+class ExecutablePolicyContent(PolicyContent):
+ """A policy content that carries maintenance execution peers."""
+
+ @abstractmethod
+ def execution_spec(self) -> PolicyExecutionSpec:
+ """Returns the immutable execution peers; never None."""
+ raise NotImplementedError()
+
+
+class AbstractExecutablePolicyContent(ExecutablePolicyContent):
+ """Base class for executable policy contents."""
+
+ def __init__(self, execution_spec: PolicyExecutionSpec | None = None):
+ self._execution_spec = (
+ execution_spec
+ if execution_spec is not None
+ else PolicyExecutionSpec.empty()
+ )
+
+ def execution_spec(self) -> PolicyExecutionSpec:
+ return self._execution_spec
+
+ def _execution_fields_equal(self, that: AbstractExecutablePolicyContent) -> bool:
+ return self.execution_spec() == that.execution_spec()
+
+ def _execution_fields_hash_code(self) -> int:
+ return hash(self.execution_spec())
+
+
+class ReadRestrictionContent(PolicyContent):
+ """Base class for contents that carry an authored read-restriction
+ expression (row filter, column mask)."""
+
+ MAX_SOURCE_LENGTH_BYTES: ClassVar[int] = 16 * 1024
+
+ def properties(self) -> dict[str, str]:
+ return {}
+
+ @staticmethod
+ def validate_source(source: str | None, field_name: str) -> None:
+ if source is None or source.strip() == "":
+ raise IllegalArgumentException(f"{field_name} cannot be blank")
+ if len(source.encode("utf-8")) > ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES:
+ raise IllegalArgumentException(
+ f"{field_name} cannot exceed "
+ f"{ReadRestrictionContent.MAX_SOURCE_LENGTH_BYTES} UTF-8 bytes"
+ )
+
+
+class RowFilterContent(ReadRestrictionContent):
+ """Content of a row-filter policy: an expression evaluated per row of a
+ tagged table."""
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {MetadataObject.Type.TABLE}
+
+ def __init__(self, expression: str | None):
+ self._expression = expression
+ self.validate()
+
+ def expression(self) -> str | None:
+ """Returns the authored row-filter expression."""
+ return self._expression
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def rules(self) -> dict[str, object]:
+ return {"expression": self._expression}
+
+ def validate(self) -> None:
+ super().validate()
+ self.validate_source(self._expression, "row-filter expression")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, RowFilterContent):
+ return False
+ return self._expression == other._expression
+
+ def __hash__(self) -> int:
+ return hash(self._expression)
+
+ def __repr__(self) -> str:
+ return f"RowFilterContent{{expression='{self._expression}'}}"
+
+
+class ColumnMaskContent(ReadRestrictionContent):
+ """Content of a column-mask policy: an expression that transforms the
+ values of a tagged table or column."""
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.TABLE,
+ MetadataObject.Type.COLUMN,
+ }
+
+ def __init__(self, expression: str | None):
+ self._expression = expression
+ self.validate()
+
+ def expression(self) -> str | None:
+ """Returns the authored column-mask expression."""
+ return self._expression
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def rules(self) -> dict[str, object]:
+ return {"expression": self._expression}
+
+ def validate(self) -> None:
+ super().validate()
+ self.validate_source(self._expression, "column-mask expression")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, ColumnMaskContent):
+ return False
+ return self._expression == other._expression
+
+ def __hash__(self) -> int:
+ return hash(self._expression)
+
+ def __repr__(self) -> str:
+ return f"ColumnMaskContent{{expression='{self._expression}'}}"
+
+
+class AccessControlContent(PolicyContent):
+ """Content of an access-control policy: the privileges a tag confers on
+ the tagged object, and the roles that satisfy the rule's condition."""
+
+ PRIVILEGES_KEY: ClassVar[str] = "privileges"
+ APPLICABLE_ROLES_KEY: ClassVar[str] = "applicableRoles"
+
+ # The privileges a tag is allowed to confer. An allowlist rather than a
+ # denylist, so the boundary fails closed: a privilege added to
+ # Privilege.Name later confers nothing through a tag until it is added
+ # here deliberately.
+ PERMITTED_PRIVILEGES: ClassVar[frozenset] = frozenset(
+ {
+ Privilege.Name.SELECT_TABLE,
+ Privilege.Name.MODIFY_TABLE,
+ Privilege.Name.PROBE_TABLE_LIKE,
+ Privilege.Name.SELECT_VIEW,
+ Privilege.Name.READ_FILESET,
+ Privilege.Name.WRITE_FILESET,
+ Privilege.Name.CONSUME_TOPIC,
+ Privilege.Name.PRODUCE_TOPIC,
+ Privilege.Name.USE_MODEL,
+ Privilege.Name.EXECUTE_FUNCTION,
+ Privilege.Name.USE_SEMANTIC_MODEL,
+ }
+ )
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ MetadataObject.Type.VIEW,
+ MetadataObject.Type.FILESET,
+ MetadataObject.Type.TOPIC,
+ MetadataObject.Type.MODEL,
+ MetadataObject.Type.FUNCTION,
+ MetadataObject.Type.SEMANTIC_MODEL,
+ }
+
+ def __init__(
+ self,
+ privileges: list[Privilege.Name] | None,
+ applicable_roles: list[str] | None,
+ ):
+ # Copied without rejecting nulls so that validate() is the single
+ # place that reports a bad entry, with the offending value named.
+ self._privileges = list(privileges) if privileges is not None else []
+ self._applicable_roles = (
+ list(applicable_roles) if applicable_roles is not None else []
+ )
+
+ def privileges(self) -> list[Privilege.Name]:
+ """Returns the privileges this rule confers on the tagged object."""
+ return list(self._privileges)
+
+ def applicable_roles(self) -> list[str]:
+ """Returns the roles that satisfy this rule's condition."""
+ return list(self._applicable_roles)
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def properties(self) -> dict[str, str]:
+ return {}
+
+ def rules(self) -> dict[str, object]:
+ return {
+ self.PRIVILEGES_KEY: [
+ privilege.name if privilege is not None else None
+ for privilege in self._privileges
+ ],
+ self.APPLICABLE_ROLES_KEY: list(self._applicable_roles),
+ }
+
+ def validate(self) -> None:
+ super().validate()
+ if not self._privileges:
+ raise IllegalArgumentException("privileges cannot be empty")
+ for privilege in self._privileges:
+ if privilege not in self.PERMITTED_PRIVILEGES:
+ raise IllegalArgumentException(
+ f"privilege {privilege} cannot be conferred by a tag, "
+ f"permitted privileges are {sorted(p.name for p in self.PERMITTED_PRIVILEGES)}"
+ )
+ if not self._applicable_roles:
+ raise IllegalArgumentException("applicableRoles cannot be empty")
+ for role in self._applicable_roles:
+ if role is None or role.strip() == "":
+ raise IllegalArgumentException("applicable role name cannot be blank")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, AccessControlContent):
+ return False
+ return (
+ self._privileges == other._privileges
+ and self._applicable_roles == other._applicable_roles
+ )
+
+ def __hash__(self) -> int:
+ return hash((tuple(self._privileges), tuple(self._applicable_roles)))
+
+ def __repr__(self) -> str:
+ return (
+ f"AccessControlContent{{privileges={self._privileges}, "
+ f"applicableRoles={self._applicable_roles}}}"
+ )
+
+
+class IcebergDataCompactionContent( # pylint: disable=too-many-instance-attributes
+ AbstractExecutablePolicyContent
+):
+ """Content of an Iceberg data-compaction policy."""
+
+ STRATEGY_TYPE_KEY: ClassVar[str] = "strategy.type"
+ JOB_TEMPLATE_NAME_KEY: ClassVar[str] = "job.template-name"
+ JOB_OPTIONS_PREFIX: ClassVar[str] = "job.options."
+ REWRITE_STRATEGY_KEY: ClassVar[str] = "rewriteStrategy"
+ SORT_ORDER_KEY: ClassVar[str] = "sortOrder"
+ TRIGGER_EXPR_KEY: ClassVar[str] = "trigger-expr"
+ SCORE_EXPR_KEY: ClassVar[str] = "score-expr"
+ MIN_DATA_FILE_MSE_KEY: ClassVar[str] = "minDataFileMse"
+ MIN_DELETE_FILE_NUMBER_KEY: ClassVar[str] = "minDeleteFileNumber"
+ DATA_FILE_MSE_WEIGHT_KEY: ClassVar[str] = "dataFileMseWeight"
+ DELETE_FILE_NUMBER_WEIGHT_KEY: ClassVar[str] = "deleteFileNumberWeight"
+ MAX_PARTITION_NUM_KEY: ClassVar[str] = "max-partition-num"
+ REWRITE_STRATEGY_BINPACK: ClassVar[str] = "binpack"
+ REWRITE_STRATEGY_SORT: ClassVar[str] = "sort"
+ DATA_FILE_MSE_METRIC: ClassVar[str] = "custom-data-file-mse"
+ DELETE_FILE_NUMBER_METRIC: ClassVar[str] = "custom-delete-file-number"
+
+ DEFAULT_MIN_DATA_FILE_MSE: ClassVar[int] = 405323966463344
+ DEFAULT_MIN_DELETE_FILE_NUMBER: ClassVar[int] = 1
+ DEFAULT_DATA_FILE_MSE_WEIGHT: ClassVar[int] = 1
+ DEFAULT_DELETE_FILE_NUMBER_WEIGHT: ClassVar[int] = 100
+ DEFAULT_MAX_PARTITION_NUM: ClassVar[int] = 50
+ DEFAULT_REWRITE_STRATEGY: ClassVar[str] = REWRITE_STRATEGY_BINPACK
+ DEFAULT_SORT_ORDER: ClassVar[str] = ""
+ DEFAULT_REWRITE_OPTIONS: ClassVar[dict] = {}
+
+ STRATEGY_TYPE_VALUE: ClassVar[str] = "iceberg-data-compaction"
+ JOB_TEMPLATE_NAME_VALUE: ClassVar[str] = "builtin-iceberg-rewrite-data-files"
+
+ _SUPPORTED_REWRITE_STRATEGIES: ClassVar[set] = {
+ REWRITE_STRATEGY_BINPACK,
+ REWRITE_STRATEGY_SORT,
+ }
+ # Names and value kinds mirror Iceberg RewriteDataFiles /
+ # SizeBasedFileRewriter, as in the Java content's supported-option map.
+ _SUPPORTED_REWRITE_OPTIONS: ClassVar[dict] = {
+ "target-file-size-bytes": "positive_long",
+ "min-file-size-bytes": "positive_long",
+ "max-file-size-bytes": "positive_long",
+ "max-file-group-size-bytes": "positive_long",
+ "min-input-files": "positive_int",
+ "max-concurrent-file-group-rewrites": "positive_int",
+ "partial-progress.max-commits": "positive_int",
+ "partial-progress.max-failed-commits": "non_negative_int",
+ "output-spec-id": "non_negative_int",
+ "delete-file-threshold": "non_negative_int",
+ "rewrite-all": "boolean",
+ "partial-progress.enabled": "boolean",
+ "use-starting-sequence-number": "boolean",
+ "remove-dangling-deletes": "boolean",
+ "rewrite-job-order": "rewrite_job_order",
+ "delete-ratio-threshold": "ratio",
+ }
+ _REWRITE_JOB_ORDERS: ClassVar[set] = {
+ "bytes-asc",
+ "bytes-desc",
+ "files-asc",
+ "files-desc",
+ "none",
+ }
+ _OPTION_KEY_PATTERN: ClassVar[re.Pattern] = re.compile(r"[A-Za-z0-9._-]+")
+ _INTEGER_PATTERN: ClassVar[re.Pattern] = re.compile(r"[+-]?[0-9]+")
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ TRIGGER_EXPR: ClassVar[str] = (
+ DATA_FILE_MSE_METRIC
+ + " >= "
+ + MIN_DATA_FILE_MSE_KEY
+ + " || "
+ + DELETE_FILE_NUMBER_METRIC
+ + " >= "
+ + MIN_DELETE_FILE_NUMBER_KEY
+ )
+ SCORE_EXPR: ClassVar[str] = (
+ DATA_FILE_MSE_METRIC
+ + " * "
+ + DATA_FILE_MSE_WEIGHT_KEY
+ + " + "
+ + DELETE_FILE_NUMBER_METRIC
+ + " * "
+ + DELETE_FILE_NUMBER_WEIGHT_KEY
+ )
+
+ def __init__(
+ self,
+ min_data_file_mse: int | None = None,
+ min_delete_file_number: int | None = None,
+ data_file_mse_weight: int | None = None,
+ delete_file_number_weight: int | None = None,
+ max_partition_num: int | None = None,
+ rewrite_strategy: str | None = None,
+ sort_order: str | None = None,
+ rewrite_options: dict[str, str] | None = None,
+ execution_spec: PolicyExecutionSpec | None = None,
+ ):
+ super().__init__(execution_spec)
+ self._min_data_file_mse = (
+ min_data_file_mse
+ if min_data_file_mse is not None
+ else self.DEFAULT_MIN_DATA_FILE_MSE
+ )
+ self._min_delete_file_number = (
+ min_delete_file_number
+ if min_delete_file_number is not None
+ else self.DEFAULT_MIN_DELETE_FILE_NUMBER
+ )
+ self._data_file_mse_weight = (
+ data_file_mse_weight
+ if data_file_mse_weight is not None
+ else self.DEFAULT_DATA_FILE_MSE_WEIGHT
+ )
+ self._delete_file_number_weight = (
+ delete_file_number_weight
+ if delete_file_number_weight is not None
+ else self.DEFAULT_DELETE_FILE_NUMBER_WEIGHT
+ )
+ self._max_partition_num = (
+ max_partition_num
+ if max_partition_num is not None
+ else self.DEFAULT_MAX_PARTITION_NUM
+ )
+ self._rewrite_strategy = (
+ rewrite_strategy.strip().lower()
+ if rewrite_strategy is not None
+ else self.DEFAULT_REWRITE_STRATEGY
+ )
+ self._sort_order = (
+ sort_order.strip() if sort_order is not None else self.DEFAULT_SORT_ORDER
+ )
+ self._rewrite_options = (
+ dict(rewrite_options)
+ if rewrite_options is not None
+ else dict(self.DEFAULT_REWRITE_OPTIONS)
+ )
+
+ def min_data_file_mse(self) -> int:
+ return self._min_data_file_mse
+
+ def min_delete_file_number(self) -> int:
+ return self._min_delete_file_number
+
+ def data_file_mse_weight(self) -> int:
+ return self._data_file_mse_weight
+
+ def delete_file_number_weight(self) -> int:
+ return self._delete_file_number_weight
+
+ def max_partition_num(self) -> int:
+ return self._max_partition_num
+
+ def rewrite_strategy(self) -> str:
+ return self._rewrite_strategy
+
+ def sort_order(self) -> str:
+ return self._sort_order
+
+ def rewrite_options(self) -> dict[str, str]:
+ return dict(self._rewrite_options)
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def properties(self) -> dict[str, str]:
+ # Properties keep stable strategy/job identity; thresholds and
+ # scoring knobs belong to rules.
+ return {
+ self.STRATEGY_TYPE_KEY: self.STRATEGY_TYPE_VALUE,
+ self.JOB_TEMPLATE_NAME_KEY: self.JOB_TEMPLATE_NAME_VALUE,
+ }
+
+ def rules(self) -> dict[str, object]:
+ rules: dict[str, object] = {
+ self.MIN_DATA_FILE_MSE_KEY: self._min_data_file_mse,
+ self.MIN_DELETE_FILE_NUMBER_KEY: self._min_delete_file_number,
+ self.DATA_FILE_MSE_WEIGHT_KEY: self._data_file_mse_weight,
+ self.DELETE_FILE_NUMBER_WEIGHT_KEY: self._delete_file_number_weight,
+ self.MAX_PARTITION_NUM_KEY: self._max_partition_num,
+ self.TRIGGER_EXPR_KEY: self.TRIGGER_EXPR,
+ self.SCORE_EXPR_KEY: self.SCORE_EXPR,
+ self.REWRITE_STRATEGY_KEY: self._rewrite_strategy,
+ self.SORT_ORDER_KEY: self._sort_order,
+ }
+ for key, value in self._rewrite_options.items():
+ rules[self.JOB_OPTIONS_PREFIX + key] = value
+ return rules
+
+ def validate(self) -> None:
+ super().validate()
+ # All fields are defaulted in the constructor, so only range checks
+ # are needed here.
+ if self._min_data_file_mse < 0:
+ raise IllegalArgumentException("minDataFileMse must be >= 0")
+ if self._min_delete_file_number < 0:
+ raise IllegalArgumentException("minDeleteFileNumber must be >= 0")
+ if self._data_file_mse_weight < 0:
+ raise IllegalArgumentException("dataFileMseWeight must be >= 0")
+ if self._delete_file_number_weight < 0:
+ raise IllegalArgumentException("deleteFileNumberWeight must be >= 0")
+ if self._max_partition_num <= 0:
+ raise IllegalArgumentException("maxPartitionNum must be > 0")
+ if self._rewrite_strategy not in self._SUPPORTED_REWRITE_STRATEGIES:
+ raise IllegalArgumentException(
+ f"rewriteStrategy must be one of "
+ f"{sorted(self._SUPPORTED_REWRITE_STRATEGIES)}, but got "
+ f"'{self._rewrite_strategy}'"
+ )
+ if self._rewrite_strategy == self.REWRITE_STRATEGY_SORT:
+ if self._sort_order.strip() == "":
+ raise IllegalArgumentException(
+ f"sortOrder must be set when rewriteStrategy is "
+ f"'{self.REWRITE_STRATEGY_SORT}'"
+ )
+ elif self._sort_order.strip() != "":
+ raise IllegalArgumentException(
+ f"sortOrder must be empty when rewriteStrategy is "
+ f"'{self.REWRITE_STRATEGY_BINPACK}'"
+ )
+ for key, value in self._rewrite_options.items():
+ self._validate_rewrite_option(key, value)
+
+ @staticmethod
+ def _validate_rewrite_option(key: str, value: str) -> None:
+ # Mirrors the Java content's validateRewriteOption contract.
+ if key is None or key.strip() == "":
+ raise IllegalArgumentException("rewrite option key is blank")
+ if not IcebergDataCompactionContent._OPTION_KEY_PATTERN.fullmatch(key):
+ raise IllegalArgumentException(
+ f"rewrite option key '{key}' contains illegal characters"
+ )
+ if key.startswith(IcebergDataCompactionContent.JOB_OPTIONS_PREFIX):
+ raise IllegalArgumentException(
+ f"rewrite option key '{key}' must not start with "
+ f"'{IcebergDataCompactionContent.JOB_OPTIONS_PREFIX}'"
+ )
+ if value is None or value.strip() == "":
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must have non-empty value"
+ )
+ kind = IcebergDataCompactionContent._SUPPORTED_REWRITE_OPTIONS.get(key)
+ if kind is None:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' is not supported by "
+ f"rewrite_data_files; supported options are "
+ f"{sorted(IcebergDataCompactionContent._SUPPORTED_REWRITE_OPTIONS)}"
+ )
+ IcebergDataCompactionContent._check_rewrite_option_value(key, value, kind)
+
+ @staticmethod
+ def _check_rewrite_option_value(key: str, value: str, kind: str) -> None:
+ if kind in ("positive_long", "positive_int", "non_negative_int"):
+ IcebergDataCompactionContent._check_integer_option(key, value, kind)
+ elif kind == "boolean":
+ if value.lower() not in ("true", "false"):
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be true or false"
+ )
+ elif kind == "rewrite_job_order":
+ if value.lower() not in IcebergDataCompactionContent._REWRITE_JOB_ORDERS:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be one of "
+ f"{sorted(IcebergDataCompactionContent._REWRITE_JOB_ORDERS)}, "
+ f"but got '{value}'"
+ )
+ elif kind == "ratio":
+ IcebergDataCompactionContent._check_ratio_option(key, value)
+
+ @staticmethod
+ def _check_integer_option(key: str, value: str, kind: str) -> None:
+ bits = 64 if kind == "positive_long" else 32
+ kind_name = "a long" if kind == "positive_long" else "an int"
+ text = value.strip()
+ if not IcebergDataCompactionContent._INTEGER_PATTERN.fullmatch(text):
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be {kind_name}"
+ )
+ parsed = int(text)
+ if not -(2 ** (bits - 1)) <= parsed <= 2 ** (bits - 1) - 1:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be {kind_name}"
+ )
+ if kind == "non_negative_int":
+ if parsed < 0:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be a non-negative int"
+ )
+ elif parsed <= 0:
+ label = "a positive long" if kind == "positive_long" else "a positive int"
+ raise IllegalArgumentException(f"rewrite option '{key}' must be {label}")
+
+ @staticmethod
+ def _check_ratio_option(key: str, value: str) -> None:
+ try:
+ ratio = float(value.strip())
+ except ValueError:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be a number between 0 and 1"
+ ) from None
+ if not 0.0 <= ratio <= 1.0:
+ raise IllegalArgumentException(
+ f"rewrite option '{key}' must be a number between 0 and 1"
+ )
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, IcebergDataCompactionContent):
+ return False
+ return (
+ self._execution_fields_equal(other)
+ and self._min_data_file_mse == other._min_data_file_mse
+ and self._min_delete_file_number == other._min_delete_file_number
+ and self._data_file_mse_weight == other._data_file_mse_weight
+ and self._delete_file_number_weight == other._delete_file_number_weight
+ and self._max_partition_num == other._max_partition_num
+ and self._rewrite_strategy == other._rewrite_strategy
+ and self._sort_order == other._sort_order
+ and self._rewrite_options == other._rewrite_options
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._execution_fields_hash_code(),
+ self._min_data_file_mse,
+ self._min_delete_file_number,
+ self._data_file_mse_weight,
+ self._delete_file_number_weight,
+ self._max_partition_num,
+ self._rewrite_strategy,
+ self._sort_order,
+ frozenset(self._rewrite_options.items()),
+ )
+ )
+
+
+class IcebergOrphanFileRemovalContent(AbstractExecutablePolicyContent):
+ """Content of an Iceberg orphan-file-removal policy."""
+
+ STRATEGY_TYPE_KEY: ClassVar[str] = "strategy.type"
+ JOB_TEMPLATE_NAME_KEY: ClassVar[str] = "job.template-name"
+ TRIGGER_EXPR_KEY: ClassVar[str] = "trigger-expr"
+ SCORE_EXPR_KEY: ClassVar[str] = "score-expr"
+ JOB_OPTIONS_PREFIX: ClassVar[str] = "job.options."
+ OLDER_THAN_DAYS_KEY: ClassVar[str] = "olderThanDays"
+ LOCATION_KEY: ClassVar[str] = "location"
+ DRY_RUN_KEY: ClassVar[str] = "dryRun"
+
+ DEFAULT_OLDER_THAN_DAYS: ClassVar[int] = 3
+ DEFAULT_DRY_RUN: ClassVar[bool] = False
+ MAX_OLDER_THAN_DAYS: ClassVar[int] = 36500
+
+ STRATEGY_TYPE_VALUE: ClassVar[str] = "iceberg-orphan-file-removal"
+ JOB_TEMPLATE_NAME_VALUE: ClassVar[str] = "builtin-iceberg-remove-orphan-files"
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def __init__(
+ self,
+ older_than_days: int | None = None,
+ location: str | None = None,
+ dry_run: bool | None = None,
+ execution_spec: PolicyExecutionSpec | None = None,
+ ):
+ super().__init__(execution_spec)
+ self._older_than_days = (
+ older_than_days
+ if older_than_days is not None
+ else self.DEFAULT_OLDER_THAN_DAYS
+ )
+ self._location = location
+ self._dry_run = dry_run if dry_run is not None else self.DEFAULT_DRY_RUN
+
+ def older_than_days(self) -> int:
+ return self._older_than_days
+
+ def location(self) -> str | None:
+ return self._location
+
+ def dry_run(self) -> bool:
+ return self._dry_run
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def properties(self) -> dict[str, str]:
+ return {
+ self.STRATEGY_TYPE_KEY: self.STRATEGY_TYPE_VALUE,
+ self.JOB_TEMPLATE_NAME_KEY: self.JOB_TEMPLATE_NAME_VALUE,
+ }
+
+ def rules(self) -> dict[str, object]:
+ rules: dict[str, object] = {
+ self.TRIGGER_EXPR_KEY: "true",
+ self.SCORE_EXPR_KEY: "1",
+ self.JOB_OPTIONS_PREFIX + self.OLDER_THAN_DAYS_KEY: self._older_than_days,
+ self.JOB_OPTIONS_PREFIX + self.DRY_RUN_KEY: self._dry_run,
+ }
+ if self._location is not None:
+ rules[self.JOB_OPTIONS_PREFIX + self.LOCATION_KEY] = self._location
+ return rules
+
+ @staticmethod
+ def validate_older_than_days(days: int) -> None:
+ if not 1 <= days <= IcebergOrphanFileRemovalContent.MAX_OLDER_THAN_DAYS:
+ raise IllegalArgumentException(
+ f"olderThanDays must be between 1 and "
+ f"{IcebergOrphanFileRemovalContent.MAX_OLDER_THAN_DAYS}"
+ )
+
+ def validate(self) -> None:
+ super().validate()
+ if self.execution_spec().commit_trigger() is True:
+ raise IllegalArgumentException(
+ "commitTrigger is not allowed for orphan file removal"
+ )
+ self.validate_older_than_days(self._older_than_days)
+ if self._location is not None:
+ if self._location.strip() == "":
+ raise IllegalArgumentException("location must not be blank")
+ if self._location != self._location.strip():
+ raise IllegalArgumentException(
+ "location must not have leading or trailing whitespace"
+ )
+ if ".." in self._location:
+ raise IllegalArgumentException(
+ f"location must not contain '..' path segments: {self._location}"
+ )
+ if "\\" in self._location:
+ raise IllegalArgumentException(
+ f"location must not contain '\\': {self._location}"
+ )
+ if "%" in self._location:
+ raise IllegalArgumentException(
+ f"location must not contain percent-encoding: {self._location}"
+ )
+ if "?" in self._location or "#" in self._location:
+ raise IllegalArgumentException(
+ f"location must not contain query or fragment: {self._location}"
+ )
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, IcebergOrphanFileRemovalContent):
+ return False
+ return (
+ self._execution_fields_equal(other)
+ and self._older_than_days == other._older_than_days
+ and self._location == other._location
+ and self._dry_run == other._dry_run
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._execution_fields_hash_code(),
+ self._older_than_days,
+ self._location,
+ self._dry_run,
+ )
+ )
+
+
+class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):
+ """Content of an Iceberg rewrite-manifests policy."""
+
+ STRATEGY_TYPE_KEY: ClassVar[str] = "strategy.type"
+ JOB_TEMPLATE_NAME_KEY: ClassVar[str] = "job.template-name"
+ TRIGGER_EXPR_KEY: ClassVar[str] = "trigger-expr"
+ SCORE_EXPR_KEY: ClassVar[str] = "score-expr"
+ MANIFEST_COUNT_CRITICAL: ClassVar[str] = "manifest_count_critical"
+ MANIFEST_COUNT_WARNING: ClassVar[str] = "manifest_count_warning"
+ AVG_MANIFEST_SIZE_THRESHOLD_BYTES: ClassVar[str] = (
+ "avg_manifest_size_threshold_bytes"
+ )
+ SPEC_ID: ClassVar[str] = "spec_id"
+ USE_CACHING: ClassVar[str] = "use_caching"
+
+ DEFAULT_MANIFEST_COUNT_CRITICAL: ClassVar[int] = 500
+ DEFAULT_MANIFEST_COUNT_WARNING: ClassVar[int] = 100
+ DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES: ClassVar[int] = 8388608
+
+ STRATEGY_TYPE_VALUE: ClassVar[str] = "iceberg-rewrite-manifests"
+ JOB_TEMPLATE_NAME_VALUE: ClassVar[str] = "builtin-iceberg-rewrite-manifests"
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def __init__(
+ self,
+ manifest_count_critical: int | None = None,
+ manifest_count_warning: int | None = None,
+ avg_manifest_size_threshold_bytes: int | None = None,
+ spec_id: int | None = None,
+ use_caching: bool | None = None,
+ execution_spec: PolicyExecutionSpec | None = None,
+ ):
+ super().__init__(execution_spec)
+ self._manifest_count_critical = (
+ manifest_count_critical
+ if manifest_count_critical is not None
+ else self.DEFAULT_MANIFEST_COUNT_CRITICAL
+ )
+ self._manifest_count_warning = (
+ manifest_count_warning
+ if manifest_count_warning is not None
+ else self.DEFAULT_MANIFEST_COUNT_WARNING
+ )
+ self._avg_manifest_size_threshold_bytes = (
+ avg_manifest_size_threshold_bytes
+ if avg_manifest_size_threshold_bytes is not None
+ else self.DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES
+ )
+ self._spec_id = spec_id
+ self._use_caching = use_caching
+
+ def manifest_count_critical(self) -> int:
+ return self._manifest_count_critical
+
+ def manifest_count_warning(self) -> int:
+ return self._manifest_count_warning
+
+ def avg_manifest_size_threshold_bytes(self) -> int:
+ return self._avg_manifest_size_threshold_bytes
+
+ def spec_id(self) -> int | None:
+ return self._spec_id
+
+ def use_caching(self) -> bool | None:
+ return self._use_caching
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def properties(self) -> dict[str, str]:
+ return {
+ self.STRATEGY_TYPE_KEY: self.STRATEGY_TYPE_VALUE,
+ self.JOB_TEMPLATE_NAME_KEY: self.JOB_TEMPLATE_NAME_VALUE,
+ }
+
+ def rules(self) -> dict[str, object]:
+ rules: dict[str, object] = {
+ self.MANIFEST_COUNT_CRITICAL: self._manifest_count_critical,
+ self.MANIFEST_COUNT_WARNING: self._manifest_count_warning,
+ self.AVG_MANIFEST_SIZE_THRESHOLD_BYTES: (
+ self._avg_manifest_size_threshold_bytes
+ ),
+ }
+ if self._spec_id is not None:
+ rules[self.SPEC_ID] = self._spec_id
+ if self._use_caching is not None:
+ rules[self.USE_CACHING] = self._use_caching
+ return rules
+
+ def validate(self) -> None:
+ super().validate()
+ if self._manifest_count_warning <= 0:
+ raise IllegalArgumentException("manifest_count_warning must be > 0")
+ if self._manifest_count_critical < self._manifest_count_warning:
+ raise IllegalArgumentException(
+ "manifest_count_critical must be >= manifest_count_warning"
+ )
+ if self._avg_manifest_size_threshold_bytes <= 0:
+ raise IllegalArgumentException(
+ "avg_manifest_size_threshold_bytes must be > 0"
+ )
+ if self._spec_id is not None and self._spec_id < 0:
+ raise IllegalArgumentException("spec_id must be >= 0")
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, IcebergRewriteManifestsContent):
+ return False
+ return (
+ self._execution_fields_equal(other)
+ and self._manifest_count_critical == other._manifest_count_critical
+ and self._manifest_count_warning == other._manifest_count_warning
+ and self._avg_manifest_size_threshold_bytes
+ == other._avg_manifest_size_threshold_bytes
+ and self._spec_id == other._spec_id
+ and self._use_caching == other._use_caching
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._execution_fields_hash_code(),
+ self._manifest_count_critical,
+ self._manifest_count_warning,
+ self._avg_manifest_size_threshold_bytes,
+ self._spec_id,
+ self._use_caching,
+ )
+ )
+
+
+class IcebergSnapshotExpirationContent(AbstractExecutablePolicyContent):
+ """Content of an Iceberg snapshot-expiration policy."""
+
+ STRATEGY_TYPE_KEY: ClassVar[str] = "strategy.type"
+ JOB_TEMPLATE_NAME_KEY: ClassVar[str] = "job.template-name"
+ TRIGGER_EXPR_KEY: ClassVar[str] = "trigger-expr"
+ SCORE_EXPR_KEY: ClassVar[str] = "score-expr"
+ JOB_OPTIONS_PREFIX: ClassVar[str] = "job.options."
+ OLDER_THAN_DAYS_KEY: ClassVar[str] = "olderThanDays"
+ RETAIN_LAST_KEY: ClassVar[str] = "retainLast"
+ STREAM_RESULTS_KEY: ClassVar[str] = "streamResults"
+
+ DEFAULT_OLDER_THAN_DAYS: ClassVar[int] = 5
+ DEFAULT_RETAIN_LAST: ClassVar[int] = 1
+ DEFAULT_STREAM_RESULTS: ClassVar[bool] = False
+ MAX_OLDER_THAN_DAYS: ClassVar[int] = 36500
+
+ STRATEGY_TYPE_VALUE: ClassVar[str] = "iceberg-snapshot-expiration"
+ JOB_TEMPLATE_NAME_VALUE: ClassVar[str] = "builtin-iceberg-expire-snapshots"
+
+ _SUPPORTED_OBJECT_TYPES: ClassVar[set] = {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def __init__(
+ self,
+ older_than_days: int | None = None,
+ retain_last: int | None = None,
+ stream_results: bool | None = None,
+ execution_spec: PolicyExecutionSpec | None = None,
+ ):
+ super().__init__(execution_spec)
+ self._older_than_days = (
+ older_than_days
+ if older_than_days is not None
+ else self.DEFAULT_OLDER_THAN_DAYS
+ )
+ self._retain_last = (
+ retain_last if retain_last is not None else self.DEFAULT_RETAIN_LAST
+ )
+ self._stream_results = (
+ stream_results
+ if stream_results is not None
+ else self.DEFAULT_STREAM_RESULTS
+ )
+
+ def older_than_days(self) -> int:
+ return self._older_than_days
+
+ def retain_last(self) -> int:
+ return self._retain_last
+
+ def stream_results(self) -> bool:
+ return self._stream_results
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._SUPPORTED_OBJECT_TYPES)
+
+ def properties(self) -> dict[str, str]:
+ return {
+ self.STRATEGY_TYPE_KEY: self.STRATEGY_TYPE_VALUE,
+ self.JOB_TEMPLATE_NAME_KEY: self.JOB_TEMPLATE_NAME_VALUE,
+ }
+
+ def rules(self) -> dict[str, object]:
+ return {
+ self.TRIGGER_EXPR_KEY: "true",
+ self.SCORE_EXPR_KEY: "1",
+ self.JOB_OPTIONS_PREFIX + self.OLDER_THAN_DAYS_KEY: self._older_than_days,
+ self.JOB_OPTIONS_PREFIX + self.RETAIN_LAST_KEY: self._retain_last,
+ self.JOB_OPTIONS_PREFIX + self.STREAM_RESULTS_KEY: self._stream_results,
+ }
+
+ @staticmethod
+ def validate_older_than_days(days: int) -> None:
+ if not 1 <= days <= IcebergSnapshotExpirationContent.MAX_OLDER_THAN_DAYS:
+ raise IllegalArgumentException(
+ f"olderThanDays must be between 1 and "
+ f"{IcebergSnapshotExpirationContent.MAX_OLDER_THAN_DAYS}"
+ )
+
+ @staticmethod
+ def validate_retain_last(retain_last: int) -> None:
+ if retain_last < 1:
+ raise IllegalArgumentException("retainLast must be a positive long")
+
+ def validate(self) -> None:
+ super().validate()
+ self.validate_older_than_days(self._older_than_days)
+ self.validate_retain_last(self._retain_last)
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, IcebergSnapshotExpirationContent):
+ return False
+ return (
+ self._execution_fields_equal(other)
+ and self._older_than_days == other._older_than_days
+ and self._retain_last == other._retain_last
+ and self._stream_results == other._stream_results
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._execution_fields_hash_code(),
+ self._older_than_days,
+ self._retain_last,
+ self._stream_results,
+ )
+ )
diff --git a/clients/client-python/gravitino/api/policy/policy_contents.py b/clients/client-python/gravitino/api/policy/policy_contents.py
new file mode 100644
index 0000000000..cf5f5fdd9b
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_contents.py
@@ -0,0 +1,272 @@
+# 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.
+
+from __future__ import annotations
+
+from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.policy.policy_content import (
+ AccessControlContent,
+ ColumnMaskContent,
+ IcebergDataCompactionContent,
+ IcebergOrphanFileRemovalContent,
+ IcebergRewriteManifestsContent,
+ IcebergSnapshotExpirationContent,
+ PolicyContent,
+ PolicyExecutionSpec,
+ RowFilterContent,
+)
+
+
+def _freeze_value(value: object) -> object:
+ """Recursively converts nested collections to hashable equivalents."""
+ if isinstance(value, dict):
+ return frozenset((key, _freeze_value(item)) for key, item in value.items())
+ if isinstance(value, (list, tuple)):
+ return tuple(_freeze_value(item) for item in value)
+ if isinstance(value, (set, frozenset)):
+ return frozenset(_freeze_value(item) for item in value)
+ return value
+
+
+class PolicyContents:
+ """Convenience factories for creating policy contents."""
+
+ class CustomContent(PolicyContent):
+ """The content of a custom policy: user-defined rules plus the object
+ types and properties that describe them."""
+
+ def __init__(
+ self,
+ custom_rules: dict[str, object],
+ supported_object_types: set[MetadataObject.Type] | None = None,
+ properties: dict[str, str] | None = None,
+ ):
+ self._custom_rules = custom_rules
+ self._supported_object_types = (
+ set(supported_object_types)
+ if supported_object_types is not None
+ else set()
+ )
+ self._properties = dict(properties) if properties is not None else {}
+
+ def rules(self) -> dict[str, object]:
+ return self._custom_rules
+
+ def supported_object_types(self) -> set[MetadataObject.Type]:
+ return set(self._supported_object_types)
+
+ def properties(self) -> dict[str, str]:
+ return dict(self._properties)
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, PolicyContents.CustomContent):
+ return False
+ return (
+ self._custom_rules == other._custom_rules
+ and self._supported_object_types == other._supported_object_types
+ and self._properties == other._properties
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ frozenset(
+ (key, _freeze_value(value))
+ for key, value in self._custom_rules.items()
+ ),
+ frozenset(self._supported_object_types),
+ frozenset(self._properties.items()),
+ )
+ )
+
+ @staticmethod
+ def custom(
+ rules: dict[str, object],
+ supported_object_types: set[MetadataObject.Type] | None = None,
+ properties: dict[str, str] | None = None,
+ ) -> PolicyContents.CustomContent:
+ """Creates the content of a custom policy.
+
+ Args:
+ rules: The user-defined rules of the policy.
+ supported_object_types: The metadata object types the policy can
+ be applied to.
+ properties: The additional properties of the policy.
+
+ Returns:
+ PolicyContents.CustomContent: The custom policy content.
+ """
+ return PolicyContents.CustomContent(rules, supported_object_types, properties)
+
+ @staticmethod
+ def iceberg_data_compaction( # pylint: disable=too-many-arguments,too-many-positional-arguments
+ min_data_file_mse: int | None = None,
+ min_delete_file_number: int | None = None,
+ data_file_mse_weight: int | None = None,
+ delete_file_number_weight: int | None = None,
+ max_partition_num: int | None = None,
+ rewrite_strategy: str | None = None,
+ sort_order: str | None = None,
+ rewrite_options: dict[str, str] | None = None,
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ) -> IcebergDataCompactionContent:
+ """Creates the content of an Iceberg data-compaction policy; unset
+ arguments take the content class's documented defaults."""
+ return IcebergDataCompactionContent(
+ min_data_file_mse,
+ min_delete_file_number,
+ data_file_mse_weight,
+ delete_file_number_weight,
+ max_partition_num,
+ rewrite_strategy,
+ sort_order,
+ rewrite_options,
+ PolicyExecutionSpec.of(
+ time_trigger,
+ commit_trigger,
+ min_interval_ms,
+ job_options,
+ updater_options,
+ ),
+ )
+
+ @staticmethod
+ def iceberg_orphan_file_removal(
+ older_than_days: int | None = None,
+ location: str | None = None,
+ dry_run: bool | None = None,
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ) -> IcebergOrphanFileRemovalContent:
+ """Creates the content of an Iceberg orphan-file-removal policy;
+ unset arguments take the content class's documented defaults."""
+ return IcebergOrphanFileRemovalContent(
+ older_than_days,
+ location,
+ dry_run,
+ PolicyExecutionSpec.of(
+ time_trigger,
+ commit_trigger,
+ min_interval_ms,
+ job_options,
+ updater_options,
+ ),
+ )
+
+ @staticmethod
+ def iceberg_rewrite_manifests(
+ manifest_count_critical: int | None = None,
+ manifest_count_warning: int | None = None,
+ avg_manifest_size_threshold_bytes: int | None = None,
+ spec_id: int | None = None,
+ use_caching: bool | None = None,
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ) -> IcebergRewriteManifestsContent:
+ """Creates the content of an Iceberg rewrite-manifests policy; unset
+ arguments take the content class's documented defaults."""
+ return IcebergRewriteManifestsContent(
+ manifest_count_critical,
+ manifest_count_warning,
+ avg_manifest_size_threshold_bytes,
+ spec_id,
+ use_caching,
+ PolicyExecutionSpec.of(
+ time_trigger,
+ commit_trigger,
+ min_interval_ms,
+ job_options,
+ updater_options,
+ ),
+ )
+
+ @staticmethod
+ def iceberg_snapshot_expiration(
+ older_than_days: int | None = None,
+ retain_last: int | None = None,
+ stream_results: bool | None = None,
+ time_trigger: str | None = None,
+ commit_trigger: bool | None = None,
+ min_interval_ms: int | None = None,
+ job_options: dict[str, str] | None = None,
+ updater_options: dict[str, str] | None = None,
+ ) -> IcebergSnapshotExpirationContent:
+ """Creates the content of an Iceberg snapshot-expiration policy;
+ unset arguments take the content class's documented defaults."""
+ return IcebergSnapshotExpirationContent(
+ older_than_days,
+ retain_last,
+ stream_results,
+ PolicyExecutionSpec.of(
+ time_trigger,
+ commit_trigger,
+ min_interval_ms,
+ job_options,
+ updater_options,
+ ),
+ )
+
+ @staticmethod
+ def row_filter(expression: str) -> RowFilterContent:
+ """Creates the content of a row-filter policy.
+
+ Args:
+ expression: The row-filter expression.
+
+ Returns:
+ RowFilterContent: The row-filter policy content.
+ """
+ return RowFilterContent(expression)
+
+ @staticmethod
+ def column_mask(expression: str) -> ColumnMaskContent:
+ """Creates the content of a column-mask policy.
+
+ Args:
+ expression: The column-mask expression.
+
+ Returns:
+ ColumnMaskContent: The column-mask policy content.
+ """
+ return ColumnMaskContent(expression)
+
+ @staticmethod
+ def access_control(
+ privileges: list[Privilege.Name],
+ applicable_roles: list[str],
+ ) -> AccessControlContent:
+ """Creates the content of an access-control policy.
+
+ Args:
+ privileges: The privileges the policy confers.
+ applicable_roles: The roles the policy applies to.
+
+ Returns:
+ AccessControlContent: The access-control policy content.
+ """
+ return AccessControlContent(privileges, applicable_roles)
diff --git a/clients/client-python/gravitino/api/policy/policy_list.py b/clients/client-python/gravitino/api/policy/policy_list.py
new file mode 100644
index 0000000000..c679b9c31b
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_list.py
@@ -0,0 +1,41 @@
+# 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.
+
+from __future__ import annotations
+
+from typing import Generic, TypeVar
+
+T = TypeVar("T")
+
+
+class PolicyList(Generic[T]):
+ """The result of listing policies: the policies plus a flag indicating
+ whether the list is partial because some policies are inaccessible to the
+ caller."""
+
+ def __init__(self, policies: list[T], has_inaccessible_policies: bool):
+ self._policies = list(policies)
+ self._has_inaccessible_policies = has_inaccessible_policies
+
+ def policies(self) -> list[T]:
+ """Returns the listed policies (a copy)."""
+ return list(self._policies)
+
+ def has_inaccessible_policies(self) -> bool:
+ """Returns True if some policies were omitted because they are
+ inaccessible to the caller."""
+ return self._has_inaccessible_policies
diff --git a/clients/client-python/gravitino/api/policy/policy_operations.py b/clients/client-python/gravitino/api/policy/policy_operations.py
new file mode 100644
index 0000000000..a3b7014368
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_operations.py
@@ -0,0 +1,174 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_change import PolicyChange
+from gravitino.api.policy.policy_content import PolicyContent
+from gravitino.api.policy.policy_tag_association import PolicyTagAssociation
+from gravitino.exceptions.base import UnsupportedOperationException
+
+
+class PolicyOperations(ABC):
+ """The operations for interacting with policies in a metalake: listing,
+ creating, altering, enabling, disabling and deleting policies."""
+
+ @abstractmethod
+ def list_policies(self) -> list[str]:
+ """Lists the names of all policies in the metalake.
+
+ Returns:
+ list[str]: The names of the policies.
+
+ Raises:
+ NoSuchMetalakeException: If the metalake does not exist.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def list_policy_infos(self) -> list[Policy]:
+ """Lists all policies in the metalake with their details.
+
+ Returns:
+ list[Policy]: The policies.
+
+ Raises:
+ NoSuchMetalakeException: If the metalake does not exist.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def get_policy(self, policy_name: str) -> Policy:
+ """Gets a policy by name.
+
+ Args:
+ policy_name: The name of the policy.
+
+ Returns:
+ Policy: The policy.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def create_policy(
+ self,
+ policy_name: str,
+ policy_type: str,
+ comment: str | None,
+ enabled: bool,
+ content: PolicyContent,
+ ) -> Policy:
+ """Creates a policy in the metalake.
+
+ Args:
+ policy_name: The name of the policy.
+ policy_type: The type of the policy.
+ comment: The comment of the policy.
+ enabled: Whether the policy is enabled.
+ content: The content of the policy.
+
+ Returns:
+ Policy: The created policy.
+
+ Raises:
+ PolicyAlreadyExistsException: If a policy with the same name
+ already exists.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def enable_policy(self, policy_name: str) -> None:
+ """Enables a policy.
+
+ Args:
+ policy_name: The name of the policy.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def disable_policy(self, policy_name: str) -> None:
+ """Disables a policy.
+
+ Args:
+ policy_name: The name of the policy.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def alter_policy(self, policy_name: str, *changes: PolicyChange) -> Policy:
+ """Alters a policy in the metalake.
+
+ Args:
+ policy_name: The name of the policy.
+ changes: The changes to apply to the policy.
+
+ Returns:
+ Policy: The altered policy.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ PolicyAlreadyExistsException: If a rename targets an existing
+ policy name.
+ """
+ raise NotImplementedError()
+
+ @abstractmethod
+ def delete_policy(self, policy_name: str) -> bool:
+ """Deletes a policy from the metalake.
+
+ Args:
+ policy_name: The name of the policy.
+
+ Returns:
+ bool: True if the policy was deleted, False if it did not exist.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ """
+ raise NotImplementedError()
+
+ def list_tag_associations_for_policy(
+ self, policy_name: str
+ ) -> list[PolicyTagAssociation]:
+ """Lists the tag associations of a policy.
+
+ Args:
+ policy_name: The name of the policy.
+
+ Returns:
+ list[PolicyTagAssociation]: The tag associations of the policy.
+
+ Raises:
+ NoSuchPolicyException: If the policy does not exist.
+ UnsupportedOperationException: If the implementation does not
+ support listing tag associations.
+ """
+ raise UnsupportedOperationException(
+ "listTagAssociationsForPolicy is not supported"
+ )
diff --git a/clients/client-python/gravitino/api/policy/policy_tag_association.py b/clients/client-python/gravitino/api/policy/policy_tag_association.py
new file mode 100644
index 0000000000..b9df8c5db7
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/policy_tag_association.py
@@ -0,0 +1,44 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_association_selector import PolicyAssociationSelector
+from gravitino.api.tag.tag import Tag
+
+
+class PolicyTagAssociation(ABC):
+ """An association between a policy and a tag, together with the selector
+ that scopes which tag assignments the association applies to."""
+
+ @abstractmethod
+ def policy(self) -> Policy:
+ """Returns the associated policy."""
+ raise NotImplementedError()
+
+ @abstractmethod
+ def tag(self) -> Tag:
+ """Returns the associated tag."""
+ raise NotImplementedError()
+
+ @abstractmethod
+ def selector(self) -> PolicyAssociationSelector:
+ """Returns the selector scoping the association."""
+ raise NotImplementedError()
diff --git a/clients/client-python/gravitino/api/policy/supports_policies.py b/clients/client-python/gravitino/api/policy/supports_policies.py
new file mode 100644
index 0000000000..fb3d4c88d2
--- /dev/null
+++ b/clients/client-python/gravitino/api/policy/supports_policies.py
@@ -0,0 +1,63 @@
+# 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.
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_list import PolicyList
+
+
+class SupportsPolicies(ABC):
+ """A metadata object that can list the policies associated with it."""
+
+ @abstractmethod
+ def list_policies(self) -> list[str]:
+ """Lists the names of the policies associated with this object.
+
+ Returns:
+ list[str]: The names of the associated policies.
+ """
+ raise NotImplementedError()
+
+ def list_policies_with_visibility(self) -> PolicyList[str]:
+ """Lists the names of the policies associated with this object,
+ together with whether some policies are inaccessible.
+
+ Returns:
+ PolicyList[str]: The policy names and the visibility flag.
+ """
+ return PolicyList(self.list_policies(), False)
+
+ @abstractmethod
+ def list_policy_infos(self) -> list[Policy]:
+ """Lists the policies associated with this object with their details.
+
+ Returns:
+ list[Policy]: The associated policies.
+ """
+ raise NotImplementedError()
+
+ def list_policy_infos_with_visibility(self) -> PolicyList[Policy]:
+ """Lists the policies associated with this object with their details,
+ together with whether some policies are inaccessible.
+
+ Returns:
+ PolicyList[Policy]: The policies and the visibility flag.
+ """
+ return PolicyList(self.list_policy_infos(), False)
diff --git a/clients/client-python/gravitino/dto/policy_dto.py b/clients/client-python/gravitino/dto/policy_dto.py
new file mode 100644
index 0000000000..d54090cbf4
--- /dev/null
+++ b/clients/client-python/gravitino/dto/policy_dto.py
@@ -0,0 +1,1006 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+from abc import abstractmethod
+from collections.abc import Callable
+from dataclasses import dataclass, field
+
+from dataclasses_json import DataClassJsonMixin, Undefined, config, dataclass_json
+
+from gravitino.api.audit import Audit
+from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_association_selector import (
+ AllValuesSelector,
+ PolicyAssociationSelector,
+ TagValueSelector,
+)
+from gravitino.api.policy.policy_content import (
+ AccessControlContent,
+ ColumnMaskContent,
+ IcebergDataCompactionContent,
+ IcebergOrphanFileRemovalContent,
+ IcebergRewriteManifestsContent,
+ IcebergSnapshotExpirationContent,
+ PolicyContent,
+ PolicyExecutionSpec,
+ RowFilterContent,
+)
+from gravitino.api.policy.policy_contents import PolicyContents
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.tag_dto import TagDTO
+from gravitino.exceptions.base import IllegalArgumentException
+from gravitino.utils.precondition import Precondition
+
+
+def _encode_object_types(types: set) -> list:
+ # The Java server writes MetadataObject.Type enum names (for example
+ # "TABLE"); it also reads them case-insensitively.
+ return sorted(object_type.name for object_type in types)
+
+
+def _decode_object_types(values: list) -> set:
+ return {MetadataObject.Type[str(value).upper()] for value in values}
+
+
+def _encode_privilege_names(names: list) -> list:
+ # Mirrors PrivilegeDTO: privilege names are written in lower case.
+ return [name.name.lower() for name in names]
+
+
+def _decode_privilege_names(values: list) -> list:
+ return [Privilege.Name[str(value).upper()] for value in values]
+
+
+_POLICY_CONTENT_DTO_TYPES: dict = {}
+
+
+def _exclude_none_fields(cls: type) -> type:
+ """Wraps a DTO class's ``to_dict`` so fields with None values are
+ omitted, mirroring the Java DTOs' NON_NULL serialization. (The
+ dataclasses_json Undefined.EXCLUDE setting does not strip None values
+ on the to_dict/to_json path.)"""
+ original_to_dict = cls.to_dict
+
+ def to_dict(self, encode_json: bool = False) -> dict:
+ result = original_to_dict(self, encode_json=encode_json)
+ return {key: value for key, value in result.items() if value is not None}
+
+ cls.to_dict = to_dict
+ return cls
+
+
+def _register_policy_content_dto(
+ policy_type: str,
+) -> Callable[[type], type]:
+ def decorator(cls: type) -> type:
+ _exclude_none_fields(cls)
+ _POLICY_CONTENT_DTO_TYPES[policy_type] = cls
+ return cls
+
+ return decorator
+
+
+class PolicyContentDTO(PolicyContent):
+ """Base class of the data transfer objects for policy contents.
+
+ The concrete wire type of a policy's content is selected by the sibling
+ ``policyType`` field of the enclosing policy object, mirroring the Java
+ DTOs' external-property polymorphic mapping.
+ """
+
+ @classmethod
+ def from_dict_by_type(cls, data: dict, policy_type: str) -> PolicyContentDTO:
+ """Deserializes a policy content DTO, dispatching on the policy type.
+
+ Args:
+ data: The serialized content.
+ policy_type: The policy type of the enclosing policy.
+
+ Returns:
+ PolicyContentDTO: The deserialized content DTO.
+
+ Raises:
+ IllegalArgumentException: If the policy type is an unknown
+ ``system_``-prefixed built-in type.
+ """
+ content_type = _POLICY_CONTENT_DTO_TYPES.get(policy_type)
+ if content_type is None:
+ if policy_type is not None and policy_type.lower().startswith(
+ Policy.BUILT_IN_TYPE_PREFIX
+ ):
+ raise IllegalArgumentException(
+ f"Unknown built-in policy type: {policy_type}"
+ )
+ # Any non-built-in policy type uses the custom content shape.
+ content_type = CustomContentDTO
+ return content_type.from_dict(data, infer_missing=True)
+
+ @abstractmethod
+ def to_domain_content(self) -> PolicyContent:
+ """Converts this DTO to the domain policy content."""
+ raise NotImplementedError()
+
+
+class ExecutionPeersDTO:
+ """Shared accessors for the flat maintenance execution peer fields
+ carried by the executable policy content DTOs."""
+
+ def execution_spec(self) -> PolicyExecutionSpec:
+ """Assembles the execution peers into a PolicyExecutionSpec."""
+ return PolicyExecutionSpec.of(
+ self._time_trigger,
+ self._commit_trigger,
+ self._min_interval_ms,
+ self._job_options,
+ self._updater_options,
+ )
+
+ def time_trigger(self) -> str | None:
+ return self._time_trigger
+
+ def commit_trigger(self) -> bool | None:
+ return self._commit_trigger
+
+ def min_interval_ms(self) -> int | None:
+ return self._min_interval_ms
+
+ def job_options(self) -> dict:
+ return dict(self._job_options) if self._job_options else {}
+
+ def updater_options(self) -> dict:
+ return dict(self._updater_options) if self._updater_options else {}
+
+
+@_register_policy_content_dto("custom")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class CustomContentDTO(PolicyContentDTO):
+ """Data transfer object for the content of a custom policy."""
+
+ _custom_rules: dict | None = field(
+ default=None, metadata=config(field_name="customRules")
+ )
+ _properties: dict | None = field(
+ default=None, metadata=config(field_name="properties")
+ )
+ _supported_object_types: set | None = field(
+ default=None,
+ metadata=config(
+ field_name="supportedObjectTypes",
+ encoder=_encode_object_types,
+ decoder=_decode_object_types,
+ ),
+ )
+
+ def custom_rules(self) -> dict:
+ return dict(self._custom_rules) if self._custom_rules else {}
+
+ def properties(self) -> dict:
+ return dict(self._properties) if self._properties else {}
+
+ def supported_object_types(self) -> set:
+ return (
+ set(self._supported_object_types) if self._supported_object_types else set()
+ )
+
+ def rules(self) -> dict:
+ return self.custom_rules()
+
+ def to_domain_content(self) -> PolicyContents.CustomContent:
+ return PolicyContents.CustomContent(
+ self.custom_rules(),
+ self.supported_object_types(),
+ self.properties(),
+ )
+
+
+@_register_policy_content_dto("system_iceberg_compaction")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class IcebergCompactionContentDTO(
+ PolicyContentDTO, ExecutionPeersDTO
+): # pylint: disable=too-many-instance-attributes
+ """Data transfer object for the content of an Iceberg data-compaction
+ policy."""
+
+ _min_data_file_mse: int | None = field(
+ default=None, metadata=config(field_name="minDataFileMse")
+ )
+ _min_delete_file_number: int | None = field(
+ default=None, metadata=config(field_name="minDeleteFileNumber")
+ )
+ _data_file_mse_weight: int | None = field(
+ default=None, metadata=config(field_name="dataFileMseWeight")
+ )
+ _delete_file_number_weight: int | None = field(
+ default=None, metadata=config(field_name="deleteFileNumberWeight")
+ )
+ _max_partition_num: int | None = field(
+ default=None, metadata=config(field_name="maxPartitionNum")
+ )
+ _rewrite_strategy: str | None = field(
+ default=None, metadata=config(field_name="rewriteStrategy")
+ )
+ _sort_order: str | None = field(
+ default=None, metadata=config(field_name="sortOrder")
+ )
+ _rewrite_options: dict | None = field(
+ default=None, metadata=config(field_name="rewriteOptions")
+ )
+ _time_trigger: str | None = field(
+ default=None, metadata=config(field_name="timeTrigger")
+ )
+ _commit_trigger: bool | None = field(
+ default=None, metadata=config(field_name="commitTrigger")
+ )
+ _min_interval_ms: int | None = field(
+ default=None, metadata=config(field_name="minIntervalMs")
+ )
+ _job_options: dict | None = field(
+ default=None, metadata=config(field_name="jobOptions")
+ )
+ _updater_options: dict | None = field(
+ default=None, metadata=config(field_name="updaterOptions")
+ )
+
+ def min_data_file_mse(self) -> int:
+ return (
+ self._min_data_file_mse
+ if self._min_data_file_mse is not None
+ else IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE
+ )
+
+ def min_delete_file_number(self) -> int:
+ return (
+ self._min_delete_file_number
+ if self._min_delete_file_number is not None
+ else IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER
+ )
+
+ def data_file_mse_weight(self) -> int:
+ return (
+ self._data_file_mse_weight
+ if self._data_file_mse_weight is not None
+ else IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT
+ )
+
+ def delete_file_number_weight(self) -> int:
+ return (
+ self._delete_file_number_weight
+ if self._delete_file_number_weight is not None
+ else IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT
+ )
+
+ def max_partition_num(self) -> int:
+ return (
+ self._max_partition_num
+ if self._max_partition_num is not None
+ else IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM
+ )
+
+ def rewrite_strategy(self) -> str:
+ return (
+ self._rewrite_strategy
+ if self._rewrite_strategy is not None
+ else IcebergDataCompactionContent.DEFAULT_REWRITE_STRATEGY
+ )
+
+ def sort_order(self) -> str:
+ return (
+ self._sort_order
+ if self._sort_order is not None
+ else IcebergDataCompactionContent.DEFAULT_SORT_ORDER
+ )
+
+ def rewrite_options(self) -> dict:
+ return dict(self._rewrite_options) if self._rewrite_options else {}
+
+ def supported_object_types(self) -> set:
+ return {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def properties(self) -> dict:
+ return {
+ IcebergDataCompactionContent.STRATEGY_TYPE_KEY: (
+ IcebergDataCompactionContent.STRATEGY_TYPE_VALUE
+ ),
+ IcebergDataCompactionContent.JOB_TEMPLATE_NAME_KEY: (
+ IcebergDataCompactionContent.JOB_TEMPLATE_NAME_VALUE
+ ),
+ }
+
+ def rules(self) -> dict:
+ return self.to_domain_content().rules()
+
+ def validate(self) -> None:
+ self.to_domain_content().validate()
+
+ def to_domain_content(self) -> IcebergDataCompactionContent:
+ return IcebergDataCompactionContent(
+ self.min_data_file_mse(),
+ self.min_delete_file_number(),
+ self.data_file_mse_weight(),
+ self.delete_file_number_weight(),
+ self.max_partition_num(),
+ self.rewrite_strategy(),
+ self.sort_order(),
+ self.rewrite_options(),
+ self.execution_spec(),
+ )
+
+
+@_register_policy_content_dto("system_iceberg_orphan_file_removal")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class IcebergOrphanFileRemovalContentDTO(
+ PolicyContentDTO, ExecutionPeersDTO
+): # pylint: disable=too-many-instance-attributes
+ """Data transfer object for the content of an Iceberg orphan-file-removal
+ policy."""
+
+ _older_than_days: int | None = field(
+ default=None, metadata=config(field_name="olderThanDays")
+ )
+ _location: str | None = field(default=None, metadata=config(field_name="location"))
+ _dry_run: bool | None = field(default=None, metadata=config(field_name="dryRun"))
+ _time_trigger: str | None = field(
+ default=None, metadata=config(field_name="timeTrigger")
+ )
+ _commit_trigger: bool | None = field(
+ default=None, metadata=config(field_name="commitTrigger")
+ )
+ _min_interval_ms: int | None = field(
+ default=None, metadata=config(field_name="minIntervalMs")
+ )
+ _job_options: dict | None = field(
+ default=None, metadata=config(field_name="jobOptions")
+ )
+ _updater_options: dict | None = field(
+ default=None, metadata=config(field_name="updaterOptions")
+ )
+
+ def older_than_days(self) -> int:
+ return (
+ self._older_than_days
+ if self._older_than_days is not None
+ else IcebergOrphanFileRemovalContent.DEFAULT_OLDER_THAN_DAYS
+ )
+
+ def location(self) -> str | None:
+ return self._location
+
+ def dry_run(self) -> bool:
+ return (
+ self._dry_run
+ if self._dry_run is not None
+ else IcebergOrphanFileRemovalContent.DEFAULT_DRY_RUN
+ )
+
+ def supported_object_types(self) -> set:
+ return {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def properties(self) -> dict:
+ return {
+ IcebergOrphanFileRemovalContent.STRATEGY_TYPE_KEY: (
+ IcebergOrphanFileRemovalContent.STRATEGY_TYPE_VALUE
+ ),
+ IcebergOrphanFileRemovalContent.JOB_TEMPLATE_NAME_KEY: (
+ IcebergOrphanFileRemovalContent.JOB_TEMPLATE_NAME_VALUE
+ ),
+ }
+
+ def rules(self) -> dict:
+ return self.to_domain_content().rules()
+
+ def validate(self) -> None:
+ self.to_domain_content().validate()
+
+ def to_domain_content(self) -> IcebergOrphanFileRemovalContent:
+ return IcebergOrphanFileRemovalContent(
+ self.older_than_days(),
+ self.location(),
+ self.dry_run(),
+ self.execution_spec(),
+ )
+
+
+@_register_policy_content_dto("system_iceberg_rewrite_manifests")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class IcebergRewriteManifestsContentDTO(
+ PolicyContentDTO, ExecutionPeersDTO
+): # pylint: disable=too-many-instance-attributes
+ """Data transfer object for the content of an Iceberg rewrite-manifests
+ policy. Note that the threshold fields use snake_case wire names, unlike
+ the camelCase execution peer fields."""
+
+ _manifest_count_critical: int | None = field(
+ default=None, metadata=config(field_name="manifest_count_critical")
+ )
+ _manifest_count_warning: int | None = field(
+ default=None, metadata=config(field_name="manifest_count_warning")
+ )
+ _avg_manifest_size_threshold_bytes: int | None = field(
+ default=None,
+ metadata=config(field_name="avg_manifest_size_threshold_bytes"),
+ )
+ _spec_id: int | None = field(default=None, metadata=config(field_name="spec_id"))
+ _use_caching: bool | None = field(
+ default=None, metadata=config(field_name="use_caching")
+ )
+ _time_trigger: str | None = field(
+ default=None, metadata=config(field_name="timeTrigger")
+ )
+ _commit_trigger: bool | None = field(
+ default=None, metadata=config(field_name="commitTrigger")
+ )
+ _min_interval_ms: int | None = field(
+ default=None, metadata=config(field_name="minIntervalMs")
+ )
+ _job_options: dict | None = field(
+ default=None, metadata=config(field_name="jobOptions")
+ )
+ _updater_options: dict | None = field(
+ default=None, metadata=config(field_name="updaterOptions")
+ )
+
+ def manifest_count_critical(self) -> int:
+ return (
+ self._manifest_count_critical
+ if self._manifest_count_critical is not None
+ else IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_CRITICAL
+ )
+
+ def manifest_count_warning(self) -> int:
+ return (
+ self._manifest_count_warning
+ if self._manifest_count_warning is not None
+ else IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_WARNING
+ )
+
+ def avg_manifest_size_threshold_bytes(self) -> int:
+ return (
+ self._avg_manifest_size_threshold_bytes
+ if self._avg_manifest_size_threshold_bytes is not None
+ else (
+ IcebergRewriteManifestsContent.DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES
+ )
+ )
+
+ def spec_id(self) -> int | None:
+ return self._spec_id
+
+ def use_caching(self) -> bool | None:
+ return self._use_caching
+
+ def supported_object_types(self) -> set:
+ return {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def properties(self) -> dict:
+ return {
+ IcebergRewriteManifestsContent.STRATEGY_TYPE_KEY: (
+ IcebergRewriteManifestsContent.STRATEGY_TYPE_VALUE
+ ),
+ IcebergRewriteManifestsContent.JOB_TEMPLATE_NAME_KEY: (
+ IcebergRewriteManifestsContent.JOB_TEMPLATE_NAME_VALUE
+ ),
+ }
+
+ def rules(self) -> dict:
+ return self.to_domain_content().rules()
+
+ def validate(self) -> None:
+ self.to_domain_content().validate()
+
+ def to_domain_content(self) -> IcebergRewriteManifestsContent:
+ return IcebergRewriteManifestsContent(
+ self.manifest_count_critical(),
+ self.manifest_count_warning(),
+ self.avg_manifest_size_threshold_bytes(),
+ self.spec_id(),
+ self.use_caching(),
+ self.execution_spec(),
+ )
+
+
+@_register_policy_content_dto("system_iceberg_snapshot_expiration")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class IcebergSnapshotExpirationContentDTO(
+ PolicyContentDTO, ExecutionPeersDTO
+): # pylint: disable=too-many-instance-attributes
+ """Data transfer object for the content of an Iceberg
+ snapshot-expiration policy."""
+
+ _older_than_days: int | None = field(
+ default=None, metadata=config(field_name="olderThanDays")
+ )
+ _retain_last: int | None = field(
+ default=None, metadata=config(field_name="retainLast")
+ )
+ _stream_results: bool | None = field(
+ default=None, metadata=config(field_name="streamResults")
+ )
+ _time_trigger: str | None = field(
+ default=None, metadata=config(field_name="timeTrigger")
+ )
+ _commit_trigger: bool | None = field(
+ default=None, metadata=config(field_name="commitTrigger")
+ )
+ _min_interval_ms: int | None = field(
+ default=None, metadata=config(field_name="minIntervalMs")
+ )
+ _job_options: dict | None = field(
+ default=None, metadata=config(field_name="jobOptions")
+ )
+ _updater_options: dict | None = field(
+ default=None, metadata=config(field_name="updaterOptions")
+ )
+
+ def older_than_days(self) -> int:
+ return (
+ self._older_than_days
+ if self._older_than_days is not None
+ else IcebergSnapshotExpirationContent.DEFAULT_OLDER_THAN_DAYS
+ )
+
+ def retain_last(self) -> int:
+ return (
+ self._retain_last
+ if self._retain_last is not None
+ else IcebergSnapshotExpirationContent.DEFAULT_RETAIN_LAST
+ )
+
+ def stream_results(self) -> bool:
+ return (
+ self._stream_results
+ if self._stream_results is not None
+ else IcebergSnapshotExpirationContent.DEFAULT_STREAM_RESULTS
+ )
+
+ def supported_object_types(self) -> set:
+ return {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ }
+
+ def properties(self) -> dict:
+ return {
+ IcebergSnapshotExpirationContent.STRATEGY_TYPE_KEY: (
+ IcebergSnapshotExpirationContent.STRATEGY_TYPE_VALUE
+ ),
+ IcebergSnapshotExpirationContent.JOB_TEMPLATE_NAME_KEY: (
+ IcebergSnapshotExpirationContent.JOB_TEMPLATE_NAME_VALUE
+ ),
+ }
+
+ def rules(self) -> dict:
+ return self.to_domain_content().rules()
+
+ def validate(self) -> None:
+ self.to_domain_content().validate()
+
+ def to_domain_content(self) -> IcebergSnapshotExpirationContent:
+ return IcebergSnapshotExpirationContent(
+ self.older_than_days(),
+ self.retain_last(),
+ self.stream_results(),
+ self.execution_spec(),
+ )
+
+
+@_register_policy_content_dto("system_row_filter")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class RowFilterContentDTO(PolicyContentDTO):
+ """Data transfer object for the content of a row-filter policy."""
+
+ _expression: str | None = field(
+ default=None, metadata=config(field_name="expression")
+ )
+
+ def expression(self) -> str | None:
+ return self._expression
+
+ def supported_object_types(self) -> set:
+ return {MetadataObject.Type.TABLE}
+
+ def properties(self) -> dict:
+ return {}
+
+ def rules(self) -> dict:
+ return {"expression": self._expression}
+
+ def validate(self) -> None:
+ PolicyContent.validate(self)
+ RowFilterContent.validate_source(self._expression, "row-filter expression")
+
+ def to_domain_content(self) -> RowFilterContent:
+ return RowFilterContent(self._expression)
+
+
+@_register_policy_content_dto("system_column_mask")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class ColumnMaskContentDTO(PolicyContentDTO):
+ """Data transfer object for the content of a column-mask policy."""
+
+ _expression: str | None = field(
+ default=None, metadata=config(field_name="expression")
+ )
+
+ def expression(self) -> str | None:
+ return self._expression
+
+ def supported_object_types(self) -> set:
+ return {MetadataObject.Type.TABLE, MetadataObject.Type.COLUMN}
+
+ def properties(self) -> dict:
+ return {}
+
+ def rules(self) -> dict:
+ return {"expression": self._expression}
+
+ def validate(self) -> None:
+ PolicyContent.validate(self)
+ ColumnMaskContent.validate_source(self._expression, "column-mask expression")
+
+ def to_domain_content(self) -> ColumnMaskContent:
+ return ColumnMaskContent(self._expression)
+
+
+@_register_policy_content_dto("system_access_control")
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class AccessControlContentDTO(PolicyContentDTO):
+ """Data transfer object for the content of an access-control policy."""
+
+ _privileges: list | None = field(
+ default=None,
+ metadata=config(
+ field_name="privileges",
+ encoder=_encode_privilege_names,
+ decoder=_decode_privilege_names,
+ ),
+ )
+ _applicable_roles: list | None = field(
+ default=None, metadata=config(field_name="applicableRoles")
+ )
+
+ def privileges(self) -> list:
+ return list(self._privileges) if self._privileges else []
+
+ def applicable_roles(self) -> list:
+ return list(self._applicable_roles) if self._applicable_roles else []
+
+ def supported_object_types(self) -> set:
+ return {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ MetadataObject.Type.VIEW,
+ MetadataObject.Type.FILESET,
+ MetadataObject.Type.TOPIC,
+ MetadataObject.Type.MODEL,
+ MetadataObject.Type.FUNCTION,
+ MetadataObject.Type.SEMANTIC_MODEL,
+ }
+
+ def properties(self) -> dict:
+ return {}
+
+ def rules(self) -> dict:
+ return self.to_domain_content().rules()
+
+ def validate(self) -> None:
+ self.to_domain_content().validate()
+
+ def to_domain_content(self) -> AccessControlContent:
+ return AccessControlContent(self.privileges(), self.applicable_roles())
+
+
+@_exclude_none_fields
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class PolicyAssociationSelectorDTO(DataClassJsonMixin):
+ """Data transfer object for a policy association selector."""
+
+ MAX_VALUE_LENGTH = 256
+
+ _type: str | None = field(default=None, metadata=config(field_name="type"))
+ _value: str | None = field(default=None, metadata=config(field_name="value"))
+
+ @staticmethod
+ def from_selector(
+ selector: PolicyAssociationSelector | None,
+ ) -> PolicyAssociationSelectorDTO | None:
+ """Converts an API selector to its DTO form."""
+ if selector is None:
+ return None
+ if isinstance(selector, AllValuesSelector):
+ return PolicyAssociationSelectorDTO(AllValuesSelector.TYPE, None)
+ if isinstance(selector, TagValueSelector):
+ return PolicyAssociationSelectorDTO(TagValueSelector.TYPE, selector.value())
+ raise IllegalArgumentException(
+ f"Unknown policy association selector type: {type(selector)}"
+ )
+
+ def type(self) -> str | None:
+ return self._type
+
+ def value(self) -> str | None:
+ return self._value
+
+ def to_selector(self) -> PolicyAssociationSelector:
+ """Converts this DTO to the API selector it represents."""
+ self.validate()
+ if self._type == AllValuesSelector.TYPE:
+ return AllValuesSelector.get()
+ return TagValueSelector.of(self._value)
+
+ def validate(self) -> None:
+ if self._type == AllValuesSelector.TYPE:
+ Precondition.check_argument(
+ self._value is None,
+ f"{AllValuesSelector.TYPE} selector must not carry a value",
+ )
+ elif self._type == TagValueSelector.TYPE:
+ Precondition.check_string_not_empty(
+ self._value, "tag value cannot be blank"
+ )
+ Precondition.check_argument(
+ len(self._value) <= self.MAX_VALUE_LENGTH,
+ f"tag value cannot exceed {self.MAX_VALUE_LENGTH} characters",
+ )
+ else:
+ raise IllegalArgumentException(
+ f"Unknown policy association selector type: {self._type}"
+ )
+
+
+@dataclass
+class PolicyDTO(Policy):
+ """Data transfer object representing a policy.
+
+ Serialization is implemented explicitly (rather than through
+ dataclasses_json) because the concrete type of the ``content`` field is
+ selected by the sibling ``policyType`` field, which dataclasses_json
+ cannot dispatch on.
+ """
+
+ _name: str
+ _policy_type: str
+ _content: PolicyContentDTO
+ _comment: str | None = None
+ _enabled: bool = True
+ _inherited: bool | None = None
+ _audit: AuditDTO | None = None
+
+ def name(self) -> str:
+ return self._name
+
+ def policy_type(self) -> str:
+ return self._policy_type
+
+ def comment(self) -> str | None:
+ return self._comment
+
+ def enabled(self) -> bool:
+ return self._enabled
+
+ def content(self) -> PolicyContentDTO:
+ return self._content
+
+ def inherited(self) -> bool | None:
+ return self._inherited
+
+ def audit_info(self) -> Audit:
+ return self._audit
+
+ def to_dict(self) -> dict:
+ result = {
+ "name": self._name,
+ "policyType": self._policy_type,
+ "enabled": self._enabled,
+ "content": (self._content.to_dict() if self._content is not None else None),
+ }
+ if self._comment is not None:
+ result["comment"] = self._comment
+ if self._inherited is not None:
+ result["inherited"] = self._inherited
+ if self._audit is not None:
+ result["audit"] = self._audit.to_dict()
+ return result
+
+ @classmethod
+ def from_dict(cls, data: dict) -> PolicyDTO:
+ content_data = data.get("content")
+ audit_data = data.get("audit")
+ return cls(
+ _name=data.get("name"),
+ _policy_type=data.get("policyType"),
+ _content=(
+ PolicyContentDTO.from_dict_by_type(content_data, data.get("policyType"))
+ if content_data is not None
+ else None
+ ),
+ _comment=data.get("comment"),
+ _enabled=data.get("enabled", True),
+ _inherited=data.get("inherited"),
+ _audit=(
+ AuditDTO.from_dict(audit_data, infer_missing=True)
+ if audit_data is not None
+ else None
+ ),
+ )
+
+ def to_json(self) -> str:
+ return json.dumps(self.to_dict())
+
+ @classmethod
+ def from_json(cls, json_str: str) -> PolicyDTO:
+ return cls.from_dict(json.loads(json_str))
+
+ def __eq__(self, other: object) -> bool:
+ if not isinstance(other, PolicyDTO):
+ return False
+ return (
+ self._name == other._name
+ and self._comment == other._comment
+ and self._policy_type == other._policy_type
+ and self._enabled == other._enabled
+ and self._content == other._content
+ and self._audit == other._audit
+ )
+
+ def __hash__(self) -> int:
+ return hash(
+ (
+ self._name,
+ self._comment,
+ self._policy_type,
+ self._enabled,
+ self._audit,
+ )
+ )
+
+ @staticmethod
+ def builder() -> PolicyDTO.Builder:
+ """Returns a builder for creating a PolicyDTO."""
+ return PolicyDTO.Builder()
+
+ class Builder:
+ """Builder for PolicyDTO; mirrors the Java PolicyDTO builder,
+ including its validation."""
+
+ def __init__(self):
+ self._name: str | None = None
+ self._comment: str | None = None
+ self._policy_type: str | None = None
+ self._enabled: bool = True
+ self._content: PolicyContentDTO | None = None
+ self._inherited: bool | None = None
+ self._audit: AuditDTO | None = None
+
+ def name(self, name: str) -> PolicyDTO.Builder:
+ self._name = name
+ return self
+
+ def comment(self, comment: str | None) -> PolicyDTO.Builder:
+ self._comment = comment
+ return self
+
+ def policy_type(self, policy_type: str) -> PolicyDTO.Builder:
+ self._policy_type = policy_type
+ return self
+
+ def enabled(self, enabled: bool) -> PolicyDTO.Builder:
+ self._enabled = enabled
+ return self
+
+ def content(self, content: PolicyContentDTO) -> PolicyDTO.Builder:
+ self._content = content
+ return self
+
+ def inherited(self, inherited: bool | None) -> PolicyDTO.Builder:
+ self._inherited = inherited
+ return self
+
+ def audit_info(self, audit: AuditDTO) -> PolicyDTO.Builder:
+ self._audit = audit
+ return self
+
+ def build(self) -> PolicyDTO:
+ Precondition.check_string_not_empty(
+ self._name, "Policy name cannot be empty"
+ )
+ Precondition.check_string_not_empty(
+ self._policy_type, "Policy type cannot be empty"
+ )
+ Precondition.check_argument(
+ self._content is not None, "Policy content cannot be null"
+ )
+ self._content.validate()
+ return PolicyDTO(
+ _name=self._name,
+ _policy_type=self._policy_type,
+ _content=self._content,
+ _comment=self._comment,
+ _enabled=self._enabled,
+ _inherited=self._inherited,
+ _audit=self._audit,
+ )
+
+
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class PolicyForTagAssociationDTO(DataClassJsonMixin):
+ """Data transfer object for a policy associated with a tag."""
+
+ _policy: PolicyDTO | None = field(
+ default=None,
+ metadata=config(
+ field_name="policy",
+ encoder=lambda policy: policy.to_dict() if policy is not None else None,
+ decoder=lambda data: (
+ PolicyDTO.from_dict(data) if isinstance(data, dict) else data
+ ),
+ ),
+ )
+ _selector: PolicyAssociationSelectorDTO | None = field(
+ default=None, metadata=config(field_name="selector")
+ )
+
+ def policy(self) -> PolicyDTO | None:
+ return self._policy
+
+ def selector(self) -> PolicyAssociationSelectorDTO | None:
+ return self._selector
+
+
+@dataclass_json(undefined=Undefined.EXCLUDE)
+@dataclass
+class TagForPolicyAssociationDTO(DataClassJsonMixin):
+ """Data transfer object for a tag associated with a policy."""
+
+ _tag: TagDTO | None = field(default=None, metadata=config(field_name="tag"))
+ _selector: PolicyAssociationSelectorDTO | None = field(
+ default=None, metadata=config(field_name="selector")
+ )
+
+ def tag(self) -> TagDTO | None:
+ return self._tag
+
+ def selector(self) -> PolicyAssociationSelectorDTO | None:
+ return self._selector
diff --git a/clients/client-python/gravitino/dto/requests/policy_create_request.py b/clients/client-python/gravitino/dto/requests/policy_create_request.py
new file mode 100644
index 0000000000..da53aac7d5
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/policy_create_request.py
@@ -0,0 +1,125 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+
+from dataclasses_json import config
+
+from gravitino.dto.policy_dto import PolicyContentDTO
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class PolicyCreateRequest(RESTRequest):
+ """Represents a request to create a policy.
+
+ Deserialization is implemented explicitly (rather than through
+ dataclasses_json) because the concrete type of the ``content`` field is
+ selected by the sibling ``policyType`` field, which dataclasses_json
+ cannot dispatch on. Serialization still goes through the inherited
+ dataclasses_json machinery.
+ """
+
+ _name: str = field(metadata=config(field_name="name"))
+ _policy_type: str = field(metadata=config(field_name="policyType"))
+ _comment: str | None = field(default=None, metadata=config(field_name="comment"))
+ _enabled: bool = field(default=True, metadata=config(field_name="enabled"))
+ _content: PolicyContentDTO | None = field(
+ default=None,
+ metadata=config(
+ field_name="content",
+ encoder=lambda content: content.to_dict() if content is not None else None,
+ ),
+ )
+
+ def validate(self) -> None:
+ """Validates the request.
+
+ Raises:
+ IllegalArgumentException: If the request is invalid.
+ """
+ Precondition.check_string_not_empty(self._name, '"name" must not be blank')
+ Precondition.check_string_not_empty(
+ self._policy_type, '"policyType" must not be blank'
+ )
+ Precondition.check_argument(
+ self._content is not None, '"content" must not be null'
+ )
+ self._content.validate()
+
+ @classmethod
+ def from_dict(
+ cls, kvs: dict, *, infer_missing: bool = False
+ ) -> PolicyCreateRequest:
+ """Deserializes a policy create request, dispatching the content on
+ the sibling ``policyType`` field, as PolicyDTO.from_dict does.
+
+ Args:
+ kvs: The serialized request.
+ infer_missing: Accepted for compatibility with the
+ dataclasses_json API; content deserialization always
+ infers missing fields, mirroring PolicyContentDTO.
+
+ Returns:
+ PolicyCreateRequest: The deserialized request.
+ """
+ content_data = kvs.get("content")
+ return cls(
+ _name=kvs.get("name"),
+ _policy_type=kvs.get("policyType"),
+ _comment=kvs.get("comment"),
+ _enabled=kvs.get("enabled", True),
+ _content=(
+ PolicyContentDTO.from_dict_by_type(content_data, kvs.get("policyType"))
+ if content_data is not None
+ else None
+ ),
+ )
+
+ @classmethod
+ def from_json(
+ cls, s: str, *, infer_missing: bool = False, **kwargs
+ ) -> PolicyCreateRequest:
+ """Deserializes a policy create request from a JSON string.
+
+ Extra keyword arguments are passed through to json.loads.
+ """
+ return cls.from_dict(json.loads(s, **kwargs), infer_missing=infer_missing)
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ @property
+ def policy_type(self) -> str:
+ return self._policy_type
+
+ @property
+ def comment(self) -> str | None:
+ return self._comment
+
+ @property
+ def enabled(self) -> bool:
+ return self._enabled
+
+ @property
+ def content(self) -> PolicyContentDTO | None:
+ return self._content
diff --git a/clients/client-python/gravitino/dto/requests/policy_set_request.py b/clients/client-python/gravitino/dto/requests/policy_set_request.py
new file mode 100644
index 0000000000..829cd9549c
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/policy_set_request.py
@@ -0,0 +1,40 @@
+# 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.
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from dataclasses_json import config, dataclass_json
+
+from gravitino.rest.rest_message import RESTRequest
+
+
+@dataclass_json
+@dataclass
+class PolicySetRequest(RESTRequest):
+ """Represents a request to enable or disable a policy."""
+
+ _enable: bool = field(metadata=config(field_name="enable"))
+
+ def validate(self) -> None:
+ """Validates the request."""
+ # always pass
+
+ @property
+ def enable(self) -> bool:
+ return self._enable
diff --git a/clients/client-python/gravitino/dto/requests/policy_tag_add_request.py b/clients/client-python/gravitino/dto/requests/policy_tag_add_request.py
new file mode 100644
index 0000000000..9c700fc2e1
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/policy_tag_add_request.py
@@ -0,0 +1,56 @@
+# 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.
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from dataclasses_json import config, dataclass_json
+
+from gravitino.api.policy.policy_association_selector import PolicyAssociationSelector
+from gravitino.dto.policy_dto import PolicyAssociationSelectorDTO
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass_json
+@dataclass
+class PolicyTagAddRequest(RESTRequest):
+ """Represents a request to associate a policy with a tag."""
+
+ _selector: PolicyAssociationSelectorDTO | None = field(
+ default=None, metadata=config(field_name="selector")
+ )
+
+ def validate(self) -> None:
+ """Validates the request.
+
+ Raises:
+ IllegalArgumentException: If the request is invalid.
+ """
+ Precondition.check_argument(
+ self._selector is not None, "selector must not be null"
+ )
+ self._selector.validate()
+
+ def selector(self) -> PolicyAssociationSelector:
+ """Returns the selector as an API selector."""
+ return self._selector.to_selector() if self._selector is not None else None
+
+ @property
+ def selector_dto(self) -> PolicyAssociationSelectorDTO | None:
+ return self._selector
diff --git a/clients/client-python/gravitino/dto/requests/policy_update_request.py b/clients/client-python/gravitino/dto/requests/policy_update_request.py
new file mode 100644
index 0000000000..2bf3b0c959
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/policy_update_request.py
@@ -0,0 +1,184 @@
+# 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.
+
+from __future__ import annotations
+
+import json
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+
+from dataclasses_json import config, dataclass_json
+
+from gravitino.api.policy.policy_change import PolicyChange
+from gravitino.dto.policy_dto import PolicyContentDTO
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+@dataclass_json
+class PolicyUpdateRequestBase(RESTRequest, ABC):
+ _type: str = field(init=False, metadata=config(field_name="@type"))
+
+ @abstractmethod
+ def policy_change(self) -> PolicyChange:
+ """Returns the policy change this request represents."""
+ raise NotImplementedError()
+
+
+class PolicyUpdateRequest:
+ """Request to update a policy."""
+
+ @dataclass_json
+ @dataclass
+ class RenamePolicyRequest(PolicyUpdateRequestBase):
+ """The policy update request for renaming a policy."""
+
+ _new_name: str = field(init=True, metadata=config(field_name="newName"))
+
+ def __post_init__(self) -> None:
+ self._type = "rename"
+
+ def validate(self) -> None:
+ """Validates the request.
+
+ Raises:
+ IllegalArgumentException: If the request is invalid.
+ """
+ Precondition.check_string_not_empty(
+ self._new_name,
+ '"newName" must not be blank',
+ )
+
+ @property
+ def new_name(self) -> str:
+ return self._new_name
+
+ def policy_change(self) -> PolicyChange.RenamePolicy:
+ return PolicyChange.rename(self._new_name)
+
+ @dataclass_json
+ @dataclass
+ class UpdatePolicyCommentRequest(PolicyUpdateRequestBase):
+ """The policy update request for updating a policy comment."""
+
+ _new_comment: str | None = field(metadata=config(field_name="newComment"))
+
+ def __post_init__(self) -> None:
+ self._type = "updateComment"
+
+ def validate(self) -> None:
+ """Validates the request."""
+ # always pass
+
+ @property
+ def new_comment(self) -> str | None:
+ return self._new_comment
+
+ def policy_change(self) -> PolicyChange.UpdatePolicyComment:
+ return PolicyChange.UpdatePolicyComment(self._new_comment)
+
+ @dataclass
+ class UpdatePolicyContentRequest(PolicyUpdateRequestBase):
+ """The policy update request for updating a policy's content.
+
+ Deserialization is implemented explicitly (rather than through
+ dataclasses_json) because the concrete type of the ``newContent``
+ field is selected by the sibling ``policyType`` field, which
+ dataclasses_json cannot dispatch on. Serialization still goes
+ through the inherited dataclasses_json machinery.
+ """
+
+ _policy_type: str = field(metadata=config(field_name="policyType"))
+ _new_content: PolicyContentDTO = field(
+ metadata=config(
+ field_name="newContent",
+ encoder=lambda content: (
+ content.to_dict() if content is not None else None
+ ),
+ )
+ )
+
+ def __post_init__(self) -> None:
+ self._type = "updateContent"
+
+ def validate(self) -> None:
+ """Validates the request.
+
+ Raises:
+ IllegalArgumentException: If the request is invalid.
+ """
+ Precondition.check_string_not_empty(
+ self._policy_type,
+ '"policyType" must not be blank',
+ )
+ Precondition.check_argument(
+ self._new_content is not None, '"newContent" must not be null'
+ )
+ self._new_content.validate()
+
+ @property
+ def policy_type(self) -> str:
+ return self._policy_type
+
+ @property
+ def new_content(self) -> PolicyContentDTO:
+ return self._new_content
+
+ @classmethod
+ def from_dict(
+ cls, kvs: dict, *, infer_missing: bool = False
+ ) -> PolicyUpdateRequest.UpdatePolicyContentRequest:
+ """Deserializes an update-content request, dispatching the new
+ content on the sibling ``policyType`` field, as
+ PolicyDTO.from_dict does for a policy's content.
+
+ Args:
+ kvs: The serialized request.
+ infer_missing: Accepted for compatibility with the
+ dataclasses_json API; content deserialization always
+ infers missing fields, mirroring PolicyContentDTO.
+
+ Returns:
+ UpdatePolicyContentRequest: The deserialized request.
+ """
+ content_data = kvs.get("newContent")
+ return cls(
+ _policy_type=kvs.get("policyType"),
+ _new_content=(
+ PolicyContentDTO.from_dict_by_type(
+ content_data, kvs.get("policyType")
+ )
+ if content_data is not None
+ else None
+ ),
+ )
+
+ @classmethod
+ def from_json(
+ cls, s: str, *, infer_missing: bool = False, **kwargs
+ ) -> PolicyUpdateRequest.UpdatePolicyContentRequest:
+ """Deserializes an update-content request from a JSON string.
+
+ Extra keyword arguments are passed through to json.loads.
+ """
+ return cls.from_dict(json.loads(s, **kwargs), infer_missing=infer_missing)
+
+ def policy_change(self) -> PolicyChange.UpdateContent:
+ return PolicyChange.UpdateContent(
+ self._policy_type, self._new_content.to_domain_content()
+ )
diff --git a/clients/client-python/gravitino/dto/requests/policy_updates_request.py b/clients/client-python/gravitino/dto/requests/policy_updates_request.py
new file mode 100644
index 0000000000..dac9589713
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/policy_updates_request.py
@@ -0,0 +1,57 @@
+# 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.
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from dataclasses_json import config
+
+from gravitino.dto.requests.policy_update_request import PolicyUpdateRequest
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class PolicyUpdatesRequest(RESTRequest):
+ """Represents a request to update a policy with a list of changes."""
+
+ _updates: list[PolicyUpdateRequest] = field(
+ metadata=config(field_name="updates"), default_factory=list
+ )
+
+ def __init__(self, updates: list[PolicyUpdateRequest]) -> None:
+ """
+ Creates a new PolicyUpdatesRequest.
+
+ Args:
+ updates (List[PolicyUpdateRequest]): The updates to apply to
+ the policy.
+ """
+ self._updates = updates
+
+ def validate(self) -> None:
+ """Validates the request.
+
+ Raises:
+ IllegalArgumentException: If the request is invalid.
+ """
+ Precondition.check_argument(
+ self._updates is not None, "updates must not be null"
+ )
+ for update_request in self._updates:
+ update_request.validate()
diff --git a/clients/client-python/gravitino/dto/responses/policy_response.py b/clients/client-python/gravitino/dto/responses/policy_response.py
new file mode 100644
index 0000000000..078607a4da
--- /dev/null
+++ b/clients/client-python/gravitino/dto/responses/policy_response.py
@@ -0,0 +1,200 @@
+# 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.
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from dataclasses_json import config, dataclass_json
+
+from gravitino.dto.policy_dto import (
+ PolicyAssociationSelectorDTO,
+ PolicyDTO,
+ PolicyForTagAssociationDTO,
+ TagForPolicyAssociationDTO,
+)
+from gravitino.dto.responses.base_response import BaseResponse
+from gravitino.dto.responses.name_list_response import NameListResponse
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+def _encode_policy(policy: PolicyDTO | None) -> dict | None:
+ return policy.to_dict() if policy is not None else None
+
+
+def _decode_policy(data) -> PolicyDTO | None:
+ return PolicyDTO.from_dict(data) if isinstance(data, dict) else data
+
+
+def _encode_policies(policies: list | None) -> list | None:
+ if policies is None:
+ return None
+ return [policy.to_dict() for policy in policies]
+
+
+def _decode_policies(data) -> list | None:
+ if data is None:
+ return None
+ return [
+ PolicyDTO.from_dict(policy) if isinstance(policy, dict) else policy
+ for policy in data
+ ]
+
+
+@dataclass_json
+@dataclass
+class PolicyResponse(BaseResponse):
+ """Represents a response containing a policy."""
+
+ _policy: PolicyDTO | None = field(
+ default=None,
+ metadata=config(
+ field_name="policy", encoder=_encode_policy, decoder=_decode_policy
+ ),
+ )
+
+ def policy(self) -> PolicyDTO:
+ return self._policy
+
+ def validate(self) -> None:
+ super().validate()
+ if self._policy is None:
+ raise IllegalArgumentException("Policy must not be null in response")
+
+
+@dataclass_json
+@dataclass
+class PolicyListResponse(BaseResponse):
+ """Represents a response containing a list of policies."""
+
+ _policies: list | None = field(
+ default=None,
+ metadata=config(
+ field_name="policies",
+ encoder=_encode_policies,
+ decoder=_decode_policies,
+ ),
+ )
+
+ def policies(self) -> list:
+ return self._policies
+
+ def validate(self) -> None:
+ super().validate()
+ if self._policies is None:
+ raise IllegalArgumentException("Policies must not be null in response")
+ for policy in self._policies:
+ if policy.content() is None:
+ raise IllegalArgumentException(
+ "Policy content must not be null in response"
+ )
+ policy.content().validate()
+
+
+@dataclass_json
+@dataclass
+class PolicyNameListResponse(NameListResponse):
+ """Represents a response containing a list of policy names, plus whether
+ some policies are inaccessible to the caller."""
+
+ _has_inaccessible_policies: bool = field(
+ default=False, metadata=config(field_name="hasInaccessiblePolicies")
+ )
+
+ def has_inaccessible_policies(self) -> bool:
+ return self._has_inaccessible_policies
+
+
+@dataclass_json
+@dataclass
+class MetadataObjectPolicyListResponse(PolicyListResponse):
+ """Represents a response containing the policies of a metadata object,
+ plus whether some policies are inaccessible to the caller."""
+
+ _has_inaccessible_policies: bool = field(
+ default=False, metadata=config(field_name="hasInaccessiblePolicies")
+ )
+
+ def has_inaccessible_policies(self) -> bool:
+ return self._has_inaccessible_policies
+
+
+@dataclass_json
+@dataclass
+class PolicyTagAssociationResponse(BaseResponse):
+ """Represents a response containing a policy-tag association."""
+
+ _policy: str | None = field(default=None, metadata=config(field_name="policy"))
+ _tag: str | None = field(default=None, metadata=config(field_name="tag"))
+ _selector: PolicyAssociationSelectorDTO | None = field(
+ default=None, metadata=config(field_name="selector")
+ )
+
+ def policy(self) -> str:
+ return self._policy
+
+ def tag(self) -> str:
+ return self._tag
+
+ def selector(self) -> PolicyAssociationSelectorDTO:
+ return self._selector
+
+ def validate(self) -> None:
+ super().validate()
+ if self._policy is None or self._policy.strip() == "":
+ raise IllegalArgumentException("Policy must not be blank in response")
+ if self._tag is None or self._tag.strip() == "":
+ raise IllegalArgumentException("Tag must not be blank in response")
+ if self._selector is None:
+ raise IllegalArgumentException("Selector must not be null in response")
+ self._selector.validate()
+
+
+@dataclass_json
+@dataclass
+class PolicyForTagAssociationListResponse(BaseResponse):
+ """Represents a response containing the policy associations of a tag."""
+
+ _associations: list[PolicyForTagAssociationDTO] | None = field(
+ default=None, metadata=config(field_name="associations")
+ )
+
+ def associations(self) -> list:
+ return self._associations
+
+ def validate(self) -> None:
+ super().validate()
+ if self._associations is None:
+ raise IllegalArgumentException("Associations must not be null in response")
+
+
+@dataclass_json
+@dataclass
+class TagForPolicyAssociationListResponse(BaseResponse):
+ """Represents a response containing the tag associations of a policy."""
+
+ _associations: list[TagForPolicyAssociationDTO] | None = field(
+ default=None, metadata=config(field_name="associations")
+ )
+
+ def associations(self) -> list:
+ return self._associations
+
+ def validate(self) -> None:
+ super().validate()
+ if self._associations is None:
+ raise IllegalArgumentException("Associations must not be null in response")
diff --git a/clients/client-python/gravitino/exceptions/base.py b/clients/client-python/gravitino/exceptions/base.py
index db9061ad65..b9a01b3c79 100644
--- a/clients/client-python/gravitino/exceptions/base.py
+++ b/clients/client-python/gravitino/exceptions/base.py
@@ -189,6 +189,18 @@ class TagAlreadyAssociatedException(AlreadyExistsException):
"""Exception thrown when a tag with specified name already associated to a metadata object."""
+class NoSuchPolicyException(NotFoundException):
+ """An exception thrown when a policy with specified name is not existed."""
+
+
+class PolicyAlreadyExistsException(AlreadyExistsException):
+ """An exception thrown when a policy with specified name already exists."""
+
+
+class PolicyAlreadyAssociatedException(AlreadyExistsException):
+ """Exception thrown when a policy with specified name already associated to a tag."""
+
+
class JobTemplateAlreadyExistsException(AlreadyExistsException):
"""An exception thrown when a job template with specified name already exists."""
diff --git a/clients/client-python/tests/unittests/api/policy/__init__.py b/clients/client-python/tests/unittests/api/policy/__init__.py
new file mode 100644
index 0000000000..13a83393a9
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/policy/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git a/clients/client-python/tests/unittests/api/policy/test_policy_change.py b/clients/client-python/tests/unittests/api/policy/test_policy_change.py
new file mode 100644
index 0000000000..04382d5a95
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/policy/test_policy_change.py
@@ -0,0 +1,61 @@
+# 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.
+
+import unittest
+
+from gravitino.api.policy.policy_change import PolicyChange
+from gravitino.api.policy.policy_contents import PolicyContents
+
+
+class TestPolicyChange(unittest.TestCase):
+ def test_rename(self) -> None:
+ expected_new_name = "new_name"
+ policy_change = PolicyChange.rename(expected_new_name)
+ self.assertEqual(expected_new_name, policy_change.new_name)
+ self.assertEqual(f"RENAME POLICY {expected_new_name}", str(policy_change))
+
+ def test_update_comment(self) -> None:
+ expected_new_comment = "new_comment"
+ policy_change = PolicyChange.update_comment(expected_new_comment)
+ self.assertEqual(expected_new_comment, policy_change.new_comment)
+ self.assertEqual(
+ f"UPDATE POLICY COMMENT {expected_new_comment}", str(policy_change)
+ )
+
+ def test_update_content(self) -> None:
+ content = PolicyContents.row_filter("age > 18")
+ policy_change = PolicyChange.update_content("system_row_filter", content)
+ self.assertEqual("system_row_filter", policy_change.policy_type)
+ self.assertEqual(content, policy_change.content)
+ self.assertEqual(
+ f"UPDATE POLICY CONTENT policyType=system_row_filter, content={content}",
+ str(policy_change),
+ )
+
+ def test_update_content_hash_with_nested_custom_rules(self) -> None:
+ content = PolicyContents.custom({"rule": ["a", "b"]})
+ policy_change = PolicyChange.update_content("custom", content)
+ equal_change = PolicyChange.update_content(
+ "custom", PolicyContents.custom({"rule": ["a", "b"]})
+ )
+ self.assertEqual(policy_change, equal_change)
+ self.assertEqual(hash(policy_change), hash(equal_change))
+
+ def test_equality(self) -> None:
+ self.assertEqual(PolicyChange.rename("a"), PolicyChange.rename("a"))
+ self.assertNotEqual(PolicyChange.rename("a"), PolicyChange.rename("b"))
+ self.assertNotEqual(PolicyChange.rename("a"), PolicyChange.update_comment("a"))
diff --git a/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py b/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py
new file mode 100644
index 0000000000..48bd670a36
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py
@@ -0,0 +1,263 @@
+# 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.
+
+import json
+import unittest
+
+from gravitino.api.policy.policy_contents import PolicyContents
+from gravitino.dto.policy_dto import (
+ AccessControlContentDTO,
+ ColumnMaskContentDTO,
+ CustomContentDTO,
+ IcebergCompactionContentDTO,
+ IcebergOrphanFileRemovalContentDTO,
+ IcebergRewriteManifestsContentDTO,
+ IcebergSnapshotExpirationContentDTO,
+ PolicyAssociationSelectorDTO,
+ PolicyContentDTO,
+ RowFilterContentDTO,
+)
+from gravitino.dto.requests.policy_create_request import PolicyCreateRequest
+from gravitino.dto.requests.policy_set_request import PolicySetRequest
+from gravitino.dto.requests.policy_tag_add_request import PolicyTagAddRequest
+from gravitino.dto.requests.policy_update_request import PolicyUpdateRequest
+from gravitino.dto.requests.policy_updates_request import PolicyUpdatesRequest
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+def _row_filter_content() -> RowFilterContentDTO:
+ return RowFilterContentDTO.from_dict({"expression": "age > 18"}, infer_missing=True)
+
+
+_CONTENT_ROUND_TRIP_CASES = [
+ (
+ "custom",
+ {
+ "customRules": {"rule1": 456},
+ "supportedObjectTypes": ["CATALOG", "TABLE"],
+ "properties": {"k": "v"},
+ },
+ CustomContentDTO,
+ ),
+ ("system_iceberg_compaction", {"minDataFileMse": 7}, IcebergCompactionContentDTO),
+ (
+ "system_iceberg_orphan_file_removal",
+ {"olderThanDays": 10, "location": "s3://b/t", "dryRun": True},
+ IcebergOrphanFileRemovalContentDTO,
+ ),
+ (
+ "system_iceberg_rewrite_manifests",
+ {"manifest_count_critical": 900},
+ IcebergRewriteManifestsContentDTO,
+ ),
+ (
+ "system_iceberg_snapshot_expiration",
+ {"olderThanDays": 9},
+ IcebergSnapshotExpirationContentDTO,
+ ),
+ ("system_row_filter", {"expression": "age > 18"}, RowFilterContentDTO),
+ ("system_column_mask", {"expression": "mask(x)"}, ColumnMaskContentDTO),
+ (
+ "system_access_control",
+ {"privileges": ["select_table"], "applicableRoles": ["analyst"]},
+ AccessControlContentDTO,
+ ),
+]
+
+
+class TestPolicyCreateRequest(unittest.TestCase):
+ def test_serialization_and_validation(self) -> None:
+ request = PolicyCreateRequest(
+ _name="policy1",
+ _policy_type="system_row_filter",
+ _comment="a comment",
+ _enabled=False,
+ _content=_row_filter_content(),
+ )
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual("policy1", wire["name"])
+ self.assertEqual("system_row_filter", wire["policyType"])
+ self.assertEqual("a comment", wire["comment"])
+ self.assertEqual(False, wire["enabled"])
+ self.assertEqual({"expression": "age > 18"}, wire["content"])
+
+ def test_default_enabled(self) -> None:
+ request = PolicyCreateRequest(
+ _name="policy1",
+ _policy_type="system_row_filter",
+ _content=_row_filter_content(),
+ )
+ self.assertTrue(request.enabled)
+ self.assertTrue(json.loads(request.to_json())["enabled"])
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyCreateRequest(
+ _name=" ",
+ _policy_type="system_row_filter",
+ _content=_row_filter_content(),
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyCreateRequest(
+ _name="p", _policy_type="", _content=_row_filter_content()
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyCreateRequest(
+ _name="p", _policy_type="system_row_filter", _content=None
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyCreateRequest(
+ _name="p",
+ _policy_type="system_row_filter",
+ _content=RowFilterContentDTO.from_dict(
+ {"expression": ""}, infer_missing=True
+ ),
+ ).validate()
+
+ def test_json_round_trip_decodes_content_by_policy_type(self) -> None:
+ for policy_type, payload, content_type in _CONTENT_ROUND_TRIP_CASES:
+ with self.subTest(policy_type=policy_type):
+ content = PolicyContentDTO.from_dict_by_type(dict(payload), policy_type)
+ request = PolicyCreateRequest(
+ _name="policy1",
+ _policy_type=policy_type,
+ _comment="a comment",
+ _enabled=False,
+ _content=content,
+ )
+ decoded = PolicyCreateRequest.from_json(request.to_json())
+ self.assertIsInstance(decoded.content, content_type)
+ decoded.validate()
+ self.assertEqual(
+ json.loads(request.to_json()), json.loads(decoded.to_json())
+ )
+
+
+class TestPolicyUpdateRequest(unittest.TestCase):
+ def test_rename_request(self) -> None:
+ request = PolicyUpdateRequest.RenamePolicyRequest("new_name")
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual("rename", wire["@type"])
+ self.assertEqual("new_name", wire["newName"])
+ self.assertEqual("new_name", request.policy_change().new_name)
+ with self.assertRaises(IllegalArgumentException):
+ PolicyUpdateRequest.RenamePolicyRequest(" ").validate()
+
+ def test_update_comment_request(self) -> None:
+ request = PolicyUpdateRequest.UpdatePolicyCommentRequest("new comment")
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual("updateComment", wire["@type"])
+ self.assertEqual("new comment", wire["newComment"])
+ self.assertEqual("new comment", request.policy_change().new_comment)
+
+ def test_update_content_request(self) -> None:
+ request = PolicyUpdateRequest.UpdatePolicyContentRequest(
+ "system_row_filter", _row_filter_content()
+ )
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual("updateContent", wire["@type"])
+ self.assertEqual("system_row_filter", wire["policyType"])
+ self.assertEqual({"expression": "age > 18"}, wire["newContent"])
+ change = request.policy_change()
+ self.assertEqual("system_row_filter", change.policy_type)
+ self.assertEqual(PolicyContents.row_filter("age > 18"), change.content)
+ with self.assertRaises(IllegalArgumentException):
+ PolicyUpdateRequest.UpdatePolicyContentRequest(
+ " ", _row_filter_content()
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyUpdateRequest.UpdatePolicyContentRequest(
+ "system_row_filter", None
+ ).validate()
+
+ def test_update_content_json_round_trip_decodes_content(self) -> None:
+ for policy_type, payload, content_type in _CONTENT_ROUND_TRIP_CASES:
+ with self.subTest(policy_type=policy_type):
+ content = PolicyContentDTO.from_dict_by_type(dict(payload), policy_type)
+ request = PolicyUpdateRequest.UpdatePolicyContentRequest(
+ policy_type, content
+ )
+ decoded = PolicyUpdateRequest.UpdatePolicyContentRequest.from_json(
+ request.to_json()
+ )
+ self.assertIsInstance(decoded.new_content, content_type)
+ decoded.validate()
+ self.assertEqual(
+ json.loads(request.to_json()), json.loads(decoded.to_json())
+ )
+ change = decoded.policy_change()
+ self.assertEqual(policy_type, change.policy_type)
+ self.assertEqual(content.to_domain_content(), change.content)
+
+
+class TestPolicyUpdatesRequest(unittest.TestCase):
+ def test_serialization_and_validation(self) -> None:
+ request = PolicyUpdatesRequest(
+ [
+ PolicyUpdateRequest.RenamePolicyRequest("new_name"),
+ PolicyUpdateRequest.UpdatePolicyCommentRequest("c"),
+ ]
+ )
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual(2, len(wire["updates"]))
+ self.assertEqual("rename", wire["updates"][0]["@type"])
+ self.assertEqual("updateComment", wire["updates"][1]["@type"])
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyUpdatesRequest(None).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyUpdatesRequest(
+ [PolicyUpdateRequest.RenamePolicyRequest(" ")]
+ ).validate()
+
+
+class TestPolicySetRequest(unittest.TestCase):
+ def test_serialization(self) -> None:
+ self.assertEqual(
+ {"enable": False}, json.loads(PolicySetRequest(False).to_json())
+ )
+ self.assertEqual({"enable": True}, json.loads(PolicySetRequest(True).to_json()))
+ PolicySetRequest(True).validate()
+
+
+class TestPolicyTagAddRequest(unittest.TestCase):
+ def test_serialization_and_selector(self) -> None:
+ request = PolicyTagAddRequest(PolicyAssociationSelectorDTO("TAG_VALUE", "gold"))
+ request.validate()
+ wire = json.loads(request.to_json())
+ self.assertEqual({"type": "TAG_VALUE", "value": "gold"}, wire["selector"])
+ selector = request.selector()
+ self.assertEqual("TAG_VALUE", selector.type())
+ self.assertEqual("gold", selector.value())
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyTagAddRequest(None).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyTagAddRequest(
+ PolicyAssociationSelectorDTO("ALL_VALUES", "gold")
+ ).validate()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/clients/client-python/tests/unittests/dto/responses/test_policy_responses.py b/clients/client-python/tests/unittests/dto/responses/test_policy_responses.py
new file mode 100644
index 0000000000..891d835b96
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/responses/test_policy_responses.py
@@ -0,0 +1,190 @@
+# 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.
+
+import json
+import unittest
+
+from gravitino.dto.responses.policy_response import (
+ MetadataObjectPolicyListResponse,
+ PolicyForTagAssociationListResponse,
+ PolicyListResponse,
+ PolicyNameListResponse,
+ PolicyResponse,
+ PolicyTagAssociationResponse,
+ TagForPolicyAssociationListResponse,
+)
+from gravitino.exceptions.base import IllegalArgumentException
+
+_POLICY = {
+ "name": "policy1",
+ "policyType": "system_access_control",
+ "enabled": True,
+ "content": {"privileges": ["select_table"], "applicableRoles": ["analyst"]},
+}
+
+
+class TestPolicyResponse(unittest.TestCase):
+ def test_policy_response(self) -> None:
+ response = PolicyResponse.from_json(
+ json.dumps({"code": 0, "policy": _POLICY}), infer_missing=True
+ )
+ response.validate()
+ self.assertEqual(0, response.code())
+ self.assertEqual("policy1", response.policy().name())
+ round_tripped = PolicyResponse.from_json(response.to_json(), infer_missing=True)
+ self.assertEqual(response.policy(), round_tripped.policy())
+
+ def test_policy_response_null_policy_invalid(self) -> None:
+ response = PolicyResponse.from_json(json.dumps({"code": 0}), infer_missing=True)
+ with self.assertRaises(IllegalArgumentException):
+ response.validate()
+
+
+class TestPolicyListResponse(unittest.TestCase):
+ def test_policy_list_response(self) -> None:
+ response = PolicyListResponse.from_json(
+ json.dumps({"code": 0, "policies": [_POLICY, _POLICY]}),
+ infer_missing=True,
+ )
+ response.validate()
+ self.assertEqual(2, len(response.policies()))
+ self.assertEqual("policy1", response.policies()[0].name())
+
+ def test_policy_list_response_null_invalid(self) -> None:
+ response = PolicyListResponse.from_json(
+ json.dumps({"code": 0}), infer_missing=True
+ )
+ with self.assertRaises(IllegalArgumentException):
+ response.validate()
+
+ def test_policy_name_list_response(self) -> None:
+ response = PolicyNameListResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "names": ["policy1", "policy2"],
+ "hasInaccessiblePolicies": True,
+ }
+ ),
+ infer_missing=True,
+ )
+ response.validate()
+ self.assertEqual(["policy1", "policy2"], response.names)
+ self.assertTrue(response.has_inaccessible_policies())
+
+ def test_policy_name_list_response_default_visibility(self) -> None:
+ response = PolicyNameListResponse.from_json(
+ json.dumps({"code": 0, "names": []}), infer_missing=True
+ )
+ self.assertFalse(response.has_inaccessible_policies())
+
+ def test_metadata_object_policy_list_response(self) -> None:
+ response = MetadataObjectPolicyListResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "policies": [_POLICY],
+ "hasInaccessiblePolicies": True,
+ }
+ ),
+ infer_missing=True,
+ )
+ response.validate()
+ self.assertEqual(1, len(response.policies()))
+ self.assertTrue(response.has_inaccessible_policies())
+
+
+class TestPolicyTagAssociationResponse(unittest.TestCase):
+ def test_association_response(self) -> None:
+ response = PolicyTagAssociationResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "policy": "policy1",
+ "tag": "tag1",
+ "selector": {"type": "TAG_VALUE", "value": "gold"},
+ }
+ ),
+ infer_missing=True,
+ )
+ response.validate()
+ self.assertEqual("policy1", response.policy())
+ self.assertEqual("tag1", response.tag())
+ self.assertEqual("gold", response.selector().value())
+
+ def test_association_response_invalid(self) -> None:
+ response = PolicyTagAssociationResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "policy": "policy1",
+ "tag": "tag1",
+ "selector": {"type": "ALL_VALUES", "value": "gold"},
+ }
+ ),
+ infer_missing=True,
+ )
+ with self.assertRaises(IllegalArgumentException):
+ response.validate()
+
+
+class TestAssociationListResponses(unittest.TestCase):
+ def test_policy_for_tag_association_list_response(self) -> None:
+ response = PolicyForTagAssociationListResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "associations": [
+ {
+ "policy": _POLICY,
+ "selector": {"type": "ALL_VALUES"},
+ }
+ ],
+ }
+ ),
+ infer_missing=True,
+ )
+ response.validate()
+ associations = response.associations()
+ self.assertEqual(1, len(associations))
+ self.assertEqual("policy1", associations[0].policy().name())
+ self.assertEqual("ALL_VALUES", associations[0].selector().type())
+
+ def test_tag_for_policy_association_list_response(self) -> None:
+ response = TagForPolicyAssociationListResponse.from_json(
+ json.dumps(
+ {
+ "code": 0,
+ "associations": [
+ {
+ "tag": {"name": "tag1", "properties": {}},
+ "selector": {"type": "ALL_VALUES"},
+ }
+ ],
+ }
+ ),
+ infer_missing=True,
+ )
+ response.validate()
+ associations = response.associations()
+ self.assertEqual(1, len(associations))
+ self.assertEqual("tag1", associations[0].tag().name())
+ self.assertEqual("ALL_VALUES", associations[0].selector().type())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/clients/client-python/tests/unittests/dto/test_policy_dto.py b/clients/client-python/tests/unittests/dto/test_policy_dto.py
new file mode 100644
index 0000000000..7b5f92010c
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/test_policy_dto.py
@@ -0,0 +1,390 @@
+# 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.
+
+import json
+import unittest
+
+from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.policy.policy_association_selector import (
+ AllValuesSelector,
+ TagValueSelector,
+)
+from gravitino.api.policy.policy_content import PolicyExecutionSpec
+from gravitino.api.policy.policy_contents import PolicyContents
+from gravitino.dto.policy_dto import (
+ AccessControlContentDTO,
+ ColumnMaskContentDTO,
+ CustomContentDTO,
+ IcebergCompactionContentDTO,
+ IcebergOrphanFileRemovalContentDTO,
+ IcebergRewriteManifestsContentDTO,
+ IcebergSnapshotExpirationContentDTO,
+ PolicyAssociationSelectorDTO,
+ PolicyContentDTO,
+ PolicyDTO,
+ PolicyForTagAssociationDTO,
+ RowFilterContentDTO,
+ TagForPolicyAssociationDTO,
+)
+from gravitino.dto.tag_dto import TagDTO
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+def _policy_json(policy_type: str, content: dict) -> str:
+ return json.dumps(
+ {
+ "name": "policy1",
+ "comment": "a comment",
+ "policyType": policy_type,
+ "enabled": True,
+ "content": content,
+ }
+ )
+
+
+class TestPolicyDTO(unittest.TestCase):
+ def test_access_control_round_trip(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json(
+ "system_access_control",
+ {
+ "privileges": ["select_table", "MODIFY_TABLE"],
+ "applicableRoles": ["analyst"],
+ },
+ )
+ )
+ self.assertEqual("policy1", policy.name())
+ self.assertEqual("system_access_control", policy.policy_type())
+ self.assertEqual("a comment", policy.comment())
+ self.assertTrue(policy.enabled())
+ content = policy.content()
+ self.assertIsInstance(content, AccessControlContentDTO)
+ self.assertEqual(
+ [Privilege.Name.SELECT_TABLE, Privilege.Name.MODIFY_TABLE],
+ content.privileges(),
+ )
+ self.assertEqual(["analyst"], content.applicable_roles())
+ # Privilege names are written in lower case, mirroring PrivilegeDTO.
+ self.assertEqual(
+ ["modify_table", "select_table"],
+ sorted(policy.to_dict()["content"]["privileges"]),
+ )
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_access_control_probe_table_like_round_trip(self) -> None:
+ # The Java server permits PROBE_TABLE_LIKE in access-control
+ # policies (see TestPolicyDTO.testAccessControlPolicySerDe), so
+ # decoding such a policy must not raise KeyError.
+ policy = PolicyDTO.from_json(
+ _policy_json(
+ "system_access_control",
+ {
+ "privileges": ["SELECT_TABLE", "PROBE_TABLE_LIKE"],
+ "applicableRoles": ["analyst", "auditor"],
+ },
+ )
+ )
+ content = policy.content()
+ self.assertIsInstance(content, AccessControlContentDTO)
+ self.assertEqual(
+ [Privilege.Name.SELECT_TABLE, Privilege.Name.PROBE_TABLE_LIKE],
+ content.privileges(),
+ )
+ self.assertEqual(["analyst", "auditor"], content.applicable_roles())
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_access_control_domain_conversion(self) -> None:
+ dto = AccessControlContentDTO.from_dict(
+ {"privileges": ["select_table"], "applicableRoles": ["r1"]},
+ infer_missing=True,
+ )
+ domain = dto.to_domain_content()
+ self.assertEqual(
+ PolicyContents.access_control([Privilege.Name.SELECT_TABLE], ["r1"]),
+ domain,
+ )
+ dto.validate()
+ with self.assertRaises(IllegalArgumentException):
+ AccessControlContentDTO.from_dict({}, infer_missing=True).validate()
+
+ def test_compaction_round_trip_and_defaults(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json("system_iceberg_compaction", {"minDataFileMse": 7})
+ )
+ content = policy.content()
+ self.assertIsInstance(content, IcebergCompactionContentDTO)
+ self.assertEqual(7, content.min_data_file_mse())
+ self.assertEqual(1, content.min_delete_file_number())
+ self.assertEqual(100, content.delete_file_number_weight())
+ self.assertEqual("binpack", content.rewrite_strategy())
+ self.assertEqual(PolicyExecutionSpec.empty(), content.execution_spec())
+ # Unset fields are omitted from the wire form.
+ self.assertEqual({"minDataFileMse": 7}, policy.to_dict()["content"])
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_compaction_execution_peers_round_trip(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json(
+ "system_iceberg_snapshot_expiration",
+ {
+ "olderThanDays": 9,
+ "timeTrigger": "0 0 * * *",
+ "commitTrigger": False,
+ "minIntervalMs": 60000,
+ "jobOptions": {"k": "v"},
+ },
+ )
+ )
+ content = policy.content()
+ self.assertIsInstance(content, IcebergSnapshotExpirationContentDTO)
+ self.assertEqual(9, content.older_than_days())
+ self.assertEqual(1, content.retain_last())
+ spec = content.execution_spec()
+ self.assertEqual("0 0 * * *", spec.time_trigger())
+ self.assertEqual(False, spec.commit_trigger())
+ self.assertEqual(60000, spec.min_interval_ms())
+ self.assertEqual({"k": "v"}, spec.job_options())
+ domain = content.to_domain_content()
+ self.assertEqual(
+ PolicyContents.iceberg_snapshot_expiration(
+ older_than_days=9,
+ time_trigger="0 0 * * *",
+ commit_trigger=False,
+ min_interval_ms=60000,
+ job_options={"k": "v"},
+ ),
+ domain,
+ )
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_orphan_file_removal_round_trip(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json(
+ "system_iceberg_orphan_file_removal",
+ {"olderThanDays": 10, "location": "s3://b/t", "dryRun": True},
+ )
+ )
+ content = policy.content()
+ self.assertIsInstance(content, IcebergOrphanFileRemovalContentDTO)
+ self.assertEqual(10, content.older_than_days())
+ self.assertEqual("s3://b/t", content.location())
+ self.assertTrue(content.dry_run())
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_rewrite_manifests_snake_case_wire_names(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json(
+ "system_iceberg_rewrite_manifests",
+ {
+ "manifest_count_critical": 900,
+ "manifest_count_warning": 200,
+ "avg_manifest_size_threshold_bytes": 1024,
+ "spec_id": 3,
+ "use_caching": True,
+ },
+ )
+ )
+ content = policy.content()
+ self.assertIsInstance(content, IcebergRewriteManifestsContentDTO)
+ self.assertEqual(900, content.manifest_count_critical())
+ self.assertEqual(200, content.manifest_count_warning())
+ self.assertEqual(1024, content.avg_manifest_size_threshold_bytes())
+ self.assertEqual(3, content.spec_id())
+ self.assertTrue(content.use_caching())
+ wire = policy.to_dict()["content"]
+ self.assertEqual(900, wire["manifest_count_critical"])
+ self.assertEqual(3, wire["spec_id"])
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ def test_rewrite_manifests_defaults(self) -> None:
+ content = IcebergRewriteManifestsContentDTO.from_dict({}, infer_missing=True)
+ self.assertEqual(500, content.manifest_count_critical())
+ self.assertEqual(100, content.manifest_count_warning())
+ self.assertEqual(8388608, content.avg_manifest_size_threshold_bytes())
+ self.assertEqual({}, content.to_dict())
+
+ def test_row_filter_and_column_mask_round_trip(self) -> None:
+ policy = PolicyDTO.from_json(
+ _policy_json("system_row_filter", {"expression": "age > 18"})
+ )
+ self.assertIsInstance(policy.content(), RowFilterContentDTO)
+ self.assertEqual("age > 18", policy.content().expression())
+ self.assertEqual(
+ PolicyContents.row_filter("age > 18"),
+ policy.content().to_domain_content(),
+ )
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ policy = PolicyDTO.from_json(
+ _policy_json("system_column_mask", {"expression": "mask(x)"})
+ )
+ self.assertIsInstance(policy.content(), ColumnMaskContentDTO)
+ self.assertEqual(
+ {MetadataObject.Type.TABLE, MetadataObject.Type.COLUMN},
+ policy.content().supported_object_types(),
+ )
+
+ def test_custom_content_and_unknown_type_fallback(self) -> None:
+ content_dict = {
+ "customRules": {"rule1": 456},
+ "supportedObjectTypes": ["CATALOG", "TABLE"],
+ "properties": {"k": "v"},
+ }
+ policy = PolicyDTO.from_json(_policy_json("custom", content_dict))
+ self.assertIsInstance(policy.content(), CustomContentDTO)
+ self.assertEqual({"rule1": 456}, policy.content().rules())
+ self.assertEqual(
+ {MetadataObject.Type.CATALOG, MetadataObject.Type.TABLE},
+ policy.content().supported_object_types(),
+ )
+ self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))
+
+ # Any non-built-in policy type also uses the custom content shape.
+ policy = PolicyDTO.from_json(_policy_json("my_custom_type", content_dict))
+ self.assertIsInstance(policy.content(), CustomContentDTO)
+
+ def test_unknown_system_type_rejected(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyDTO.from_json(_policy_json("system_unknown", {}))
+
+ def test_builder_validation(self) -> None:
+ content = RowFilterContentDTO.from_dict(
+ {"expression": "x > 1"}, infer_missing=True
+ )
+ policy = (
+ PolicyDTO.builder()
+ .name("p")
+ .policy_type("system_row_filter")
+ .content(content)
+ .build()
+ )
+ self.assertEqual("p", policy.name())
+ self.assertTrue(policy.enabled())
+ with self.assertRaises(IllegalArgumentException):
+ PolicyDTO.builder().policy_type("system_row_filter").content(
+ content
+ ).build()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyDTO.builder().name("p").policy_type("system_row_filter").build()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyDTO.builder().name("p").policy_type("system_row_filter").content(
+ RowFilterContentDTO.from_dict({"expression": " "}, infer_missing=True)
+ ).build()
+
+ def test_equality_ignores_inherited(self) -> None:
+ def build(inherited):
+ return PolicyDTO(
+ _name="p",
+ _policy_type="system_row_filter",
+ _content=RowFilterContentDTO.from_dict(
+ {"expression": "x > 1"}, infer_missing=True
+ ),
+ _inherited=inherited,
+ )
+
+ self.assertEqual(build(True), build(None))
+ self.assertEqual(hash(build(True)), hash(build(None)))
+ self.assertNotEqual(
+ build(True),
+ PolicyDTO.from_json(
+ _policy_json("system_row_filter", {"expression": "y > 2"})
+ ),
+ )
+
+
+class TestPolicyAssociationSelectorDTO(unittest.TestCase):
+ def test_all_values(self) -> None:
+ dto = PolicyAssociationSelectorDTO.from_selector(AllValuesSelector.get())
+ self.assertEqual("ALL_VALUES", dto.type())
+ self.assertIsNone(dto.value())
+ self.assertEqual({"type": "ALL_VALUES"}, dto.to_dict())
+ self.assertEqual(AllValuesSelector.get(), dto.to_selector())
+ dto.validate()
+
+ def test_tag_value(self) -> None:
+ dto = PolicyAssociationSelectorDTO.from_selector(TagValueSelector.of("gold"))
+ self.assertEqual("TAG_VALUE", dto.type())
+ self.assertEqual("gold", dto.value())
+ self.assertEqual(TagValueSelector.of("gold"), dto.to_selector())
+ round_tripped = PolicyAssociationSelectorDTO.from_json(
+ dto.to_json(), infer_missing=True
+ )
+ self.assertEqual(dto, round_tripped)
+
+ def test_from_selector_none(self) -> None:
+ self.assertIsNone(PolicyAssociationSelectorDTO.from_selector(None))
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyAssociationSelectorDTO("ALL_VALUES", "gold").validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyAssociationSelectorDTO("TAG_VALUE", " ").validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyAssociationSelectorDTO("TAG_VALUE", "x" * 257).validate()
+ PolicyAssociationSelectorDTO("TAG_VALUE", "x" * 256).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyAssociationSelectorDTO("OTHER", None).validate()
+
+
+class TestAssociationDTOs(unittest.TestCase):
+ def test_policy_for_tag_association(self) -> None:
+ association = PolicyForTagAssociationDTO.from_dict(
+ {
+ "policy": json.loads(
+ _policy_json("system_row_filter", {"expression": "x > 1"})
+ ),
+ "selector": {"type": "TAG_VALUE", "value": "gold"},
+ },
+ infer_missing=True,
+ )
+ self.assertEqual("policy1", association.policy().name())
+ self.assertEqual("gold", association.selector().value())
+ round_tripped = PolicyForTagAssociationDTO.from_json(
+ association.to_json(), infer_missing=True
+ )
+ self.assertEqual(association.policy(), round_tripped.policy())
+ self.assertEqual(association.selector(), round_tripped.selector())
+
+ def test_tag_for_policy_association(self) -> None:
+ tag = TagDTO.builder().name("tag1").build()
+ association = TagForPolicyAssociationDTO(
+ _tag=tag,
+ _selector=PolicyAssociationSelectorDTO("ALL_VALUES", None),
+ )
+ round_tripped = TagForPolicyAssociationDTO.from_json(
+ association.to_json(), infer_missing=True
+ )
+ self.assertEqual("tag1", round_tripped.tag().name())
+ self.assertEqual("ALL_VALUES", round_tripped.selector().type())
+
+
+class TestPolicyContentDTODispatch(unittest.TestCase):
+ def test_dispatch_by_type(self) -> None:
+ self.assertIsInstance(
+ PolicyContentDTO.from_dict_by_type({}, "system_iceberg_compaction"),
+ IcebergCompactionContentDTO,
+ )
+ self.assertIsInstance(
+ PolicyContentDTO.from_dict_by_type({}, "custom"), CustomContentDTO
+ )
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContentDTO.from_dict_by_type({}, "system_nope")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/clients/client-python/tests/unittests/test_policy_api.py b/clients/client-python/tests/unittests/test_policy_api.py
new file mode 100644
index 0000000000..ec9a245978
--- /dev/null
+++ b/clients/client-python/tests/unittests/test_policy_api.py
@@ -0,0 +1,459 @@
+# 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.
+
+import unittest
+
+from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.policy.policy import Policy
+from gravitino.api.policy.policy_association_selector import (
+ AllValuesSelector,
+ TagValueSelector,
+)
+from gravitino.api.policy.policy_content import (
+ AccessControlContent,
+ IcebergDataCompactionContent,
+ PolicyExecutionSpec,
+)
+from gravitino.api.policy.policy_contents import PolicyContents
+from gravitino.api.policy.policy_list import PolicyList
+from gravitino.api.policy.supports_policies import SupportsPolicies
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+class TestPolicyExecutionSpec(unittest.TestCase):
+ def test_empty(self) -> None:
+ spec = PolicyExecutionSpec.of()
+ self.assertFalse(spec.has_any())
+ self.assertEqual(PolicyExecutionSpec.empty(), spec)
+ self.assertIsNone(spec.time_trigger())
+ self.assertIsNone(spec.commit_trigger())
+ self.assertIsNone(spec.min_interval_ms())
+ self.assertEqual({}, spec.job_options())
+ self.assertEqual({}, spec.updater_options())
+
+ def test_blank_time_trigger_normalized_to_none(self) -> None:
+ spec = PolicyExecutionSpec.of(time_trigger=" ")
+ self.assertIsNone(spec.time_trigger())
+ self.assertFalse(spec.has_any())
+
+ def test_commit_trigger_false_is_retained(self) -> None:
+ spec = PolicyExecutionSpec.of(commit_trigger=False)
+ self.assertEqual(False, spec.commit_trigger())
+ self.assertTrue(spec.has_any())
+
+ def test_negative_min_interval_rejected(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyExecutionSpec.of(min_interval_ms=-1)
+
+ def test_blank_option_key_or_value_rejected(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyExecutionSpec.of(job_options={" ": "v"})
+ with self.assertRaises(IllegalArgumentException):
+ PolicyExecutionSpec.of(updater_options={"k": ""})
+
+ def test_equality_and_hash(self) -> None:
+ left = PolicyExecutionSpec.of(time_trigger="0 0 * * *", job_options={"k": "v"})
+ right = PolicyExecutionSpec.of(time_trigger="0 0 * * *", job_options={"k": "v"})
+ self.assertEqual(left, right)
+ self.assertEqual(hash(left), hash(right))
+ self.assertNotEqual(left, PolicyExecutionSpec.empty())
+
+
+class TestReadRestrictionContents(unittest.TestCase):
+ def test_row_filter(self) -> None:
+ content = PolicyContents.row_filter("age > 18")
+ self.assertEqual("age > 18", content.expression())
+ self.assertEqual({MetadataObject.Type.TABLE}, content.supported_object_types())
+ self.assertEqual({}, content.properties())
+ self.assertEqual({"expression": "age > 18"}, content.rules())
+ content.validate()
+
+ def test_row_filter_blank_expression_rejected(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.row_filter(" ")
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.row_filter(None)
+
+ def test_row_filter_oversized_expression_rejected(self) -> None:
+ # 9000 two-byte characters exceed the 16 * 1024 UTF-8 byte limit.
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.row_filter("é" * 9000)
+
+ def test_column_mask(self) -> None:
+ content = PolicyContents.column_mask("mask(ssn)")
+ self.assertEqual(
+ {MetadataObject.Type.TABLE, MetadataObject.Type.COLUMN},
+ content.supported_object_types(),
+ )
+ self.assertEqual({"expression": "mask(ssn)"}, content.rules())
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.column_mask("")
+
+
+class TestAccessControlContent(unittest.TestCase):
+ def test_rules_and_types(self) -> None:
+ content = PolicyContents.access_control(
+ [Privilege.Name.SELECT_TABLE, Privilege.Name.MODIFY_TABLE],
+ ["analyst"],
+ )
+ self.assertEqual(
+ {
+ "privileges": ["SELECT_TABLE", "MODIFY_TABLE"],
+ "applicableRoles": ["analyst"],
+ },
+ content.rules(),
+ )
+ self.assertIn(MetadataObject.Type.TABLE, content.supported_object_types())
+ self.assertIn(MetadataObject.Type.VIEW, content.supported_object_types())
+ self.assertEqual({}, content.properties())
+ content.validate()
+
+ def test_empty_privileges_rejected(self) -> None:
+ content = AccessControlContent([], ["analyst"])
+ with self.assertRaises(IllegalArgumentException):
+ content.validate()
+
+ def test_null_privilege_rejected(self) -> None:
+ content = AccessControlContent([None], ["analyst"])
+ with self.assertRaises(IllegalArgumentException):
+ content.validate()
+
+ def test_empty_or_blank_roles_rejected(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ AccessControlContent([Privilege.Name.SELECT_TABLE], []).validate()
+ with self.assertRaises(IllegalArgumentException):
+ AccessControlContent([Privilege.Name.SELECT_TABLE], [" "]).validate()
+
+ def test_null_lists_become_empty(self) -> None:
+ content = AccessControlContent(None, None)
+ self.assertEqual([], content.privileges())
+ self.assertEqual([], content.applicable_roles())
+
+
+class TestIcebergDataCompactionContent(unittest.TestCase):
+ def test_defaults(self) -> None:
+ content = PolicyContents.iceberg_data_compaction()
+ self.assertEqual(405323966463344, content.min_data_file_mse())
+ self.assertEqual(1, content.min_delete_file_number())
+ self.assertEqual(1, content.data_file_mse_weight())
+ self.assertEqual(100, content.delete_file_number_weight())
+ self.assertEqual(50, content.max_partition_num())
+ self.assertEqual("binpack", content.rewrite_strategy())
+ self.assertEqual("", content.sort_order())
+ self.assertEqual({}, content.rewrite_options())
+ self.assertEqual(PolicyExecutionSpec.empty(), content.execution_spec())
+ content.validate()
+
+ def test_properties_and_rules(self) -> None:
+ content = PolicyContents.iceberg_data_compaction(
+ rewrite_options={"target-file-size-bytes": "123"}
+ )
+ self.assertEqual(
+ {
+ "strategy.type": "iceberg-data-compaction",
+ "job.template-name": "builtin-iceberg-rewrite-data-files",
+ },
+ content.properties(),
+ )
+ rules = content.rules()
+ self.assertEqual(
+ IcebergDataCompactionContent.TRIGGER_EXPR, rules["trigger-expr"]
+ )
+ self.assertEqual(IcebergDataCompactionContent.SCORE_EXPR, rules["score-expr"])
+ self.assertEqual("binpack", rules["rewriteStrategy"])
+ self.assertEqual("123", rules["job.options.target-file-size-bytes"])
+ self.assertEqual(
+ {
+ MetadataObject.Type.CATALOG,
+ MetadataObject.Type.SCHEMA,
+ MetadataObject.Type.TABLE,
+ },
+ content.supported_object_types(),
+ )
+
+ def test_execution_peers_passed_through(self) -> None:
+ content = PolicyContents.iceberg_data_compaction(
+ time_trigger="0 0 * * *", min_interval_ms=1000
+ )
+ self.assertEqual("0 0 * * *", content.execution_spec().time_trigger())
+ self.assertEqual(1000, content.execution_spec().min_interval_ms())
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(rewrite_strategy="sort").validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(sort_order="x").validate()
+ PolicyContents.iceberg_data_compaction(
+ rewrite_strategy="sort", sort_order="id"
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(rewrite_strategy="zipper").validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(min_data_file_mse=-1).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(max_partition_num=0).validate()
+
+ def test_rewrite_strategy_is_normalized(self) -> None:
+ content = PolicyContents.iceberg_data_compaction(
+ rewrite_strategy=" SORT ", sort_order="id"
+ )
+ self.assertEqual("sort", content.rewrite_strategy())
+ content.validate()
+ self.assertEqual(
+ PolicyContents.iceberg_data_compaction(rewrite_strategy="binpack"),
+ PolicyContents.iceberg_data_compaction(rewrite_strategy=" BinPack "),
+ )
+
+ def test_valid_rewrite_options(self) -> None:
+ PolicyContents.iceberg_data_compaction(
+ rewrite_options={
+ "target-file-size-bytes": "1048576",
+ "min-input-files": "5",
+ "partial-progress.max-failed-commits": "0",
+ "rewrite-all": "true",
+ "partial-progress.enabled": "FALSE",
+ "rewrite-job-order": "Bytes-Asc",
+ "delete-ratio-threshold": "0.5",
+ }
+ ).validate()
+
+ def test_invalid_rewrite_options(self) -> None:
+ invalid_options = [
+ {"target-file-size-bytes": "-1"},
+ {"target-file-size-bytes": "0"},
+ {"target-file-size-bytes": "1.5"},
+ {"min-input-files": "0"},
+ {"partial-progress.max-failed-commits": "-1"},
+ {"rewrite-all": "yes"},
+ {"rewrite-job-order": "random"},
+ {"delete-ratio-threshold": "1.5"},
+ {"delete-ratio-threshold": "abc"},
+ {"unknown-option": "1"},
+ {"job.options.target-file-size-bytes": "1"},
+ {"bad key!": "1"},
+ {"target-file-size-bytes": ""},
+ ]
+ for options in invalid_options:
+ with self.subTest(options=options):
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_data_compaction(
+ rewrite_options=options
+ ).validate()
+
+
+class TestIcebergOrphanFileRemovalContent(unittest.TestCase):
+ def test_defaults_and_rules(self) -> None:
+ content = PolicyContents.iceberg_orphan_file_removal()
+ self.assertEqual(3, content.older_than_days())
+ self.assertIsNone(content.location())
+ self.assertEqual(False, content.dry_run())
+ rules = content.rules()
+ self.assertEqual("true", rules["trigger-expr"])
+ self.assertEqual("1", rules["score-expr"])
+ self.assertEqual(3, rules["job.options.olderThanDays"])
+ self.assertEqual(False, rules["job.options.dryRun"])
+ self.assertNotIn("job.options.location", rules)
+ content.validate()
+
+ def test_location_in_rules_when_set(self) -> None:
+ content = PolicyContents.iceberg_orphan_file_removal(
+ location="s3://bucket/table"
+ )
+ self.assertEqual("s3://bucket/table", content.rules()["job.options.location"])
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_orphan_file_removal(commit_trigger=True).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_orphan_file_removal(older_than_days=0).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_orphan_file_removal(older_than_days=36501).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_orphan_file_removal(
+ location="s3://bucket/../table"
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_orphan_file_removal(
+ location=" s3://bucket/table"
+ ).validate()
+
+
+class TestIcebergRewriteManifestsContent(unittest.TestCase):
+ def test_defaults_and_rules(self) -> None:
+ content = PolicyContents.iceberg_rewrite_manifests()
+ self.assertEqual(500, content.manifest_count_critical())
+ self.assertEqual(100, content.manifest_count_warning())
+ self.assertEqual(8388608, content.avg_manifest_size_threshold_bytes())
+ self.assertIsNone(content.spec_id())
+ self.assertIsNone(content.use_caching())
+ rules = content.rules()
+ self.assertEqual(500, rules["manifest_count_critical"])
+ self.assertEqual(100, rules["manifest_count_warning"])
+ self.assertEqual(8388608, rules["avg_manifest_size_threshold_bytes"])
+ self.assertNotIn("spec_id", rules)
+ self.assertNotIn("use_caching", rules)
+ content.validate()
+
+ def test_optional_rules_included_when_set(self) -> None:
+ content = PolicyContents.iceberg_rewrite_manifests(spec_id=2, use_caching=True)
+ self.assertEqual(2, content.rules()["spec_id"])
+ self.assertEqual(True, content.rules()["use_caching"])
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_rewrite_manifests(
+ manifest_count_warning=0
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_rewrite_manifests(
+ manifest_count_critical=50, manifest_count_warning=100
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_rewrite_manifests(
+ avg_manifest_size_threshold_bytes=0
+ ).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_rewrite_manifests(spec_id=-1).validate()
+
+
+class TestIcebergSnapshotExpirationContent(unittest.TestCase):
+ def test_defaults_and_rules(self) -> None:
+ content = PolicyContents.iceberg_snapshot_expiration()
+ self.assertEqual(5, content.older_than_days())
+ self.assertEqual(1, content.retain_last())
+ self.assertEqual(False, content.stream_results())
+ rules = content.rules()
+ self.assertEqual(5, rules["job.options.olderThanDays"])
+ self.assertEqual(1, rules["job.options.retainLast"])
+ self.assertEqual(False, rules["job.options.streamResults"])
+ content.validate()
+
+ def test_validation_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_snapshot_expiration(older_than_days=0).validate()
+ with self.assertRaises(IllegalArgumentException):
+ PolicyContents.iceberg_snapshot_expiration(retain_last=0).validate()
+
+
+class TestCustomContent(unittest.TestCase):
+ def test_custom_content(self) -> None:
+ content = PolicyContents.custom(
+ {"rule1": 123},
+ {MetadataObject.Type.TABLE},
+ {"key": "value"},
+ )
+ self.assertEqual({"rule1": 123}, content.rules())
+ self.assertEqual({MetadataObject.Type.TABLE}, content.supported_object_types())
+ self.assertEqual({"key": "value"}, content.properties())
+ content.validate()
+ self.assertEqual(
+ content,
+ PolicyContents.custom(
+ {"rule1": 123}, {MetadataObject.Type.TABLE}, {"key": "value"}
+ ),
+ )
+
+ def test_custom_content_hash_with_nested_rule_values(self) -> None:
+ rules = {"rule": ["a", "b"], "nested": {"x": [1, 2], "y": {"z": 3}}}
+ content = PolicyContents.custom(rules, {MetadataObject.Type.TABLE}, {})
+ equal_content = PolicyContents.custom(
+ {"nested": {"y": {"z": 3}, "x": [1, 2]}, "rule": ["a", "b"]},
+ {MetadataObject.Type.TABLE},
+ {},
+ )
+ self.assertEqual(content, equal_content)
+ self.assertEqual(hash(content), hash(equal_content))
+ self.assertIn(content, {equal_content})
+
+
+class TestBuiltInType(unittest.TestCase):
+ def test_from_policy_type(self) -> None:
+ self.assertEqual(
+ Policy.BuiltInType.ICEBERG_COMPACTION,
+ Policy.BuiltInType.from_policy_type("system_iceberg_compaction"),
+ )
+ self.assertEqual(
+ Policy.BuiltInType.ACCESS_CONTROL,
+ Policy.BuiltInType.from_policy_type("SYSTEM_ACCESS_CONTROL"),
+ )
+ self.assertEqual(
+ Policy.BuiltInType.CUSTOM, Policy.BuiltInType.from_policy_type("custom")
+ )
+
+ def test_from_policy_type_failures(self) -> None:
+ with self.assertRaises(IllegalArgumentException):
+ Policy.BuiltInType.from_policy_type(None)
+ with self.assertRaises(IllegalArgumentException):
+ Policy.BuiltInType.from_policy_type("system_unknown")
+ with self.assertRaises(IllegalArgumentException):
+ Policy.BuiltInType.from_policy_type("something_else")
+
+ def test_content_classes(self) -> None:
+ self.assertEqual(
+ IcebergDataCompactionContent,
+ Policy.BuiltInType.ICEBERG_COMPACTION.content_class(),
+ )
+ self.assertEqual(
+ AccessControlContent,
+ Policy.BuiltInType.ACCESS_CONTROL.content_class(),
+ )
+ self.assertEqual(
+ PolicyContents.CustomContent, Policy.BuiltInType.CUSTOM.content_class()
+ )
+
+
+class TestSelectors(unittest.TestCase):
+ def test_all_values_singleton(self) -> None:
+ self.assertIs(AllValuesSelector.get(), AllValuesSelector.get())
+ self.assertEqual("ALL_VALUES", AllValuesSelector.get().type())
+ self.assertEqual(AllValuesSelector.get(), AllValuesSelector())
+
+ def test_tag_value_selector(self) -> None:
+ selector = TagValueSelector.of("gold")
+ self.assertEqual("TAG_VALUE", selector.type())
+ self.assertEqual("gold", selector.value())
+ self.assertEqual(TagValueSelector.of("gold"), selector)
+ with self.assertRaises(IllegalArgumentException):
+ TagValueSelector.of(" ")
+
+
+class TestPolicyListAndSupportsPolicies(unittest.TestCase):
+ def test_policy_list_copy(self) -> None:
+ policy_list = PolicyList(["a", "b"], True)
+ policies = policy_list.policies()
+ policies.append("c")
+ self.assertEqual(["a", "b"], policy_list.policies())
+ self.assertTrue(policy_list.has_inaccessible_policies())
+
+ def test_visibility_defaults(self) -> None:
+ class _Stub(SupportsPolicies):
+ def list_policies(self):
+ return ["p1"]
+
+ def list_policy_infos(self):
+ return []
+
+ stub = _Stub()
+ listed = stub.list_policies_with_visibility()
+ self.assertEqual(["p1"], listed.policies())
+ self.assertFalse(listed.has_inaccessible_policies())
+ self.assertEqual([], stub.list_policy_infos_with_visibility().policies())
+
+
+if __name__ == "__main__":
+ unittest.main()