Skip to main content

mz_storage_types/connections/
string_or_secret.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::sync::Arc;
11
12use mz_ore::future::InTask;
13use mz_repr::CatalogItemId;
14use mz_secrets::SecretsReader;
15use proptest_derive::Arbitrary;
16use serde::{Deserialize, Serialize};
17
18use crate::connections::SecretsReaderExt;
19
20#[derive(Arbitrary, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
21pub enum StringOrSecret {
22    String(String),
23    Secret(CatalogItemId),
24}
25
26impl StringOrSecret {
27    /// Gets the value as a string, reading the secret if necessary.
28    pub async fn get_string(
29        &self,
30        in_task: InTask,
31        secrets_reader: &Arc<dyn SecretsReader>,
32    ) -> anyhow::Result<String> {
33        match self {
34            StringOrSecret::String(s) => Ok(s.clone()),
35            StringOrSecret::Secret(id) => secrets_reader.read_string_in_task_if(in_task, *id).await,
36        }
37    }
38
39    /// Asserts that this string or secret is a string and returns its contents.
40    pub fn unwrap_string(&self) -> &str {
41        match self {
42            StringOrSecret::String(s) => s,
43            StringOrSecret::Secret(_) => panic!("StringOrSecret::unwrap_string called on a secret"),
44        }
45    }
46
47    /// Asserts that this string or secret is a secret and returns its global
48    /// ID.
49    pub fn unwrap_secret(&self) -> CatalogItemId {
50        match self {
51            StringOrSecret::String(_) => panic!("StringOrSecret::unwrap_secret called on a string"),
52            StringOrSecret::Secret(id) => *id,
53        }
54    }
55}
56
57impl<V: std::fmt::Display> From<V> for StringOrSecret {
58    fn from(v: V) -> StringOrSecret {
59        StringOrSecret::String(format!("{}", v))
60    }
61}