dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
#!/usr/bin/env python3

# Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
#
# This file is part of Ri.
# The Ri project belongs to the Dunimd Team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Ri (Ri) - A high-performance Rust middleware framework with modular architecture.

This Python library provides bindings to the Ri Rust core, enabling Python applications to leverage
a comprehensive set of middleware services including caching, messaging, service mesh, authentication,
device management, observability, protocol handling, and database integration. The framework follows
a plugin-based architecture where each module provides specialized functionality that can be composed
into unified middleware solutions.

Key Components:
- Core Framework: Application lifecycle management, configuration, logging, and filesystem abstraction
- Python Module Support: Native integration for Python-based service modules
- Infrastructure Services: Caching, queuing, and database connectivity
- Traffic Management: Gateway routing, rate limiting, and circuit breaker patterns
- Service Mesh: Service discovery, load balancing, and traffic routing
- Security: Authentication, authorization, and session management
- Device Management: IoT device control and resource allocation
- Observability: Metrics collection, tracing, and health monitoring
- Protocol Support: Multi-protocol connection handling and frame processing
- Data Validation: Schema validation, sanitization, and error reporting

Example Usage:
    from ri import RiAppBuilder, RiCacheModule, RiGateway
    
    app = (RiAppBuilder()
        .with_config("config.yaml")
        .with_logging(RiLogConfig())
        .build())
    cache = RiCacheModule()
    gateway = RiGateway()
"""

__version__ = "0.1.9"
__author__ = "Dunimd Team"
__license__ = "Apache-2.0"

# Import the Rust extension module containing all Ri bindings
# The ri extension is generated by PyO3 and provides zero-overhead access to Rust implementations
from .ri import (
    # =============================================================================
    # Core classes - Fundamental framework components for application lifecycle,
    # configuration management, logging, hooks, and service context management
    # =============================================================================
    RiAppBuilder as _RustAppBuilder,
    RiAppRuntime as _RustAppRuntime,
    RiConfig, RiConfigManager, RiError,
    RiFileSystem, RiHookBus, RiHookEvent, RiHookKind, RiLogConfig,
    RiLogLevel, RiLogger, RiModulePhase, RiServiceContext,
    
    # =============================================================================
    # Lock utilities - Safe lock utilities for concurrent programming
    # Note: RiLockResult is a type alias, not a pyclass
    # =============================================================================
    RiLockError,
    
    # =============================================================================
    # Python module support - Enables Python-based service modules to integrate
    # with the Ri framework, supporting both synchronous and asynchronous service patterns
    # =============================================================================
    RiPythonModule, RiPythonModuleAdapter, RiPythonServiceModule, RiPythonAsyncServiceModule,
    
    # =============================================================================
    # Health check types - Health monitoring for services and modules
    # =============================================================================
    RiHealthStatus, RiHealthCheckResult, RiHealthCheckConfig, RiHealthReport,
    
    # =============================================================================
    # Lifecycle management - Module lifecycle observation
    # =============================================================================
    RiLifecycleObserver,
    
    # =============================================================================
    # Analytics module - Log analytics and usage statistics
    # =============================================================================
    RiLogAnalyticsModule,
    
    # =============================================================================
    # Cache classes - In-memory caching with configurable backends, eviction policies,
    # statistics tracking, and event notification capabilities
    # =============================================================================
    RiCacheModule, RiCacheManager, RiCacheConfig, RiCacheBackendType,
    RiCachePolicy, RiCacheStats, RiCachedValue, RiCacheEvent,
    
    # =============================================================================
    # Queue classes - Message queuing with multiple backend support, retry policies,
    # dead letter handling, and queue statistics monitoring
    # =============================================================================
    RiQueueModule, RiQueueConfig, RiQueueManager, RiQueueMessage, 
    RiQueueStats, RiQueueBackendType, RiRetryPolicy, RiDeadLetterConfig,
    
    # =============================================================================
    # Gateway classes - Traffic management including HTTP routing, rate limiting,
    # circuit breaker patterns, and sliding window algorithms for distributed systems
    # =============================================================================
    RiGateway, RiGatewayConfig, RiRouter, RiRoute,
    RiRateLimiter, RiRateLimitConfig, RiRateLimitStats,
    RiSlidingWindowRateLimiter, RiCircuitBreaker, RiCircuitBreakerConfig,
    RiCircuitBreakerState, RiCircuitBreakerMetrics,
    RiBackendServer, RiLoadBalancerServerStats,
    RiLoadBalancer, RiLoadBalancerStrategy,
    
    # =============================================================================
    # Service mesh classes - Service discovery, traffic routing, load balancing,
    # weighted destinations, and traffic splitting for microservices architecture
    # =============================================================================
    RiServiceMesh, RiServiceMeshConfig, RiServiceDiscovery,
    RiServiceInstance, RiServiceStatus, RiServiceMeshStats,
    RiServiceEndpoint, RiServiceHealthStatus,
    RiTrafficRoute, RiMatchCriteria, RiRouteAction, RiWeightedDestination,
    RiTrafficManager, RiHealthChecker, RiHealthSummary, RiHealthCheckType,
    
    # =============================================================================
    # Auth classes - Authentication and authorization including JWT management,
    # session handling, OAuth integration, role-based and permission-based access control
    # =============================================================================
    RiAuthModule, RiAuthConfig, RiJWTManager, RiJWTClaims, RiJWTValidationOptions,
    RiSessionManager, RiSession, RiPermissionManager, RiPermission, RiRole,
    RiOAuthManager, RiOAuthToken, RiOAuthUserInfo, RiOAuthProvider,
    RiJWTRevocationList, RiRevokedTokenInfo,
    RiSecurityManager,
    
    # =============================================================================
    # Device classes - IoT device management including device control, health monitoring,
    # resource allocation, connection pooling, and network device discovery
    # =============================================================================
    RiDeviceControlModule, RiDevice, RiDeviceType, RiDeviceStatus,
    RiDeviceCapabilities, RiDeviceHealthMetrics, RiDeviceController,
    RiDeviceConfig, RiDeviceControlConfig, RiDeviceSchedulingConfig, RiNetworkDeviceInfo,
    RiDiscoveryResult, RiResourceRequest,
    RiResourceAllocation, RiRequestSlaClass, RiResourceWeights,
    RiAffinityRules,
    RiResourcePool, RiResourcePoolConfig, RiResourcePoolStatistics, RiResourcePoolManager,
    RiResourcePoolStatus, RiConnectionPoolStatistics,
    RiResourceScheduler, RiDeviceScheduler, RiSchedulingPolicy,
    RiAllocationRecord, RiAllocationRequest, RiAllocationStatistics,
    RiDeviceTypeStatistics, RiSchedulingRecommendation, RiSchedulingRecommendationType,
    RiDeviceDiscoveryEngine,
    
    # =============================================================================
    # Observability classes - Metrics, tracing, and health monitoring for system
    # observability and performance analysis
    # =============================================================================
    RiObservabilityModule, RiObservabilityConfig,
    RiMetricsRegistry, RiTracer,
    RiMetricType, RiMetricConfig, RiMetricSample, RiMetric,
    RiObservabilityData,
    RiSystemMetricsCollector, RiSystemMetrics,
    RiCPUMetrics, RiMemoryMetrics, RiDiskMetrics, RiNetworkMetrics,
    
    # =============================================================================
    # Validation classes - Data validation, schema validation, sanitization,
    # and validation result reporting with configurable severity levels
    # =============================================================================
    RiValidationError, RiValidationResult, RiValidationSeverity,
    RiValidatorBuilder, RiValidationRunner, RiSanitizer,
    RiSanitizationConfig, RiSchemaValidator, RiValidationModule,
    
    # =============================================================================
    # Protocol classes - Multi-protocol support including connection management,
    # frame processing, security levels, and protocol statistics monitoring
    # =============================================================================
    RiProtocolManager, RiProtocolType, RiProtocolConfig,
    RiProtocolStatus, RiProtocolStats, RiConnectionState,
    RiConnectionStats, RiProtocolHealth,
    RiFrame, RiFrameHeader, RiFrameType,
    RiConnectionInfo, RiMessageFlags, RiSecurityLevel,
    RiFrameParser, RiFrameBuilder,
    
    # =============================================================================
    # Database classes - Database configuration, connection pooling, row-level
    # access, and result set management across different database backends
    # =============================================================================
    RiDatabaseConfig, RiDatabasePool, RiDBRow, RiDBResult,
    RiDynamicPoolConfig, RiDatabaseMetrics,
    RiDatabaseMigration,
    RiPyORMRepository,

    # =============================================================================
    # gRPC classes - gRPC server and client support
    # =============================================================================
    RiGrpcConfig, RiGrpcStats,
    RiGrpcServiceRegistryPy,
    RiGrpcServerPy, RiGrpcClientPy,

    # =============================================================================
    # WebSocket classes - WebSocket server and client support
    # =============================================================================
    RiWSServerConfig, RiWSEvent, RiWSSessionInfo, RiWSServerStats,
    RiWSPythonHandler, RiWSSessionManagerPy,
    RiWSServerPy, RiWSClientConfig, RiWSClientStats, RiWSClientPy,

    # =============================================================================
    # Module RPC classes - Inter-module RPC communication for distributed method calls
    # =============================================================================
    RiModuleRPC, RiModuleClient, RiModuleEndpoint, RiMethodCall, RiMethodResponse,
)

# =============================================================================
# Submodules - Functional submodules organized by domain area, providing
# specialized functionality for specific middleware concerns
# =============================================================================
from .ri import (
    device, cache, fs, hooks, observability,
    queue, gateway, service_mesh, auth, protocol, database,
    grpc, ws
)

# =============================================================================
# __all__ export list - Public API surface defining all symbols intended for
# external use. These symbols are imported when 'from ri import *' is used.
# Organized by functional category for clarity and maintainability.
# =============================================================================
__all__ = [
    # Core classes - Application framework, configuration, logging, and hooks
    'RiAppBuilder', 'RiAppRuntime', 'RiConfig', 'RiConfigManager', 'RiError',
    'RiFileSystem', 'RiHookBus', 'RiHookEvent', 'RiHookKind', 'RiLogConfig',
    'RiLogLevel', 'RiLogger', 'RiModulePhase', 'RiServiceContext',
    
    # Lock utilities - Safe lock utilities for concurrent programming
    'RiLockError',
    
    # Python module support - Python service module integration
    'RiPythonModule', 'RiPythonModuleAdapter', 'RiPythonServiceModule', 'RiPythonAsyncServiceModule',
    
    # Health check types - Health monitoring for services and modules
    'RiHealthStatus', 'RiHealthCheckResult', 'RiHealthCheckConfig', 'RiHealthReport',
    
    # Lifecycle management - Module lifecycle observation
    'RiLifecycleObserver',

    # Analytics module - Log analytics and usage statistics
    'RiLogAnalyticsModule',
    
    # Cache classes - Caching infrastructure and management
    'RiCacheModule', 'RiCacheManager', 'RiCacheConfig', 'RiCacheBackendType',
    'RiCachePolicy', 'RiCacheStats', 'RiCachedValue', 'RiCacheEvent',
    
    # Queue classes - Message queuing infrastructure
    'RiQueueModule', 'RiQueueConfig', 'RiQueueManager', 'RiQueueMessage', 
    'RiQueueStats', 'RiQueueBackendType', 'RiRetryPolicy', 'RiDeadLetterConfig',
    
    # Gateway classes - Traffic management and resilience patterns
    'RiGateway', 'RiGatewayConfig', 'RiRouter', 'RiRoute',
    'RiRateLimiter', 'RiRateLimitConfig', 'RiRateLimitStats',
    'RiSlidingWindowRateLimiter', 'RiCircuitBreaker', 'RiCircuitBreakerConfig',
    'RiCircuitBreakerState', 'RiCircuitBreakerMetrics',
    'RiBackendServer', 'RiLoadBalancerServerStats',
    'RiLoadBalancer', 'RiLoadBalancerStrategy',
    
    # Service mesh classes - Service discovery, traffic routing, and health checking
    'RiServiceMesh', 'RiServiceMeshConfig', 'RiServiceDiscovery',
    'RiServiceInstance', 'RiServiceStatus', 'RiServiceMeshStats',
    'RiServiceEndpoint', 'RiServiceHealthStatus',
    'RiTrafficRoute', 'RiMatchCriteria', 'RiRouteAction', 'RiWeightedDestination',
    'RiTrafficManager', 'RiHealthChecker', 'RiHealthSummary', 'RiHealthCheckType',
    
    # Auth classes - Authentication, authorization, and session management
    'RiAuthModule', 'RiAuthConfig', 'RiJWTManager', 'RiJWTClaims', 'RiJWTValidationOptions',
    'RiSessionManager', 'RiSession', 'RiPermissionManager', 'RiPermission', 'RiRole',
    'RiOAuthManager', 'RiOAuthToken', 'RiOAuthUserInfo', 'RiOAuthProvider',
    'RiJWTRevocationList', 'RiRevokedTokenInfo',
    'RiSecurityManager',
    
    # Device classes - IoT device control and resource management
    'RiDeviceControlModule', 'RiDevice', 'RiDeviceType', 'RiDeviceStatus',
    'RiDeviceCapabilities', 'RiDeviceHealthMetrics', 'RiDeviceController',
    'RiDeviceConfig', 'RiDeviceControlConfig', 'RiDeviceSchedulingConfig', 'RiNetworkDeviceInfo',
    'RiDiscoveryResult', 'RiResourceRequest',
    'RiResourceAllocation', 'RiRequestSlaClass', 'RiResourceWeights',
    'RiAffinityRules',
    'RiResourcePool', 'RiResourcePoolConfig', 'RiResourcePoolStatistics', 'RiResourcePoolManager',
    'RiResourcePoolStatus', 'RiConnectionPoolStatistics',
    'RiResourceScheduler', 'RiDeviceScheduler', 'RiSchedulingPolicy',
    'RiAllocationRecord', 'RiAllocationRequest', 'RiAllocationStatistics',
    'RiDeviceTypeStatistics', 'RiSchedulingRecommendation', 'RiSchedulingRecommendationType',
    'RiDeviceDiscoveryEngine',
    
    # Observability classes - Metrics, tracing, and monitoring
    'RiObservabilityModule', 'RiObservabilityConfig',
    'RiMetricsRegistry', 'RiTracer',
    'RiMetricType', 'RiMetricConfig', 'RiMetricSample', 'RiMetric',
    'RiObservabilityData',
    'RiSystemMetricsCollector', 'RiSystemMetrics',
    'RiCPUMetrics', 'RiMemoryMetrics', 'RiDiskMetrics', 'RiNetworkMetrics',
    
    # Validation classes - Data validation and sanitization
    'RiValidationError', 'RiValidationResult', 'RiValidationSeverity',
    'RiValidatorBuilder', 'RiValidationRunner', 'RiSanitizer',
    'RiSanitizationConfig', 'RiSchemaValidator', 'RiValidationModule',
    
    # Protocol classes - Multi-protocol support and frame processing
    'RiProtocolManager', 'RiProtocolType', 'RiProtocolConfig',
    'RiProtocolStatus', 'RiProtocolStats', 'RiConnectionState',
    'RiConnectionStats', 'RiProtocolHealth',
    'RiFrame', 'RiFrameHeader', 'RiFrameType',
    'RiConnectionInfo', 'RiMessageFlags', 'RiSecurityLevel',
    'RiFrameParser', 'RiFrameBuilder',

    # Database classes - Database configuration and connection pooling
    'RiDatabaseConfig', 'RiDatabasePool', 'RiDBRow', 'RiDBResult',
    'RiDynamicPoolConfig', 'RiDatabaseMetrics',
    'RiDatabaseMigration',
    'RiPyORMRepository',

    # gRPC classes - gRPC server and client support
    'RiGrpcConfig', 'RiGrpcStats',
    'RiGrpcServiceRegistryPy',
    'RiGrpcServerPy', 'RiGrpcClientPy',

    # WebSocket classes - WebSocket server and client support
    'RiWSServerConfig', 'RiWSEvent', 'RiWSSessionInfo', 'RiWSServerStats',
    'RiWSPythonHandler', 'RiWSSessionManagerPy',
    'RiWSServerPy', 'RiWSClientConfig', 'RiWSClientStats', 'RiWSClientPy',

    # Module RPC classes - Inter-module RPC for distributed method calls
    'RiModuleRPC', 'RiModuleClient', 'RiModuleEndpoint', 'RiMethodCall', 'RiMethodResponse',

    # Submodules - Functional submodule references
    'device', 'cache', 'fs', 'hooks', 'observability',
    'queue', 'gateway', 'service_mesh', 'auth', 'protocol', 'database',
    'grpc', 'ws'
]


class RiAppRuntime:
    """Python wrapper for Ri application runtime.
    
    This class provides a Pythonic interface to the Rust RiAppRuntime,
    enabling access to the service context and application lifecycle.
    
    Note:
        This is a thin wrapper around the Rust RiAppRuntime (_RustAppRuntime).
        The wrapper provides a consistent Python API while the actual implementation
        resides in the Rust core. This design ensures zero-overhead access to the
        Rust runtime while maintaining Pythonic usage patterns.
    
    The application runtime manages the complete lifecycle of Ri applications,
    including module initialization, startup, shutdown, and hook event emission.
    
    Attributes:
        _runtime: The underlying Rust RiAppRuntime instance.
    
    Example:
        >>> app = RiAppBuilder().with_config("config.yaml").build()
        >>> app.run(lambda ctx: print("Application started"))
    """
    
    def __init__(self, runtime: _RustAppRuntime):
        """Initialize the wrapper with a Rust runtime instance.
        
        Args:
            runtime: The underlying Rust RiAppRuntime instance from the builder.
        """
        self._runtime = runtime
    
    def get_context(self) -> 'RiServiceContext':
        """Get the service context from the runtime.
        
        Returns:
            RiServiceContext: The service context providing access to core
                functionalities like logging, configuration, and filesystem.
        """
        return self._runtime.get_context()
    
    def run(self, callback) -> None:
        """Run the application with the given callback.
        
        This method executes the complete application lifecycle, including
        module initialization, startup, the provided callback, and shutdown.
        
        Args:
            callback: A callable that will be invoked after all modules have
                been initialized and started. The callback receives no arguments
                in the Python binding (unlike Rust which receives the context).
        
        Example:
            >>> def on_start():
            ...     print("Application is running")
            >>> app.run(on_start)
        """
        return self._runtime.py_run(callback)


class RiAppBuilder:
    """Python wrapper for Ri application builder.
    
    This class provides a Pythonic interface to the Rust RiAppBuilder,
    enabling configuration of Ri applications with method chaining.
    
    Note:
        This is a thin wrapper around the Rust RiAppBuilder (_RustAppBuilder).
        The wrapper is necessary because Rust's PyO3 bindings require reassignment
        for builder methods (e.g., ``builder = builder.with_config(...)``), which
        is not idiomatic in Python. This wrapper automatically handles the
        reassignment internally, allowing natural method chaining without
        explicit reassignment.
        
        **Why this wrapper exists:**
        
        - Rust builder methods return ``Self`` and consume the original builder
        - PyO3 bindings expose this as ``builder = builder.method()`` pattern
        - Python users expect ``builder.method().method()`` chaining without reassignment
        - This wrapper bridges the gap between Rust and Python idioms
        
        **Design Rationale:**
        
        The wrapper maintains the same API surface as the Rust builder while
        providing a more Pythonic experience. All method calls are delegated
        to the underlying Rust implementation with zero overhead.
    
    Attributes:
        _builder: The underlying Rust RiAppBuilder instance.
    
    Example:
        Basic usage with method chaining::
        
            from ri import RiAppBuilder, RiLogConfig
            
            app = (RiAppBuilder()
                .with_config("config.yaml")
                .with_logging(RiLogConfig())
                .with_observability(RiObservabilityConfig())
                .build())
        
        Adding modules::
        
            from ri import RiAppBuilder, RiCacheModule
            
            app = (RiAppBuilder()
                .with_module(RiCacheModule())
                .with_config("config.yaml")
                .build())
    
    See Also:
        RiAppRuntime: The runtime instance created by this builder.
        RiServiceContext: The context provided to running applications.
    """
    
    def __init__(self):
        """Initialize a new Ri application builder.
        
        Creates a new builder instance with default settings. The builder
        can then be configured using the ``with_*`` methods before calling
        ``build()`` to create the application runtime.
        """
        self._builder = _RustAppBuilder()
    
    def with_config(self, config_path: str) -> 'RiAppBuilder':
        """Add a configuration file path.
        
        Args:
            config_path: Path to the configuration file (YAML, TOML, or JSON).
        
        Returns:
            RiAppBuilder: Self for method chaining.
        
        Example:
            >>> builder.with_config("config.yaml").with_config("override.yaml")
        """
        self._builder = self._builder.py_with_config(config_path)
        return self
    
    def with_logging(self, config: 'RiLogConfig') -> 'RiAppBuilder':
        """Configure logging with the provided config.
        
        Args:
            config: RiLogConfig instance with logging settings.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_logging(config)
        return self
    
    def with_observability(self, config: 'RiObservabilityConfig') -> 'RiAppBuilder':
        """Configure observability with the provided config.
        
        Args:
            config: RiObservabilityConfig instance with observability settings.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_observability(config)
        return self
    
    def with_module(self, module) -> 'RiAppBuilder':
        """Add a module to the application.
        
        Args:
            module: A service module instance (sync or async).
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_module(module)
        return self
    
    def with_modules(self, modules: list) -> 'RiAppBuilder':
        """Add multiple modules to the application.
        
        Args:
            modules: List of service module instances.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_modules(modules)
        return self
    
    def with_async_module(self, module) -> 'RiAppBuilder':
        """Add an async module to the application.
        
        Args:
            module: An async service module instance.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_async_module(module)
        return self
    
    def with_async_modules(self, modules: list) -> 'RiAppBuilder':
        """Add multiple async modules to the application.
        
        Args:
            modules: List of async service module instances.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_async_modules(modules)
        return self
    
    def with_python_module(self, module) -> 'RiAppBuilder':
        """Add a Python module to the application.
        
        Args:
            module: A Python module adapter instance.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_python_module(module)
        return self
    
    def with_dms_module(self, module) -> 'RiAppBuilder':
        """Add a Ri module to the application.
        
        Args:
            module: A Ri module instance.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_dms_module(module)
        return self
    
    def with_dms_modules(self, modules: list) -> 'RiAppBuilder':
        """Add multiple Ri modules to the application.
        
        Args:
            modules: List of Ri module instances.
        
        Returns:
            RiAppBuilder: Self for method chaining.
        """
        self._builder = self._builder.py_with_dms_modules(modules)
        return self
    
    def build(self) -> 'RiAppRuntime':
        """Build the application runtime.
        
        Constructs the RiAppRuntime with all configured modules, logging,
        observability, and configuration settings.
        
        Returns:
            RiAppRuntime: The configured application runtime ready to run.
        
        Raises:
            RiError: If the build process fails (e.g., invalid config,
                circular module dependencies).
        
        Example:
            >>> app = RiAppBuilder().with_config("config.yaml").build()
            >>> app.run(lambda: print("Started"))
        """
        runtime = self._builder.py_build()
        return RiAppRuntime(runtime)