coactor 0.1.0

An embedded distributed Actor framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::{error::Error, sync::Arc, time::Duration};

use async_trait::async_trait;
use aws_sdk_s3::{Client, primitives::ByteStream};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::wall_time_millis;
use crate::coordination::CoordinationErrorKind;
use crate::{
    ActorAddress, ActorOwnerReader, ActorOwnerRecord, ActorOwnerStore, CoordinationError,
    MutationOutcome, NodeDirectory, NodeLeaseStore, NodeRecord, Revision,
    VersionedActorOwnerRecord,
};

#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum S3StoreConfigError {
    #[error("S3 bucket must not be empty")]
    EmptyBucket,
    #[error(
        "S3 prefix must be empty or contain canonical non-dot path segments without leading/trailing slashes"
    )]
    InvalidPrefix,
}

struct DirectoryCache {
    nodes: Vec<NodeRecord>,
    refresh_at: Option<tokio::time::Instant>,
}

/// AWS S3-backed implementation of the Coordination Store capabilities.
pub struct S3CoordinationStore {
    client: Client,
    bucket: Arc<str>,
    prefix: Arc<str>,
    directory_refresh_interval: Duration,
    directory_cache: tokio::sync::Mutex<DirectoryCache>,
}

impl S3CoordinationStore {
    /// Creates a store from an AWS SDK Client, bucket, and canonical object prefix.
    pub fn new(
        client: Client,
        bucket: impl Into<String>,
        prefix: impl Into<String>,
    ) -> Result<Self, S3StoreConfigError> {
        let bucket = bucket.into();
        let prefix = prefix.into();
        if bucket.trim().is_empty() {
            return Err(S3StoreConfigError::EmptyBucket);
        }
        if !prefix.is_empty()
            && (prefix.starts_with('/')
                || prefix.ends_with('/')
                || prefix
                    .split('/')
                    .any(|part| part.is_empty() || part == "." || part == ".."))
        {
            return Err(S3StoreConfigError::InvalidPrefix);
        }
        Ok(Self {
            client,
            bucket: bucket.into(),
            prefix: prefix.into(),
            directory_refresh_interval: Duration::from_secs(3),
            directory_cache: tokio::sync::Mutex::new(DirectoryCache {
                nodes: Vec::new(),
                refresh_at: None,
            }),
        })
    }

    /// Sets the Node Directory cache refresh interval.
    ///
    /// A zero duration is valid and effectively disables caching.
    pub fn directory_refresh_interval(mut self, interval: Duration) -> Self {
        self.directory_refresh_interval = interval;
        self
    }

    fn key(&self, suffix: &str) -> String {
        if self.prefix.is_empty() {
            suffix.to_owned()
        } else {
            format!("{}/{suffix}", self.prefix)
        }
    }
    fn node_key(&self, node_id: &str) -> String {
        self.key(&format!("nodes/{node_id}/lease.json"))
    }
    fn actor_key(&self, address: &ActorAddress) -> String {
        self.key(&format!(
            "actors/{}/{}/ownership.json",
            address.actor_type(),
            address.actor_id()
        ))
    }
    fn nodes_prefix(&self) -> String {
        self.key("nodes/")
    }

    async fn read_node_key(
        &self,
        node_id: &str,
        include_expired: bool,
    ) -> Result<Option<(NodeRecord, Revision, u64)>, CoordinationError> {
        let output = match self
            .client
            .get_object()
            .bucket(self.bucket.as_ref())
            .key(self.node_key(node_id))
            .send()
            .await
        {
            Ok(output) => output,
            Err(error) if error.as_service_error().is_some_and(|e| e.is_no_such_key()) => {
                return Ok(None);
            }
            Err(error) => return Err(classify_read_error(error)),
        };
        let revision = output
            .e_tag
            .ok_or_else(|| CoordinationError::from_kind(CoordinationErrorKind::InvalidData))?;
        let bytes = output
            .body
            .collect()
            .await
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::Unavailable, error))?
            .into_bytes();
        let mut lease: StoredNodeLease = serde_json::from_slice(&bytes)
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::InvalidData, error))?;
        lease.node.node_id = node_id.to_owned();
        if !include_expired && lease.expires_at_unix_ms <= wall_time_millis() {
            return Ok(None);
        }
        Ok(Some((
            lease.node,
            Revision::new(revision),
            lease.expires_at_unix_ms,
        )))
    }

    async fn put_node(
        &self,
        node: NodeRecord,
        ttl: Duration,
        revision: Option<&Revision>,
    ) -> Result<MutationOutcome<Revision>, CoordinationError> {
        let key = self.node_key(&node.node_id);
        let lease = StoredNodeLease {
            node,
            expires_at_unix_ms: wall_time_millis()
                .saturating_add(ttl.as_millis().try_into().unwrap_or(u64::MAX)),
        };
        let body = serde_json::to_vec(&lease)
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::InvalidData, error))?;
        let mut request = self
            .client
            .put_object()
            .bucket(self.bucket.as_ref())
            .key(key)
            .body(ByteStream::from(body));
        request = match revision {
            Some(revision) => request.if_match(revision.as_str()),
            None => request.if_none_match("*"),
        };
        match request.send().await {
            Ok(output) => output
                .e_tag
                .map(|etag| MutationOutcome::Applied(Revision::new(etag)))
                .ok_or_else(|| CoordinationError::from_kind(CoordinationErrorKind::InvalidData)),
            Err(error) => classify_write_error(error),
        }
    }

    async fn read_actor_key(
        &self,
        address: &ActorAddress,
    ) -> Result<Option<VersionedActorOwnerRecord>, CoordinationError> {
        let output = match self
            .client
            .get_object()
            .bucket(self.bucket.as_ref())
            .key(self.actor_key(address))
            .send()
            .await
        {
            Ok(output) => output,
            Err(error) if error.as_service_error().is_some_and(|e| e.is_no_such_key()) => {
                return Ok(None);
            }
            Err(error) => return Err(classify_read_error(error)),
        };
        let revision = output
            .e_tag
            .ok_or_else(|| CoordinationError::from_kind(CoordinationErrorKind::InvalidData))?;
        let bytes = output
            .body
            .collect()
            .await
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::Unavailable, error))?
            .into_bytes();
        let record = serde_json::from_slice(&bytes)
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::InvalidData, error))?;
        Ok(Some(VersionedActorOwnerRecord {
            record,
            revision: Revision::new(revision),
        }))
    }

    async fn fetch_nodes(&self) -> Result<Vec<NodeRecord>, CoordinationError> {
        let prefix = self.nodes_prefix();
        let mut continuation_token = None;
        let mut nodes = Vec::new();
        loop {
            let mut request = self
                .client
                .list_objects_v2()
                .bucket(self.bucket.as_ref())
                .prefix(&prefix);
            if let Some(token) = continuation_token {
                request = request.continuation_token(token);
            }
            let output = request.send().await.map_err(classify_read_error)?;
            for object in output.contents() {
                let Some(key) = object.key() else { continue };
                let Some(rest) = key.strip_prefix(&prefix) else {
                    continue;
                };
                let Some(node_id) = rest.strip_suffix("/lease.json") else {
                    continue;
                };
                if node_id.is_empty() || node_id.contains('/') {
                    continue;
                }
                if let Some((node, _, _)) = self.read_node_key(node_id, false).await? {
                    nodes.push(node);
                }
            }
            if !output.is_truncated.unwrap_or(false) {
                break;
            }
            continuation_token = output.next_continuation_token;
            if continuation_token.is_none() {
                return Err(CoordinationError::from_kind(
                    CoordinationErrorKind::InvalidData,
                ));
            }
        }
        nodes.sort_by(|a, b| a.node_id.cmp(&b.node_id));
        Ok(nodes)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct StoredNodeLease {
    #[serde(flatten)]
    node: NodeRecord,
    expires_at_unix_ms: u64,
}

#[async_trait]
impl NodeDirectory for S3CoordinationStore {
    async fn read_node(&self, node_id: &str) -> Result<Option<NodeRecord>, CoordinationError> {
        Ok(self
            .read_node_key(node_id, false)
            .await?
            .map(|(node, _, _)| node))
    }
    async fn list_nodes(&self) -> Result<Vec<NodeRecord>, CoordinationError> {
        let mut cache = self.directory_cache.lock().await;
        if cache
            .refresh_at
            .is_some_and(|at| tokio::time::Instant::now() < at)
        {
            return Ok(cache.nodes.clone());
        }
        let nodes = self.fetch_nodes().await?;
        let jitter = 0.8 + (rand::random::<u16>() % 401) as f64 / 1000.0;
        cache.refresh_at =
            Some(tokio::time::Instant::now() + self.directory_refresh_interval.mul_f64(jitter));
        cache.nodes = nodes.clone();
        Ok(nodes)
    }
}

#[async_trait]
impl NodeLeaseStore for S3CoordinationStore {
    async fn read_node_lease(
        &self,
        node_id: &str,
    ) -> Result<Option<(NodeRecord, Revision)>, CoordinationError> {
        Ok(self
            .read_node_key(node_id, false)
            .await?
            .map(|(node, revision, _)| (node, revision)))
    }
    async fn acquire_node(
        &self,
        node: NodeRecord,
        ttl: Duration,
    ) -> Result<MutationOutcome<Revision>, CoordinationError> {
        match self.read_node_key(&node.node_id, true).await? {
            None => self.put_node(node, ttl, None).await,
            Some((_, revision, expires_at)) if expires_at <= wall_time_millis() => {
                self.put_node(node, ttl, Some(&revision)).await
            }
            Some(_) => Ok(MutationOutcome::Conflict),
        }
    }
    async fn renew_node(
        &self,
        node: NodeRecord,
        ttl: Duration,
        revision: &Revision,
    ) -> Result<MutationOutcome<Revision>, CoordinationError> {
        self.put_node(node, ttl, Some(revision)).await
    }
    async fn release_node(
        &self,
        node_id: &str,
        revision: &Revision,
    ) -> Result<MutationOutcome<()>, CoordinationError> {
        match self
            .client
            .delete_object()
            .bucket(self.bucket.as_ref())
            .key(self.node_key(node_id))
            .if_match(revision.as_str())
            .send()
            .await
        {
            Ok(_) => Ok(MutationOutcome::Applied(())),
            Err(error) => classify_write_error(error).map(|outcome| match outcome {
                MutationOutcome::Applied(_) => MutationOutcome::Applied(()),
                MutationOutcome::Conflict => MutationOutcome::Conflict,
                MutationOutcome::Indeterminate(error) => MutationOutcome::Indeterminate(error),
            }),
        }
    }
}

#[async_trait]
impl ActorOwnerReader for S3CoordinationStore {
    async fn read_actor_owner(
        &self,
        address: &ActorAddress,
    ) -> Result<Option<VersionedActorOwnerRecord>, CoordinationError> {
        self.read_actor_key(address).await
    }
}

#[async_trait]
impl ActorOwnerStore for S3CoordinationStore {
    async fn compare_exchange_actor_owner(
        &self,
        address: &ActorAddress,
        record: ActorOwnerRecord,
        revision: Option<&Revision>,
    ) -> Result<MutationOutcome<Revision>, CoordinationError> {
        let body = serde_json::to_vec(&record)
            .map_err(|error| CoordinationError::new(CoordinationErrorKind::InvalidData, error))?;
        let mut request = self
            .client
            .put_object()
            .bucket(self.bucket.as_ref())
            .key(self.actor_key(address))
            .body(ByteStream::from(body));
        request = match revision {
            Some(revision) => request.if_match(revision.as_str()),
            None => request.if_none_match("*"),
        };
        match request.send().await {
            Ok(output) => output
                .e_tag
                .map(|etag| MutationOutcome::Applied(Revision::new(etag)))
                .ok_or_else(|| CoordinationError::from_kind(CoordinationErrorKind::InvalidData)),
            Err(error) => classify_write_error(error),
        }
    }
}

fn classify_read_error<E>(error: aws_sdk_s3::error::SdkError<E>) -> CoordinationError
where
    E: Error + Send + Sync + 'static + aws_sdk_s3::error::ProvideErrorMetadata,
{
    let kind = if error
        .raw_response()
        .is_some_and(|response| matches!(response.status().as_u16(), 401 | 403))
    {
        CoordinationErrorKind::PermissionDenied
    } else {
        CoordinationErrorKind::Unavailable
    };
    CoordinationError::new(kind, error)
}

fn classify_write_error<E>(
    error: aws_sdk_s3::error::SdkError<E>,
) -> Result<MutationOutcome<Revision>, CoordinationError>
where
    E: Error + Send + Sync + 'static + aws_sdk_s3::error::ProvideErrorMetadata,
{
    if error
        .raw_response()
        .is_some_and(|response| response.status().as_u16() == 412)
    {
        Ok(MutationOutcome::Conflict)
    } else if error.as_service_error().is_some() {
        Err(classify_read_error(error))
    } else {
        Ok(MutationOutcome::Indeterminate(classify_read_error(error)))
    }
}