1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
45use fidl::endpoints::RequestStream;
6use fidl_fuchsia_process_lifecycle::{LifecycleRequest, LifecycleRequestStream};
7use fuchsia_async as fasync;
8use fuchsia_runtime::{take_startup_handle, HandleInfo, HandleType};
9use futures::{Future, StreamExt};
10use log::{debug, warn};
1112/// Takes the startup handle for LIFECYCLE and returns a stream listening for Lifecycle FIDL
13/// requests on it.
14pub fn take_lifecycle_request_stream() -> LifecycleRequestStream {
15let lifecycle_handle_info = HandleInfo::new(HandleType::Lifecycle, 0);
16let lifecycle_handle = take_startup_handle(lifecycle_handle_info)
17 .expect("must have been provided a lifecycle channel in procargs");
18let async_chan = fasync::Channel::from_channel(lifecycle_handle.into());
19 LifecycleRequestStream::from_channel(async_chan)
20}
2122/// Serves the Lifecycle protocol from the component runtime used for controlled shutdown of the
23/// archivist. When Stop is requrested executes the given callback.
24pub async fn on_stop_request<F, Fut>(mut request_stream: LifecycleRequestStream, cb: F)
25where
26F: FnOnce() -> Fut,
27 Fut: Future<Output = ()>,
28{
29match request_stream.next().await {
30None => {
31warn!("Lifecycle closed");
32 }
33Some(Err(err)) => {
34warn!(err:?; "Lifecycle error");
35 }
36Some(Ok(LifecycleRequest::Stop { .. })) => {
37debug!("Initiating shutdown.");
38 cb().await
39}
40 }
41}