qsu

Check-in Differences
Login

Check-in Differences

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From qsu-0.3.0 To qsu-0.4.0

2024-04-03
22:54
Re-export log and tracing. check-in: 999a598d71 user: jan tags: trunk
2024-03-22
13:34
Release maintenance. check-in: c90cbdbc41 user: jan tags: qsu-0.4.0, trunk
13:31
Cleanup and docs. check-in: 1e925f55cf user: jan tags: trunk
2024-03-13
10:26
Crate maintenance. check-in: 79a9d5aff8 user: jan tags: trunk
2024-01-30
11:58
Release maintenance. check-in: 0c6e1661ef user: jan tags: qsu-0.3.0, trunk
11:53
Update version. check-in: eeff552f76 user: jan tags: trunk

Changes to Cargo.toml.

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
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


-
+


+














+
+
+
+















-
-
+
+


-
+







-
-
+
+











-
-
+
+













-
-
+
+







[package]
name = "qsu"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
license = "0BSD"
# https://crates.io/category_slugs
categories = [ "asynchronous" ]
keywords = [ "service", "systemd", "winsvc" ]
repository = "https://repos.qrnch.tech/pub/qsu"
description = "Service subsystem wrapper."
rust-version = "1.56"
exclude = [
  ".fossil-settings",
  ".efiles",
  ".fslckout",
  "www",
  "build_docs.sh",
  "Rocket.toml",
  "rustfmt.toml"
]

# https://doc.rust-lang.org/cargo/reference/manifest.html#the-badges-section
[badges]
maintenance = { status = "experimental" }

[features]
default = ["rt"]
clap = ["dep:clap", "dep:itertools"]
full = ["clap", "installer", "rocket", "rt", "systemd", "tokio"]
installer = ["dep:sidoc"]
systemd = ["dep:sd-notify"]
rocket = ["rt", "dep:rocket", "tokio"]
rt = []
tokio = ["rt", "tokio/macros", "tokio/rt-multi-thread", "tokio/signal"]
wait-for-debugger = ["dep:dbgtools-win"]

[dependencies]
apperr = { version = "0.2.0" }
async-trait = { version = "0.1.77" }
chrono = { version = "0.4.33" }
clap = { version = "4.4.18", optional = true, features = [
chrono = { version = "0.4.35" }
clap = { version = "4.5.2", optional = true, features = [
  "derive", "env", "string", "wrap_help"
] }
env_logger = { version = "0.11.1" }
env_logger = { version = "0.11.3" }
futures = { version = "0.3.30" }
itertools = { version = "0.12.1", optional = true }
killswitch = { version = "0.4.2" }
log = { version = "0.4.20" }
parking_lot = { version = "0.12.1" }
rocket = { version = "0.5.0", optional = true }
sidoc = { version = "0.1.0", optional = true }
tokio = { version = "1.35.1", features = ["sync"] }
time = { version = "0.3.31", features = ["macros"] }
tokio = { version = "1.36.0", features = ["sync"] }
time = { version = "0.3.34", features = ["macros"] }
tracing = { version = "0.1.40" }

[dependencies.tracing-subscriber]
version = "0.3.18"
default-features = false
features = ["env-filter", "time", "fmt", "ansi"]

[target.'cfg(target_os = "linux")'.dependencies]
sd-notify = { version = "0.4.1", optional = true }

[target.'cfg(unix)'.dependencies]
libc = { version = "0.2.152" }
nix = { version = "0.27.1", features = ["pthread", "signal"] }
libc = { version = "0.2.153" }
nix = { version = "0.28.0", features = ["pthread", "signal"] }

[target.'cfg(windows)'.dependencies]
dbgtools-win = { version = "0.2.1", optional = true }
eventlog = { version = "0.2.2" }
registry = { version = "1.2.3" }
scopeguard = { version = "1.2.0" }
windows-service = { version = "0.6.0" }
windows-sys = { version = "0.52.0", features = [
  "Win32_Foundation", "Win32_System_Console"
] }
winreg = { version = "0.52.0" }

[dev-dependencies]
clap = { version = "4.4.14", features = ["derive", "env", "wrap_help"] }
tokio = { version = "1.35.1", features = ["time"] }
clap = { version = "4.5.2", features = ["derive", "env", "wrap_help"] }
tokio = { version = "1.36.0", features = ["time"] }

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs", "--generate-link-to-definition"]

[[example]]
name = "hellosvc"

Changes to examples/hellosvc-rocket.rs.

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
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










-
-
+
+















-
+





-
+


-
+








+







#[macro_use]
extern crate rocket;

mod argp;
mod err;
mod procres;

use qsu::{
  argp::ArgParser,
  rt::{
    RocketServiceHandler, SrvAppRt, StartState, StopState, SvcEvt,
    SvcEvtReader
    InitCtx, RocketServiceHandler, RunEnv, SrvAppRt, SvcEvt, SvcEvtReader,
    TermCtx
  }
};

use rocket::{Build, Ignite, Rocket};

use err::Error;
use procres::ProcRes;


struct MyService {}

#[qsu::async_trait]
impl RocketServiceHandler for MyService {
  async fn init(
    &mut self,
    ss: StartState
    ictx: InitCtx
  ) -> Result<Vec<Rocket<Build>>, qsu::AppErr> {
    tracing::trace!("Running init()");

    let mut rockets = vec![];

    ss.report(Some("Building a rocket!".into()));
    ictx.report(Some("Building a rocket!".into()));
    let rocket = rocket::build().mount("/", routes![index]);

    ss.report(Some("Pushing a rocket".into()));
    ictx.report(Some("Pushing a rocket".into()));
    rockets.push(rocket);

    Ok(rockets)
  }

  async fn run(
    &mut self,
    rockets: Vec<Rocket<Ignite>>,
    _re: &RunEnv,
    mut set: SvcEvtReader
  ) -> Result<(), qsu::AppErr> {
    for rocket in rockets {
      tokio::task::spawn(async {
        rocket.launch().await.unwrap();
      });
    }
76
77
78
79
80
81
82
83
84


85
86
87
88
89
90
91
77
78
79
80
81
82
83


84
85
86
87
88
89
90
91
92







-
-
+
+







        }
      }
    }

    Ok(())
  }

  async fn shutdown(&mut self, ss: StopState) -> Result<(), qsu::AppErr> {
    ss.report(Some(format!("Entered {}", "shutdown").into()));
  async fn shutdown(&mut self, tctx: TermCtx) -> Result<(), qsu::AppErr> {
    tctx.report(Some(format!("Entered {}", "shutdown").into()));
    tracing::trace!("Running shutdown()");
    Ok(())
  }
}


fn main() -> ProcRes {

Changes to examples/hellosvc-tokio.rs.

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
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











+
-
+











-
-
+
+




+
+
+
+
-
+







//! Simple service that does nothing other than log/trace every N seconds.

mod argp;
mod err;
mod procres;

use std::time::{Duration, Instant};

use qsu::{
  argp::ArgParser,
  rt::{
    InitCtx, RunEnv, SrvAppRt, SvcEvt, SvcEvtReader, TermCtx,
    SrvAppRt, StartState, StopState, SvcEvt, SvcEvtReader, TokioServiceHandler
    TokioServiceHandler
  }
};

use err::Error;
use procres::ProcRes;


struct MyService {}

#[qsu::async_trait]
impl TokioServiceHandler for MyService {
  async fn init(&mut self, ss: StartState) -> Result<(), qsu::AppErr> {
    ss.report(Some("Entered init".into()));
  async fn init(&mut self, ictx: InitCtx) -> Result<(), qsu::AppErr> {
    ictx.report(Some("Entered init".into()));
    tracing::trace!("Running init()");
    Ok(())
  }

  async fn run(
    &mut self,
    _re: &RunEnv,
    mut set: SvcEvtReader
  async fn run(&mut self, mut set: SvcEvtReader) -> Result<(), qsu::AppErr> {
  ) -> Result<(), qsu::AppErr> {
    const SECS: u64 = 30;
    let mut last_dump = Instant::now() - Duration::from_secs(SECS);
    loop {
      if Instant::now() - last_dump > Duration::from_secs(SECS) {
        log::error!("error");
        log::warn!("warn");
        log::info!("info");
70
71
72
73
74
75
76
77
78


79
80
81
82
83
84
85
75
76
77
78
79
80
81


82
83
84
85
86
87
88
89
90







-
-
+
+







        }
      }
    }

    Ok(())
  }

  async fn shutdown(&mut self, ss: StopState) -> Result<(), qsu::AppErr> {
    ss.report(Some(("Entered shutdown".to_string()).into()));
  async fn shutdown(&mut self, tctx: TermCtx) -> Result<(), qsu::AppErr> {
    tctx.report(Some(("Entered shutdown".to_string()).into()));
    tracing::trace!("Running shutdown()");
    Ok(())
  }
}


fn main() -> ProcRes {

Changes to examples/hellosvc.rs.

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
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







-
+










-
-
+
+




+
+
+
+
-
+







  thread,
  time::{Duration, Instant}
};

use qsu::{
  argp::ArgParser,
  rt::{
    ServiceHandler, SrvAppRt, StartState, StopState, SvcEvt, SvcEvtReader
    InitCtx, RunEnv, ServiceHandler, SrvAppRt, SvcEvt, SvcEvtReader, TermCtx
  }
};

use err::Error;
use procres::ProcRes;


struct MyService {}

impl ServiceHandler for MyService {
  fn init(&mut self, ss: StartState) -> Result<(), qsu::AppErr> {
    ss.report(Some("Entered init".into()));
  fn init(&mut self, ictx: InitCtx) -> Result<(), qsu::AppErr> {
    ictx.report(Some("Entered init".into()));
    tracing::trace!("Running init()");
    Ok(())
  }

  fn run(
    &mut self,
    _re: &RunEnv,
    mut set: SvcEvtReader
  fn run(&mut self, mut set: SvcEvtReader) -> Result<(), qsu::AppErr> {
  ) -> Result<(), qsu::AppErr> {
    const SECS: u64 = 30;
    let mut last_dump = Instant::now() - Duration::from_secs(SECS);
    loop {
      if Instant::now() - last_dump > Duration::from_secs(SECS) {
        log::error!("error");
        log::warn!("warn");
        log::info!("info");
73
74
75
76
77
78
79
80
81


82
83
84
85
86
87
88
77
78
79
80
81
82
83


84
85
86
87
88
89
90
91
92







-
-
+
+








      thread::sleep(std::time::Duration::from_secs(1));
    }

    Ok(())
  }

  fn shutdown(&mut self, ss: StopState) -> Result<(), qsu::AppErr> {
    ss.report(Some(("Entered shutdown".to_string()).into()));
  fn shutdown(&mut self, tctx: TermCtx) -> Result<(), qsu::AppErr> {
    tctx.report(Some(("Entered shutdown".to_string()).into()));
    tracing::trace!("Running shutdown()");
    Ok(())
  }
}


fn main() -> ProcRes {

Changes to src/rt.rs.

125
126
127
128
129
130
131















132
133
134
135
136
137
138
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







use tokio::runtime;

use tokio::sync::broadcast;


use crate::{err::Error, lumberjack::LumberJack, AppErr};

/// The run time environment.
///
/// Can be used by the application callbacks to determine whether it is running
/// as a service.
#[derive(Debug, Clone)]
pub enum RunEnv {
  /// Running as a foreground process.
  Foreground,

  /// Running as a service.
  ///
  /// If the service subsystem has named services, this will contain the
  /// service name.
  Service(Option<String>)
}

/// Used to pass an optional message to the service subsystem whenever a
/// startup or shutdown checkpoint as been reached.
pub enum StateMsg {
  Ref(&'static str),
  Owned(String)
}
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
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







-
-
-
-
-
+
+
+



-
+
+
+
+
+
+
+
+
+
+
+
+






-
+
-
-
+
-
-
+
+



-
+
+
+
+
+
+
+
+
+
+
+
+












-
+

-
+

-
+











-
+

+
+
+
+
-
+

-
+








  fn stopping(&self, checkpoint: u32, msg: Option<StateMsg>);

  fn stopped(&self);
}


/// Report startup checkpoints to the service subsystem.
///
/// An instance of this is handed to the server application through the service
/// handler's `init()` trait method.
pub struct StartState {
/// Context passed to `init()` service application callback.
pub struct InitCtx {
  re: RunEnv,
  sr: Arc<dyn StateReporter + Send + Sync>,
  cnt: Arc<AtomicU32>
}
impl StartState {

impl InitCtx {
  /// Return context used to identify whether service application is running as
  /// a foreground process or a system service.
  pub fn runenv(&self) -> RunEnv {
    self.re.clone()
  }

  /// Report startup state to the system service manager.
  ///
  /// For foreground processes and services that do not support startup state
  /// notifications this method has no effect.
  pub fn report(&self, status: Option<StateMsg>) {
    let checkpoint = self.cnt.fetch_add(1, Ordering::SeqCst);
    self.sr.starting(checkpoint, status);
  }
}

/// Report shutdown checkpoints to the service subsystem.

///
/// An instance of this is handed to the server application through the service
/// Context passed to `term()` service application callback.
/// handler's `shutdown()` trait method.
pub struct StopState {
pub struct TermCtx {
  re: RunEnv,
  sr: Arc<dyn StateReporter + Send + Sync>,
  cnt: Arc<AtomicU32>
}
impl StopState {

impl TermCtx {
  /// Return context used to identify whether service application is running as
  /// a foreground process or a system service.
  pub fn runenv(&self) -> RunEnv {
    self.re.clone()
  }

  /// Report shutdown state to the system service manager.
  ///
  /// For foreground processes and services that do not support shutdown state
  /// notifications this method has no effect.
  pub fn report(&self, status: Option<StateMsg>) {
    let checkpoint = self.cnt.fetch_add(1, Ordering::SeqCst);
    self.sr.stopping(checkpoint, status);
  }
}


/// "Synchronous" (non-`async`) server application.
///
/// Implement this for an object that wraps a server application that does not
/// use an async runtime.
pub trait ServiceHandler {
  fn init(&mut self, ss: StartState) -> Result<(), AppErr>;
  fn init(&mut self, ictx: InitCtx) -> Result<(), AppErr>;

  fn run(&mut self, ser: SvcEvtReader) -> Result<(), AppErr>;
  fn run(&mut self, re: &RunEnv, ser: SvcEvtReader) -> Result<(), AppErr>;

  fn shutdown(&mut self, ss: StopState) -> Result<(), AppErr>;
  fn shutdown(&mut self, tctx: TermCtx) -> Result<(), AppErr>;
}


/// `async` server application built on the tokio runtime.
///
/// Implement this for an object that wraps a server application that uses
/// tokio as an async runtime.
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
#[async_trait]
pub trait TokioServiceHandler {
  async fn init(&mut self, ss: StartState) -> Result<(), AppErr>;
  async fn init(&mut self, ictx: InitCtx) -> Result<(), AppErr>;

  async fn run(
    &mut self,
    re: &RunEnv,
    ser: SvcEvtReader
  async fn run(&mut self, ser: SvcEvtReader) -> Result<(), AppErr>;
  ) -> Result<(), AppErr>;

  async fn shutdown(&mut self, ss: StopState) -> Result<(), AppErr>;
  async fn shutdown(&mut self, tctx: TermCtx) -> Result<(), AppErr>;
}


/// Rocket server application handler.
///
/// While Rocket is built on top of tokio, it \[Rocket\] wants to initialize
/// tokio itself.
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
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







-
+










+



-
+







pub trait RocketServiceHandler {
  /// Rocket service initialization.
  ///
  /// The returned `Rocket`s will be ignited and their shutdown handlers will
  /// be triggered on shutdown.
  async fn init(
    &mut self,
    ss: StartState
    ictx: InitCtx
  ) -> Result<Vec<rocket::Rocket<rocket::Build>>, AppErr>;

  /// Server application main entry point.
  ///
  /// If the `init()` trait method returned `Rocket<Build>` instances to the
  /// qsu runtime it will ignote these and pass them to `run()`.  It is the
  /// responsibility of this method to launch the rockets and await them.
  async fn run(
    &mut self,
    rockets: Vec<rocket::Rocket<rocket::Ignite>>,
    re: &RunEnv,
    ser: SvcEvtReader
  ) -> Result<(), AppErr>;

  async fn shutdown(&mut self, ss: StopState) -> Result<(), AppErr>;
  async fn shutdown(&mut self, tctx: TermCtx) -> Result<(), AppErr>;
}


/// Event notifications that originate from the service subsystem that is
/// controlling the server application.
#[derive(Clone, Debug)]
pub enum SvcEvt {
385
386
387
388
389
390
391


392
393
394

395
396
397

398
399
400



401
402
403
404
405
406
407
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







+
+


-
+


-
+


-
+
+
+







  fn systemd(self, st: SrvAppRt) -> Result<(), Error> {
    LumberJack::default().set_init(self.log_init).init()?;

    tracing::debug!("Running service '{}'", self.svcname);

    let reporter = Arc::new(systemd::ServiceReporter {});

    let re = RunEnv::Service(Some(self.svcname.clone()));

    let res = match st {
      SrvAppRt::Sync(handler) => {
        rttype::sync_main(handler, reporter, None, self.test_mode)
        rttype::sync_main(re, handler, reporter, None, self.test_mode)
      }
      SrvAppRt::Tokio(rtbldr, handler) => {
        rttype::tokio_main(rtbldr, handler, reporter, None)
        rttype::tokio_main(rtbldr, re, handler, reporter, None)
      }
      #[cfg(feature = "rocket")]
      SrvAppRt::Rocket(handler) => rttype::rocket_main(handler, reporter, None)
      SrvAppRt::Rocket(handler) => {
        rttype::rocket_main(re, handler, reporter, None)
      }
    };

    res
  }

  /// Run as a Windows service.
  #[cfg(windows)]
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
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







+
+


-
+




-
+



-
+
+
+







  fn foreground(self, st: SrvAppRt) -> Result<(), Error> {
    LumberJack::default().set_init(self.log_init).init()?;

    tracing::debug!("Running service '{}'", self.svcname);

    let reporter = Arc::new(nosvc::ServiceReporter {});

    let re = RunEnv::Foreground;

    match st {
      SrvAppRt::Sync(handler) => {
        rttype::sync_main(handler, reporter, None, self.test_mode)
        rttype::sync_main(re, handler, reporter, None, self.test_mode)
      }

      #[cfg(feature = "tokio")]
      SrvAppRt::Tokio(rtbldr, handler) => {
        rttype::tokio_main(rtbldr, handler, reporter, None)
        rttype::tokio_main(rtbldr, re, handler, reporter, None)
      }

      #[cfg(feature = "rocket")]
      SrvAppRt::Rocket(handler) => rttype::rocket_main(handler, reporter, None)
      SrvAppRt::Rocket(handler) => {
        rttype::rocket_main(re, handler, reporter, None)
      }
    }
  }
}

impl RunCtx {
  /// Create a new service running context.
  pub fn new(name: &str) -> Self {

Changes to src/rt/rttype/rocket.rs.

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
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







-
-
+
+







+




-
+





+







use tokio::{sync::broadcast, task};

use killswitch::KillSwitch;

use crate::{
  err::{AppErrors, Error},
  rt::{
    signals, RocketServiceHandler, StartState, StateReporter, StopState,
    SvcEvt, SvcEvtReader
    signals, InitCtx, RocketServiceHandler, RunEnv, StateReporter, SvcEvt,
    SvcEvtReader, TermCtx
  }
};


/// Internal "main()" routine for server applications that run one or more
/// Rockets as their main application.
pub(crate) fn rocket_main(
  re: RunEnv,
  handler: Box<dyn RocketServiceHandler + Send>,
  sr: Arc<dyn StateReporter + Send + Sync>,
  rx_svcevt: Option<broadcast::Receiver<SvcEvt>>
) -> Result<(), Error> {
  rocket::execute(rocket_async_main(handler, sr, rx_svcevt))?;
  rocket::execute(rocket_async_main(re, handler, sr, rx_svcevt))?;

  Ok(())
}

async fn rocket_async_main(
  re: RunEnv,
  mut handler: Box<dyn RocketServiceHandler + Send>,
  sr: Arc<dyn StateReporter + Send + Sync>,
  rx_svcevt: Option<broadcast::Receiver<SvcEvt>>
) -> Result<(), Error> {
  let ks = KillSwitch::new();

  // If a SvcEvt receiver end-point was handed to us, then use it.  Otherwise
104
105
106
107
108
109
110
111


112
113
114
115

116
117
118
119
120
121
122
106
107
108
109
110
111
112

113
114
115
116
117

118
119
120
121
122
123
124
125







-
+
+



-
+







  };

  let mut rx_svcevt2 = rx_svcevt.resubscribe();

  let set = Box::new(SvcEvtReader { rx: rx_svcevt });

  // Call application's init() method.
  let ss = StartState {
  let ictx = InitCtx {
    re: re.clone(),
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let (rockets, init_apperr) = match handler.init(ss).await {
  let (rockets, init_apperr) = match handler.init(ictx).await {
    Ok(rockets) => (rockets, None),
    Err(e) => (Vec::new(), Some(e))
  };

  // Ignite rockets so we can get Shutdown contexts for each of the instances.
  let mut ignited = vec![];
  let mut rocket_shutdowns = vec![];
164
165
166
167
168
169
170
171

172
173
174
175
176
177
178
167
168
169
170
171
172
173

174
175
176
177
178
179
180
181







-
+







        }
      }
    }
  });

  let run_apperr = if init_apperr.is_none() {
    sr.started();
    handler.run(ignited, *set).await.err()
    handler.run(ignited, &re, *set).await.err()
  } else {
    None
  };


  // Always send the first shutdown checkpoint here.  Either init() failed or
  // run retuned.  Either way, we're shutting down.
191
192
193
194
195
196
197
198


199
200
201
202

203
204
205
206
207
208
209
194
195
196
197
198
199
200

201
202
203
204
205

206
207
208
209
210
211
212
213







-
+
+



-
+







  }

  if (ks.finalize().await).is_err() {
    log::warn!("Attempted to finalize KillSwitch that wasn't triggered yet");
  }

  // Call the application's shutdown() function.
  let ss = StopState {
  let tctx = TermCtx {
    re,
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let term_apperr = handler.shutdown(ss).await.err();
  let term_apperr = handler.shutdown(tctx).await.err();

  // Inform the service subsystem that the the shutdown is complete
  sr.stopped();

  // There can be multiple failures, and we don't want to lose information
  // about what went wrong, so return an error context that can contain all
  // callback errors.

Changes to src/rt/rttype/sync.rs.

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
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







-
-
+
+









+







use std::sync::{atomic::AtomicU32, Arc};

use tokio::sync::broadcast;

use crate::{
  err::{AppErrors, Error},
  rt::{
    signals, ServiceHandler, StartState, StateReporter, StopState, SvcEvt,
    SvcEvtReader
    signals, InitCtx, RunEnv, ServiceHandler, StateReporter, SvcEvt,
    SvcEvtReader, TermCtx
  }
};

#[cfg(unix)]
use crate::rt::signals::SigType;

/// Internal "main()" routine for server applications that run plain old
/// non-`async` code.
pub(crate) fn sync_main(
  re: RunEnv,
  mut handler: Box<dyn ServiceHandler>,
  sr: Arc<dyn StateReporter + Send + Sync>,
  rx_svcevt: Option<broadcast::Receiver<SvcEvt>>,
  test_mode: bool
) -> Result<(), Error> {
  // Get rid of unused variable warning
  #[cfg(unix)]
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
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







-
+
+



-
+





-
+










-
+
+



-
+







    rx
  };

  let set = Box::new(SvcEvtReader { rx: rx_svcevt });

  // Call server application's init() method, passing along a startup state
  // reporter object.
  let ss = StartState {
  let ictx = InitCtx {
    re: re.clone(),
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let init_apperr = handler.init(ss).err();
  let init_apperr = handler.init(ictx).err();

  // If init() was successful, set the service's state to "started" and then
  // call the server application's run() method.
  let run_apperr = if init_apperr.is_none() {
    sr.started();
    handler.run(*set).err()
    handler.run(&re, *set).err()
  } else {
    None
  };

  // Always send the first shutdown checkpoint here.  Either init() failed or
  // run retuned.  Either way, we're shutting down.
  sr.stopping(1, None);

  // Call the application's shutdown() function, passing along a shutdown state
  // reporter object.
  let ss = StopState {
  let tctx = TermCtx {
    re,
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let term_apperr = handler.shutdown(ss).err();
  let term_apperr = handler.shutdown(tctx).err();

  // Inform the service subsystem that the the shutdown is complete
  sr.stopped();

  // There can be multiple failures, and we don't want to lose information
  // about what went wrong, so return an error context that can contain all
  // callback errors.

Changes to src/rt/rttype/tokio.rs.

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
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







-
+











+









-
+










+







use std::sync::{atomic::AtomicU32, Arc};

use tokio::{runtime, sync::broadcast, task};

use crate::{
  err::{AppErrors, Error},
  rt::{
    signals, StartState, StateReporter, StopState, SvcEvt, SvcEvtReader,
    signals, InitCtx, RunEnv, StateReporter, SvcEvt, SvcEvtReader, TermCtx,
    TokioServiceHandler
  }
};

use killswitch::KillSwitch;


/// Internal "main()" routine for server applications that run the tokio
/// runtime for `async` code.
pub(crate) fn tokio_main(
  rtbldr: Option<runtime::Builder>,
  re: RunEnv,
  handler: Box<dyn TokioServiceHandler>,
  sr: Arc<dyn StateReporter + Send + Sync>,
  rx_svcevt: Option<broadcast::Receiver<SvcEvt>>
) -> Result<(), Error> {
  let rt = if let Some(mut bldr) = rtbldr {
    bldr.build()?
  } else {
    tokio::runtime::Runtime::new()?
  };
  rt.block_on(tokio_async_main(handler, sr, rx_svcevt))?;
  rt.block_on(tokio_async_main(re, handler, sr, rx_svcevt))?;

  Ok(())
}

/// The `async` main function for tokio servers.
///
/// If `rx_svcevt` is `Some(_)` it means the channel was created elsewhere
/// (implied: The transmitting endpoint lives somewhere else).  If it is `None`
/// the channel needs to be created.
async fn tokio_async_main(
  re: RunEnv,
  mut handler: Box<dyn TokioServiceHandler>,
  sr: Arc<dyn StateReporter + Send + Sync>,
  rx_svcevt: Option<broadcast::Receiver<SvcEvt>>
) -> Result<(), Error> {
  let ks = KillSwitch::new();

  // If a SvcEvt receiver end-point was handed to us, then use it.  Otherwise
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
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







-
+
+



-
+



-
+


















-
+
+



-
+








    rx
  };

  let set = Box::new(SvcEvtReader { rx: rx_svcevt });

  // Call application's init() method.
  let ss = StartState {
  let ictx = InitCtx {
    re: re.clone(),
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let init_apperr = handler.init(ss).await.err();
  let init_apperr = handler.init(ictx).await.err();

  let run_apperr = if init_apperr.is_none() {
    sr.started();
    handler.run(*set).await.err()
    handler.run(&re, *set).await.err()
  } else {
    None
  };

  // Always send the first shutdown checkpoint here.  Either init() failed or
  // run retuned.  Either way, we're shutting down.
  sr.stopping(1, None);


  // Now that the main application has terminated kill off any remaining
  // auxiliary tasks (read: signal waiters)
  ks.trigger();

  if (ks.finalize().await).is_err() {
    log::warn!("Attempted to finalize KillSwitch that wasn't triggered yet");
  }

  // Call the application's shutdown() function.
  let ss = StopState {
  let tctx = TermCtx {
    re,
    sr: Arc::clone(&sr),
    cnt: Arc::new(AtomicU32::new(2)) // 1 is used by the runtime, so start at 2
  };
  let term_apperr = handler.shutdown(ss).await.err();
  let term_apperr = handler.shutdown(tctx).await.err();

  // Inform the service subsystem that the the shutdown is complete
  sr.stopped();

  // There can be multiple failures, and we don't want to lose information
  // about what went wrong, so return an error context that can contain all
  // callback errors.

Changes to src/rt/winsvc.rs.

32
33
34
35
36
37
38
39

40
41
42
43
44
45
46
32
33
34
35
36
37
38

39
40
41
42
43
44
45
46







-
+







#[cfg(feature = "wait-for-debugger")]
use dbgtools_win::debugger;


use crate::{
  err::Error,
  lumberjack::LumberJack,
  rt::{SrvAppRt, SvcEvt}
  rt::{RunEnv, SrvAppRt, SvcEvt}
};

use super::StateMsg;


const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
//const SERVICE_STARTPENDING_TIME: Duration = Duration::from_secs(10);
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
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







+


-
+















+
















+
+



-
+



-
+



-
+







  // This must be done _before_ launching the application runtime thread below.
  CELL.get_or_init(|| Mutex::new(Some(xfer)));

  // Launch main application thread.
  //
  // The server application must be run on its own thread because the service
  // dispatcher call below will block the thread.
  let svcnm = svcname.to_string();
  let jh = thread::Builder::new()
    .name("svcapp".into())
    .spawn(move || srvapp_thread(st, rx_fromsvc))?;
    .spawn(move || srvapp_thread(st, svcnm, rx_fromsvc))?;

  // Register generated `ffi_service_main` with the system and start the
  // service, blocking this thread until the service is stopped.
  service_dispatcher::start(svcname, ffi_service_main)?;

  match jh.join() {
    Ok(_) => Ok(()),
    Err(e) => *e
      .downcast::<Result<(), Error>>()
      .expect("Unable to downcast error from svcapp thread")
  }
}

fn srvapp_thread(
  st: SrvAppRt,
  svcname: String,
  rx_fromsvc: oneshot::Receiver<Result<HandshakeMsg, Error>>
) -> Result<(), Error> {
  // Wait for the service subsystem to report that it has initialized.
  // It passes along a channel end-point that can be used to send events to
  // the service manager.

  let Ok(res) = rx_fromsvc.blocking_recv() else {
    panic!("Unable to receive handshake");
  };

  let Ok(HandshakeMsg { tx, rx }) = res else {
    panic!("Unable to receive handshake");
  };

  let reporter = Arc::new(ServiceReporter { tx: tx.clone() });

  let re = RunEnv::Service(Some(svcname));

  match st {
    SrvAppRt::Sync(handler) => {
      // Don't support test mode when running as a windows service
      crate::rt::rttype::sync_main(handler, reporter, Some(rx), false)
      crate::rt::rttype::sync_main(re, handler, reporter, Some(rx), false)
    }
    #[cfg(feature = "tokio")]
    SrvAppRt::Tokio(rtbldr, handler) => {
      crate::rt::rttype::tokio_main(rtbldr, handler, reporter, Some(rx))
      crate::rt::rttype::tokio_main(rtbldr, re, handler, reporter, Some(rx))
    }
    #[cfg(feature = "rocket")]
    SrvAppRt::Rocket(handler) => {
      crate::rt::rttype::rocket_main(handler, reporter, Some(rx))
      crate::rt::rttype::rocket_main(re, handler, reporter, Some(rx))
    }
  }
}


// Generate the windows service boilerplate.  The boilerplate contains the
// low-level service entry function (ffi_service_main) that parses incoming

Changes to tests/apps/mod.rs.

1
2
3
4
5

6
7
8
9
10
11
12
1
2
3
4

5
6
7
8
9
10
11
12




-
+







use std::sync::Arc;

use parking_lot::Mutex;

use qsu::rt::{ServiceHandler, StartState, StopState, SvcEvtReader};
use qsu::rt::{InitCtx, RunEnv, ServiceHandler, SvcEvtReader, TermCtx};

#[cfg(feature = "tokio")]
use qsu::rt::TokioServiceHandler;


#[cfg(feature = "rocket")]
use qsu::{
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
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







-
+







+
+
+
+
-
+







-
+







    self.fail.shutdown();
    self
  }
}


impl ServiceHandler for MySyncService {
  fn init(&mut self, _ss: StartState) -> Result<(), qsu::AppErr> {
  fn init(&mut self, _ictx: InitCtx) -> Result<(), qsu::AppErr> {
    self.visited.lock().init = true;
    if self.fail.init {
      Err(Error::hello("From Sync::init()"))?;
    }
    Ok(())
  }

  fn run(
    &mut self,
    _re: &RunEnv,
    _set: SvcEvtReader
  fn run(&mut self, _set: SvcEvtReader) -> Result<(), qsu::AppErr> {
  ) -> Result<(), qsu::AppErr> {
    self.visited.lock().run = true;
    if self.fail.run {
      Err(Error::hello("From Sync::run()"))?;
    }
    Ok(())
  }

  fn shutdown(&mut self, _ss: StopState) -> Result<(), qsu::AppErr> {
  fn shutdown(&mut self, _tctx: TermCtx) -> Result<(), qsu::AppErr> {
    self.visited.lock().shutdown = true;
    if self.fail.shutdown {
      Err(Error::hello("From Sync::shutdown()"))?;
    }
    Ok(())
  }
}
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
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







-
+







+
+
+
+
-
+







-
+







    self
  }
}

#[cfg(feature = "tokio")]
#[qsu::async_trait]
impl TokioServiceHandler for MyTokioService {
  async fn init(&mut self, _ss: StartState) -> Result<(), qsu::AppErr> {
  async fn init(&mut self, _ictx: InitCtx) -> Result<(), qsu::AppErr> {
    self.visited.lock().init = true;
    if self.fail.init {
      Err(Error::hello("From Tokio::init()"))?;
    }
    Ok(())
  }

  async fn run(
    &mut self,
    _re: &RunEnv,
    _set: SvcEvtReader
  async fn run(&mut self, _set: SvcEvtReader) -> Result<(), qsu::AppErr> {
  ) -> Result<(), qsu::AppErr> {
    self.visited.lock().run = true;
    if self.fail.run {
      Err(Error::hello("From Tokio::run()"))?;
    }
    Ok(())
  }

  async fn shutdown(&mut self, _ss: StopState) -> Result<(), qsu::AppErr> {
  async fn shutdown(&mut self, _tctx: TermCtx) -> Result<(), qsu::AppErr> {
    self.visited.lock().shutdown = true;
    if self.fail.shutdown {
      Err(Error::hello("From Tokio::shutdown()"))?;
    }
    Ok(())
  }
}
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
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







-
+











+









-
+









}

#[cfg(feature = "rocket")]
#[qsu::async_trait]
impl RocketServiceHandler for MyRocketService {
  async fn init(
    &mut self,
    _ss: StartState
    _ictx: InitCtx
  ) -> Result<Vec<Rocket<Build>>, qsu::AppErr> {
    self.visited.lock().init = true;
    if self.fail.init {
      Err(Error::hello("From Rocket::init()"))?;
    }
    Ok(Vec::new())
  }

  async fn run(
    &mut self,
    _rockets: Vec<Rocket<Ignite>>,
    _re: &RunEnv,
    _set: SvcEvtReader
  ) -> Result<(), qsu::AppErr> {
    self.visited.lock().run = true;
    if self.fail.run {
      Err(Error::hello("From Rocket::run()"))?;
    }
    Ok(())
  }

  async fn shutdown(&mut self, _ss: StopState) -> Result<(), qsu::AppErr> {
  async fn shutdown(&mut self, _tctx: TermCtx) -> Result<(), qsu::AppErr> {
    self.visited.lock().shutdown = true;
    if self.fail.shutdown {
      Err(Error::hello("From Rocket::shutdown()"))?;
    }
    Ok(())
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :

Changes to www/changelog.md.

1
2
3
4
5

6
7
8
9
10
11
12

















13
14
15
16
17
18
19
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




-
+







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







# Change log

## [Unreleased]

[Details](/vdiff?from=qsu-0.3.0&to=trunk)
[Details](/vdiff?from=qsu-0.4.0&to=trunk)

### Added

### Changed

### Removed

---

## [0.4.0] - 2024-03-22

[Details](/vdiff?from=qsu-0.3.0&to=qsu-0.4.0)

### Added

- Add a `rt::RunEnv` type that is passed to application handler callbacks,
  allowing the application to be information about whether they are being run
  as foreground processes or as services.

### Changed

- Replace `StartState` and `StopState` with `InitCtx` and `TermCtx`, each of
  which also contain a `RunEnv`.

---

## [0.3.0] - 2024-01-30

[Details](/vdiff?from=qsu-0.2.1&to=qsu-0.3.0)

### Changed