1use crate::RuntimeCapability;
16use std::fmt::{Display, Formatter};
17
18mod resource;
19pub use resource::{ResourceBudgetError, ResourceBudgetKind, ResourceBudgetScope};
20mod transaction;
21pub use transaction::{
22 TransactionRetryError, TransactionRetryReason, GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY,
23};
24mod storage_format;
25pub use storage_format::{
26 StorageFormatError, APPEND_WAL_FORMAT, LOGICAL_DUMP_FORMAT,
27 RELATIONAL_CHECKPOINT_LAYOUT_FORMAT, RELATIONAL_DURABLE_CODEC_FORMAT,
28 RELATIONAL_ROW_PAGE_FORMAT, RELATIONAL_SCHEMA_FORMAT, SEARCH_PROJECTION_MANIFEST_FORMAT,
29 STORAGE_MANIFEST_FORMAT, WAL_FILE_FORMAT,
30};
31mod admission;
32mod relational;
33mod wal_record;
34pub use admission::RuntimeAdmissionRefusal;
35pub use relational::{find_relational_error_kind, RelationalErrorKind, RelationalErrorSurface};
36pub use wal_record::{WalRecordLimit, WalRecordLimitError};
37
38#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum FileDescriptorError {
43 InvalidBudget {
44 limit: usize,
45 },
46 ConfigurationConflict {
47 configured: usize,
48 requested: usize,
49 },
50 CapacityPolicyConflict {
51 configured: bool,
52 requested: bool,
53 },
54 BudgetExceeded {
55 requested: usize,
56 available: usize,
57 limit: usize,
58 },
59 OsLimit {
60 requested: usize,
61 os_code: Option<i32>,
62 soft: Option<u64>,
63 hard: Option<u64>,
64 },
65}
66
67impl Display for FileDescriptorError {
68 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
69 match self {
70 Self::InvalidBudget { limit } => write!(formatter, "invalid file descriptor budget: {limit}"),
71 Self::ConfigurationConflict { configured, requested } => write!(formatter,
72 "project file descriptor budget conflict: configured {configured}, requested {requested}"),
73 Self::CapacityPolicyConflict { configured, requested } => write!(formatter,
74 "project strict_capacity_limit conflict: configured {configured}, requested {requested}"),
75 Self::BudgetExceeded { requested, available, limit } => write!(formatter,
76 "project file descriptor budget exceeded: requested {requested}, available {available}, limit {limit}"),
77 Self::OsLimit { requested, os_code, soft, hard } => write!(formatter,
78 "operating system file descriptor limit: requested {requested}, soft {soft:?}, hard {hard:?}, OS code {os_code:?}"),
79 }
80 }
81}
82
83impl std::error::Error for FileDescriptorError {}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum ReadBudgetResource {
88 Rows,
89 PayloadBytes,
90}
91
92impl ReadBudgetResource {
93 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::Rows => "result_rows",
96 Self::PayloadBytes => "result_payload_bytes",
97 }
98 }
99
100 pub const fn budget_option(self) -> &'static str {
104 match self {
105 Self::Rows => "max_read_result_rows",
106 Self::PayloadBytes => "max_read_result_payload_bytes",
107 }
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct ReadBudgetError {
114 pub resource: ReadBudgetResource,
115 pub limit: usize,
116 pub message: String,
117}
118
119impl Display for ReadBudgetError {
120 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
121 formatter.write_str(&self.message)
122 }
123}
124
125impl std::error::Error for ReadBudgetError {}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum SearchProjectionRebuildRefusal {
130 TargetExists,
132 TargetParentMissing,
134 TargetInvalid,
136 TargetAppeared,
138 VerificationMismatch,
140}
141
142impl SearchProjectionRebuildRefusal {
143 pub const fn as_str(self) -> &'static str {
144 match self {
145 Self::TargetExists => "target_exists",
146 Self::TargetParentMissing => "target_parent_missing",
147 Self::TargetInvalid => "target_invalid",
148 Self::TargetAppeared => "target_appeared",
149 Self::VerificationMismatch => "verification_mismatch",
150 }
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum SearchProjectionEpochAdvanceRefusal {
159 ProjectionChanged,
162 ChangeLogGap,
165 RangeUnavailable,
168 UncheckpointedChanges,
171}
172
173impl SearchProjectionEpochAdvanceRefusal {
174 pub const fn as_str(self) -> &'static str {
175 match self {
176 Self::ProjectionChanged => "projection_changed",
177 Self::ChangeLogGap => "change_log_gap",
178 Self::RangeUnavailable => "range_unavailable",
179 Self::UncheckpointedChanges => "uncheckpointed_changes",
180 }
181 }
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum SearchProjectionBatchBudget {
187 ChangeBatch,
190 GraphDelta,
192 ProjectionDelta,
196}
197
198impl SearchProjectionBatchBudget {
199 pub const fn as_str(self) -> &'static str {
200 match self {
201 Self::ChangeBatch => "change_batch",
202 Self::GraphDelta => "graph_delta",
203 Self::ProjectionDelta => "projection_delta",
204 }
205 }
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub enum HawDBError {
210 Parse(String),
211 Semantic(String),
212 Storage(String),
213 Constraint {
217 surface: RelationalErrorSurface,
218 message: String,
219 },
220 Schema {
223 surface: RelationalErrorSurface,
224 message: String,
225 },
226 FileDescriptors(FileDescriptorError),
227 StorageIntegrity(String),
228 WalRecoveryIo {
230 operation: &'static str,
231 kind: std::io::ErrorKind,
232 os_code: Option<i32>,
233 message: String,
234 },
235 UnsupportedStorageFormat(StorageFormatError),
236 PublishOutcomeUnknown {
242 destination: std::path::PathBuf,
243 message: String,
244 },
245 ProjectionBusy,
247 SearchProjectionMismatch {
256 projection: Option<std::path::PathBuf>,
257 message: String,
258 },
259 SearchProjectionRebuildRefused {
265 reason: SearchProjectionRebuildRefusal,
266 target: std::path::PathBuf,
267 message: String,
268 },
269 SearchProjectionEpochAdvanceRefused {
274 reason: SearchProjectionEpochAdvanceRefusal,
275 source_graph_commit_epoch: Option<u64>,
276 target_graph_commit_epoch: u64,
277 message: String,
278 },
279 SearchProjectionPrefixBehindSource {
294 complete_through_commit_epoch: u64,
295 source_commit_epoch: u64,
296 },
297 SearchProjectionBatchBudgetExceeded {
306 budget: SearchProjectionBatchBudget,
307 commit_epoch: Option<u64>,
308 required_operations: usize,
309 limit: usize,
310 },
311 SearchProductionQualificationGraphEpochMismatch {
321 expected_canonical_graph_commit_epoch: u64,
322 opened_graph_commit_epoch: u64,
323 },
324 SearchProductionQualificationRefused {
337 blocker_codes: Vec<String>,
338 },
339 SearchProjectionOwnershipMismatch {
345 projection: std::path::PathBuf,
346 recorded: Vec<String>,
347 requested: Vec<String>,
348 },
349 SearchProjectionOwnershipMarkerCorrupt {
356 projection: std::path::PathBuf,
357 marker: String,
358 message: String,
359 },
360 Execution(String),
361 ResourceBudgetExceeded(Box<ResourceBudgetError>),
363 ReadBudgetExceeded(ReadBudgetError),
364 WalRecordLimitExceeded(Box<WalRecordLimitError>),
368 RuntimeAdmissionRefused(RuntimeAdmissionRefusal),
372 RuntimeIoWaveReservationExceeded {
378 requested_slots: usize,
379 reserved_slots: usize,
380 },
381 RuntimeTaskStopped(crate::RuntimeCancellationReason),
386 GraphExpansionCandidateLimitExceeded {
387 requested: usize,
388 limit: usize,
389 },
390 GraphExpansionPayloadLimitExceeded {
391 requested: usize,
392 limit: usize,
393 },
394 TransactionConflict {
395 read_epoch: u64,
396 committed_epoch: u64,
397 key: String,
398 },
399 TransactionRetryRequired(Box<TransactionRetryError>),
401 TransactionReadDependencyRefused {
403 reason: String,
404 },
405 AppendSequenceExhausted {
406 table: String,
407 watermark: i64,
408 requested: usize,
409 },
410 CapabilityUnavailable {
411 capability: RuntimeCapability,
412 },
413 ReadOnly {
418 operation: &'static str,
419 },
420 BranchCommandUnsupported {
421 command: &'static str,
422 context: &'static str,
423 },
424 BranchBusy {
425 resource: &'static str,
426 },
427 BranchEvidenceBudgetExceeded {
428 resource: &'static str,
429 requested: u64,
430 limit: u64,
431 },
432 BranchReclamationBlocked {
435 branch_id: crate::Uuid,
436 catalog_revision: u64,
437 metadata_revision: u64,
438 cause: Box<HawDBError>,
439 },
440}
441
442impl Display for HawDBError {
443 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
444 match self {
445 HawDBError::Parse(message) => write!(f, "parse error: {message}"),
446 HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
447 HawDBError::Storage(message) => write!(f, "storage error: {message}"),
448 HawDBError::Constraint { surface, message }
449 | HawDBError::Schema { surface, message } => {
450 write!(f, "{}: {message}", surface.prefix())
451 }
452 HawDBError::FileDescriptors(error) => Display::fmt(error, f),
453 HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
454 HawDBError::StorageIntegrity(message) => {
455 write!(f, "storage integrity error: {message}")
456 }
457 HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
458 HawDBError::PublishOutcomeUnknown { destination, message } => write!(
459 f,
460 "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
461 destination.display()
462 ),
463 HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
464 HawDBError::SearchProjectionMismatch { message, .. } => {
465 write!(f, "storage error: {message}")
466 }
467 HawDBError::SearchProjectionRebuildRefused {
468 reason, message, ..
469 } => write!(
470 f,
471 "search projection rebuild refused ({}): {message}",
472 reason.as_str()
473 ),
474 HawDBError::SearchProjectionEpochAdvanceRefused {
475 reason, message, ..
476 } => write!(
477 f,
478 "search projection epoch advance refused ({}): {message}",
479 reason.as_str()
480 ),
481 HawDBError::SearchProjectionPrefixBehindSource {
482 complete_through_commit_epoch,
483 source_commit_epoch,
484 } => write!(
485 f,
486 "execution error: search projection complete-through epoch {complete_through_commit_epoch} differs from source snapshot epoch {source_commit_epoch}; prepare the complete source interval before publishing its watermark"
487 ),
488 HawDBError::SearchProjectionBatchBudgetExceeded {
489 budget,
490 commit_epoch,
491 required_operations,
492 limit,
493 } => match (budget, commit_epoch) {
494 (SearchProjectionBatchBudget::ChangeBatch, Some(commit_epoch)) => write!(
495 f,
496 "storage error: search projection change at commit epoch {commit_epoch} requires {required_operations} operations, exceeding configured per-batch limit {limit}"
497 ),
498 (SearchProjectionBatchBudget::ChangeBatch, None) => write!(
499 f,
500 "storage error: search projection change requires {required_operations} operations, exceeding configured per-batch limit {limit}"
501 ),
502 (SearchProjectionBatchBudget::GraphDelta, _) => write!(
503 f,
504 "storage error: search projection graph delta operation count {required_operations} exceeded configured limit {limit}"
505 ),
506 (SearchProjectionBatchBudget::ProjectionDelta, _) => write!(
507 f,
508 "storage error: incremental projection update operation count {required_operations} exceeded configured limit {limit}"
509 ),
510 },
511 HawDBError::SearchProductionQualificationGraphEpochMismatch {
512 expected_canonical_graph_commit_epoch,
513 opened_graph_commit_epoch,
514 } => write!(
515 f,
516 "storage error: qualified out-of-core search expected canonical graph commit epoch {expected_canonical_graph_commit_epoch}, opened graph is at {opened_graph_commit_epoch}"
517 ),
518 HawDBError::SearchProductionQualificationRefused { blocker_codes } => write!(
519 f,
520 "storage error: segmented lexical projection is not qualified for the current production release: {}",
521 blocker_codes.join(",")
522 ),
523 HawDBError::SearchProjectionOwnershipMismatch {
524 projection,
525 recorded,
526 requested,
527 } => write!(
528 f,
529 "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
530 projection.display(),
531 recorded.join(", "),
532 requested.join(", ")
533 ),
534 HawDBError::SearchProjectionOwnershipMarkerCorrupt {
535 projection,
536 marker,
537 message,
538 } => write!(
539 f,
540 "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
541 projection.display()
542 ),
543 HawDBError::Execution(message) => write!(f, "execution error: {message}"),
544 HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
545 HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
546 HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
547 f,
548 "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
549 ),
550 HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
551 HawDBError::RuntimeAdmissionRefused(error) => write!(f, "execution error: {error}"),
552 HawDBError::RuntimeIoWaveReservationExceeded {
553 requested_slots,
554 reserved_slots,
555 } => write!(
556 f,
557 "execution error: runtime I/O wave requested {requested_slots} slots, exceeding the {reserved_slots}-slot reservation"
558 ),
559 HawDBError::RuntimeTaskStopped(reason) => {
560 write!(f, "execution error: runtime task stopped: {reason}")
561 }
562 HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
563 f,
564 "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
565 ),
566 HawDBError::TransactionConflict {
567 read_epoch,
568 committed_epoch,
569 key,
570 } => write!(
571 f,
572 "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
573 ),
574 HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
575 HawDBError::AppendSequenceExhausted {
576 table,
577 watermark,
578 requested,
579 } => write!(
580 f,
581 "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
582 ),
583 HawDBError::TransactionReadDependencyRefused { reason } => {
584 write!(f, "transaction read dependency capture refused: {reason}")
585 }
586 HawDBError::CapabilityUnavailable { capability } => {
587 write!(f, "capability unavailable: {}", capability.as_str())
588 }
589 HawDBError::ReadOnly { operation } => {
590 write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
591 }
592 HawDBError::BranchCommandUnsupported { command, context } => {
593 write!(f, "{command} is unavailable in {context}")
594 }
595 HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
596 HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
597 f,
598 "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
599 ),
600 HawDBError::BranchReclamationBlocked {
601 branch_id,
602 catalog_revision,
603 metadata_revision,
604 cause,
605 } => write!(
606 f,
607 "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
608 ),
609 }
610 }
611}
612
613impl std::error::Error for HawDBError {
614 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
615 match self {
616 Self::FileDescriptors(error) => Some(error),
617 Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
618 Self::ReadBudgetExceeded(error) => Some(error),
619 Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
620 Self::RuntimeAdmissionRefused(error) => Some(error),
621 Self::RuntimeTaskStopped(reason) => Some(reason),
622 Self::TransactionRetryRequired(error) => Some(error.as_ref()),
623 Self::UnsupportedStorageFormat(error) => Some(error),
624 Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
625 _ => None,
626 }
627 }
628}
629
630impl HawDBError {
631 pub fn read_budget_exceeded(
632 resource: ReadBudgetResource,
633 limit: usize,
634 message: impl Into<String>,
635 ) -> Self {
636 Self::ReadBudgetExceeded(ReadBudgetError {
637 resource,
638 limit,
639 message: message.into(),
640 })
641 }
642
643 pub fn relational(
645 kind: RelationalErrorKind,
646 surface: RelationalErrorSurface,
647 message: impl Into<String>,
648 ) -> Self {
649 let message = message.into();
650 match kind {
651 RelationalErrorKind::Constraint => Self::Constraint { surface, message },
652 RelationalErrorKind::Schema => Self::Schema { surface, message },
653 }
654 }
655
656 pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
658 match self {
659 Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
660 Self::Schema { .. } => Some(RelationalErrorKind::Schema),
661 _ => None,
662 }
663 }
664
665 pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
667 match self {
668 Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
669 _ => None,
670 }
671 }
672
673 pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
675 if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
676 return error.clone();
677 }
678 if let Some(error) = find_publish_outcome_unknown(&error) {
682 return error;
683 }
684 if let Some(reason) = find_runtime_task_stop(&error) {
687 return Self::RuntimeTaskStopped(reason);
688 }
689 if let Some(resource) = file_descriptor_error(&error) {
690 Self::FileDescriptors(resource)
691 } else if let Some(resource) = resource::find_resource_budget_error(&error) {
692 Self::from(resource)
693 } else if let Some(error) = storage_format::find_storage_format_error(&error) {
694 Self::UnsupportedStorageFormat(error)
695 } else if let Some(kind) = find_relational_error_kind(&error) {
696 Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
697 } else {
698 Self::Storage(error.to_string())
699 }
700 }
701
702 pub fn from_storage_error_with_context(
706 error: impl std::error::Error + 'static,
707 context: &str,
708 ) -> Self {
709 match Self::from_storage_error(error) {
710 Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
711 Self::Constraint {
712 surface: surface @ RelationalErrorSurface::Storage,
713 message,
714 } => Self::Constraint {
715 surface,
716 message: format!("{context}: {message}"),
717 },
718 Self::Schema {
719 surface: surface @ RelationalErrorSurface::Storage,
720 message,
721 } => Self::Schema {
722 surface,
723 message: format!("{context}: {message}"),
724 },
725 error => error,
726 }
727 }
728
729 pub const fn is_retryable_transaction_conflict(&self) -> bool {
732 matches!(
733 self,
734 Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
735 )
736 }
737
738 pub fn is_graph_change_conflict(&self) -> bool {
742 matches!(
743 self,
744 Self::TransactionConflict { key, .. } if key == GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY
745 )
746 }
747}
748
749pub type Result<T> = std::result::Result<T, HawDBError>;
750
751impl From<crate::RuntimeIoWaveError> for HawDBError {
753 fn from(error: crate::RuntimeIoWaveError) -> Self {
754 match error {
755 crate::RuntimeIoWaveError::Stopped(reason) => Self::RuntimeTaskStopped(reason),
756 crate::RuntimeIoWaveError::ReservationExceeded {
757 requested_slots,
758 reserved_slots,
759 } => Self::RuntimeIoWaveReservationExceeded {
760 requested_slots,
761 reserved_slots,
762 },
763 }
764 }
765}
766
767impl HawDBError {
768 pub fn or_stop(
772 error: &(dyn std::error::Error + 'static),
773 otherwise: impl FnOnce() -> Self,
774 ) -> Self {
775 match find_runtime_task_stop(error) {
776 Some(reason) => Self::RuntimeTaskStopped(reason),
777 None => otherwise(),
778 }
779 }
780
781 pub fn from_execution_error(error: impl std::error::Error + 'static) -> Self {
784 if let Some(reason) = find_runtime_task_stop(&error) {
785 return Self::RuntimeTaskStopped(reason);
786 }
787 match find_runtime_io_wave_reservation(&error) {
788 Some((requested_slots, reserved_slots)) => Self::RuntimeIoWaveReservationExceeded {
789 requested_slots,
790 reserved_slots,
791 },
792 None => Self::Execution(error.to_string()),
793 }
794 }
795}
796
797fn find_publish_outcome_unknown(error: &(dyn std::error::Error + 'static)) -> Option<HawDBError> {
798 let mut current = Some(error);
799 while let Some(error) = current {
800 if let Some(error @ HawDBError::PublishOutcomeUnknown { .. }) =
801 error.downcast_ref::<HawDBError>()
802 {
803 return Some(error.clone());
804 }
805 if let Some(error) = error.downcast_ref::<std::io::Error>()
806 && let Some(inner) = error.get_ref()
807 && let Some(error) = find_publish_outcome_unknown(inner)
808 {
809 return Some(error);
810 }
811 current = error.source();
812 }
813 None
814}
815
816fn find_runtime_io_wave_reservation(
817 error: &(dyn std::error::Error + 'static),
818) -> Option<(usize, usize)> {
819 let mut current = Some(error);
820 while let Some(error) = current {
821 if let Some(crate::RuntimeIoWaveError::ReservationExceeded {
822 requested_slots,
823 reserved_slots,
824 }) = error.downcast_ref::<crate::RuntimeIoWaveError>()
825 {
826 return Some((*requested_slots, *reserved_slots));
827 }
828 if let Some(HawDBError::RuntimeIoWaveReservationExceeded {
829 requested_slots,
830 reserved_slots,
831 }) = error.downcast_ref::<HawDBError>()
832 {
833 return Some((*requested_slots, *reserved_slots));
834 }
835 if let Some(error) = error.downcast_ref::<std::io::Error>()
837 && let Some(inner) = error.get_ref()
838 && let Some(refusal) = find_runtime_io_wave_reservation(inner)
839 {
840 return Some(refusal);
841 }
842 current = error.source();
843 }
844 None
845}
846
847fn find_runtime_task_stop(
849 error: &(dyn std::error::Error + 'static),
850) -> Option<crate::RuntimeCancellationReason> {
851 let mut current = Some(error);
852 while let Some(error) = current {
853 if let Some(reason) = error.downcast_ref::<crate::RuntimeCancellationReason>() {
854 return Some(*reason);
855 }
856 if let Some(HawDBError::RuntimeTaskStopped(reason)) = error.downcast_ref::<HawDBError>() {
857 return Some(*reason);
858 }
859 if let Some(error) = error.downcast_ref::<std::io::Error>()
861 && let Some(inner) = error.get_ref()
862 && let Some(reason) = find_runtime_task_stop(inner)
863 {
864 return Some(reason);
865 }
866 current = error.source();
867 }
868 None
869}
870
871impl From<crate::RuntimeCancellationReason> for HawDBError {
873 fn from(reason: crate::RuntimeCancellationReason) -> Self {
874 Self::RuntimeTaskStopped(reason)
875 }
876}
877
878impl From<ResourceBudgetError> for HawDBError {
879 fn from(error: ResourceBudgetError) -> Self {
880 Self::ResourceBudgetExceeded(Box::new(error))
881 }
882}
883
884impl From<std::io::Error> for HawDBError {
885 fn from(error: std::io::Error) -> Self {
886 Self::from_storage_error(error)
887 }
888}
889
890pub fn file_descriptor_error(
891 error: &(dyn std::error::Error + 'static),
892) -> Option<FileDescriptorError> {
893 let mut current = Some(error);
894 while let Some(error) = current {
895 if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
896 return Some(resource.clone());
897 }
898 if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
899 return Some(resource.clone());
900 }
901 if let Some(error) = error.downcast_ref::<std::io::Error>() {
902 if let Some(code) = error.raw_os_error()
903 && descriptor_os_limit(code)
904 {
905 return Some(FileDescriptorError::OsLimit {
906 requested: 1,
907 os_code: Some(code),
908 soft: None,
909 hard: None,
910 });
911 }
912 if let Some(inner) = error.get_ref()
915 && let Some(resource) = file_descriptor_error(inner)
916 {
917 return Some(resource);
918 }
919 }
920 current = error.source();
921 }
922 None
923}
924
925fn descriptor_os_limit(code: i32) -> bool {
926 #[cfg(unix)]
927 {
928 matches!(code, 23 | 24)
929 }
930 #[cfg(windows)]
931 {
932 code == 4
933 }
934 #[cfg(not(any(unix, windows)))]
935 {
936 let _ = code;
937 false
938 }
939}
940
941#[cfg(test)]
942mod runtime_io_wave_tests {
943 use super::*;
944
945 fn refusal() -> crate::RuntimeIoWaveError {
946 crate::RuntimeIoWaveError::ReservationExceeded {
947 requested_slots: 2,
948 reserved_slots: 1,
949 }
950 }
951
952 #[test]
953 fn reservation_refusal_stays_typed_directly_and_through_io_context() {
954 for error in [
955 HawDBError::from(refusal()),
956 HawDBError::from_execution_error(refusal()),
957 HawDBError::from_execution_error(std::io::Error::other(refusal())),
958 ] {
959 assert!(matches!(
960 error,
961 HawDBError::RuntimeIoWaveReservationExceeded {
962 requested_slots: 2,
963 reserved_slots: 1,
964 }
965 ));
966 }
967 }
968
969 #[test]
970 fn stopped_io_wave_stays_a_task_stop() {
971 assert!(matches!(
972 HawDBError::from_execution_error(crate::RuntimeIoWaveError::Stopped(
973 crate::RuntimeCancellationReason::DeadlineExceeded,
974 )),
975 HawDBError::RuntimeTaskStopped(crate::RuntimeCancellationReason::DeadlineExceeded)
976 ));
977 }
978}