|
| 1 | +use std::{fmt, str::FromStr, sync::Arc}; |
| 2 | + |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | +use si_data_nats::{async_nats::jetstream, NatsClient}; |
| 5 | +use strum::EnumDiscriminants; |
| 6 | +use ulid::{Ulid, ULID_LEN}; |
| 7 | + |
| 8 | +use crate::{ |
| 9 | + error::LayerDbResult, |
| 10 | + event::LayeredEventMetadata, |
| 11 | + nats::{self, subject}, |
| 12 | +}; |
| 13 | + |
| 14 | +use self::rebase::{RebaseFinished, RebaseRequest}; |
| 15 | + |
| 16 | +pub mod rebase; |
| 17 | + |
| 18 | +#[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] |
| 19 | +pub struct ActivityId(Ulid); |
| 20 | + |
| 21 | +impl ActivityId { |
| 22 | + pub fn new() -> ActivityId { |
| 23 | + ActivityId(Ulid::new()) |
| 24 | + } |
| 25 | + |
| 26 | + pub fn array_to_str<'buf>(&self, buf: &'buf mut [u8; ULID_LEN]) -> &'buf mut str { |
| 27 | + self.0.array_to_str(buf) |
| 28 | + } |
| 29 | + |
| 30 | + pub fn into_inner(self) -> Ulid { |
| 31 | + self.0 |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl Default for ActivityId { |
| 36 | + fn default() -> Self { |
| 37 | + Self::new() |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +impl FromStr for ActivityId { |
| 42 | + type Err = ulid::DecodeError; |
| 43 | + |
| 44 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 45 | + Ok(Self(Ulid::from_str(s)?)) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl From<ulid::Ulid> for ActivityId { |
| 50 | + fn from(value: ulid::Ulid) -> Self { |
| 51 | + Self(value) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl fmt::Display for ActivityId { |
| 56 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 57 | + self.0.fmt(f) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] |
| 62 | +pub struct Activity { |
| 63 | + pub id: ActivityId, |
| 64 | + pub payload: ActivityPayload, |
| 65 | + pub metadata: LayeredEventMetadata, |
| 66 | +} |
| 67 | + |
| 68 | +impl Activity { |
| 69 | + pub fn new(payload: ActivityPayload, metadata: LayeredEventMetadata) -> Activity { |
| 70 | + Activity { |
| 71 | + id: ActivityId::new(), |
| 72 | + payload, |
| 73 | + metadata, |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + pub fn rebase(request: RebaseRequest, metadata: LayeredEventMetadata) -> Activity { |
| 78 | + Activity::new(ActivityPayload::RebaseRequest(request), metadata) |
| 79 | + } |
| 80 | + |
| 81 | + pub fn rebase_finished(request: RebaseFinished, metadata: LayeredEventMetadata) -> Activity { |
| 82 | + Activity::new(ActivityPayload::RebaseFinished(request), metadata) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +#[derive(Debug, Serialize, Deserialize, Clone, EnumDiscriminants, PartialEq, Eq)] |
| 87 | +pub enum ActivityPayload { |
| 88 | + RebaseRequest(RebaseRequest), |
| 89 | + RebaseFinished(RebaseFinished), |
| 90 | +} |
| 91 | + |
| 92 | +impl ActivityPayload { |
| 93 | + pub fn to_subject(&self) -> String { |
| 94 | + let discriminate: ActivityPayloadDiscriminants = self.into(); |
| 95 | + discriminate.to_subject() |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +impl ActivityPayloadDiscriminants { |
| 100 | + pub fn to_subject(&self) -> String { |
| 101 | + match self { |
| 102 | + ActivityPayloadDiscriminants::RebaseRequest => "rebase.request".to_string(), |
| 103 | + ActivityPayloadDiscriminants::RebaseFinished => "rebase.finished".to_string(), |
| 104 | + } |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[derive(Debug, Clone)] |
| 109 | +pub struct ActivityPublisher { |
| 110 | + prefix: Option<Arc<str>>, |
| 111 | + context: jetstream::context::Context, |
| 112 | +} |
| 113 | + |
| 114 | +impl ActivityPublisher { |
| 115 | + pub fn new(nats_client: &NatsClient) -> ActivityPublisher { |
| 116 | + let prefix = nats_client.metadata().subject_prefix().map(|s| s.into()); |
| 117 | + let context = jetstream::new(nats_client.as_inner().clone()); |
| 118 | + ActivityPublisher { context, prefix } |
| 119 | + } |
| 120 | + |
| 121 | + pub fn prefix(&self) -> Option<&str> { |
| 122 | + self.prefix.as_deref() |
| 123 | + } |
| 124 | + |
| 125 | + pub fn publish(&self, activity: &Activity) -> LayerDbResult<()> { |
| 126 | + let nats_subject = subject::for_activity(self.prefix(), activity); |
| 127 | + let nats = self.context.clone(); |
| 128 | + let nats_payload = postcard::to_stdvec(&activity)?; |
| 129 | + let _nats_join = |
| 130 | + tokio::spawn(async move { nats.publish(nats_subject, nats_payload.into()).await }); |
| 131 | + Ok(()) |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +#[allow(dead_code)] |
| 136 | +pub struct ActivitySubscriber { |
| 137 | + instance_id: Ulid, |
| 138 | + messages: jetstream::consumer::pull::Stream, |
| 139 | +} |
| 140 | + |
| 141 | +impl ActivitySubscriber { |
| 142 | + pub async fn new( |
| 143 | + instance_id: Ulid, |
| 144 | + nats_client: &NatsClient, |
| 145 | + to_receive: Option<Vec<ActivityPayloadDiscriminants>>, |
| 146 | + ) -> LayerDbResult<ActivitySubscriber> { |
| 147 | + let context = jetstream::new(nats_client.as_inner().clone()); |
| 148 | + |
| 149 | + let activities = |
| 150 | + nats::layerdb_activities_stream(&context, nats_client.metadata().subject_prefix()) |
| 151 | + .await? |
| 152 | + .create_consumer(Self::consumer_config( |
| 153 | + nats_client.metadata().subject_prefix(), |
| 154 | + instance_id, |
| 155 | + to_receive, |
| 156 | + )) |
| 157 | + .await? |
| 158 | + .messages() |
| 159 | + .await?; |
| 160 | + |
| 161 | + Ok(ActivitySubscriber { |
| 162 | + instance_id, |
| 163 | + messages: activities, |
| 164 | + }) |
| 165 | + } |
| 166 | + |
| 167 | + pub fn messages(&mut self) -> &mut jetstream::consumer::pull::Stream { |
| 168 | + &mut self.messages |
| 169 | + } |
| 170 | + |
| 171 | + #[inline] |
| 172 | + fn consumer_config( |
| 173 | + prefix: Option<&str>, |
| 174 | + instance_id: Ulid, |
| 175 | + to_receive: Option<Vec<ActivityPayloadDiscriminants>>, |
| 176 | + ) -> jetstream::consumer::pull::Config { |
| 177 | + let name = format!("activity-stream-{instance_id}"); |
| 178 | + let description = format!("activity stream for [{name}]"); |
| 179 | + |
| 180 | + match to_receive { |
| 181 | + Some(payload_types) => jetstream::consumer::pull::Config { |
| 182 | + name: Some(name), |
| 183 | + description: Some(description), |
| 184 | + deliver_policy: jetstream::consumer::DeliverPolicy::New, |
| 185 | + filter_subjects: payload_types |
| 186 | + .iter() |
| 187 | + .map(|t| nats::subject::for_activity_discriminate(prefix, t)) |
| 188 | + .map(|s| s.to_string()) |
| 189 | + .collect(), |
| 190 | + ..Default::default() |
| 191 | + }, |
| 192 | + None => jetstream::consumer::pull::Config { |
| 193 | + name: Some(name), |
| 194 | + description: Some(description), |
| 195 | + deliver_policy: jetstream::consumer::DeliverPolicy::New, |
| 196 | + ..Default::default() |
| 197 | + }, |
| 198 | + } |
| 199 | + } |
| 200 | +} |
0 commit comments