Coverage for faststream/nats/broker/broker.py: 95%

128 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1import logging 

2from collections.abc import Iterable, Sequence 

3from typing import ( 

4 TYPE_CHECKING, 

5 Annotated, 

6 Any, 

7 Optional, 

8 Union, 

9 cast, 

10) 

11from urllib.parse import urlparse 

12 

13import anyio 

14import nats 

15from fast_depends import Provider, dependency_provider 

16from nats.aio.client import ( 

17 DEFAULT_CONNECT_TIMEOUT, 

18 DEFAULT_DRAIN_TIMEOUT, 

19 DEFAULT_INBOX_PREFIX, 

20 DEFAULT_MAX_FLUSHER_QUEUE_SIZE, 

21 DEFAULT_MAX_OUTSTANDING_PINGS, 

22 DEFAULT_MAX_RECONNECT_ATTEMPTS, 

23 DEFAULT_PENDING_SIZE, 

24 DEFAULT_PING_INTERVAL, 

25 DEFAULT_RECONNECT_TIME_WAIT, 

26 Client, 

27 ReconnectToServerHandler, 

28) 

29from nats.aio.msg import Msg 

30from nats.errors import Error 

31from nats.js.errors import BadRequestError 

32from typing_extensions import deprecated, overload, override 

33 

34from faststream.__about__ import SERVICE_NAME 

35from faststream._internal.broker import BrokerUsecase 

36from faststream._internal.constants import EMPTY 

37from faststream._internal.context.repository import ContextRepo 

38from faststream._internal.di import FastDependsConfig 

39from faststream._internal.types import IdGenerator 

40from faststream.exceptions import SetupError 

41from faststream.message import gen_cor_id 

42from faststream.middlewares import AckPolicy 

43from faststream.nats.configs import NatsBrokerConfig 

44from faststream.nats.publisher.producer import ( 

45 NatsFastProducerImpl, 

46 NatsJSFastProducer, 

47) 

48from faststream.nats.response import NatsPublishCommand 

49from faststream.nats.security import ( 

50 NatsCredentials, 

51 NatsJWT, 

52 NatsNKey, 

53 NatsSecurity, 

54 NatsToken, 

55 parse_security, 

56 warn_deprecated_security_args, 

57) 

58from faststream.nats.subscriber.usecases.basic import LogicSubscriber 

59from faststream.response.publish_type import PublishType 

60from faststream.security import BaseSecurity 

61from faststream.specification.schema import BrokerSpec 

62 

63from .logging import make_nats_logger_state 

64from .registrator import NatsRegistrator 

65 

66if TYPE_CHECKING: 

67 from types import TracebackType 

68 

69 from fast_depends.dependencies import Dependant 

70 from fast_depends.library.serializer import SerializerProto 

71 from nats.aio.client import ( 

72 Callback, 

73 Credentials, 

74 ErrorCallback, 

75 JWTCallback, 

76 SignatureCallback, 

77 ) 

78 from nats.js.api import Placement, RePublish, StorageType 

79 from nats.js.kv import KeyValue 

80 from nats.js.object_store import ObjectStore 

81 from typing_extensions import TypedDict 

82 

83 from faststream._internal.basic_types import LoggerProto, SendableMessage 

84 from faststream._internal.configs import UnderlyingDriverAnnotations 

85 from faststream._internal.parser import CodecProto 

86 from faststream._internal.types import BrokerMiddleware, CustomCallable 

87 from faststream.nats.configs.broker import JsInitOptions 

88 from faststream.nats.helpers import KVBucketDeclarer, OSBucketDeclarer 

89 from faststream.nats.message import NatsMessage 

90 from faststream.nats.schemas import PubAck, Schedule 

91 from faststream.specification.schema.extra import Tag, TagDict 

92 

93 class NatsInitKwargs(TypedDict, total=False): 

94 """NatsBroker.connect() method type hints. 

95 

96 Args: 

97 error_cb: 

98 Callback to report errors. 

99 disconnected_cb: \ 

100 Callback to report disconnection from NATS. 

101 closed_cb: 

102 Callback to report when client stops reconnection to NATS. 

103 discovered_server_cb: 

104 A callback to report when a new server joins the cluster. 

105 reconnected_cb: 

106 Callback to report success reconnection. 

107 name: 

108 Label the connection with name (shown in NATS monitoring 

109 pedantic: 

110 Turn on NATS server pedantic mode that performs extra checks on the protocol. 

111 https://docs.nats.io/using-nats/developer/connecting/misc#turn-on-pedantic-mode 

112 verbose: 

113 Verbose mode produce more feedback about code execution. 

114 allow_reconnect: 

115 Whether recover connection automatically or not. 

116 connect_timeout: 

117 Timeout in seconds to establish connection with NATS server. 

118 reconnect_time_wait: 

119 Time in seconds to wait for reestablish connection to NATS server 

120 max_reconnect_attempts: 

121 Maximum attempts number to reconnect to NATS server. 

122 ping_interval: 

123 Interval in seconds to ping. 

124 max_outstanding_pings: 

125 Maximum number of failed pings 

126 dont_randomize: 

127 Boolean indicating should client randomly shuffle servers list for reconnection randomness. 

128 flusher_queue_size: 

129 Max count of commands awaiting to be flushed to the socket 

130 no_echo: 

131 Boolean indicating should commands be echoed. 

132 tls_hostname: 

133 Hostname for TLS. 

134 token: 

135 Auth token for NATS auth. 

136 drain_timeout: 

137 Timeout in seconds to drain subscriptions. 

138 signature_cb: 

139 A callback used to sign a nonce from the server while authenticating with nkeys. 

140 The user should sign the nonce and return the base64 encoded signature. 

141 user_jwt_cb: 

142 A callback used to fetch and return the account signed JWT for this user. 

143 user_credentials: 

144 A user credentials file or tuple of files. 

145 nkeys_seed: 

146 Path-like object containing nkeys seed that will be used. 

147 nkeys_seed_str: 

148 Nkeys seed to be used. 

149 inbox_prefix: 

150 Prefix for generating unique inboxes, subjects with that prefix and NUID.ß 

151 pending_size: 

152 Max size of the pending buffer for publishing commands. 

153 flush_timeout: 

154 Max duration to wait for a forced flush to occur 

155 ws_connection_headers: 

156 WebSockets connection headers. 

157 reconnect_to_server_handler: 

158 Reconnect to server handler. 

159 """ 

160 

161 error_cb: "ErrorCallback | None" 

162 disconnected_cb: "Callback | None" 

163 closed_cb: Callback | None 

164 discovered_server_cb: "Callback | None" 

165 reconnected_cb: "Callback | None" 

166 name: str | None 

167 pedantic: bool 

168 verbose: bool 

169 allow_reconnect: bool 

170 connect_timeout: int 

171 reconnect_time_wait: int 

172 max_reconnect_attempts: int 

173 ping_interval: int 

174 max_outstanding_pings: int 

175 dont_randomize: bool 

176 flusher_queue_size: int 

177 no_echo: bool 

178 tls_hostname: str | None 

179 tls_handshake_first: bool 

180 token: str | None 

181 drain_timeout: int 

182 signature_cb: "SignatureCallback | None" 

183 user_jwt_cb: "JWTCallback | None" 

184 user_credentials: "Credentials | None" 

185 nkeys_seed: str | None 

186 nkeys_seed_str: str | None 

187 inbox_prefix: str | bytes 

188 pending_size: int 

189 flush_timeout: float | None 

190 ws_connection_headers: dict[str, list[str]] | None 

191 reconnect_to_server_handler: ReconnectToServerHandler | None 

192 

193 

194# Server-sent `-ERR` reasons that will never succeed on retry, so the 

195# initial connection attempt should fail fast instead of being silently 

196# retried like a transient error until `max_reconnect_attempts` is hit. 

197UNRECOVERABLE_CONNECT_ERRORS = ( 

198 "authorization violation", 

199 "authorization timeout", 

200 "invalid client protocol", 

201 "maximum payload violation", 

202 "invalid subject", 

203 "stale connection", 

204 "maximum connections exceeded", 

205 "parser error", 

206 "secure connection - tls required", 

207) 

208 

209 

210def _validate_deprecated_security( 

211 deprecated_arguments: Sequence[str], 

212) -> None: 

213 signature_callback_supplied = "signature_cb" in deprecated_arguments 

214 jwt_callback_supplied = "user_jwt_cb" in deprecated_arguments 

215 if signature_callback_supplied != jwt_callback_supplied: 

216 msg = "`user_jwt_cb` and `signature_cb` must be provided together." 

217 raise SetupError(msg) 

218 

219 authentication_mechanisms = [ 

220 name 

221 for name in ( 

222 "token", 

223 "user_credentials", 

224 "nkeys_seed", 

225 "nkeys_seed_str", 

226 ) 

227 if name in deprecated_arguments 

228 ] 

229 if signature_callback_supplied: 

230 authentication_mechanisms.append("JWT callbacks") 

231 

232 if len(authentication_mechanisms) > 1: 

233 mechanisms = ", ".join(authentication_mechanisms) 

234 msg = ( 

235 "Only one deprecated NATS authentication mechanism can be " 

236 f"used at a time, but got: {mechanisms}." 

237 ) 

238 raise SetupError(msg) 

239 

240 

241def _adapt_deprecated_security( 

242 security: BaseSecurity | None, 

243 *, 

244 tls_hostname: str | None, 

245 token: str | None, 

246 signature_cb: Optional["SignatureCallback"], 

247 user_jwt_cb: Optional["JWTCallback"], 

248 user_credentials: Optional["Credentials"], 

249 nkeys_seed: str | None, 

250 nkeys_seed_str: str | None, 

251) -> BaseSecurity | None: 

252 deprecated_arguments = tuple( 

253 name 

254 for name, value in ( 

255 ("tls_hostname", tls_hostname), 

256 ("token", token), 

257 ("user_credentials", user_credentials), 

258 ("nkeys_seed", nkeys_seed), 

259 ("nkeys_seed_str", nkeys_seed_str), 

260 ("signature_cb", signature_cb), 

261 ("user_jwt_cb", user_jwt_cb), 

262 ) 

263 if value is not EMPTY and value is not None 

264 ) 

265 

266 if deprecated_arguments: 

267 warn_deprecated_security_args(*deprecated_arguments) 

268 

269 _validate_deprecated_security(deprecated_arguments) 

270 

271 if security is not None: 

272 use_ssl = security.use_ssl 

273 ssl_context = security.ssl_context 

274 else: 

275 use_ssl = False 

276 ssl_context = None 

277 

278 if isinstance(security, NatsSecurity): 

279 resolved_tls_hostname = security.tls_hostname 

280 tls_handshake_first = security.tls_handshake_first 

281 else: 

282 resolved_tls_hostname = None 

283 tls_handshake_first = False 

284 if tls_hostname is not EMPTY and tls_hostname is not None: 

285 resolved_tls_hostname = tls_hostname 

286 

287 if token is not EMPTY and token is not None: 

288 return NatsToken( 

289 token, 

290 ssl_context=ssl_context, 

291 use_ssl=use_ssl, 

292 tls_hostname=resolved_tls_hostname, 

293 tls_handshake_first=tls_handshake_first, 

294 ) 

295 if user_credentials is not EMPTY and user_credentials is not None: 

296 return NatsCredentials( 

297 user_credentials, 

298 ssl_context=ssl_context, 

299 use_ssl=use_ssl, 

300 tls_hostname=resolved_tls_hostname, 

301 tls_handshake_first=tls_handshake_first, 

302 ) 

303 if nkeys_seed is not EMPTY and nkeys_seed is not None: 

304 return NatsNKey.from_file( 

305 nkeys_seed, 

306 ssl_context=ssl_context, 

307 use_ssl=use_ssl, 

308 tls_hostname=resolved_tls_hostname, 

309 tls_handshake_first=tls_handshake_first, 

310 ) 

311 if nkeys_seed_str is not EMPTY and nkeys_seed_str is not None: 

312 return NatsNKey.from_seed( 

313 nkeys_seed_str, 

314 ssl_context=ssl_context, 

315 use_ssl=use_ssl, 

316 tls_hostname=resolved_tls_hostname, 

317 tls_handshake_first=tls_handshake_first, 

318 ) 

319 if ( 

320 user_jwt_cb is not EMPTY 

321 and user_jwt_cb is not None 

322 and signature_cb is not EMPTY 

323 and signature_cb is not None 

324 ): 

325 return NatsJWT( 

326 user_jwt_cb, 

327 signature_cb, 

328 ssl_context=ssl_context, 

329 use_ssl=use_ssl, 

330 tls_hostname=resolved_tls_hostname, 

331 tls_handshake_first=tls_handshake_first, 

332 ) 

333 return security 

334 

335 

336class NatsBroker( 

337 NatsRegistrator, 

338 BrokerUsecase[Msg, Client, NatsBrokerConfig], 

339): 

340 """A class to represent a NATS broker.""" 

341 

342 url: list[str] 

343 

344 def __init__( 

345 self, 

346 servers: str | Iterable[str] = ("nats://localhost:4222",), 

347 *, 

348 error_cb: Optional["ErrorCallback"] = None, 

349 disconnected_cb: Optional["Callback"] = None, 

350 closed_cb: Optional["Callback"] = None, 

351 discovered_server_cb: Optional["Callback"] = None, 

352 reconnected_cb: Optional["Callback"] = None, 

353 name: str | None = SERVICE_NAME, 

354 pedantic: bool = False, 

355 verbose: bool = False, 

356 allow_reconnect: bool = True, 

357 connect_timeout: int = DEFAULT_CONNECT_TIMEOUT, 

358 reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT, 

359 max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS, 

360 ping_interval: int = DEFAULT_PING_INTERVAL, 

361 max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS, 

362 dont_randomize: bool = False, 

363 flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE, 

364 no_echo: bool = False, 

365 tls_hostname: Annotated[ 

366 str | None, 

367 deprecated( 

368 "Use `security=NatsSecurity(...)` instead. " 

369 "This argument will be removed in 1.0.0." 

370 ), 

371 ] = EMPTY, 

372 token: Annotated[ 

373 str | None, 

374 deprecated( 

375 "Use `security=NatsToken(...)` instead. " 

376 "This argument will be removed in 1.0.0." 

377 ), 

378 ] = EMPTY, 

379 drain_timeout: int = DEFAULT_DRAIN_TIMEOUT, 

380 signature_cb: Annotated[ 

381 Optional["SignatureCallback"], 

382 deprecated( 

383 "Use `security=NatsJWT(...)` instead. " 

384 "This argument will be removed in 1.0.0." 

385 ), 

386 ] = EMPTY, 

387 user_jwt_cb: Annotated[ 

388 Optional["JWTCallback"], 

389 deprecated( 

390 "Use `security=NatsJWT(...)` instead. " 

391 "This argument will be removed in 1.0.0." 

392 ), 

393 ] = EMPTY, 

394 user_credentials: Annotated[ 

395 Optional["Credentials"], 

396 deprecated( 

397 "Use `security=NatsCredentials(...)` instead. " 

398 "This argument will be removed in 1.0.0." 

399 ), 

400 ] = EMPTY, 

401 nkeys_seed: Annotated[ 

402 str | None, 

403 deprecated( 

404 "Use `security=NatsNKey.from_file(...)` instead. " 

405 "This argument will be removed in 1.0.0." 

406 ), 

407 ] = EMPTY, 

408 nkeys_seed_str: Annotated[ 

409 str | None, 

410 deprecated( 

411 "Use `security=NatsNKey.from_seed(...)` instead. " 

412 "This argument will be removed in 1.0.0." 

413 ), 

414 ] = EMPTY, 

415 inbox_prefix: str | bytes = DEFAULT_INBOX_PREFIX, 

416 pending_size: int = DEFAULT_PENDING_SIZE, 

417 flush_timeout: float | None = None, 

418 ws_connection_headers: dict[str, list[str]] | None = None, 

419 reconnect_to_server_handler: ReconnectToServerHandler | None = None, 

420 js_options: Union["JsInitOptions", dict[str, Any], None] = None, 

421 graceful_timeout: float | None = 15.0, 

422 ack_policy: AckPolicy = EMPTY, 

423 id_generator: IdGenerator = gen_cor_id, 

424 decoder: Optional["CustomCallable"] = None, 

425 codec: Optional["CodecProto"] = None, 

426 parser: Optional["CustomCallable"] = None, 

427 dependencies: Sequence["Dependant"] = (), 

428 middlewares: Sequence["BrokerMiddleware[Any, Any]"] = (), 

429 routers: Iterable[NatsRegistrator] = (), 

430 security: Optional["BaseSecurity"] = None, 

431 specification_url: str | Iterable[str] | None = None, 

432 protocol: str | None = "nats", 

433 protocol_version: str | None = "custom", 

434 description: str | None = None, 

435 tags: Iterable[Union["Tag", "TagDict"]] = (), 

436 logger: Optional["LoggerProto"] = EMPTY, 

437 log_level: int = logging.INFO, 

438 apply_types: bool = True, 

439 serializer: Optional["SerializerProto"] = EMPTY, 

440 provider: Optional["Provider"] = None, 

441 context: Optional["ContextRepo"] = None, 

442 underlying_driver_annotations: "UnderlyingDriverAnnotations | None" = None, 

443 ) -> None: 

444 """Initialize the NatsBroker object. 

445 

446 Args: 

447 servers: 

448 NATS cluster addresses to connect. 

449 error_cb: 

450 Callback to report errors. 

451 disconnected_cb: 

452 Callback to report disconnection from NATS. 

453 closed_cb: 

454 Callback to report when client stops reconnection to NATS. 

455 discovered_server_cb: 

456 A callback to report when a new server joins the cluster. 

457 reconnected_cb: 

458 Callback to report success reconnection. 

459 name: 

460 Label the connection with name (shown in NATS monitoring). 

461 pedantic: 

462 Turn on NATS server pedantic mode that performs extra checks on the protocol. 

463 https://docs.nats.io/using-nats/developer/connecting/misc#turn-on-pedantic-mode 

464 verbose: 

465 Verbose mode produce more feedback about code execution. 

466 allow_reconnect: 

467 Whether recover connection automatically or not. 

468 connect_timeout: 

469 Timeout in seconds to establish connection with NATS server. 

470 reconnect_time_wait: 

471 Time in seconds to wait for reestablish connection to NATS server 

472 max_reconnect_attempts: 

473 Maximum attempts number to reconnect to NATS server. 

474 ping_interval: 

475 Interval in seconds to ping. 

476 max_outstanding_pings: 

477 Maximum number of failed pings 

478 dont_randomize: 

479 Boolean indicating should client randomly shuffle servers list for reconnection randomness. 

480 flusher_queue_size: 

481 Max count of commands awaiting to be flushed to the socket 

482 no_echo: 

483 Boolean indicating should commands be echoed. 

484 tls_hostname: 

485 Hostname for TLS. 

486 token: 

487 Auth token for NATS auth. 

488 drain_timeout: 

489 Timeout in seconds to drain subscriptions. 

490 signature_cb: 

491 A callback used to sign a nonce from the server while authenticating with nkeys. 

492 The user should sign the nonce and return the base64 encoded signature. 

493 user_jwt_cb: 

494 A callback used to fetch and return the account signed JWT for this user. 

495 user_credentials: 

496 A user credentials file or tuple of files. 

497 nkeys_seed: 

498 Path-like object containing nkeys seed that will be used. 

499 nkeys_seed_str: 

500 Nkeys seed to be used. 

501 inbox_prefix: 

502 Prefix for generating unique inboxes, subjects with that prefix and NUID.ß 

503 pending_size: 

504 Max size of the pending buffer for publishing commands. 

505 flush_timeout: 

506 Max duration to wait for a forced flush to occur. 

507 ws_connection_headers: 

508 WebSockets connection headers. 

509 reconnect_to_server_handler: 

510 Reconnect to server handler. 

511 js_options: 

512 JetStream initialization options. 

513 graceful_timeout: 

514 Graceful shutdown timeout. Broker waits for all running subscribers completion before shut down. 

515 ack_policy: 

516 Default acknowledgement policy for all subscribers. Individual subscribers can override. 

517 id_generator: 

518 Factory used to generate `correlation_id` when a publish/request call doesn't set one explicitly. 

519 Defaults to `gen_cor_id` (uuid4-based). 

520 decoder: 

521 Custom decoder object. 

522 codec: 

523 Custom codec object. 

524 parser: 

525 Custom parser object. 

526 dependencies: 

527 Dependencies to apply to all broker subscribers. 

528 middlewares: 

529 "Middlewares to apply to all broker publishers/subscribers. 

530 routers: 

531 "Routers to apply to broker. 

532 security: 

533 Security options to connect broker and generate AsyncAPI server security information. 

534 specification_url: 

535 AsyncAPI hardcoded server addresses. Use `servers` if not specified. 

536 protocol: 

537 AsyncAPI server protocol. 

538 protocol_version: 

539 AsyncAPI server protocol version. 

540 description: 

541 AsyncAPI server description. 

542 tags: 

543 AsyncAPI server tags. 

544 logger: 

545 User specified logger to pass into Context and log service messages. 

546 log_level: 

547 Service messages log level. 

548 apply_types: 

549 Whether to use FastDepends or not. 

550 serializer: 

551 FastDepends-compatible serializer to validate incoming messages. 

552 provider: 

553 Provider for FastDepends. 

554 context: 

555 Context for FastDepends. 

556 underlying_driver_annotations: Extra driver type hints that 

557 FastStream cannot inject, mapped to the annotation to use 

558 instead. Merged over the broker's own rows. Wrap a value in 

559 `UnderlyingDriverAnnotation` to name the import to suggest. 

560 """ 

561 servers = [servers] if isinstance(servers, str) else list(servers) 

562 

563 security = _adapt_deprecated_security( 

564 security, 

565 tls_hostname=tls_hostname, 

566 token=token, 

567 signature_cb=signature_cb, 

568 user_jwt_cb=user_jwt_cb, 

569 user_credentials=user_credentials, 

570 nkeys_seed=nkeys_seed, 

571 nkeys_seed_str=nkeys_seed_str, 

572 ) 

573 

574 parsed_servers = [ 

575 urlparse(server if "://" in server else f"//{server}") for server in servers 

576 ] 

577 

578 if ( 

579 security is not None 

580 and type(security) 

581 not in { 

582 BaseSecurity, 

583 NatsSecurity, 

584 } 

585 and any(parsed.username is not None for parsed in parsed_servers) 

586 ): 

587 msg = "URL credentials conflict with `security`." 

588 raise SetupError(msg) 

589 

590 secure_kwargs = parse_security(security) 

591 if tls_hostname is not EMPTY and tls_hostname is not None: 

592 secure_kwargs["tls_hostname"] = tls_hostname 

593 

594 if specification_url is not None: 

595 if isinstance(specification_url, str): 

596 specification_url = [specification_url] 

597 else: 

598 specification_url = list(specification_url) 

599 else: 

600 specification_url = [ 

601 server.replace(parsed.netloc, parsed.netloc.rpartition("@")[-1], 1) 

602 for server, parsed in zip(servers, parsed_servers, strict=True) 

603 ] 

604 

605 js_producer = NatsJSFastProducer( 

606 parser=parser, 

607 decoder=decoder, 

608 ) 

609 

610 producer = NatsFastProducerImpl( 

611 parser=parser, 

612 decoder=decoder, 

613 ) 

614 

615 super().__init__( 

616 # NATS options 

617 servers=servers, 

618 name=name, 

619 verbose=verbose, 

620 allow_reconnect=allow_reconnect, 

621 reconnect_time_wait=reconnect_time_wait, 

622 max_reconnect_attempts=max_reconnect_attempts, 

623 no_echo=no_echo, 

624 pedantic=pedantic, 

625 inbox_prefix=inbox_prefix, 

626 pending_size=pending_size, 

627 connect_timeout=connect_timeout, 

628 drain_timeout=drain_timeout, 

629 flush_timeout=flush_timeout, 

630 ping_interval=ping_interval, 

631 max_outstanding_pings=max_outstanding_pings, 

632 dont_randomize=dont_randomize, 

633 flusher_queue_size=flusher_queue_size, 

634 ws_connection_headers=ws_connection_headers, 

635 # security 

636 **secure_kwargs, 

637 # callbacks 

638 error_cb=self._log_connection_broken(error_cb), 

639 reconnected_cb=self._log_reconnected(reconnected_cb), 

640 disconnected_cb=disconnected_cb, 

641 closed_cb=closed_cb, 

642 discovered_server_cb=discovered_server_cb, 

643 reconnect_to_server_handler=reconnect_to_server_handler, 

644 # Basic args 

645 routers=routers, 

646 config=NatsBrokerConfig( 

647 producer=producer, 

648 js_producer=js_producer, 

649 js_options=js_options or {}, 

650 # both args 

651 broker_middlewares=middlewares, 

652 broker_parser=parser, 

653 broker_decoder=decoder, 

654 broker_codec=codec, 

655 logger=make_nats_logger_state( 

656 logger=logger, 

657 log_level=log_level, 

658 ), 

659 fd_config=FastDependsConfig( 

660 use_fastdepends=apply_types, 

661 serializer=serializer, 

662 provider=provider or dependency_provider, 

663 context=context or ContextRepo(), 

664 ), 

665 # subscriber args 

666 broker_dependencies=dependencies, 

667 graceful_timeout=graceful_timeout, 

668 ack_policy=ack_policy, 

669 id_generator=id_generator, 

670 extra_context={ 

671 "broker": self, 

672 }, 

673 underlying_driver_annotations=underlying_driver_annotations or {}, 

674 ), 

675 specification=BrokerSpec( 

676 description=description, 

677 url=specification_url, 

678 protocol=protocol, 

679 protocol_version=protocol_version, 

680 security=security, 

681 tags=tags, 

682 ), 

683 ) 

684 

685 async def _connect(self) -> "Client": 

686 connection = await nats.connect(**self._connection_kwargs) 

687 self.config.connect(connection) 

688 return connection 

689 

690 async def stop( 

691 self, 

692 exc_type: type[BaseException] | None = None, 

693 exc_val: BaseException | None = None, 

694 exc_tb: Optional["TracebackType"] = None, 

695 ) -> None: 

696 await super().stop(exc_type, exc_val, exc_tb) 

697 

698 if self._connection is not None: 

699 await self._connection.drain() 

700 self._connection = None 

701 

702 self.config.disconnect() 

703 

704 async def start(self) -> None: 

705 """Connect broker to NATS cluster and startup all subscribers.""" 

706 await self.connect() 

707 

708 stream_context = self.config.connection_state.stream 

709 

710 for stream, subjects in filter( 

711 lambda x: x[0].declare, 

712 self._stream_builder.objects.values(), 

713 ): 

714 try: 

715 await stream_context.add_stream( 

716 config=stream.config, 

717 subjects=list(subjects), 

718 ) 

719 

720 except BadRequestError as e: # ruff: ignore[try-except-in-loop] 

721 self._setup_logger() 

722 

723 log_context = LogicSubscriber.build_log_context( 

724 message=None, 

725 subject="", 

726 queue="", 

727 stream=stream.name, 

728 ) 

729 

730 logger_state = self.config.logger 

731 

732 if ( 

733 e.description 

734 == "stream name already in use with a different configuration" 

735 ): 

736 old_config = (await stream_context.stream_info(stream.name)).config 

737 

738 logger_state.log(str(e), logging.WARNING, log_context) 

739 

740 for subject in old_config.subjects or (): 

741 subjects.append(subject) 

742 

743 stream.config.subjects = list(subjects) 

744 await stream_context.update_stream(config=stream.config) 

745 

746 else: # pragma: no cover 

747 logger_state.log( 

748 str(e), 

749 logging.ERROR, 

750 log_context, 

751 exc_info=e, 

752 ) 

753 

754 finally: 

755 # prevent from double declaration 

756 stream.declare = False 

757 

758 await super().start() 

759 

760 @overload 

761 async def publish( 

762 self, 

763 message: "SendableMessage", 

764 subject: str, 

765 headers: dict[str, str] | None = None, 

766 reply_to: str = "", 

767 correlation_id: str | None = None, 

768 stream: None = None, 

769 timeout: float | None = None, 

770 schedule: Optional["Schedule"] = None, 

771 ) -> None: ... 

772 

773 @overload 

774 async def publish( 

775 self, 

776 message: "SendableMessage", 

777 subject: str, 

778 headers: dict[str, str] | None = None, 

779 reply_to: str = "", 

780 correlation_id: str | None = None, 

781 stream: str | None = None, 

782 timeout: float | None = None, 

783 schedule: Optional["Schedule"] = None, 

784 ) -> "PubAck": ... 

785 

786 @override 

787 async def publish( 

788 self, 

789 message: "SendableMessage", 

790 subject: str, 

791 headers: dict[str, str] | None = None, 

792 reply_to: str = "", 

793 correlation_id: str | None = None, 

794 stream: str | None = None, 

795 timeout: float | None = None, 

796 schedule: Optional["Schedule"] = None, 

797 ) -> Optional["PubAck"]: 

798 """Publish message directly. 

799 

800 This method allows you to publish message in not AsyncAPI-documented way. You can use it in another frameworks 

801 applications or to publish messages from time to time. 

802 

803 Please, use `@broker.publisher(...)` or `broker.publisher(...).publish(...)` instead in a regular way. 

804 

805 Args: 

806 message: 

807 Message body to send. 

808 Can be any encodable object (native python types or `pydantic.BaseModel`). 

809 subject: 

810 NATS subject to send message. 

811 headers: 

812 Message headers to store metainformation. 

813 **content-type** and **correlation_id** will be set automatically by framework anyway. 

814 reply_to: 

815 NATS subject name to send response. 

816 correlation_id: 

817 Manual message **correlation_id** setter. 

818 **correlation_id** is a useful option to trace messages. 

819 stream: 

820 This option validates that the target subject is in presented stream. 

821 Can be omitted without any effect if you doesn't want PubAck frame. 

822 timeout: 

823 Timeout to send message to NATS. 

824 schedule: 

825 Schedule to publish message at a specific time. 

826 

827 Returns: 

828 `None` if you publishes a regular message. 

829 `faststream.nats.PubAck` if you publishes a message to stream. 

830 """ 

831 cmd = NatsPublishCommand( 

832 message=message, 

833 correlation_id=correlation_id or self.config.id_generator(), 

834 subject=subject, 

835 headers=headers, 

836 reply_to=reply_to, 

837 stream=stream, 

838 timeout=timeout or 0.5, 

839 _publish_type=PublishType.PUBLISH, 

840 schedule=schedule, 

841 ) 

842 

843 result: PubAck | None 

844 if stream: 

845 result = await super()._basic_publish(cmd, producer=self.config.js_producer) 

846 else: 

847 result = await super()._basic_publish(cmd, producer=self.config.producer) 

848 return result 

849 

850 @override 

851 async def request( # type: ignore[override] 

852 self, 

853 message: "SendableMessage", 

854 subject: str, 

855 headers: dict[str, str] | None = None, 

856 correlation_id: str | None = None, 

857 stream: str | None = None, 

858 timeout: float = 0.5, 

859 ) -> "NatsMessage": 

860 """Make a synchronous request to outer subscriber. 

861 

862 If out subscriber listens subject by stream, you should setup the same **stream** explicitly. 

863 Another way you will reseave confirmation frame as a response. 

864 

865 Args: 

866 message: 

867 Message body to send. 

868 Can be any encodable object (native python types or `pydantic.BaseModel`). 

869 subject: 

870 NATS subject to send message. 

871 headers: 

872 Message headers to store metainformation. 

873 **content-type** and **correlation_id** will be set automatically by framework anyway. 

874 correlation_id: 

875 Manual message **correlation_id** setter. 

876 **correlation_id** is a useful option to trace messages. 

877 stream: 

878 JetStream name. This option is required if your target subscriber listens for events using JetStream. 

879 timeout: 

880 Timeout to send message to NATS. 

881 

882 Returns: 

883 `faststream.nats.message.NatsMessage` object as an outer subscriber response. 

884 """ 

885 cmd = NatsPublishCommand( 

886 message=message, 

887 correlation_id=correlation_id or self.config.id_generator(), 

888 subject=subject, 

889 headers=headers, 

890 timeout=timeout, 

891 stream=stream, 

892 _publish_type=PublishType.REQUEST, 

893 ) 

894 

895 producer = self.config.js_producer if stream is not None else self.config.producer 

896 

897 msg: NatsMessage = await super()._basic_request(cmd, producer=producer) 

898 return msg 

899 

900 async def key_value( 

901 self, 

902 bucket: str, 

903 *, 

904 description: str | None = None, 

905 max_value_size: int | None = None, 

906 history: int = 1, 

907 ttl: float | None = None, # in seconds 

908 max_bytes: int | None = None, 

909 storage: Optional["StorageType"] = None, 

910 replicas: int = 1, 

911 placement: Optional["Placement"] = None, 

912 republish: Optional["RePublish"] = None, 

913 direct: bool | None = None, 

914 # custom 

915 declare: bool = True, 

916 ) -> "KeyValue": 

917 kv_declarer = cast("KVBucketDeclarer", self.config.kv_declarer) 

918 return await kv_declarer.create_key_value( 

919 bucket=bucket, 

920 description=description, 

921 max_value_size=max_value_size, 

922 history=history, 

923 ttl=ttl, 

924 max_bytes=max_bytes, 

925 storage=storage, 

926 replicas=replicas, 

927 placement=placement, 

928 republish=republish, 

929 direct=direct, 

930 declare=declare, 

931 ) 

932 

933 async def object_storage( 

934 self, 

935 bucket: str, 

936 *, 

937 description: str | None = None, 

938 ttl: float | None = None, 

939 max_bytes: int | None = None, 

940 storage: Optional["StorageType"] = None, 

941 replicas: int = 1, 

942 placement: Optional["Placement"] = None, 

943 declare: bool = True, 

944 ) -> "ObjectStore": 

945 os_declarer = cast("OSBucketDeclarer", self.config.os_declarer) 

946 return await os_declarer.create_object_store( 

947 bucket=bucket, 

948 description=description, 

949 ttl=ttl, 

950 max_bytes=max_bytes, 

951 storage=storage, 

952 replicas=replicas, 

953 placement=placement, 

954 declare=declare, 

955 ) 

956 

957 def _log_connection_broken( 

958 self, 

959 error_cb: Optional["ErrorCallback"] = None, 

960 ) -> "ErrorCallback": 

961 c = LogicSubscriber.build_log_context(None, "") 

962 

963 async def wrapper(err: Exception) -> None: 

964 if error_cb is not None: 

965 await error_cb(err) 

966 

967 if isinstance(err, Error): 

968 reason = str(err).removeprefix("nats: ").strip("'").lower() 

969 if reason in UNRECOVERABLE_CONNECT_ERRORS: 

970 raise err 

971 

972 if isinstance(err, Error) and self.config.connection_state: 

973 self.config.logger.log( 

974 f"Connection broken with {err!r}", 

975 logging.WARNING, 

976 c, 

977 exc_info=err, 

978 ) 

979 

980 return wrapper 

981 

982 def _log_reconnected( 

983 self, 

984 cb: Optional["Callback"] = None, 

985 ) -> "Callback": 

986 c = LogicSubscriber.build_log_context(None, "") 

987 

988 async def wrapper() -> None: 

989 if cb is not None: 989 ↛ 992line 989 didn't jump to line 992 because the condition on line 989 was always true

990 await cb() 

991 

992 if not self.config.connection_state: 

993 self.config.logger.log("Connection established", logging.INFO, c) 

994 

995 return wrapper 

996 

997 async def new_inbox(self) -> str: 

998 """Return a unique inbox that can be used for NATS requests or subscriptions. 

999 

1000 The inbox prefix can be customised by passing `inbox_prefix` when creating your `NatsBroker`. 

1001 

1002 This method calls `nats.aio.client.Client.new_inbox` [1] under the hood. 

1003 

1004 [1] https://nats-io.github.io/nats.py/modules.html#nats.aio.client.Client.new_inbox 

1005 """ 

1006 return self.connection.new_inbox() 

1007 

1008 @override 

1009 async def ping(self, timeout: float | None) -> bool: 

1010 sleep_time = (timeout or 10) / 10 

1011 

1012 with anyio.move_on_after(timeout) as cancel_scope: 

1013 if self._connection is None: 1013 ↛ 1014line 1013 didn't jump to line 1014 because the condition on line 1013 was never true

1014 return False 

1015 

1016 while True: 

1017 if cancel_scope.cancel_called: 1017 ↛ 1018line 1017 didn't jump to line 1018 because the condition on line 1017 was never true

1018 return False 

1019 

1020 if self._connection.is_connected: 1020 ↛ 1023line 1020 didn't jump to line 1023 because the condition on line 1020 was always true

1021 return True 

1022 

1023 await anyio.sleep(sleep_time) 

1024 

1025 return False 

1026 

1027 @property 

1028 def connection(self) -> "Client": 

1029 return self.config.broker_config.connection_state.connection