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
use anyhow::Result;
use atomic_enum::atomic_enum;
use jsonschema::JSONSchema;
use schemars::{schema_for, JsonSchema};
use serde_json::Value;
use std::{
	env,
	sync::{atomic::Ordering, Arc, Mutex},
	time::{Duration, Instant},
};
use tokio::sync::{mpsc, oneshot};

use crate::{errors::ValidationErrorSet, prediction, shutdown::Shutdown, spec::Cog, CogResponse};

#[derive(Debug, thiserror::Error)]
pub enum Error {
	#[error("Runner is busy")]
	Busy,

	#[error("Prediction was canceled")]
	Canceled,

	#[error("Failed to validate input.")]
	Validation(ValidationErrorSet),

	#[error("Failed to run prediction: {0}")]
	Prediction(#[from] anyhow::Error),
}

#[atomic_enum]
#[derive(serde::Serialize, JsonSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Health {
	Unknown,
	Starting,
	Ready,
	Busy,
	SetupFailed,
}

pub static RUNNER_HEALTH: AtomicHealth = AtomicHealth::new(Health::Unknown);

type ResponseSender = oneshot::Sender<Result<(Value, Duration), Error>>;

#[derive(Clone)]
pub struct Runner {
	schema: Arc<JSONSchema>,
	sender: mpsc::Sender<(ResponseSender, prediction::Request)>,
}

impl Runner {
	pub fn new<T: Cog + 'static>(shutdown: Shutdown, cancel: flume::Receiver<()>) -> Self {
		RUNNER_HEALTH.swap(Health::Starting, Ordering::SeqCst);

		let (sender, mut rx) = mpsc::channel::<(ResponseSender, prediction::Request)>(1);

		let handle_shutdown = shutdown.clone();
		let handle = tokio::spawn(async move {
			tracing::info!("Running setup()...");
			let cog = tokio::select! {
				_ = tokio::time::sleep(Duration::from_secs(5 * 60)) => {
					tracing::error!("Failed run setup(): Timed out");
					RUNNER_HEALTH.swap(Health::SetupFailed, Ordering::SeqCst);
					handle_shutdown.start();
					return;
				}
				cog = T::setup() => {
					match cog {
						Ok(cog) => Arc::new(Mutex::new(cog)),
						Err(error) => {
							tracing::error!("Failed run setup(): {error}");
							RUNNER_HEALTH.swap(Health::SetupFailed, Ordering::SeqCst);
							handle_shutdown.start();
							return;
						}
					}
				}
			};

			RUNNER_HEALTH.swap(Health::Ready, Ordering::SeqCst);
			if env::var("KUBERNETES_SERVICE_HOST").is_ok() {
				if let Err(err) = tokio::fs::create_dir_all("/var/run/cog").await {
					tracing::error!("Failed to create cog runtime state directory: {err}");
					RUNNER_HEALTH.swap(Health::SetupFailed, Ordering::SeqCst);
					handle_shutdown.start();
					return;
				}

				if let Err(error) = tokio::fs::File::create("/var/run/cog/ready").await {
					tracing::error!("Failed to signal cog is ready: {error}");
					RUNNER_HEALTH.swap(Health::SetupFailed, Ordering::SeqCst);
					handle_shutdown.start();
					return;
				}
			}

			// Cog is not Sync, so we wrap it with a Mutex and this function to run it from an async context (and thus make it cancellable).
			let run_prediction_async = |input| async {
				let cog = cog.lock().unwrap();

				cog.predict(input)
			};

			while let Some((tx, req)) = rx.recv().await {
				tracing::debug!("Processing prediction: {req:?}");
				RUNNER_HEALTH.swap(Health::Busy, Ordering::SeqCst);

				// We need spawn_blocking here to (sneakily) allow blocking code in serde Deserialize impls (used in `Path`, for example).
				let input = req.input.clone();
				let input =
					tokio::task::spawn_blocking(move || serde_json::from_value(input).unwrap())
						.await
						.unwrap();

				let start = Instant::now();
				tokio::select! {
					_ = cancel.recv_async() => {
						let _ = tx.send(Err(Error::Canceled));
						tracing::debug!("Prediction canceled");
					},
					response = run_prediction_async(input)=> {
						tracing::debug!("Prediction complete: {response:?}");
						let _ = tx.send(match response {
							Err(error) => Err(Error::Prediction(error)),
							Ok(response) => match response.into_response(req).await {
								Err(error) => Err(Error::Prediction(error)),
								Ok(response) => Ok((response, start.elapsed())),
							},
						});
					}
				}

				RUNNER_HEALTH.swap(Health::Ready, Ordering::SeqCst);
			}
		});

		tokio::spawn(async move {
			shutdown.handle().await;
			tracing::debug!("Shutting down runner...");
			handle.abort();
		});

		let schema = jsonschema::JSONSchema::compile(
			&serde_json::to_value(schema_for!(T::Request)).unwrap(),
		)
		.unwrap();

		Self {
			sender,
			schema: Arc::new(schema),
		}
	}

	pub fn validate(&self, input: &Value) -> Result<(), ValidationErrorSet> {
		self.schema.validate(input)?;

		Ok(())
	}

	pub async fn run(&self, req: prediction::Request) -> Result<(Value, Duration), Error> {
		if !matches!(RUNNER_HEALTH.load(Ordering::SeqCst), Health::Ready) {
			tracing::debug!("Failed to run prediction: runner is busy");
			return Err(Error::Busy);
		}

		self.validate(&req.input).map_err(Error::Validation)?;
		RUNNER_HEALTH.swap(Health::Busy, Ordering::SeqCst);

		let (tx, rx) = oneshot::channel();

		tracing::debug!("Sending prediction to runner: {req:?}");
		let _ = self.sender.send((tx, req)).await;
		tracing::debug!("Waiting for prediction response...");
		let result = rx.await.unwrap();
		tracing::debug!("Prediction response received: {result:?}");

		RUNNER_HEALTH.swap(Health::Ready, Ordering::SeqCst);

		result
	}
}