maincopy-server 0.1.0

Self-hosted publishing server with exact previews and explicit release approval
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use std::{sync::Arc, time::Duration};

use thiserror::Error;
use time::OffsetDateTime;
use tokio::sync::Notify;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

use crate::database::store::{DatabaseAdmissionError, DatabaseCommandError, DatabaseMutationError};

use super::{
    activation::{
        PublicationActivationError, PublicationCoordinatorHandle, PublicationCoordinatorUnavailable,
    },
    store::{PublicationRouteOwnershipError, PublicationStore, StartupSnapshotLoadError},
};

const RETRY_DELAY: Duration = Duration::from_millis(100);

/// Activates durable scheduled approvals when their UTC activation time arrives.
pub(crate) struct PublicationScheduler {
    store: PublicationStore,
    coordinator: PublicationCoordinatorHandle,
    wakeup: Arc<Notify>,
    cancellation: CancellationToken,
}

impl PublicationScheduler {
    pub(crate) fn new(
        store: PublicationStore,
        coordinator: PublicationCoordinatorHandle,
        wakeup: Arc<Notify>,
        cancellation: CancellationToken,
    ) -> Self {
        Self {
            store,
            coordinator,
            wakeup,
            cancellation,
        }
    }

    /// Runs until cancellation or an activation outcome that cannot be retried safely.
    pub(crate) async fn run(self) -> Result<(), PublicationSchedulerError> {
        loop {
            if self.run_iteration().await? == LoopControl::Stop {
                return Ok(());
            }
        }
    }

    async fn run_iteration(&self) -> Result<LoopControl, PublicationSchedulerError> {
        let scheduled = tokio::select! {
            biased;
            _ = self.cancellation.cancelled() => return Ok(LoopControl::Stop),
            result = self.store.next_scheduled_publication() => {
                result.map_err(PublicationSchedulerError::Load)?
            }
        };
        let Some(scheduled) = scheduled else {
            return Ok(wait_for_requery(None, &self.wakeup, &self.cancellation).await);
        };
        let delay = delay_until(
            scheduled.publication.view().scheduled_at,
            OffsetDateTime::now_utc(),
        );
        if delay.is_zero() {
            self.activate(scheduled.publication_id).await
        } else {
            Ok(wait_for_requery(Some(delay), &self.wakeup, &self.cancellation).await)
        }
    }

    async fn activate(
        &self,
        publication_id: Uuid,
    ) -> Result<LoopControl, PublicationSchedulerError> {
        // Once admitted, scheduled activation must run to a known durable
        // outcome even when shutdown is requested concurrently.
        let result = self
            .coordinator
            .activate_scheduled(publication_id, OffsetDateTime::now_utc())
            .await;
        match result {
            Err(PublicationActivationError::Coordinator(
                PublicationCoordinatorUnavailable::Closed,
            )) if self.cancellation.is_cancelled() => Ok(LoopControl::Stop),
            Ok(_) | Err(PublicationActivationError::ReleaseBlocked { .. }) => {
                Ok(LoopControl::Continue)
            }
            Err(error) if retryable(&error) => {
                Ok(wait_for_requery(Some(RETRY_DELAY), &self.wakeup, &self.cancellation).await)
            }
            Err(source) => Err(PublicationSchedulerError::Activation {
                publication_id,
                source,
            }),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum LoopControl {
    Continue,
    Stop,
}

fn delay_until(scheduled_at: OffsetDateTime, now: OffsetDateTime) -> Duration {
    if scheduled_at <= now {
        return Duration::ZERO;
    }
    (scheduled_at - now).try_into().unwrap_or(Duration::MAX)
}

fn retryable(error: &PublicationActivationError) -> bool {
    matches!(
        error,
        PublicationActivationError::Database(
            DatabaseMutationError::Admission(DatabaseAdmissionError::QueueFull)
                | DatabaseMutationError::Command(
                    DatabaseCommandError::IdempotencyConflict | DatabaseCommandError::Rejected
                )
        ) | PublicationActivationError::RouteOwnership(PublicationRouteOwnershipError::Query(_))
    )
}

async fn wait_for_requery(
    delay: Option<Duration>,
    wakeup: &Notify,
    cancellation: &CancellationToken,
) -> LoopControl {
    match delay {
        Some(delay) => {
            tokio::select! {
                biased;
                _ = cancellation.cancelled() => LoopControl::Stop,
                _ = wakeup.notified() => LoopControl::Continue,
                _ = tokio::time::sleep(delay) => LoopControl::Continue,
            }
        }
        None => {
            tokio::select! {
                biased;
                _ = cancellation.cancelled() => LoopControl::Stop,
                _ = wakeup.notified() => LoopControl::Continue,
            }
        }
    }
}

#[derive(Debug, Error)]
pub(crate) enum PublicationSchedulerError {
    #[error("could not load the scheduled publication queue")]
    Load(#[source] StartupSnapshotLoadError),
    #[error("could not activate scheduled publication {publication_id}")]
    Activation {
        publication_id: Uuid,
        #[source]
        source: PublicationActivationError,
    },
}

#[cfg(test)]
mod tests {
    use std::{future::Future, path::Path};

    use markdown_compiler::{ContentTreeDigest, PostCollection, PostId, PostSlug, prepare_content};
    use tokio::task::JoinHandle;

    use super::*;
    use crate::{
        config::{
            DatabaseBusyTimeout, DatabaseConfigurationView, DatabaseReadPoolSize,
            DatabaseWriterQueueCapacity,
        },
        content_fixtures::{content_tree, post, publication},
        database,
        domain::publication::{
            PublicLedgerProjection,
            activation::{PublicationCoordinator, observed_post_revisions},
            store::{
                CommandIdempotencyKey, InstallStartupSnapshot, PublicationRoute,
                SchedulePublication,
            },
        },
        frontend_assets::embedded_manifest,
        render::{
            ContentCatalog, SiteSnapshotReader, compile_content_catalog,
            render_bound_post_revision_preview, render_site_shell, snapshot_store,
        },
        web::Readiness,
    };

    const POST_ID: &str = "11111111-1111-4111-8111-111111111111";
    const PREVIEW_REPRODUCTION_PATH: &str = "/api/admin/v1/preview-assets/reproduce";

    struct SupervisedTask {
        cancellation: CancellationToken,
        task: Option<JoinHandle<()>>,
    }

    impl SupervisedTask {
        fn spawn<Start, Operation>(root: Arc<tempfile::TempDir>, start: Start) -> Self
        where
            Start: FnOnce(CancellationToken) -> Operation + Send + 'static,
            Operation: Future<Output = ()> + Send + 'static,
        {
            let cancellation = CancellationToken::new();
            let task_cancellation = cancellation.clone();
            let task = tokio::spawn(async move {
                let _root = root;
                start(task_cancellation).await;
            });
            Self {
                cancellation,
                task: Some(task),
            }
        }

        async fn stop(&mut self) {
            self.cancellation.cancel();
            self.task.take().unwrap().await.unwrap();
        }
    }

    impl Drop for SupervisedTask {
        fn drop(&mut self) {
            self.cancellation.cancel();
            if let Some(task) = self.task.take() {
                task.abort();
            }
        }
    }

    struct SchedulerFixture {
        _root: Arc<tempfile::TempDir>,
        store: PublicationStore,
        coordinator: PublicationCoordinator,
        snapshots: SiteSnapshotReader,
        writer: SupervisedTask,
    }

    impl SchedulerFixture {
        async fn start() -> Self {
            let catalog = catalog();
            let ledger = PublicLedgerProjection::empty();
            let initial = render_site_shell(Arc::clone(&catalog), embedded_manifest(), &ledger)
                .unwrap()
                .into_snapshot()
                .unwrap();
            let initial_digest = initial.digest.clone();
            let root = Arc::new(tempfile::tempdir().unwrap());
            let database = database::bootstrap(database_configuration(
                &root.path().join("state/maincopy.db"),
            ))
            .await
            .unwrap();
            let (stores, writer) = database.into_store(8);
            let writer = SupervisedTask::spawn(Arc::clone(&root), |cancellation| async move {
                writer.run(cancellation).await.unwrap();
            });
            let store = stores.publications;
            let head = store
                .install_startup_snapshot(InstallStartupSnapshot {
                    expected: None,
                    candidate_digest: initial_digest,
                    activated_at: OffsetDateTime::now_utc() - time::Duration::hours(1),
                    source_commit: None,
                    posts: observed_post_revisions(&catalog),
                })
                .await
                .unwrap();
            let (snapshots, activator) = snapshot_store(initial);
            let content_digest = ContentTreeDigest::from_bytes([0x11; 32]);
            let coordinator = PublicationCoordinator {
                catalog: Arc::clone(&catalog),
                content_digest: content_digest.clone(),
                candidates: Arc::new(std::collections::BTreeMap::from([(
                    content_digest,
                    catalog,
                )])),
                ledger,
                site: head,
                activator,
                store: store.clone(),
                profiles: stores.profiles,
                tip_recipient: None,
                frontend: embedded_manifest(),
                source_commit: None,
                scheduled: std::collections::BTreeMap::new(),
                scheduler_wakeup: Arc::new(Notify::new()),
                readiness: Readiness::new(true),
                cancellation: CancellationToken::new(),
            };
            Self {
                _root: root,
                store,
                coordinator,
                snapshots,
                writer,
            }
        }

        async fn seed_scheduled(&mut self, scheduled_at: OffsetDateTime, key: u128) -> Uuid {
            let post_id = PostId::parse(POST_ID).unwrap();
            let rendered = self.coordinator.catalog.current_post(&post_id).unwrap();
            let revision = rendered.revision.clone();
            let accepted_preview_digest = render_bound_post_revision_preview(
                &self.coordinator.catalog,
                embedded_manifest(),
                &post_id,
                &revision,
                None,
                PREVIEW_REPRODUCTION_PATH,
                None,
            )
            .unwrap()
            .unwrap()
            .digest;
            let publication_id = fixture_uuid(key);
            let scheduled = self
                .store
                .schedule_publication(SchedulePublication {
                    creation_key: CommandIdempotencyKey::new(fixture_uuid(key + 100)),
                    publication_id,
                    stable_post_id: post_id,
                    pinned_post_digest: revision,
                    expected_revision: None,
                    expected_site: self.coordinator.site.clone(),
                    source_commit: None,
                    content_digest: self.coordinator.content_digest.clone(),
                    accepted_preview_digest,
                    slug: rendered.document.metadata.slug.clone(),
                    aliases: rendered.document.metadata.aliases.clone().into(),
                    accepted_at: scheduled_at - time::Duration::hours(1),
                    scheduled_at,
                })
                .await
                .unwrap();
            self.coordinator.scheduled.insert(publication_id, scheduled);
            publication_id
        }

        fn start_actor(self) -> RunningSchedulerFixture {
            let Self {
                _root,
                store,
                coordinator,
                snapshots,
                writer,
            } = self;
            let (handle, actor) = coordinator.into_actor(8);
            let actor = SupervisedTask::spawn(Arc::clone(&_root), |cancellation| async move {
                actor.run(cancellation).await.unwrap();
            });
            RunningSchedulerFixture {
                _root,
                store,
                handle,
                snapshots,
                actor,
                writer,
            }
        }
    }

    struct RunningSchedulerFixture {
        _root: Arc<tempfile::TempDir>,
        store: PublicationStore,
        handle: PublicationCoordinatorHandle,
        snapshots: SiteSnapshotReader,
        actor: SupervisedTask,
        writer: SupervisedTask,
    }

    impl RunningSchedulerFixture {
        async fn stop(mut self) {
            self.actor.stop().await;
            self.writer.stop().await;
        }
    }

    fn database_configuration(path: &Path) -> DatabaseConfigurationView<'_> {
        DatabaseConfigurationView {
            path,
            busy_timeout: DatabaseBusyTimeout::from_milliseconds(1_000).unwrap(),
            writer_queue_capacity: DatabaseWriterQueueCapacity::new(8).unwrap(),
            read_pool_size: DatabaseReadPoolSize::new(2).unwrap(),
        }
    }

    fn fixture_uuid(discriminator: u128) -> Uuid {
        Uuid::from_u128(0xaaaa_aaaa_aaaa_4aaa_8aaa_0000_0000_0000 | discriminator)
    }

    fn catalog() -> Arc<ContentCatalog> {
        let tree = content_tree(
            publication(
                "publication.toml",
                "[site]\n\
                 title = \"Scheduler tests\"\n\
                 base_url = \"https://example.com/\"\n\
                 description = \"Scheduler tests.\"\n\
                 [author]\n\
                 name = \"Example Author\"\n\
                 [assets]\n\
                 allowed_https_origins = []\n"
                    .to_owned(),
            ),
            vec![post(
                "posts/scheduled.md",
                PostCollection::Posts,
                format!(
                    "+++\n\
                     id = {POST_ID:?}\n\
                     title = \"Scheduled post\"\n\
                     slug = \"scheduled-post\"\n\
                     authored_at = 2026-08-29T15:00:00-04:00\n\
                     description = \"Scheduler activation fixture.\"\n\
                     draft = false\n\
                     +++\n\
                     Scheduled publication body.\n"
                ),
            )],
            Vec::new(),
            0,
        );
        let content = prepare_content(&tree).unwrap();
        Arc::new(compile_content_catalog(&content).unwrap())
    }

    #[test]
    fn retryability_is_limited_to_backpressure_and_ordinary_conflicts() {
        let queue_full =
            PublicationActivationError::Database(DatabaseAdmissionError::QueueFull.into());
        let rejected = PublicationActivationError::Database(DatabaseCommandError::Rejected.into());
        let idempotency_conflict =
            PublicationActivationError::Database(DatabaseCommandError::IdempotencyConflict.into());
        let writer_closed =
            PublicationActivationError::Database(DatabaseAdmissionError::WriterClosed.into());
        let uncertain =
            PublicationActivationError::Database(DatabaseCommandError::OutcomeUnknown.into());
        let invalid =
            PublicationActivationError::Database(DatabaseCommandError::InvalidValue.into());
        let route_query = PublicationActivationError::RouteOwnership(
            PublicationRouteOwnershipError::Query(sqlx::Error::PoolTimedOut),
        );
        let route_conflict =
            PublicationActivationError::RouteOwnership(PublicationRouteOwnershipError::Conflict {
                route: PublicationRoute::Canonical(PostSlug::parse("claimed-route").unwrap()),
            });

        assert!(retryable(&queue_full));
        assert!(retryable(&rejected));
        assert!(retryable(&idempotency_conflict));
        assert!(retryable(&route_query));
        assert!(!retryable(&writer_closed));
        assert!(!retryable(&uncertain));
        assert!(!retryable(&invalid));
        assert!(!retryable(&route_conflict));
        assert!(!retryable(
            &PublicationActivationError::DurableStateMismatch
        ));
    }

    #[tokio::test]
    async fn due_publication_activation_updates_the_snapshot_projection_and_durable_ledger() {
        let mut fixture = SchedulerFixture::start().await;
        let initial_digest = fixture.snapshots.load_full().digest.clone();
        fixture
            .seed_scheduled(OffsetDateTime::now_utc() - time::Duration::seconds(1), 1)
            .await;
        let running = fixture.start_actor();
        let cancellation = CancellationToken::new();
        let scheduler = PublicationScheduler::new(
            running.store.clone(),
            running.handle.clone(),
            running.handle.scheduler_wakeup(),
            cancellation.clone(),
        );

        assert_eq!(
            scheduler.run_iteration().await.unwrap(),
            LoopControl::Continue
        );
        let projection = running.handle.read();
        let post_id = PostId::parse(POST_ID).unwrap();
        assert_eq!(projection.ledger.len(), 1);
        assert!(projection.ledger.published_post(&post_id).is_some());
        assert_ne!(projection.site.digest, initial_digest);
        assert_eq!(running.snapshots.load_full().digest, projection.site.digest);
        let durable = running.store.startup_snapshot_state().await.unwrap();
        assert_eq!(durable.ledger, projection.ledger);
        assert!(durable.scheduled.is_empty());
        assert!(durable.activating.is_empty());
        assert_eq!(
            durable.site.as_ref().map(|site| &site.digest),
            Some(&projection.site.digest)
        );

        cancellation.cancel();
        running.stop().await;
    }

    #[tokio::test]
    async fn rejected_early_activation_waits_before_retrying_and_keeps_the_schedule() {
        let mut fixture = SchedulerFixture::start().await;
        let publication_id = fixture
            .seed_scheduled(OffsetDateTime::now_utc() + time::Duration::hours(1), 2)
            .await;
        let readiness = fixture.coordinator.readiness.clone();
        let running = fixture.start_actor();
        let cancellation = CancellationToken::new();
        let scheduler = PublicationScheduler::new(
            running.store.clone(),
            running.handle.clone(),
            running.handle.scheduler_wakeup(),
            cancellation.clone(),
        );
        tokio::time::pause();
        let started = tokio::time::Instant::now();

        assert_eq!(
            scheduler.activate(publication_id).await.unwrap(),
            LoopControl::Continue
        );
        assert!(tokio::time::Instant::now().duration_since(started) >= RETRY_DELAY);
        assert!(readiness.is_ready());
        assert!(running.handle.read().ledger.is_empty());
        // SQLx's pool acquisition deadline also uses Tokio time. Restore the
        // real clock before inspecting durable state so automatic advancement
        // cannot race a returned read connection under parallel test load.
        tokio::time::resume();
        let durable = running.store.startup_snapshot_state().await.unwrap();
        assert_eq!(durable.scheduled.len(), 1);
        assert_eq!(durable.scheduled[0].publication_id, publication_id);
        assert!(durable.activating.is_empty());

        cancellation.cancel();
        running.stop().await;
    }

    #[tokio::test]
    async fn closed_coordinator_is_fatal_unless_cancellation_is_already_requested() {
        let mut fixture = SchedulerFixture::start().await;
        let publication_id = fixture
            .seed_scheduled(OffsetDateTime::now_utc() - time::Duration::seconds(1), 3)
            .await;
        let SchedulerFixture {
            _root,
            store,
            coordinator,
            snapshots: _,
            mut writer,
        } = fixture;
        let (handle, actor) = coordinator.into_actor(1);
        drop(actor);

        let fatal = PublicationScheduler::new(
            store.clone(),
            handle.clone(),
            handle.scheduler_wakeup(),
            CancellationToken::new(),
        )
        .run()
        .await
        .unwrap_err();
        assert!(matches!(
            fatal,
            PublicationSchedulerError::Activation {
                publication_id: failed_id,
                source: PublicationActivationError::Coordinator(
                    PublicationCoordinatorUnavailable::Closed
                ),
            } if failed_id == publication_id
        ));
        assert_eq!(
            store
                .next_scheduled_publication()
                .await
                .unwrap()
                .map(|scheduled| scheduled.publication_id),
            Some(publication_id)
        );

        let cancellation = CancellationToken::new();
        cancellation.cancel();
        let stopping = PublicationScheduler::new(
            store,
            handle.clone(),
            handle.scheduler_wakeup(),
            cancellation,
        );
        assert_eq!(
            stopping.activate(publication_id).await.unwrap(),
            LoopControl::Stop
        );

        writer.stop().await;
        drop(_root);
    }

    #[tokio::test(start_paused = true)]
    async fn timed_wait_requeries_at_deadline() {
        let wakeup = Arc::new(Notify::new());
        let cancellation = CancellationToken::new();
        let task = tokio::spawn({
            let wakeup = Arc::clone(&wakeup);
            let cancellation = cancellation.clone();
            async move { wait_for_requery(Some(Duration::from_secs(60)), &wakeup, &cancellation).await }
        });

        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(59)).await;
        assert!(!task.is_finished());
        tokio::time::advance(Duration::from_secs(1)).await;
        assert_eq!(task.await.unwrap(), LoopControl::Continue);
    }

    #[tokio::test(start_paused = true)]
    async fn wakeup_requeries_before_a_later_deadline() {
        let wakeup = Arc::new(Notify::new());
        let cancellation = CancellationToken::new();
        let task = tokio::spawn({
            let wakeup = Arc::clone(&wakeup);
            let cancellation = cancellation.clone();
            async move { wait_for_requery(Some(Duration::from_secs(60)), &wakeup, &cancellation).await }
        });

        tokio::task::yield_now().await;
        wakeup.notify_one();
        assert_eq!(task.await.unwrap(), LoopControl::Continue);
    }

    #[tokio::test(start_paused = true)]
    async fn cancellation_stops_an_idle_wait() {
        let wakeup = Arc::new(Notify::new());
        let cancellation = CancellationToken::new();
        let task = tokio::spawn({
            let wakeup = Arc::clone(&wakeup);
            let cancellation = cancellation.clone();
            async move { wait_for_requery(None, &wakeup, &cancellation).await }
        });

        tokio::task::yield_now().await;
        cancellation.cancel();
        assert_eq!(task.await.unwrap(), LoopControl::Stop);
    }
}