//! The open-or-create sequence every KV bucket module shares. use crate::Error; /// Open `bucket`, creating it with `history: 1` and `description` when it /// does not exist yet. `label` names the bucket in the creation log line. pub(crate) async fn open_or_create( js: &async_nats::jetstream::Context, bucket: &str, label: &str, description: String, ) -> Result { open_or_create_expiring(js, bucket, label, description, None).await } /// [`open_or_create`] with a `max_age`: a key nobody writes for that long goes /// away, for a bucket whose keys come from a publisher that never deletes. The /// age applies to a bucket created here; one that already exists keeps its own. pub(crate) async fn open_or_create_expiring( js: &async_nats::jetstream::Context, bucket: &str, label: &str, description: String, max_age: Option, ) -> Result { match js.get_key_value(bucket).await { Ok(store) => Ok(store), Err(e) => { tracing::info!( bucket, reason = %e, "{label} bucket not available, creating it" ); js.create_key_value(async_nats::jetstream::kv::Config { bucket: bucket.to_owned(), description, history: 1, max_age: max_age.unwrap_or_default(), ..Default::default() }) .await .map_err(|source| Error::CreateBucket { bucket: bucket.to_owned(), source, }) } } }