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 SystemSchemaUpgradeRequired {
422 owner: String,
423 installed_version: u64,
424 expected_version: u64,
425 },
426 ReadOnly {
431 operation: &'static str,
432 },
433 BranchCommandUnsupported {
434 command: &'static str,
435 context: &'static str,
436 },
437 BranchBusy {
438 resource: &'static str,
439 },
440 BranchEvidenceBudgetExceeded {
441 resource: &'static str,
442 requested: u64,
443 limit: u64,
444 },
445 BranchReclamationBlocked {
448 branch_id: crate::Uuid,
449 catalog_revision: u64,
450 metadata_revision: u64,
451 cause: Box<HawDBError>,
452 },
453}
454
455impl Display for HawDBError {
456 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
457 match self {
458 HawDBError::Parse(message) => write!(f, "parse error: {message}"),
459 HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
460 HawDBError::Storage(message) => write!(f, "storage error: {message}"),
461 HawDBError::Constraint { surface, message }
462 | HawDBError::Schema { surface, message } => {
463 write!(f, "{}: {message}", surface.prefix())
464 }
465 HawDBError::FileDescriptors(error) => Display::fmt(error, f),
466 HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
467 HawDBError::StorageIntegrity(message) => {
468 write!(f, "storage integrity error: {message}")
469 }
470 HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
471 HawDBError::PublishOutcomeUnknown { destination, message } => write!(
472 f,
473 "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
474 destination.display()
475 ),
476 HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
477 HawDBError::SearchProjectionMismatch { message, .. } => {
478 write!(f, "storage error: {message}")
479 }
480 HawDBError::SearchProjectionRebuildRefused {
481 reason, message, ..
482 } => write!(
483 f,
484 "search projection rebuild refused ({}): {message}",
485 reason.as_str()
486 ),
487 HawDBError::SearchProjectionEpochAdvanceRefused {
488 reason, message, ..
489 } => write!(
490 f,
491 "search projection epoch advance refused ({}): {message}",
492 reason.as_str()
493 ),
494 HawDBError::SearchProjectionPrefixBehindSource {
495 complete_through_commit_epoch,
496 source_commit_epoch,
497 } => write!(
498 f,
499 "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"
500 ),
501 HawDBError::SearchProjectionBatchBudgetExceeded {
502 budget,
503 commit_epoch,
504 required_operations,
505 limit,
506 } => match (budget, commit_epoch) {
507 (SearchProjectionBatchBudget::ChangeBatch, Some(commit_epoch)) => write!(
508 f,
509 "storage error: search projection change at commit epoch {commit_epoch} requires {required_operations} operations, exceeding configured per-batch limit {limit}"
510 ),
511 (SearchProjectionBatchBudget::ChangeBatch, None) => write!(
512 f,
513 "storage error: search projection change requires {required_operations} operations, exceeding configured per-batch limit {limit}"
514 ),
515 (SearchProjectionBatchBudget::GraphDelta, _) => write!(
516 f,
517 "storage error: search projection graph delta operation count {required_operations} exceeded configured limit {limit}"
518 ),
519 (SearchProjectionBatchBudget::ProjectionDelta, _) => write!(
520 f,
521 "storage error: incremental projection update operation count {required_operations} exceeded configured limit {limit}"
522 ),
523 },
524 HawDBError::SearchProductionQualificationGraphEpochMismatch {
525 expected_canonical_graph_commit_epoch,
526 opened_graph_commit_epoch,
527 } => write!(
528 f,
529 "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}"
530 ),
531 HawDBError::SearchProductionQualificationRefused { blocker_codes } => write!(
532 f,
533 "storage error: segmented lexical projection is not qualified for the current production release: {}",
534 blocker_codes.join(",")
535 ),
536 HawDBError::SearchProjectionOwnershipMismatch {
537 projection,
538 recorded,
539 requested,
540 } => write!(
541 f,
542 "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
543 projection.display(),
544 recorded.join(", "),
545 requested.join(", ")
546 ),
547 HawDBError::SearchProjectionOwnershipMarkerCorrupt {
548 projection,
549 marker,
550 message,
551 } => write!(
552 f,
553 "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
554 projection.display()
555 ),
556 HawDBError::Execution(message) => write!(f, "execution error: {message}"),
557 HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
558 HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
559 HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
560 f,
561 "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
562 ),
563 HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
564 HawDBError::RuntimeAdmissionRefused(error) => write!(f, "execution error: {error}"),
565 HawDBError::RuntimeIoWaveReservationExceeded {
566 requested_slots,
567 reserved_slots,
568 } => write!(
569 f,
570 "execution error: runtime I/O wave requested {requested_slots} slots, exceeding the {reserved_slots}-slot reservation"
571 ),
572 HawDBError::RuntimeTaskStopped(reason) => {
573 write!(f, "execution error: runtime task stopped: {reason}")
574 }
575 HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
576 f,
577 "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
578 ),
579 HawDBError::TransactionConflict {
580 read_epoch,
581 committed_epoch,
582 key,
583 } => write!(
584 f,
585 "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
586 ),
587 HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
588 HawDBError::AppendSequenceExhausted {
589 table,
590 watermark,
591 requested,
592 } => write!(
593 f,
594 "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
595 ),
596 HawDBError::TransactionReadDependencyRefused { reason } => {
597 write!(f, "transaction read dependency capture refused: {reason}")
598 }
599 HawDBError::CapabilityUnavailable { capability } => {
600 write!(f, "capability unavailable: {}", capability.as_str())
601 }
602 HawDBError::SystemSchemaUpgradeRequired {
603 owner,
604 installed_version,
605 expected_version,
606 } => write!(
607 f,
608 "execution error: system schema {owner} requires upgrade from version {installed_version} to {expected_version} but the database is read-only"
609 ),
610 HawDBError::ReadOnly { operation } => {
611 write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
612 }
613 HawDBError::BranchCommandUnsupported { command, context } => {
614 write!(f, "{command} is unavailable in {context}")
615 }
616 HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
617 HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
618 f,
619 "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
620 ),
621 HawDBError::BranchReclamationBlocked {
622 branch_id,
623 catalog_revision,
624 metadata_revision,
625 cause,
626 } => write!(
627 f,
628 "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
629 ),
630 }
631 }
632}
633
634impl std::error::Error for HawDBError {
635 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
636 match self {
637 Self::FileDescriptors(error) => Some(error),
638 Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
639 Self::ReadBudgetExceeded(error) => Some(error),
640 Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
641 Self::RuntimeAdmissionRefused(error) => Some(error),
642 Self::RuntimeTaskStopped(reason) => Some(reason),
643 Self::TransactionRetryRequired(error) => Some(error.as_ref()),
644 Self::UnsupportedStorageFormat(error) => Some(error),
645 Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
646 _ => None,
647 }
648 }
649}
650
651impl HawDBError {
652 pub fn read_budget_exceeded(
653 resource: ReadBudgetResource,
654 limit: usize,
655 message: impl Into<String>,
656 ) -> Self {
657 Self::ReadBudgetExceeded(ReadBudgetError {
658 resource,
659 limit,
660 message: message.into(),
661 })
662 }
663
664 pub fn relational(
666 kind: RelationalErrorKind,
667 surface: RelationalErrorSurface,
668 message: impl Into<String>,
669 ) -> Self {
670 let message = message.into();
671 match kind {
672 RelationalErrorKind::Constraint => Self::Constraint { surface, message },
673 RelationalErrorKind::Schema => Self::Schema { surface, message },
674 }
675 }
676
677 pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
679 match self {
680 Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
681 Self::Schema { .. } => Some(RelationalErrorKind::Schema),
682 _ => None,
683 }
684 }
685
686 pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
688 match self {
689 Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
690 _ => None,
691 }
692 }
693
694 pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
696 if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
697 return error.clone();
698 }
699 if let Some(error) = find_publish_outcome_unknown(&error) {
703 return error;
704 }
705 if let Some(reason) = find_runtime_task_stop(&error) {
708 return Self::RuntimeTaskStopped(reason);
709 }
710 if let Some(resource) = file_descriptor_error(&error) {
711 Self::FileDescriptors(resource)
712 } else if let Some(resource) = resource::find_resource_budget_error(&error) {
713 Self::from(resource)
714 } else if let Some(error) = storage_format::find_storage_format_error(&error) {
715 Self::UnsupportedStorageFormat(error)
716 } else if let Some(kind) = find_relational_error_kind(&error) {
717 Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
718 } else {
719 Self::Storage(error.to_string())
720 }
721 }
722
723 pub fn from_storage_error_with_context(
727 error: impl std::error::Error + 'static,
728 context: &str,
729 ) -> Self {
730 match Self::from_storage_error(error) {
731 Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
732 Self::Constraint {
733 surface: surface @ RelationalErrorSurface::Storage,
734 message,
735 } => Self::Constraint {
736 surface,
737 message: format!("{context}: {message}"),
738 },
739 Self::Schema {
740 surface: surface @ RelationalErrorSurface::Storage,
741 message,
742 } => Self::Schema {
743 surface,
744 message: format!("{context}: {message}"),
745 },
746 error => error,
747 }
748 }
749
750 pub const fn is_retryable_transaction_conflict(&self) -> bool {
753 matches!(
754 self,
755 Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
756 )
757 }
758
759 pub fn is_graph_change_conflict(&self) -> bool {
763 matches!(
764 self,
765 Self::TransactionConflict { key, .. } if key == GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY
766 )
767 }
768}
769
770pub type Result<T> = std::result::Result<T, HawDBError>;
771
772impl From<crate::RuntimeIoWaveError> for HawDBError {
774 fn from(error: crate::RuntimeIoWaveError) -> Self {
775 match error {
776 crate::RuntimeIoWaveError::Stopped(reason) => Self::RuntimeTaskStopped(reason),
777 crate::RuntimeIoWaveError::ReservationExceeded {
778 requested_slots,
779 reserved_slots,
780 } => Self::RuntimeIoWaveReservationExceeded {
781 requested_slots,
782 reserved_slots,
783 },
784 }
785 }
786}
787
788impl HawDBError {
789 pub fn or_stop(
793 error: &(dyn std::error::Error + 'static),
794 otherwise: impl FnOnce() -> Self,
795 ) -> Self {
796 match find_runtime_task_stop(error) {
797 Some(reason) => Self::RuntimeTaskStopped(reason),
798 None => otherwise(),
799 }
800 }
801
802 pub fn from_execution_error(error: impl std::error::Error + 'static) -> Self {
805 if let Some(reason) = find_runtime_task_stop(&error) {
806 return Self::RuntimeTaskStopped(reason);
807 }
808 match find_runtime_io_wave_reservation(&error) {
809 Some((requested_slots, reserved_slots)) => Self::RuntimeIoWaveReservationExceeded {
810 requested_slots,
811 reserved_slots,
812 },
813 None => Self::Execution(error.to_string()),
814 }
815 }
816}
817
818fn find_publish_outcome_unknown(error: &(dyn std::error::Error + 'static)) -> Option<HawDBError> {
819 let mut current = Some(error);
820 while let Some(error) = current {
821 if let Some(error @ HawDBError::PublishOutcomeUnknown { .. }) =
822 error.downcast_ref::<HawDBError>()
823 {
824 return Some(error.clone());
825 }
826 if let Some(error) = error.downcast_ref::<std::io::Error>()
827 && let Some(inner) = error.get_ref()
828 && let Some(error) = find_publish_outcome_unknown(inner)
829 {
830 return Some(error);
831 }
832 current = error.source();
833 }
834 None
835}
836
837fn find_runtime_io_wave_reservation(
838 error: &(dyn std::error::Error + 'static),
839) -> Option<(usize, usize)> {
840 let mut current = Some(error);
841 while let Some(error) = current {
842 if let Some(crate::RuntimeIoWaveError::ReservationExceeded {
843 requested_slots,
844 reserved_slots,
845 }) = error.downcast_ref::<crate::RuntimeIoWaveError>()
846 {
847 return Some((*requested_slots, *reserved_slots));
848 }
849 if let Some(HawDBError::RuntimeIoWaveReservationExceeded {
850 requested_slots,
851 reserved_slots,
852 }) = error.downcast_ref::<HawDBError>()
853 {
854 return Some((*requested_slots, *reserved_slots));
855 }
856 if let Some(error) = error.downcast_ref::<std::io::Error>()
858 && let Some(inner) = error.get_ref()
859 && let Some(refusal) = find_runtime_io_wave_reservation(inner)
860 {
861 return Some(refusal);
862 }
863 current = error.source();
864 }
865 None
866}
867
868fn find_runtime_task_stop(
870 error: &(dyn std::error::Error + 'static),
871) -> Option<crate::RuntimeCancellationReason> {
872 let mut current = Some(error);
873 while let Some(error) = current {
874 if let Some(reason) = error.downcast_ref::<crate::RuntimeCancellationReason>() {
875 return Some(*reason);
876 }
877 if let Some(HawDBError::RuntimeTaskStopped(reason)) = error.downcast_ref::<HawDBError>() {
878 return Some(*reason);
879 }
880 if let Some(error) = error.downcast_ref::<std::io::Error>()
882 && let Some(inner) = error.get_ref()
883 && let Some(reason) = find_runtime_task_stop(inner)
884 {
885 return Some(reason);
886 }
887 current = error.source();
888 }
889 None
890}
891
892impl From<crate::RuntimeCancellationReason> for HawDBError {
894 fn from(reason: crate::RuntimeCancellationReason) -> Self {
895 Self::RuntimeTaskStopped(reason)
896 }
897}
898
899impl From<ResourceBudgetError> for HawDBError {
900 fn from(error: ResourceBudgetError) -> Self {
901 Self::ResourceBudgetExceeded(Box::new(error))
902 }
903}
904
905impl From<std::io::Error> for HawDBError {
906 fn from(error: std::io::Error) -> Self {
907 Self::from_storage_error(error)
908 }
909}
910
911pub fn file_descriptor_error(
912 error: &(dyn std::error::Error + 'static),
913) -> Option<FileDescriptorError> {
914 let mut current = Some(error);
915 while let Some(error) = current {
916 if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
917 return Some(resource.clone());
918 }
919 if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
920 return Some(resource.clone());
921 }
922 if let Some(error) = error.downcast_ref::<std::io::Error>() {
923 if let Some(code) = error.raw_os_error()
924 && descriptor_os_limit(code)
925 {
926 return Some(FileDescriptorError::OsLimit {
927 requested: 1,
928 os_code: Some(code),
929 soft: None,
930 hard: None,
931 });
932 }
933 if let Some(inner) = error.get_ref()
936 && let Some(resource) = file_descriptor_error(inner)
937 {
938 return Some(resource);
939 }
940 }
941 current = error.source();
942 }
943 None
944}
945
946fn descriptor_os_limit(code: i32) -> bool {
947 #[cfg(unix)]
948 {
949 matches!(code, 23 | 24)
950 }
951 #[cfg(windows)]
952 {
953 code == 4
954 }
955 #[cfg(not(any(unix, windows)))]
956 {
957 let _ = code;
958 false
959 }
960}
961
962#[cfg(test)]
963mod runtime_io_wave_tests {
964 use super::*;
965
966 fn refusal() -> crate::RuntimeIoWaveError {
967 crate::RuntimeIoWaveError::ReservationExceeded {
968 requested_slots: 2,
969 reserved_slots: 1,
970 }
971 }
972
973 #[test]
974 fn reservation_refusal_stays_typed_directly_and_through_io_context() {
975 for error in [
976 HawDBError::from(refusal()),
977 HawDBError::from_execution_error(refusal()),
978 HawDBError::from_execution_error(std::io::Error::other(refusal())),
979 ] {
980 assert!(matches!(
981 error,
982 HawDBError::RuntimeIoWaveReservationExceeded {
983 requested_slots: 2,
984 reserved_slots: 1,
985 }
986 ));
987 }
988 }
989
990 #[test]
991 fn stopped_io_wave_stays_a_task_stop() {
992 assert!(matches!(
993 HawDBError::from_execution_error(crate::RuntimeIoWaveError::Stopped(
994 crate::RuntimeCancellationReason::DeadlineExceeded,
995 )),
996 HawDBError::RuntimeTaskStopped(crate::RuntimeCancellationReason::DeadlineExceeded)
997 ));
998 }
999}