Coverage for core / src / sensorkit / api / declarative.py: 92%

373 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2from __future__ import annotations 

3 

4import asyncio 

5import functools 

6import inspect 

7import itertools 

8import warnings 

9from collections.abc import Callable, Coroutine 

10from enum import StrEnum, auto 

11from typing import Any, final, get_type_hints, overload, override 

12 

13from loguru import logger 

14from pydantic import BaseModel 

15 

16from sensorkit.api.bootstrap import connect 

17from sensorkit.backend.request import CallContext, LongRequest, Request, RequestBase 

18from sensorkit.common.importutil import get_caller_module 

19from sensorkit.core.client import SensorKit, ServiceContext 

20from sensorkit.core.controller import ExecutionHandlerCallback, TaskHandlerCallback 

21from sensorkit.core.delegate import ( 

22 ControllerDelegate, 

23 DeviceDelegate, 

24 EntityDelegate, 

25 ProgramDelegate, 

26) 

27from sensorkit.core.device import CommandHandlerCallback, DeviceCommand 

28from sensorkit.core.entity import DeviceDetails 

29from sensorkit.core.executor import TaskFactoryFunc 

30from sensorkit.core.impl.controller import ControllerImpl 

31from sensorkit.core.impl.device import DeviceImpl 

32from sensorkit.core.impl.entity import EntityImpl 

33from sensorkit.core.impl.program import ProgramImpl 

34from sensorkit.core.task import Task, TaskExecution 

35from sensorkit.core.trait import Archetype, Trait 

36 

37type InitDeinitCallback = Callable[[], Coroutine[Any, Any, None] | None] 

38type SimpleHandler[P: BaseModel | None, R: BaseModel | None] = ( 

39 Callable[[P], Coroutine[Any, Any, R]] 

40 | Callable[[Any, P], Coroutine[Any, Any, R]] 

41) 

42type LongHandler[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None] = ( 

43 Callable[[P, CallContext[V, R]], Coroutine[Any, Any, None]] 

44 | Callable[[Any, P, CallContext[V, R]], Coroutine[Any, Any, None]] 

45) 

46 

47AUTO_ENTITY_ATTR = "__sk_entity__" 

48DECL_MARK_ATTR = "__sk_decl__" 

49CALLBACK_MARK_ATTR = "__sk_callback__" 

50REQUEST_ATTR = "__sk_request__" 

51 

52 

53def _mark_decl_type(cls: type, decl_type: type[DeclaredEntity], **kwargs): 

54 setattr(cls, DECL_MARK_ATTR, staticmethod(functools.partial(decl_type, **kwargs))) 

55 return cls 

56 

57 

58def auto_create_decl(instance): 

59 if decl_factory := getattr(instance, DECL_MARK_ATTR, None): 

60 decl = decl_factory(None) 

61 setattr(instance, AUTO_ENTITY_ATTR, decl) 

62 

63 return instance 

64 

65 

66def decl_for_instance(instance) -> DeclaredEntity[Any] | None: 

67 return getattr(instance, AUTO_ENTITY_ATTR, None) 

68 

69 

70def entity_for_instance(instance): 

71 return decl.impl if (decl := decl_for_instance(instance)) else None 

72 

73 

74def _unwrap_method(func: Callable): 

75 """Return the underlying function of a method, so that a mark can be set on it. 

76 

77 Function objects are mutable, unlike methods, and are shared across subclass relationships. 

78 """ 

79 return func.__func__ if inspect.ismethod(func) else func 

80 

81 

82def _mark_callback(func: Callable, kind: CallbackKind): 

83 """Mark a function as an unassociated callback.""" 

84 setattr(_unwrap_method(func), CALLBACK_MARK_ATTR, kind) 

85 

86 

87def _mark_request(func: Callable, request: RequestBase): 

88 """Record the request a handler was declared for.""" 

89 setattr(_unwrap_method(func), REQUEST_ATTR, request) 

90 

91 

92def get_request(func: Callable) -> RequestBase: 

93 """Return the request a handler was declared for.""" 

94 return getattr(func, REQUEST_ATTR) 

95 

96 

97def is_callback(func: Callable): 

98 """Return True if the given function is declared as a callback.""" 

99 return hasattr(func, CALLBACK_MARK_ATTR) 

100 

101 

102def get_callback_kind(func: Callable): 

103 """Return the type code of the callback function.""" 

104 return getattr(func, CALLBACK_MARK_ATTR) 

105 

106 

107def introspect_param_type(func: Callable): 

108 """Return the parameter type hint of the given single-parameter function.""" 

109 type_hints = get_type_hints(func) 

110 type_hints.pop("return", None) 

111 

112 if len(type_hints) != 1: 

113 raise DeclarationError("Callback must have exactly one typed parameter") 

114 

115 return next(iter(type_hints.values())) 

116 

117 

118def _envelope_task_type(annotation: Any) -> Any | None: 

119 """Return the task annotation of an execution envelope, or None for other annotations.""" 

120 match annotation: 

121 case type() if issubclass(annotation, TaskExecution): 

122 return annotation.model_fields["task"].annotation 

123 

124 return None 

125 

126 

127def _is_concrete_task(annotation: Any) -> bool: 

128 """Return True if the annotation names one task subclass.""" 

129 return isinstance(annotation, type) and issubclass(annotation, Task) and annotation is not Task 

130 

131 

132def introspect_decls(obj): 

133 """Discover declared entities and callbacks within the given object.""" 

134 decls: list[DeclaredEntity] = [] 

135 callbacks: list[tuple[Callable, CallbackKind]] = [] 

136 

137 for symbol in dir(obj): 

138 if symbol.startswith("__") and symbol != AUTO_ENTITY_ATTR: 

139 continue 

140 

141 # We use getattr_static here to avoid triggering property evaluations. This is quite slow, 

142 # but with expected usage this performance should be acceptable. 

143 attr = inspect.getattr_static(obj, symbol) 

144 

145 match attr: 

146 case DeclaredEntity(): 

147 decls.append(attr) 

148 case func if is_callback(func): 

149 # Since getattr_static returns the function object, we need to do another getattr 

150 # to get the method. 

151 func = getattr(obj, symbol) 

152 callbacks.append((func, get_callback_kind(func))) 

153 

154 return decls, callbacks 

155 

156 

157class CallbackKind(StrEnum): 

158 ENTITY_INIT = auto() 

159 ENTITY_DEINIT = auto() 

160 COMMAND_HANDLER = auto() 

161 TASK_HANDLER = auto() 

162 REQUEST_HANDLER = auto() 

163 TASK_FACTORY = auto() 

164 ENABLE = auto() 

165 DISABLE = auto() 

166 

167 

168class DeclaredEntity[T: EntityImpl = EntityImpl](EntityDelegate): 

169 """Represents an eventual entity registration, collecting callbacks before the service starts.""" 

170 

171 def __init__(self, name: str | None): 

172 self.name = name 

173 self._associated_callbacks: list[tuple[CallbackKind, Callable]] = [] 

174 

175 # These are set when the service is registered. 

176 self.client: SensorKit | None = None # TODO: Remove when the impl itself provides this. 

177 self.service: ServiceContext | None = None 

178 self.impl: T | None = None 

179 

180 @property 

181 def delegate_target(self): 

182 return self.impl 

183 

184 @property 

185 def binding(self): 

186 warnings.warn("Deprecated impl access from declarative object", stacklevel=2) 

187 return self.impl 

188 

189 @final 

190 def associate(self, func: Callable, kind: CallbackKind): 

191 """Queue a callback to be registered with the implementation after it is created.""" 

192 self._associated_callbacks.append((kind, func)) 

193 

194 @final 

195 async def register( 

196 self, 

197 client: SensorKit, 

198 service: ServiceContext, 

199 *, 

200 acquire_lease: bool = True, 

201 ): 

202 """Register the declared entity with the SensorKit backend. 

203 

204 Args: 

205 client: the SensorKit client instance for interacting with the backend 

206 service: the service context that manages this entity's lifecycle 

207 acquire_lease: whether to acquire a lease on the entity during registration 

208 

209 Raises: 

210 DeclarationError: if the entity does not have a name assigned 

211 Exception: any exception raised by an initialization callback is propagated 

212 """ 

213 if not self.name: 

214 raise DeclarationError("Entity must have a name") 

215 

216 # Create our entity implementation and register all associated callbacks. Nothing hits the 

217 # wire at this point. 

218 self.impl = self.create_impl(service) 

219 

220 for kind, func in self._associated_callbacks: 

221 self.register_callback(kind, func) 

222 

223 # Validate the declaration against the now-configured impl, before we touch the backend. 

224 self.validate_declaration() 

225 

226 # Store references for use by the caller. 

227 self.client = client 

228 self.service = service 

229 

230 # Register and attach the impl. If lease acquisition fails, we raise here and the service 

231 # will exit. 

232 await service.register_impl(self.impl, acquire_lease=acquire_lease) 

233 

234 def validate_declaration(self): 

235 """Validate the declaration against the configured implementation.""" 

236 pass 

237 

238 def create_impl(self, service: ServiceContext): 

239 """Instantiate the implementation object bound to *service*.""" 

240 return EntityImpl.for_service_context(service, self.name) 

241 

242 def register_callback(self, kind: CallbackKind, func: Callable): 

243 """Route a callback to the appropriate registration method on the implementation.""" 

244 match kind: 

245 case CallbackKind.ENTITY_INIT: 

246 self.impl.on_attach(func) 

247 case CallbackKind.ENTITY_DEINIT: 

248 self.impl.on_detach(func) 

249 case CallbackKind.REQUEST_HANDLER: 

250 request = get_request(func) 

251 self.impl.on_attach(functools.partial(self.impl.handle_request, request, func)) 

252 

253 

254class DeclaredDevice(DeclaredEntity[DeviceImpl], DeviceDelegate): 

255 """Represents an eventual device registration.""" 

256 

257 def __init__( 

258 self, 

259 name: str | None, 

260 *, 

261 archetype: Archetype | None = None, 

262 traits: list[Trait] | None = None, 

263 ): 

264 super().__init__(name) 

265 self.archetype = archetype 

266 self.declared_traits = frozenset( 

267 itertools.chain( 

268 (archetype,) if archetype is not None else (), 

269 traits or (), 

270 ) 

271 ) 

272 

273 @override 

274 def create_impl(self, svc: ServiceContext): 

275 return DeviceImpl.for_service_context(svc, self.name, archetype=self.archetype) 

276 

277 @override 

278 def validate_declaration(self): 

279 # FIXME: For now we trust the device to publish the keywords required by its traits. 

280 # This should be removed in favor of API that allows the device implementation 

281 # to explicitly declare the keywords it publishes, which can then be used to 

282 # validate whether its traits are satisfied. 

283 for trait in self.declared_traits: 

284 for kw_id in trait.effective_keyword_ids(): 

285 self.impl.declare_published_keyword(kw_id) 

286 

287 # Validate declared traits against the info the device will publish when it attaches. 

288 details = self.impl.entity_info().details 

289 

290 if not isinstance(details, DeviceDetails): 

291 raise RuntimeError("Device did not publish its details") 

292 

293 for trait in self.declared_traits: 

294 if not trait.match(details): 

295 missing = [] 

296 

297 if commands := trait.effective_command_ids() - details.supported_commands: 

298 missing.append("does not implement " + ", ".join(sorted(commands))) 

299 

300 if keywords := trait.effective_keyword_ids() - details.published_keywords: 

301 missing.append("does not publish " + ", ".join(sorted(keywords))) 

302 

303 raise DeclarationError( 

304 f"Device declares trait '{trait.name}' but {'; '.join(missing)}" 

305 ) 

306 

307 @override 

308 def register_callback(self, kind: CallbackKind, func: Callable): 

309 super().register_callback(kind, func) 

310 

311 match kind: 

312 case CallbackKind.ENABLE: 

313 self.impl.on_enable(func) 

314 case CallbackKind.DISABLE: 

315 self.impl.on_disable(func) 

316 case CallbackKind.COMMAND_HANDLER: 

317 command_type = introspect_param_type(func) 

318 

319 if not issubclass(command_type, DeviceCommand): 

320 raise DeclarationError("Command handler parameter has incorrect type") 

321 

322 self.impl.command_handler(command_type)(func) 

323 

324 

325class DeclaredController(DeclaredEntity[ControllerImpl], ControllerDelegate): 

326 """Represents an eventual controller registration.""" 

327 

328 @override 

329 def create_impl(self, svc: ServiceContext): 

330 return ControllerImpl.for_service_context(svc, self.name) 

331 

332 @override 

333 def register_callback(self, kind: CallbackKind, func: Callable): 

334 super().register_callback(kind, func) 

335 

336 match kind: 

337 case CallbackKind.ENABLE: 

338 self.impl.on_enable(func) 

339 case CallbackKind.DISABLE: 

340 self.impl.on_disable(func) 

341 case CallbackKind.TASK_HANDLER: 

342 annotation = introspect_param_type(func) 

343 

344 match _envelope_task_type(annotation): 

345 case None if _is_concrete_task(annotation): 

346 self.impl.add_task_handler(annotation, task_callback=func) 

347 case task_type if _is_concrete_task(task_type): 

348 self.impl.add_task_handler(task_type, execution_callback=func) 

349 case _: 

350 raise DeclarationError( 

351 "Task handler parameter must name a concrete task type" 

352 ) 

353 

354 

355class DeclaredProgram(DeclaredEntity[ProgramImpl], ProgramDelegate): 

356 """Represents an eventual program registration.""" 

357 

358 @override 

359 def create_impl(self, svc: ServiceContext): 

360 return ProgramImpl.for_service_context(svc, self.name) 

361 

362 @override 

363 def register_callback(self, kind: CallbackKind, func: Callable): 

364 super().register_callback(kind, func) 

365 

366 match kind: 

367 case CallbackKind.ENABLE: 

368 self.impl.on_enable(func) 

369 case CallbackKind.DISABLE: 

370 self.impl.on_disable(func) 

371 case CallbackKind.TASK_FACTORY: 

372 self.impl.task_factory(func) 

373 

374 

375class Service: 

376 """Runs a single SensorKit service instance given a set of declared entity objects.""" 

377 

378 def __init__(self, name: str, version: str): 

379 self.name = name 

380 self.version = version 

381 self.declarations: set[DeclaredEntity] = set() 

382 self.context: ServiceContext | None = None 

383 self.client: SensorKit | None = None 

384 self._delegate_entity: DeclaredEntity | None = None 

385 self._register_lock = asyncio.Lock() 

386 self._started = False 

387 loop = asyncio.get_running_loop() 

388 self.running = loop.create_future() 

389 self.shutdown = loop.create_future() 

390 

391 def add(self, declared: DeclaredEntity, name: str | None = None): 

392 """Add an entity declaration to the service. 

393 

394 >>> my_entity = declare_entity(name="my_entity") 

395 >>> service.add(my_entity) 

396 

397 If `name` is given and the declaration already includes a static name assignment, an error 

398 is raised. 

399 

400 If no `name` is given and the declaration has no static name assigned, the entity will 

401 "share" the name of the containing service. This can only apply to the first such nameless 

402 declaration. Adding a second declaration without a name will raise an error. 

403 """ 

404 if name: 

405 if declared.name: 

406 raise DeclarationError("Cannot reassign entity name") 

407 

408 declared.name = name 

409 elif not declared.name: 

410 if self._delegate_entity: 

411 raise DeclarationError("Cannot determine entity name") 

412 

413 # Set the name of this entity to the name of the service. This allows single-entity 

414 # services to avoid having to name both the service and the entity. 

415 self._delegate_entity = declared 

416 declared.name = self.name 

417 

418 self.declarations.add(declared) 

419 

420 def include(self, obj: Any, *, name: str | None = None): 

421 """Add all entity declarations contained or marked in the given object. 

422 

423 Typically, the target object will be the instance of a class that has been decorated by, 

424 e.g., `declare_entity`. In this case, the marks applied by that decorator are found and 

425 a single entity declaration is created automatically. 

426 

427 >>> @declare_entity 

428 >>> class MyEntity: 

429 >>> ... 

430 >>> service.include(MyEntity(), name="my_entity") 

431 

432 If the input object is a type, the type will be instantiated assuming a no-parameter 

433 constructor. The instance object will then be searched for marks and entity declarations 

434 as above. 

435 

436 >>> service.include(MyEntity, name="my_entity") 

437 

438 If the input object is a module, marks do not apply. It is simply searched for entity 

439 declarations. 

440 

441 >>> import myorg.devices 

442 >>> service.include(myorg.devices) 

443 

444 In all cases, the `name` argument is applied if and only if a single entity declaration is 

445 resolved. If more than one is resolved (e.g., in the module case), an error is raised to 

446 indicate the name assignment ambiguity. 

447 """ 

448 if isinstance(obj, type): 

449 cls = obj 

450 

451 try: 

452 obj = cls() 

453 except Exception as e: 

454 raise DeclarationError(f"Failed to instantiate class {cls.__name__}") from e 

455 

456 typename = type(obj).__name__ 

457 

458 # If we have an instance of a class marked for automatic entity creation, make it so. 

459 auto_create_decl(obj) 

460 

461 # Get the declarations contained in the input object. 

462 decls, callbacks = introspect_decls(obj) 

463 

464 if not decls: 

465 raise DeclarationError(f"No entity declarations found in {typename}") 

466 

467 if len(decls) == 1: 

468 # Exactly one declaration in this namespace. This will typically be the case for 

469 # classes that implement an entity. 

470 decl = decls[0] 

471 

472 # Automatically associate all floating callbacks and then add the declaration. 

473 for func, kind in callbacks: 

474 decl.associate(func, kind) 

475 

476 self.add(decl, name) 

477 else: 

478 # Multiple declarations. This will generally be a module include. In this case, we 

479 # treat the existence of any floating callbacks as an error condition rather than make 

480 # assumptions about which declaration is intended to be associated with which callback. 

481 if callbacks: 

482 raise DeclarationError( 

483 f"Floating callbacks alongside multiple declarations in {typename}" 

484 ) 

485 

486 # Similarly, we can't be sure about name assignment either. The module include use case 

487 # demands hardcoded naming. 

488 if name is not None: 

489 raise DeclarationError( 

490 f"Name assignment is ambiguous with multiple declarations in {typename}" 

491 ) 

492 

493 # Add all declarations. 

494 for decl in decls: 

495 self.add(decl) 

496 

497 return decls 

498 

499 def include_module(self, **kwargs): 

500 """Add all entity declarations found in the calling module. 

501 

502 See the `include` method. 

503 """ 

504 # Include decls from the module of the user code call site. We must check for None here 

505 # because in certain contexts there may be no calling module. 

506 if mod := get_caller_module(depth=1): 

507 self.include(mod, **kwargs) 

508 

509 async def register(self): 

510 """Idempotent method to connect to the backend and register this service.""" 

511 async with self._register_lock: 

512 if self.client is None: 

513 self.client = await connect() 

514 

515 if self.context is None: 

516 self.context = await self.client.register_service(self.name, self.version) 

517 

518 async def start(self): 

519 """Start the service.""" 

520 if self._started: 

521 raise RuntimeError("Service was already started") 

522 

523 self._started = True 

524 

525 try: 

526 # Register as a service. 

527 await self.register() 

528 

529 # Register all declared entities. 

530 await asyncio.gather( 

531 *( 

532 decl.register( 

533 self.client, self.context, acquire_lease=decl is not self._delegate_entity 

534 ) 

535 for decl in self.declarations 

536 ) 

537 ) 

538 

539 self.running.set_result(True) 

540 except BaseException as e: 

541 logger.debug(f"service error propagated to declarative API: {type(e).__name__}: {e}") 

542 self.running.set_exception(e) 

543 self.shutdown.set_exception(e) 

544 

545 if self.context is not None: 

546 await self.context.shutdown() 

547 

548 raise 

549 

550 async def wait_for_shutdown(): 

551 try: 

552 await self.context.join() 

553 self.shutdown.set_result(True) 

554 except asyncio.CancelledError: 

555 self.shutdown.cancel() 

556 raise 

557 except BaseException as e: 

558 if not self.shutdown.done(): 

559 self.shutdown.set_exception(e) 

560 

561 if not isinstance(e, Exception): 

562 # Make sure to re-raise BaseException. 

563 raise 

564 

565 self._shutdown_waiter = asyncio.create_task(wait_for_shutdown()) 

566 

567 async def run(self): 

568 """Run the service.""" 

569 await self.start() 

570 

571 try: 

572 await self.shutdown 

573 finally: 

574 await self.stop() 

575 

576 async def stop(self): 

577 """Stop the service.""" 

578 if self.context is not None: 

579 await self.context.shutdown() 

580 

581 await self.shutdown 

582 

583 

584class DeclarationError(Exception): 

585 """Raised when a declaration or its usage is invalid.""" 

586 

587 

588def _decorator(decl: DeclaredEntity | None, kind: CallbackKind, func: Callable): 

589 if decl: 

590 # Associate the callback with the declaration. 

591 decl.associate(func, kind) 

592 else: 

593 # Mark as floating, for later automatic association. 

594 _mark_callback(func, kind) 

595 

596 return func 

597 

598 

599def on_attach(arg: DeclaredEntity | InitDeinitCallback): 

600 """Register a callback to be executed during entity initialization.""" 

601 match arg: 

602 case DeclaredEntity(): 

603 return functools.partial(_decorator, arg, CallbackKind.ENTITY_INIT) 

604 case _: 

605 return _decorator(None, CallbackKind.ENTITY_INIT, arg) 

606 

607 

608def on_detach(arg: DeclaredEntity | InitDeinitCallback): 

609 """Register a callback to be executed during entity deinitialization.""" 

610 match arg: 

611 case DeclaredEntity(): 

612 return functools.partial(_decorator, arg, CallbackKind.ENTITY_DEINIT) 

613 case _: 

614 return _decorator(None, CallbackKind.ENTITY_DEINIT, arg) 

615 

616 

617def command_handler(arg: DeclaredEntity | CommandHandlerCallback): 

618 """Declare a command handler.""" 

619 match arg: 

620 case DeclaredEntity(): 

621 return functools.partial(_decorator, arg, CallbackKind.COMMAND_HANDLER) 

622 case _: 

623 return _decorator(None, CallbackKind.COMMAND_HANDLER, arg) 

624 

625 

626def task_handler(arg: DeclaredEntity | TaskHandlerCallback | ExecutionHandlerCallback): 

627 """Declare a task handler for a controller. 

628 

629 The handler's parameter annotation selects its task type and input. 

630 A task annotation receives the task. 

631 A `TaskExecution[T]` annotation receives the execution envelope of a `T` task. 

632 """ 

633 match arg: 

634 case DeclaredEntity(): 

635 return functools.partial(_decorator, arg, CallbackKind.TASK_HANDLER) 

636 case _: 

637 return _decorator(None, CallbackKind.TASK_HANDLER, arg) 

638 

639 

640def task_factory(arg: DeclaredEntity | TaskFactoryFunc): 

641 """Declare the task factory function for a program.""" 

642 match arg: 

643 case DeclaredEntity(): 

644 return functools.partial(_decorator, arg, CallbackKind.TASK_FACTORY) 

645 case _: 

646 return _decorator(None, CallbackKind.TASK_FACTORY, arg) 

647 

648 

649@overload 

650def request_handler[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None]( 

651 request: LongRequest[P, R, V], 

652 decl: DeclaredEntity | None = None, 

653) -> Callable[[LongHandler[P, R, V]], LongHandler[P, R, V]]: ... 

654 

655 

656@overload 

657def request_handler[P: BaseModel | None, R: BaseModel | None]( 

658 request: Request[P, R], 

659 decl: DeclaredEntity | None = None, 

660) -> Callable[[SimpleHandler[P, R]], SimpleHandler[P, R]]: ... 

661 

662 

663def request_handler(request: RequestBase, decl: DeclaredEntity | None = None): 

664 """Declare a handler for the given request. 

665 

666 The handler takes the request message, and takes a CallContext as well if the request is 

667 long-running. A handler that takes no CallContext gives its response type as the return 

668 annotation. A request that declares no message types it as None. 

669 

670 >>> slew_request = declare_long_request("slew", message=SlewMessage) 

671 >>> 

672 >>> @request_handler(slew_request) 

673 ... async def handle_slew( 

674 ... self, 

675 ... params: SlewMessage, 

676 ... call: CallContext[None], 

677 ... ): 

678 ... ... 

679 

680 A type checker verifies the annotations against the request declaration, so annotate every 

681 parameter. Nothing checks the handler at runtime until it is called. 

682 

683 Callers invoke the request through an entity client. 

684 

685 >>> await kit.entity("mount").call(slew_request, SlewMessage(...)) 

686 

687 Args: 

688 request: The request declaration the handler serves. 

689 decl: The entity declaration to associate with, when not declaring on a marked class. 

690 """ 

691 return functools.partial(_request_decorator, decl, request) 

692 

693 

694def _request_decorator(decl: DeclaredEntity | None, request: RequestBase, func: Callable): 

695 _mark_request(func, request) 

696 return _decorator(decl, CallbackKind.REQUEST_HANDLER, func) 

697 

698 

699def on_enable(arg: DeclaredEntity | Callable): 

700 """Register a callback to be called when a program or device is enabled.""" 

701 match arg: 

702 case DeclaredEntity(): 

703 return functools.partial(_decorator, arg, CallbackKind.ENABLE) 

704 case _: 

705 return _decorator(None, CallbackKind.ENABLE, arg) 

706 

707 

708def on_disable(arg: DeclaredEntity | Callable): 

709 """Register a callback to be called when a program or device is disabled.""" 

710 match arg: 

711 case DeclaredEntity(): 

712 return functools.partial(_decorator, arg, CallbackKind.DISABLE) 

713 case _: 

714 return _decorator(None, CallbackKind.DISABLE, arg) 

715 

716 

717def declare_entity(cls: type | None = None, *, name: str | None = None): 

718 """Declare a generic entity to be implemented by a local service.""" 

719 if cls: 

720 return _mark_decl_type(cls, DeclaredEntity) 

721 else: 

722 return DeclaredEntity(name) 

723 

724 

725def declare_device( 

726 cls: type | None = None, 

727 *, 

728 name: str | None = None, 

729 type: Archetype | None = None, 

730 traits: list[Trait] | None = None, 

731): 

732 """Declare a Device to be implemented by a local service. 

733 

734 Can be used as a bare class decorator (`@sk.declare_device`), a keyword 

735 decorator (`@sk.declare_device(type=..., traits=[...])`), or an explicit declaration 

736 (`my_device = sk.declare_device(name="foo", type=..., traits=[...])`) 

737 

738 `type` assigns the device's principal archetype. Omitting it leaves the 

739 device without archetype identity. Both `type` and `traits` are validated 

740 against the implementation's capabilities. 

741 """ 

742 

743 if cls: 

744 return _mark_decl_type(cls, DeclaredDevice, archetype=type, traits=list(traits or [])) 

745 elif name is not None: 

746 return DeclaredDevice(name, archetype=type, traits=traits) 

747 elif type is not None or traits: 

748 return functools.partial( 

749 _mark_decl_type, 

750 decl_type=DeclaredDevice, 

751 archetype=type, 

752 traits=list(traits or []), 

753 ) 

754 else: 

755 return DeclaredDevice(None) 

756 

757 

758def declare_controller(cls: type | None = None, *, name: str | None = None): 

759 """Declare a Controller to be implemented by a local service.""" 

760 if cls: 

761 return _mark_decl_type(cls, DeclaredController) 

762 else: 

763 return DeclaredController(name) 

764 

765 

766def declare_program(cls: type | None = None, *, name: str | None = None): 

767 """Declare a Program to be implemented by a local service.""" 

768 if cls: 

769 return _mark_decl_type(cls, DeclaredProgram) 

770 else: 

771 return DeclaredProgram(name)