outerbounds 0.3.176rc6__py3-none-any.whl → 0.3.178__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,293 +0,0 @@
1
- import json
2
- import os
3
- from outerbounds._vendor import yaml
4
- from typing import Dict, Any
5
- from .cli_to_config import build_config_from_options
6
-
7
- CODE_PACKAGE_PREFIX = "mf.obp-apps"
8
-
9
- CAPSULE_DEBUG = os.environ.get("OUTERBOUNDS_CAPSULE_DEBUG", False)
10
-
11
-
12
- class classproperty(property):
13
- def __get__(self, owner_self, owner_cls):
14
- return self.fget(owner_cls)
15
-
16
-
17
- class AppConfigError(Exception):
18
- """Exception raised when app configuration is invalid."""
19
-
20
- pass
21
-
22
-
23
- class AuthType:
24
- BROWSER = "Browser"
25
- API = "API"
26
-
27
- @classmethod
28
- def enums(cls):
29
- return [cls.BROWSER, cls.API]
30
-
31
- @classproperty
32
- def default(cls):
33
- return cls.BROWSER
34
-
35
-
36
- class AppConfig:
37
- """Class representing an Outerbounds App configuration."""
38
-
39
- def __init__(self, config_dict: Dict[str, Any]):
40
- """Initialize configuration from a dictionary."""
41
- self.config = config_dict or {}
42
- self.schema = self._load_schema()
43
- self._final_state = {}
44
-
45
- def set_state(self, key, value):
46
- self._final_state[key] = value
47
- return self
48
-
49
- def get_state(self, key, default=None):
50
- return self._final_state.get(key, self.config.get(key, default))
51
-
52
- def dump_state(self):
53
- x = {k: v for k, v in self.config.items()}
54
- for k, v in self._final_state.items():
55
- x[k] = v
56
- return x
57
-
58
- @staticmethod
59
- def _load_schema():
60
- """Load the configuration schema from the YAML file."""
61
- schema_path = os.path.join(os.path.dirname(__file__), "config_schema.yaml")
62
- with open(schema_path, "r") as f:
63
- return yaml.safe_load(f)
64
-
65
- def get(self, key: str, default: Any = None) -> Any:
66
- """Get a configuration value by key."""
67
- return self.config.get(key, default)
68
-
69
- def validate(self) -> None:
70
- """Validate the configuration against the schema."""
71
- self._validate_required_fields()
72
- self._validate_field_types()
73
- self._validate_field_constraints()
74
-
75
- def set_deploy_defaults(self, packaging_directory: str) -> None:
76
- """Set default values for fields that are not provided."""
77
- if not self.config.get("auth"):
78
- self.config["auth"] = {}
79
- if not self.config["auth"].get("public"):
80
- self.config["auth"]["public"] = True
81
- if not self.config["auth"].get("type"):
82
- self.config["auth"]["type"] = AuthType.BROWSER
83
-
84
- if not self.config.get("health_check"):
85
- self.config["health_check"] = {}
86
- if not self.config["health_check"].get("enabled"):
87
- self.config["health_check"]["enabled"] = False
88
-
89
- if not self.config.get("resources"):
90
- self.config["resources"] = {}
91
- if not self.config["resources"].get("cpu"):
92
- self.config["resources"]["cpu"] = 1
93
- if not self.config["resources"].get("memory"):
94
- self.config["resources"]["memory"] = "4096Mi"
95
- if not self.config["resources"].get("disk"):
96
- self.config["resources"]["disk"] = "20Gi"
97
-
98
- if not self.config.get("replicas", None):
99
- self.config["replicas"] = {
100
- "min": 1,
101
- "max": 1,
102
- }
103
- else:
104
- max_is_set = self.config["replicas"].get("max", None) is not None
105
- min_is_set = self.config["replicas"].get("min", None) is not None
106
- if max_is_set and not min_is_set:
107
- # If users want to set 0 replicas for min,
108
- # then they need explicitly specify min to 0
109
- self.config["replicas"]["min"] = 1 # Atleast set 1 replica
110
- if min_is_set and not max_is_set:
111
- # In the situations where we dont have min/max replicas, we can
112
- # set max to min.
113
- self.config["replicas"]["max"] = self.config["replicas"].get("min")
114
-
115
- def _validate_required_fields(self) -> None:
116
- """Validate that all required fields are present."""
117
- required_fields = self.schema.get("required", [])
118
- for field in required_fields:
119
- if field not in self.config:
120
- raise AppConfigError(
121
- f"Required field '{field}' is missing from the configuration."
122
- )
123
-
124
- def _validate_field_types(self) -> None:
125
- """Validate that fields have correct types."""
126
- properties = self.schema.get("properties", {})
127
-
128
- for field, value in self.config.items():
129
- if field not in properties:
130
- raise AppConfigError(f"Unknown field '{field}' in configuration.")
131
-
132
- field_schema = properties[field]
133
- field_type = field_schema.get("type")
134
-
135
- if field_type == "string" and not isinstance(value, str):
136
- raise AppConfigError(f"Field '{field}' must be a string.")
137
-
138
- elif field_type == "integer" and not isinstance(value, int):
139
- raise AppConfigError(f"Field '{field}' must be an integer.")
140
-
141
- elif field_type == "boolean" and not isinstance(value, bool):
142
- raise AppConfigError(f"Field '{field}' must be a boolean.")
143
-
144
- elif field_type == "array" and not isinstance(value, list):
145
- raise AppConfigError(f"Field '{field}' must be an array.")
146
-
147
- elif field_type == "object" and not isinstance(value, dict):
148
- raise AppConfigError(f"Field '{field}' must be an object.")
149
-
150
- def _validate_field_constraints(self) -> None:
151
- """Validate field-specific constraints."""
152
- properties = self.schema.get("properties", {})
153
-
154
- # Validate name
155
- if "name" in self.config:
156
- name = self.config["name"]
157
- max_length = properties["name"].get("maxLength", 20)
158
- if len(name) > max_length:
159
- raise AppConfigError(
160
- f"App name '{name}' exceeds maximum length of {max_length} characters."
161
- )
162
-
163
- # Validate port
164
- if "port" in self.config:
165
- port = self.config["port"]
166
- min_port = properties["port"].get("minimum", 1)
167
- max_port = properties["port"].get("maximum", 65535)
168
- if port < min_port or port > max_port:
169
- raise AppConfigError(
170
- f"Port number {port} is outside valid range ({min_port}-{max_port})."
171
- )
172
-
173
- # Validate dependencies (only one type allowed)
174
- if "dependencies" in self.config:
175
- deps = self.config["dependencies"]
176
- if not isinstance(deps, dict):
177
- raise AppConfigError("Dependencies must be an object.")
178
-
179
- valid_dep_types = [
180
- "from_requirements_file",
181
- "from_pyproject_toml",
182
- ]
183
-
184
- found_types = [dep_type for dep_type in valid_dep_types if dep_type in deps]
185
-
186
- if len(found_types) > 1:
187
- raise AppConfigError(
188
- f"You can only specify one mode of specifying dependencies. You have specified : {found_types} . Please only set one."
189
- )
190
-
191
- # Validate that each tag has exactly one key
192
- if "tags" in self.config:
193
- tags = self.config["tags"]
194
- for tag in tags:
195
- if not isinstance(tag, dict):
196
- raise AppConfigError(
197
- "Each tag must be a dictionary. %s is of type %s"
198
- % (str(tag), type(tag))
199
- )
200
- if len(tag.keys()) != 1:
201
- raise AppConfigError(
202
- "Each tag must have exactly one key-value pair. Tag %s has %d key-value pairs."
203
- % (str(tag), len(tag.keys()))
204
- )
205
- if "replicas" in self.config:
206
- replicas = self.config["replicas"]
207
- if not isinstance(replicas, dict):
208
- raise AppConfigError("Replicas must be an object.")
209
- max_is_set = self.config["replicas"].get("max", None) is not None
210
- if max_is_set:
211
- if replicas.get("max") == 0:
212
- raise AppConfigError("Max replicas must be greater than 0.")
213
-
214
- if replicas.get("min", 1) > replicas.get("max"):
215
- raise AppConfigError(
216
- "Min replicas must be less than max replicas. %s > %s"
217
- % (replicas.get("min", 1), replicas.get("max", 1))
218
- )
219
-
220
- def to_dict(self) -> Dict[str, Any]:
221
- """Return the configuration as a dictionary."""
222
- return self.config
223
-
224
- def to_yaml(self) -> str:
225
- """Return the configuration as a YAML string."""
226
- return yaml.dump(self.config, default_flow_style=False)
227
-
228
- def to_json(self) -> str:
229
- """Return the configuration as a JSON string."""
230
- return json.dumps(self.config, indent=2)
231
-
232
- @classmethod
233
- def from_file(cls, file_path: str) -> "AppConfig":
234
- """Create a configuration from a file."""
235
- if not os.path.exists(file_path):
236
- raise AppConfigError(f"Configuration file '{file_path}' does not exist.")
237
-
238
- with open(file_path, "r") as f:
239
- try:
240
- config_dict = yaml.safe_load(f)
241
- except Exception as e:
242
- raise AppConfigError(f"Failed to parse configuration file: {e}")
243
-
244
- return cls(config_dict)
245
-
246
- def update_from_cli_options(self, options):
247
- """
248
- Update configuration from CLI options using the same logic as build_config_from_options.
249
- This ensures consistent handling of CLI options whether they come from a config file
250
- or direct CLI input.
251
- """
252
- cli_config = build_config_from_options(options)
253
-
254
- # Process each field using allow_union property
255
- for key, value in cli_config.items():
256
- if key in self.schema.get("properties", {}):
257
- self._update_field(key, value)
258
-
259
- return self
260
-
261
- def _update_field(self, field_name, new_value):
262
- """Update a field based on its allow_union property."""
263
- properties = self.schema.get("properties", {})
264
-
265
- # Skip if field doesn't exist in schema
266
- if field_name not in properties:
267
- return
268
-
269
- field_schema = properties[field_name]
270
- allow_union = field_schema.get("allow_union", False)
271
-
272
- # If field doesn't exist in config, just set it
273
- if field_name not in self.config:
274
- self.config[field_name] = new_value
275
- return
276
-
277
- # If allow_union is True, merge values based on type
278
- if allow_union:
279
- current_value = self.config[field_name]
280
-
281
- if isinstance(current_value, list) and isinstance(new_value, list):
282
- # For lists, append new items
283
- self.config[field_name].extend(new_value)
284
- elif isinstance(current_value, dict) and isinstance(new_value, dict):
285
- # For dicts, update with new values
286
- self.config[field_name].update(new_value)
287
- else:
288
- # For other types, replace with new value
289
- self.config[field_name] = new_value
290
- else:
291
- raise AppConfigError(
292
- f"Field '{field_name}' does not allow union. Current value: {self.config[field_name]}, new value: {new_value}"
293
- )
File without changes