little-durable-objects 0.1.2

Standalone regional durable-object control plane, host, and durability runtime
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    time::Duration,
};

use anyhow::{Context, Result};
use async_trait::async_trait;
use serde_json::Value;
use tokio::sync::{Notify, watch};
use tracing::warn;

use crate::{
    actor::{
        ActorExecutionResult, ActorExecutor, ActorInvocation, ActorInvocationFailure,
        ActorMethodEviction, ActorMethodInvocation, ActorMethodOutcome,
    },
    actor_state::{ActorExecutionAdmission, ActorExecutionLocks},
    control_plane::ControlPlaneClient,
    state_log::StateAppend,
    state_transport::{LoadedState, StateTransport, StateWrite},
};

use super::HostEndpoint;

#[async_trait]
pub(crate) trait StateWriteAuthority: Send + Sync {
    async fn authorize_state_write(
        &self,
        actor: &crate::actor::ActorKey,
        host_id: &super::HostId,
        owner_epoch: u64,
        expected_generation: &str,
    ) -> Result<String>;
}

#[async_trait]
impl StateWriteAuthority for ControlPlaneClient {
    async fn authorize_state_write(
        &self,
        actor: &crate::actor::ActorKey,
        host_id: &super::HostId,
        owner_epoch: u64,
        expected_generation: &str,
    ) -> Result<String> {
        ControlPlaneClient::authorize_state_write(
            self,
            actor,
            host_id,
            owner_epoch,
            expected_generation,
        )
        .await
    }
}

pub(crate) struct ActorHost {
    endpoint: HostEndpoint,
    namespace_id: String,
    executor: Arc<dyn ActorExecutor>,
    state_write_authority: Arc<dyn StateWriteAuthority>,
    state: Arc<dyn StateTransport>,
    executions: ActorExecutionLocks,
    accepting: AtomicBool,
    active: AtomicUsize,
    activity_tx: watch::Sender<usize>,
    idle: Notify,
}

impl ActorHost {
    pub(crate) fn new(
        endpoint: HostEndpoint,
        namespace_id: String,
        executor: Arc<dyn ActorExecutor>,
        state_write_authority: Arc<dyn StateWriteAuthority>,
        state: Arc<dyn StateTransport>,
    ) -> Self {
        let (activity_tx, _) = watch::channel(0);
        Self {
            endpoint,
            namespace_id,
            executor,
            state_write_authority,
            state,
            executions: ActorExecutionLocks::new(),
            accepting: AtomicBool::new(true),
            active: AtomicUsize::new(0),
            activity_tx,
            idle: Notify::new(),
        }
    }

    pub(crate) fn activity(&self) -> watch::Receiver<usize> {
        self.activity_tx.subscribe()
    }

    pub(crate) fn id(&self) -> &super::HostId {
        &self.endpoint.id
    }

    pub(crate) async fn invoke_actor(
        &self,
        invocation: ActorInvocation,
        owner_epoch: u64,
        state_read_url: String,
    ) -> Result<ActorExecutionResult> {
        if let Some(result) = self.validate_invocation(&invocation)? {
            return Ok(result);
        }
        let _activity = ActivityGuard::begin(self);
        let object = invocation.actor.storage_key();
        let _execution = match self.executions.admit(&object).await? {
            ActorExecutionAdmission::Acquired(guard) => guard,
            ActorExecutionAdmission::Full => return Ok(ActorExecutionResult::HostUnavailable),
        };
        if !self.accepting.load(Ordering::SeqCst) {
            return Ok(ActorExecutionResult::HostUnavailable);
        }
        let mut loaded = match self
            .load_owned_state(&invocation, owner_epoch, &state_read_url)
            .await?
        {
            OwnershipRead::Owned(loaded) => loaded,
            OwnershipRead::Reroute => return Ok(ActorExecutionResult::Reroute),
        };
        let (result, next_state) = match self.execute_method(&invocation, &loaded).await {
            Ok(outcome) => outcome,
            Err(failure) => return Ok(failure),
        };
        let append = match loaded.log.append(owner_epoch, next_state) {
            Ok(append) => append,
            Err(error) => return Ok(self.state_failure(&invocation, error).await),
        };
        if append == StateAppend::Unchanged {
            return Ok(ActorExecutionResult::Completed { result });
        }
        self.publish_result(&invocation, owner_epoch, loaded, result)
            .await
    }

    pub(crate) async fn drain(&self, timeout: Duration) -> Result<()> {
        self.accepting.store(false, Ordering::SeqCst);
        tokio::time::timeout(timeout, async {
            while self.active.load(Ordering::SeqCst) != 0 {
                self.idle.notified().await;
            }
        })
        .await
        .context("actor invocations did not drain before shutdown")?;
        Ok(())
    }

    fn validate_invocation(
        &self,
        invocation: &ActorInvocation,
    ) -> Result<Option<ActorExecutionResult>> {
        if !self.accepting.load(Ordering::SeqCst) {
            return Ok(Some(ActorExecutionResult::HostUnavailable));
        }
        invocation.validate()?;
        if invocation.actor.namespace_id != self.namespace_id {
            anyhow::bail!("actor invocation crossed the host namespace");
        }
        if !self.executor.supports(&invocation.actor.actor_type) {
            return Ok(Some(failed(
                "actor_error",
                "actor type is not loaded by this host",
            )));
        }
        Ok(None)
    }

    async fn load_owned_state(
        &self,
        invocation: &ActorInvocation,
        owner_epoch: u64,
        state_read_url: &str,
    ) -> Result<OwnershipRead> {
        let mut loaded = self
            .state
            .read(state_read_url)
            .await
            .context("load actor state")?;
        if has_newer_owner(&loaded, owner_epoch) {
            return Ok(OwnershipRead::Reroute);
        }
        if !loaded.log.claim(owner_epoch).map_err(state_error)? {
            return Ok(OwnershipRead::Owned(loaded));
        }
        if !self.publish_claim(invocation, owner_epoch, &loaded).await? {
            return Ok(OwnershipRead::Reroute);
        }
        loaded = self.state.read(state_read_url).await?;
        if has_current_owner(&loaded, owner_epoch) {
            Ok(OwnershipRead::Owned(loaded))
        } else {
            Ok(OwnershipRead::Reroute)
        }
    }

    async fn execute_method(
        &self,
        invocation: &ActorInvocation,
        loaded: &LoadedState,
    ) -> std::result::Result<(Value, Value), ActorExecutionResult> {
        let outcome = self
            .executor
            .invoke(ActorMethodInvocation {
                request_id: invocation.request_id.clone(),
                actor: invocation.actor.clone(),
                method: invocation.method.clone(),
                args: invocation.args.clone(),
                state: loaded.log.latest_state().cloned(),
            })
            .await;
        match outcome {
            Ok(ActorMethodOutcome::Completed { result, state }) => Ok((result, state)),
            Ok(ActorMethodOutcome::Failed(failure)) => {
                self.evict(&invocation.actor).await;
                Err(failed("actor_error", failure.message))
            }
            Err(error) => {
                self.evict(&invocation.actor).await;
                Err(failed(
                    "actor_error",
                    format!("actor executor failed: {error:#}"),
                ))
            }
        }
    }

    async fn state_failure(
        &self,
        invocation: &ActorInvocation,
        error: anyhow::Error,
    ) -> ActorExecutionResult {
        self.evict(&invocation.actor).await;
        failed("state_error", format!("{error:#}"))
    }

    async fn publish_result(
        &self,
        invocation: &ActorInvocation,
        owner_epoch: u64,
        loaded: LoadedState,
        result: Value,
    ) -> Result<ActorExecutionResult> {
        if let Err(error) = self.publish_state(invocation, owner_epoch, &loaded).await {
            self.evict(&invocation.actor).await;
            warn!(
                actor = %invocation.actor.storage_key(),
                error = %format!("{error:#}"),
                "actor completed but state publication could not be confirmed"
            );
            return Ok(ActorExecutionResult::Failed {
                failure: ActorInvocationFailure::outcome_unknown_after_execution(),
            });
        }
        Ok(ActorExecutionResult::Completed { result })
    }

    async fn publish_claim(
        &self,
        invocation: &ActorInvocation,
        owner_epoch: u64,
        loaded: &LoadedState,
    ) -> Result<bool> {
        let write_url = self
            .authorize_write(invocation, owner_epoch, &loaded.generation)
            .await
            .context("authorize actor ownership claim")?;
        match self.state.write(&write_url, loaded.log.encode()?).await? {
            StateWrite::Written => Ok(true),
            StateWrite::GenerationMismatch => Ok(false),
        }
    }

    async fn publish_state(
        &self,
        invocation: &ActorInvocation,
        owner_epoch: u64,
        loaded: &LoadedState,
    ) -> Result<()> {
        let write_url = self
            .authorize_write(invocation, owner_epoch, &loaded.generation)
            .await?;
        match self.state.write(&write_url, loaded.log.encode()?).await? {
            StateWrite::Written => Ok(()),
            StateWrite::GenerationMismatch => {
                anyhow::bail!("actor state generation changed during execution")
            }
        }
    }

    async fn authorize_write(
        &self,
        invocation: &ActorInvocation,
        owner_epoch: u64,
        generation: &str,
    ) -> Result<String> {
        self.state_write_authority
            .authorize_state_write(
                &invocation.actor,
                &self.endpoint.id,
                owner_epoch,
                generation,
            )
            .await
    }

    async fn evict(&self, actor: &crate::actor::ActorKey) {
        if let Err(error) = self
            .executor
            .evict(ActorMethodEviction {
                actor: actor.clone(),
            })
            .await
        {
            warn!(error = %format!("{error:#}"), "failed to evict actor after invocation failure");
        }
    }
}

enum OwnershipRead {
    Owned(LoadedState),
    Reroute,
}

fn has_newer_owner(loaded: &LoadedState, owner_epoch: u64) -> bool {
    loaded
        .log
        .latest()
        .is_some_and(|record| record.owner_epoch > owner_epoch)
}

fn has_current_owner(loaded: &LoadedState, owner_epoch: u64) -> bool {
    loaded
        .log
        .latest()
        .is_some_and(|record| record.owner_epoch == owner_epoch)
}

fn failed(code: impl Into<String>, message: impl Into<String>) -> ActorExecutionResult {
    ActorExecutionResult::Failed {
        failure: ActorInvocationFailure {
            code: code.into(),
            message: message.into(),
        },
    }
}

fn state_error(error: anyhow::Error) -> anyhow::Error {
    error.context("validate actor state log")
}

struct ActivityGuard<'a> {
    host: &'a ActorHost,
}

impl<'a> ActivityGuard<'a> {
    fn begin(host: &'a ActorHost) -> Self {
        let active = host.active.fetch_add(1, Ordering::SeqCst) + 1;
        let _ = host.activity_tx.send(active);
        Self { host }
    }
}

impl Drop for ActivityGuard<'_> {
    fn drop(&mut self) {
        let active = self.host.active.fetch_sub(1, Ordering::SeqCst) - 1;
        let _ = self.host.activity_tx.send(active);
        if active == 0 {
            self.host.idle.notify_waiters();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use serde_json::json;

    use super::*;
    use crate::{actor::ActorKey, state_log::StateLog};

    struct FakeExecutor;

    #[async_trait]
    impl ActorExecutor for FakeExecutor {
        fn supports(&self, actor_type: &str) -> bool {
            actor_type == "Counter"
        }

        async fn invoke(&self, _invocation: ActorMethodInvocation) -> Result<ActorMethodOutcome> {
            Ok(ActorMethodOutcome::Completed {
                result: json!({ "count": 1 }),
                state: json!({ "count": 1 }),
            })
        }
    }

    #[derive(Default)]
    struct FakeAuthority {
        generations: Mutex<Vec<String>>,
    }

    #[async_trait]
    impl StateWriteAuthority for FakeAuthority {
        async fn authorize_state_write(
            &self,
            _actor: &ActorKey,
            _host_id: &super::super::HostId,
            _owner_epoch: u64,
            expected_generation: &str,
        ) -> Result<String> {
            self.generations
                .lock()
                .unwrap()
                .push(expected_generation.into());
            Ok("https://state.invalid/write".into())
        }
    }

    #[derive(Default)]
    struct FakeStateTransport {
        body: Mutex<Vec<u8>>,
        generation: Mutex<u64>,
    }

    #[async_trait]
    impl StateTransport for FakeStateTransport {
        async fn read(&self, _signed_url: &str) -> Result<LoadedState> {
            Ok(LoadedState {
                log: StateLog::decode(&self.body.lock().unwrap())?,
                generation: self.generation.lock().unwrap().to_string(),
            })
        }

        async fn write(&self, _signed_url: &str, bytes: Vec<u8>) -> Result<StateWrite> {
            *self.body.lock().unwrap() = bytes;
            *self.generation.lock().unwrap() += 1;
            Ok(StateWrite::Written)
        }
    }

    #[tokio::test]
    async fn actor_execution_uses_the_injected_state_write_authority() -> Result<()> {
        let authority = Arc::new(FakeAuthority::default());
        let host = ActorHost::new(
            HostEndpoint {
                id: super::super::HostId::new("host-1"),
                route: "http://host.invalid/".into(),
            },
            "project-1".into(),
            Arc::new(FakeExecutor),
            authority.clone(),
            Arc::new(FakeStateTransport::default()),
        );

        let result = host
            .invoke_actor(
                ActorInvocation {
                    request_id: "request-1".into(),
                    actor: ActorKey {
                        namespace_id: "project-1".into(),
                        actor_type: "Counter".into(),
                        actor_id: "counter-1".into(),
                    },
                    method: "increment".into(),
                    args: Vec::new(),
                },
                1,
                "https://state.invalid/read".into(),
            )
            .await?;

        assert_eq!(
            result,
            ActorExecutionResult::Completed {
                result: json!({ "count": 1 })
            }
        );
        assert_eq!(*authority.generations.lock().unwrap(), ["0", "1"]);
        Ok(())
    }
}