-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_loader.py
More file actions
271 lines (215 loc) · 9.35 KB
/
plugin_loader.py
File metadata and controls
271 lines (215 loc) · 9.35 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import importlib
import importlib.util
import os
import sys
from pathlib import Path
from tournament_core import (
IMatchmakingStrategy,
IPointsCalculator,
ITournamentRepository,
MatchmakingStrategyRegistry,
PointsCalculatorRegistry,
)
class PluginLoader:
"""
Loads plugins dynamically from modules or files.
Supports hot-loading of custom strategies and calculators.
"""
def __init__(
self,
strategy_registry: MatchmakingStrategyRegistry,
calculator_registry: PointsCalculatorRegistry,
repository: ITournamentRepository,
):
self.strategy_registry = strategy_registry
self.calculator_registry = calculator_registry
self.repository = repository
self.loaded_modules = {}
def load_strategy_from_module(self, module_name: str, class_name: str) -> None:
"""
Load a strategy class from a module.
Example:
loader.load_strategy_from_module('my_strategies', 'MyCustomStrategy')
"""
try:
module = importlib.import_module(module_name)
strategy_class = getattr(module, class_name)
if not issubclass(strategy_class, IMatchmakingStrategy):
raise TypeError(f"{class_name} must implement IMatchmakingStrategy")
# Instantiate and register
strategy = strategy_class(self.repository)
self.strategy_registry.register(strategy)
print(
f"✓ Loaded strategy: {strategy.get_strategy_name()} from {module_name}.{class_name}"
)
except Exception as e:
print(f"✗ Failed to load strategy from {module_name}.{class_name}: {e}")
def load_calculator_from_module(self, module_name: str, class_name: str) -> None:
"""
Load a calculator class from a module.
Example:
loader.load_calculator_from_module('my_calculators', 'MyCustomCalculator')
"""
try:
module = importlib.import_module(module_name)
calculator_class = getattr(module, class_name)
if not issubclass(calculator_class, IPointsCalculator):
raise TypeError(f"{class_name} must implement IPointsCalculator")
# Instantiate and register
calculator = calculator_class()
self.calculator_registry.register(calculator)
print(
f"✓ Loaded calculator: {calculator.get_calculator_name()} from {module_name}.{class_name}"
)
except Exception as e:
print(f"✗ Failed to load calculator from {module_name}.{class_name}: {e}")
def load_strategy_from_file(self, file_path: str, class_name: str) -> None:
"""
Load a strategy class from a Python file.
Example:
loader.load_strategy_from_file('./plugins/custom_strategy.py', 'CustomStrategy')
"""
try:
# Load module from file
module_name = Path(file_path).stem
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Get and register strategy
strategy_class = getattr(module, class_name)
if not issubclass(strategy_class, IMatchmakingStrategy):
raise TypeError(f"{class_name} must implement IMatchmakingStrategy")
strategy = strategy_class(self.repository)
self.strategy_registry.register(strategy)
self.loaded_modules[module_name] = module
print(f"✓ Loaded strategy: {strategy.get_strategy_name()} from {file_path}")
except Exception as e:
print(f"✗ Failed to load strategy from {file_path}: {e}")
def load_calculator_from_file(self, file_path: str, class_name: str) -> None:
"""
Load a calculator class from a Python file.
Example:
loader.load_calculator_from_file('./plugins/custom_calc.py', 'CustomCalc')
"""
try:
# Load module from file
module_name = Path(file_path).stem
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Get and register calculator
calculator_class = getattr(module, class_name)
if not issubclass(calculator_class, IPointsCalculator):
raise TypeError(f"{class_name} must implement IPointsCalculator")
calculator = calculator_class()
self.calculator_registry.register(calculator)
self.loaded_modules[module_name] = module
print(
f"✓ Loaded calculator: {calculator.get_calculator_name()} from {file_path}"
)
except Exception as e:
print(f"✗ Failed to load calculator from {file_path}: {e}")
def discover_and_load_plugins(self, plugins_dir: str = "./plugins") -> None:
"""
Discover and load all plugins from a directory.
Looks for classes that implement the plugin interfaces.
"""
if not os.path.exists(plugins_dir):
print(f"Plugins directory not found: {plugins_dir}")
return
print(f"\nDiscovering plugins in: {plugins_dir}")
for filename in os.listdir(plugins_dir):
if filename.endswith(".py") and not filename.startswith("_"):
file_path = os.path.join(plugins_dir, filename)
self._auto_load_from_file(file_path)
def _auto_load_from_file(self, file_path: str) -> None:
"""Automatically detect and load plugins from a file."""
try:
module_name = Path(file_path).stem
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
# Find all classes that implement our interfaces
for attr_name in dir(module):
attr = getattr(module, attr_name)
# Check if it's a class
if not isinstance(attr, type):
continue
# Check if it implements our interfaces
try:
if (
issubclass(attr, IMatchmakingStrategy)
and attr != IMatchmakingStrategy
):
strategy = attr(self.repository)
self.strategy_registry.register(strategy)
print(f" ✓ Loaded strategy: {strategy.get_strategy_name()}")
elif (
issubclass(attr, IPointsCalculator)
and attr != IPointsCalculator
):
calculator = attr()
self.calculator_registry.register(calculator)
print(
f" ✓ Loaded calculator: {calculator.get_calculator_name()}"
)
except TypeError:
# Not a valid subclass
pass
self.loaded_modules[module_name] = module
except Exception as e:
print(f" ✗ Failed to load from {file_path}: {e}")
def reload_plugin(self, module_name: str) -> None:
"""
Reload a plugin module.
Useful for development when you modify a plugin.
"""
if module_name not in self.loaded_modules:
print(f"Module {module_name} not loaded")
return
try:
module = self.loaded_modules[module_name]
importlib.reload(module)
print(f"✓ Reloaded module: {module_name}")
except Exception as e:
print(f"✗ Failed to reload {module_name}: {e}")
# Example custom plugin that users can create:
"""
# File: plugins/my_custom_strategy.py
from tournament_core import IMatchmakingStrategy, Match, RoundConfig, generate_id, now_iso
from typing import list, Dict, Any
class RandomMatchmakingStrategy(IMatchmakingStrategy):
'''Randomly pairs players together.'''
def __init__(self, repository):
self.repository = repository
def get_strategy_name(self) -> str:
return "random"
def supports_players_per_match(self, n: int) -> bool:
return True # Supports any number
def create_matches(self, tournament_id, round_id, available_players, config):
import random
players = available_players.copy()
random.shuffle(players)
matches = []
n = config.players_per_match
while len(players) >= n:
match_players = [players.pop() for _ in range(n)]
match = Match(
id=generate_id(),
round_id=round_id,
tournament_id=tournament_id,
player_ids=match_players,
scheduled_at=now_iso(),
players_per_match=n
)
matches.append(match)
self.repository.save_match(match)
return {
"matches": matches,
"waiting_players": players,
"metadata": {"shuffled": True}
}
"""