-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathfactory.py
More file actions
205 lines (160 loc) · 7.29 KB
/
Copy pathfactory.py
File metadata and controls
205 lines (160 loc) · 7.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""Template factory for creating provider-specific templates with extensions."""
from abc import ABC, abstractmethod
from typing import Any, Optional, Protocol
from orb.domain.base.ports.logging_port import LoggingPort
from orb.domain.template.template_aggregate import Template
class TemplateFactoryPort(Protocol):
"""Port for template factory following DIP."""
def create_template(
self, template_data: dict[str, Any], provider_type: Optional[str] = None
) -> Template:
"""Create appropriate template type based on provider."""
...
def supports_provider(self, provider_type: str) -> bool:
"""Check if factory supports a provider type."""
...
class BaseTemplateFactory(ABC):
"""Abstract base template factory."""
@abstractmethod
def create_template(
self, template_data: dict[str, Any], provider_type: Optional[str] = None
) -> Template:
"""Create appropriate template type based on provider."""
@abstractmethod
def supports_provider(self, provider_type: str) -> bool:
"""Check if factory supports a provider type."""
class TemplateFactory(BaseTemplateFactory):
"""Factory for creating provider-specific templates with extensions.
This factory follows the Factory Pattern and integrates with the template
extension registry to create appropriate template types based on provider.
It follows SOLID principles:
- SRP: Single responsibility of creating templates
- OCP: Open for extension (new providers), closed for modification
- DIP: Depends on abstractions (ports) not concretions
"""
def __init__(
self,
extension_registry: Optional[Any] = None,
logger: Optional[LoggingPort] = None,
) -> None:
"""Initialize template factory.
Args:
extension_registry: Registry for provider extensions (injected by infrastructure layer)
logger: Logger port for logging factory operations
"""
self._extension_registry = extension_registry
self._logger = logger
# Registry of provider-specific template classes
self._provider_template_classes: dict[str, type] = {}
def register_provider_template_class(self, provider_type: str, template_class: type) -> None:
"""Register a provider-specific template class.
Args:
provider_type: The provider type (e.g., 'aws', 'provider1', 'provider2')
template_class: The template class for this provider
"""
if not issubclass(template_class, Template):
raise ValueError(f"Template class must inherit from Template, got {template_class}")
self._provider_template_classes[provider_type] = template_class
if self._logger:
self._logger.debug("Registered template class for provider: %s", provider_type)
def create_template(
self, template_data: dict[str, Any], provider_type: Optional[str] = None
) -> Template:
"""Create appropriate template type based on provider.
Args:
template_data: Template configuration data
provider_type: Provider type to create template for
Returns:
Template instance (provider-specific if available, otherwise core Template)
"""
# Determine provider type if not provided
if not provider_type:
provider_type = self._determine_provider_type(template_data)
# Log template creation
if self._logger:
self._logger.debug("Creating template for provider: %s", provider_type)
# Create provider-specific template if available
if provider_type and provider_type in self._provider_template_classes:
try:
template_class = self._provider_template_classes[provider_type]
template = template_class(**template_data)
if self._logger:
self._logger.debug(
"Created %s template: %s", provider_type, template.template_id
)
return template
except Exception as e:
if self._logger:
self._logger.error("Failed to create %s template: %s", provider_type, e)
raise
# Use the core template only when no provider-specific class is registered.
try:
template = Template(**template_data)
if self._logger:
self._logger.debug("Created core template: %s", template.template_id)
return template
except Exception as e:
if self._logger:
self._logger.error("Failed to create core template: %s", e)
raise
def supports_provider(self, provider_type: str) -> bool:
"""Check if factory supports a provider type.
Args:
provider_type: The provider type to check
Returns:
True if the provider is supported (has registered template class)
"""
return provider_type in self._provider_template_classes
def get_supported_providers(self) -> list[str]:
"""Get list of supported provider types.
Returns:
List of provider types that have registered template classes
"""
return list(self._provider_template_classes.keys())
def _determine_provider_type(self, template_data: dict[str, Any]) -> Optional[str]:
"""Determine provider type from template data.
Args:
template_data: Template configuration data
Returns:
Provider type if determinable, None otherwise
"""
# Check explicit provider_type field
if "provider_type" in template_data:
return template_data["provider_type"]
# Check provider_name field and extract type
if "provider_name" in template_data:
provider_name = template_data["provider_name"]
if isinstance(provider_name, str) and "-" in provider_name:
return provider_name.split("-")[0]
return None
def create_template_with_extensions(
self,
template_data: dict[str, Any],
provider_type: Optional[str] = None,
extension_data: Optional[dict[str, Any]] = None,
) -> Template:
"""Create template with provider extensions applied.
Args:
template_data: Core template configuration data
provider_type: Provider type to create template for
extension_data: Additional extension configuration data
Returns:
Template instance with extensions applied
"""
# Merge extension data if provided
if extension_data:
merged_data = {**template_data, **extension_data}
else:
merged_data = template_data.copy()
# Apply extension defaults from registry
if (
provider_type
and self._extension_registry is not None
and self._extension_registry.has_extension(provider_type)
):
extension_defaults = self._extension_registry.get_extension_defaults(
provider_type, extension_data
)
# Extension defaults have lower priority than explicit template data
merged_data = {**extension_defaults, **merged_data}
return self.create_template(merged_data, provider_type)