Repository navigation
Expand file tree
/
Copy pathcontext.py
More file actions
570 lines (478 loc) · 21.2 KB
/
Copy pathcontext.py
File metadata and controls
570 lines (478 loc) · 21.2 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import logging
import sys
from collections.abc import Callable
from dataclasses import InitVar, dataclass, field, fields, is_dataclass
from importlib import import_module, metadata
from inspect import Parameter, isclass, signature
from types import ModuleType, NoneType, UnionType
from typing import (
Any,
TypeVar,
Union,
get_args,
get_origin,
get_type_hints,
)
from bluesky.protocols import HasName
from bluesky.run_engine import RunEngine
from ophyd_async.core import NotConnectedError, PathProvider
from pydantic import (
BaseModel,
GetCoreSchemaHandler,
GetJsonSchemaHandler,
create_model,
)
from pydantic.fields import FieldInfo
from pydantic.json_schema import JsonSchemaValue, SkipJsonSchema
from pydantic_core import CoreSchema, core_schema
from blueapi import __version__, utils
from blueapi.config import (
ApplicationConfig,
DeviceManagerSource,
EnvironmentConfig,
PlanSource,
ServiceAccount,
TiledConfig,
)
from blueapi.core.protocols import DeviceManager
from blueapi.utils import (
BlueapiPlanModelConfig,
is_function_sourced_from_module,
load_module_all,
)
from blueapi.utils.invalid_config_error import InvalidConfigError
from blueapi.utils.path_provider import StartDocumentPathProvider
from .bluesky_types import (
BLUESKY_PROTOCOLS,
AsyncDevice,
BlueapiDevice,
Device,
Plan,
PlanGenerator,
is_bluesky_compatible_device,
is_bluesky_plan_generator,
)
LOGGER = logging.getLogger(__name__)
if "ophyd" in sys.modules:
# This is an awful hack/workaround to avoid blueapi hanging on shutdown when
# EPICS environment variables are set.
# See https://github.com/DiamondLightSource/blueapi/issues/1147#issuecomment-3242278545
from ophyd import EpicsSignal
_ = EpicsSignal("libca bug workaround")
def is_compatible(val: Device, target: type, args: tuple[type, ...] | None):
return isinstance(val, target) and is_compatible_args(val, target, args)
def generic_bounds(val: Device, target: type) -> tuple[type, ...]:
for base in getattr(val, "__orig_bases__", ()):
if (get_origin(base) or base) == target:
return get_args(base)
return ()
def is_compatible_args(val: Device, target: type, args: tuple[type, ...] | None):
return (not args) or all(
actual is Any
or type(actual) is TypeVar
or type(expected) is TypeVar
or expected == actual
or issubclass(actual, expected)
for expected, actual in zip(args, generic_bounds(val, target), strict=False)
)
def qualified_name(target: type) -> str:
module_name = f"{target.__module__}." if target.__module__ != "builtins" else ""
name = target.__qualname__ if hasattr(target, "__qualname__") else target.__name__
if isinstance(target, TypeVar):
return "Any"
return f"{module_name}{name}"
def qualified_generic_name(target: type) -> str:
args = get_args(target)
subscript = (
"[" + ", ".join(qualified_name(arg) for arg in args) + "]" if args else ""
)
return f"{qualified_name(target)}{subscript}"
def is_bluesky_type(typ: Any) -> bool:
return (
typ in BLUESKY_PROTOCOLS
or isinstance(typ, BLUESKY_PROTOCOLS)
or (isinstance(typ, type) and issubclass(typ, AsyncDevice))
)
@dataclass
class BlueskyContext:
"""
Context for building a Bluesky application.
The context holds the RunEngine and any plans/devices that you may want to use.
"""
configuration: InitVar[ApplicationConfig | None] = None
run_engine: RunEngine = field(
default_factory=lambda: RunEngine(context_managers=[], call_returns_result=True)
)
tiled_conf: TiledConfig | None = field(default=None, init=False, repr=False)
path_provider: PathProvider | None = None
plans: dict[str, Plan] = field(default_factory=dict)
devices: dict[str, BlueapiDevice] = field(default_factory=dict)
_reference_cache: dict[type, type] = field(default_factory=dict)
_warned_name_clash: bool = field(default=False, init=False, repr=False)
def __post_init__(self, configuration: ApplicationConfig | None):
self.run_engine.md.setdefault("versions", {})["blueapi"] = __version__
if not configuration:
return
if configuration.numtracker is not None:
# The numtracker client itself is wired up by the service, see
# blueapi.service.interface.context
if configuration.env.metadata is None:
raise InvalidConfigError(
"Numtracker url has been configured, but there is no instrument or"
" instrument_session in the environment metadata"
)
path_provider = StartDocumentPathProvider()
self.run_engine.subscribe(path_provider.run_start, "start")
self.run_engine.subscribe(path_provider.run_stop, "stop")
self.path_provider = path_provider
self.with_config(configuration.env)
if (tiled_conf := configuration.tiled) is not None and tiled_conf.enabled:
if configuration.env.metadata is None:
raise InvalidConfigError(
"Tiled has been configured but `instrument` metadata is not set - "
"this field is required to make authorization decisions."
)
if isinstance(tiled_conf.authentication, ServiceAccount):
if configuration.oidc is None:
raise InvalidConfigError(
"Tiled has been configured but oidc configuration is missing "
"this field is required to make authorization decisions."
)
tiled_conf.authentication.token_url = configuration.oidc.token_endpoint
self.tiled_conf = tiled_conf
def find_device(self, addr: str | list[str]) -> Device | None:
"""
Find a device in this context, allows for recursive search.
Args:
addr (Union[str, List[str]]): Address of the device, examples:
"motors", "motors.x"
Returns:
Optional[Device]: _description_
"""
if isinstance(addr, str):
return self.find_device(addr.split("."))
head, *tail = addr
if entry := self.devices.get(head):
return entry.find_component(tail)
return None
def with_config(self, config: EnvironmentConfig) -> None:
if config.metadata is not None:
self.run_engine.md.update(config.metadata.model_dump())
package_map = metadata.packages_distributions()
packages = {src.module.split(".")[0] for src in config.sources}
for pkg in packages:
if root_pkg := package_map.get(pkg):
version = metadata.version(root_pkg[0])
LOGGER.info("Using package %s[%s]", root_pkg[0], version)
for source in config.sources:
mod = import_module(source.module)
match source:
case PlanSource():
LOGGER.info("Including plans from %s", source.module)
self.with_plan_module(mod)
case DeviceManagerSource(mock=mock, name=name):
LOGGER.info(
"Including devices from 'deviceManager' source %s:%s",
source.module,
name,
)
manager = getattr(mod, name)
if not isinstance(manager, DeviceManager):
raise ValueError(
f"{name} in module {mod} is not a device manager"
)
self.with_device_manager(manager, mock)
if not self.devices:
LOGGER.warning(
"Context had no devices after loading environment - are all modules "
"included and marked with the correct 'kind'?"
)
if not self.plans:
LOGGER.warning("Context had no plans registered after loading environment")
def with_plan_module(self, module: ModuleType) -> None:
"""
Register all functions in the module supplied as plans.
Module should take the form:
def plan_1(...) -> MsgGenerator:
...
def _helper(...):
...
def plan_2(...) -> MsgGenerator:
...
__all__ = ["plan_1", "plan_2"]
Args:
module (ModuleType): Module to pass in
"""
for obj in load_module_all(module):
# The rule here is that we only inspect objects defined in the module
# (as opposed to objects imported from other modules) to determine if
# they are valid plans, unless there is an __all__ defined in the module,
# in which case we only inspect objects listed there, regardless of their
# original source module.
if is_bluesky_plan_generator(obj) and (
hasattr(module, "__all__")
or is_function_sourced_from_module(obj, module)
):
self.register_plan(obj)
def with_device_manager(self, manager: DeviceManager, mock: bool = False):
fixtures = {"path_provider": self.path_provider} if self.path_provider else {}
build_result = manager.build_and_connect(mock=mock, fixtures=fixtures)
for device in build_result.devices.values():
self.register_device(device)
if errs := build_result.build_errors:
LOGGER.warning(
f"{errs} errors while building devices",
exc_info=ExceptionGroup(
"Errors while building devices", list(errs.values())
),
)
if errs := build_result.connection_errors:
LOGGER.warning(
f"{len(errs)} errors while connecting devices",
exc_info=NotConnectedError(errs),
)
if not (
build_result.devices
or build_result.build_errors
or build_result.connection_errors
):
LOGGER.warning("Device manager did not build any devices")
utils.report_successful_devices(build_result.devices, mock, LOGGER)
return build_result.devices, {
**build_result.build_errors,
**build_result.connection_errors,
}
def register_plan(self, plan: PlanGenerator) -> PlanGenerator:
"""
Register the argument as a plan in the context. Can be used as a decorator e.g.
@ctx.plan
def my_plan(a: int, b: str):
...
Args:
plan (PlanGenerator): Plan generator function to register
Returns:
PlanGenerator: The plan passed in for chaining/decorating
"""
if not is_bluesky_plan_generator(plan):
raise TypeError(f"{plan} is not a valid plan generator function")
model = create_model(
plan.__name__,
__config__=BlueapiPlanModelConfig,
**self._type_spec_for_function(plan), # type: ignore
)
LOGGER.debug("Registering plan %s from %s", plan.__name__, plan.__module__)
self.plans[plan.__name__] = Plan(
name=plan.__name__,
model=model,
plan_function=plan,
description=plan.__doc__,
)
return plan
def register_device(self, device: Device, name: str | None = None) -> None:
"""
Register an device in the context. The device needs to be registered with a
name. If the device is Readable, Movable or Flyable it has a `name`
attribute which can be used. The attribute can be overridden with the
`name` parameter here. If the device conforms to a different protocol then
the parameter must be used to name it.
Children of ophyd-async devices, including signals, are also registered
under their own names, e.g. registering "stage" also registers "stage-x"
and "stage-x-velocity". If a name is already in use, the existing device
is kept and the new one and its children are not registered.
Args:
device (Device): The device to register
name (Optional[str], optional): A name for the device. Defaults to None.
Raises:
KeyError: If no name is found/supplied
"""
if not is_bluesky_compatible_device(device):
raise TypeError(f"{device} is not a Bluesky compatible device")
if name is None:
if isinstance(device, HasName):
name = device.name
else:
raise KeyError(f"Must supply a name for this device: {device}")
if self._add_device(name, device):
self._register_children(device)
def _register_children(self, device: Device) -> None:
"""Register the children of an ophyd-async device under their own names."""
if not isinstance(device, AsyncDevice):
return
for _, child in device.children():
if child.name and self._add_device(child.name, child):
self._register_children(child)
def _add_device(self, name: str, device: Device) -> bool:
"""Add a device unless a different one is already registered as name."""
existing = self.devices.setdefault(name, BlueapiDevice(device))
if existing.device is not device:
# Expected for e.g. a motor's user_readback, which has the motor's name.
# The caller skips its children too, as their names start with this one
if not self._warned_name_clash:
LOGGER.warning(
"Some devices were not registered as their names are in use, "
"e.g. motor readbacks. Enable debug logging to see which"
)
self._warned_name_clash = True
LOGGER.debug(
"Not registering %s or its children, name '%s' is in use",
device,
name,
)
return False
return True
def unregister_all_devices(self):
"""Unregister all devices from the context."""
self.devices.clear()
def _reference(self, target: type) -> type:
"""
Create an intermediate reference type for the required ``target`` type that
will return an existing device during pydantic deserialisation/validation
Args:
target: Expected type of the device that is expected for IDs being
deserialised by the return type
Returns:
New type that can be deserialised by pydantic returning an existing device
for a string device ID
"""
if target not in self._reference_cache:
class Reference(target):
origin = get_origin(target)
args = get_args(target)
@classmethod
def __get_pydantic_core_schema__(
cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
def valid(value):
val = self.find_device(value)
if not val:
raise ValueError(f"Device {value} cannot be found")
elif not is_compatible(val, cls.origin or target, cls.args):
actual = qualified_name(type(val))
required = qualified_generic_name(target)
raise ValueError(
f"Device {value} ({actual}) is not of type {required}"
)
return val
return core_schema.no_info_after_validator_function(
valid, handler(str)
)
@classmethod
def __get_pydantic_json_schema__(
cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
json_schema = handler(core_schema)
json_schema = handler.resolve_ref_schema(json_schema)
json_schema["type"] = qualified_name(target)
# devices are wrapped in BlueapiDevice, so check entry.device
json_schema["enum"] = sorted(
[
name
for name, entry in self.devices.items()
if isinstance(entry.device, cls.origin or target)
]
)
if cls.args:
json_schema["types"] = [qualified_name(arg) for arg in cls.args]
return json_schema
self._reference_cache[target] = Reference
return self._reference_cache[target]
def _type_spec_for_function(
self, func: Callable[..., Any]
) -> dict[str, tuple[type, FieldInfo]]:
"""
Parse a function signature and build map of field types and default
values that can be used to deserialise arguments from external sources.
Any references to any of the bluesky protocols are replaced with an
intermediate reference type that allows existing devices to be returned
for device ID strings.
Args:
func: The function whose signature is being parsed
Returns:
Mapping of {name: (type, default)} to be used by pydantic for deserialising
function arguments
"""
args = signature(func).parameters
types = get_type_hints(func)
new_args: dict[str, tuple[type, FieldInfo]] = {}
for name, para in args.items():
arg_type = types.get(name, Parameter.empty)
if arg_type is Parameter.empty:
raise ValueError(
f"Type annotation is required for '{name}' in '{func.__name__}'"
)
match para.kind:
case Parameter.VAR_POSITIONAL:
arg_type = tuple[arg_type, ...]
case Parameter.VAR_KEYWORD:
arg_type = dict[str, arg_type]
no_default = para.default is Parameter.empty and para.kind not in (
Parameter.VAR_POSITIONAL,
Parameter.VAR_KEYWORD,
)
if (
isclass(arg_type)
and (issubclass(arg_type, BaseModel) or is_dataclass(arg_type))
and isinstance(para.default, str)
):
default_factory = self._composite_factory(arg_type)
_type = SkipJsonSchema[self._convert_type(arg_type, no_default)]
info = FieldInfo(default_factory=default_factory)
else:
_type = self._convert_type(arg_type, no_default)
match para.default:
case Parameter.empty:
if para.kind is Parameter.VAR_POSITIONAL:
info = FieldInfo(default_factory=tuple)
elif para.kind is Parameter.VAR_KEYWORD:
info = FieldInfo(default_factory=dict)
else:
info = FieldInfo(default_factory=None)
case None:
info = FieldInfo(default_factory=lambda: None)
case _:
info = FieldInfo(default=para.default)
new_args[name] = (_type, info)
return new_args
def _convert_type(self, typ: Any, no_default: bool = True) -> type:
"""
Recursively convert a type to something that can be deserialised by
pydantic. Bluesky protocols (and types that extend them) are replaced
with an intermediate reference types that allows the current context to
be used to look up an existing device when deserialising device ID
strings.
Other types are returned as passed in.
Args:
typ: The type that is required - potentially referencing Bluesky protocols
Returns:
A Type that can be deserialised by Pydantic
"""
if typ is NoneType and not no_default:
return SkipJsonSchema[NoneType]
root = get_origin(typ)
if is_bluesky_type(root or typ):
return self._reference(typ)
args = get_args(typ)
if args:
new_types = tuple(self._convert_type(i, no_default) for i in args)
if root == UnionType:
root = Union
return root[new_types] if root else typ # type: ignore
return typ
def _composite_factory[C](self, composite_class: type[C]) -> Callable[[], C]:
def _inject_composite():
if issubclass(composite_class, BaseModel):
devices = {
field_name: self.find_device(field_name)
for field_name in composite_class.model_fields.keys()
}
else:
assert is_dataclass(composite_class), (
f"Unsupported composite type: {composite_class}, composite must be"
" a pydantic BaseModel or a dataclass"
)
devices = {
field.name: self.find_device(field.name)
for field in fields(composite_class)
}
return composite_class(**devices)
return _inject_composite